text stringlengths 454 608k | url stringlengths 17 896 | dump stringclasses 91
values | source stringclasses 1
value | word_count int64 101 114k | flesch_reading_ease float64 50 104 |
|---|---|---|---|---|---|
e/samples/radioclient/
This is a program for playing around with XML-RPC, SOAP, and the Blogger API
using a Radio Userland 8 server. The sample used to be called bloggertest,
but I renamed it.
The big readme.txt file is included at the end of this message.
I've spent a lot of time in the last two weeks playing with XML-RPC, Blogger
and SOAP and I wanted to have a sample that was simpler to modify and
experiment with than Simon's textRouter. You should not use radioclient
without the understanding that you are working on live data and could
corrupt your blog, so user beware (see the readme). radioclient starts up
the shell automatically and imports xmlrpclib and Mark Pilgrim's blogger
module, which I included with the sample. This makes it relatively simple to
run additional tests from the shell, so I also included a tests directory of
various XML-RPC, SOAP, and blogger tests I've run so far.
I expect that Dan Shafer, myself and possibly others will have more to say
about this sample in the future. I hope we might do some tutorials to
introduce people to client web services using PythonCard as well as
modifications to the app so it can interact with other blog sites.
ka
---
readme.txt:
This app is a playground of sorts for testing XML-RPC, the Blogger API, and
SOAP using a local Radio Userland 8 server. The interface is designed for
easy testing and experimenting in Python, so it is not particularly user
friendly. If you know the IP address, username, and password for a remote
server, radioclient can also talk to that box by changing the following line
in the on_openBackground method:
# username, password, server url
self.blog = RadioBloggerSite('', '', '')
*** A WARNING ***
This is not a commercial tool supported by Userland or connected in any way
with the Radio Userland 8 product. This is a development app done by open
source developers that use Radio and is part of the PythonCard samples
designed to help stress and show off the PythonCard framework.
Since this app is talking to a live server, you are viewing, adding,
editing, and deleting real data. If you are using the default Radio
settings, your changes will be upstreamed to the public Radio server as
changes are made. You should keep backups of your data, templates, and
generated pages.
*** YOU HAVE BEEN WARNED ***
WINDOWS ONLY
Radio 8 is only available for Windows and the Macintosh. PythonCard, which
relies on wxPython, works on Windows and Linux/GTK, but isn't available on
the Mac yet, except using a Windows emulator or running wxGTK on Mac OS X.
So, for the time being this sample is effectively just for Windows users
that also have Radio 8.
RADIO AND THE BLOGGER API
Radio implements the Blogger API as defined at
As of Radio 8.0.2
it doesn't implement getUserInfo
getUsersBlogs returns info about the public Radio server not the local
server
getTemplate and setTemplate appear to only work with the 'main' template
This test app will be updated as changes are made to the blogger api in
Radio
Over time, this app might be expanded to include additional tests against
other XML-RPC, Blogger API, and SOAP web services. The tests folder contains
interactive shell sessions using various web service libraries.
Note that wxPython has a great multi-column list control called wxListCtrl
that will eventually be supported in PythonCard. Until then, the columns are
being simulated with tabs and/or spaces in a plain List.
WEBLOGS PING
Mark is supposed to just wrap this one-liner into blogger.py, so I'm not
going
to add it to my own wrapper classes unless he doesn't do that soon.
#
"Actually, XML-RPC is easier in Python than almost any other language,
because the XML-RPC library uses a very cool feature of Python called
"dynamic binding" to create a kind of virtual proxy that lets you call
remote functions with exactly the same syntax as calling local functions.
import xmlrpclib
remoteServer = xmlrpclib.Server("")
remoteServer.weblogUpdates.ping(SITE_NAME, SITE_URL)
This short example pings weblogs.com to tell it that your weblog has
changed. I use this script to connect this Greymatter weblog to the
weblogs.com community (since Greymatter has no weblogs.com support built
in). But the point here is the syntax of that third line: it's the same
syntax as calling a local function. Once the proxy (remoteServer) is set up,
the XML-RPC library makes the object act as if it has a weblogUpdates object
within it and a ping method within that. It's all a lie, of course; under
the covers it's constructing an XML-RPC request and sending it off, and then
receiving an XML-RPC response and parsing it and returning a native Python
object. But I, as a Python developer, don't have to worry about all that if
I don't want to, and I don't have to learn a new syntax for calling remote
functions."
REFERENCES
Python
win32 extensions
wxPython
windows binaries at:
PythonCard
xmlrpclib (use 0.9.9 if you have Python 2.1.x, it is included as part of
Python 2.2)
pyblogger
The Blogger API
Radio Userland 8
emulatingBloggerInRadio
emulatingBloggerInManila
ggerApi
textRouter (a manila/blogger app written in PythonCard by Simon Kittle)
Python.Scripting: Python, XML-RPC and SOAP
Python and XML: An Introduction
_______________________________________________
Pythoncard-users mailing list
Pythoncard-users@[...].net | http://aspn.activestate.com/ASPN/Mail/Message/PythonCard/1017624 | crawl-002 | refinedweb | 918 | 60.04 |
1560831758
We will create a sample chat application to demonstrate this feature. However, because we are focusing on just user presence, we will not implement the actual chat feature.
If you are building an application that has a user base, you might need to show your users when their friends are currently online. This comes in handy especially in messenger applications where the current user would like to know which of their friends are available for instant messaging.
Here is a screen recording on how we want the application to work:
If you want a tutorial on how to create a messenger application on iOS, check out this article.
To follow along you need the following requirements:
Let’s get started.
Before creating the iOS application, let’s create the backend application in Node.js. This application will have the necessary endpoints the application will need to function properly. To get started, create a new directory for the project.
In the root of the project, create a new
package.json file and paste the following contents into it:
{ "name": "presensesample", "version": "1.0.0", "main": "index.js", "dependencies": { "body-parser": "^1.18.3", "express": "^4.16.4", "pusher": "^2.1.3" } }
Above, we have defined some npm dependencies that the backend application will need to function. Amongst the dependencies, we can see the
pusher library. This is the Pusher JavaScript server SDK.
Next, open your terminal application and
cd to the root of the project you just created and run the following command:
$ npm install
This command will install all the dependencies we defined above in the
package.json file.
Next, create a new file called
index.js and paste the following code into the file:
// File: ./index.js
const express = require(‘express’);
const bodyParser = require(‘body-parser’);
const Pusher = require(‘pusher’);
const app = express();
let users = {}; let currentUser = {}; let pusher = new Pusher({ appId: 'PUSHER_APP_ID', key: 'PUSHER_APP_KEY', secret: 'PUSHER_APP_SECRET', cluster: 'PUSHER_APP_CLUSTER' }); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); // TODO: Add routes here app.listen(process.env.PORT || 5000);
In the code above, we imported the libraries we need for the backend application. We then instantiated two new variables:
users and
currentUser. We will be using these variables as a temporary in-memory store for the data since we are not using a database.
Next, we instantiated the Pusher library using the credentials for our application. We will be using this instance to communicate with the Pusher API. Next, we add the
listen method which instructs the Express application to start the application on port 5000.
Next, let’s add some routes to the application. In the code above, we added a comment to signify where we will be adding the route definitions. Replace the comment with the following code:
// File: ./index.js
// [...] app.post('/users', (req, res) => { const name = req.body.name; const matchedUsers = Object.keys(users).filter(id => users[id].name === name); if (matchedUsers.length === 0) { const id = generate_random_id(); users[id] = currentUser = { id, name }; } else { currentUser = users[matchedUsers[0]]; } res.json({ currentUser, users }); }); // [...]
Above, we have the first route. The route is a
POST route that creates a new user. It first checks the
users object to see if a user already exists with the specified name. If a user does not exist, it generates a new user ID using the
generate_random_id method (we will create this later) and adds it to the
users object. If a user exists, it skips all of that logic.
Regardless of the outcome of the user check, it sets the
currentUser as the user that was created or matched and then returns the
currentUser and
users object as a response.
Next, let’s define the second route. Because we are using presence channels, and presence channels are private channels, we need an endpoint that will authenticate the current user. Below the route above, add the following code:
// File: ./index.js
// [...] app.post('/pusher/auth/presence', (req, res) => { let socketId = req.body.socket_id; let channel = req.body.channel_name; let presenceData = { user_id: currentUser.id, user_info: { name: currentUser.name } }; let auth = pusher.authenticate(socketId, channel, presenceData); res.send(auth); }); // [...]
Above, we have the Pusher authentication route. This route gets the expected
socket_id and
channel_name and uses that to generate an authentication token. We also supply a
presenceData object that contains all the information about the user we are authenticating. We then return the token as a response to the client.
Finally, in the first route, we referenced a function
generate_random_id. Below the route we just defined, paste the following code:
// File: ./index.js
// [...] function generate_random_id() { let s4 = () => (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1); return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4(); } // [...]
The function above just generates a random ID that we can then use as the user ID when creating new users.
Let’s add a final default route. This will catch visits to the backend home. In the same file, add the following:
// […]
app.get('/', (req, res) => res.send('It works!')); // [...]
With this, we are done with the Node.js backend. You can run your application using the command below:
$ node index.js
Your app will be available here:.
Launch Xcode and create a new sample Single View App project. We will call ours
presensesample.
When you are done creating the application, close Xcode. Open your terminal application and
cd to the root directory of the iOS application and run the following command:
$ pod init
This will create a new
Podfile file in the root directory of your application. Open the file and replace the contents with the following:
# File: ./Podfile
target ‘presensesample’ do
platform :ios, ‘12.0’
use_frameworks! pod 'Alamofire', '~> 4.7.3' pod 'PusherSwift', '~> 5.0' pod 'NotificationBannerSwift', '~> 1.7.3' end
Above, we have defined the application’s dependencies. To install the dependencies, run the following command:
$ pod install
The command above will install all the dependencies in the
Podfile and also create a new
.xcworkspace file in the root of the project. Open this file in Xcode to launch the project and not the
.xcodeproj file.
The first thing we will do is create the storyboard scenes we need for the application to work. We want the storyboard to look like this:
Open the main storyboard file and delete all the scenes in the file so it is empty. Next, add a view controller to the scene.
TIP: You can use the command + shift + L shortcut to bring the objects library.
With the view controller selected, click on Editor > Embed In > Navigation Controller. This will embed the current view controller in a navigation controller. Next, with the navigation view controller selected, open the attributes inspector and select the Is Initial View Controller option to set the navigation view controller as the entry point for the storyboard.
Next, design the view controller as seen in the screenshot below. Later on in the article, we will be connecting the text field and button to the code using an
@IBOutlet and an
@IBAction.
Next, add the tab bar controller and connect it to the view controller using a manual segue. Since tab bar controllers come with two regular view controllers, delete them and add two table view controllers instead as seen below:
When you are done creating the scenes, let’s start adding the necessary code.
Create a new controller class called
LoginViewController and set it as the custom class for the first view controller attached to the navigation controller. Paste the following code into the file:
// File: ./presensesample/LoginViewController.swift
import UIKit
import Alamofire
import PusherSwift
import NotificationBannerSwift
class LoginViewController: UIViewController { var user: User? = nil var users: [User] = [] @IBOutlet weak var nameTextField: UITextField! override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) user = nil users = [] navigationController?.isNavigationBarHidden = true } @IBAction func startChattingButtonPressed(_ sender: Any) { if nameTextField.text?.isEmpty == false, let name = nameTextField.text { registerUser(["name": name.lowercased()]) { successful in guard successful else { return StatusBarNotificationBanner(title: "Failed to login.", style: .danger).show() } self.performSegue(withIdentifier: "showmain", sender: self) } } } func registerUser(_ params: [String : String], handler: @escaping(Bool) -> Void) { let url = "" Alamofire.request(url, method: .post, parameters: params) .validate() .responseJSON { resp in if resp.result.isSuccess, let data = resp.result.value as? [String: Any], let user = data["currentUser"] as? [String: String], let users = data["users"] as? [String: [String: String]], let id = user["id"], let name = user["name"] { for (uid, user) in users { if let name = user["name"], id != uid { self.users.append(User(id: uid, name: name)) } } self.user = User(id: id, name: name) self.nameTextField.text = nil return handler(true) } handler(false) } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let vc = segue.destination as? MainViewController { vc.viewControllers?.forEach { if let onlineVc = $0 as? OnlineTableViewController { onlineVc.users = self.users onlineVc.user = self.user } } } } }
In the controller above, we have defined the
users and
user properties which will hold the available users and the current user when the user is logged in. We also have the
nameTextField which is an
@IBOutlet to the text field in the storyboard view controller, so make sure you connect the outlet if you hadn’t previously done so.
In the same controller, we have the
startChattingButtonPressed method which is an
@IBAction so make sure you connect it to the submit button in the storyboard view controller if you have not already done so. In this method, we call the
registerUser method to register the user using the API. If the registration is successful, we direct the user to the
showmain segue.
The segue between the login view controller and the tab bar controller should be set with an identifier of
showmain.
In the
registerUser method, we send the name to the API and receive a JSON response. We parse it to see if the registration was successful or not.
The final method in the class is the
prepare method. This method is automatically called by iOS when a new segue is being loaded. We use this to preset some data to the view controller we are about to load.
Next, create a new file called
MainViewController and set this as the custom class for the tab bar view controller. In the file, paste the following code:
// File: ./presensesample/MainViewController.swift
import UIKit
class MainViewController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() navigationItem.title = "Who's Online" navigationItem.hidesBackButton = true navigationController?.isNavigationBarHidden = false // Logout button navigationItem.rightBarButtonItem = UIBarButtonItem( title: "Logout", style: .plain, target: self, action: #selector(logoutButtonPressed) ) } override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) { navigationItem.title = item.title } @objc fileprivate func logoutButtonPressed() { viewControllers?.forEach { if let vc = $0 as? OnlineTableViewController { vc.users = [] vc.pusher.disconnect() } } navigationController?.popViewController(animated: true) } }
In the controller above, we have a few methods defined. The
viewDidLoad method sets the title of the controller and other navigation controller specific things. We also define a Logout button in this method. The button will trigger the
logoutButtonPressed method.
In the
logoutButtonPressed method, we try to log the user out by resetting the
users property in the view controller and also we disconnect the user from the Pusher connection.
Next, create a new controller class named
ChatTableViewController. Set this class as the custom class for one of the tab bar controllers child controllers. Paste the following code into the file:
// File: ./presensesample/ChatTableViewController.swift
import UIKit
class ChatTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() } override func numberOfSections(in tableView: UITableView) -> Int { return 0 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 0 } }
The controller above is just a base controller and we do not intend to add any chat logic to this controller.
Create a new controller class called
OnlineTableViewController. Set this controller as the custom class for the second tab bar controller child controller. Paste the following code to the controller class:
// File: ./presensesample/OnlineTableViewController.swift
import UIKit
import PusherSwift
struct User { let id: String var name: String var online: Bool = false init(id: String, name: String, online: Bool? = false) { self.id = id self.name = name self.online = online! } } class OnlineTableViewController: UITableViewController { var pusher: Pusher! var user: User? = nil var users: [User] = []: "onlineuser", for: indexPath) let user = users[indexPath.row] cell.textLabel?.text = "\(user.name) \(user.online ? "[Online]" : "")" return cell } }
In the code above, we first defined a
User struct. We will use this to represent the user resource. We have already referenced this struct in previous controllers we created earlier.
Next, we defined the
OnlineTableViewController class which is extends the
UITableViewController class. In this class, we override the usual table view controller methods to provide the table with data.
You have to set the cell reuse identifier of this table to
onlineuserin the storyboard.
Above we also defined some properties:
pusher- this will hold the Pusher SDK instance that we will use to subscribe to Pusher Channels.
users- this will hold an array of
Userstructs.
user- this is the user struct of the current user.
Next, in the same class, add the following method:
// File: ./presensesample/OnlineTableViewController.swift
// [...] override func viewDidLoad() { super.viewDidLoad() tableView.allowsSelection = false // Create the Pusher instance... pusher = Pusher( key: "PUSHER_APP_KEY", options: PusherClientOptions( authMethod: .endpoint(authEndpoint: ""), host: .cluster("PUSHER_APP_CLUSTER") ) ) // Subscribe to a presence channel... let channel = pusher.subscribeToPresenceChannel( channelName: "presence-chat", onMemberAdded: { member in if let info = member.userInfo as? [String: String], let name = info["name"] { if let index = self.users.firstIndex(where: { $0.id == member.userId }) { let userModel = self.users[index] self.users[index] = User(id: userModel.id, name: userModel.name, online: true) } else { self.users.append(User(id: member.userId, name: name, online: true)) } self.tableView.reloadData() } }, onMemberRemoved: { member in if let index = self.users.firstIndex(where: { $0.id == member.userId }) { let userModel = self.users[index] self.users[index] = User(id: userModel.id, name: userModel.name, online: false) self.tableView.reloadData() } } ) // Bind to the subscription succeeded event... channel.bind(eventName: "pusher:subscription_succeeded") { data in guard let deets = data as? [String: AnyObject], let presence = deets["presence"] as? [String: AnyObject], let ids = presence["ids"] as? NSArray else { return } for userid in ids { guard let uid = userid as? String else { return } if let index = self.users.firstIndex(where: { $0.id == uid }) { let userModel = self.users[index] self.users[index] = User(id: uid, name: userModel.name, online: true) } } self.tableView.reloadData() } // Connect to Pusher pusher.connect() } // [...]
In the
viewDidLoad method above, we are doing several things. First, we instantiate the Pusher instance. In the options, we specify the authorize endpoint. We use the same URL as the backend we created earlier.
The next thing we do is subscribe to a presence channel called
presence-chat. When working with presence channels, the channel name must be prefixed with
presence-. The
subscribeToPresenceChannel method has two callbacks that we can add logic to:
onMemberAdded- this event is called when a new user joins the
presence-chatchannel. In this callback, we check for the user that was added and mark them as online in the
usersarray.
onMemberRemoved- this event is called when a user leaves the
presence-chatchannel. In this callback, we check for the user that left the channel and mark them as offline.
Next, we bind to the
pusher:subscription_succeeded event. This event is called when a user successfully subscribes to updates on a channel. The callback on this event returns all the currently subscribed users. In the callback, we use this list of subscribed users to mark them online in the application.
Finally, we use the
connect method on the
pusher instance to connect to Pusher.
One last thing we need to do before we are done with the iOS application is allowing the application load data from arbitrary URLs. By default, iOS does not allow this, and it should not. However, since we are going to be testing locally, we need this turned on temporarily. Open the
info.plist file and update it as seen below:
Now, our app is ready. You can run the application and you should see the online presence status of other users when they log in.
In this tutorial, we learned how to use presence channels in your iOS application using Pusher Channels.
The source code for the application created in this tutorial is available on GitHub.
☞ Learn Swift 4: From Beginner to Advanced
☞ Top 10 Node.js Frameworks
☞ Machine Learning In Node.js With TensorFlow.js
☞ Express.js & Node.js Course for Beginners - Full Tutorial
☞ How to Perform Web-Scraping using Node.js
☞ Build a web scraper with Node
☞ Getting started with Flutter
☞ Android Studio for beginners
☞ Building a mobile chat app with Nest.js and Ionic 4
Originally published by Neo Ighodaro at
#mobile-apps #node-js #swift 12441441
Are.
For more info:
Website:
Call: +1-978-309-9910
#top swift app development company usa #best swift app development company #swift app development #swift ios app development #swift app development company #hire expert swift ios app developers in usa | https://morioh.com/p/8f75c2412b81 | CC-MAIN-2021-39 | refinedweb | 2,791 | 51.34 |
Hi Christoph,On 19 Sep 2007, at 04:36, Christoph Lameter wrote:> Currently there is a strong tendency to avoid larger page > allocations in> the kernel because of past fragmentation issues and the current> defragmentation methods are still evolving. It is not clear to what > extend> they can provide reliable allocations for higher order pages (plus the> definition of "reliable" seems to be in the eye of the beholder).>> Currently we use vmalloc allocations in many locations to provide a > safe> way to allocate larger arrays. That is due to the danger of higher > order> allocations failing. Virtual Compound pages allow the use of regular> page allocator allocations that will fall back only if there is an > actual> problem with acquiring a higher order page.>>.I like this a lot. It will get rid of all the silly games we have to play when needing both large allocations and efficient allocations where possible. In NTFS I can then just allocated higher order pages instead of having to mess about with the allocation size and allocating a single page if the requested size is <= PAGE_SIZE or using vmalloc() if the size is bigger. And it will make it faster because a lot of the time a higher order page allocation will succeed with your patchset without resorting to vmalloc() so that will be a lot faster.So where I currently have fs/ntfs/malloc.h the below mess I could get rid of it completely and just use the normal page allocator/ deallocator instead...static inline void *__ntfs_malloc(unsigned long size, gfp_t gfp_mask){ if (likely(size <= PAGE_SIZE)) { BUG_ON(!size); /* kmalloc() has per-CPU caches so is faster for now. */ return kmalloc(PAGE_SIZE, gfp_mask & ~__GFP_HIGHMEM); /* return (void *)__get_free_page(gfp_mask); */ } if (likely(size >> PAGE_SHIFT < num_physpages)) return __vmalloc(size, gfp_mask, PAGE_KERNEL); return NULL;}And other places in the kernel can make use of the same. I think XFS does very similar things to NTFS in terms of larger allocations at least and there are probably more places I don't know about off the top of my head...I am looking forward to your patchset going into mainline. (-:Best regards, Anton> Advantages:>> - If higher order allocations are failing then virtual compound pages> consisting of a series of order-0 pages can stand in for those> allocations.>> - "Reliability" as long as the vmalloc layer can provide virtual > mappings.>> - Ability to reduce the use of vmalloc layer significantly by using> physically contiguous memory instead of virtual contiguous memory.> Most uses of vmalloc() can be converted to page allocator calls.>> - The use of physically contiguous memory instead of vmalloc may > allow the> use larger TLB entries thus reducing TLB pressure. Also reduces > the need> for page table walks.>> Disadvantages:>> - In order to use fall back the logic accessing the memory must be> aware that the memory could be backed by a virtual mapping and take> precautions. virt_to_page() and page_address() may not work and> vmalloc_to_page() and vmalloc_address() (introduced through this> patch set) may have to be called.>> - Virtual mappings are less efficient than physical mappings.> Performance will drop once virtual fall back occurs.>> - Virtual mappings have more memory overhead. vm_area control > structures> page tables, page arrays etc need to be allocated and managed to > provide> virtual mappings.>> The patchset provides this functionality in stages. Stage 1 introduces> the basic fall back mechanism necessary to replace vmalloc allocations> with>> alloc_page(GFP_VFALLBACK, order, ....)>> which signifies to the page allocator that a higher order is to be > found> but a virtual mapping may stand in if there is an issue with > fragmentation.>> Stage 1 functionality does not allow allocation and freeing of virtual> mappings from interrupt contexts.>> The stage 1 series ends with the conversion of a few key uses of > vmalloc> in the VM to alloc_pages() for the allocation of sparsemems memmap > table> and the wait table in each zone. Other uses of vmalloc could be > converted> in the same way.>>> Stage 2 functionality enhances the fallback even more allowing > allocation> and frees in interrupt context.>> SLUB is then modified to use the virtual mappings for slab caches> that are marked with SLAB_VFALLBACK. If a slab cache is marked this > way> then we drop all the restraints regarding page order and allocate> good large memory areas that fit lots of objects so that we rarely> have to use the slow paths.>> Two slab caches--the dentry cache and the buffer_heads--are then > flagged> that way. Others could be converted in the same way.>> The patch set also provides a debugging aid through setting>> CONFIG_VFALLBACK_ALWAYS>> If set then all GFP_VFALLBACK allocations fall back to the virtual> mappings. This is useful for verification tests. The test of this> patch set was done by enabling that options and compiling a kernel.>>> Stage 3 functionality could be the adding of support for the large> buffer size patchset. Not done yet and not sure if it would be useful> to do.>> Much of this patchset may only be needed for special cases in which > the> existing defragmentation methods fail for some reason. It may be > better to> have the system operate without such a safety net and make sure > that the> page allocator can return large orders in a reliable way.>> The initial idea for this patchset came from Nick Piggin's fsblock> and from his arguments about reliability and guarantees. Since his> fsblock uses the virtual mappings I think it is legitimate to> generalize the use of virtual mappings to support higher order> allocations in this way. The application of these ideas to the large> block size patchset etc are straightforward. If wanted I can base> the next rev of the largebuffer patchset on this one and implement> fallback.>> Contrary to Nick, I still doubt that any of this provides a > "guarantee".> Have said that I have to deal with various failure scenarios in the VM> daily and I'd certainly like to see it work in a more reliable manner.>> IMHO getting rid of the various workarounds to deal with the small 4k> pages and avoiding additional layers that group these pages in > subsystem> specific ways is something that can simplify the kernel and make the> kernel more reliable overall.>> If people feel that a virtual fall back is needed then so be it. Maybe> we can shed our security blanket later when the approaches to deal> with fragmentation have matured.>> The patch set is also available via git from the largeblock git > tree via>> git pull> git://git.kernel.org/pub/scm/linux/kernel/git/christoph/ > largeblocksize.git> vcompound>> -- > -> To unsubscribe from this list: send the line "unsubscribe linux- > kernel" in> the body of a message to majordomo@vger.kernel.org> More majordomo info at> Please read the FAQ at | https://lkml.org/lkml/2007/9/19/31 | CC-MAIN-2017-04 | refinedweb | 1,118 | 52.6 |
I am using 2 sortable objects and 1 droppable object.The 2
sortable are connected using "connectWith" property.
to see a image example.
The idea is that i will drag objects
from the bottom sortable to the upper sortable or to the droppable
object.
The problem is that when i am dragging a object from
the bottom sortable to the draggable object
I have this in my controller:
def selectmodels
@brand = Brand.find_by_name(params[:brand_name]) @models =
Model.where(:brand_id => @brand.id) render json: @models
end
The returned code is processed by:
$.ajax({ url: '/selectmodels?brand_name=' + test, type:
'get', dataType: 'json',
synchronized void drop(Board board) { int[][] a =
getArray(); int[][] b = board.getArray(); //I don't have
currentObject here... what do I need to write? if
(Board.goDown(currentX, currentY, b, a, board, currentObject)) {
currentY++; updateXY(); }}
The method call is curren
curren
i am trying to implement an autocomplete combobox using jquery ui
plugin.
with the below mentioned code i am able to achieve the
autocomplete part but not the dropdown part (due to the uncaught typeerror
the dropdown arrow is not visible)
$.widget( "ui.combobox",
{ _create: function() { var input,
self = this,
i am working on a little learning project and have run into an issue
that i cant work out.
I get the following error message on
google chromes dev console :-
Uncaught TypeError: Object
[object Object] has no method 'match'lexer.nexthandlebars-1.0.0.beta.6.js:364lexhandlebars-1.0.0.beta.6.js:392lexhandlebars-1.0.0.beta.6.js:214parsehandlebars-1.
I have this kind of json:
{ "1": {"id": 1,
"first": "mymethod", "second" : [true, true, false]} , "4": {"id": 2,
"first": "foo", "second" : [true, true, false]}, "67": {"id": 67,
"first": "bar", "second": [true, true, false]}, "70": {"id": 70,
"first": "foobar", "second" : [true, true, false]}}
I am trying to parse it using gson
I'm rewriting a JavaScript library that I wrote some time ago.Its
purpose is to display an array of objects as a table, that can be sorted,
filtered and edited without server communication.
The current
solution "pollutes" the objects with additional attributes, that are needed
to steer the display.The original object may look like this
{"name":"...","lastn
I am having big trouble fixing this error.
I have a view in
Backbone.js and I want to bind some actions on it with keyboard
events.
Here is my view :
window.PicturesView =
Backbone.View.extend({ initialize : function() {
$(document).on('keydown', this.keyboard, this); }, remove
: function() { $(document
T writing code using ExtJS4.0.1, MVC architecture. And when I develop
main form I meet problem with search extension for web site.
When I was trying to create new widget in controller, I need render
result in subpanel. and so when I write sample code I meet following
problem:
**Uncaught TypeError: Object [object Object] has no
method 'setSortState'**
I have an object, and I am using php's session to persist the objects
state. Here is basically what I'm doing:
I have "object A"
which contains one "object B". In the constructor for A, I am simply
grabbing B from the session and setting "object B" equal to its appropriate
value in the session.
I then proceed to call some of object
b's functions, but I have a feeling | http://bighow.org/tags/Object/1 | CC-MAIN-2017-04 | refinedweb | 543 | 64.41 |
SSHim () is a library for testing and debugging SSH automation clients. The aim is to provide a scriptable SSH server which can be made to behave like any SSH-enabled device.
Currently SSHim does just enough to fire up an SSH server using Paramiko and read and write values. Eventually it could be expanded to support additional channel types, scripted tunneling and more.
To install from pypi:
pip install sshim
To install as an egg-link in development mode:
python setup.py develop -N
To run from the folder direct:
PYTHONPATH=. python examples/counter.py
Or to run the tests:
nosetests -x -s -w tests/
Simple Example:
import logging logging.basicConfig(level='DEBUG') logger = logging.getLogger() import sshim, re # define the callback function which will be triggered when a new SSH connection is made: def hello_world(script): # ask the SSH client to enter a name script.write('Please enter your name: ') # match their input against a regular expression which will store the name in a capturing group called name groups = script.expect(re.compile('(?P<name>.*)')).groupdict() # log on the server-side that the user has connected logger.info('%(name)s just connected', **groups) # send a message back to the SSH client greeting it by name script.writeline('Hello %(name)s!' % groups) # create a server and pass in the callback method # connect to it using `ssh localhost -p 3000` server = sshim.Server(hello_world, port=3000) try: server.run() except KeyboardInterrupt: server.stop()
Because SSHim uses Python to script the SSH server, complicated emulated interfaces can be created using branching, stored state and looping, e.g:
import logging logging.basicConfig(level='DEBUG') import sshim, time, re # define the callback function which will be triggered when a new SSH connection is made: def counter(script): while True: for n in xrange(0, 10): # send the numbers 0 to 10 to the client with a little pause between each one for dramatic effect: script.writeline(n) time.sleep(0.1) # ask them if they are interested in seeing the show again script.write('Again? (y/n): ') # parse their input with a regular expression and pull it into a named group groups = script.expect(re.compile('(?P<again>[yn])')).groupdict() # if they didn't say yes, break out the loop and disconnect them if groups['again'] != 'y': break # create a server and pass in the callback method # connect to it using `ssh localhost -p 3000` server = sshim.Server(counter, port=3000) try: server.run() except KeyboardInterrupt: server.stop()
Synchronously start the server in the current thread, blocking indefinitely.
Stop the server, waiting for the runloop to exit.
Expect a line of input from the user. If this has the match method, it will call it on the input and return the result, otherwise it will use the equality operator, ==. Notably, if a regular expression is passed in its match method will be called and the matchdata returned. This allows you to use matching groups to pull out interesting data and operate on it.
If echo is set to False, the server will not echo the input back to the client.
Send raw encoded bytes to the client.
Send unicode to the client.
Send unicode to the client and append a carriage return and newline. | http://pythonhosted.org/sshim/ | CC-MAIN-2016-44 | refinedweb | 540 | 65.52 |
Parent Directory
|
Revision Log
Sapling model updates.
#!/usr/bin/perl -w package LoaderUtils; use strict; use Tracer; use SeedUtils; ; } =head3 RolesForLoading my ($roles, $errors) = RolesForLoading($function); Split a functional assignment into roles. If the functional assignment seems suspicious, it will be flagged as invalid. A count will be returned of the number of roles that are rejected because they are too long. =over 4 =item function Functional assignment to parse. =item RETURN Returns a two-element list. The first is either a reference to a list of roles, or an undefined value (indicating a suspicious functional assignment). The second is the number of roles that are rejected for being too long. =back =cut sub RolesForLoading { # Get the parameters. my ($function) = @_; # Declare the return variables. my ($roles, $errors) = (undef, 0); # Only proceed if there are no suspicious elements in the functional assignment. if (! ($function =~ /\b(?:similarit|blast\b|fasta|identity)|%|E=/i)) { # Initialize the return list. $roles = []; # Split the function into roles. my @roles = roles_of_function($function); # Keep only the good roles. for my $role (@roles) { if (length($role) > 250) { $errors++; } else { push @$roles, $role; } } } # Return the results. return ($roles, $errors); } 1; | http://biocvs.mcs.anl.gov/viewcvs.cgi/Sprout/LoaderUtils.pm?revision=1.2&view=markup&pathrev=mgrast_release_3_1_0 | CC-MAIN-2019-43 | refinedweb | 191 | 60.21 |
table of contents
NAME¶
getunwind - copy the unwind data to caller's buffer
SYNOPSIS¶
#include <syscall.h> #include <linux/unwind.h>
long getunwind(void *buf, size_t buf_size);
Note: There is no glibc wrapper for this system call; see NOTES.
DESCRIPTION¶
Note: this function is obsolete..
RETURN VALUE¶
On success, getunwind() returns the size of the unwind data. On error, -1 is returned and errno is set to indicate the error.
ERRORS¶
getunwind() fails with the error EFAULT if the unwind info can't be stored in the space specified by buf.
VERSIONS¶
This system call is available since Linux 2.4.
CONFORMING TO¶
This system call is Linux-specific, and is available only on the IA-64 architecture.
NOTES¶¶
COLOPHON¶
This page is part of release 5.10 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at. | https://manpages.debian.org/testing/manpages-dev/getunwind.2.en.html | CC-MAIN-2021-49 | refinedweb | 154 | 67.86 |
Interactive Child's Mobile
Introduction: Interactive Child's Mobile" and 3/8" diameter and 4 feet of 1/2" diameter)
- Fishing line (approximately 5 yards)
- Light-colored thread (approximately 5 yards)
- Hot glue gun (1) and hot glue sticks (1-2)
- Stuffed toy (1) (one which had circuitry in it and therefore has easy access to the insides is convenient)
- Electronics
- Arduino UNOs (2)
- LEDs** (3)
- FTDI Breakout board (1)***
- USB cables, A to B plugs (2)
- XBee radios (2)
- XBee breakout boards with headers (2) ****
- Mini Servo motors (2)
- A-B USB cable (1)
- 1-axis accelerometer (1)
- Three-terminal switches (3)
- Push buttons (2)
- Flex sensors (2)
- Resistors (2x10k and 4x2.2k)
- Blacklight flashlights with screw-off heads (2)
- Solid-core wire (a lot*****)
- Electrical tape (approximately 1 yard)
- Soldering iron (1) and solder (approximately 1 yard)
- Battery packs and batteries (we used one of three AAAs, one of three AAs, and two of two AAs, but some of this is flexible)
* We used 12" x 24" sheets from inventables.com. Depending on the sizes and shapes of your parts, you might be able to use 12"x8" sheets, which are the next-smallest size. Also, the blue fluorescent acrylic from Inventables doesn't fluoresce (as of March, 2012).
** We used lilypad LEDs because we had them in a color we liked (orange-yellow). We don't recommend using lilypad LEDs instead of regular ones, though.
*** One of these will make your life much easier if your XBee radios aren't already configured to talk to each other. Don't assume they will.
**** XBee radios have non-standard pin spacing, so you will want a workaround. Reference. Alternatively reference digikey.com
***** We used about a dozen wires of approximately 4 yards in length to suspend switches from the ceiling for easier access. Securing the blacklights and the servos to the dowels also required a few yards of wire. Other than that, most of the wiring could be done with a yard or two of wire.
Step 1: Design Parts
The acrylic for this project is cut using a laser cutter. We designed our parts in Solidworks, but feel free to use whatever CAD software you prefer. All of our parts were between 3 and 6 inches on a side, with most of them being approximately 4" square. For the theme our our baby mobile, we designed two flowers, two butterflies, and one rainbow.
The sides of the acrylic fluoresce more than the faces do. To show this off (and to mix up the colors) we cut holes and inset parts for all of the acrylic shapes. To facilitate mixing and matching of these inset parts, we cut one of each of the flowers and the butterflies out of each color of acrylic. We also cut the corresponding arc of the rainbow out of each color of acrylic (with pink being the largest and green being the smallest). This gave us 20 parts, enough for two mobiles with 10 parts each. We also cut small (1/16") holes where we wanted to attach the parts to each other to facilitate the assembly process later.
Assemble the parts onto cutsheets (according to the format for the laser cutter you use), putting the parts as close together as you can given the tolerance of your laser cutter. Be aware that parts placed too close to the edge of the sheet may get cut off. Then cut the parts (or get someone to cut them for you).
The images for this step show the Solidworks parts for all the components we designed.
Step 2: Assemble Parts
Decide what color combinations you like best and lay out how you would like to assemble your parts. We found that the orange and yellow acrylics looked similar, so we preferred to accent the pink and green with the orange and yellow, and vice versa. We initially intended to use only fishing line to secure parts to each other but found that thread was easier to work with and allowed spinning parts more movement. However, for parts requiring structure, fishing line worked very well to hold subparts in a particular configuration. For our mobile, we used thread to hold together the two butterflies and the flowers. We used fishing line to hold together the tulips and the rainbows. as these looked significantly better with more structure.
All subparts were secured to each other using square knots through corresponding holes. (See step 1 again and look at the alignment of the holes in the parts, if you're interested.) The spacing was intended to match that in the parts, though of course getting this exact in practice was difficult.
Step 3: Test Components
If you have not already, download the arduino software from. You will need this for programming and testing components. Plug one of the arduinos into your computer and run one of the demos (e.g. Blink) to confirm your arduino is working; do the same with the other arduino. Now you're ready to test the other components.
The bend sensors serve as variable resistors. For our purposes, we need a reading from them. We therefore need to solder a 10k resistor in between one of the sides and ground. In fact, using the sensor will be a lot easier if you solder leads to each of the pins. Make sure to insulate the connections with heat shrink tubing or electrical tape. Note also that the joint of the bend sensor can wear through and break, so reinforcing this with tape is a good idea. The resistor, as mentioned previously, will go to ground; the same pin to which the resistor is soldered will go to the analog input; and the other pin will go to power (5V). Plug the bend sensor into the arduino in this configuration, with the input to pin A0. Then configure the arduino to print out the analog input values. If you aren't familiar with arduino software, use the code below. See what kinds of values you get when you bend your flex sensor versus when the sensor is straight.
void setup()
{
Serial.begin(9600); // Setup serial
digitalWrite(13, HIGH); // Indicates that the program has intialized
}
void loop()
{
raw = analogRead(A0); // Reads the Input PIN
Serial.println(raw); // Prints the input value
delay(10); // Make it not scroll too quickly
}
In the next step, you will hack the servos for continuous motion. For now, though, it's a good idea to make sure they work in the first place. The orange wire is signal, red is power (5V), and brown is ground; hook a servo up to the arduino in this manner. Run one of the servo test modules to make sure your servo behaves as expected. You will need long leads on the servos (at least 1 yard, depending on how long the fishing line suspending the mobile will be), so now would be a good time to attach those by sliding them into the corresponding pins on the servo. We found that braiding the wires together helped to keep them consolidated and ensured we knew which wires went to which component.
Solder leads to the power, ground, and signal pins of the accelerometer. Hook the accelerometer up to the arduino, with the input going to one of the analog pins (e.g. A0). Print the raw values as you did for the bend sensors. Try tapping the accelerometer and see what kinds of changes in the values you get. We found that giving the accelerometer a good shake tended to make our input numbers go from three digits to four digits.
Screw the heads off the two flashlights. The spring in the center of the head corresponds to power and the metal threads around the outside correspond to ground. Carefully solder a long power lead to the spring and a long ground lead to the threads. (You will need at least 1.5 yards of each wire to get from the end of the mobile to the arduino.) Plug the ground wire into a ground pin and the power wire into one of the digital pins. When you set the pin to high, the light should turn on, and when you set the pin to low, the light should turn off.
Solder long leads to each end of each of the LEDs, making note of which lead goes to ground and which carries the signal. Test each LED like you did each flashlight--insert the ground wire into a ground pin and the signal wire into a digital pin, then ensure the LED turns on when you set the pin high and off when you set the pin low.
All of your electrical components should now be working, and with the exception of hacking the servos and programming the XBees, they should be ready to use!
Step 4: Hack Servos
The servos are intended to rotate continuously in one direction, which necessitates hacking the servos. The first step in doing this is to remove the hard stop attached to one of the gears. Remove the screws from the casing and remove the plastic top to expose the gears. Take careful note of the order in which the gears are placed so that you can put them back in this order! The bottom pin has a raised plastic piece which prevents the servo from rotating more than 180 degrees in either direction. Carefully cut off this stop--small wire cutters with an angled tip work well for this. Then put all the gears back and screw back on the top, then put on a plastic horn. You should be able to twist the horn continuously in either direction. If you can't, take the horn and cover back off and make sure you removed the entire stop.
The potentiometer (pot) inside the servo tells the servo what position is has. To allow continuous motion, we want the servo to think that the pot is in the middle at all times so that any value other than 0 degrees will cause it to rotate. The pot has a range of 5k, so you can replace the pot with two 2.2k resistors (don't ask us about the math--this was recommended to us). The pot is the cylindrical device inside the body which has a shaft attached to it. Snip the wires holding the pot so you can extract the pot from the casing. Solder a 2.2k resistor in between the white wire (signal) and the black wire (ground) and another 2.2k resistor in between the white wire and the red wire (power). Use electrical tape or heat shrink tubing to insulate the connections. Then (very carefully!) put the pot and shaft back in place and make sure all the components fit back into the body of the motor. Once everything is back in place, screw back on the casing.
Step 5: Program XBees
If you know your XBee radios are properly configured to talk to each other, skip this step.
Configuring XBee's is not exactly the most straightforward of processes. You will need 2 of them, they should be 2 of the same model. We used two S1's. Go ahead and download the XCTU software from beneath the tab named Diagnostics, Utilities, & MIBs. While that is installing, take the FTDI breakout board and solder on leads to Power (3.3 V), Ground, TX & RX (possibly labeled DOUT & DIN).
General rules for XBee's:
1) Only power with 3.3 V, or else you'll fry the radio. Note, your FTDI board and your Ardunio UNO's should have 3.3V rails.
2) A wire that goes to TX on one end goes to RX on the other.
3) Your XBee's should only need 4 wires plugged in ever.
Hook up one of your XBee's to the FTDI board and plug it in to your computer. Then start the XCTU software (as a general rule, plug it in first, then start XCTU).
Hit the Test/Query button towards the right, and if any on-screen instructions pop up, follow them.* You should receive verification that you have some fashion of an XBee. Head over to the Modem Configuration tab, click read, then check 'Always Update Firmware,' then hit write. You will want to do this to both XBee's and receive confirmation that they are configured with identical firmware, and they should be the same model number, though their serial numbers will differ. Next hit Read, uncheck 'Always Update Firmware' and make sure that you set the baud rate to 9600 (under Serial Interfacing; Interface Data Rate) and if you want to avoid interference from your neighbor's XBee tinkering, go ahead and set a different PanID & Channel. Your radios should work if you give them the same Channel, but different ID's. In order to test they can communicate, plug one radio into an Arduino, hook it up to the computer and run the Arduino software. Open the Com Port Serial Monitor (Ctr Shift M) and go back to your 'Terminal' tab from XCTU. Anything you type in the Terminal should appear magically on the other Arduino's Serial Monitor.
At this point, if it doesn't work, check the first three general rules of XBee's (see above, especially #2: i.e. wire goes from TX on the arduino to DIN on the XBee). If it still doesn't work, especially if you have a different model of XBee than we did, use the power of Google to find configuration tutorials. XCTU should have all the power you need to configure them, it is just a trick of making sure you carefully read all the options and they are configured on the same channels with same baud rates, etc. One of them might need to be in 'command' mode while another is in 'peer,' although not necessarily. There are many models of XBee's...
Step 6: Assemble Toy Circuitry
The arduino which goes into the toy will send values depending on whether the flex sensors and the accelerometer are giving high or low values. The flex sensors read high if at least one of them is high. If both the flex sensors and the accelerometer are low, transmit 0; if the flex sensors only are high, transmit 1; if the accelerometer only is high, transmit 2; if both components are high, transmit 3. This significantly simplifies the processing which must be done on the receiving arduino.
Now, there's a bit of a pickle here. The arduino usually transmits a value of '0'. However, for reasons we have not yet determined, the arduino sometimes transmits everything as a ASCII character that is 48 above whatever you desired. We got around this difficulty by just having the receiving arduino test for both possible values, but we'll be sure to update this if we figure out why we get funny values sometimes. It helps to make sure you use the Serial.write() command, not the Serial.print() or Serial.println() commands when you are hoping to actually transmit data across the radios. Also, at this point, as you start plugging things in and putting code on the Arduinos, you'll want to avoid uploading code to an Arduino that has anything plugged into it's TX or RX pins (pins 0 & 1).
We used three 1.5V batteries in series to power the arduino (three AAs). The arduino performs some internal power regulation, so you can power the arduino off of 4.5V or 6V.
Solder the ground leads of the two flex sensors and the arduino together, leaving the end of one lead free to plug into the board. Do the same with the three power leads. Plug the ground leads into one of the ground pins on the arduino and the power leads into the 5V power pin. Plug the power lead of the XBee into the 3.3V pin and the ground lead of the XBee into another ground pin, then plug the RX/DIN lead into the TX pin of the arduino. (The XBee is receiving from the arduino, hence the input of the XBee being connected to the output of the arduino.) Finally, plug the ground lead of the batter pack into the final ground pin and the power lead of the battery pack into the Vin pin.
The toy circuitry is now assembled! Now all you need to do is program the arduino. We used the below code to control our toy.
// Values to be read
int accelVal = 0;
int bendVal1 = 0;
int bendVal2 = 0;
int accelRef;
int bendRef1;
int bendRef2;
boolean accelOn = false;
boolean bendOn = false;
int sendVal = 0;
void setup() {
// This code runs once, at the beginning
Serial.begin(9600); // Initialize serial monitor
// Get reference values: these allow us to calibrate the values we send for any variation in component behavior
accelRef = analogRead(A3);
bendRef1 = analogRead(A4);
bendRef2 = analogRead(A5);
}
void loop() {
// This code runs continuously
delay(1);
// Get values
accelVal = analogRead(A3);
bendVal1 = analogRead(A4);
bendVal2 = analogRead(A5);
// Check if accelerometer is on
if ((accelVal - accelRef) > (accelRef / 3)){ // This is an arbitrary reference that we found worked well
accelOn = true;
} else {
accelOn = false;
}
// Check if bend sensors are on
if ((bendVal1 < (3 * bendRef1 / 4)) || (bendVal2 < (3 * bendRef2 / 4))){ // This is an arbitrary reference
bendOn = true;
} else {
bendOn = false;
}
// Determine the correct value to transmit based on the sensors
if (accelOn == false) {
if (bendOn == false) {
sendVal = 0;
} else {
sendVal = 1;
}
} else {
if (bendOn == false) {
sendVal = 2;
} else {
sendVal = 3;
}
}
// Transmit the value
Serial.write(sendVal);
}
Step 7: Assemble Mobile
We assembled the parts of the mobile back in step 2, so now it's time to put all of them together. Lay out your mobile on the floor to make sure the two sides will not hit each other. We used the full 4' of the thick top dowel. The next layer consisted of medium-weight dowel of approximately 1.5' in length. From this hung a light-weight dowel of approximately 1' in length, off of which hung a butterfly and a flower, and another medium-weight dowel, again approximately 1.5' in length; this hung low enough so as not to interfere with the other branch. Off of that dowel we hung a rainbow and another light dowel of approximately 1' in length with another butterfly and another flower. Each side of the mobile had one of each of the five parts, and we tried to balance the colors used, as well.
We found it useful to lay out one side of the mobile and mark the lengths of the dowels we liked, then cut two of each of the lengths we wanted (to mirror the mobile on the other side). Once you have the dowels at the lengths you like, tie the requisite parts at the ends of the corresponding dowels using fishing line. Secure the fishing line to the dowel with hot glue. Once you have all the components set, balance the mobile, starting from the bottom. Tie fishing line to the center of the bottom dowel, find the balance point, and glue the fishing line in place. Then tie this branch to the end of the medium dowel with the rainbow on the other end and secure. Balance this branch, then tie to one end of the other medium dowel. Balance the final light dowel and secure to the other end of the medium dowel. Finally, balance this branch and attach a servo horn directly at the balance point with fishing line and hot glue. Repeat this process on the other branch. Attach a servo to each end of the heavy dowel, using hot glue. You may find it helpful to troubleshoot the mobile assembly before attaching the servos to the horns, but eventually you will hot glue the servo horns to the servo shafts; this is necessary because of the weight of the branches, although the branches are not very heavy. Braid the three wires for each servo together and secure them along the thick dowel rod, having them meet in the middle.
Cut the remaining medium-weight dowel in half and attach one half to each side of the main heavy-weight dowel rod. Tape and/or glue the blacklights to the ends of the medium-weight dowel, facing towards the mobile. You will need to play with the angle of the blacklight heads somewhat to obtain a nice angle such that all the mobile pieces are hit by the blacklight. Twist the blacklight wires together and secure them to the rod, meeting at the balance point of the rod. Use fishing line to tie an LED to each end of the thick dowel and one in the middle, securing the fishing line with hot glue as necessary. Twist the wires for each LED together and make them meet in the middle. Twist all the wires from the LEDs, blacklights, and motors together and with the fishing line suspending the center of the mobile. These wires will all go to the arduino in the ceiling where the mobile is mounted. (Of course, if your ceiling does not have removable tiles like the one we used does, you will need some other place to store all your circuitry.)
Step 8: Assemble Mobile Circuitry
We assembled and tested all the components for the mobile circuitry in steps 3, 4, and 5, so now it's time to put them together. We found that a mini breadboard helped us to clean up our circuit so we could see all the components. You can, however, build the circuit entirely on the arduino if you prefer.
Connect the 3.3V pin of the arduino to the VDD pin of the XBee, the RX pin of the arduino the the VIN pin of the XBee, and a ground pin of the arduino to the ground pin of the XBEE. We found that we needed to power the two motors separately from the arduino because the arduino could not source enough current to power the arduinos as well as all the other components. Connect the power wires of the servos to each other and to the power wire of the AAA battery pack. Connect the ground wires of the servos to each other and to the ground wire of the AAA battery pack. Solder the ground wires of the LEDs, the blacklights, and the servos all together, leaving one end free to plug into a ground pin. Connect all components to the requisite pins--we used pins 12 and 11 for blacklights, 10 and 9 for servos, and 8, 7, and 6 for LEDs.
Finally, power the arduino itself. We used two battery packs of two AAs each connected in series to give us a 6V input; you can also, as discussed previously, power arduinos off of 4.5V; we used whatever we had available. Connect the power lead to the VIN pin and the ground lead to a GND pin. Incidentally, we found that soldering leads onto the battery packs from the flashlights worked well--we used one of these to power the servos.
Now all you need to do is program the arduino. We used the below code on the mobile arduino to control the various components.
#include <Servo.h>
int serial_val = 0;
boolean motors_on = false;
// Counters for the LEDs flashing
int x1 = 0;
int x2 = 0;
int x3 = 0;
// Sample pins for mobile-mounted arduino
static int ledPin1 = 6;
static int ledPin2 = 7;
static int ledPin3 = 8;
static int motorPin1 = 9;
static int motorPin2 = 10;
static int flashlightPin1 = 11;
static int flashlightPin2 = 12;
// Servo information
Servo motor1;
Servo motor2;
int pos1 = 0; // position of motor1
int pos2 = 0; // position of motor2
void setup() {
// Setup code runs once at the beginning
Serial.begin(9600); // Starts the serial monitor
// Tell the arduino which pins will be used for output; no pins will be used for input on the mobile
pinMode(motorPin1, OUTPUT);
pinMode(motorPin2, OUTPUT);
pinMode(flashlightPin1, OUTPUT);
pinMode(flashlightPin2, OUTPUT);
pinMode(ledPin1, OUTPUT);
pinMode(ledPin2, OUTPUT);
pinMode(ledPin3, OUTPUT);
// Pin 13 is the built-in LED, usually used to signify that the program wrote correctly
pinMode(13, OUTPUT);
digitalWrite(13, HIGH);
}
void loop() {
// Main code, which runs repeatedly
// read value from (radio), subtract 48 for quick fix from ASCII to int
if(Serial.available())
serial_val = Serial.read()-48;
// Check to make sure the value read is reasonable
Serial.println(serial_val);
if(serial_val > 0)
{
digitalWrite(13, HIGH);
}
else
{
digitalWrite(13, LOW);
}
// Increment counters
x1 = x1 + 1;
x2 = x2 + 1;
x3 = x3 + 1;
// Check values of counters; random primes were selected as cutoffs so the cycles wouldn't line up
if (x1 > 20483){
x1 = 0;
} else {
if (x1 < 1000){
digitalWrite(ledPin1, HIGH); // Turn on for 1 second every 20.483 seconds
} else {
digitalWrite(ledPin1, LOW); // Turn off the rest of the time
}
}
if (x2 > 29303){
x2 = 0;
} else {
if (x2 < 1200) {
digitalWrite(ledPin2, HIGH); // Turn on for 1.2 seconds every 29.303 seconds
} else {
digitalWrite(ledPin2, LOW); // Turn off the rest of the time
}
}
if (x3 > 18397){
x3 = 0;
} else {
if (x3 < 900) {
digitalWrite(ledPin3, HIGH); // Turn on for 0.9 seconds every 18.397 seconds
} else {
digitalWrite(ledPin3, LOW); // Turn off the rest of the time
}
}
// Delay just a bit so the program can respond
delay(1);
// to turn the blacklights on / off:
if(serial_val == 1 || serial_val ==3)
{
digitalWrite(flashlightPin1, HIGH);
digitalWrite(flashlightPin2, HIGH);
}
else
{
digitalWrite(flashlightPin1, LOW);
digitalWrite(flashlightPin2, LOW);
}
// Turn the motors on or off
// This code actually turns them on and off for brief spurts by attaching and detaching the motors
// because otherwise they ran at too high a speed and the pieces hit each other
if(serial_val == 2 || serial_val == 3)
{
if(motors_on)
{
motors_on = false;
motor1.detach();
motor2.detach();
}
else
{
motors_on = true;
motor1.attach(motorPin1); // Attach motor1 to appropriate pin
motor2.attach(motorPin2); // Attach motor2 to appropriate pin
motor1.write(0);
motor2.write(0);
delay(300);
}
}
else
{
if(motors_on)
{
motors_on = false;
motor1.detach();
motor2.detach();
}
}
}
Step 9: Final Assembly
If you are mounting your mobile inside the ceiling, like we did, stand on a table or other tall object and move aside a tile in the ceiling. The circuitry will rest on top of a neighboring tile. Tie the mobile to the ceiling and place the circuitry inside the ceiling. Test the mobile and toy interaction to make sure no wires were displaced in the hanging of the mobile. Then slide the ceiling tile back into place.
Open the toy's midsection and pull out most of the stuffing. Our toy had a very large head, so we put the boards inside the head. If you are afraid that your wires may slip out (ours did!), encase the arduino gently with tape to hold everything in place. (You could get around this problem by making your own circuit board and soldering everything in place, but this method works all right.) Carefully slide the arduino into the stuffed animal and pad with a little bit of the extracted stuffing. Next, sew the bend sensors to the sides of the stuffed animal, hiding the stitching as much as possible in the animal's fur. Finally, slide in the battery pack. Pad with as much stuffing as will fit. Turn the battery pack on and test the interaction with the mobile.
Congratulations! You now have a working, glow-in-the-dark, interactive baby mobile.
~Molly and Josh.
Maybe I missed it, but where did you find the uv led flashlights with twist off heads?
This is really cool.
A word of caution, sometimes flourescent colours induce vomiting in infants. In Sweden babytoys with these colours were pulled back in the 90'ties because of fears the vomit would suffocate the babies.
I would love to make ths switch activated for my handicapped child but its abit over my head Anyway to simplify.
The hardest part is getting the two arduinos to work with each other; if you're just interested in the glowing, moving mobile, you could simplify a lot of the work by just working with the mobile and not using the toy. Feel free to message me offline if you'd like to talk more about this! | http://www.instructables.com/id/Interactive-Childs-Mobile/ | CC-MAIN-2017-39 | refinedweb | 4,719 | 69.31 |
The Problem(s) With Solaris SVR4 Link-Editor Mapfiles
By Ali Bahrami-Oracle on Jan 06, 2010
Lately, I've been working on a new mapfile syntax to replace this original language, which Solaris inherited as part of its System V Release 4 origins. In the process, I've examined every line of the manual, and of the code, many times. I believe I understand it all the way down now, and I'd like to record some of what I've learned here. My main reason for doing this is as justification for undertaking a replacement language. Oddly enough though, I believe that this information will make it easier to decode, use, and write these older mapfiles. Once you understand the quirks, you can work around them.
This discussion will not cover the new syntax that will come in a subsequent installment. However, I do want to reassure you that full support for the original mapfile language will remain in place. We're not about to force anyone to rewrite 20+ years worth of mapfiles. The goal is to freeze the old support in its current form, provide a better alternative, and gradually move the world to it over a period of years.
Terse To A Fault / Not ExtensibleThe:
- There are only a limited number of magic characters available, mainly on the top row of the keyboard.
- Only a few of these characters have mnemonic meanings that make intuitive sense in the context of object linking. And those that do have such a meaning can easily imply more than one thing. For example, In the SVR4 syntax, '=' means segment creation, and ':' means section to segment assignment. The reverse would make just as much sense: ':' could have meant segment creation, and '=' could have meant assign sections to segments. No one would have found this less intuitive. I used to constantly get these backwards, and would have to look at the manual or another mapfile to remember which character has which meaning. That's pretty sad, considering that '=' is probably the most mnemonic character in the language.
- After the first few good characters (=, :) are taken, the remaining assignments become rather arbitrary. For instance, the | character is used to specify section order, while @ specifies the creation of a "segment size symbol". Neither of these evoke meaning. To the extent that they do, it's a negative effect, such as the fact that '|' evokes shell pipelines, but means nothing like that in mapfiles.
- Some characters are overloaded, having different meanings in different contexts.
SVR4 Mapfile Syntax As EvolutionFor me, the best way to understand the SVR4 mapfile syntax has been to start with it's original form, and then consider how and where each subsequent feature has been added.
In the late 1980's, starting around 1986 or so, Unix System V Release 4 (SVR4) was being developed at AT&T. They created a new linking format (ELF), to resolve the inadequacies of previous format (COFF) used in SVR3. SVR3 had a rather elaborate mapfile syntax. Rather than stay with this syntax, the SVR4 people designed a new, smaller, and simpler replacement. We don't know their reasons for this decision, and can only guess that they didn't think the SVR3 language was necessary, or a good fit with their new ELF based link-editor. As an aside, while researching different mapfile languages during the design of the replacement syntax for Solaris, I discovered that there is a notable similarity between the SVR3 mapfile language and GNU ld linker scripts. SVR3 lives on, as does much of Unix, in its influence on later systems.
The original SVR4 language was very small, consisting of four different possible statements. All of these have the form:
where name is a segment name, and magic is a character that determines what the directive does:where name is a segment name, and magic is a character that determines what the directive does:name magic ... ;
- Segment Definition (=): Create segments and/or modify their attributes
- Section to Segment Assignment (:): Specify how sections are assigned to segments
- Section-Within-Segment Ordering (|): Specify the order in which output sections are ordered within a segment
- Segment size symbols (@): Create absolute symbols containing final segment size in output object.
Solaris started with the original SVR4 code base. Since then, Sun has added three more top level statements:
- Symbol scope/version definition ({}): Assign symbols to versions
- File Control Directives (-): Specify which versions can be used from sharable object dependencies
- Hardware/Software capabilities (=): Augment/override the capabilities from objects..[version-name] { scope: symbol [= ...]; *; } [inherited-version-name...];
Segment Definition (=)Segment definition statements can be used to create a new segment, or to modify existing ones:
If a segment-attribute-value is one of (LOAD, NOTE, NULL, STACK), then it defines the type of segment being created:If a segment-attribute-value is one of (LOAD, NOTE, NULL, STACK), then it defines the type of segment being created:segment_name = segment-attribute-value... ;
- LOAD segments are regions of the object to be mapped into the process address space at runtime, represented by PT_LOAD program header entries. LOAD segments were part of the original AT&T language.
- NOTE segments are regions of the object to contain note sections, represented by PT_NOTE program header entries. NOTE segments were part of the original AT&T language.
- NULL segments are a concept added by Sun. As far as we can determine, they were created in order to have a type of segment that won't be eliminated from the output object if no sections are assigned to them. Their actual meaning depends on whether the ?E flags is set or not, as described below.
- STACK "segments" were added by Sun relatively recently in order to allow modifying the attributes of the process stack. This is not really a segment at all: It does not specify a memory mapping, and sections cannot be assigned to it. Rather, it allows access to the PT_SUNWSTACK program header, setting the header flags to specify stack permissions. Only the flags can be set on a stack "segment". The representation of this concept as a segment was done to simplify the underlying implementation of the feature.
If a segment-attribute-value starts with the '?' character, then it is a segment flag:
- ?R, ?W, ?X
- Set the Read (PF_R), Write (PF_W), and eXecute (PF_X) program header flags, respectively. This is a feature of the original SVR4 syntax, and is self explanatory.
- ?E
- The Empty flag can be be used with either a LOAD, or NULL segment:
- Applied to a LOAD segment, the ?E flag creates a "reservation". This is an obscure and little used feature by which a program header is written to the output object, "reserving" a region of the address space for use by the program, which presumably knows how to locate it and do something useful. Sections cannot be assigned to such a segment.
- Applied to a NULL segment, the ?E flag adds extra PT_NULL program headers to the end of the program header array. This feature is useful for post optimizers which rewrite objects to add segments, and need a place to create corresponding PT_LOAD program headers for them.
- The ?E flag is meaningless when applied to NOTE or STACK segments.
The Empty flag was added by Sun. It should be noted that ?E does not correspond to an actual program header flag. It's treatment as a flag in the mapfile syntax, rather than expressing it as a different sort of option (using a magic character other than '?' as a prefix) was primarily a matter of implementation convenience.
- ?N
- Normally, the link-editor makes the ELF and program headers part of the first loadable segment in the object. The ?N flag, if set on the first loadable segment, prevents this from occurring. The headers are still placed in the output object, but are not part of a segment, and therefore not available at runtime. It is meaningless to apply ?N to a non-LOAD segment.
This flag was added by Sun. As with ?E, it does not correspond to a real program header flag. It's representation as a flag is a matter of implementation convenience.
- ?O
- This is another flag, added by Sun, that does not correspond to a real program header. It is used to control the order the placement of sections from input files within the output sections in the segment. Sections are assigned to segments via the ':' mapfile directive. Normally, sections are added in the order seen by the link-editor. When ?O is set, the order of the input sections matches the order in which these assignment directives are found in the mapfile.
This feature was added to support the use of the -xF option to the compiler. That option causes each function to be placed in its own section, rather than all of the functions from a given source file going into a single generic text section. Then, their order can be specified using a mapfile, as with this example taken from the Linker and Libraries Manual).text = LOAD ?RXO; text : .text%foo text : .text%bar text : .text%main
A segment-attribute-value can also be a numeric value, prefixed with one of the letters (A, L, R, V), to set the Alignment, Maximum length, Rounding, Physical address, or Virtual address of a LOAD segment, respectively.
The syntax for segment definition suffers from a variety of issues:
- Most of the options can only be applied to specific segment types, primarily to type LOAD. However, the syntax does nothing to prevent you from trying to apply attributes that are invalid for the type of segment in question. For instance, you might try to assign an address to a STACK segment. The link-editor contains a fair amount of code dedicated to detecting such uses and issuing errors. A better syntax would not allow you to specify nonsensical options in the first place.
- STACK "segments" are not really segments at all, but simply a convenient way to manipulate a specific program header. This is confusing, and can lead the user to believe they can control aspects of the stack (such as it's address) that are not user settable.
- An ELF object can only have one PT_SUNWSTACK program header. The segment notation used by mapfiles requires the user to give their stack "segment" a name, perhaps causing a user to think they might be able to create more than one stack by specifying more than one mapfile directive using different names. The link-editor contains code dedicated to catching this and turning it into an error.
- The ?E, ?N, and ?O flags are confusing, in that they do not correspond directly to ELF program header flags, their terseness, and also their obscure semantics.
- There is a syntactic ambiguity with capability directives, which use the same magic character (=) as segment definitions, but which are otherwise unrelated. See the discussion of capability directives below for details.
Section to Segment Assignment (:.
Sections can be assigned to a specific segment via the following syntax, which uses the ':' magic character. The result of such a statement is to place a new entrance criteria on the internal list:
segment_name : section-attribute-value... [: file-name...];
If a section-attribute-value starts with a '$' prefix, then it specifies a section type. This can be one of ($PROGBITS, $SYMTAB, $STRTAB, $REL, $RELA, $NOTE, $NOBITS).
If a section-attribute-value starts with a '?' prefix, then it specifies one or more section header flags: A (SHF_ALLOC), W (SHF_WRITE), or X (SHF_EXECINSTR). To specify that a given flag must not be present, you can prepend it with the '!' character.
A section-attribute-value that does not start with a '$' or '?' prefix is a section name.
If there is a second colon (':') character on the line, then all items following it are file paths, and if any of these match the path for the input file containing the section to be assigned, it is considered to be a match. If the path name is prefixed with a '*', then the basename of the path is compared to the given name rather than the entire path.
Odd aspects of section to segment assignment:
- The list of section types is incomplete. ELF defines many more section types than the 7 listed above. Apparently this feature isn't used, at least with types outside of $PROGBITS or $NOBITS, because I've never heard of a complaint about it. In any event, all ELF section types should be supported.
- The use of a '*' prefix to mean 'basename' in file paths is odd. Conditioned by common shell idioms, any Unix user would expect a '*' within a filepath to be a standard glob wildcard, expanded as the shell would. You'd expect it to match an arbitrary number of characters, and to be usable in the middle of the name, not just at the beginning. Another reasonable assumption would be that it is a regular expression, with the implication that other regular expression features are also possible. None of that applies: A '*' prefix means 'basename', and only if it is the first character.
- The fact that segment definition, and the assignment rules, are two separate statements creates the potential for a class of error where the user attempts to assign sections to a segment that cannot accept them (e.g. STACK). Having lured you in with a syntax that suggests something that isn't possible, the link-editor contains code to detect and refuse such assignments. Better syntax could prevent this.
Section-Within-Segment Ordering (|)Section within segment ordering can be used to cause the link-editor to order output sections within a segment in a specified order. The specification is done by section name:
segment_name | section_name1; segment_name | section_name2; segment_name | section_name3;
The named sections are placed at the head of the output section in the order listed.
One might expect to be able to put more than one section on a line (you can't), and the use of '|' may cause a Unix user to make some invalid assumptions about shell pipes, or the C bitwise OR operator. However, there's nothing really terrible about this directive.
It's also not terribly useful --- I'm not sure I've ever seen it used outside of our link-editor tests.
Segment size symbols (@)The '@' magic character is used to create an absolute symbol containing the length of the associated segment, in bytes:
segment_name @ symbol_name;
There is no corresponding mechanism to create a symbol containing the starting address of a segment, so it is debatable how useful the length is. Perhaps the user is expected to know the name of the first item (possibly a function in a text segment) and use that. In any case, we've never seen this feature used outside of our own tests.
The use of '@' carries no useful mnemonic information, but that's not unique to this particular directive.
Symbol Scope/Version Definition ({}:
- A symbol scope name (default/global, eliminate, exported, hidden/local, protected, singleton, symbolic), followed by a colon. These statements change the current scope, which starts as global, to the one specified. Any symbols listed after a scope declaration receive that scope, until changed by a following scope definition.
- A '*', which is called the scope auto-reduction operator. All global symbols in the final object not explicitly listed in a scope/version directive are given the current scope, which must be hidden/local, or eliminate. Auto-reduction is a powerful tool for preventing implementation details of an object from becoming visible to other objects.
- A symbol name, optionally followed by a '=' operator and attributes, finally terminated with a ';'.
The attributes that are allowed for a symbol are:
- A numeric value, prefixed with a 'V', giving the symbol value.
- A numeric value, prefixed with a 'S', giving the symbol size.
- One of 'FUNCTION', 'DATA', or 'COMMON', specifying the type of the symbol.
- 'FILTER', or 'AUX', specifying that the symbol is a standard or auxiliary filter, followed by the name of the object supplying the filtee. The two tokens are separated by whitespace.
- A large number of flags that specify various attributes: 'PARENT', 'EXTERN', 'DIRECT', 'NODIRECT', 'INTERPOSE', 'DYNSORT', 'NODYNSORT'.
- The use of 'V' and 'S' prefixes for value and size, contrasted with the full keywords 'FILTER' and 'AUX' is odd.
- The lack of some sort of connecting syntax between FILTER/AUX and the associated object is confusing, and leads to certain confusing errors. For example, a statement like 'filter function' is probably intended to say that the symbol is a function, and also a filter, but will be interpreted as being a filter to a library named 'function', drawing no error from the link-editor. A syntax such as 'filter=object' might have been better.
- The syntax does not distinguish between the type and flag values values. This is generally not a problem, but a syntax that did would be more precise, and possibly helpful.
File Control Directives (-:
shared_object_name - version_name [version_name ...];
where version_name is the name of versions found within the shared object.
When a given shared object is specified with one of these directives, the link-editor will only consider using symbols from the object that come from the listed versions, or the versions they inherit. The link-editor will then make the versions actually used dependencies for the output object.
Alternatively, a version_name can be specified using the form:
$ADDVERS=version_name
In this case, the specified name is made a dependency for the output object whether or not it was actually needed by the link.
There are some odd aspects to file control directives:
- The '-' magic character has no mnemonic value (as usual).
- The use of the '$' character in $ADDVERS, to create a type of optional attribute, is unusual, and represents an overloading of '$' relative to other directives.
- The use of '$' aside, the $ADDVERS= notation is unusual relative to the rest of the language, which might have used another magic character instead.
Hardware/Software Capabilities (=)The hardware and software capabilities of an object can be augmented, or replaced, using mapfile capability directives:
where the values on the right hand side of the '=' operator can be one of the following:where the values on the right hand side of the '=' operator can be one of the following:hwcap_1 = capitem...; sfcap_1 = capitem...;
- The name of a capability
- A numeric value, prefixed with a 'V' to indicate that it is a number rather than a name.
- $OVERRIDE, instructing the link-editor that the capabilities specified in the mapfile should completely replace those provided by the input objects, rather than add to them.
Perhaps the most unfortunate fact about the capability directives is that they use the '=' magic character, which normally indicates a segment definition. This has some odd ramifications:
- The names 'hwcap_1', and sfcap_1' have been stolen from the segment namespace, and cannot be used to name segments.
- As new capabilities are added to the system, it may become necessary to introduce new capability directives. For example, it is clear that 'hwcap_2' will soon be needed on X86 platforms. When this happens, the new name will also be taken from the segment namespace. Existing mapfiles using that name for a segment will break. One might reasonably expect that there are no such mapfiles, but that is a poor justification.
- These names are case sensitive. Although segments cannot be named 'hwcap_1', or 'sfcap_1', they can have these names using any other case. For instance, 'HWCAP_1' will be interpreted as a segment, not as a capability.
One can understand the temptation to reuse '=' for capabilities, instead of picking some other unused magic character. Which one would you pick to convey the idea of 'capability'? I don't find any of the available characters (%, \^, &, ~) compelling in the least. Still, this overloading of '=' is a problem.
As a demonstration of how very similar mapfile lines can have wildly different meanings, consider the following example, which uses the debug feature of the link-editor to show us how mapfile lines are interpreted:
% cat hello.c #include <stdio.h> int main(int argc, char **argv) { printf("hello\\n"); return (0); } % cat mapfile-cap HwCaP_1 = LOAD ?RWX; # A segment hwcap_1 = V0x12; # A capability % LD_OPTIONS=-Dmap cc hello.c -Mmapfile-cap debug: debug: map file=mapfile-cap debug: segment declaration (=), segment added: debug: debug: segment[3] sg_name: HwCaP_1 debug: p_vaddr: 0 p_flags: [ PF_X PF_W PF_R ] debug: p_paddr: 0 p_type: [ PT_LOAD ] debug: p_filesz: 0 p_memsz: 0 debug: p_offset: 0 p_align: 0x10000 debug: sg_length: 0 debug: sg_flags: [ FLG_SG_ALIGN FLG_SG_FLAGS FLG_SG_TYPE ] debug: debug: hardware/software declaration (=), capabilities added: debug:
Other misfeatures of the capability syntax are the overloading of the '$' prefix to indicate an instruction to the link-editor ($OVERRIDE), and the use of the 'V' prefix in front of numeric values. These prefixes have different, though similar, meanings elsewhere, which makes the language hard to understand.
Mapfile Magic Character Decoder RingAnother strategy for understanding SVR4 mapfiles is to organize things by magic character.
Most mapfile directives have the form:
where name is generally (but not always) a segment name, and magic is a character that determines what the directive does.where name is generally (but not always) a segment name, and magic is a character that determines what the directive does.name magic ... ;
The following is a comprehensive list, in no particular order, of the magic characters and related syntactic elements used in the current SVR4 mapfile language:
Time For A Fresh StartThe
The mapfile syntax issue usually comes up in the context of wanting to add a new feature, and disparing at the ugliness of what that implies. One is usually in the middle of solving a considerably more focused and urgent problem, and not willing or able to take an extensive detour to replace underlying infrastructure. And so we've moved forward, adding one thing, and then another, with the situation slowly, but not catastrophically, getting worse each time The current state of our mapfile language is such that we shy away from adding new features, and we are aware of other projects that may need some link-editor support in the near future. The right infrastructure simplifies everything it touches, and as we know all too well, the reverse is also true.
We've known for quite awhile that eventually it would be necessary to tackle this issue systematically and produce a new mapfile language for Solaris. That time has finally arrived.
This is great news, and solid background work.
As a matter of personal interest, I've tried once or twice to divine what's going on with ld. I never got too far, owing to other demands, but neither could I remember that I ever got a foothold from the attempts.
These blog articles are saving me a ton of time in background reading, at the very least. At their best, they're turning on a number of lights for me. Thanks! And keep up the great work.
Posted by Michael Ernest on January 06, 2010 at 11:35 AM MST # | https://blogs.oracle.com/ali/entry/the_problem_s_with_solaris | CC-MAIN-2016-30 | refinedweb | 3,829 | 52.39 |
Jacek Generowicz <jacek.generowicz at cern.ch> wrote in message news:<tyfbruf998w.fsf at lxplus014.cern.ch>... > ==== Example 1: a debugging aid ================================ > === Example 2: Alexander Schmolck's updating classes =============== Here's another example of a real life situation where I thought it'd be good to have macros in Python. I was writing a GUI system and I had to define lots of code twice, both for the x-axis and y-axis. Such as if y > self.y - bs and y < self.y + bs + self.height: return (abs(x - self.x) < bs, abs(x - (self.x + self.width)) < bs) else: return False, False and then if x > self.x - bs and x < self.x + bs + self.width: return (abs(y - self.y) < bs, abs(y - (self.y + self.height)) < bs) else: return False, False Obviously this was quite unsatisfactory. I ended up putting the axis code in a separate class so I could use them interchangeably. I.e. If I passed func(self.y, self.x) and then func(self.x, self.y) I would get the same effect on both axises. But this would've been an excellent place for macros IMO (unless there's a more clever solution as a whole). Using macros that combine both function call and "code block" syntax, I could've written a simple function like this: defBoth getSize(self): return self.size And it would've been expanded to def getWidth(self): return self.width def getHeight(self): return self.height The macro would've had to change all "size" to either "width" or "height", and also change "pos" to either "x" or "y" and so on. This way, I could've got no duplicated code but also a more intuitive interface than I currently have (to get width, one needs to type obj.x.getSize() instead of obj.getWidth()). And it's obvious this kind of "defBoth" wouldn't be added as a language level construct -- Thus macros are the only good solution. | https://mail.python.org/pipermail/python-list/2003-August/180469.html | CC-MAIN-2014-15 | refinedweb | 332 | 78.55 |
# Hashing
It is an efficient searching technique. Searching is a widespread operation on any data structure. Hashing is used to search specific records from a large domain of records. If we can efficiently search a record out of many records, we easily perform different operations on that data. Hashing is storing and retrieving data from the database in the order of O(1) time. We can also call it the mapping technique because we try to map smaller values into larger values by using hashing.
Following are the significant terminologies related to hashing
**Search Key**
In the database, we usually perform searching with the help of some keys. These keys are called search keys. If we take the student data, then we search by some registration number. This registration number is a search key. We have to put the search keys in hash tables.
**Hash Table**
It is a data structure that provides us the methodology to store data properly. A hash table is shown below. It is similar to an array. And we have indexes in it also like an array.
**Hash Function**
When we perform searching, inserting, or deleting some data from it, we don’t need to scan the whole table. With the help of a hash function, we will perform it with the order of O(1) time. There are different hash functions such as:
* K mod 10
* K mod n
* Mid Square
* Folding Method
‘K mod 10’ and ‘K mod n’ are the most widely used methods.
Suppose we have a number 24 and hash function ‘K mod 10’.With the help of the hash function, we will map 24 in the hash table. For this purpose, we can put K is equal to 24 so:
*24 mod 10 = 4*
So we can place 24 at index 4 in the hash table. Then for 52 number
*52 mod 10 = 2*
52 will go to index 2 location. Next for number 91
*91 mod 10 = 1*
So, 91 will be placed at index 1 in the table. Then finally for 67
*67 mod 10 = 7*
A hash table uses two components:
* Hash function
* Bucket Array
For an element key pair, the hash function calculates some value based on a key. A hash function is a function with a key as an input parameter. A hash function will give us two parts:
**Hash Codes**
In this, we assign an integer to the key. It is going to map the key to some integer.
**Compression Map**
It will convert the integer, or rather it will map the integer which we have received from the hash code to an integer in the range 0 to n-1. Once we have the hash function of the key, we would first receive an integer, and then map that integer to 0 to n-1. So the outcome of the hash code or the outcome of the hash function will be an integer in the range 0 to the n-1. This integer depends on the key of the input element.
In the bucket array, we are going to store the element in an array of hash functions of the key. So once we will receive an integer in the range 0 to n minus 1.So, we will store the element in an array of not just the key but the array of hash function of the key. So, once we do this, the keys no longer have to be integers. Also, we don’t need to know the range of keys because we are going to map it into a range which is provided by us.
**Hash Code**
Hash code is a function that converts a key to an integer. So it's going to convert a key of any type to an integer.
Following are some properties of a good hash code:
* It will minimize collisions. It means that if we are given two keys that are different, their hash codes should also be different. So if two keys say ‘K1’ does not equal ‘K2’.
*K1 ≠K2*
It implies that the hash code of key 1 should also not equal to the hash code of key 2.If two keys are a map to the same hash code, then we say a collision has occurred. We don’t want this. We want different hash codes for different keys. So we want to minimize collisions.
* A good hashcode should be uniform. If we have a key ‘K1’ and that is equal to key ‘K2’.
*K1 = K2*
Then we don’t need different answers for hash code. Because for the same value of the key, if we run our hash code, then we should always get the same value of the hash code. So if both keys are equal, then the hash code of Key 1 has to equal the hash code of Key 2.
*hash(K1) = hash(K2)*
**Hash Code Map Example**
***Memory Address***
In this, we are going to interpret the memory address of the key as the hash code. So we are going to take the memory address of the key as the hash code of the key.
Let's take an example of it. We have a key 1, and this is at a memory address of 5000. Then we have key 2, and this is at memory address 5010.
 *Hash(K1) = 5000*
*Hash(K2) = 5010*
It can be seen that the key, whatever the data type it may be, has arrived at an integer that maps to that data.
*Disadvantage*
The disadvantage of this hash code is that this is not uniform.
***Integer Cast***
It is a method of mapping to an integer. In this, whatever the data type of the key may be, typecast it to an integer. So if we have a string and we typecast a character of that string, it is going to return an ASCII value to us. And thereby, we will get an integer.
*Disadvantage*
Its disadvantage is that for data types like double or float, we encounter a loss of data. And a lot of collisions will occur in this method.
***Component Sum***
It is a type of hash code in which the partition bits of the key into fixed-length components. Suppose we have a float or a double that’s going to be 64 bits for us. We will partition them into a fixed bit component. So we will partition these 64 bits into two 32 bits. Then we will add these two 32 bits to get a 32-bit hash code after ignoring overflow.
Suppose we use a string case. And We have a key that is equal to the string ‘NAME’. So, in this case, we will not directly typecast this to an integer. We will divide this into four 32 bit segments. Then we will add these values. For each of these values, we take ASCII values of each of these characters. Then we will get the final hash code by adding each of these values.
*Key = ‘NAME’*
*ASC(N) + ASC(A) + ASC(M) + ASC(E)*
*Hash Code (Key) = X*
Disadvantage
Its disadvantage is that a lot of collisions can occur with different arrangements of various segments.
***Polynomial Accumulation***
In this, firstly, we divide a key into different segments like component sum. But in polynomial accumulation, we just take some variables or integers or some non-zero constant.
Suppose we have a key that is equal to a string ‘CODE’. We will divide this key into 32-bit segments. Then we will take the ASCII value of each of the string characters. Then we will take the sum of ASCII of each character into non-zero constant ( a ).
*Key = ‘CODE’*
*( ASC(C) x a0 )+( ASC(O) x a1) + (ASC(D) x a2) + (ASC(E) x a3)*
*Hash Code (Key, a)*
In this, if we change the arrangement of letters, the hash code is also going to change. For the same keys, we will get the same hash code. For the different keys, we will get different hash codes. Now let's take a look at the program of hash code. Let's say that key is going to be an array. Elements of this array will contain 32-bit segments which we have divided our key into. At position 0, we will have ASCII of ‘C’. At position 1,2, and 3, we will have ASCII of ‘O’,’D’, and ‘E’. Now program to calculate the hash code is:
```
for(i= n-1 ; i > = 0 ; i--){
sum = ( sum * a ) + arr[i];
}
arr[ C , O , D , E ]
i = 3 , sum = E ;
i = 2 , sum = Ea + D ;
i = 1 , sum = Ea2+ Da + O;
i = 0 , sum = Ea3+ Da2+ Oa + C;
```
**Hashing Techniques to Resolve Collision**
When we calculate some hash function or location or address for keys and use that same hash function. That hash function will give the same index, but we cannot store two values at the same place in the hash table. This process is called a collision. To resolve these collisions, we have some techniques:
***Separate Chaining***
In this type, if two keys hash to the same hash value, then in the bucket array for that particular hash value index, we will create a linked list.
Let's consider we have keys 100,105,200, and 205. Hash function is equal to K times mod of 10.
*Keys = 100 ,105,200,205*
*H(K) = K mod 10*
Since the range of this function is 10, we have a bucket array of elements ranging from 0 to 9. For the first key-value, which is 100, 100 mod 10 is equal to 0. So it will be filled at index 0. At index 0, we will start a linked list with the key of 100. Now for key 105,
*105 mod 10 = 5*
So now start a linked list with a key of 105 at index 5.Then, for key 200,
*200 mod 10 = 0*
So we will go to the index 0 and add it to the end of the linked list after 100. Now for the key 205,
*205 mod 10 = 5*
We will go to index 5 and add it to the end of the linked list after 105. This is how to separate chaining works.
So we always need two functions for a hash table in it. The first insert operation and the second is the search operation. Let's look at the algorithm of each function.
***Insert***
This algorithm is fairly simple. If we say insert and we have an algorithm ‘insert item' . And we have a (key, element) pair which we want to insert. So, we will go to the index, which is equal to the key. Then at that index, we will have a linked list. This is going to be an array of linked list.So to this linked list, we will insert at the end the key-element pair.
***Search***
If we want to search for a key-element pair, the linked list we search for the element will be equal to the linked present in the array of the index key. So call this linked as C and store the array of a key in it. Now C is a linked list in which we want to search.
***Linear Probing***
In this, when a collision occurs, that is two distinct keys are mapped to the same hash value. In such a case, the colliding element will be positioned in the later circularly available table cell.
To understand the working of linear probing, let's consider that our hash function is:
*H(x) = x mod 10*
And keys are:
*Keys = (18,41,22,32,44,59,79)*
Now hash values will be:
*Hash Values = ( 8, 1,2,2,4,9,9)*
As the range is 10, the bucket array will have indexes from 0 to 9. We will place each key in the index, which is equal to their hash value. For the key value 32, its index value is the same as key-value 22. Index 2 has been already filled with key 22, so I will check its next index. As next index 3 is empty or free, so key 32 will be placed here. The index for key 79 is 9, but it has already been filled with key 59 because its index is also 9. So, we will go to the next circularly available table cell, which is 0. As index 0 is free, so we will place key 79 here:
Now let's see the pseudocode for inserting an element. Firstly we will calculate the hash code or hash value of the key and store that value in variable ‘H’. The key could be either placed at index H or could be placed at an index somewhere different from H provided that H is not empty. So let's keep the incrementing variable i equal to 0.
***Quadratic Probing***
In linear probing, a lot of elements start clustering. That is, elements will start to be stored in groups or in a group of consecutive filled cells. This is not good because when we want to add an element to a cluster , we have to probe through many indexes to finally add that element. So it is not very time efficient. The solution to this problem is quadratic probing. In quadratic probing, we have to check which indexes to check when we want to add an element. We iteratively check the index of the hash value of the key plus square of i mod N.The expression for quadratic probing is:
Suppose we have a hash function:
*H(x) = x mod 10*
And keys are:
*Keys = ( 2, 12 , 22 )*
Hash value will be:
*Hash = ( 2,2,2 )*
Now we will create an array having indexes 0 to 9.Firstly, key 2 will be placed at index value 2 in the array. Key 12 has index value 2, but index 2 has already filled with key 2.So to place key 12, the index value will be:
Now key 22 has index value 2, but it has been already filled, so we will find their index values as:
***Double Hashing***
In double hashing, we check iteratively indexes of the hash value of K plus j into the hash value of 2K.
*Double Hashing = Hash1(K) + j Hash 2(K)*
We have two hash functions in double hashing. In the above expression, ‘j’ is the iterative element starting at 0.
The values of both hash functions will be:
Now we will create a bucket array from 0 to 12 index value because the maximum range of N is 13. Now we will insert these hash values into the bucket array.
For adding key value 18:
*5 + (0\*3) = 5*
So 18 will go to the index value 5.
For key value 41:
*2+ (0\*1)=2*
Similarly for keys 22 and 44:
*9+ (0\*6) = 9*
*5+(0\*5) = 5*
Keys 22 will go to index value 9 but key 44 has index value 5 which is not empty. So now we will take:
*5+(1\*5) = 10*
So the index value for key 44 will be 10.
 | https://habr.com/ru/post/563664/ | null | null | 2,705 | 72.46 |
import tmp.pngThen click the window to take screenshot from, and it beeps twice when the file is ready. You can also select a region from screen by pressing the button somewhere and dragging the cursor to mark the corners of the region. If you use KDE, there is a program which comes with most KDE installs called KSnapshot. It can take images from any window or area, take images on a timer, and remove window decorations automatically. Simply open it, and have it take a snapshot of the active window with the remove decorations box checked. The Gimp can also take screenshots (File -> Create -> Screenshot). Select "take screenshot of a single window" and uncheck "include window decoration". If your snapshots contains menubars and other irrelevant things, use an image manipulation program such as The GIMP to remove them. Note that the programs mentioned in this chapter can be used in Windows too.
./nameofscript.sh screenshot.png 100where:
#!/bin/bash name=${1%.*} cp $name.png $name-best.png optipng $name-best.png for ((i=1; i<=$2; i++)) do pngout -r -y $name.png $name-trial.png DeflOpt $name-trial.png du --bytes $name-best.png $name-trial.png | sort -n | awk 'BEGIN {ORS=" "} {print $2}' | xargs cp doneNote that PNGOUT can read BMP files directly. You don't need to convert them first. Also note that in some cases PNGOUT produces PNG files that don't work on all platforms (due to broken zlib implementations on those platforms); this is rare in practice. | http://tasvideos.org/Screenshots.html | CC-MAIN-2018-34 | refinedweb | 254 | 65.32 |
CookieException Class
The exception that is thrown when an error is made adding a Cookie to a CookieContainer.
Assembly: System (in System.dll)
System.Exception
System.SystemException
System.FormatException
System.Net.CookieException
This exception is thrown if an attempt is made to Add a Cookie with length greater than MaxCookieSize to a CookieContainer.
Associated Tips
- Make sure the cookie size does not exceed the maximum allowed by the cookie container.
This exception is thrown when an attempt is made to add a Cookie with length greater than MaxCookieSize to a CookieContainer. The default maximum cookie size is 4096 bytes.
- When setting the Name property for a cookie, make sure the value is not a null reference or empty string.
The Name property must be initialized before using an instance of the Cookie class. The following characters are reserved and cannot be used for this attribute value: equal sign, semicolon, comma, new line (\n), carriage return (\r), tab (\t). The dollar sign ($) character cannot be the first character.
- When setting the Port property for a cookie, make sure the value is valid and enclosed in double quotes.
The Port attribute restricts the ports to which a cookie may be sent. The default value means no restriction. Setting the property to an empty string ("") restricts the port to the one used in the HTTP response. Otherwise the value must be a string in quotation marks that contains port values delineated with commas.
- When setting the Value property for a cookie, make sure the value is not null.
The following characters are reserved and cannot be used for this property: semicolon, comma.. | https://msdn.microsoft.com/en-US/library/system.net.cookieexception(v=vs.110).aspx | CC-MAIN-2016-30 | refinedweb | 269 | 55.74 |
Secure ASP.NET
When You re Not Yourself, Impersonate!
By Don Kiely
I recently completed courseware for AppDev that focuses on some advanced features of the .NET Framework 2.0. Several of the course sections I wrote deal with security; along the way I had to take a good look at impersonation. Because impersonation is frequently the subject of questions on the ASP.NET support forums at (of which I m a moderator), I thought this would be good fodder for a security column. I ve derived the material here from the AppDev course I wrote.
One of the most powerful things you can do with Windows identity objects in .NET is to impersonate another user for a short time. While the impersonation is in effect, the code executes with the security context of the impersonated user instead of the currently logged-in user. If it creates a file, the impersonated user owns the file. If the logged-in user has access to a SQL Server database, but the impersonated user doesn t, any attempt to connect to the database will throw a security exception.
By default, ASP.NET Web applications run under a special Windows account: MACHINE\NETWORK SERVICES in Windows Server 2003 and later and MACHINE\ASPNET in earlier versions of Windows. You can set up an ASP.NET application to be able to impersonate the actual user and perform actions with that user s security context.
Many of the examples of ASP.NET impersonation you find, particularly on MSDN, are quite complicated. This seems to have led many people to think that it is a complex operation. Although it is certainly an advanced technique, it isn t hard to do and the code is fairly simple. The sample application I discuss here starts running as the default ASP.NET process identity, then impersonates the current logged-in user. While impersonating the user, it creates a text file in the impersonated user s My Documents directory. Then the code will revert to the ASP.NET process identity. Along the way, it prints messages to the Web page about which identity is currently in effect. Below are the contents of the page when the sample runs (RIVERCHASER is the machine, of course).
Impersonation Sample
Current identity: RIVERCHASER\ASPNET
Impersonating RIVERCHASER\donkiely
Current identity: RIVERCHASER\ASPNET
To make this work, you must do a little setup once you ve created the ASP.NET project. First, create an IIS virtual directory that points to the directory containing the ASP.NET application. Impersonation won t work using the Cassini Web server that Visual Studio normally runs when you debug a Web site. The entire application runs with the logged in user s security credentials rather than that of either NETWORK SERVICES or ASPNET. This makes sense, because IIS is not involved when you use Cassini.
Next, change the authentication method for the virtual directory to Integrated Windows authentication only. By default, new virtual directories use both Windows and anonymous access. In the directory s property page s Directory Security tab, click the Edit button in the Anonymous access and authentication control section. Uncheck the anonymous option and leave the Windows Integrated authentication option checked.
Once you have the virtual directory set up, it s time to code. Create an ASP.NET application. Here I m using VB, but you can easily translate it to C#. Put all the code in the page s Load event procedure. You ll also need to import the System.IO and System.Security.Principal namespaces. After writing a page title, the code uses the shared GetCurrent method of the WindowsIdentity class to print the name of the current user under which the code is running. This will be the ASP.NET process identity:
Response.Output.Write("<h1>Impersonation Sample</h1>")
Response.Output.Write("<h4>Current identity: {0}</h4>", _
WindowsIdentity.GetCurrent.Name)
Next, the code gets a reference to the current Windows principal. This is the user who is running the application, the impersonated user, switching the security context from the ASP.NET process account. The Page class in ASP.NET has a User property that returns an IPrincipal object directly so you don t have to use .NET Framework classes. The code then uses the Identity property to get the associated WindowsIdentity object, casting the IIdentity object returned from the Identity property to a WindowsIdentity object. It also instantiates a WindowsImpersonationContext object that we ll use later to revert the impersonation:
Dim prin As IPrincipal = Me.User
Dim iden As WindowsIdentity = _
DirectCast(prin.Identity, WindowsIdentity)
Dim wic As WindowsImpersonationContext = Nothing
The code below calls the identity s Impersonate method, which kicks in the impersonation. It returns a WindowsImpersonationContext object used later to undo the impersonation:
wic = iden.Impersonate
Now the code in the page is running with the impersonated user s security context. It once again writes the user s name, which is no longer the ASP.NET process context. While still impersonating the user, it creates a text file in the user s My Documents directory:
Response.Output.Write("<h4>Impersonating {0}</h4>", _
WindowsIdentity.GetCurrent.Name)
Dim path As String = _
Environment.GetFolderPath( _
Environment.SpecialFolder.MyDocuments) & "\text.txt"
File.WriteAllText(path, "Hello from " _
& WindowsIdentity.GetCurrent.Name)
In the Finally block the code calls the WindowsImpersonationContext s sole custom method, Undo. This reverts the security context of the application to the ASP.NET process account. It once again writes out the current user s name to prove that the security context is once again that of the ASP.NET process account:
Finally
wic.Undo()
End Try
Response.Output.Write("<h4>Current identity: {0}</h4>", _
WindowsIdentity.GetCurrent.Name)
For fun, go ahead and run the application in Visual Studio, which uses Cassini by default. You ll find that you as the logged in user are displayed as both the current identity and the impersonated user. What a concept, impersonating yourself! Then try it for real. Use your favorite Web browser it doesn t have to be Internet Explorer, as long as it is a recent version of the browser and enter this URL:
You should see the page as shown above.
Now check the file that the page created while impersonating you. In Windows Explorer navigate to your My Documents directory and look for the text.txt file. Open it in Notepad or another text editor to see the content, which, when I ran it is:
Hello from RIVERCHASER\donkiely
But there s more to this than just some content. To prove that donkiely actually created and owns the file, open Windows Explorer. Right-click the file and select Properties from the pop-up menu. Select the Security tab and click the Advanced button in the lower right of the dialog box. This opens the Advanced Security Settings dialog box. Select the Owner tab and see that the impersonated user owns the file, rather than the ASP.NET process account (which wouldn t be able to write to my My Documents directory, anyway).
Impersonation is a powerful technique! You won t want to use it often because it is fraught with potential security risk, allowing a Web application to do things on a server as a user that is presumably more powerful than the ASP.NET process account. But when you need it, it can add some nice capabilities to your:do[email protected] and read his blog at. | https://www.itprotoday.com/development-techniques-and-management/when-you-re-not-yourself-impersonate | CC-MAIN-2018-43 | refinedweb | 1,237 | 50.02 |
28 October 2010 12:51 [Source: ICIS news]
LONDON (ICIS)--Dow Chemical reported robust underlying growth in the third quarter driven by stronger prices and performance products growth, but a net profit for the period down 25.3% at $597m (€436m), it said on Thursday.
The prior year quarter’s net result included gains from the sale of Netherlands refiner TRN and the Optimal business in Malaysia.
Dow said that net income from “continuing operations excluding certain items” was $705m from $357m in the 2009 third quarter.
“Dow’s transformed portfolio delivered accelerated earnings growth this quarter, resulting in a two-fold increase over last year,” said CEO Andrew Liveris.
“Continued solid demand recovery in North America and ?xml:namespace>
"Our operating rates reached levels not seen since the first quarter of 2008, reflecting both broad-based demand growth and a return to our signature operational excellence capabilities,” he added.
Dow’s third quarter sales were up 6.8% as reported at $12.9bn but were 23% higher excluding the impact of divestments.
Sales volumes were 14% higher with gains in all geographies and all operating segments, Dow said.
The largest volume increases were in Europe, the Middle East, Africa and
Volumes and profits were up strongly in the performance products segment, which includes businesses bought from the speciality materials maker Rohm and Haas.
Dow’s performance Systems businesses also reported strongly higher earnings before interest, tax, deprecation and amortisation.
Sales prices were up 9% with increases for basic chemicals and basic plastics buoying those businesses.
Dow’s global operating rate was up 8 percentage points year on year and 6% sequentially at 86%, the highest operating rate since the first quarter of 2008.
Liveris said Dow was confident in a sustained global economic recovery. “Our view is that robust growth in emerging economies will continue as domestic demand in faster growing geographies such as Brazil, Asia, Middle East and eastern Europe is further strengthening in a number of leading end-markets, including amongst others infrastructure, transportation, and packaging," he said.
“We are also encouraged to see signs of improved growth in North America and Europe, especially
Liveris added: "We expect growth in the developed world will be at a slightly lower rate than experienced in the first half of the year – importantly, it is growth, nonetheless."
Dow’s earnings were at the top end of financial analysts estimates at $0.45 for the period.
For more on Dow Chemical | http://www.icis.com/Articles/2010/10/28/9405560/us-dow-q3-net-profit-down-25.3-amid-strong-underlying-growth.html | CC-MAIN-2014-52 | refinedweb | 410 | 52.39 |
I have a Swift project, and I successfully added some Objective C class files let say ObjectiveClass.h, into this Swift project and able to use it in the project, using bridging header. Now in the ObjectiveClass.h class, I want to import a Swift class of the Swift project. How can I do this?
I've searched a lot but not found any answers for this yet. Most answered questions are about how to import Objective-C class into Swift project, or import Swift class into Objective-C project. But my case is different
Very Simple. Just declare
@objc public before the swift class. Like this
@objc public class YourSwiftClass : NSObject { }
Now in the objective c class use
#import "YourProjectName-Swift.h". You will get error that the mentioned file was not found. Don't worry, just run the project once. When you click on the file at runtime you will see the contents of "YourProjectName-Swift.h" . Now you can access any methods of the swift class. | https://codedump.io/share/YHLomwA2mtIg/1/ios-swift-project-already-imported-objective-c-file-and-i-want-to-import-a-swift-class-into-this-objective-c | CC-MAIN-2017-17 | refinedweb | 169 | 85.28 |
NiftyWarp
NiftyWarp
NiftyWarp
A warp/home plugin that allows for private, listed, and unlisted warps.
NiftyWarp was written because I wanted to create and manage warps in a way that was easy, but that didn't end up in a giant, cluttered-up list for everyone on the server. However, I didn't want to simply create personal warp lists only because I wanted the make sure it was easy for people to be able to share access to their warps if they so chose.
Download JAR | Source Code
Features
- Warp Types
- Create "listed" warps that are visible and useable by anyone.
- Create "unlisted" warps that are invisible to others, but still useable by anyone.
- Create "private" warps that are invisible to others, and only useable by you.
- Change warp type for easy sharing with others.
- Simple home warp creation and usage (e.g. /home, /sethome)
- Cross-World Warping
- Clearly see which warps are yours and which ones belong to others
- Configurable default type
- Permissions support (and three non-permissions-plugin options as well)
Dependencies:
PermissionsBukkit (Optional) - tested with 1.3
Installation
- Download latest JAR from this page.
- Stop your server.
- Delete previous NiftyWarp .JAR file from your Bukkit server plugins folder.
- Copy your newly downloaded NiftyWarp .JAR file to your Bukkit server plugins folder.
- Restart your server.
Please note this procedure doesn't include configuring permissions for this plugin
Please see the guides below for more information
Commands
/addwarp <warpName>
Adds a warp at your current location and takes into account your direction
- Command: /nwadd
- Aliases: /nwa, /addwarp, /createwarp, /setwarp
/deletewarp <warpName>
Deletes a warp
- Command: /nwdelete
- Aliases: /nwd, /deletewarp, /removewarp
/sethome
Set your home warp (currently just makes a warp named "home")
- Command: /nwhomeset
- Aliases: /nwhs, /homeset, /sethome
Warp to your home (currently just warps to your "home" warp)
- Command: /nwhome
- Aliases: /nwh, /home
/listwarps <worldName> <private | unlisted | listed>
Gets the list of warps. You can use asterisk for world to get all worlds if specifying type.
- Command: /nwlist
- Aliases: /nwl, /listwarps
/renamewarp <warpName> <newWarpName>
Renames an existing warp
- Command: /nwrename
- Aliases: /nwr, /renamewarp
/setwarptype <warpName> private | unlisted | listed
Sets the privacy/visibility of a warp after creation
- Command: /nwset
- Aliases: /nws, /settype, /setwarptype
/warp <warpName>
Use a warp
- Command: /nwwarp
- Aliases: /nw, /nww, /warp
/warptocoord <x> <y> <z> [worldName]
Warps to a specific coordinate. World name is optional, uses current world by default
- Command: /nwwarptocoord
- Aliases: /nwwtc, /nww2c, warptocoord, warp2coord, wtc, w2c
In order to be able to function alongside other warp plugins, all of the main commands are unique to NiftyWarp and prefixed with "nw". However, for ease of use, I've also included quite a few common and intuitive aliases. Please see the for more info.
Permissions Plugin Nodes
User: These permissions are for managing and using your own warps.
- niftywarp.use.add
- niftywarp.use.delete
- niftywarp.use.home
- niftywarp.use.homeset
- niftywarp.use.list
- niftywarp.use.rename
- niftywarp.use.set
- niftywarp.use.warp
- niftywarp.use.warptocoord
- niftywarp.use.version
Admin: These permissions will allow you to delete/rename/set other people's warps.
- niftywarp.admin.delete
- niftywarp.admin.rename
- niftywarp.admin.set
PermissionsBukkit notes:
For "easy" setup when using PermissionsBukkit, see the Example PermissionsBukkit page.
Non-Permissions-Plugin Rulesets
Regardless of whether or not you have the PermissionsBukkit plugin installed, you can configure NiftyWarp to use that plugin or to not use it. If you set use-plugin to false, you can use the following alternative permission options:
- ops-only - means only Ops can use this plugin's commands.
- ops-for-admin - means only Ops can use the admin type functionality (such as renaming other people's warps).
- ffa - or Free For All ... means anyone can use any commands/functionality
Upcoming Features
Planned:
- Configurable Safety
- Safely placing you when the warp loc is inside a block
- Safely placing you when warp loc is now over lava
- Safely placing you when warp loc would cause you to fall to your death
- Configurable namespace
- More /listwarps options
- /spawn command and /setspawn command
- Admin:
- See all warps by type (private/unlisted/listed)
- List a specific person's warps (including private)
- (and a few more ideas I have)
- Warp Import/Export routines
- iConomy Support
- MySQL Support
Likely:
- Warp sharing (e.g. /sendwarp)
- Warp copying (e.g. /copywarp)
- Help command (e.g. /nwhelp)
Changelog
Version 1.3.3 (March 15 2012)
- Fixed blank configuration file on first load up -> It will now generate a well documented default YML file.
- Fixed a bug where /sethome was not working as expected.
- Cleaned up some code
Version 1.3.2 (March 11 2012)
- Supports latest 1.2 based Craftbukkit (CB 2060)!
Version 1.3.1
- Supports latest 1.8.1 build RB (CB 1185)
- Properly support PermissionsBukkit. You will need to remove any niftywarp-related permissions from your permissions.yml file.
- Added a version command (/nwversion or /nwv)
- Added a fix for an OptimisticLockException that happens intermittently in some environments
Version 1.3
- Updated to 1.8.1 server support (last tested with build 1145)
- Small update to German translation
- Updated to support PermissionsBukkit
- Removed support for nijikokun's Permissions plugin
- NiftyWarp still supports no-permissions-plugin alternatives
Version 1.2
- Updated to 1.7.3 server support (build 1000)
- Added ability to warp to a coordinate (x,y,z,world)
- Added a "maximum warps" per user config option. Defaults to 20
- Added destination chunk loading before warping
- Added filters to the ListWarps command (world and/or type)
- Added basic internationalization for in-game messages. Currently, German is supported. Will add more on request
Version 1.1
- Updated to 1.7.2 server support (build 953)
- Simple home warp creation and usage (e.g. /home, /sethome)
- Permissions overhaul
- Permissions 2.x support
- Better Permissions 3.x support
- Three new non-Permissions-plugin based options
This plugin looks great! Does it still work with recent minecraft versions? Can anyone suggest a similar warp plugin?
Bit old but, nope prefer single functional addons, the multifunctional always try to do to much and just get in the way. Plus its easier to replace a single plugin then suddenly have to find replacements for an all in one. Never liked all in one devices either for that matter. :) Will keep running this while it fullfills my needs :)
@ohjays
Why do you want to use HomeSpawnPlus anyway? That's what I don't get. Wouldn't you rather have everything warp-related in one plugin? myUltraWarps can handle /home and /spawn just fine, so why don't you use myUltraWarps instead? All the data is in an easily modifiable and readable .txt file; you get nice messages welcoming you home instead of something boring and stupid like "Teleported home." that most plugins will give you (I don't remember what NiftyWarp or HomeSpawnPlus says); you can set the spawn points for all your worlds, not just the Overworld (which is also good if you use a MultiWorld or MultiVerse plugin); and you can customize the spawn messages any way you want for each of your worlds (again, very useful if you have more than three worlds or some special mod worlds). I don't know much about HomeSpawnPlus other than it handles /home and /spawn, and it may very well do those two things very well, but I really think you would be much happier with myUltraWarps than you would be hanging on to that little redundant plugin.
Unfortunately myultrawarps does not play nice with homespawnplus for some reason, overriding its home/spawn handling so ill stick for this till i find a warp that just does warps :)
Okay, guys, here's the deal: NiftyWarp hasn't been updated in months. The owner hasn't even left a comment on this feed for a very long time. This plugin is dead. It could be revived, but I personally doubt it. However, do not fear. I have a new warping plugin that I think you will all love. It has way more features than NiftyWarp and is far more efficient in its programming. MarioG1 already mentioned it two comments below, but I wanted to give more detail and to make a little correction: this plugin doesn't have the same features as NiftyWarp; it has the same features plus many, many more.
You can warp not only using commands, but also using signs or even buttons, levers, or pressure plates! It includes the warping commands /top and /jump invented by Essentials. It has /back and /forward commands that work just like your Internet browser, but for warps! Ever teleported away from an amazing cave because you were being attacked by cave spiders and then you couldn't find the cave again? That won't happen anymore. Just use /back. You can teleport to other players, too, with /to and you can even set it up so that either players can teleport to each other freely or they have to send a teleportation request to the player they want to teleport to, allowing you to keep your secret base's location a secret or just keep annoying people from teleporting to you all the time.
Best of all, this plugin is active and it's gonna stay that way. I'm constantly adding new never-before-imagined features, fixing bugs I find, and making the plugin better with every release. Every time I hear a CraftBukkit update is coming, I make sure that my plugin (soon to be "plugins") is one of the first plugins on the entire Bukkit website to be updated. I even keep an updated source code for the plugin on GitHub so if you want to change any pieces of the code or you just can't wait for Bukkit to approve the new version, you can go ahead and go on GitHub and get the source code early.
The plugin is called myUltraWarps and I truly think you will all love it. Have fun ultra-warping!
REALDrummer
myUltraWarps Bukkit plugin author
Unfortunately that plugin add a lot of extras ie home that stuff up my home plugin and spawn as well i believe
I found another warp plugin with the same features as nifty warp.
But the other plugin has an big advantage: It is still in development!!!
how do u use signs to warp [warp] spawn
Is this still being developed ?. Just found this and it looks like what ive been searching for independent warps for all no problem with identical warp names, public warps
thanks
Been setting up warps and i find "/delwarp otheruser.hiswarp" won't work even though i can created it and its showing ? i can create for the other user just not delete, tells me "Error: That warp does not exist" but it does ?
thanks for this ! great plugin
is there anyway you could set it for other people ??
this would be so helpfull thank you
Somehow people are loosing all their private warps when changing their color with ColorMe. Can you please fix this?
I almost forgot to say: cool plugin!
@MarioG1
It would be so awesome if you could implement a setting to let /listwarps display only the warps the player itself has made.
@efstajas
Yes it seems so. :(
It think i start learning java this year, I am quit good in C+ +, php and html and I hope I can fix the bugs sometime but I think this would take some time until i am good enough in java to write an bukkit plugins. :)
@MarioG1
Hmmh, okay. I don't use MySQL with this plugin so I don't know. I really hope the developer will come back again and fix all these bugs. :( I was shure I finally found a great plugin, and right now it seems like we won't get support for it anymore.
@efstajas
I know, but i have to use an MySQL server to store the warp data (an other plugin requires an MySQL server in the bukkit config).
Setwarp, nwl and warp are working fine but delete, rename and setwarptype aren't working :(.
@MarioG1
Everything works perfectly for me.
The problem with this plugin is that is ins't up to date and has some bugs.
deletwarp, renamewarp and setwarptype aren't working correctly at the moment.
Also, some warps on my server are only accessible by the one that created them ALTHOUGH they are listed. What's up with that?
@MarioG1
Doesn't work if all warps are listed.
I think its already implemented.
Try /nwl private. | https://dev.bukkit.org/projects/niftywarp/#c69 | CC-MAIN-2022-21 | refinedweb | 2,079 | 62.78 |
score:26
There are two issues with the code you've posted.
The first is that the JSX transformer is not transforming your code because the appropriate
type attribute is not present on the
script tag.
Change
<script> var Hello = React.createClass({ ...
to
<script type="text/jsx"> var Hello = React.createClass({ ...
Secondly, you're calling
document.getElementById('container') before that
div actually exists on the page; move that final
script tag and its contents to after the
div (e.g., to the bottom of the
body).
You should end up with code that is similar to how it's shown in the tutorial:
<!-- index.html --> <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>Hello React</title> <script src=""></script> <script src=""></script> <script src=""></script> </head> <body> <div id="content"></div> <script type="text/jsx"> // Your code here </script> </body> </html>
score:0
I'm a newbie to react added to Website. I find the demo code in and the code in codepen is different.
I download the code from codepen. It's this: (It works)
render() { return ( React.createElement("form", { onSubmit: this.handleSubmit }, React.createElement("label", null, "Name:", React.createElement("input", { type: "text", value: this.state.value, onChange: this.handleChange })), React.createElement("input", { type: "submit", value: "Submit" })) ); } } ReactDOM.render( React.createElement(NameForm, null), document.getElementById('root'));
And the code in official site is this: (It doesn't work)
render() { return ( <form onSubmit={this.handleSubmit}> <label> Name: <input type="text" value={this.state.value} onChange={this.handleChange} /> </label> <input type="submit" value="Submit" /> </form> ); } } ReactDOM.render( <NameForm />, document.getElementById('root') );
I don't know why they are different, but I only know I should use methods instead of tags
score:0
There can be different reasons for this issue. One is already answered by @Michelle Tilley on top
Make sure you have checked and tried above the first solution.
So let me explain what was the reason in my case.
I missed using
%PUBLIC_URL% in my
index.html file and that was the reason I was facing this issue.
index.html
let say you have imported the files for layout and Js like used below.
<script src="/vendor/jquery/dist/jquery.min.js"></script>
this will create error such as
SyntaxError: expected expression, got '<' jquery.min.js:1 SyntaxError: expected expression, got '<' bootstrap.bundle.min.js:1 SyntaxError: expected expression, got '<' js.cookie.js:1
to solve this issue. you need to import files properly by using
%PUBLIC_URL% e.g
<script src="%PUBLIC_URL%/vendor/jquery/dist/jquery.min.js"></script> <script src="%PUBLIC_URL%/vendor/js/bootstrap.bundle.min.js"></script>
Hope this will help others. Cheers
score:1
This is an old thread, but I ran into this error recently when I did an npm run build on my React app and just copied it over from a Windows box to a Linux Box using WinSCP. I am using nginx to serve the app on the Linux box. Turns out my problem was that there was not execute permissions on the JS files in the static directory. This caused an error and just served my index.html instead of the js file, hence the SyntaxError: expected expression, got '<'. Hopefully this will help someone who stumbles onto this thread in the future.
Just run
chmod -R 755 static from the app's directory
score:1
Narsters's answer worked for me, but I had to add this line to my package.json
score:1
i had same problem and the problem was
npm init
after i ran this it asks some kind of questions and fills data into
package.json and changes
homepage and other stuff i just opened package.json and removed all that lines which is created by npm at the end of file like
description,homepage,author
score:1
I was also facing the same error when using react via cdn in my html file and i stumbled upon this post which looks quite similar to my problem.
The problem with my code was that the js was unable to understand jsx code used by me in my components render method.
Here is how i got it fixed. other than react i added another cdn for babel-standalone like this
<script src=""></script>
along with changing
type="text/javascript" to
type="text/babel" on script tag wrapping my js code.
<script type="text/babel">/* my react code containing jsx */</script>
Posting this answer in hope it might help someone facing the same issue.
Source: stackoverflow.com
Related Query
- Syntax Error "Expecting expression, got '<'" while trying to run reactjs tutorial
- Mysterious error in render() while trying to run React tutorial code
- Webpack Error when trying to run reactJS app (w. typescript)
- Getting an error while trying to access nested objects in Reactjs
- Got an Unhandeled Error at run time while checking state of user
- Syntax error "Unexpected token" while following React + Node.js blog tutorial
- Example "server.php" from ReactJS tutorial has syntax error
- I got this errors while trying to create css modules using npm run eject
- Can't beat the "Actions must be plain objects. Use custom middleware for async actions." error while trying to follow redux.js.org tutorial
- Syntax Error While Trying to Do Ternary Operation inside Return
- getting error while trying to style elements by ID in ReactJS
- Getting an error message while trying to execute Router Component in ReactJS using Jest and Enzyme
- ReactJS giving error Uncaught TypeError: Super expression must either be null or a function, not undefined
- I am getting error in console "You need to enable JavaScript to run this app." reactjs
- got Can't resolve 'react/jsx-runtime' error while use try to create the shared component with storybook in react-typescript
- Why I got Error while Creating React App?
- Trying to deploy my React app with gh-pages but got this error message : The "file" argument must be of type string. Received type undefined
- Why is npm react-scripts producing a syntax error when I run `npm run start`?
- Error while trying to use the following icon from the Manifest
- I have this error that say "Cannot update a components while rendering a different component" when I run react.js code
- Gatsby error [HPM] Error occurred while trying to proxy request / from localhost:8000 to (ECONNREFUSED)
- Webpack 5 Receiving a Polyfill Error?!?! My JavaScript React project is receiving a polyfill error while trying to compile my webpack.config.js file
- React-native, Firebase network error while trying to log in
- `No "exports" main resolved ` error when trying to run Storybook
- Error while trying to access files in the app
- Error when trying to run a test file on React component
- ReferenceError: window is not defined. I got this error when I run npm test to unit testing by jest
- Getting an error that images is null while trying to show a preview of the uploaded images in react js
- Babel-Loader Syntax error on npm run build
- While trying to create pages in gatsby-node, I received this build error
More Query from same tag
- Jest & Enzyme - SyntaxError: Unexpected token import
- React native - dynamically add a view onPress
- React - Select multiple checkboxes holding Shift key
- Login Error: Error: A case reducer on a non-draftable value must not return undefined
- Files bigger than 16 kb gets corrupted when uploaded, using apollo and graphql
- How to clear input fields after submit in react
- Calling a function to change state in parent component from the child component in react
- Javascript onClick not firing when assigned inside of array.map
- react-google-maps MapWithAMarker fails to rerender when marker position changes
- How to get type of rootReducer?
- How can i set only value on react select
- Add row to existing table dynamically in ReactJS
- setState getting updated multiple times
- Child component inside .map function display all children instances
- Text disappears after reaching the required length
- Explanation needed: getting data from API with useEffect hook and get name
- react-router-dom v6 useNavigate passing value to another component
- How to configure both localStorage and sessionStorage in redux-persist?
- Map loop in JSX to generate dynamic table headers in React
- Trying to return all objects... stored in another main object in Javascript
- Why my hook state doesn´t update correctly?
- How to redirect html to dialer with call number *123#
- How to pass state to child component with function based React?
- How can I add/override Footer component in React material-table?
- ReactJS - Using .setState to change nested values
- react component - change child content on resize of the react element (when width gets to narrow) - not the window size via fixed breakpoints
- React Redux - mapDispatchToProps called for every event in a map function
- React can't read array in array?
- ReactJS Passing data to a rendered modal?
- Unable to find an element with the placeholder text "Search..." reactjs jest | https://www.appsloveworld.com/reactjs/100/12/syntax-error-expecting-expression-got-while-trying-to-run-reactjs-tutorial | CC-MAIN-2022-40 | refinedweb | 1,477 | 53.41 |
The help for the Vector Tile tools is wrong. This code from the help does not work. It keeps saying the value type for in_map is wrong.
Create Vector Tile Package—Data Management toolbox | ArcGIS for Desktop
p = arcpy.mp.ArcGISProject("c:\\temp\\myproject.aprx")
for m in p.listMaps():
print("Packaging" + m.name)
arcpy.CreateVectorTilePackage_management(m, m.name + '.vtpk', "INDEXED", 295828763.795777, 1128.497176)
It just has "Map" for the in_map when copied from the python snippet but that of course does not work in script. I have yet to find anything it likes. Any hints?
arcpy.management.CreateVectorTilePackage("Map", r"C:\Vector\Settings.vtpk", "ONLINE", None, "INDEXED", 295828763.795778, 564.248588, r"C:\Vector\SettingsIndex.shp", None, None)
The tool to create the vector index will also not accept in_map. Its help has a sample from some other tool??
Create Vector Tile Index—Data Management toolbox | ArcGIS for Desktop
The following Python window script demonstrates how to use the CreateVectorTileIndex tool in immediate mode.
import arcpy from arcpy
import env
env.workspace = "C:/data/cartography.gdb/transportation"
arcpy.CreateIndexTiles_cartography("CURRENT", "tiles", 10000)
Also when copying the snippet from Pro it has another parameter with the value ONLINE that does not exist in the help.
#arcpy.management.CreateVectorTileIndex("Map", r"C:\Vector\SettingsIndex.shp", "ONLINE", None, 10000)
Please let me know the correct params or point me to help files that are correct.
Thanks
Hi Doug,
I know it has been some time since you posted this but it looks like you are experiencing a bug that was recently logged.
BUG-000098329 - Create Vector Tile Package fails with "ERROR 000623: Invalid value type for parameter in_map" when run as a standalone script
The Create Vector Tile Package tool will run just fine in Pro and you should also be able to run it from the built in python window:
arcpy.env.workspace = "C:/TilePackageExample"
arcpy.CreateVectorTilePackage_management('Map', 'Example.vtpk', 'ONLINE')
The issue seems to occur when trying to run as a standalone script and it doesn't seem to recognize the input type. I hope this helps!
Colin | https://community.esri.com/thread/175464-help-on-vector-tile-tools-is-incorrect | CC-MAIN-2019-13 | refinedweb | 349 | 57.06 |
curl-library
Re: probs. building libcurl w/gssapi on win32
Date: Fri, 23 May 2008 13:49:42 -0400
Yang Tse wrote:
> Ok, you might have read my first mail. But didn't understand it or get the idea.
>.
>
> Get it now ?
>
> I'm unable of writing it more clearly. But I could use upercase if you
> want ;-))))))))
You're correct, I misread/misunderstood your email. I see now that
patching krb5.c too will fix the problem.
I'm not a C developer. But I'm trying to stretch myself a bit
technically here to help provide the project with a patch that fixes
this problem. It's inevitable that I'm going to make some coding
mistakes in the process. But some appreciation of the contribution I'm
trying to make - and a little less sarcastic comments - would be nice.
I realize that I might have gotten a bit snippy in an earlier email (for
which I apologized to Dan, and would like to apologize to you as well),
and perhaps that's contributed to the tone of your responses. All I can
say is that I got a bit frustrated at the conflicting directions on how
you devs wanted this patch done, and my emotion shone through. But
again, my apologies for that.
There's one other thing I want to respond to from your other email, and
then I'm going to let this drop:
"I just gave you an idea that you could also try as a different approach
to solve _YOUR_ problem for which you are being paid."
This is not _MY_ problem:
1) I haven't asked you or anyone to write a custom new feature for me -
or to integrate a new feature that I've written. The curl documentation
says that it already supports GSSAPI and SPNEGO (see:), but that support is broken. So I
am trying to write code to help fix something in the project that's
broken - yes, partly for my job, but also for the community as well.
It's certainly possible that nobody else needs this code working right
now except for me. But I'd think it's in everyone's interest to see to
it that curl doesn't have bugs in its advertised features, even if
they're minor ones.
2) My problem has already been solved. I already came up with a patch
that fixes these issues on our project, and it's been working fine.
What I'm doing now is trying to donate that patch back to the project
and the community so that everyone can benefit from this work. And I am
NOT being paid to do that. I'm spending time on it (at the expense of
other work!) solely because I feel it is the right thing to do. All
I've been asking for in return is a consensus on how the developers want
these bugs patched. Not an unreasonable request, IMO.
Let's move on ...
"Attached is the patch that I wrote to address this thread's problem.
Obviously it is against current repository version. It would be
interesting to know if it works ... I won't commit it to CVS unless 3
qualified positive votes are given."
Yes, it appears to work fine. Thanks much for taking the time to put
that together.
Not sure if you're only looking for votes from devs, but if you're open
to votes from the community at large, please count me as a positive vote.
Lastly, there's one final patch that I had to make to fix SPNEGO support
(attached). Any questions/comments on it, please let me know.
DR
Only in curl-7.18.2-CVS-work/lib: Debug
Only in curl-7.18.2-CVS-work/lib: Release
Only in curl-7.18.2-CVS-work/lib: curllib.ncb
Only in curl-7.18.2-CVS-work/lib: curllib.plg
diff -uarw -x '*.dsp' -x '*.vcproj' curl-7.18.2-CVS/lib/http_negotiate.c curl-7.18.2-CVS-work/lib/http_negotiate.c
--- curl-7.18.2-CVS/lib/http_negotiate.c 2008-04-14 11:22:46.000000000 -0400
+++ curl-7.18.2-CVS-work/lib/http_negotiate.c 2008-05-23 12:20:48.151112200 -0400
@@ -27,6 +27,11 @@
#define GSS_C_NT_HOSTBASED_SERVICE gss_nt_service_name
#endif
+#ifdef HAVE_SPNEGO
+#include <spnegohelp.h>
+#include <openssl/objects.h>
+#endif
+
#ifndef CURL_DISABLE_HTTP
/* -- WIN32 approved -- */
#include <stdio.h>
Received on 2008-05-23 | http://curl.haxx.se/mail/lib-2008-05/0258.html | CC-MAIN-2015-32 | refinedweb | 743 | 75.81 |
Terça-feira Mai 19, 2009
Terça-feira Abr 21, 2009
SOA: An Overview
By Joao Savio Ceregatti Longo on Abr 21, 2009
I. Motivation
Reuse systems
Standardization of communication between systems enabling integration
II. SOA
Definition: paradigm for the implementation and maintenance of business processes that are in large distributed systems. But we can also think of SOA as a layer that provides a higher level of abstraction based on the Object Oriented paradigm (OO). It has as keywords: interoperability, loose coupling and services.
Interoperability
Interoperability is achieved through an enterprise service bus (ESB) that we can see in the representation below:
The ESB would be the highest layer of abstraction that has several responsibilities, such as:
Provide connectivity
Transformation of data
Routing (smart)
Dealing with security
Dealing with reliability
Management services
Monitoring and logging
The idea is that all
systems are integrated through the enterprise service bus. For
example, if you have a system made in PHP, but your company currently
uses Java, it is not necessary to completely change the old, but
provide an integration of the them through an ESB for example.
Loose Coopling
In turn, loose coupling is related to the reduction of dependency of the system, minimizing the effects of changes and failures. We can illustrate this in the Object Oriented Programming with a class tight and one loose coupled:
public class classTightCoupling {
public String name;
public int age;
}
public class classLooseCoupling {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
In the first class, if you have an object, simply do nameOfObject.name = "something" to change the value of the variable. In the second class, the access to the variable "name" can only be done by the methods setName and getName. That is good! It may seem silly in these small examples, but imagine if you have an giant API that has rules to change the values of its variables. If this API was tightly coupled, there would be a great dependence between her classes and those that you were using, because anyone could modify the variables in any way and this could affect the outcome completely.
But, back to our world of SOA, we can use the loose coupling in various situations:
Asynchronous Communication - this means that the sender and recipient are not synchronized. This is good because the systems that are exchanging messages don't need to be online at the same time.
Iteration Patterns - only string are supported or other data types too? Structures? Arrays? Lists? Objects? Inheritance and polymorphism? Well, the more complex is the data type, the more your system is tighly coupled. For example, if you use objects to exchange messages, only the object oriented languages may participate in the integration.
Compensation - it's related with the security in the transaction. If you have to update two backends, how to deal with the problems if only an update was successful? Usually the commit is made of two stages, i.e., backends are updated at the same time. But, the more loose coupled and that ensures the overall consistency is change the backends separately. If only an update is successful, you can reverse it to the previous situation and send an error message, for example.
Control Logic Process - if you have a central controller, the failure of a component will stop all the process. Moreover, reducing the coupling, i.e., making a decentralized control, you eliminate this problem.
We only have mentioned advantages of loose coupling. But, there are also disadvantages, because the more a system is loose coupled, it is more complex. Therefore, it is up to you decide how much you're willing to pay for it.
Services
The third key word is "services" that can be defined as a piece of an independent corporative functionality. There are three types:
Basic Services - there are basic services of data and logic. For example: create a new user, change a user, returning the age of a registered person, say if a year is leap or not, etc. They belong to only one type of backend.
Composite Services - they are services that are composed of other services, and usually multiple backends. In SOA, composing new services from existing ones is called orchestration. As in an orchestra, you combine "instruments" to perform different tasks more complex than those possible with only one. These services are still considered without states and with rapid execution.
Process Services - these are called workflows. These services contain states and sometimes need to use multiple sessions. Using a shopping cart as an example, we have one for each client, i. e., a session service for each one. And we have many possible states, because the service has to save the order when the client is looking for more products, finalizing the purchase when the confirmation is made, wait for confirmation of payment and complete the order only when the product is delivered.
III. Conclusion
In this article, we set and talk about the basics of SOA, it is essential to understand Web Services and other types of modeling practices.
IV. References
About
Search
Recent Posts
- My Last Day as a Campus Ambassador
- OSUM Webinar - NetBeans 6.7: a única IDE que você precisa!
- Software Freedom Day was very good!
- Software Freedom Day in Rio Claro/SP - Brazil
- UNESP - Rio Claro/SP/Brazil reaches 100 OSUM members
- Web Services with NetBeans
- JSF Introduction Photos!
- Lecture in Asser - Rio Claro/SP
- SOA e-mail discussion group
- Photos Open Source lecture in UNESP - Rio Claro/SP | https://blogs.oracle.com/joaosavio/tags/soa | CC-MAIN-2014-15 | refinedweb | 923 | 53.81 |
A Web API is an online “application programming interface” that allows developers to interact with external services. These are the commands that the developer of the service has determined will be used to access certain features of their program. It is referred to as an interface because a good API should have commands that make it intuitive to interact with.
An example of this might be if we want to get information about a user from their social media account. That social media platform would likely have a web API for developers to use in order to request that data. Other commonly used APIs handle things like advertising (AdMob), machine learning (ML Kit), and cloud storage.
It’s easy to see how interacting with these types of services could extend the functionality of an app. In fact, the vast majority of successful apps on the Play Store will use at least one web API!
In this post, we’ll explore how to use a web API from within an Android app.
How a Web API works
Most APIs work using either XML or JSON. These languages allow us to send and retrieve large amounts of useful information in the form of objects.
XML is eXtensible Markup Language. If you are an Android developer, then you’re probably already familiar with XML from building your layouts and saving variables.
XML is easy to understand and generally places keys inside triangle brackets, followed by their values. It looks a bit like HTML:
<client> <name>Jeff</name> <age>32</age> </client>
JSON, on the other hand, stands for “Javascript Object Notation.” It is a short-hand for sending data online. Like XML or a CSV file, it can be used to send “value/attribute pairs.”
Here the syntax looks a little different, though:
[{client: {“name”:”Jeff”, “age”: 32}}]
These are “data objects” in that they are conceptual entities (people in this case) that can be described by key/value pairs. We use these in our Android apps by turning them into objects just as we normally would, with the use of classes.
See also: How to use classes in Java
To see this in action, we need to find a Web API that we can use readily. In this example, we will be using JSON Placeholder. This is a free REST API specifically for testing and prototyping, which is perfect for learning a new skill! REST is a particular architectural “style” that has become standard for communicating across networks. REST-compliant systems are referred to as “RESTful” and share certain characteristics. You don’t need to worry about that right now, however.
Setting up our project for Retrofit 2
For this example, we’ll also be using something called Retrofit 2. Retrofit 2 is an extremely useful HTTP client for Android that allows apps to connect to a Web API safely and with a lot less code on our part. This can then be used, for example, to show Tweets from Twitter, or to check the weather. It significantly reduces the amount of work we need to do to get that working.
See also: Consuming APIs: Getting started with Retrofit on Android
First up, we need to add internet permission to our Android Manifest file to make sure our app is allowed to go online. Here is what you need to include:
<uses-permission android:
We also need to add a dependency if we are going to get Retrofit 2 to work in our app. So in your module-level build.gradle file add:
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
We also need something called Gson:
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
Gson is what is going to convert the JSON data into a Java object for us (a process called deserialization). We could do this manually, but using tools like this makes life much easier!
There are actually later versions of Retrofit that make a few changes. If you want to be up-to-the-moment, check out the official website.
Converting JSON to Java object
A “Route” is a URL that represents an endpoint for the API. If we take a look at JSON Placeholder, you’ll see we have options such as “/posts” and “/comments?postId=1”. Chances are you will have seen URLs like this yourself while browsing the web!
Click on /posts and you’ll see a large amount of data in JSON format. This is a dummy text that mimics the way a page full of posts on social media looks. It is the information we want to get from our app and then display on the screen.
[{ "userId": 1, "id": 1, "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", "body": "quia et suscipitnsuscipit recusandae consequuntur expedita et cumnreprehenderit molestiae ut ut quas totamnnostrum rerum est autem sunt rem eveniet architecto" }, { "userId": 1, "id": 2, "title": "qui est esse", "body": "est rerum tempore vitaensequi sint nihil reprehenderit dolor beatae ea dolores nequenfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendisnqui aperiam non debitis possimus qui neque nisi nulla" }, { "userId": 1, "id": 3, "title": "ea molestias quasi exercitationem repellat qui ipsa sit aut", "body": "et iusto sed quo iurenvoluptatem occaecati omnis eligendi aut adnvoluptatem doloribus vel accusantium quis pariaturnmolestiae porro eius odio et labore et velit aut" }
To handle this information, we’re going to need a class that can build objects from the deserialized data. To that end, create a new class in your project and call it “PlaceholderPost”. This will need variables that correspond to the data we’re getting from the /posts page (“body”, “ID” etc.). We’ll be getting that information from the web API, so we need a getter for each of them.
The final class should look like this:
public class PlaceholderPost { private int userID; private int id; private String title; private String body; public int getUserId() { return userID; } public int getId() { return id; } public String getTitle() { return title; } public String getBody() { return body; } }
This could just as easily be users on Twitter, messages on Facebook, or information about the weather!
Interface files
Next, we need a new interface file. You create this the same way you create a class: by clicking on your package name in the project window and choosing “New > Class” but here you’re selecting “Interface” underneath where you enter the name. An interface file contains methods that are later implemented by a class. I’ve called mine “PlaceholderAPI”.
This interface needs just a single method to retrieve all the data from “/Post”. If you take a look at that JSON again, you’ll notice that the curly brackets are inside square brackets. This means that we have an array of objects, which is why we want to build a list for them. The objects are instances of our “PlaceholderPost” that we just made, so that’s what we’re putting in here!
For those that are very new to programming, remember that any red lines probably mean you haven’t imported a class. Just click on the highlighted statement and press alt+return to do this automatically.
(I can’t imagine anyone using this as an early programming lesson but you never know!)
This looks like so:
import java.util.List; import retrofit2.Call; import retrofit2.http.GET; public interface PlaceholderAPI { @GET("posts") Call<List> getPosts(); }
Displaying the content
Now, hop back into your main activity. We could build a fancy layout for displaying all this data, but to keep things nice and simple, I’m just going to stick with the layout as it is.
To use Retrofit, we’re going to need to create a new Retrofit object. We do this with the following lines of code:
Retrofit retrofit = new Retrofit.Builder() .baseUrl("") .build();
As you can see, we’re passing in the rest of the URL here. We then want to use our interface:
Call<List> call = placeholderAPI.getPosts();
Now we just need to call the method! Because things have been too easy so far, Android does throw a little spanner in the works by preventing you from doing this on the main thread. The reason, of course, is that if the process takes too long, it will end up freezing the app! This is true when using any Web API. It makes sense, but it’s not terribly convenient when we just want to make a tutorial. Fortunately, we don’t need to create a second thread ourselves as Retrofit actually does all that for us.
We’ll now get an onResponse and onFailure callback. onFailure is, of course, where we need to handle any errors.
onResponse does not mean that everything went smoothly, however. It simply means that there was a response; that the website exists. Should we get a 404 message, this would still be considered a “response.” Thus, we need to check again if the process went smoothly with isSuccessful(), which checks to see that the HTTP code is not an error.
To keep things really simple, I’m going to display just one piece of data from one of the objects we’ve received. To achieve this, I renamed the textView in the layout file to give it the id “text”. You can experiment with this yourself.
The full code looks like this:
call.enqueue(new Callback<List>() { @Override public void onResponse(Call<List> call, Response<List> response) { if (response.isSuccessful()) { List posts = response.body(); Log.d("Success", posts.get(3).getBody().toString()); TextView textView = findViewById(R.id.text); textView.setText(posts.get(3).getBody().toString()); } else { Log.d("Yo", "Boo!"); return; } } @Override public void onFailure(Call<List> call, Throwable t) { Log.d("Yo", "Errror!"); } }); Log.d("Yo","Hello!"); } }
Wrapping up
At this point, you should have a good idea of how a web API works and why you want one. You would have also created your first app that uses a web API to do something potentially useful.
Of course, there are countless other web APIs, and each work in their own ways. Some will require additional SDKs to use or different libraries. Likewise, there are many other actions beyond the “GET” request we demonstrated here. For example, you can use “POST” in order to send data to the server, which is useful if you ever want your users to be able to post to social media from your apps.
The possibilities are endless once you combine the power and flexibility of Android with the huge resources available online. | http://www.nochedepalabras.com/how-to-use-a-web-api-from-your-android-app.html | CC-MAIN-2020-40 | refinedweb | 1,748 | 62.68 |
Using notify (especially in Laravel) (v0.15.2)
- psychonetic last edited by
I am trying to use the new notify component in my laravel project.
But nothing works:
import {Notify} from “quasar-framework/dist/quasar.mat.esm”;
If I try to use it like described in the documentation: Notify.create(‘bla’) nothing happens. No notification and no errors.
Importing via import {Notify} from ‘quasar’ has never worked for any component (also before v0.15). I always needed to say from ‘quasar-framework’ or now in v0.15 'from “quasar-framework/dist/quasar.mat.esm”;
Any idea?
Importing via import {Notify} from ‘quasar’ has never worked for any component (also before v0.15). I always needed to say from ‘quasar-framework’ or now in v0.15 'from “quasar-framework/dist/quasar.mat.esm”;
Well, as someone pointed out here,
import { Notify } from 'quasarshould work:
Still, i’m trying to understand how quasar succeed to resolve the dependency. As well, on root of a quasar projet, a
.quasarfolder is created with a file called
entry.jsthere. As well, I don’t get how components are resolved from
quasardependency. Maybe @rstoenescu could explain us?
- benoitranque last edited by
make sure you add Notify in quasar.conf.js:
module.exports = function (ctx) { return { framework: { plugins: [ 'Notify' ] } } }
Then in any .vue file:
this.$q.notify('hello!')
@akaryatrh If you are interested in why
import * from quasarworks take a look here
When you run
quasar build, the Quasar CLI calls Webpack in order to bundle the files. In the versions before 0.15 the Webpack Config was explicitly written in the build folder. Since 0.15 the Webpack config is now provided by quasar-cli and merged with your changes during build.
What you see in the line posted above is a so called Webpack alias. This allows for shorthand notations which will then be resolved by Webpack. So every time Webpack encounters quasar in an import statement it is replaced by the path to the quasar source.
You can learn more about this feature here:
Thanks to being able to extend the Webpack config in quasar.config.js you can even write your own aliases. | https://forum.quasar-framework.org/topic/1882/using-notify-especially-in-laravel-v0-15-2 | CC-MAIN-2020-40 | refinedweb | 360 | 69.07 |
Let’s check how to make a countplot in Seaborn. I’ll load taxis built-in data to show you the countplot in detail.
The full seaborn.countplot consist of several parameters:
(*, x=None, y=None, hue=None, data=None,
order=None, hue_order=None, orient=None,
color=None, palette=None, saturation=0.75,
dodge=True, ax=None, **kwargs)
I will share my knowledge to explain to you you parameters of the countplot Seaborn method. It will help you to create a move advanced Seaborn countplot.
This is the completed code to create a counterplot in Python using the Seaborn module.
import seaborn as sns import matplotlib.pyplot as plt df = sns.load_dataset('taxis') sns.countplot(x='passengers', data=df) plt.show()
Countplot ratation
To flip the chart, just change the x argument to y.
sns.countplot(y='passengers', data=df)
You can also use a orient parameter and set “v” for a vertical alignment or “h” for a horizontal one.
Countplot hue
To increase the amount of data in the chart you may use the hue parameter. It is adding an additional sets of data to your counterplot graph. I decided to visualize payments with color of the taxi to check the relationship between them.
sns.countplot(x='payment', data=df, hue='color')
Countplot hue_order
The hue_order parameter gives you the possibility of changing the order of a hue. I used simply df[‘color’].value_counts().index[::-1] structure to change the order by index in the reverse order.
sns.countplot(x='payment', data=df, hue='color', hue_order = df['color'].value_counts().index[::-1])
Countplot order
To sort the data series use the order parameter. I picked df[‘passengers’].value_counts().index to sort counts.
sns.countplot(x='passengers', data=df, order=df['passengers'].value_counts().index)
Countplot ascending order
To sort the data series in ascending order, add the reverse indexing using index[::-1].
sns.countplot(x='passengers', data=df, order=df['passengers'].value_counts().index[::-1])
Countplot color
It is also possible to change the color of your python countplot. I set the color parameter to blue.
sns.countplot(x='passengers', data=df, color='blue')
Countplot palette
If one color is not enough for you or you want to make your chart look more attractive, use the palette parameter. I dediced to use the inferno.
sns.countplot(x='passengers', data=df, palette='inferno')
Countplot saturation
For those who care about details, you can also change the color saturation. The default is 0.75. Watch the saturation change as you lower it to 0.2.
sns.countplot(x='passengers', data=df, saturation=0.2)
Countplot dodge
To stack data in a countplot, use a dodge. By default, dodge is set to true. If you change this parameter to false, the count graph will change like this. The data has been accumulated.
sns.countplot(x='payment', data=df, hue='color', dodge=False)
These are all the parameters of the countplot method that I wanted to discuss for you. I hope you will improve your charting skills at Seaborn with this python course. | https://pythoneo.com/seaborn-countplot/ | CC-MAIN-2022-40 | refinedweb | 507 | 60.72 |
CoreJava Project
CoreJava Project Hi Sir,
I need a simple project(using core Java, Swings, JDBC) on core Java... If you have please send to my account
CoreJava
CoreJava Sir, What is the difference between pass by value and pass by reference. can u give an example
hi sir - Java Beginners
hi sir Hi,sir,i am try in netbeans for to develop the swings,plz provide details about the how to run a program in netbeans and details about... the details sir,
Thanks for ur coporation sir Hi Friend
corejava - Java Beginners
corejava pass by value semantics Example of pass by value semantics in Core Java. Hi friend,Java passes parameters to methods using pass by value semantics. That is, a copy of the value of each of the specified
sir - Java Beginners
ThanQ Hi Friend,
Try the following code
hi - SQL
hi hi sir,i want to create a database in oracle,not in my sql sir,plz tell me how to create a database. Hi Friend,
Try the following code:
import java.sql.*;
import oracle.sql.*;
import oracle.jdbc.driver.,create a new button and embed the datepicker code to that button sir,plzzzzzzzzzzzzzzzzzzzzzzzzzzz
Corejava Interview,Corejava questions,Corejava Interview Questions,Corejava
hi - Java Beginners
hi hi sir, i am using jtable to add the records to the database by using submit button ( i am using submit 4 add records 2 database sir) ,if i want... this problem sir,provide a solution 4 me sir,plz
Hi - IDE Questions
Hi Hi sir,i am using netbeans ide,if i am create a file in netbeans.........
Thank u,
sir,i want some information about mainframes,if u know plz provide the information sir,plzzzzzzzzzzzzz entering the 2 dates in the jtable,i want to difference between that dates,plz provide the suitable example sir
Hi Friend,
Please visit the following links: - Swing AWT
hi sir,how to set a title for jtable plz tell me sir Hi Friend,
Try the following code:
import java.awt.*;
import javax.swing.*;
public class SimpleTable extends JFrame {
public SimpleTable
hi - Java Beginners
hi hi sir,thanks for providing the datepicker program
but i want... in more times ,plz provide sir
Thanks in advance Hi... class when i am want,in that type of flexibility plz provide the program sir,in my
hi - Java Beginners
hi hi sir,i want a program for
when i am place the mouse cursor in textfield box then automatically 1 number is generated,again i am place...,
plz provide the solution sir Hi Friend,
Try the following code,Thanks for ur coporation,
i am save the 1 image... saved image based on the customer data previously),plz provide program sir... that image is rendered to my frame,that's my question Hi Friend
hi - Java Beginners
hi hi sir,when i am enter a one value in jtextfield the related... jtextfield automatically,how 2 resolve this sir,in my swings application.
plz provide ur phone no sir Hi Friend,
Try the following code:
import
hii sir
Hi,
Hi, Hi,what is the purpose of hash table
hi - Java Beginners
);
}
}
sir,plz see this and provide the answer sir,plzzzzzzzzzzzzzzzzzzzzzzzzzzzz,
i am declare the final for jtextfields
Hi
Ask Questions?
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions. | http://www.roseindia.net/tutorialhelp/comment/22290 | CC-MAIN-2013-20 | refinedweb | 578 | 52.83 |
Resize image script not working after update
- Gustaphzon
Hi.
I borrowed a script from macdrifter.com and changed it little. It worked perfect, but after the update to 1.4 it runs without errors but don't resize the image. It only saves a new image in the same size as the original. Here is the code
import Image import photos import console img = photos.pick_image() def customSize(img): w, h = img.size print 'w: ' + str(w) print 'h: '+ str(h) if w != 1000: wsize = 1000/float(w) print 'wsize: '+str(wsize) hsize = int(float(h)*float(wsize)) print 'hsize: ' + str(hsize) img = img.resize((1000, hsize), Image.ANTIALIAS) return img image = customSize(img) print image.size image.show() saveit = photos.save_image(img) print "\n\n Bilden sparad"
I'm a beginner and don't understand why this happens. Can someone please help me.
In the second last line, it should be
photos.save_image(image)instead of
photos.save_image(img). | https://forum.omz-software.com/topic/380/resize-image-script-not-working-after-update | CC-MAIN-2018-30 | refinedweb | 160 | 63.86 |
Tax
Have a Tax Question? Ask a Tax Expert
The gift from your dad is not taxable to you and you do not have to report it. Since your father gave you more than $13,000 in 1 year, he is required to file a gift tax return (Form 709) but he will not actually have to pay gift taxes as there is a credit available to offset the taxes ($1,000,000 lifetime exemption amount on excess gifts). If your father is married and his spouse agrees to gift splitting, then gift taxes may not be issue even though the forms are required to be filed. | http://www.justanswer.com/tax/29e1i-retirement-package-year-35-000-plus-unemployment.html | CC-MAIN-2017-17 | refinedweb | 107 | 78.93 |
Windows 2000 to provoke domain game 337
According to this article found on PC Week, Mircosoft Windows 2000 implements DDNS (Dynamic Domain Name System) in a way that makes it extremely difficult for administrators to integrate the operating system upgrade with Unix systems, which use the older, static DNS. I would like to ask if someone here could explain what is the difference between Static DNS and Dynamic DNS, and why it's not implement almost at all unices, including Linux. I smell a fight here between Unix Admins and NT/2000 Admins in some corporates. Am I wrong?
Re:Ironic (Score:1)
Re:dhcp - dns (Score:1)
It ain't illegal (Score:2)
Oh good grief (Score:1)
I've seen a few intelligent comments here, along with a whole slew of "Help me! Help me! Microsoft is out to get me, those evil dirty bastards!"
Sheesh. Assign your root DNS to your Unix machines, and delegate the Win2K DDNS to a subdomain. It's that simple...
They can coexist. How the hell do you think the internet works except for delegation of DNS duties to thousands of different machines and DNS implementations?
The Microsoft DNS implementation is compliant with BIND 8. It may or not allow dynamically allocated Unix machines, but it most certainly responds to DNS lookups from Unix machines, and it most certainly will use a Unix machine as an authorative DNS for a different domain. I'll bet it even implements some level of security to prevent a machine from overwriting the DNS record for a server... in fact I'm going to go experiment with this right now.
Sheesh, what a bunch of maroons. This is a non issue, the article was FUD, get over it.
Re:DDNS vs. Static DNS (Score:1)
What's this I hear?
YOU talking about SECURITY?
Haven't been paying attention to recent news, eh? Remember the 7-second crack? Used a trojan installed on an employee's NT box to fetch their password though they were connecting via SSH.
But no, a hacker can't do any harm an NT box. Riiiight.
An NT admin would be just as wise to apply patches as we are -- there's no less need. Except Microsoft distributes patches but rarely, so you CAN'T. Personally, I'd rather have the option to spend the time to be secure. You don't even have the choice.
Re:MSFT is full of soulless evil people (Score:1)
"While we will eventually support a standard, the IETF is having problems coming up with final draft."
Crap why do you lie? You know as well as I do that M$ has no intention of supporting the standard. You will give some lame excuse like you did with your HTML standard. Why can't you ship W2K which supports the current standards and then implement the new standards when they get approved. Read the haloween docs it is the stated intent of m$ to break standards.
RE JAVA.
It does not matter if Java is a language or platform you dolt!. You signed a contract and then violated it with malicious intent. M$ INTENDED to break java. m$ signed a contract they knew they were going to break. Read the DOJ transcripts, real the depositions before you go sprouting off on lame excuses.
M$ lies, m$ cheats, m$ steals. You my friend are an instrument of unethical people. Clean up your karma before it's too late.
Re:Corporate environment, infomercials (Score:1)
You can learn a lot from this guy. (Score:1)
Re:MSFT is full of soulless evil people (Score:1)
Re:Way to go, Microsoft! (Score:1)
Static vs. Dynamic IP. (Score:2)
---
Stephen L. Palmer
Just another BOFH.
True--better MetaIP than MS (Score:1)
Re: FUD request job for you programmers... (Score:1)
A document becomes an RFC by:
a) being written
b) being sent to the IETF
c) waiting in a 100-deep queue for some time
d) getting assigned a number
RFC-ness doesn't guarantee that it is official doctrine, only that "hey, here's the spec, get it at your local site."
There are stronger levels of IETF document for official blessings.
dynamic/static dns (Score:1)
Re:DDNS vs. Static DNS (Score:1)
Hopefully when a more complete linux dhcp client is working the problems will be solved.
Ironic (Score:1)
BTW, you probably want to change that before someone sues.
---
Put Hemos through English 101!
"An armed society is a polite society" -- Robert Heinlein
Re:How long to find security hole in DDNS (Score:1)
For the record, get it straight. MICROSOFT DID NOT INVENT DDNS! In my (not so) humble opinin, this is a great move! Finally we are getting rid of WINS (which was TRULY a Microsoft-only thing) and replacing it with a decent 'standard'.
Stop looking for reasons to berate Microsoft, especially when the lot of you haven't even tried to check on the facts. I have to be one of the few people here who knows what WINS was, and to realize that it deserved all of the negative feelings that DDNS is getting.
Get a life. Go read Linux-Advocacy-HOWTO. Stop being a bunch of conspiracy-driven punks.
Re:Ironic (Score:3)
Re:Security (Score:1)
Yes, this could be a risk. To address this risk, you are allowed to limit who you accept updates from (in both BIND and WIN2K DDNS).
A Win2K DHCP server can act as a proxy for its clients so that registration of both A and PTR records occurs via the DHCP server, NOT the DHCP client.
Most installations that I've seen only accept updates from the DHCP server, not the individual clients.
DDNS (Score:1)
dhcp - dns (Score:2)
DHCP Distribution: Version 3.0
Current Version: 3.0b1pl0
Version 3 of the ISC DHCP Distribution adds conditional behaviour, address pools with access control, and client classing. An interim implementation of dynamic DNS updates for the server only is included, but is not supported. The README file contains information about how to enable this - it is not compiled into the DHCP server by default.
Features in upcoming releases, starting with 3.1, will include the final asynchronous Dynamic DNS Support, DHCPv4 16-bit option codes, asynchronous DNS query resolution, DHCP Authentication, and support for a DHCP Interserver Protocol and live querying and update of the DHCP database. I don't see why they say it doesn't exist on UNIX. There are also perl scripts that do the job.
Politics of Name Spaces (& noncluefull reporter) (Score:3)
I'm working with DDNS both at home and at work using both Unix (Proprietary or Linux) and Win2K. They interoperate fine.
The only issues I've seen are with IXFR implementations (incremental zone transfers) and some "noise" data for some subzones. The workaround is that you can delegate the "noise" zones back over to a Win2K box until the BIND 8.2.1 code is fixed.
The REAL PROBLEM as documented in the story about Boe...oh, the "large aerospace firm" is that many large enterprises segment their IT structure along operating system lines rather than functional lines. It is much more efficient to LOSE operating system religion and use the "appropriate tool" for a job.
The DNS folks where I'm consulting use both Solaris and Win2K systems as nameservers. Solaris hosts the root namespace and the IP management tools. Win2K hosts the Active Directory Integrated delegated zones. The same folks in THE NETWORK GROUP (a functional split not an OS-centric split) manage all of these zones. There is no pissing contest over OS machismo. If more companies were to split their IT into functional areas, rather than OS empires, they might see a better result.
I'll get off my soapbox now. Just my two cents.
Re:Static vs. Dynamic IP. (Score:1)
Re:stay in sckool (Score:1)
Re:MSFT is full of soulless evil people (Score:1)
Now, please mark this as Off Topic, and let's get back to DDNS.
--Rae
sysadmins at "war"? (Score:1)
They've swallowed the FUD about DDNS in this article, ignored the fact that's it's substantially a technical non-issue, and now I have both of them in my office shouting at each other, both demanding control.
What do I do?
Yep. Sack 'em both, and get two (or one?) admins who are prepared to work on both systems and do what it takes to get the job done. The company will be a better place without weenies, OS bigots, or prima donnas.
Re:DDNS, what msn said (Score:2)
Beside the fact that I disagree with you, perhaps the reason that NT has less "security issues" is because the code is not open for such review.
If the code was at least open for REVIEW (not development), at least a lot of unresolved bugs that are going to pop up sooner or later, and take big hits with them. At least if the code is there for review, an admin could take steps to prevent something from getting exploited, even if it doesn't actually FIX the problem.
I'm a full advocate for open source, but when security is an issue, the more you can see the better.
-Erik-
changing the icon (Score:1)
or, at least I _think_ I got the old expression right
Re:Way to go, Microsoft! (Score:1)
Installations are permutable. Order matters.
Raelin
nPr vs nCr
Re:hahaha. (Score:1)
time_t st_ctime;
and further down
...
st_ctime Time when file status was last changed. Changed by
the following functions: chmod(), chown(),
creat(), link(2), mknod(), pipe(), unlink(2),
utime(), and write().
Yes, creating a hard link to a file, chowning it, or chmoding it will change its ctime. creation time my eye. Oh well slashdot doesn't respect pre tags anymore, deal with the formatting.
Re:DDNS vs. Static DNS (Score:1)
Nobody can set anything up these days on NT with the click of a mouse, you need MCSEs, service packs, hotfixes, HUGE NT manuals, etc.
I added 100 IP addresses to an NT box recently and it took more than one mouse click to do it.
Re:nt kernel is old too (Score:1)
Huh? NTs design is influenced by a number of things, including early versions of OS/2, VMS and Mach, but it really isn't any of those things, and it certainly isn't a monolithic kernel.
The POSIX API support you mention is separate from the OS core, so, for that matter, is the Win32 API.
Re:hmm.. (Score:1)
Re:nt kernel is old too (Score:1)
Yes, I agree. At my work I have a very nice oak desk. For fear of wrecking the wood, I use the NT4 CD as a coaster. It's very effective.
It's been working great for over 4 months. Who says NT is worthless.
Re:carnegie mellon u (Score:1)
1. They are keeping up with their students, and just keeping a record of what MAC addresses are whose, that way if you do anything illegal, they can say "It was this guy".
2. They are giving you a static IP (good thing) which is the way to go. That way, you get the benifits of DHCP, and the benifits of a static IP. So, is your IP the same all the time? Or does it change?
Re:Agreed (Score:1)
Let me be the FIRST to announce,..
"LAST POST!"
Ok,. now no one else make comments please...
Re:DHCP is lame, DDNS is lame (Score:1)
This is BIND 4 vs BIND 8, not NT vs Unix (Score:1)
Re:DHCP is lame, DDNS is lame (Score:1)
Re:Way to go, Microsoft! (Score:1)
Cool, Astroturf has reached Slashdot...
I don't know what experience you have on UNIX boxen, but I've used both UNIX workstations and NT workstations, and I can tell you you are full of shit. NT is a productivity destroyer, as the Windows interface just isn't designed to get work done. It may have been designed not to scare Joe Blow, with the dancing paperclips and the flying sheets of paper, but it certainly hasn't been designed to let people do what they want to do.
Hell, even the bloody Macintosh is better in that respect, because at least it has a good graphical interface. Windows is just an ugly, unholy mess built on top of an unstable kernel.
Re:dhcp - dns (Score:1)
Umm...most business users don't admin a server at all. I've had to download patches for everything I admin, from the NT boxes to the Linux boxes to the Cisco routers. The PHB's just want it to work, and usually don't care how you do it.
Leave the system admin to root, baby....
Re:hmm.. (Score:1)
I like Linux because of the plethora of modifications I can make to it, and the amount of customization I can make to the UI. I also really appreciate the online documentation, which is in a sane and easy to use format. Once I figured out how to use it, I fell in love.
So, what computing paradigm to you love? I probably haven't tried it, but if you would help me get it installed, I'll be happy to give it a try.
Re:Way to go, Microsoft! (Score:1)
Re:Way to go, Microsoft! (Score:1)
Re:Please, someone RTFM. (Score:1)
Re: pretty good (Score:1)
you know that is obviously false. i think his point was that microsoft is often associated with having fabulous amounts of money, perhaps more than people should be giving them. (oh god, i'm just setting myself up for an anti-trust debate, aren't i?)
>>Micros~1 - Hello... I've used win95/98/nt and I've *never* had to type in an 8.3 file name.
if you use any of your older 16-bit apps in windows, you will encounter these silly abbreviations (eg pictur~1.jpg) all the time. however, i usually run into these things in DOS, which turns long filenames into a nightmare, not a blessing.
>>I think linux geeks are just bitter about MS's dominance.
the complaints about ~1 filenames have nothing to do with MS's dominance. just because you've never had to struggle against its ugly side does not mean it's not a bad system. people complain because it sucks.
>> Macrostupid - Surely the people who were fooled into running these macros are to blame.
the people that passed on that virus are mostly newbies, and don't know how to wield the power of macros anyway! unfortunately, there are millions of newbies out there, and microsoft pushes their products into their hands more feverishly than any other demographic. if you don't believe me, i'm sure the talking paperclip can convince you otherwise.
>>I get 15+ days uptime all the time on my machine.
well cool, as long as we're sharing our experiences i might as well give mine! i've got win98 on a top of the line dell machine that i'm using right now. this whole summer it has not had an uptime of more than 5 days. hell, i don't even push this machine! i use it to browse slashdot and chat mostly. what causes it to crash after 5 days for no good reason? beats me. buggy coding i guess. oh sure, it made it to 8 days *once* but who wants to use a computer that has 194 meg of allocated memory with no apps running?
and this is windows *98*, supposedly fixing those truckloads of bugs. when i had win95 on a diff computer (that i sold, hehe) i couldn't even make it through the *day* without it crashing. usually crashed 3 times a day. are you telling me this is 'acceptable'?
Re:Wake up and quit babbling (Score:1)
There I was addressing the current roaming user, using a non-Microsoft platform. I have a problem
with DDNS in general, not just Microsoft's.
I don't think dynamic DNS solves the roaming
machine problem because of the TTL and security
issues. The problem it does help solve is plug-
and-play -- you can fire up 100 w2k boxes on a
network using a promiscuous DHCP server or even
the client-autoconfigured range and they will
all get registered in the DNS based on the
network settings on the *client* end. Just like
the Macintosh Chooser. How useful that is depends
on what you plan to do with the information and
how scalable it needs to be. In our environment,
out-of-band end-user access through a secure web
server is better.
To answer your question, as far as I've seen, the
w2k DDNS client does not do kerberos or any other
form of strong auth.
Internet Explorer does not and for the forseeable future will not do kerberos (according to the lead
NT5 security engineer when I was in Redmond). The
NT5/w2k version does some SID token-passing with
proprietary headers, not SASL. You can't really
fault MS for this, though, because there are no
standards for kerberos over http. CMU keeps trying
to get people to kerberise web applications, but
Stanford gave up and went s/ident and even MIT
makes x509 client certs for users rather than
force kerberos on an unwilling application.
File & print service does do kerberos and can be
configured to refuse to negotiate non-kerberised
connections if you know that all clients and all
servers on your network are guaranteed to be
running w2k. In the real world, I expect WINS and
legacy NT domains to last through 2010. We still
have 2 key production NT 3.51 servers because the
commercial off-the-shelf application they run is
not reliable under NT 4.0. There are more
architectural differences between NT4 and w2k than
between NT3 and NT4.
Re: FUD request job for you programmers... (Score:1)
> been updating the W2K code to follow the RFC.
> drafts.
Or vice versa.
Win2K dynamic DNS client is 100% BIND 8 compatible (Score:1)
requests with no authentication whatsoever.
If you do that, you deserve what you get.
Re:Way to go, Microsoft! (Score:1)
bugs. On my machine, installing VC 6.0 broke at
least 2 non-MS applications. Go take a look at
bug reports.
Man, I had to take care of a dozen NT boxes
loaded with development tools. I know more about ways to destroy this systems by a wrong sequence in applying patches, fixes and errata than I ever wanted. Our Linux boxes are order of magnitude easier to maintain. And I am no UNIX fan. I like goog GUI and IDE's. It just a fact that
UNIX style is much more stable for development use.
Original poster insisted that MS enviroment is stable. I think he is full of shit.
AcceleratedX rocks, BTW...
Possibly not needed... (Score:1)
Always the chance I could be wrong, of course.
Re:uhhh... no (Score:1)
I was talking about the concept of DDNS vs SDNS.
The concept behind DDNS is that a device should always have the same name but the IP can change.
The concept behind SDNS is that a device should always have the same IP but the name can change.
That is what I meant by bindings.
Re:Way to go, Microsoft! (Score:1)
Re:the article got it all wrong (Score:1)
Re:How useful really is DDNS or DHCP facing ipv6? (Score:1)
If you don't have any REAL subnets / LANs then you can tell the ridges that all conference rooms are really in all the vLANs of the organisations, and stuff will just magically work. I suspect the behind-the-scenes cost in data traffic is horrific, but I don't care
This also lets you grab a server, complete with UPS, and run over to another building with it, and hardly anyone notices
Or so I'm told (Do you read this stuff Tim?)
DDNS without security and stability is Evil (Score:2)
problem.
You say, "Its nice to be able to connect w/ a laptop anywhere on a 100+ subnet network and get the same domain name to resolve everytime."
Why?
How many people besides you regularly connect to
a server running on your laptop?
Are you sure you control the TTL on your DNS
server, every DNS server used by every client
that talks to you, and every server you talk to?
What do you do when a remote site's TCP wrappers
refuse access because they cached your old PTR
record?
What assurances do you have that someone can't
spoof your dynamic name and steal credentials? If
you think you're authenticated by MAC address,
try ifconfig eth0 hw de:ad:be:ef:01:23 (doesn't
work with all enet cards, but does with the common
ones). If you use kerberos, x509, or ssh host keys
and you actually bother to verify them, then you
have less of a problem, but many common services,
like unencrypted web pages, have no end-to-end
server verification protocol. Interestingly
enough, Microsoft's NT domain protocols do not
strongly authenticate the server to the client.
If an attacker puts himself at the server's IP
address and generates a nonrandom nonce, you lose.
Microsoft considered strongly authenticating
DDNS to be too hard (and nonexportable), so they
basically trust whatever you put in the Network
Control Panel (or a packet manufactured with
smblib) as long as the name has not already been
taken. Taken names can probably be freed up with
the same sort of games people play to take over
IRC channels. Bzzt! Game Over.
Microsoft says it plans to get rid of WINS, but
the initial implementation brings all the
instability and insecurity of WINS to DNS. No
thanks. The non-Microsoft solutions tend not to
be much better at this time.
Out-of-band authentication like MyIP or the old
ml.org web page works, but that ain't DDNS,
that's end-user access to static DNS... which
can be a good thing. We provide something similar
for our students.
In case deja URLs aren't permanent, search for "WINS" in comp.os.ms-wendows.networking.win95 during January 1996.
Re:Boys, be ambitious - (Score:1)
politics is politics...
posix is posix...
and personally i am not surprised that you feel
way and i am not surprised MS has taken another
step...it's just unfortunate..oh well...
Re:Blame the right people (Score:1)
Get real. You don't actually think that MS didn't approve of this article before PCWeek released it,do you?
You MS PR flacks are really quite stupid,you know.
Re:Oh Dear (censored by Atheist Commision) (Score:1)
ISC supports Windows better than Microsoft does (Score:1)
of w2k are totally unrelated.
The ISC DHCPD 3.1 feature referenced, and the
patches to 2.0 which have been around for over a
year, does this:
When a Windows 95/98/NT client, or a UNIX or any
other client configured to send option 12, is
assigned an IP address, the ISC DHCP server
connects to the DNS server on the client's
behalf to update its entry.
This allows you to secure your DNS server to
accept (possibly DNSSec'd) updates from your
DHCP server only.
The Microsoft DDNS solution does this:
After a Windows 2000 client has been assigned an
address by the DHCP server, it contacts the DNS
server directly to update its entry.
The Microsoft solution requires your DNS server to
accept updates directly from your clients. The
Microsoft solution does not attempt to support
Win95/98/NT clients at all. does so people... chooses their server platform, dare I say it, *ignorant* people...
Re:Khttpd is not in the kernel. We have uhttpd. (Score:1)
Its in 2.3.15
Paul Laufer
Re:Static vs. Dynamic IP. The scoop! (Score:4)
First, some background as to what Dynamic DNS truly is, because its obvious most of the slashdotters are posting without a clue. Here's a clue, and its free, as in free software
What is Dynamin DNS?
DynDNS is result of putting together several RFC documented techniques in a quite nifty way. Start with DNS [rfc1034 & 1035], add DHCP [1531, 1532, 1533, 1534] and tie the two together with Incremental Zone Transfers and Notify [rfc 1995 & 1996], and call it DynDNS [rfc 2136 & 2137].
Read rfcs 1995 & 1996 for a discussion on why full zone transfers [AXFR] are a bad thing (for bandwidth consumption), and see the elegant solution proposed with the incremental zone transfer [IXFR] extension. This is the basis for updating a primary name server with a new RR containing the hostname & IP pair (and IP->hostname reverse pair). You can also use this mechanism to remove a RR when the host is no longer associated with that address. There is also a discussion of security so that only pre-programmed IP addresses can do IXFRs, and allows extensions for fully authenticated updates when someone gets around to writing the code someday.
Read rfc 2132 to understand how a DHCP client does a DHCPREQUEST to a dhcp server, and how it can pass its hostname inside of option 61, client identifier. This is what win9x currently does with its client code, but only a patched version of some dhcp clients for linux do this.
Now, to put it all together.
A machine [win or linux] with a dhcp client boots up, broadcasts a bootp request (the transport mechanism for dhcp) with a DHCPDISCOVER message. A dhcp server on the network responds with its local address in a broadcast (because the client has no IP address at this point, all traffic must be broadcasts), and then the client broadcasts a DHCPREQUEST to that specific server. Contained in the REQUEST packet is option 61, containing the hostname of the machine. In win9x, this is what is entered in the network control panel "computer name" field, in *nix it the contents of
Then there is a whole bunch of communication between the dhcp server and client so they both agree on things (go read the rfcs, or sniff some packets off the wire, or both) with the end result the dhcp server now has given the client a lease on an IP address for a certain amount of time.
Now comes the DynDNS bit.
The dhcp server now communicates to the primary name server with an IXFR message, sending a RR containing an A record (and a PTR to the reverse DNS server) with the any and all information that might be contained in a RR, and the TTL is set to one half of the lease time given to the client. If the name and IP address are not currently in the DNS database, they are added. If they already exist, the IXFR message is refused, and the DHCP server must change the name to something unique. This is one mechanism to prevent overwriting your important servers addresses with bogus info.
What micros~1 is doing.
From what I can tell from some presentations I have seen, and playing with win2k beta, they have tied their DynDNS into ActiveDirectory as an attempt to shut out the *nix/OSS implementations until they get a foothold in the corporate door. I can't tell exactly what they are doing until I get a lab testbed set up and see if they interact correctly with BIND 8.2.1 or other rfc2136 compliant systems (someone mentioned cisco's registrar product, its real nice, and real expensive, and not based on any bind code). There is something going on with rfc 2052 defining directory servers on the internet, but I only read enough of it to give me a headache.
Static vs. Dynamic
M$ strategy is to put all IP addresses into AD, making the entire network a big, dynamic mess. As a network guy, I want all the important services to have static IP addresses. This means servers, DNS machines, router ports, mail servers, and anything else that should be stable.
M$ considers servers to be unstable (based on BSoDs and regular reboots), so they want the IP addresses to be dynamic. That's a bad way of thinking.
The article in ZD is actually correct on a lot of things. There are already battles going on between the ultra-reliable thinking *nix admins and the reboots-are-good ninnies who have realised they can't make M$s win2k work in a unix based world.
The only solution is for the OSS community to make a standard implementation of dhcp client, one that by default passes
the AC
Re:dhcp - dns (Score:1)
Re:Way to go, Microsoft! (Score:1)
Re:microsoft rulez (Score:1)
DDNS vs. Static DNS (Score:5)
DDNS is indeed implemented in the Unices - w/o a problem. The current version of Bind (8) supports DDNS and the development version of DHCP supports the DDNS updates.
The difference in the two (Dynamic/Static) is that, as everyone knows, static DNS requires you to know the IP address of the domain name you're recording. In DDNS, the client requests an IP address from a DHCP server, then, as long as the DHCP server is configured to 'know' the client, it recognizes which client is requesting the IP (based on MAC addressing) and informs the DNS server that it is giving a certain IP address to a client for a particular domain name, and the DNS server accepts the information and adjusts its lookup tables accordingly.
I've implemented this in Linux w/o a problem whatsoever - and I know of a school that has implemented it in a Solaris environment.
Its been out there for a LONG time, btw - by that I mean at least 3 yrs. It wasn't pretty, at times, 3 yrs ago - but it was there. Now, it is a very well integrated solution.
Its nice to be able to connect w/ a laptop anywhere on a 100+ subnet network and get the same domain name to resolve everytime
:).
Btw - first?
:-)
Brice
Re:Oh Dear Lord (Score:1)
Re:Boys, be ambitious - (Score:1)
The situation I described with their MCSE's has to be addressed if Linux is to keep their gains in the server market...
Jim in Tokyo
Interesting... (Score:1)
Last I checked, DDNS was already a set standard, albeit a very new one that most Unices don't use yet. So there's nothing inherently evil about including that in Win2000. But, M$ is breaking interoperability with Unix servers to do so, due to the poor design decision of making a lot of their stuff (although with "Active" in its name, you can tell it's going to be insecure/unstable/buggy/all-of-the-above) depend on a standard which isn't mainstream yet, even if it is probably an open one.
Very clever, I must admit. A way to twist Open-Source to their advantage. Nonetheless, I'd say this ought to go into the 2.3 development tree now, so that it'll hopefully be ready before Win2k or at least not long after.
Re:Ironic. Don't you think? (Score:1)
Re:dhcp - dns (Score:1)
Re:DHCP is lame, DDNS is lame (Score:1)
-earl
heh...some sensitive admins here.... (Score:1)
i would read it as referring to the subset of MS-using sysadmins who are ignorant, not as labeling the entire group as ignorant...
Re:MSFT is full of soulless evil people (Score:1)
Oh, please Bill! Let me work there!
Honestly, can you really think of another company that has enough power to even think of doing what the Halloween documents suggested. Remember, might != right. Being able to force your customers to buy something does not make a good long-term business plan. Eventually they come after you with pitchforks.
Re:Another job for you programmers... (Score:1)
Re:Interesting... (Score:1)
I'd say this ought to go into the 2.3 development tree now
Except that DNS isn't done with the kernel, just as HTTP and SMTP aren't either.
Re:Khttpd is not in the kernel. We have uhttpd. (Score:1)
Re: pretty good (Score:1)
Re:dhcp - dns (Score:1)
Re:dhcp - dns (Score:3)
Networking, DNS/DHCP administration, network security, etc are things that should NOT be left to Windows dialog boxes and wizards. The person in charge of these should study, and learn about them before trying to use them. After that is done, compiling and configuring Bind and dhcpd to do these DYNDNS updates is trivial. My original point was that the technology exists for any mildly competent person in charge of DHCP/DNS on a Unix box, despite the PCWeek author's claim that it just does not exist.
For adequate security models, I'll trust Bugtraq and the dozens of other mailing lists/newsgroups far over MS's little bug page which takes 3-4 weeks to acknowledge security problems, and another 3-4 to come out with a workaround like "don't use this option." If a business wants to protect their networks, they MUST hire a competent person to do the job (I'm available if anyone's looking
Running network services like these on Windows just doesn't promote the Unix concepts of RTFM. Explaining to my brother the concept of mapping hostnames to an IP and likewise that IP to the hostname, or what an MX record is, was made terribly difficult because of what Microsoft has done.
you can dynamic dns now! (Score:1)
I'm not sure what the whole issue is here - ISC's BIND supports dynamic updates now. And their DHCP client supports sending the hostname as part of the packet.
In fact, if you look at this link [sector13.org], you'll see that I currently use a perl program to take entries out of my DHCPD lease file, and update my DNS with the new hostnames, DYNAMICALLY!
- Kazin
Microsoft doesn't like standards. (Score:1)
Problem is.. it violates the real standards for DNS.
To do DDNS requires that all upstream servers update excessively; AXFR's are performed on average every *FIVE MINUTES* in DDNS from what I've seen.
Problem #2; Microsoft doesn't even know what an AXFR is. NT DNS follows standards for lookups, but if you need a secondary DNS server and your primary is NT, well, break out the checkbook. M$ DNS follows ZERO standards in zone transfers, not to mention file format! You *CAN'T* secondary with unix without more headaches than it's worth.
DDNS is nothing more than another Microsoft attempt to gain more control over the internet through 'evolving' standards by blatantly ignoring them.
I pity the fools who believe the hype.
-RISCy Business | Rabid System Administrator and BOFH
Re:Microsoft's ploy... bullchit. (Score:1)
Re:microsoft rulez (Score:1)
Dynamic vs Static (Score:1)
There is nothing that says that you need dynamic DNS in order to associate a FQDN to a specific workstation in a DHCP environment. With DHCP, you can reserve an IP address for a specific workstation simply by giving it the workstation's ethernet address. I set up a bunch of X terminals like this at my previous job. Works great. Less filling.
As a rule of thumb, servers (i.e. hosts that need to be accessed via a specific FQDN) ought to have a static IP address anyway, and it is unwise to create dependencies like this (for example, NIS server needs DHCP server in order to boot).
In my opinion, Dynamic DNS is nifty, but if Microsoft is not keep the standard open, then it is useless.
That's a really naive view... (Score:1)
If you don't trust a patch floating around a mailing list/newsgroup, fine. They will eventually get looked at by the (trusted) maintainers, who will personally review the patch and likely include it in the standard distribution. It's not as if joe schmoe can magically write some code, post it on a newsgroup, and *bam*, it's in the distro. It doesn't work like that. Code has to go through an EXTENSIVE public review process before it gets merged into the main tree. That's a more than adequate security model, and better than most proprietary software vendors.
If getting patches from an untrusted source in a newsgroup bothers you, then you can wait for them to get reviewed and either be rejected (and the functionality added in some other way), or make their way into the standard distribution. I don't see what's so hard about that.
You obviously haven't actually had any direct experience with the way these projects work.
Berlin-- [berlin-consoritum.org]
MS DDNS vs Unix DNS (Score:1)
We're currently installing an Oracle workflow system that relies on LDAP to grab user information from our e-mail server to populate the workflow system directory. The Oracle system is hosted on a Unix box, but most of the user information comes from our e-mail servers, which are all MS Exchange. We also use NetWare.
If the directory services in Win2k are all one-way into the MS directory and we migrate to Win2k, will it prevent our Oracle WF system from pulling user data from the DDNS to populate its own LDAP directory?
Thanks in advance. And if I've phrased the question incorrectly (or cluelessly), please give me a clue.
(Pulling on reflective armor and awaiting response to my first-ever Slashdot post!)
Re:dhcp - dns (Score:1)
Re:dhcp - dns (Score:1)
Re:New ? (Score:1)
Re:DDNS vs. Static DNS (Score:1)
DDNS is an option (Score:1)
RFCs MS will (hopefully) use (Score:3)
If anyone is interested in actually reading them, the RFCs MS is SUPPOSED to be following with this are 2136 and 2052.
Also, no one I know who is testing this out (in the IT consulting firm who will be doing a great deal of this whem it spills out upon the world) is fooling themselves about what a GIANT political battle this could turn into. To avoid this, you will probably see Active Directory Domains handling their own DDNS, and forwarding to existing UNIX infrastructure for all other name resolution if those doing the implementation aren't up to the fight.
...how other systems in the network will resolve to systems in the DDNS zones is supposed to be worked out, (with the use of some crazy zone magic) but I've not seen it work yet.
Re:Static vs. Dynamic IP. (Score:2)
However, the dialect of transactional signatures (TSIG) supported by Windows 2000 is *not* the same as that supported by vanilla BIND, and that will cause problems. Basically, you'll have to allow "unsigned" dynamic updates if you use BIND instead of the Microsoft DNS Server.
MS supporting DDNS is a Good Thing (Score:2)
At home, because it's almost always the only DHCP client, my laptop always gets 192.168.0.10 (the beginning of my assigned DHCP range), so I can pretend it has a fixed IP address for local DNS purposes. At work, it gets a different IP address almost every day. WINS can resolve its name anyway; DNS can't because we don't have DDNS yet. MS supporting DDNS is good; my Solaris and Linux machines (which have clients for DNS but not WINS) would be able to look up my laptop by name, just like my Windows box (which has clients for both DNS and WINS).
Yes, MS might screw up DDNS, through malice or incompetence, and provide something only 99% compatible with the RFC. Recall the pump DHCP client included with Red Hat 6.0, which worked great with most Unix DHCP servers but not with NT's. But note that it was quickly patched to work with NT. Open-sourced clients can quickly deal with a bit of incompatibility, whether malicious or accidental.
The fact that MS supports a new open standard like DDNS before your favorite OS does is a reason to start working on an open DDNS client, not an excuse to bash MS. DDNS is good. NT becoming more standards-compliant is good. If at some point in the future MS starts changing their DDNS server around to deliberately cause problems with other people's clients, *then* bash MS, and suggest to your local sysadmin that he run DHCP and DNS from a cheap Linux/*BSD/whatever box instead of an NT server to maintain maximum compatibility with existing clients. But bashing MS in advance just for announcing the intent to support a good, new, open standard is counterproductive. Would you really prefer WINS?
Re:Umm? (Score:2)
DHCP vs DDNS (Score:2)
Corporate environment, infomercials (Score:2)
I agree with you completely, because this strengthens my theory about MS's server strategy.
DDNS may not be a compelling solution for a global, public network, but it sounds as though it's a very nice option for a local net, and that's where Microsoft is concentrating their efforts.
It is important to remember that the Winxx platform is not the logical center of Microsoft's empire. MS Office is. MS Office is the "killer app" which makes most businesses buy Wintel boxes on the desktop, and Windows on the desktop is why those same businesses buy NT servers. The presence of MS Office for the Mac was a significant factor in Apple's resurgence in sales.
Microsoft is leveraging this advantage very effectively, integrating Office with IIS, and with DDNS they are now making it even easier for any salesperson to connect their Windows laptop to connect to any open ethernet port in the office and start working immediately.
That, all by itself, is a good thing. What is not a good thing is for MS to specifcially design their ActiveDirectory so that it requires DDNS. Novell's NDS doesn't require DDNS, and from what I've seen ActiveDirectory does less than Novell's solution. I'm sure that the programmers behind W2K are very good at their jobs, so I must assume that the decision to make W2K DDNS dependant was a conscious choice. If MS publishes a white paper stating the reasons for this, I will read it, (and the soon-to-follow slashdot commentary) and make my mind up then.
PC Week deserves criticism for not doing their homework on this (no surprise there). To state that Unix does not offer this service, when it does, is terrible journanlism.
But then, any "news" article about Windows 2000 which is followed by a link titled
"Check prices: Windows 2000" isn't actually journalism at all, it's an infomercial. | https://slashdot.org/story/99/08/28/1336258/windows-2000-to-provoke-domain-game | CC-MAIN-2016-44 | refinedweb | 7,217 | 71.85 |
Example code is pasted below. Basically, just wanted to say that this is
either completely non-intuitive, or I am failing to understand something
fundamental about matplotlib.
My impression would be that twinx would let me assign categorical values to
however they were before I twinned them (i.e., using the original axis'
order and coordinates). But, if you use categorical values, it will
truncate them to the length of the categorical list/array. In the example
code, if you comment out the x1/x2 categorical assignments and use integers
instead (uncomment those), it works as you'd expect. You can even swap the
order in which the integers are plotted, but NOT if you use the text
assignments, despite the fact that the integer and text axes are the same.
Gallery:
Anyway, someone please let me know if there is some design principle I'm
missing here, or if this is a special case. It's missing from any of the
top level documentation (see:
, ) and took me the
better part of this afternoon to figure out. The only conclusion I can come
to is that matplotlib treats these values differently, and converts the
text arrays to integers under the hood without trying to align them.
Cheers,
AJ
Code:
import matplotlib.pyplot as plt
x1 = ['apples', 'bananas', 'cheerios']
##x1 = [1,3,5]
y1 = [5, 6, 15]
x2 = ['apples','carrots','bananas','watermelon','cheerios']
##x2 = [1,2,3,4,5]
y2 = [100, 200, 300, 400, 500]
fig, ax = plt.subplots()
ax.scatter(x2, y2)
ax2 = ax.twinx()
ax2.scatter(x1, y1, color = "orange")
plt.show()
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <> | https://discourse.matplotlib.org/t/categorical-variables-and-twinx-make-basically-no-sense/20402 | CC-MAIN-2021-43 | refinedweb | 272 | 63.19 |
We are excited to release new functionality to enable a 1-click import from Google Code onto the Allura platform on SourceForge. You can import tickets, wikis, source, releases, and more with a few simple steps.
Hi,
If it helps, I've removed the from so the next line is an import:
File "<string>", line 1
import getopt, os, pwd, sys
^
SyntaxError: no viable alternative at input 'import'
John
> -----Original Message-----
> From: Leo Soto M. [mailto:leo.soto@...]
> Sent: 27 October 2009 17:42
> To: Baker, John (IT/UK)
> Cc: Sebastien.Boisgerault@...; jython-
> users@...
> Subject: Re: [Jython-users] from and with keywords
>
> On Tue, Oct 27, 2009 at 2:12 PM, <john.m.baker@...> wrote:
> > Hello,
> > I used Jython 2.5.1 and there are no spaces before from... the
> modules also
> > load correctly in Python.
>
> Perhaps you have some weird bytes at the start of the file? The error
> says "line 2".
>
> Perhaps some bogus Unicode BOM?
> --
> Leo Soto:
View entire thread | http://sourceforge.net/p/jython/mailman/message/23871929/ | CC-MAIN-2014-10 | refinedweb | 163 | 75.71 |
Technical Articles
Easy Descriptive Statistics with Python and SAP HANA Cloud
As Solution Advisors, we occasionally participate in POCs which require us to receive and analyze real customer data. Often, the first step to developing an analysis plan is to perform some exploratory data analysis on the data to determine the distribution of values and uniqueness of each column. Since we are dealing with real customer use-cases the datasets tend to be very wide, often with missing data. It is important to be able to get a sense of the quality of the dataset quickly since we may have to get back to the customer with our questions about the dataset before the project and analysis planning can begin.
I discovered a nice trick to generate this information within SAP HANA Cloud using the hana_ml Python library and wanted to share it as my first blog post. 😊
Problem: SAP Data Intelligence Fact Sheet cannot be exported
The fact sheets on profiled datasets in SAP Data Intelligence provide descriptive statistics on each column but we are not able to save this information as a dataset to manipulate and report on.
SAP Data Intelligence fact sheet provides descriptive statistics
However, the describe() method in the hana_ml Python library provides a simple way to generate this summary for us. This summary is generated natively in SAP HANA so it is fast as well.
Those familiar with Python may already be familiarity with describe(). For a pandas dataFrame, calling describe will produce a nice table with descriptive statistics like min, max, mean, and quartile values of each column.
The hana_ml Python library has also implemented this method and it is a handy way to generate descriptive statistics on any SAP HANA table. It is very flexible as well, allowing you to save the results natively as an SAP HANA table or bring it into your Python environment. Finally, it is a great way to understand how the Python wrapper works on top of SAP HANA Cloud.
SAP HANA DataFrames are SQL statements
There are already several great blogs on the SAP HANA DataFrame but it allows you to utilize your Python knowledge to work with your SAP HANA environment. The SAP HANA DataFrame provides a pointer to the data in HANA without storing any of the physical data. It is very flexible and allows you to perform data manipulations and transformations easily. It also let’s you move your data from your HANA environment and Python environment easily. With collect(), you can materialize your SAP HANA dataFrame as a Pandas dataFrame to offer even greater flexibility.
HANA dataFrame represents a table, column or SQL. Source:
Use SAP HANA_ml Python library to import local files (e.g. csv, Excel)
In addition to generating descriptive statistics on your SAP HANA tables, you can also use the hana_ml library to load local files (e.g. .csv or Excel) to SAP HANA cloud automatically. To get started, let’s first import the necessary libraries and establish our connection to SAP HANA Cloud.
First, let’s import the necessary libraries:
import pandas as pd import hana_ml.dataframe as dataframe print('HANA ML version: ' + hana_ml.__version__) print('Pandas version: ' + pd.__version__)
Next, set up our SAP HANA Cloud connection:
# Import libraries import hana_ml.dataframe as dataframe # Create connection to HANA Cloud # Instantiate connection object conn = dataframe.ConnectionContext(address = '<Your tenant info here for example something(4)
Create connection to HANA tenant and test connection
The sample file I used for this demo is the 2018 file from the Airline Delay and Cancellation Data, 2019-2018. I wanted to test the performance vs. Pandas but you can use whatever file you have handy.
Using Pandas, we can import the file and run describe() to get summary statistics in Python.
import pandas as pd df = pd.read_csv('../datasets/airline-delay/2018.csv')
Pandas describe method
To do the same in SAP HANA Cloud, we’ll first need to convert the Pandas dataFrame to an SAP HANA table. We can use the create_dataframe_from_pandas()to do this. It will automatically upload the Pandas DataFrame to SAP HANA to create a table or view, and an SAP HANA DataFrame as well.
Although we do not need to specify the datatype formats, the automatic conversion is not the most efficient. For example, pandas object types are converted to NVARCHAR(5000). However, we can use Pandas to provide the format lengths of string columns to minimize storage by calculating the maximum length of each string column.
# Subset dataframe to only object (string) types df2 = df.select_dtypes(include='object') # Create table of columns and data types r = df2.dtypes.to_frame('dtypes').reset_index() # Filter to string columns sv = r[r['dtypes']=='object'].set_index('index') # Iterate for each string column for i in sv.index.to_list(): # Get max length l = df2[i].str.len().max().astype(int) # Write max length to columns table sv.loc[i, 'len'] = f'NVARCHAR({l})' # Create dictionary of columns:length hana_fmt = sv['len'].to_dict() hana_fmt
Find max length of character strings and create format dictionary
Now, we can use create_dataframe_from_pandas() to create the SAP HANA table. There are many optional options as well, be sure to check out the docs.
# conn - Connection to HANA Cloud # pandas_df - Pandas dataFrame to upload # table_name - HANA table name to create # table_structure - HANA table format dictionary # allow_bigint - Allows mapping to bigint or int # force - replace HANA table if exists dataframe.create_dataframe_from_pandas(connection_context = conn, pandas_df = df, table_name = 'AIRLINES_2018', allow_bigint = True, force = True)
Creating HANA Cloud table using dtype formats
The code above creates the SAP HANA dataFrame (“df_hana”) which points to the “AIRLINES_2018” SAP HANA table but you can also reference tables like below. We can call the describe() on that SAP HANA dataFrame to generate the descriptive stats we need. The code below brings the descriptive statistics into Pandas with collect()
%%time stats = conn.table('AIRLINE_2018') stats.describe().collect()
SAP HANA describe() collected to Pandas
However, if we wanted this information in SAP HANA we can do so without bringing into Pandas and saving directly as a SAP HANA table.
df_hana.describe().save('STATS_AIRLINE2018')
We can see this table created in the SAP HANA Database Explorer:
Descriptive statistics saved as table in SAP HANA Cloud
We can understand what is happening behind the scenes with the select_statement. This shows the underlying SQL behind the SAP HANA DataFrame.
df_hana.describe().select_statement
Underlying SQL statement we do not have to write
As you can see, the SAP hana_ml Python library is very flexible and allows you to combine the flexibility to Python with the power of SAP HANA.
You can use it to automate the time-consuming task of running descriptive statistics to accelerate the process of data discovery and exploratory data analysis.
Special thanks to Andreas Forster, Marc Daniau, and Onno Bagijn and the other bloggers for sharing their invaluable knowledge.
Great Blog Jeremy Yu . Very detailed step by step instructions..
Looking forward to the next one.. in this series.
me too
The article makes me feel like I need to learn more about this field | https://blogs.sap.com/2021/05/24/easy-descriptive-statistics-with-python-and-sap-hana-cloud/ | CC-MAIN-2022-27 | refinedweb | 1,176 | 53.51 |
About |
Projects |
Docs |
Forums |
Lists |
Bugs |
Get Gentoo! |
Support |
Planet |
Wiki.
>> Note:
>> 1) There are 2 gnap_shared.sh so far, one in the src and one in the toos
>> directory of the gnap svn tree. This should maybe be changed...
>
> shoudl be
Where do you want to have it?
>> 2) The gnap_* scripts do 'source "gnap_shared.sh"', which is probably
>> not
>> good. In which directory will we put gnap_shared.sh?
>
> at moment "/usr/lib/gnap"
Seems to make the most sense, i'll change that.
>> 08-namespace-gnap_shared.patch
>>
>> This cleanes up the namespace, all variables that are used as input
>> parameters in gnap_shared.sh are prefixed with GNAP_ to get a clean
>> usage
>> of the namespace. More to that later.
>
> great
It's not 100% clean so far, i did not work on variables in gnap_overlay
and gnap_remaster so far, i also forgot to check which implications this
has on the config files.
>>.
>
>
>>.
>
> i prefer to mantain gnap simple as possible, Really some catalyst option
> is so usefull to use it alone? non-implemented-catalyst options are
> sufficent usefull to implement them in gnap_make?
Hmm, all the reasons why i thought this might be a good idea are only
minor. So... i'll move that off my todo list until i find a valid use case
for it.
>> 3) gnap_make feature: improved overlay handling
[...]
> To improve is ever good :)
An alternative would be to introduce overlay handling to catalyst, but i
think, we don't want that. :-)
>>."
Any comments on this?
Examples:
gconfirm() {
if [[ "${FORCEYES}" -eq 1 ]]; then
gwarn "${*} forced to yes"
else
read -ep " ${W}*${N} ${*} [N]: " answer
if [[ "${answer}" != 'y' && "${answer}" != 'Y' ]]; then
if [[ -n "${GNAP_TEMPDIR}" ]]; then
cleanup
fi
echo "${GNAP_PRODUCT} aborted !"
exit 2
fi
fi
}
what if the user mixes up for example german and us keyboard layout, wants
to say y but gets z instead?
if [[ -f "${GNAP_LOGPREFIX}.out" || -f "${GNAP_LOGPREFIX}.err" ]]; then
if [[ "${FORCEYES}" -ne 1 ]]; then
read -ep " ${W}*${N} Logfile(s) already exists.
Append/Overwrite
[A]: " \
answer
if [[ "${answer}" == 'o' || "${answer}" == 'O' ]]; then
rm "${GNAP_LOGPREFIX}.out" "${GNAP_LOGPREFIX}.err"
fi
fi
fi
Same here, i cannot think of keymap issues but peope sometimes hit the
wrong button. Should we have the questions in a loop until they are
answered correctly?
>>}"
>> That's all i wanted to say about the gnap_scripts at the moment.
>
> you say a lot :)
Hmm... is that good or bad? :)
> nice job
Thanks, unfortunately not what i applied for. :-(
See you,
Philipp
--
gnap-dev@g.o mailing list
Updated Jun 17, 2009
Summary:
Archive of the gnap-dev mailing list.
Donate to support our development efforts.
Your browser does not support iframes. | http://archives.gentoo.org/gnap-dev/msg_df542b06c2b38aae0a23e6cfdd20c8cf.xml | CC-MAIN-2014-42 | refinedweb | 442 | 77.33 |
XAML and XAML-Related Concepts in the JavaScript API for Silverlight
If you use the JavaScript API for Silverlight, XAML processing and other behavior related to XAML differs significantly in some areas. The event handlers are referenced as HTML-level script includes rather than partial classes. Also, XAML is architecturally the primary instantiation technique for the JavaScript API for Silverlight, and thus you will frequently be defining them as XAML pages or XAML fragments, then accessing the created objects with FindName. This topic explains the XAML behavior and some key techniques for creating or accessing objects from XAML using JavaScript API.
Event Handlers in XAML for JavaScript API
In XAML, the API being used (managed or JavaScript) affects the technique of specifying event handlers. The API is mutually exclusive on a XAML page level. The signal for which API is used is the presence or absence of the x:Class attribute on the root element of a XAML page. If x:Class exists, the page uses the managed API. If x:Class is absent, the page uses the JavaScript API.
The following XAML example shows how to add a handler for the Loaded event for the Canvas, which in this example is the root of a XAML file. The absence of x:Class on this root indicates the JavaScript API. Resolution of the function name is therefore deferred until run time. At run time, when the event occurs, the JavaScript scripting scope is checked for a member named "onLoaded" and that function is executed.
<Canvas xmlns="" Loaded="onLoaded" />
The function named onLoaded is defined in a JavaScript file. This JavaScript file is associated with the HTML of the hosting page through the src parameter of the <SCRIPT> tag in HTML. This is necessary because it is the browser host that is really interpreting the script; the Silverlight plug-in is only an intermediary in the processing of the JavaScript API and does not provide the actual script engine. There is nothing in the XAML that must reference a specific JavaScript file; that is only relevant at the browser and DOM level.
<!-- Reference the JavaScript file where the event functions are defined from the plug-in host HTML page. --> <script type="text/javascript" src="eventfunctions.js"> ... </script>
The Object Tree and FindName
In the JavaScript API, the initial object tree is always constructed by parsing XAML. Except for some type-conversion usages that can parse strings, loading XAML is the only way to "construct" an object in the JavaScript API. After such a tree is constructed, you typically will want to interact with the object tree. In order to do so, you need a scripting object reference to one of the objects in the tree.
The best way to establish such a reference is to assign a Name or x:Name attribute to any object element in the XAML where you plan to reference that object during run time. In the JavaScript API, the name is conceptually just a string, not an object. But the name string is used to retrieve the actual object by then making a call to FindName in any run-time code. FindName exists in the API in such a way that you can call FindName on just about any object in the JavaScript API, including on the object that represents the Silverlight plug-in. You will commonly see that the first line or lines of a user function that is written for JavaScript API for Silverlight makes FindName calls to get object references, then the remainder of the function operates against those objects.
Even if there are no named objects, you can still get into the object tree at run time through the Root property on the Silverlight plug-in. This returns the object that is the root of the loaded XAML.
In addition, any event handler attached to a Silverlight object has access to a sender value from an event. This sender and the relevant event handler are frequently attached in such a way that sender is the object that you want to interact with. If not, sender still provides a convenient object that you can call FindName from. For more information on event handling in the JavaScript API for Silverlight, see Handling Silverlight Events by Using JavaScript.
The Object Tree and CreateFromXaml
The Silverlight content on your Web page is arranged as a hierarchy of objects in a tree structure. The single, topmost object in the structure is the root object, and it corresponds to the root of the XAML file that is loaded as the Source for a Silverlight plug-in. The root object is generally a Canvas object, because Canvas can contain other objects such as TextBlock or MediaElement. (Silverlight 1.0 only supported Canvas as a root; if you use JavaScript API with Silverlight 5 clients, you can use other UIElement objects as the root.)
To add XAML content dynamically to the tree structure after the initial loading of the source XAML, you first create the XAML fragment by using the CreateFromXaml method. At this point, the XAML fragment you create is disconnected from the Silverlight object tree. This means that the fragment is not rendered yet. However, even before adding it to the object tree, you can modify the properties of the objects in the XAML fragment. Object methods cannot be invoked prior to connecting the tree.
After you have created a disconnected object set from your XAML fragment, you generally will want to add it to the active Silverlight object tree. The fragment can either be added as a child object to a parent object, or it can set a property value of an object. When the fragment becomes part of the Silverlight object tree, the objects in the XAML fragment are rendered. Depending on the extent of the XAML provided as CreateFromXaml input, you can create a single Silverlight object, such as a TextBlock, or a complex tree of Silverlight objects.
There are several requirements for adding XAML content dynamically to the Silverlight object tree:
There must be existing XAML content associated with the Silverlight plug-in. You cannot use CreateFromXaml to replace the entire tree of content; you must at.
The CreateFromXaml method can be invoked only by the Silverlight plug-in. However, it is easy in the JavaScript API to get an object reference to the plug-in: just call GetHost on any Silverlight object.
XAML content that is created by using the CreateFromXaml method can be assigned to only one object. If you want to add objects created from identical XAML to different areas of the application, you must invoke CreateFromXaml multiple times and use different variables for the return value. (If you do this, be careful of name collisions; see Creating Namescopes with CreateFromXAML later in this topic.)
The Silverlight object that will contain the new XAML content must be capable of encapsulating an object, either as a child element or as a property value.
The string you specify for xamlContent of CreateFromXaml must specify well-formed XML (in particular, it must have a single root element). CreateFromXaml will fail and cause an error if the provided XML string is not well formed.
The root element is implicitly using the Silverlight XML namespace. You can set the Silverlight namespace explicitly, but do not set the default XML namespace to any other value other than the Silverlight namespace.
Creating XAML Namescopes with CreateFromXAML
XAML used for CreateFromXaml can have values defined for Name or x:Name. As part of the CreateFromXaml call, a preliminary XAML namescope is created, based on the root of the provided XAML. This preliminary namescope evaluates any defined names in the provided XAML for uniqueness. If names in the provided XAML are not internally unique at this point, CreateFromXaml throws an error. However, if names in the provided XAML collide with names that are already in the primary XAML namescope, no errors occur immediately. This is because when the CreateFromXaml method is called, the created object tree that is returned is disconnected. still creates a preliminary XAML namescope that evaluates any defined names in the provided XAML for uniqueness. If names in the provided XAML are not internally unique at this point, CreateFromXaml throws an error. The difference in the behavior is that the disconnected object tree is now flagged to not attempt to merge its XAML namescope with the primary XAML namescope when it is connected to the main application object tree. After you connect the trees, in effect, your application will have a unified object tree but discrete XAML namescopes. A name defined at the CreateFromXaml root or on any object in the previously disconnected tree is not associated with the primary XAML namescope; it has its own discrete XAML namescope.
The complication with having discrete XAML namescopes is that calls to the FindName method no longer operate against a unified namescope. Instead, the particular object that FindName is called on will imply the scope, with the scope being the XAML namescope that the calling object is within. Therefore, if you attempt to call FindName to get a named object in the primary XAML namescope, it will not find the objects from a discrete XAML namescope created by CreateFromXaml. Conversely, calling FindName from the discrete XAML namescope will not find named objects in the primary XAML namescope. The FindName method defined on the Silverlightplug-in object does not entirely work around this issue; its XAML namescope is always the primary XAML namescope.
This discrete XAML namescope issue only affects XAML namescopes and the FindName call. You can still walk the object tree structure upward in some cases by calling the GetParent method, or downward by calling into the relevant collection properties or properties (such as the collection returned by Canvas.Children).
To get to objects that are defined in a discrete XAML namescope, you can use several techniques:
Walk the object tree with GetParent and/or collection properties.
If you are calling from a discrete XAML namescope and want the primary XAML namescope, it is always easy primary XAML namescope and want an object within a discrete XAML namescope, you should plan ahead in your code and retain a reference to the object that was returned by CreateFromXaml. This object is now a valid object for calling FindName within the discrete XAML namescope. You could keep this object as a global variable or otherwise pass it by using method parameters.
See Also | https://docs.microsoft.com/en-us/previous-versions/windows/silverlight/dotnet-windows-silverlight/cc903955%28v%3Dvs.95%29 | CC-MAIN-2019-26 | refinedweb | 1,743 | 58.42 |
Using Pseudo code, design an algorithm that can sum the digits of an integer in
the range 100-999. For example, given a number 734, the answer would be 7 + 3
+ 4, which equals 14. Given 103 the sum would be 1 + 0 + 3, which equals 4.
Hint: in order to extract each digit (units, tens, hundreds etc.) from a given
number, think about using the division (/) and, or modulus
of that number byof that number by
10 or multiples of 10.
Additional marks are available for an algorithm that can deal with any size of
number.
2. Complete the outline Java class below by,
Using the algorithm above to implement the sumOfDigits value method, which
accepts a number as a parameter and returns the sum of its digits.
Implement the main method that should prompt the user to input an integer
number then print the number and a message stating whether the sum of its
digits is equal to 10. Note - the user should be forced to enter a number between
100 and 999 inclusive. Sample program executions might look as follows
Input Number: 730
The sum of the digits of 730 is 10 and is equal to 10.
Input Number: 198
The sum of the digits of 198 is 18 and is NOT equal to 10.
// Sample outline class.
public class Sum
{
public static int sumOfDigits int number)
{
// complete method
}
public static void main(String[] args)
{
// complete method
}
} | http://www.javaprogrammingforums.com/whats-wrong-my-code/19971-pseudo-code-algorithms.html | CC-MAIN-2014-41 | refinedweb | 240 | 69.82 |
Unable to Program SiPy
Despite some initial success, I am unable to program SiPy module. My main setup is Windows 7 64-bit, using Atom and most recent Pymakr package, and a PyCom SiPy w/ Expansion Board 2.0. I have the latest firmware for the boards.
Here is a detailed description of troubleshooting/results:
Unboxing/Setup
- Connected over serial. Updated to latest firmware with wizard.
- Able to program the device over REPL in Atom
Building a project
- Moved main and boot files inside of the project folder
- Synchronized and ran perfectly. Checked Sigfox backend and saw all messages received
Failures with Atom
- REPL began locking up. I was either left at “Connecting on COMxx” or could see the “>>>,” but could not type anything.
- Inconsistent: I could program if I unplugged and plugged back in. Sometimes, though connected the REPL would lock.
Troubleshooting (With no Success)
- OS: Also tried Xubuntu. Was not even able to update firmware.
- Hardware: Tried multiple cables, another module, and another expansion board. Board is in correct orientation.
- Firmware: I am updated to the latest version. I had some success restoring to factory firmware, but then lost ability again to program and updated to latest again.
- Serial: Also tried VS Code, PuTTY, and Python 2.7's serial module, all of which I was successful with before any issues began. I am using the correct baud rate, and port, and have the latest drivers installed.
- Telnet: Tried with Mac OSX Laptop and with iPhone (SSH Client Free app). I get a response, but still cannot type. I am simply left with this response and no '>>>' for entering commands:
MicroPython v1.8.6-776-gd0a46cd on 2017-09-29; SiPy with ESP32 Login as: Password: Login succeeded! Type "help()" for more information
I may post this in another part of the discussion board as well, since there seems to be more support for LoPy, and the issue is not necessarily just for SiPy.
TL;DR my SiPy connects to and is recognized by my computer, but I cannot program it.
@jcaron It worked! My bad. Didn't even think about that. I erased flash memory and uploaded most recent firmware. Thank you @robert-hh as well.
For the future, are there any best practices for connecting/disconnecting, from both a hardware and software standpoint. e.g. my boot.py file:
import os from machine import UART uart = UART(0, 115200) os.dupterm(uart)
Should I include anything else?
@robert-hh I'm on Windows, but I got this output:
...\Pycom Firmware Update\Upgrade\bin> esptool.py --port COM23 erase_flash esptool.py v2.0-beta1 Connecting................................................ A fatal error occurred: Failed to connect to Espress if device: Timed out waiting for packet header
@choco The serial connection is independent from the SiPy, since it is provided by the USB/UART bridge, which works, even when the SiPy is silent. What confuses me is that you see the splash screen of MicroPython, but no >>> prompt. Could you try ro erase flash and then re-load the firmware. For erasing you need esptool.py, which is in the subdirectory of the updater software. And then, in a command window, run:
python3 esptool.py --port COM23 erase_flash
Ctrl-C does nothing as well (and I have my project and global settings marked true for Ctrl-C on Connect). The REPL is entirely locked and unresponsive. When I open Atom, this is what I see:
Connecting on COM23... # I open Atom Cancelled # I hit "reconnect" after a while Connecting on COM23... > Failed to connect (Error: Port is not open). Click here to try again. # Same line twice > Failed to connect (Error: Port is not open). Click here to try again. [] # Flashing cursor
Device manager shows USB Serial Port 23 as active when I plug the SiPy in, and it disappears when I remove it. Further, if I open a session in PuTTY, though I cannot issue any commands, when I close out of PuTTY, I get a dialog box asking if I want to close the session.
@choco this may sound silly, but have you tried Ctrl-C? While your boot.py/main.py is running, REPL is not available unless you terminate the currently running script. | https://forum.pycom.io/topic/1896/unable-to-program-sipy/3?lang=en-US | CC-MAIN-2021-17 | refinedweb | 705 | 75.91 |
Frequently Asked Questions About Berkeley DB Java Edition
There are two caveats with NFS based storage, although the motivation for them in Java Edition (JE) is different from that of Berkeley DB. First, JE requires that the underlying storage system reliably persist data to the operating system level when write() is called and durably when fsync() is called. However, some remote file system server implementations will cache writes on the server side (as a performance optimization) and return to the client (in this case JE) before making the data durable. While this is not a problem when the environment directory's disk is local, this can present issues in a remote file system configuration because the protocols are generally stateless. The problem scenario can occur if (1) JE performs a write() call, (2) the server accepts the data but does not make it durable by writing it to the server's disk, (3) the server returns from the write() call to the client, and then (4) the server crashes. If the client (JE) does not know that the server has crashed (the protocol is stateless), and then JE later successfully calls write() on a piece of data later in the log file, it is possible for the JE log file to have holes in it, causing data corruption.
In JE 3.2.65 and later releases, a new parameter has been added, called je.log.useODSYNC, which causes the JE environment log files to be opened with the O_DSYNC flag. This flag causes all writes to be written durably to the disk. In the case of a remote file system it tells the server not to return from the write() call until the data has been made durable on the server's local disk. The flag should never be used in a local environment configuration since it incurs a performance penalty. Conversely, this flag should always be used in a remote file system configuration or data corruption may result.
When using JE in a remote file system configuration, the system should never be configured with multiple file system clients (i.e. multiple hosts accessing the file system server). In this configuration it is possible for client side caching to occur which will allow the log files to become out of sync on the clients (JE) and therefore corrupt. The only solution we know of for this is to open the environment log files with the O_DIRECT flag, but this is not available using the Java VM.
Second, Java Edition (JE) uses the file locking functionality provided through java.nio.channels.FileChannel.lock(). Java does not specify the underlying implementation, but presumably in many cases it is based on the flock() system call. Whether flock() works across NFS is platform dependent. A web search shows several bug reports about its behavior on Linux where flock() is purported to incorrectly return a positive status.
JE uses file locking for two reasons:
Of course the simplest way of dealing with flock() vs NFS is to only use a single process to access a JE environment. If that is not possible, and if you cannot rely on flock() across NFS on your systems, you could handle (1) by taking responsibility in your application to ensure that there is a single writer process attached. Having two writer processes in a single environment could result in database corruption. (Note that the issue is with processes, and not threads.)
Handling the issue of log cleaning (2) in your application is also possible, but more cumbersome. To do so, you must disable the log cleaner (by setting the je.env.runCleaner property to false) whenever there are multiple processes accessing an Environment. If file deletion is not locked out properly, the reader processes might periodically see a com.sleepycat.je.log.LogFileNotFoundException, and would have to close and reopen to get a fresh snapshot. Such an exception might happen very sporadically, or might happen frequently enough to make the setup unworkable. To perform a log cleaning, the application should first ensure that all reader processes have closed the Environment (i.e. all read-only processes have closed all Environment handles). Once closed, the writer process should perform log cleaning by calling Environment.cleanLog() and Environment.checkpoint(). Following the completion of the checkpoint, the reader processes can re-open the environment.
We've had a few questions about whether data files can be shared between Berkeley DB and Berkeley DB Java Edition. The answer is that the on disk format is different for the two products, and data files cannot be shared between the two. Both products do share the same format for the data dump and load utilities (com.sleepycat.je.util.DbDump, com.sleepycat.je.util.DbLoad), so you can import and export data between the two products.
Also, JE data files are platform independent, and can be moved from one machine to another. Lastly, both products both support the Direct Persistence Layer API, the persistent Java Collections API and a similar byte array based API.
JE supports get() and put() operations with partial data. However, this feature is not fully optimized, since the entire record is always read or written to the database, and the entire record is cached.
So the only advantage (currently) to using partial get() and put() operations is that only a portion of the record is copied to or from the buffer supplied by the application. In the future we may provide optimizations of this feature, but until then we cannot claim that JE has high performance LOB support.
For more information on partial get() and put() operations please see our documentation.
Key prefixing is a database storage technique which reduces the space used to store B-Tree keys. It is useful for applications with large keys that have similar prefixes. JE supports key prefixing as of version 3.3.62. See DatabaseConfig.setKeyPrefixing.
JE also does not currently support key compression. While we have thought about it for both the DB and JE products, there are issues with respect to the algorithm that is used, the size of the key, and the actual values of the key. For example, LZW-style compression works well, but needs a lot of bytes to compress to be effective. If you're compressing individual keys, and they're relatively small, LZW-style compression is likely to make the key bigger, not smaller.
JE configuration properties can be programmatically specified through Base API (com.sleepycat.je) classes such as EnvironmentConfig, DatabaseConfig, StatsConfig, TransactionConfig, and CheckpointConfig. When using the replication (com.sleepycat.je.rep) package, ReplicatedEnvironment properties may be set using ReplicationConfig. When using the DPL (com.sleepycat.persist) package, EntityStore configuration properties may be set using StoreConfig. The application instantiates one of these configuration classes and sets the desired values.
For Environment and ReplicatedEnvironment configuration properties, there's a second configuration option, which is the je.properties file. Any property set though the get/set methods in the EnvironmentConfig and ReplicationConfig classes can also be specified by creating a je.properties file in the environment home directory. Properties set through je.properties take precedence, and give the application the option of changing configurations without recompiling the application. All properties that can be specified in je.properties can also be set through EnvironmentConfig.setConfigParam or ReplicationConfig.setConfigParam.
The complete set of Environment and ReplicatedEnvironment properties are documented in the EnvironmentConfig and ReplicationConfig classes. The javadoc for each property describes the allowed values, default value and whether whether the property is mutable. Mutable properties can be changed after the environment open. Properties not documented in these classes are experimental and some may be phased out over time, while others may be promoted and documented.
The general capability for assigning IDs is a "sequence", and has the same functionality as a SQL SEQUENCE. The idea of a sequence is that it allocates values efficiently (without causing a performance bottleneck), and guarantees that the same value won't be used twice.
When using the DPL, the @PrimaryKey(sequence="...") annotation may be used to define a sequence. When using the Base API, the Sequence class provides a lower level form of sequence functionality, and an example case is in <jeHome>/examples/je/SequenceExample.java.
If you are currently storing objects using a TupleBinding, it is possible to add fields to the tuple without converting your existing databases and without creating a data incompatibility. Please note also that class evolution is supported without any application level coding through the Direct Persistence Layer API.
This excerpt from the Javadoc may be made to tuple bindings. Collections Overview
The tuple binding uses less space and executes faster than the serial binding. But once a tuple is written to a database, the order of fields in the tuple may not be changed and fields may not be deleted. The only type evolution allowed is the addition of fields at the end of the tuple, and this must be explicitly supported by the custom binding implementation.
Specifically, if your type changes are limited to adding new fields then you can use the TupleInput.available() method to check whether more fields are available for reading. The available() method is the implementation of java.io.InputStream.available(). It returns the number of bytes remaining to be read. If the return value is greater than zero, then there is at least one more field to be read.
When you add a field to your database record definition, in your TupleBinding.objectToEntry method you should unconditionally write all fields including the additional field.
In your TupleBinding.entryToObject method you should call available() after reading all the original fixed fields. If it returns a value greater than zero, you know that the record contains the new field and you can read it. If it returns zero, the record does not contain the new field.
For example:
public Object entryToObject(TupleInput input) { // Read all original fields first, unconditionally. if (input.available() > 0) { // Read additional field #1 } if (input.available() > 0) { // Read additional field #2 } // etc }
Below is a simple Servlet example that uses JE. It opens a JE Environment in the init method and then reads all the data out of it in the doGet() method.
import java.io.*; import java.text.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*;; /** * The simplest possible servlet. */ public class HelloWorldExample extends HttpServlet { private Environment env = null; private Database db = null; public void init(ServletConfig config) throws ServletException { super.init(config); try { openEnv("c:/temp"); } catch (DatabaseException DBE) { DBE.printStackTrace(System.out); throw new UnavailableException(this, DBE.toString()); } } public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { ResourceBundle rb = ResourceBundle.getBundle("LocalStrings",request.getLocale()); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head>"); String title = rb.getString("helloworld.title"); out.println("<title>" + title + "</title>"); out.println("</head>"); out.println("<body bgcolor=\"white\">"); out.println("<a href=\"../helloworld.html\">"); out.println("<img src=\"../images/code.gif\" height=24 " + "width=24 align=right border=0 alt=\"view code\"></a>"); out.println("<a href=\"../index.html\">"); out.println("<img src=\"../images/return.gif\" height=24 " + "width=24 align=right border=0 alt=\"return\"></a>"); out.println("<h1>" + title + "</h1>"); dumpData(out); out.println("</body>"); out.println("</html>"); } public void destroy() { closeEnv(); } private void dumpData(PrintWriter out) { try { long startTime = System.currentTimeMillis(); out.println("<pre>"); Cursor cursor = db.openCursor(null, null); try { DatabaseEntry key = new DatabaseEntry(); DatabaseEntry data = new DatabaseEntry(); while (cursor.getNext(key, data, LockMode.DEFAULT) == OperationStatus.SUCCESS) { out.println(new String(key.getData()) + "/" + new String(data.getData())); } } finally { cursor.close(); } long endTime = System.currentTimeMillis(); out.println("Time: " + (endTime - startTime)); out.println("</pre>"); } catch (DatabaseException DBE) { out.println("Caught exception: "); DBE.printStackTrace(out); } } private void openEnv(String envHome) throws DatabaseException { EnvironmentConfig envConf = new EnvironmentConfig(); env = new Environment(new File(envHome), envConf); DatabaseConfig dbConfig = new DatabaseConfig(); dbConfig.setReadOnly(true); db = env.openDatabase(null, "testdb", dbConfig); } private void closeEnv() { try { db.close(); env.close(); } catch (DatabaseException DBE) { } } }
You can use the Environment.getConfig() API to retrieve configuration information after the Environment has been created. For example:
import java.io.File; import com.sleepycat.je.*; public class GetParams { static public void main(String argv[]) throws Exception { EnvironmentConfig envConfig = new EnvironmentConfig(); envConfig.setTransactional(true); envConfig.setAllowCreate(true); Environment env = new Environment(new File("/temp"), envConfig); EnvironmentConfig newConfig = env.getConfig(); System.out.println(newConfig.getCacheSize()); env.close(); } }
will display
> java GetParams 7331512 >
Note that you have to call getConfig(), rather than query the EnvironmentConfig that was used to create the Environment.
Berkeley DB, Java Edition comes in two flavors, Concurrent Data Store (CDS) and Transactional Data Store (TDS). The difference between the two products lies in whether you use transactions or not. Literally speaking, you are using TDS if you call the public API method, EnvironmentConfig.setTransactional(true).
Both products support multiple concurrent reader and writer threads, and both create durable, recoverable databases. We're using "durability" in the database sense, which means that the data is persisted to disk and will reappear if the application comes back up after a crash. What transactions provide is the ability to group multiple operations into a single, atomic element, the ability to undo operations, and control over the granularity of durability.
For example, suppose your application has a two databases, Person and Company. To insert new data, your application issues two operations, one to insert into Person, and another to insert into Company. You need transactions if your application would like to group those operations together so that the inserts only take effect if both operations are successful.
Note that an additional issue is whether you use secondary indices in JE. Suppose you have a secondary index on the address field in Person. Although it only takes one method call into JE to update both the Person database and its secondary index Address, the application needs to use transactions to make the update atomic. Otherwise, it's possible that if the system crashed at given point, Person could be updated but not Address.
Transactions also let you explicitly undo a set of operations by calling Transaction.abort(). Without transactions, all modifications are final after they return from the API call.
Lastly, transactions give you finer grain durability. After calling Transaction.commit, the modification is guaranteed to be durable and recoverable. In CDS, without transactions, the database is guaranteed to be durable and recoverable back to the last Environment.sync() call, which can be an expensive operation.
Note that there are different flavors of Transaction.commit that let you trade off levels of durability and performance, explained in this [#41|FAQ entry.
So in summary, choose CDS when:
Choose TDS when:
There is a single download and jar file for both products. Which one you use is a licensing issue, and has no installation impact.
Yes; "tables" are databases, "rows" are key/data pairs, and "columns" are application-encapsulated fields. The application must provide its own methods for accessing a specific field, or "column" within the data value.
The memory overhead for keeping a database open is quite small. In general, it is expected that applications will keep databases open for as long as the environment is open. The exception may be an application that has a very large number of databases and only needs to access a small subset of them at any one time.
If you notice that your application is short on memory because you have too many databases open, then consider only opening those you are using at any one time. Pooling open database handles could be considered at that point, if the overhead of opening databases each time they are used has a noticeable performance impact.
The smallest cache size is 96KB (96 * 1024). You can set this by either calling EnvironmentConfig.setCacheSize(96 * 1024) on the EnvironmentConfig instance that you use to create your environment, or by setting the je.maxMemory property in your je.properties file.
In the past, we've discussed whether it makes sense to provide a set of interfaces that are implemented by the Berkeley DB JE API and the Java API for Berkeley DB. We looked into this during the design of JE and decided against it because in general it would complicate things for "ordinary" users of both JE and DB.
JE requires Java SE 1.5 or later. There are no plans to support J2ME at this time.
It is important that je.jar and your application jar files—in particular the classes that are being serialized by SerialBinding-are loaded under the same class loader. For running in a servlet, this typically means that you would place je.jar and your application jars in the same directory.
Additionally, it is important to not place je.jar in the extensions directory for your JVM. Instead place je.jar in the same location as your application jars. The extensions directory is reserved for privileged library code.
One user with a WebSphere Studio (WSAD) application had a classloading problem because the je.jar was in both the WEB-INF/lib and the ear project. Removing the je.jar from the ear project resolved the problem.
If you want to read and write to the JE environment, then you should provide r/w permission on the directory, je.lck, and *.jdb files for JE.
If you want read-only access to JE, then you should either:
If JE finds that the JE environment directory is writable, it will attempt to write to the je.lck file. If it finds that the JE environment directory is not writable, it will verify that the Environment is opened for read-only.
We assume that you have installed the m2eclipse maven plugin in Eclipse, and created a maven project in Eclipse for your JE based project. To deploy BDB JE maven, you need to add a BDB JE dependency and repository into the pom.xml of your project.
<dependencies> <dependency> <groupId>com.sleepycat</groupId> <artifactId>je</artifactId> <version>4.0.103</version> </dependency> </dependencies>
Please confirm that the desired version of JE has been included into JE maven. You can find out the up-to-date JE version at:
<repositories> <repository> <id>oracleReleases</id> <name>Oracle Released Java Packages</name> <url></url> <layout>default</layout> </repository> </repositories>
Save the modified pom.xml. Now m2eclipse will automatically download and configure JE's jar and javadoc (assuming that you have selected "Download Artifact Sources" and "Download Artifact JavaDoc" in the maven preference section of Eclipse) for your project.
The common cause of a com.sleepycat.je.LockConflictException is the situation where 2 or more transactions are deadlocked because they're waiting on locks that the other holds. For example:
The lock timeout message may give you insight into the nature of the contention. Besides the default timeout message, which lists the contending lockers, their transactions, and other waiters, it's also possible to enable tracing that will display the stacktraces of where locks were acquired.
Stacktraces can be added to a deadlock message by setting the je.txn.deadlockStackTrace property through your je.properties file or EnvironmentConfig. This should only be set during debugging because of the added memory and processing cost.
Enabling stacktraces gives you more information about the target of contention, but it may be necessary to also examine what locks the offending transactions hold. That can be done through your application's knowledge of current activity, or by setting the je.txn.dumpLocks property. Setting je.txn.dumpLocks will make the deadlock exception message include a dump of the entire lock table, for debugging. The output of the entire lock table can be large, but is useful for determining the locking relationships between records.
Another note, which doesn't impact the deadlock itself, is that the default setting for lock timeouts (specified by je.lock.timeout or EnvironmentConfig.setLockTimeout() can be too long for some applications with contention, and throughput improves when this value is decreased. However, this issue only affects performance, not true deadlocks.
In JE 4.0 and later releases on the 4.x.y line, and JE 3.3.92 and later releases on the 3.3.x line, the NIO parameters je.log.useNIO, je.log.directNIO, and je.log.chunkedNIO are deprecated. Setting them has no affect.
In JE 3.3.91 and earlier, the NIO parameters are functional, but should never be used since they are now known to cause data corrupting bugs in JE.
Calling Thread.interrupt() is not recommended for an active JE thread if the goal is to stop the thread or do thread coordination. If you interrupt a thread which is executing a JE operation, the state of the database will be undefined. That's because JE might have been in the middle of I/O activity when the operation was aborted midstream, and it becomes very difficult to detect and handle all possible outcomes.
If JE can detect the interrupt, it will mark the environment as unusable and will throw a RunRecoveryException. This tells you that you must close the environment and re-open it before using it again. If JE doesn't throw RunRecovery up it. This is the recommended technique.
If you absolutely must interrupt threads for some reason, you should expect that you will see RunRecoveryException. Each thread should treat this exception as an indication that it should stop.
We believe that Windows 7 (as of build 7600) has an IO bug which is triggered by JE 3.3.91 and earlier under certain conditions. Unfortunately, this bug causes file corruption which is eventually detected by JE's checksumming mechanism. JE 4.0 (and later) has a "write queue" mechanism built into it which prevents this bug from being triggered. Because JE 3.3.91 (and earlier releases) were shipped before Windows 7, we were not aware of the bug and therefore not able to include preventive code. JE 3.3.92 detects if it is running on Windows 7 and prevents triggering the bug. We have reported this bug to Microsoft. [#17865]
Yes. The com.sleepycat.je.XAEnvironment class implements the javax.transaction.xa.XAResource interface, which can be used to perform 2 phase commit transactions. The relevant methods in this interface are start(), {{end()}}}, prepare(), commit(), and rollback(). The XAEnvironment.setXATransaction() is an internal entrypoint that is only public for the unit tests.
The XA Specification has the concept of implicit transactions (a transaction that is associated with a thread and does not have to be passed to the JE API); this is supported in JE 2.0. You can use the XAResource.start() method to create a JE transaction and join it to the calling thread. To disassociate a transaction from a thread, use the end() method. When you use thread-implied transactions, you do not have to pass in a Transaction argument to the JE API (e.g. through methods such as get() and put()). Instead, passing null in a thread-implied transaction environment tells JE to use the implied transaction.
Here's a small example of how to use XAEnvironment and 2 Phase Commit:
XAEnvironment env = new XAEnvironment(home, null); Xid xid = [something...]; env.start(xid, 0); // creates a thread-implied transaction for you ... calls to get/put, etc. with null transaction arg will use the implicit transaction... env.end(xid, 0); // disassociate this thread from the implied transaction env.prepare(xid); if (commit) { env.commit(xid, false); } else { env.rollback(xid); }
Berkeley DB does not have a query language. It has API methods for performing queries that can be implemented as lookups in a primary or secondary index. Wildcard queries and non-key must be performed by scanning an entire index and examining each key and/or value.
In an SQL database or another database product with a query language, a full index scan is executed when you perform a wildcard query or a non-key query. In Berkeley DB you write a loop that scans the index. While you have to write the loop, you'll see better performance than in an SQL database because there is no SQL processing involved.
Berkeley DB supports simple key lookups as well as prefix or range queries. Range queries allow you to search for all keys in a range of keys or for all keys starting with a given prefix value. For more information on range queries in the Base API, see:
For more information on range queries in the DPL API, see:
As of JE 4.0, key-only queries may be performed and I/O is significantly reduced if ReadUncommitted isolation is configured. Because JE data records are stored separately, the I/O to read the data record is avoided when the data record is not already in cache. Note that if other isolation levels are used, then the I/O cannot be avoided because the data record must be read in order to lock the record.
To perform a {{ReadUncommitted}} key-only query using the Base API, use any Database or Cursor method to perform the query and specify the following:
To perform a ReadUncommitted key-only query using the DPL, use any EntityIndex to perform the query and specify the following:
Berkeley DB has direct support only for intersection (AND) joins across the secondary keys of a single primary database. You cannot join more than one primary database. If you are using the DPL, the same is true: you can only join across the secondary keys of a single primary index.
For example, imagine a primary database (index) called Person that has two secondary keys: birthdate and favorite color. Using the Join API, you can find all Person records that have a given birthdate AND a given favorite color.
When using the Base API, see the(com.sleepycat.je.Cursor[,%20com.sleepycat.je.JoinConfig) Database.join] method. When using the DPL, see the EntityJoin class.
To perform a join across more than primary database (index), you must write a loop that iterates over the records of one database (index) and does a lookup in one or more additional databases (indexes).
In an SQL database or another database product with a query language, similar iterative processing takes place when the join is executed. In Berkeley DB while you must write the code that iteratively performs the join, you'll see better performance than in an SQL database because there is no SQL processing involved.
Imagine an application where a single primary employee database has three fields that are indexed by secondary databases: status, department, salary. The user wishes to query for a specific status, a specific department, and range of salary values. Berkeley DB supports joins, and the join API can be used to select the AND (intersection) of a specific status and a specific department. However, the join API cannot be use to select a range of salaries. Berkeley DB also supports range searches, making it possible to iterate over a range of values using a secondary index such as a salary index. However, there is no way to automatically combine a range search and a join.
To combine a range search and a join you'll need to first perform one of the two using a Berkeley DB API, and then perform the other manually as a "filter" on the results of the first. So you have two choices:
Which option performs best depends on whether the join or the range query will produce a smaller result set, on average. If the join produces a smaller result set, use option 2; otherwise, use option 1. There is a 3rd option to consider if this particular query is performance critical. You could create a secondary index on preassigned ranges of salary For example, assign the secondary key 1 for salaries between $10,000 and $19,999, key 2 for salaries between $20,000 and $29,999, etc.
If a query specifies only one such salary range, you can perform a join using all three of your secondary indices, with no filtering after the join. If the query spans ranges, you'll have to do multiple joins and then union the results. If the query specifies a partial range, you'll have to filter out the non-matching results. This may be quite complex, but it can be done if necessary. Before performing any such optimization, be sure to measure performance of your queries to make sure the optimization is worthwhile.
If you can limit the specified ranges to only those that you've predefined, that will actually simplify things rather than make them more complex, and will perform very well also. In this case, you can always perform a single join with no filtering. Whether this is practical depends on whether you can constrain the queries to use predefined ranges.
On range searches in general, they can be done with Cursor.getSearchKeyRange or with the SortedSet.subSet and SortedMap.subMap methods, depending on whether you are using the base API or the Collections API. It is up to you which to use.
If you use Cursor.getSearchKeyRange you'll need to call getNext to iterate through the results. You'll have to watch for the end range yourself by checking the key returned by getNext. This API does not have a way to enforce range end values automatically.
If you use the Collections API you can call subMap or subSet and get an Iterator on the resulting collection. That iterator will enforce both the beginning and the end of the range automatically.
If you have a secondary database with sorted duplicates configured, you may wish to sort the duplicates according to some other field in the primary record. Let's say your secondary key is F1 and you have another field in your primary record, F2, that you wish to use for ordering duplicates. You would like to use F1 as your secondary key, with duplicates ordered by F2.
In Berkeley DB, the "data" for a secondary database is the primary key. When duplicates are allowed in a secondary, the duplicate comparison function simply compares those primary key values. Therefore, a duplicate comparison function cannot be used to sort by F2, since the primary record is not available to the comparison function.
The purpose of key and duplicate comparison functions in Berkeley DB is to allow sorting values in some way other than simple byte-by-byte comparison. In general it is not intended to provide a way to order keys or duplicates using record data that is not present in the key or duplicate entry. Note that the comparison functions are called very often - whenever any Btree operation is performed - so it is important that the comparison be fast.
There are two ways you can accomplish sorting by F2:
Option #1 has the advantage of automatically sorting by F2. However, you will never be able to do a join (via the Database.join method) on the F1 key alone. You will be able to do a join on the F1+F2 value, but it seems unlikely that will be useful. Secondaries are often used for joins. Therefore, we recommend option #2 unless you are quite sure that you won't need to do a join on F1. The trade-offs are:
Duplicate records are records that are in a single database and have the same key. Since there is more than one record per key, a simple lookup by key is not sufficient to find all duplicate records for that key.
When using the DPL, the SecondaryIndex.subIndex method is the simplest way to access duplicate records.
When using the Base API, you need to position a cursor at the desired key, and then retrieve all the subsequent duplicate records. The Getting Started Guide has a good section on how to position your cursor: Search For Records and then how to retrieve the rest of the duplicates: Working with Duplicate Records.
As with most Btree based data stores, Berkeley DB Java Edition does not store record counts for non-duplicate records, so some form of internal or application based traversal is required to get the size of the result set. This is in general true of relational databases too; it's just that the count is done for you internally when the SQL count statement is executed. Berkeley DB Java Edition version 3.1.0 introduced a Database.count() method, which returns the number of all key/data pairs in the database. This method does an optimized, internal traversal, does not impact the working set in the cache, but may not be accurate in the face of concurrent modifications in the database.
To get a transactionally current count, or to count the result of a join, do this:
cursor = db.openCursor(...)
OR
db.join(someCursors); count = 0; while(cursor.getNext(...) == OperationStatus.SUCCESS) { count++; }
There are a few ways to optimize an application-implemented count:
count = 0; while (cursor.getNextNoDup(...) == OperationStatus.SUCCESS) { count += cursor.count(); }
because you will only look up 3 records (one for each key value), not 3000 records.
Phantoms are records that can appear in the course of performing operations in one thread when records are inserted by other threads. For example, if you perform a key lookup and the record is not found, and then you later perform a lookup with the same key and the record is found, then the record was inserted by another thread and is called a phantom.
Phantoms and how to prevent them in transactional applications are described in Writing Transactional Applications under Configuring Serializable Isolation.
However, you may wish to prevent phantoms but you cannot use transactions. For example, if you are using Deferred Write, then you cannot use transactions. For phantoms that appear after a search by key, another technique for preventing them is to use a loop that tries to insert with putNoOverwrite, and if the insert fails then does a search by key.
Here is a code sketch using the base API:
Cursor cursor = ...; DatabaseEntry key = ...; DatabaseEntry insertData = ...; DatabaseEntry foundData = ...; boolean exists = false; boolean done = false; while (!done) { OperationStatus status = cursor.putNoOverwrite(key, insertData); if (status == OperationStatus.SUCCESS) { /* A new record is inserted */ exists = false; done = true; } else { status = cursor.getSearchKey(key, foundData, LockMode.RMW); if (status == OperationStatus.SUCCESS) { /* An existing record is found */ exists = true; done = true; } /* else continue loop */ } }
If the putNoOverwrite succeeds, the cursor holds the write lock on the inserted record and no other thread can change that record. If the putNoOverwrite fails, then the record must exist so we search by key to lock it. If the search succeeds, then the cursor holds the write lock on the existing record and no other thread can modify that record. If the search fails, then another thread must have deleted the record and we loop again.
This technique relies on a property of JE cursors called "cursor stability". When a cursor is positioned on a record, the cursor maintains its position regardless of the actions of other threads. The record at the cursor position is locked and no other thread may modify it. This is true whether transactions are used or not, and when deferred write is used.
With this technique it is necessary to use a cursor in order to hold the lock. Database.get, Database.putNoOverwrite and other Database methods do not hold a lock when used without an explicit transaction. The same is true of the corresponding DPL methods: EntityIndex.get, PrimaryIndex.put, etc.
Using this technique is recommended rather than using your own locking (with synchronized or java.util.concurrent). Custom locking is error prone and almost always unnecessary.
As an aside, JE cursor stability is slightly different when "dirty read" (LockMode.READ_UNCOMMITTED) is used. In this case, the cursor will remain positioned on the record, but another thread may change the record or even delete it.
Using a single Database instance for multiple threads is supported and, as of JE 4.0, has no performance drawbacks.
In JE 3.3 and earlier, using a single Database instance for multiple threads presented a minor bottleneck. The issue is that the Database object maintains a set of Cursors open against it. This set is used to check if all Cursors are closed against the Database when close() is called, but to do that JE has to synchronize against it before updating it. So if multiple threads are sharing the same Database handle it makes for a synchronization bottleneck. In a multi-threaded case, unless there's a good reason to share a Database handle, it's probably better to use separate handles for each thread.
JE 2.1.30 introduced two new performance motivated locking options.
No-locking mode is on one end of the spectrum. When EnvironmentConfig.setLocking(false) is specified, all locking is disabled, which relieves the application of locking overhead. No-locking should be used with care. It's only valid in a non-transactional environment and the application must ensure that there is no concurrent activity on the database. Concurrent activity while in no-locking mode can lead to database corruption. In addition, log cleaning is disabled in no-locking mode, so the application is responsible for managing log cleaning through explicit calls to the Environment.cleanLog() method.
On the other end of the spectrum is the je.lock.nLockTables property, which can specify the number of lock tables. While the default is 1, increasing this number can improve multithreaded concurrency. The value of this property should be a prime number, and should ideally be the nearest prime that is not greater than the number of concurrent threads.
A good starting point is to invoke DbCacheSize with the parameters:
-records <count> # Total records (key/data pairs); required -key <bytes> # Average key bytes per record; required [-data <bytes>] # Average data bytes per record; if omitted no leaf # node sizes are included in the output
See the DbCacheSize javadoc for more information.
Note that DbPrintLog -S gives the average record size under Log statistics, in the LN (leaf node) row, at the avg bytes column.
To measure the cache size for a 64-bit JVM, DbCacheSize needs to be run on the 64-bit JVM.
To take full advantage of JE cache memory, it is strongly recommended that compressed oops (-XX:+UseCompressedOops) is specified when a 64-bit JVM is used and the maximum heap size is less than 32 GB. As described in the referenced documentation, compressed oops is sometimes the default JVM mode even when it is not explicitly specified in the Java command. However, if compressed oops is desired then it must be explicitly specified in the Java command when running DbCacheSize or a JE application. If it is not explicitly specified then JE will not aware of it, even if it is the JVM default setting, and will not take it into account when calculating cache memory sizes.
For read-write applications, we strongly recommend that the JE cache size be large enough to hold all Btree internal nodes (INs) for the records in the active data set. DbCacheSize can be used to estimate the cache size to hold all internal nodes for a given data set. For some applications the active data set may be a subset of the entire data set, for example, if there are hot spots in the access pattern. For truly random key access and other access patterns where there are no significant hot spots, the cache should be sized to hold all internal nodes.
JE, like most database products, performs best when the metadata (in this case the Btree internal nodes) needed to execute a read or write operation is present in its cache. For example, if the internal nodes at the bottom level of the Btree (BINs) are not in the cache, then for each operation a BIN must be fetched from the file system. This may often result in a random read I/O, although no storage device I/O will occur if the BIN happens to be present in the file system cache.
In addition, for write operations, the BIN will be dirtied. If the cache is not large enough to hold the BINs, the dirty BIN will quickly be evicted from the cache, and when it is evicted it will be written. The write of the BIN may be buffered, and the buffer will not be flushed to the file system until the write buffer fills, the log file fills, or another operation causes the buffer to be written.
The net effect is that additional reading and writing will be necessary when not all BINs are present in the JE cache. When all BINs are in cache, they will only be read when first accessed, and will only be written by a checkpoint. The checkpoint interval can be selected to trade off the cost of the writing, for reduced recovery time in the event of a crash.
The description of the performance trade-offs in the preceding paragraph is probably applicable, in a very rough sense, to many database products. For JE in particular, its log structured storage system adds another dimension to the picture. Each time a BIN is dirtied and written to the log via cache eviction, at least some redundant information is written to the log, because a BIN (like anything else in JE's append-only log) cannot be overwritten. The redundant BIN entries in the log must be garbage collected by the JE log cleaner, which adds an additional cost.
In general, the JE log cleaner thread acts like an application thread that is performing record updates. When it cleans a log file, each active record or internal node must be copied to the end of the log, which is very much like a record update (although nothing in the record is changed). These updates are just like application-initiated updates in the sense that when the cache does not hold a BIN that is needed, then the BIN must be fetched into cache, the BIN will be dirtied by the update, and the dirty BIN may soon be flushed to the log by cache eviction. If the cache is small enough and the application write rate is high enough, this can create a negative feedback cycle of eviction and log cleaning which has a large performance impact. This is the probably the most important reason that the JE cache should be sized to hold all internal nodes in the active data set.
It is worth noting that leaf nodes (LNs) are not affected by the issues discussed in the preceding two paragraphs. Leaf nodes hold record data and are logged at the time of the operation (insert, update or delete), as opposed to internal nodes (metadata) which are dirtied by each operation and later logged by checkpoints and eviction. Therefore, the preceding issue does not need to be taken into account when deciding whether to size the cache large enough to hold leaf nodes. Leaf nodes may be kept in the JE cache, the file system cache, or a combination of the two. In fact, it is often advantageous to evict leaf nodes immediately from the JE cache after an operation is completed (and rely instead on the file system cache to hold leaf nodes) because this reduces JVM GC cost -- see CacheMode.EVICT_LN for more information. DbCacheSize reports the amount of memory needed for internal nodes only, and for internal nodes plus leaf nodes.
Read-only applications are also not affected by the preceding issue. If only read operations are performed and the cache does not hold all internal nodes, then extra read I/Os may be necessary, but the append-only structured storage system and log cleaner do not come into play.
JE, like most databases, performs best when database objects are found in its cache. The cache eviction algorithm is the way in which JE decides to remove objects from the cache and can be a useful policy to tune. The default cache eviction policy is LRU (least recently used) based. Database objects that are accessed most recently are kept within cache, while older database objects are evicted when the cache is full. LRU suits applications where the working set can stay in cache and/or there are some data records are used more frequently than others.
An alternative cache eviction policy was added in JE 2.0.83 that is instead primarily based on the level of the node in the Btree. This level based algorithm can improve performance for some applications with both of the following characteristics:
The alternative cache eviction policy is specified by setting this configuration parameter in your je.properties file or EnvironmentConfig object: je.evictor.lruOnly=false
The level based algorithm works by evicting the lowest level nodes of the Btree first, even if higher level nodes are less recently used. In addition, dirty nodes are evicted after non-dirty nodes. This algorithm can benefit random access applications because it keeps higher level Btree nodes in the tree for as long as possible, which for a random key, can increase the likelihood that the relevant Btree internal nodes will be in the cache.
When using je.evictor.lruOnly=false, you may also consider changing the default value for je.evictor.nodesPerScan to a value larger than the default of 10, to perhaps 100. This setting controls the number of Btree nodes that are considered, or sampled, each time a node is evicted. We have found in our tests that a setting of 100 produces good results when system is IO bound. The larger the nodesPerScan, the more accurate the algorithm.
However, don't set it too high. When considering larger numbers of nodes for each eviction, the evictor may delay the completion of a given database operation, which impacts the response time of the application thread. In JE 4.1 and later, setting this value too high in an application that is largely CPU bound can reduce the effectiveness of cache eviction. It's best to start with the default value, and increase it gradually to see if it is beneficial for your application.
The cache management policies described above apply to all operations within an environment. In JE 4.0.103, a new com.sleepycat.je.CacheMode class was introduced, which lets the application indicate caching policy at the per-operation, per-database, or per environment level. CacheMode is best used when the application has specific knowledge about the access pattern of a particular set of data. For example, if the application knows a given database will be accessed only once and will not be needed again, it might be appropriate to use CacheMode.MAKE_COLD.
When in doubt, it is best to avoid specific CacheMode directives, or at least to wait until application development is finished, and you are doing performance tuning with a holistic view.
Gathering environment statistics is a useful first step to doing JE performance tuning. Execute the following code snippet periodically to display statistics for the past period and and to reset statistics counters for the next display.
StatsConfig config = new StatsConfig(); config.setClear(true); System.err.println(env.getStats(config));
The Javadoc for com.sleepycat.je.EnvironmentStats describes each field. Cache behavior can have a major effect on performance, and nCacheMiss is an indicator of how hot the cache is. You may want to adjust the cache size, data access pattern, or cache eviction policy and monitor nCacheMiss.
Applications which use transactions may want to check nFSyncs to see how many of these costly system calls have been issued. Experimenting with other flavors of commit durability, like TxnWriteNoSync and TxnNoSync can improve performance.
nCleanerRuns and cleanerBacklog are indicators of log cleaning activity. Adjusting the property je.cleaner.minUtilization can increase or decrease log cleaning. The user may also elect to do batch log cleaning, as described in the Javadoc for Environment.cleanLog(), to control when log cleaning occurs.
High values for nRepeatFaultReads and nRepeatIteratorReads may indicate non-optimal read buffer sizes. See the FAQ entry on configuring read buffers.
A user posted a question about the pros and cons of using multiple databases. The question was: We are designing a application where each system could handle at least 100 accounts. We currently need about 10 databases. We have three options we are considering.
All three options are practical solutions using JE. Which option is best depends on a number of trade-offs.
The data for each account is kept logically separate and easy to manage. Databases can be efficiently renamed, truncated and removed (see Environment.renameDatabase, truncateDatabase and removeDatabase), although this is not as efficient as directly managing the log files, as with a separate environment (option 2). Copying a database can be done with the DbDump and DbLoad utilities, or with a custom utility.
With this option a single transaction can be used for records in multiple accounts, since transactions may span databases and a single environment is used for all accounts. Secondary indices cannot span accounts, since secondaries cannot span databases.
The cost of opening and closing accounts is mid-way between option 2 and 3. Opening and closing databases is less expensive than opening and closing environments.
The per-account overhead is lower than option 2, but higher than option 3. The per-database disk overhead is about 3 to 5 KB. The per-database memory overhead is about the same but is only incurred for open databases, so it can be be minimized by closing databases that are not in active use. Note that prior to JE 3.3.62 this memory overhead was not reclaimed when a database was closed. For this reason, if large numbers of databases are used then option 1 is not recommended with releases prior to JE 3.3.62.
The checkpoint overhead is higher than option 3, because the number of databases is larger. How much this overhead matters depends on the data access pattern and checkpoint frequency. This tradeoff is described following option 3 below.
If database names are used to identify accounts, another issue is that Database.getDatabaseName does a linear search of the records in the mapping tree and is slow. A workaround is to store the name in your own application, with the reference to the Database.
The data for each account is kept physically separate and easy to manage, since a separate environment directory exists for each account. Deleting and copying accounts can be performed as file system operations.
With this option a single transaction cannot be used for records in multiple accounts, since transactions may not span environments. Secondary indices cannot span accounts, since secondaries cannot span databases or environments.
The cost of opening and closing accounts is highest, because opening and closing databases is less expensive than opening and closing environments. Be sure to close environments cleaning to minimize recovery time.
This option has the highest overhead per account, because of the per-environment memory and disk space overhead, as well as the background threads for each environment. In JE 3.3.62 and later, a shared cache may be used for all environments. With this option it is important to configure a shared cache (see EnvironmentConfig.setSharedCache) to avoid a multiplying effect on the cache size of all open environments. For this reason, this option is not recommended with releases prior to JE 3.3.62.
The checkpoint overhead is higher than option 3, because the number of environments and databases is larger. How much this overhead matters depends on the data access pattern and checkpoint frequency. This tradeoff is described following option 3 below.
The data for each account is kept logically separate using the key prefix, but accounts must be managed using custom utilities that take this prefix into account. The DPL (see com.sleepycat.persist) may be useful for this option, since it makes it easy to use key ranges that are based on a key prefix.
With this option a single transaction can be used for records in multiple accounts, since a single environment is used for all accounts. Secondary indices can also span accounts, since the same database(s) are used for all accounts.
The cost of opening and closing accounts is lowest (close to zero), since neither databases nor environments are opened or closed.
Because the number of databases and environments is smallest, the per-account memory and disk overhead is lowest with this option. Key prefixing should normally be configured to avoid redundant storage of the account key prefix (see DatabaseConfig.setKeyPrefixing).
The checkpoint overhead is lowest with this option, because the number of environments and databases is smallest. How much this overhead matters depends on the data access pattern and checkpoint frequency. This tradeoff is described below.
It costs more to checkpoint the root of a database than other portions. Whether this matters depends on how the application accesses the database. For example, it costs marginally less to insert 1000 records into 1 database than to insert 1 record into 1000 databases. However, it costs much less to checkpoint the former rather than the latter. Suppose we update 1 record in 1000 databases. In a small test program, the checkpoint takes around 730 ms. Suppose we update 1000 records in 1 database. In the same test, the checkpoint takes around 15 ms.
In addition, each environment has information that must be checkpointed, which will make the total checkpoint overhead somewhat larger in option 2, since each environment must be checkpointed separately.
In general, JE performs best when its working set fits within cache. But due to the interaction of Java garbage collection and JE, there can be scenarios when JE actually performs better with a smaller cache.
JE caches items by keeping references to database objects. To keep within the memory budget mandated by the cache size, JE will release references to those objects and they will be garbage collected by the JVM. Many JVMs use an approach called generational garbage collection. Objects are categorized by age in order to apply different collection heuristics. Garbage collecting items from the younger space is cheaper and is done with a "partial GC" pass while longer-lived items require a more expensive "Full GC".
If the application tends to access data records that are rarely re-used, <b>and</b> the JE cache has excessive capacity, the JE cache will become populated with data records that are no longer needed by the application. These data records will eventually age and the JVM will re-categorize them as older objects, which then provokes more Full GC. If the JE cache is smaller, JE itself will tend to dereference, or evict these once-used records more frequently and the JVM will have younger objects to garbage collect.
Garbage collection is really only an issue when the application is CPU bound. To find this point of equilibrium, the user can monitor EnvironmentStats.nCacheMisses and the application's throughput. Reducing the cache to the smallest size where nCacheMisses is 0 will show the optimal performance. Enabling GC statistics in the JVM can help too. (In the Java SE 5 JVM this is enabled with ("-verbose:gc", "-XX+PrintGCDetails", "-XX:+PrintGCTimeStamps")
JE follows two patterns when reading items from disk. In one mode a single database object, which might be a Btree node or a single data record, is faulted in because the application is executing a Database or Cursor operation and cannot find the item in cache. In a second mode, JE will read large sequential portions of the log on behalf of activities like environment startup or log cleaning, and will read in one or multiple objects.
Single object reads use temporary buffers of a size specified by je.log.faultReadSize while sequential reads use temporary buffers of a size specified by je.log.iteratorReadSize. The defaults for these properties are listed in <jeHome>/example.properties, and are currently 2K and 8K respectively.
The ideal read buffer size is as small as possible to reduce memory consumption but is also large enough to adequately fit in most database objects. Because JE must fit the whole database object into a buffer when doing a single object read, a too-small read buffer for single object reads can result in wasted, repeated read calls. When doing sequential reading, JE can piece together parts of a database object, but a too-small read buffer for sequential reads may result in excessive copying of data. The nRepeatFaultReads and nRepeatIteratorReads fields in EnvironmentStats show the number of wasted reads for single and sequential object reading.
If nRepeatFaultReads is greater than 0, the application may try increasing the value of je.log.faultReadSize. If nRepeatIteratorReads is greater than 0, the application may want to adjust je.log.iteratorReadSize and je.log.iteratorMaxSize.
JE log files are append only, and all record insertions, deletions, and modifications are added to the end of the current log file. See the FAQ on What is so different about JE log files? for more information.
New data is buffered in write log buffers before being flushed to disk. As each log buffer is filled, a write system call is issued. As each .jdb file reaches its maximum size, a fsync system call is issued and a new .jdb file is created.
Increasing the write log buffer size and the JE log file size can improve write performance by decreasing the number of write and fsync calls. However, write log buffer size has to be balanced against the total JE memory budget, which is represented by the je.maxMemory, or EnvironmentConfig.getCacheSize(). It may be more productive to use available memory to cache database objects rather than write log buffers. Likewise, increasing the JE log file size can make it harder for the log cleaner to effectively compress the log.
The number and size of the write log buffers is determined by je.log.bufferSize, je.log.numBuffers, and je.log.totalBufferBytes. By default, there are 3 write log buffers and they consume 7% of je.maxMemory. The nLogBuffers and bufferBytes fields in EnvironmentStats will show what the current settings are.
An application can experiment with the impact of changing the number and size of write log buffers. A non-transactional system may benefit by reducing the number of buffers to 2. Any write intensive application may benefit by increasing the log buffer sizes. That's done by setting je.log.totalBufferBytes to the desired value and setting je.log.bufferSize to the total buffer size/number of buffers. Note that JE will restrict write buffers to half of je.maxMemory, so it may be necessary to increase the cache size to grow the write buffers to the desired degree.
Many users see a large performance difference when they enable or disable transactions in their application, without doing any tuning or special configuration.
The performance difference is the result of the durability (the D in ACID) of transactions. When transactions are configured, the default configuration is full durability: at each transaction commit, the transaction data is flushed to disk. This guarantees that the data is recoverable in the event of an application crash or an OS crash; however, it comes with a large performance penalty because the data is written physically to disk.
If you need transactions (for atomicity, for example, the A in ACID) but you don't need full durability, you can relax the durability requirement. When using transactions there are three durability options:
You can call these specific Transaction methods, or you can call commit and change the default using an environment parameter. Without transactions, JE provides the equivalent of commitNoSync durability.
Note that the performance of commitSync can vary widely by OS/disk/driver combination. Some systems are configured to buffer writes rather than flush all the way to disk, even when the application requests an fsync. If you need full durability guarantees, you must use a OS/disk/driver configuration that supports this.
The different durability options beg the question: How can changes be explicitly flushed to disk at a specific point in time, in a non-transactional application or when commitNoSync or commitWriteNoSync is used?
In a transactional application, you have three options for forcing changes to disk:
In a non-transactional application, you have two options for forcing changes to disk:
Berkeley DB Java Edition (JE) appends records to the log, so they are stored in the order they are written, that is in time or "temporal" order. But if the records are written in a non-sequential key-order, that is the "spatial" ordering is different than the "temporal" order, then reading them in key order will read in log (disk) order. Reading a disk in sequential order is faster than reading in random order. When key order is not equal to disk order, and neither the operating system's file system cache or the JE cache are "hot", a database scan will generally be slower because the disk head may have to move on every read.
One way to improve read performance when key (spatial) order is not the same as disk (temporal) order, is to preload the database into the JE cache using the Database.preload() method. preload() is optimized to read records in disk order, not key order. See the documentation.
The JE cache should be sized large enough to hold the pre-loaded data or you may actually see a negative performance impact.
Another alternative is to change the application that writes the records to write them in key order. If records are rewritten in key order then a cursor scan will cause the records to be read in a disk-sorted order. The disk head will be moved a minimum number of times during the scan, and when it does, it will always move in the same direction.
There are different ways to reorder the records. If the application can be taken off-line DbDump/DbLoad can be used to reorder the records. See the DbDump and DbLoad documentation.
If the application can not be taken off-line the reordering can be accomplished by reading keys via a Cursor in either of the following ways:
If your application has a large cache size, tuning the Java GC may be necessary. You will almost certainly be using a 64b JVM (i.e. -d64), the -server option, and setting your heap and stack sizes with -Xmx and -Xms. Be sure that you don't set the cache size too close to the heap size so that your application has plenty of room for its data and to avoided excessive full GC's. We have found that the Concurrent Mark Sweep GC is generally the best in this environment since it yields more predictable GC results. This can be enabled with -XX:+UseConcMarkSweepGC.
Best practices dictates that you disable System.gc() calls with -XX:-DisableExplicitGC.
Other JVM options which may prove useful are -XX:NewSize (start with 512m or 1024m as a value), -XX:MaxNewSize (try 1024m as a value), and -XX:CMSInitiatingOccupancyFraction=55. NewSize is typically tuned in relationship to the overall heap size so if you specify this parameter you will also need to provide a -Xmx value. A convenient way of specifying this in relative terms is to use -XX:NewRatio. The values we've suggested are only starting points. The actual values will vary depending on the runtime characteristics of the application.
You may also want to refer to the following articles:
See Six Things Everyone Should Know about JE Log Files.
You'll find more about log files in the Getting Started Guide.
The previous FAQ explained the basics of JE log files and the concept of obsolete data. The JE package includes a utility that can be used to measure the utilization level of your log files. DbSpace gives you information about how packed your log files are. DbSpace can be used this way:
$ java -jar je.jar DbSpace usage: java { com.sleepycat.je.util.DbSpace | -jar je.jar DbSpace } -h <dir> # environment home directory [-q] # quiet, print grand totals only [-u] # sort by utilization [-d] # dump file summary details [-V] # print JE version number
For example, you might see this output:
$ java -jar je.jar DbSpace -h <environment directory> -q File Size (KB) % Used -------- --------- ------ TOTALS 18167 60
which says that in this 18Mb environment, 60% of the disk space used is taken by active JE log entries, and 40% is not utilized.
Checkpoints serve to limit the time it takes to re-open a JE environment, and also enable log cleaning, as described in this FAQ. By default, JE executes checkpoints transparently to the application, but it can be useful when troubleshooting to find the location of the checkpoints. For example, lack of checkpointing could explain a lack of log file cleaning
The following unadvertised option to the DbPrintLog utility provides a summary of checkpoint locations, at the end of the utility's output. For example, this command:
java com.sleepycat.je.util.DbPrintLog -h <environment directory> -S
will result in output of this type:
<..snip..> Per checkpoint interval info: lnTxn ln mapLNTxn mapLN end-end end-start start-end maxLNReplay ckptEnd <..snip..> 16,911 0 0 2 2,155,691 2,152,649 3,042 16,911 0x2/0x87ed74 83,089 0 0 2 10,586,792 10,581,048 5,744 83,090 0x3/0x90e19c 0 0 0 0 0 0 0 0 0x3/0x90e19c
The last column indicates the location of the last checkpoint. The first number is the .jdb file and the second number is the offset in the file. In this case, the last checkpoint is in file 00000003.jdb at offset 0x90e19c. The log cleaner can not reclaim space in any .jdb files that follow that location.
Note that DbPrintLog is simply looking at the CkptStart and CkptEnd entries in the log and attempting to derive the checkpoint intervals from those entries. CkptStart can be missing because it was part of a file that was cleaned and deleted. CkptEnd can be missing for the same reason, or because the checkpoint never finished because of an abnormal shutdown.
Note that DbPrintLog -S can consume significant resources. If desired, the -s option can be used to restrict the amount of log analyzed by the utility.
As of Berkeley Db, Java Edition 3.0, the com.sleepycat.collections package is fully compatible with the Java Collections framework. In previous releases, Collections.size() was not supported, and collection iterators had to be explicitly closed. These incompatibilities have been addressed to provide full interoperability with other Java libraries that use the Java Collections Framework interfaces.
In earlier versions, the user had to consider the context any time a StoredCollection is passed to a component that will call its iterator() method. If that component is not aware of the StoredIterator class, naturally it will not call the StoredIterator.close() method. This will cause a leak of unclosed Cursors, which can cause performance problems. For more on this topic, see In earlier versions of the Java collections API, why did iterators returned by the JE collections API need to be explicitly closed by the caller?
If the component cannot be modified to call StoredIterator.close(), the only solution is to copy the elements from the StoredCollection to a standard Java collection, and pass the resulting copy to the component. The simplest solution is to call the StoredCollection.toList() method to copy the StoredCollection to a standard Java ArrayList.
If the StoredCollection is large and only some of the elements need to be passed to the component, it may be undesirable to call the toList() method on the entire collection since that will copy all elements from the database into memory. There are two ways to create a standard Java collection containing only the needed elements:
Let's say you have two databases: a primary database with the key {ID, attribute} and a secondary database with the key {ID}. How can you access all the attributes for a given ID? In other words, how can you access all the duplicate records in the secondary database for a given key?
We must admit at this point that the example given is partially a trick question. In this particular case you can get the attributes for a given ID without the overhead of creating and maintaining a secondary database! If you call SortedMap.subMap(fromKey,toKey) for a given ID in the primary database the resulting map will contain only the attributes you're interested in. For the fromKey pass the ID you're interested in and a zero (or lowest valued) attribute. For the toKey pass an ID one greater than the ID you're interested in (the attribute doesn't matter). Also see the extension method StoredSortedMap.subMap(Object,boolean,Object,boolean) if you would like more control over the subMap operation.
Note that this technique works only if the {ID, attribute} key is ordered. Because the ID is the first field in the key, the map is sorted primarily by ID and secondarily by attribute within ID. This type of sorting works with tuple keys, but not with serial keys. In general serial keys do not provide a deterministic sort order. To use a tuple key using a TupleBinding or another tuple binding class in the com.sleepycat.bind.tuple package.
But getting back to the general question of how to access duplicates, if you have a database with duplicates you can access the duplicates in a number of ways using the collections API: by creating a subMap or subSet for the key in question, as described above, or by using the extension method StoredMap.duplicates(). This is described in [href="" StoredMap.duplicates()], [href=" retrieving by index key tutorial], and using stored collections tutorial.
As of Berkeley DB, Java Edition 3.0, the com.sleepycat.collections package is now fully compatible with the Java Collections framework. In previous releases, Collections.size() was not supported, and collection iterators had to be explicitly closed. These incompatibilities have been addressed to provide full interoperability with other Java libraries that use the Java Collections Framework interfaces.
Using earlier releases, if you obtain an Iterator from a StoredCollection, it is always a StoredIterator and must be explicitly closed. Closing the iterator is necessary to release the locks held by the underlying cursor. To avoid performance problems, is important to close the cursor as soon as it is no longer needed.
Since the Java Iterator interface has no close() method, the close() method on the StoredIterator class must be used. Alternatively, to avoid casting the Iterator to a StoredIterator, you can call the StoredIterator.close(Iterator) static method; this method will do nothing if the argument given is not a StoredIterator.
To ensure that an Iterator is always closed, even if an exception is thrown, use a finally clause. For example:
Iterator i = myStoredCollection.iterator(); try { while (i.hasNext()) { Object o = i.next(); // do some work } } finally { StoredIterator.close(i); }
Persistence is defined in the documentation for the Entity annotation and the following topics are discussed:
Primary keys and sequences are discussed in the documentation for the ] PrimaryKey] annotation and the following general topics about keys are also discussed:
For information about secondary keys and composite keys, see the SecondaryKey annotation and the KeyField annotation.
Entities are stored by primary key in a PrimaryIndex and how to store entities is described in the PrimaryIndex class documentation.
Entities may also be queried and deleted by secondary key using a SecondaryIndex and this is described in the SecondaryIndex class documentation. The SecondaryIndex documentation also discusses the four mappings provided by primary and secondary indexes:
Both PrimaryIndex and SecondaryIndex implement the EntityIndex interface. The EntityIndex documentation has more information about the four mappings along with example data. It also discusses the following general data access topics:
Relationships in the DPL are defined using secondary keys. A secondary key provides an alternate way to lookup entities, and also defines a relationship between the entity and the key. For example, a Person entity with a secondary key field consisting of a set of email addresses defines a One-to-Many relationship between the Person entity and the email addresses. The Person entity has multiple email addresses and can be accessed by any of them.
Optionally a secondary key can define a relationship with another entity. For example, an Employee entity may have a secondary key called departmentName that is the primary key of a Department entity. This defines a Many-to-One relationship between the Employee and the Department entities. In this case we call the departmentName a foreign key and foreign key constraints are used to ensure that the departmentName key is valid.
Both simple key relationships and relationships between entities are defined using the SecondaryKey annotation. This annotation has properties for defining the type of relationship, the related entity (if any), and what action to take when the related entity is deleted.
For more information about defining relationships and to understand how relationships are accessed, see the SecondaryIndex documentation which includes the following topics:
There are two ways that an entity object may refer to another object. In the first approach, called embedding, the referenced object is simply defined as a field of the entity class. The only requirement is the the class of the embedded object be @Persistent. For example:
@Entity class Person { @PrimaryKey long id; String name; Address address; private Person() {} } @Persistent class Address { String street; String city; String state; String country; int postalCode; private Address() {} }
The embedded object is stored in the same record as the entity, in this case in the Person PrimaryIndex. There is no way to access the Address object except by looking up the Person object in its PrimaryIndex and examining the Person.address field. The Address object cannot be accessed independently. If the same Address object is stored in more than one Person entity, a separate copy of the address will be stored in each Person record.
You may wish to access the address independently or to share the address information among multiple Person objects. To do that you must define the Address class as an @Entity and define a relationship between the Person and the Address entities using a secondary key. For example:
@Entity class Person { @PrimaryKey long id; String name; @SecondaryKey(relate=MANY_TO_ONE, relatedEntity=Address.class) long addressId; private Person() {} } @Entity class Address { @PrimaryKey long id; String street; String city; String state; String country; int postalCode; private Address() {} }
With this second approach, the Address is an entity with a primary key. It is stored separately from the Person entity and can be accessed independently. After getting a Person entity, you must lookup the Address by the Person.addressId value in the Address PrimaryIndex. If more than one Person entity has the same addressId value, the referenced Address is effectively shared.
The requirement to make all classes persistent (subclasses and superclasses as well as embedded classes) is documented under "Complex and Proxy Types" in the documentation for the Entity annotation.
There are a couple of reasons for requiring that all persistent classes be annotated with @Persistent when using the annotation entity model (the default entity model).
First, bytecode annotation of persistent classes, to optimize marshaling and un-marshaling, is performed based on the presence of the annotation when the class is loaded. In order for this to work efficiently and correctly, all classes must be annotated.
Second, the annotation is used for version numbering when classes are evolved. For example, if a superclass instance fields change and that source code not under your control, you will have difficulty in controlling evolution of its instance fields. It is for this reason that a PersistentProxy is required when using external classes that cannot be annotated or controlled.
If the source code for a superclass or embedded class is not under your control, you should consider copying the data into your persistent class, or referencing it and using a PersistentProxy to translate the external class to a persistent class that is under your control.
If using JE annotations is undesirable then you may wish to subclass EntityModel and implement a different source of metadata. While annotations are very unobtrusive compared to other techniques such as implementing interfaces or subclassing from a common base class, we understand that they may be undesirable. Note, however, that if you don't use annotations then you won't get the performance benefits of bytecode annotation.
The EJB3-oriented Java Persistence API is SQL-oriented, and could not be fully implemented with Berkeley DB except by adding SQL or some other query language first. There was a public discussion on TheServerSide of this issue during the design phase for the DPL.
Note that it is not just the annotation syntax that is different between DPL and the EJB3 Java Persistence API:
In general, Berkeley DB's advantages are that it provides better performance and a simpler usage model than is possible with an SQL database. To implement the EJB3 Persistence API for Berkeley DB would negate both of these advantages to some degree.
The DbDump and DbLoad utilities can be used to dump and load all Databases in an EntityStore. They can be used to copy, backup or restore the data in a store when you don't wish to copy the entire set of log files in the environment.
The Database Names section of the EntityStore documentation describes how to determine which database names to dump or load.
In addition, it is useful to understand the process for dumping and loading databases in general. Two points are important to keep in mind:
Here is an example of the steps to dump a store from one environment and load the dumped output in a second environment.
Carbonado is an open source Java persistence framework. It is published by Amazon on SourceForge:
Carbonado allows using Berkeley DB C Edition, Berkeley DB Java Edition, or an SQL database as an underlying repository. This is extremely useful when an abstraction that supports an SQL-based backend is a requirement, or when there is a need to synchronize data between Berkeley DB and SQL databases.
Because it supports SQL databases and the relational model, Carbonado provides a different set of features than the DPL. The following feature set comparison may be useful in deciding which API to use.
JE HA replicated applications are by their nature distributed applications that communicate over the network. Attention to proper configuration will help prevent problems that may prove hard to diagnose and rectify in a running distributed environment. The checklist below is intended to help ensure that key configuration issues have been considered from the outset. It's also a good list to revisit in case you do encounter unusual problems after your application has been deployed, in case there were any inadvertent configuration changes.
Also, if multiple machines are in use check that there is a network path between any two machines. Use a network utility like ping to verify that a network path exists.
java -jar je.jar DbGroupAdmin -groupName <group name> -helperHosts <host:port> -dumpGroup | http://www.oracle.com/technetwork/database/database-technologies/berkeleydb/je-faq-096044.html | CC-MAIN-2017-22 | refinedweb | 13,202 | 54.83 |
.
Clicking on a row in the DataGrid control will display both the numeric and string values, for easy copy-paste goodness. Changing the values of the Slider control will change which characters are displayed. By default characters from to Ȁ are displayed.
Download source (ZIP, 1K) | View MXML
<?xml version="1.0" encoding="utf-8"?> <!-- --> <mx:Application xmlns: <mx:Script> <![CDATA[ import mx.collections.ArrayCollection; [Bindable] private var charCodes:ArrayCollection; private function init():void { charCodes = new ArrayCollection(); var i:int; for (i = slider.values[0]; i <= slider.values[1]; i++) { charCodes.addItem({charCodeNum:i, charCodeValue:"" + formatString(i) + ";", charCodeStr:String.fromCharCode(i)}); } } private function formatString(str:Object, minLength:int = 4):String { return ("000000000" + str.toString()).substr(-minLength); } ]]> </mx:Script> <mx:VBox> <mx:DataGrid <mx:columns> <mx:DataGridColumn <mx:DataGridColumn </mx:columns> </mx:DataGrid> <mx:HBox <mx:HSlider <mx:Label </mx:HBox> </mx:VBox> <mx:Label </mx:Application>
View source is enabled in the following example.
Update 2007/09/01: I just discovered another trick today. You can use custom XML entities which allow you to use “©” from within your Flex applications instead of “©” or “©”:
<?xml version="1.0" encoding="utf-8"?> <!-- --> <!DOCTYPE example[ <!ENTITY copy "©"> ]> <mx:Application xmlns: <mx:Label </mx:Application>
Update 2008/08/19: You can also use special characters in your Flex applications using the following syntax:
© (MXML),
© (MXML), and
\u00A9 (ActionScript), as seen in the following example:
<?xml version="1.0" encoding="utf-8"?> <!-- --> <mx:Application <mx:Script> <![CDATA[ private function init():void { btn3. <mx:Button <mx:Button </mx:Application>
View source is enabled in the following example.
24 thoughts on “Using special characters in your Flex applications”
Nice to see this sample. Thanks!
But as I know we can directly use Unicode chars without any need of any kind of replacement if you have the right font.
The translation between &#xxxx; and characters seems to be done at compile time, most likely by the XML parser. This is a bummer if you load data from a database and want to display some special characters.
I’ve been desperately trying to create a currency formatter which gets it’s currency symbol via a remote object call to display a € (Euro symbol, char code 8364). Can’t get it to work… all I get is a â (a with circumflex).
Your method works fine if I do this:
But not if I do this:
(and because of that, loading a string containing “€″ obviously wouldn’t work either)
You would have to do this (which doesn’t work so well when you load your data externally, it’s not feasible to scan through all text looking for entities):
As it is I have given up, other currencies are written with their three-letter abbreviations anyway, so writing EUR 33.00 is perfectly fine. However, it would look so much better with a proper €. If you have any similiar ideas of how to get special characters to work in an even more general way I would be very interested.
Theo,
How is it not working?
If I try this in my MXML document it seems to work:
Also, if I load a remote document (content.txt) it looks like it parses that € character properly (as long as I set the
htmlTextproperty and not the
textproperty). Observe:
And my content.txt file looks like:
Is that roughly what you were looking for, or did I totally misunderstand?
Peter (who hopes the formatting for this turned out)
Yes, it works in a MXML document, because the XML parser translates € into €, but it doesn’t work if you put the € in ActionScript code, or if you load it using remote objects. Like this (in an .as or a script tag):
That will display the literal string in the text field, however
works fine.
I hadn’t considered htmlText though, good idea. It should work regardless.
To properly display the euro character from strings got via a RemoteObject (using AMFPHP) I simply used this line of code :
And oddly enough, this works…
Instead of a weird square character, I get the nice ‘€’ one!
nice! It is also critical that you have the special characters embedded in the font you’re using.
Well, no…
At least not for my snippet.
Hi.
Just looking for a special character for a “does not equal” eg. an equals sign with a slash going through it…do you have any idea if one exists? Thanks
Jack,
On Windows you can use charmap.exe to find all sorts of special characters and their unicode values (which may or may not be different/available, depending on which font you’re using).
The character you want is “Not Equal To”, and is U+2260: ࣔ
Peter
Hi Peter,.
Can you please help me on this ?
Thanks.
Ty for this its prolly the best resource on the web for these codes. I’m surprised Adobe hasn’t provided better. I would normally consider that their responsibility. Ty again.
Could you pls let me know how to handle the HTTP request paramters which has special characters like – (hyphen).
username
the parameter user-name has a special character -.
How to handle this.
pls help.
Could you pls let me know how to handle the HTTP request paramters which has special characters like – (hyphen).
the parameter user-name has a special character -.
How to handle this.
pls help.
Really very use full.
Thanks for this article.
If u use embededd fonts in your app – take a look at this article. Any idea as to what might be causing the problem. First of all am I using the correct unicode range?
I also tried with String.fromCharCode(8364) , for euro it works fine but not for any other currency symbols
Thanks
Saj.
Problem with different currency symbols not getting displayed is resolved. I was using a wrong unicode range. As peterd said earlier the best way to check the unicode range is through charmap.exe (Windows. Just run this from your windows run command). When I used unicode range U+0021-U+FFFC things started working fine.
Thanks
Saj.
Hi Saj,
I have the same problem. Can you help me on this. how did you resolved this.
Please do post the same, if you have a sample.
Admiring the time and effort you put into your blog and detailed information you offer! I will bookmark your blog and have my children check up here often. Thumbs up!
Great info here!
I need to display Math equations and Chemical formulas in a Spark (Adobe Flex 4) text control. Can someone tell me what my options are?
Thanks!
Hey. This works like a charm ;)
static private var entityMap:Object = { ‘ ’:' ’, ‘¡’:'¡’, ‘¢’:'¢’, ‘£’:'£’, ‘¤’:'¤’, ‘¥’:'¥’, ‘¦’:'¦’, ‘§’:'§’, ‘¨’:'¨’, ‘©’:'©’, ‘ª’:'ª’, ‘«’:'«’, ‘¬’:'¬’, ‘’:'’, ‘®’:'®’, ‘¯’:'¯’, ‘°’:'°’, ‘±’:'±’, ‘²’:'²’, ‘³’:'³’, ‘´’:'´’, ‘µ’:'µ’, ‘¶’:'¶’, ‘·’:'·’, ‘¸’:'¸’, ‘¹’:'¹’, ‘º’:'º’, ‘»’:'»’, ‘¼’:'¼’, ‘½’:'½’, ‘¾’:'¾’, ‘¿’:'×’:'×’, ‘Ø’:'Ø’, ‘Ù’:'Ù’, ‘Ú’:'Ú’, ‘Û’:'Û’, ‘Ü’:'Ü’, ‘Ý’:'Ý’, ‘Þ’:'Þ’, ‘ß’:'÷’:'÷’, ‘ø’:'ø’, ‘ù’:'ù’, ‘ú’:'ú’, ‘û’:'û’, ‘ü’:'ü’, ‘ý’:'ý’, ‘þ’:'þ’, ‘ÿ’:'ÿ’, ‘ƒ’:'Σ’:'Σ’, ‘Τ’:'Τ’, ‘Υ’:'Υ’, ‘Φ’:'Φ’, ‘Χ’:'Χ’, ‘Ψ’:'Ψ’, ‘Ω’:'ς’:'ς’, ‘σ’:'σ’, ‘τ’:'τ’, ‘υ’:'υ’, ‘φ’:'φ’, ‘χ’:'χ’, ‘ψ’:'ψ’, ‘ω’:'ω’, ‘ϑ’:'ϑ’, ‘ϒ’:'ϒ’, ‘ϖ’:'ϖ’, ‘•’:'•’, ‘…’:'…’, ‘′’:'′’, ‘″’:'″’, ‘‾’:'‾’, ‘⁄’:'⁄’, ‘℘’:'℘’, ‘ℑ’:'ℑ’, ‘ℜ’:'ℜ’, ‘™’:'™’, ‘ℵ’:'ℵ’, ‘←’:'←’, ‘↑’:'↑’, ‘→’:'→’, ‘↓’:'↓’, ‘↔’:'↔’, ‘↵’:'↵’, ‘⇐’:'⇐’, ‘⇑’:'⇑’, ‘⇒’:'⇒’, ‘⇓’:'⇓’, ‘⇔’:'⇔’, ‘∀’:'∀’, ‘∂’:'∂’, ‘∃’:'∃’, ‘∅’:'∅’, ‘∇’:'∇’, ‘∈’:'∈’, ‘∉’:'∉’, ‘∋’:'∋’, ‘∏’:'∏’, ‘∑’:'∑’, ‘−’:'−’, ‘∗’:'∗’, ‘√’:'√’, ‘∝’:'∝’, ‘∞’:'∞’, ‘∠’:'∠’, ‘∧’:'∧’, ‘∨’:'∨’, ‘∩’:'∩’, ‘∪’:'∪’, ‘∫’:'∫’, ‘∴’:'∴’, ‘∼’:'∼’, ‘≅’:'≅’, ‘≈’:'≈’, ‘≠’:'≠’, ‘≡’:'≡’, ‘≤’:'≤’, ‘≥’:'≥’, ‘⊂’:'⊂’, ‘⊃’:'⊃’, ‘⊄’:'⊄’, ‘⊆’:'⊆’, ‘⊇’:'⊇’, ‘⊕’:'⊕’, ‘⊗’:'⊗’, ‘⊥’:'⊥’, ‘⋅’:'⋅’, ‘⌈’:'⌈’, ‘⌉’:'⌉’, ‘⌊’:'⌊’, ‘⌋’:'⌋’, ‘〈’:'〈’, ‘〉’:'〉’, ‘◊’:'◊’, ‘♠’:'♠’, ‘♣’:'♣’, ‘♥’:'♥’, ‘♦’:'♦’, ‘”‘:’"’, ‘&’:'&’, ”:’>’, ‘Œ’:'Œ’, ‘œ’:'œ’, ‘Š’:'Š’, ‘š’:'š’, ‘Ÿ’:'Ÿ’, ‘ˆ’:'ˆ’, ‘˜’:'˜’, ‘ ’:' ’, ‘ ’:' ’, ‘ ’:' ’, ‘’:'’, ‘’:'’, ‘’:'’, ‘’:'’, ‘–’:'–’, ‘—’:'—’, ‘‘’:'‘’, ‘’’:'’’, ‘‚’:'‚’, ‘“’:'“’, ‘”’:'”’, ‘„’:'„’, ‘†’:'†’, ‘‡’:'‡’, ‘‰’:'‰’, ‘‹’:'‹’, ‘›’:'›’, ‘€’:'€’ };
static public function convertEntities(str:String):String
{
var re:RegExp = /&\w*;/g
var entitiesFound:Array = str.match(re);
var entitiesConverted:Object = {};
var len:int = entitiesFound.length;
var oldEntity:String;
var newEntity:String;
for (var i:int = 0; i < len; i++)
{
oldEntity = entitiesFound[i];
newEntity = entityMap[oldEntity];
if (newEntity && !entitiesConverted[oldEntity])
{
str = str.split(oldEntity).join(newEntity);
entitiesConverted[oldEntity] = true;
}
}
return str;
}
hey i great post!!
i wanted to insert a “” mark in tooltip in flex 4 but dont have a clue how to do it.
and i m using creatTooltip(“sample +someField.text+ text”) function to creat tooltip and inserting text in it.
i want someField.text to b appear as quoted.
thnks in advanced as ur posts are great!!
cheers
In my application, i am not using any specific font, still at some places, i am getting the WON symbol (“\u20A9″) perfectly and at some places, i am getting square boxes.
Why so?
Nishant
In my application, i hav used WON sign, at some places it gets rendered perfectly and at some places it does not. Can anyone tell me , what might be the issue?
Nishant | http://blog.flexexamples.com/2007/08/02/using-special-characters-in-your-flex-applications/ | CC-MAIN-2016-36 | refinedweb | 1,399 | 66.13 |
Today I'm "celebrating" the anniversary of my life with GraphQL in production Rails apps–1 year full of trials and errors, misses and hits, wtf-s and successes.
As an open-source addict, I especially loved working with GraphQL: it's a rather young technology, and hence there is a lot of opportunities for contributions (at least, in Ruby world) and experiments.
And now I'm presenting the result of one such experiment–the
action_policy-graphql gem, which glues together GraphQL Ruby and Action Policy authorization library.
Wait, Action Policy, was ist das*?
* "what is it" in German (I'm listening to Rammstein while writing this post 🎸)
About the same time as I've started working with GraphQL, I've presented a new Ruby authorization library, Action Policy, to the world (at RailsConf 2018).
Action Policy has been extracted from multiple projects I've been working on in the last few years. It's ideologically similar to Pundit (and initially was built on top of it) but provides a bunch of additional features out-of-the-box (and has a very different architecture inside).
One of these features is an ability to provide an additional context on why the authorization check failed–failure reasons tracking.
This feature has been a dark horse for a long time, we barely used it (mostly for debugging purposes) until we started working with GraphQL–that's when the ugly duckling turned into a beautiful swan.
To learn more about Action Policy and its features check out the slides from the most recent talk I gave at Seattle.rb early this year:.
Authorization & GraphQL
Authorization is an act of giving someone official permission to do something (not to be confused with authentication).
Every time we "ask" in our code, "Is a user allowed to do that?" we perform the act of authorization.
When dealing with GraphQL, this question could be divided into more specific ones:
- Is a user allowed to interact with the object (of a specific type or in a particular node of the graph)?
- Is a user allowed to perform this mutation or subscribe to this subscription?
Another related aspect is data scoping: filter collections according to the user's permissions instead of checking every single item.
The
graphql gem provides basic authorization support (via the
#authorized? hook) and scoping support (via the
#scope_items hook): it can be good enough in the beginning but doesn't scale well due to the amount of boilerplate.
That's why I've started the development of
action_policy-graphql gem–to provide a better API for fields authorization and scoping (similar to the one you can see in GraphQL Pro for
pundit and
cancancan). Now we describe our APIs like this:
# field authorization example (`authorize: true`) field :home, Home, null: false, authorize: true do argument :id, ID, required: true end # data scoping using policies (`authorized_scope: true`) field :events, EventType.connection_type, null: false, authorized_scope: true
This implementation uses field extensions internally, which turned out to be more flexible than building on top of the
#authorized? and
#scope_items hooks.
The problem seemed to be solved: it became effortless to use the authorization and scoping rules defined in policy classes in the API to check permissions and raise exceptions ("Access Denied!"). Though the latter one–raising exceptions–wasn't the best way to inform users about the lack of permissions.
What about preventing these exceptions and telling frontend clients, which actions are permitted and not?
Let the client know about its rights
The problem of pushing current user's permissions information down to the client (frontend/mobile application) is not new; it existed years before GraphQL was born.
The problem could be translated into the following question: how to make the client know which actions are allowed to a user (and show/hide specific buttons/links/controls)?
How to solve it?
You may try, for example, to pass only the authorization model (role, permissions set) and implement (i.e., duplicate) the authorization rules client-side. Such duplication is the easiest way to shoot yourself in the foot.
You should rely on a single source of authorization truth.
And this single source of truth is, usually, a server (because that's where you perform the authorization checks themselves).
Thus, we need to transform our policy rules to client-compatible format–for example, JSON object.
Dumping all the possible authorization rules for a user into a JSON object doesn't seem to be a good idea, especially if we have dozens of policy classes. Hopefully, one of the GraphQL advantages is the ability to request only the data you need (and avoid overfetching).
So, we started with the simple idea of adding
canDoSmth boolean fields to our GraphQL types:
class EventType < Types::BaseType # include Action Policy helpers (`authorize!`, `allowed_to?`) include ActionPolicy::Behaviour field :can_destroy, Boolean, null: false def can_destroy # checks the EventPolicy#destroy? rule for the object allowed_to?(:destroy?, object, context: {user: context[:current_user]}) end end
Now a client can ask the server whether it's allowed to delete the event:
query { event(id: $id) { canDestroy # true | false } }
We also added a macro to define authorization fields to reduce the boilerplate:
class EventType < Types::BaseType include ActionPolicy::Behaviour expose_authorization_rules :destroy?, :edit?, :rsvp? end
"Are we there yet?". Nope.
Clients need more context
It turned out that in most cases knowing whether the action is allowed or not (
true or
false) is not enough: we also need to show a notification to the user (or answer the question "Why?"). And in some situations, this message should be different depending on the reason why we disallowed this action.
Consider a simplified example of a rule checking whether a user is allowed to RSVP to the event:
def rsvp? allowed_to?(:show?) && # => User should have an access to this event rsvp_open? && # => RSVP should be open seats_available? # => There must be seats left end
We're most interested in the last two checks (because if a user has no access to the event, it shouldn't ask for permission to RSVP).
When RSVP is closed, we want to show the "RSVP has been closed for this event" message; when no more seats available–"This event is sold out."
How can we get this information from our policy? Using the failure reasons functionality!
We need to change our rule a bit for that:
def rsvp? allowed_to?(:show?) && # wrapping method call into a `check?` method # tracks the failure of this check (i.e. when it returns false) check?(:rsvp_open?) && check?(:seats_available?) end
Now we can retrieve the additional context from the authorization check result:
policy = EventPolicy.new(record: event, user: user) # first, apply the rule policy.apply(:rsvp?) # now we can access the result object and its reasons # for example, details hash contains the checks names grouped # by a policy policy.result.reasons.details #=> {event: [:rsvp_open?]} or {event: [:seats_available?]}
Wait? Details hash? Identifiers? We need human-readable messages!
OK. Here come the Action Policy and i18n integration.
Let's add our message to the locales files:
en: action_policy: policy: event: rsvp?: "You cannot RSVP to this event" rsvp_opened?: "RSVP has been closed for this event" seats_available?: "This event is sold out"
To access the localized messages, you use the
#full_messages method on the result object:
policy.result.reasons.full_messages #=> ["RSVP has been closed for this event"] # to access the top-level (rule) message policy.result.message #=> "You cannot RSVP to this event"
Now go back to GraphQL and enhance our
expose_authorization_rules macro to define a field with an
AuthorizationResult type:
Which contains a
reasons field of a
FailureReasons type:
From the client perspective, it looks like this:
query { event(id: $id) { canDestroy { value # true | false message # top-level message reasons { details # JSON-encoded failure details fullMessages # human-readable messages } } } }
What are the pros of this approach?
- You have a standardized API for fetching the authorization information
- You have a single abstraction layer for dealing with authorization (policy classes)
- Adding authorization rules to the schema is simple (and, thanks to Action Policy testability, testing is simple, too).
And all that functionality you get for free when using
action_policy-graphql gem!
Read more dev articles on!
Discussion
This is amazing! I'll be kicking off a new project in the following weeks/months for a client and I'll take this for a ride. :)
Thanks for the writeup and all the work you did on the gem itself (and action policy)! | https://practicaldev-herokuapp-com.global.ssl.fastly.net/evilmartians/exposing-permissions-in-graphql-apis-with-action-policy-1mfh | CC-MAIN-2020-45 | refinedweb | 1,400 | 53.41 |
/* Debug hooks for GCC. Copyright (C)_DEBUG_H #define GCC_DEBUG_H /* APPLE LOCAL begin opt diary */ #include "input.h" /* Optimization diary messages */ enum debug_od_msg { OD_msg_loop_vectorized, OD_msg_loop_not_vectorized, OD_msg_loop_vectorized_using_versioning, OD_msg_loop_vectorized_using_peeling, OD_msg_loop_not_vectorized_multiple_exits, OD_msg_loop_not_vectorized_bad_data_ref, OD_msg_loop_not_vectorized_unsupported_ops, OD_msg_loop_not_vectorized_data_dep }; /* Optimization diary entry categories */ enum debug_od_category { OD_parm_hint = 0x0001, OD_limit = 0x0002, OD_report = 0x0004, OD_action = 0x0008, OD_hint = 0x0010, OD_command = 0x0020 }; /* APPLE LOCAL end opt diary */ /* This structure contains hooks for the debug information output functions, accessed through the global instance debug_hooks set in toplev.c according to command line options. */ struct gcc_debug_hooks { /* Initialize debug output. MAIN_FILENAME is the name of the main input file. */ void (* init) (const char *main_filename); /* Output debug symbols. */ void (* finish) (const char *main_filename); /* Macro defined on line LINE with name and expansion TEXT. */ void (* define) (unsigned int line, const char *text); /* MACRO undefined on line LINE. */ void (* undef) (unsigned int line, const char *macro); /* Record the beginning of a new source file FILE from LINE number in the previous one. */ void (* start_source_file) (unsigned int line, const char *file); /* Record the resumption of a source file. LINE is the line number in the source file we are returning to. */ void (* end_source_file) (unsigned int line); /* Record the beginning of block N, counting from 1 and not including the function-scope block, at LINE. */ void (* begin_block) (unsigned int line, unsigned int n); /* Record the end of a block. Arguments as for begin_block. */ void (* end_block) ) (tree); /* Record a source file location at (FILE, LINE). */ void (* source_line) (unsigned int line, const char *file); /* Called at start of prologue code. LINE is the first line in the function. This has been given the same prototype as source_line, so that the source_line hook can be substituted if appropriate. */ void (* begin_prologue) (unsigned int line, const char *file); /* Called at end of prologue code. LINE is the first line in the function. */ void (* end_prologue) (unsigned int line, const char *file); /* Record end of epilogue code. */ void (* end_epilogue) (unsigned int line, const char *file); /* Called at start of function DECL, before it is declared. */ void (* begin_function) (tree decl); /* Record end of function. LINE is highest line number in function. */ void (* end_function) (unsigned int line); /* Debug information for a function DECL. This might include the function name (a symbol), its parameters, and the block that makes up the function's body, and the local variables of the function. */ void (* function_decl) (tree decl); /* Debug information for a global DECL. Called from toplev.c after compilation proper has finished. */ void (* global_decl) (tree decl); /* Debug information for a type DECL. Called from toplev.c after compilation proper, also from various language front ends to record built-in types. The second argument is properly a boolean, which indicates whether or not the type is a "local" type as determined by the language. (It's not a boolean for legacy reasons.) */ void (* type_decl) (tree decl, int local); /* Debug information for imported modules and declarations. */ void (* imported_module_or_decl) (tree decl, tree context); /* DECL is an inline function, whose body is present, but which is not being output at this point. */ void (* deferred_inline_function) (tree decl); /* DECL is an inline function which is about to be emitted out of line. The hook is useful to, e.g., emit abstract debug info for the inline before it gets mangled by optimization. */ void (* outlining_inline_function) (tree decl); /* Called from final_scan_insn for any CODE_LABEL insn whose LABEL_NAME is non-null. */ void (* label) (rtx); /* Called after the start and before the end of writing a PCH file. The parameter is 0 if after the start, 1 if before the end. */ void (* handle_pch) (unsigned int); /* Called from final_scan_insn for any NOTE_INSN_VAR_LOCATION note. */ void (* var_location) (rtx); /* APPLE LOCAL begin opt diary */ /* Called to emit optimization diary entry. */ void (* opt_diary_entry) (enum debug_od_msg, expanded_location); /* APPLE LOCAL end opt diary */ /* Called from final_scan_insn if there is a switch between hot and cold text sections. */ void (* switch_text_section) (void); /* This is 1 if the debug writer wants to see start and end commands for the main source files, and 0 otherwise. */ int start_end_main_source_file; }; extern const struct gcc_debug_hooks *debug_hooks; /* The do-nothing hooks. */ extern void debug_nothing_void (void); extern void debug_nothing_charstar (const char *); extern void debug_nothing_int_charstar (unsigned int, const char *); extern void debug_nothing_int (unsigned int); extern void debug_nothing_int_int (unsigned int, unsigned int); extern void debug_nothing_tree (tree); extern void debug_nothing_tree_int (tree, int); extern void debug_nothing_tree_tree (tree, tree); extern bool debug_true_tree (tree); extern void debug_nothing_rtx (rtx); /* APPLE LOCAL opt diary */ extern void debug_nothing_od_msg_loc (enum debug_od_msg, expanded_location); /*2_debug_hooks; extern const struct gcc_debug_hooks vmsdbg_debug_hooks; /* Dwarf2 frame information. */ extern void dwarf2out_begin_prologue (unsigned int, const char *); extern void dwarf2out_end_epilogue (unsigned int, const char *); extern void dwarf2out_frame_init (void); extern void dwarf2out_frame_finish (void); /* Decide whether we want to emit frame unwind information for the current translation unit. */ extern int dwarf2out_do_frame (void); extern void debug_flush_symbol_queue (void); extern void debug_queue_symbol (tree); extern void debug_free_queue (void); extern int debug_nesting; extern int symbol_queue_index; #endif /* !GCC_DEBUG_H */ | http://opensource.apple.com//source/llvmgcc42/llvmgcc42-2335.9/gcc/debug.h | CC-MAIN-2016-40 | refinedweb | 791 | 55.95 |
.
Let’s start with some standard imports:
import numpy as np import matplotlib.pyplot as plt %matplotlib inline Control: Foundations) forms-diagonal elements equal $ \beta $ time the super-diagonal triangular matrix.
- $ U $ is an $ (N+1) \times (N+1) $ upper triangular matrix.
The factorization can be normalized so that the diagonal elements of $ U $ are unity.
Using the LU representation in (9), we obtain
$$ U \bar y = L^{-1} \bar a \tag{10} $$
Since $ L^{-1} $ is lower triangular,-diagonal, and sub-diagonal, the $ LU $ decomposition takes
- $ L $ to be zero except in the diagonal and the leading sub-diagonal.
- $ U $ to be zero except on the diagonal and the super-diagonal.matrix.
import numpy as np import scipy.stats as spst import scipy.linalg as la class LQFilter: def __init__(self, d, h, y_m, r=None, h_eps=None, β=None): """ Parameters ---------- d : list or numpy.array (1-D or a 2-D column vector) The order of the coefficients: [d_0, d_1, ..., d_m] h : scalar Parameter of the objective function (corresponding to the quadratic term) y_m : list or numpy.array (1-D or a 2-D column vector) Initial conditions for y r : list or numpy.array (1-D or a 2-D column vector) The order of the coefficients: [r_0, r_1, ..., r_k] (optional, if not defined -> deterministic problem) β : scalar Discount factor (optional, default value is one) """ self.h = h self.d = np.asarray(d) self.m = self.d.shape[0] - 1 self.y_m = np.asarray(y_m) if self.m == self.y_m.shape[0]: self.y_m = self.y_m.reshape(self.m, 1) else: raise ValueError("y_m must be of length m = {self.m:d}") #--------------------------------------------- # Define the coefficients of ϕ upfront #--------------------------------------------- ϕ = np.zeros(2 * self.m + 1) for i in range(- self.m, self.m + 1): ϕ[self.m - i] = np.sum(np.diag(self.d.reshape(self.m + 1, 1) \ @ self.d.reshape(1, self.m + 1), k=-i ) ) ϕ[self.m] = ϕ[self.m] + self.h self.ϕ = ϕ #----------------------------------------------------- # If r is given calculate the vector ϕ_r #----------------------------------------------------- if r is None: pass else: self.r = np.asarray(r) self.k = self.r.shape[0] - 1 ϕ_r = np.zeros(2 * self.k + 1) for i in range(- self.k, self.k + 1): ϕ_r[self.k - i] = np.sum(np.diag(self.r.reshape(self.k + 1, 1) \ @ self.r.reshape(1, self.k + 1), k=-i ) ) if h_eps is None: self.ϕ_r = ϕ_r else: ϕ_r[self.k] = ϕ_r[self.k] + h_eps self.ϕ_r = ϕ_r #----------------------------------------------------- # If β is given, define the transformed variables #----------------------------------------------------- if β is None: self.β = 1 else: self.β = β self.d = self.β**(np.arange(self.m + 1)/2) * self.d self.y_m = self.y_m * (self.β**(- np.arange(1, self.m + 1)/2)) \ .reshape(self.m, 1) def construct_W_and_Wm(self, N): """ This constructs the matrices W and W_m for a given number of periods N """ m = self.m d = self.d W = np.zeros((N + 1, N + 1)) W_m = np.zeros((N + 1, m)) #--------------------------------------- # Terminal conditions #--------------------------------------- D_m1 = np.zeros((m + 1, m + 1)) M = np.zeros((m + 1, m)) # (1) Constuct the D_{m+1} matrix using the formula for j in range(m + 1): for k in range(j, m + 1): D_m1[j, k] = d[:j + 1] @ d[k - j: k + 1] # Make the matrix symmetric D_m1 = D_m1 + D_m1.T - np.diag(np.diag(D_m1)) # (2) Construct the M matrix using the entries of D_m1 for j in range(m): for i in range(j + 1, m + 1): M[i, j] = D_m1[i - j - 1, m] #---------------------------------------------- # Euler equations for t = 0, 1, ..., N-(m+1) #---------------------------------------------- ϕ = self.ϕ W[:(m + 1), :(m + 1)] = D_m1 + self.h * np.eye(m + 1) W[:(m + 1), (m + 1):(2 * m + 1)] = M for i, row in enumerate(np.arange(m + 1, N + 1 - m)): W[row, (i + 1):(2 * m + 2 + i)] = ϕ for i in range(1, m + 1): W[N - m + i, -(2 * m + 1 - i):] = ϕ[:-i] for i in range(m): W_m[N - i, :(m - i)] = ϕ[(m + 1 + i):] return W, W_m def roots_of_characteristic(self): """ This function calculates z_0 and the 2m roots of the characteristic equation associated with the Euler equation (1.7) Note: ------ numpy.poly1d(roots, True) defines a polynomial using its roots that can be evaluated at any point. If x_1, x_2, ... , x_m are the roots then p(x) = (x - x_1)(x - x_2)...(x - x_m) """ m = self.m ϕ = self.ϕ # Calculate the roots of the 2m-polynomial roots = np.roots(ϕ) # Sort the roots according to their length (in descending order) roots_sorted = roots[np.argsort(abs(roots))[::-1]] z_0 = ϕ.sum() / np.poly1d(roots, True)(1) z_1_to_m = roots_sorted[:m] # We need only those outside the unit circle λ = 1 / z_1_to_m return z_1_to_m, z_0, λ def coeffs_of_c(self): ''' This function computes the coefficients {c_j, j = 0, 1, ..., m} for c(z) = sum_{j = 0}^{m} c_j z^j Based on the expression (1.9). The order is c_coeffs = [c_0, c_1, ..., c_{m-1}, c_m] ''' z_1_to_m, z_0 = self.roots_of_characteristic()[:2] c_0 = (z_0 * np.prod(z_1_to_m).real * (- 1)**self.m)**(.5) c_coeffs = np.poly1d(z_1_to_m, True).c * z_0 / c_0 return c_coeffs[::-1] def solution(self): """ This function calculates {λ_j, j=1,...,m} and {A_j, j=1,...,m} of the expression (1.15) """ λ = self.roots_of_characteristic()[2] c_0 = self.coeffs_of_c()[-1] A = np.zeros(self.m, dtype=complex) for j in range(self.m): denom = 1 - λ/λ[j] A[j] = c_0**(-2) / np.prod(denom[np.arange(self.m) != j]) return λ, A def construct_V(self, N): ''' This function constructs the covariance matrix for x^N (see section 6) for a given period N ''' V = np.zeros((N, N)) ϕ_r = self.ϕ_r for i in range(N): for j in range(N): if abs(i-j) <= self.k: V[i, j] = ϕ_r[self.k + abs(i-j)] return V def simulate_a(self, N): """ Assuming that the u's are normal, this method draws a random path for x^N """ V = self.construct_V(N + 1) d = spst.multivariate_normal(np.zeros(N + 1), V) return d.rvs() def predict(self, a_hist, t): """ This function implements the prediction formula discussed in section 6 (1.59) It takes a realization for a^N, and the period in which the prediction is formed Output: E[abar | a_t, a_{t-1}, ..., a_1, a_0] """ N = np.asarray(a_hist).shape[0] - 1 a_hist = np.asarray(a_hist).reshape(N + 1, 1) V = self.construct_V(N + 1) aux_matrix = np.zeros((N + 1, N + 1)) aux_matrix[:(t + 1), :(t + 1)] = np.eye(t + 1) L = la.cholesky(V).T Ea_hist = la.inv(L) @ aux_matrix @ L @ a_hist return Ea_hist def optimal_y(self, a_hist, t=None): """ - if t is NOT given it takes a_hist (list or numpy.array) as a deterministic a_t - if t is given, it solves the combined control prediction problem (section 7)(by default, t == None -> deterministic) for a given sequence of a_t (either deterministic or a particular realization), it calculates the optimal y_t sequence using the method of the lecture Note: ------ scipy.linalg.lu normalizes L, U so that L has unit diagonal elements To make things consistent with the lecture, we need an auxiliary diagonal matrix D which renormalizes L and U """ N = np.asarray(a_hist).shape[0] - 1 W, W_m = self.construct_W_and_Wm(N) L, U = la.lu(W, permute_l=True) D = np.diag(1 / np.diag(U)) U = D @ U L = L @ np.diag(1 / np.diag(D)) J = np.fliplr(np.eye(N + 1)) if t is None: # If the problem is deterministic a_hist = J @ np.asarray(a_hist).reshape(N + 1, 1) #-------------------------------------------- # Transform the 'a' sequence if β is given #-------------------------------------------- if self.β != 1: a_hist = a_hist * (self.β**(np.arange(N + 1) / 2))[::-1] \ .reshape(N + 1, 1) a_bar = a]) #-------------------------------------------- # Transform the optimal sequence back if β is given #-------------------------------------------- if self.β != 1: y_hist = y_hist * (self.β**(- np.arange(-self.m, N + 1)/2)) \ .reshape(N + 1 + self.m, 1) return y_hist, L, U, y_bar else: # If the problem is stochastic and we look at it Ea_hist = self.predict(a_hist, t).reshape(N + 1, 1) Ea_hist = J @ Ea_hist a_bar = Ea]) return y_hist, L, U, y_bar $
# Set seed and generate a_t sequence np.random.seed(123) n = 100 a_seq = np.sin(np.linspace(0, 5 * np.pi, n)) + 2 + 0.1 * np.random.randn(n) def plot_simulation(γ=0.8, m=1, h=1, y_m=2): d = γ * np.asarray([1, -1]) y_m = np.asarray(y_m).reshape(m, 1) testlq = LQFilter(d, h, y_m) y_hist, L, U, y = testlq.optimal_y(a_seq) y = y[::-1] # Reverse y # Plot simulation results fig, ax = plt.subplots(figsize=(10, 6)) p_args = {'lw' : 2, 'alpha' : 0.6} time = range(len(y)) ax.plot(time, a_seq / h, 'k-o', ms=4, lw=2, alpha=0.6, label='$a_t$') ax.plot(time, y, 'b-o', ms=4, lw=2, alpha=0.6, label='$y_t$') ax.set(title=rf'Dynamics with $\gamma = {γ}$', xlabel='Time', xlim=(0, max(time)) ) ax.legend() ax.grid() plt.show() plot_simulation()
Here’s what happens when we change $ \gamma $ to 5.0
plot_simulation(γ=5)
And here’s $ \gamma = 10 $
plot_simulation(γ=10)} $. | https://python-advanced.quantecon.org/lu_tricks.html | CC-MAIN-2020-40 | refinedweb | 1,524 | 70.8 |
Method Declaration and Method Call in Java Programming
Almost every computer programming language has elements akin to Java’s methods. If you’ve worked with other languages, you may recall terms like subprogram, procedure, function, subroutine, subprocedure, or PERFORM statement. Whatever you call a method in your favorite programming language, it’s a bunch of instructions, collected in one place and waiting to be executed.
Method declaration
A method declaration is a plan describing the steps that Java will take if and when the method is called into action. A method call is one of those calls to action. As a Java developer, you write both method declarations and method calls. This figure shows you the method declaration and the method call from this listing.
package org.allyourcode.myfirstproject; public class MyFirstJavaClass { /** * @param args */ public static void main(String[] args) { javax.swing.JOptionPane.showMessageDialog (null, "Hello"); } }
If you’re being lazy, you can refer to the code in the outer box in the figure as a method. If you’re not being lazy, you can refer to it as a method declaration.
A method declaration is a list of instructions: “Do this, then do that, and then do this other thing.” The declaration in the listing (and in the figure) contains a single instruction.
To top it all off, each method has a name. In the listing, the method declaration’s name is main. The other words — such as public, static, and void — aren’t parts of the method declaration’s name.
A method declaration has two parts: the method header (the first line) and the method body (the rest of it, which is the part surrounded by {} — curly braces), as shown in this figure.
Method call
A method call includes the name of the method being called, followed by some text in parentheses. So the code in the listing contains a single method call:
javax.swing.JOptionPane.showMessageDialog (null, "Hello")
In this code, javax.swing.JOptionPane.showMessageDialog is the name of a method, and null, “Hello” is the text in parentheses.
A Java instruction typically ends with a semicolon, so the following is a complete Java instruction:
javax.swing.JOptionPane.showMessageDialog (null, "Hello");
This instruction tells the computer to execute whatever statements are inside the javax.swing.JOptionPane.showMessageDialog method declaration.
Another term for Java instruction is Java statement, or just statement.
The names of methods
Like many elements in Java, a method has several names, ranging from the shortest name to the longest name and with names in the middle. For example, the code in the listing calls a method whose simple name is showMessageDialog.
In Java, each method lives inside a class, and showMessageDialog lives inside the API’s JOptionPane class. So a longer name for the showMessageDialog method is JOptionPane.showMessageDialog.
A package in Java is a collection of classes. The JOptionPane class is part of an API package named javax.swing. So the showMessageDialog method’s fully qualified name is javax.swing.JOptionPane.showMessageDialog. Which version of a method’s name you use in the code depends on the context.
In Java, a package contains classes, and a class contains methods. A class’s fully qualified name includes a package name, followed by the class’s simple name. A method’s fully qualified name includes a package name, followed by a class’s simple name, followed by the method’s simple name. To separate one part of a name from another, you use a period (or “dot”).
Method parameters
In the listing, this call displays a dialog box:
javax.swing.JOptionPane.showMessageDialog (null, "Hello");
The dialog box has the word Message in its title bar and an i icon on its face. (The letter i stands for information.) Why do you see the Message title and the i icon? For a clue, notice the method call’s two parameters: null and “Hello”.
The effect of the values null and “Hello” depends entirely on the instructions inside the showMessageDialog method’s declaration. You can read these instructions, if you want, because the entire Java API code is available for viewing — but you probably don’t want to read the 2,600 lines of Java code in the JOptionPane class.
Here’s a brief description of the effect of the values null and “Hello” in the showMessageDialog call’s parameter list:
In Java, the value null stands for “nothing.”
In particular, the first parameter null in a call to showMessageDialog indicates that the dialog box doesn’t initially appear inside any other window. That is, the dialog box can appear anywhere on the computer screen. (The dialog box appears inside of “nothing” in particular on the screen.)
In Java, double quotation marks denote a string of characters.
The second “Hello” parameter tells the showMessageDialog method to display the characters Hello on the face of the dialog box.
Even without this description of the showMessageDialog method’s parameters, you can avoid reading the 2,600 lines of Java API code. Instead, you can examine the indispensable Java documentation pages. You can find these documentation pages by visiting the Oracle website’s Java SE Documentation at a Glance page. | https://www.dummies.com/programming/java/method-declaration-and-method-call-in-java-programming/ | CC-MAIN-2019-13 | refinedweb | 860 | 55.74 |
In this tutorial we will check how to obtain the average value of an array, using cpplinq as an Arduino library, running on the ESP32. The tests shown here were performed using an ESP32 board from DFRobot.
Introduction
In this tutorial we will check how to obtain the average value of an array, using cpplinq as an Arduino library, running on the ESP32.
To make the example below slightly more complex, we will chain cpplinq operators to first filter only all the elements of the array that are lesser than 100, and then get the average of those elements.
The tests shown here were performed using an ESP32 board from DFRobot.
The code
The first thing we will do is importing the cpplinq library. After that, we will declare that we will be using the cpplinq namespace.
#include "cpplinq.hpp" using namespace cpplinq;
Moving on to the setup function, we will start by opening a serial connection. We will use it to output the result of our program.
Serial.begin(115200);
Then we will declare an array of integers, which we will first filter and then obtain the average value.
int ints[] = {5,5,2,100,200};
After this, we will need to convert the array to a range object, in order for us to be able to apply the cpplinq operators. We perform this conversion by calling the from_array function, passing as input our array of integers.
from_array(ints)
Then we will filter all the elements of the array that are lesser than 100. To do this, we will leverage the where operator, passing as input a function that implements the filtering criteria.
Recall from previous tutorials that this function will be applied to all elements of the array and it should return true if a given element fills the criteria, and false otherwise. So, our function should return true if the integer is lesser than 100, and false if it is greater or equal.
Note that we are going to use the C++ lambda syntax.
where([](int i) {return i < 100;})
After this, to get the average of the resulting array of filtered elements, we simply need to call the avg operator, without passing anything as input.
avg()
To chain all the previous function calls, we will use the >> operator. Note that the result of the expression tree should be an integer containing the average value of all the elements lesser than 100.
int result = from_array(ints) >> where([](int i) {return i < 100;}) >> avg();
To finalize, we will print to the serial port the result obtained.
Serial.print("Average: "); Serial.println(result);
The final source code can be seen below.
#include "cpplinq.hpp" using namespace cpplinq; void setup() { Serial.begin(115200); int ints[] = {5,5,2,100,200}; int result = from_array(ints) >> where([](int i) {return i < 100;}) >> avg(); Serial.print("Average: "); Serial.println(result); } void loop() {}
Testing the code
To test the code, simply compile it and upload it to your device, using the Arduino IDE. After the procedure finishes, open the serial monitor.
You should get a result similar to figure 1. As can be seen, it corresponds to the average of all the elements lesser than 100. Those elements where 5, 5 and 2. We obtained the value 4, which is the average value.
> | https://techtutorialsx.com/2019/04/25/esp32-arduino-cpplinq-the-average-operator/ | CC-MAIN-2020-40 | refinedweb | 549 | 53.81 |
Agenda
See also: IRC log
Ed to scribe 11/18
<fjh>
Minutes - FJH would like to make one change
<fjh> Group agrees to publish the Best Practices doc as first working draft
<fjh> propose changing resolution to read as "First Public Working Draft"
RESOLUTION: Minutes from 10/20 and 10/21 approved (with minor change as per fjh's comment)
fjh: Can we approve minutes of the 4th?
RESOLUTION: Minutes of 11/4 approved.
fjh: one question: Do we want to
publish the examples?
... need to make a decision today - is with examples OK?
<fjh>
smullan: May be difficult to remove them at this point, embedded in doc...
fjh: We don't want public
publication of the examples.
... but members can have access. But can we agree on Hal's suggestion
... not make the files available to non-members
<brich> +1
fjh: Personal preference would be to publish
pdatta: Critical part of examples already in the doc.
<fjh> brad notes attacks are available for long time, so probably ok to publish
pdatta: but we need to be cautious
<fjh> hal notes if publish, cannot take it back
Hal: Don't see we loose by publishing.
<bhill>
bhill: There are tools for these attacks too
fjh: Notes this is the first draft, not the final.
<bhill>
fjh: Sounds like we're on the fence leaning to the cautious side
RESOLUTION: WG recommends not to publish the example files at this point
<fjh>
fjh: On ECC, only recommend, not MUST at this point, most likely
<shivaram> ECC NIST curves are free of IP as far as I know
<bal> I disagree with the suggestion that ECC only be RECOMMEND, not MUST
klanz: Does anyone know about IP problems with a MUST
fjh: Big item is to make sure 1.1. reflects our discussions so far.
<bal> Standard disclaimer: I'm not an IPR attorney. Having said that, it is my stong belief that MUST for the ECC NIST prime curves (P192, P256, P521) would not require implementers to take any IPR licenses.
<gedgar> is there any wording in NIST documents on IPR considerations for thier curves?
<shivaram> +q
<shivaram> may be get some clarification from Tim Polk @ NIST regarding ECC curves
kyiu: Several problems found with
xsd/DTD in RFCs
... and believes RFC 4050 defines EC point differently than X9.62
... Further issues e.g. with number of support digits.
... and some namespace scoping issues (DTD elements)
... (this is all in Kelvin's email)
<klanz>
<fjh> kelvin notes that converting to base 10 may be inefficient may be preferable to base64 encode, with respect to decimal type
<klanz> * Russian Doll,
<klanz> * Salami Slice,
<klanz> * Venetian Blind or
<klanz> * Garden of Eden
kyui: Working on proposal correcting this and in the ds namespace
<klanz> maybe there a similar techniques for DTD's ... Norm would know ;-)
kyui: also to cover interop with RFC 4050 through a profile
<klanz> I know G. Karlinger
<fjh>
<scribe> ACTION: kyiu to get in touch with RFC 4050 authors [recorded in]
<trackbot> Created ACTION-105 - Get in touch with RFC 4050 authors [on Kelvin Yiu - due 2008-11-18].
<gedgar> Is this an issue, to reconcile RFC 4050 with X9.62 ?
magnus and klanz to help put Kelvin in touch with RFC 4050 authors
<esimon2> Is it possible to automatically generate the DTDs from the schemas (e.g. using XSLT)?
fjh: Let us focus on schema first and worry about the DTD later.
<gedgar> I agree that Schemas are the direction we are going here in Boeing.
<gedgar> I should say that schemas are the direction we are going here in Boeing and it is more useful than DTDs
fjh: Certificates and DER encodings
<bal> +q
fjh: Maybe add attribute to indicate encoding?
<jwray> +q
scantor: Would like future
version make encoding explicit
... do believe that most of non-DER/BER would not be handled. Then we can require DER/BER.
<fjh> scantor notes difficult to profile given complexity of protocol stack and involvement of CA etc
scantor: In terms of future work, combining DER/BER is a reasonable boundary.
bal: Would like to avoid this issue right now, refers to PKIX discussion. Implementations need to be flexible in what they receive/accept.
scantor: Something needs to understand the cert, right?
bal: Not really, because I pass it on.
scantor: Talking about the receiver...
bal: Even then you can ignore
parts of it.
... Today's libraries are very flexible.
scantor: Not convinced of that -
only BER/DER seen.
... My concern is to having to impement support for other codings
bal: Haven't seen this as an issue in practice.
jwray: Maybe draw the line
between BER/DER and other encodings. Have only seen BER
encoded, really.
... You have to touch DER in order to calculate the signature. DER is subset of BER.
... If requirement to support more than DER/BER then that needs to be clearly labeled.
klanz: Maybe a formal request to
our working group. Should we inherit the PKIX problem?
... Canonicalization/encoding issue not just for us, it seems. And it must have been so for several years...
fjh: We can define reqs for XML
signature going forward. E.g. to carry encoding information or
to profile what formats are acceptable.
... Which is different from PKIX issues, IMO.
klanz: But are we the right place to solve it?
<fjh> magnus notes responsibility of signer and receiver, signer gets cert from CA, that might have incorrect encoding, but still usable
<fjh> magnus notes concern of introducing requirement on signer that might break existing implementations
<Zakim> fjh, you wanted to not 11 influence ca
fjh: Three questions: How to move
forward?
... Is the sense that we should not put this in 1.1.
... from the sound of the discussion
... If we profile, will we influence CAs?
klanz: Whatever markup we add, it can only be a hint.
scantor: Don't believe this is
PKIX responsibility and that is this group's
responsibility.
... Going forward, should have a URI that represents the encoding.
<fjh> scantor notes, why not state that content is BER/DER encoded
scantor: Makes life easier for verifiers.
<fjh> smullan notes implementations often assume DER encoded, different issue that multiple encodings in a cert, eg extensions
smullan: We assume DER encoded.
But may handle some parts that are incorrectly encoded. Open to
put something in best practices.
... if a new format took off then nothing would work, most likely and an encoding tag would be required.
fjh: Scott has two proposals: URI
encoding tag in 2.0 + profiling stating that BER/DER
encoding.
... tentatively include and see what feedback we get?
klanz: Also a property on what encoding it was signed in?
<bal> i think it's clear that it has to be signed as DER
+1
<klanz> well, but many implementations verify raw
<klanz> as is
scantor: need to know the encoding in order to verify and make use of.
bal: If you only care about the public key then there are other ways...
scantor: Intend to get back to that too.
klanz: Be aware of the large deployed set of certs that should be used.
<fjh> suggest concrete proposal to recommend BER/DER with flexibility in extensions, also URI encoding tag
<magnus> Actually, extensions is not the only place that will need flexibility.
<klanz>
<fjh>
fjh: If not XSLT processing
within the signature processing, could not we do that outside
of the signature processing?
... Should this be a requirement in the doc?
... can we prevent arbitrary transforms?
klanz: Should be some openness to
app developer, and use XSLT for this.
... Only specific transforms.
fjh: I have a concern, but will take this to list to reconcile.
<klanz> 2. Requirement: The ds:SignatureValue and the ds:SignedInfo shall be
<klanz> verified before the ds:Reference elements. Hence only signed
<klanz> ds:Transforms will be executed.
<klanz> Stylesheets referred to via xsl:include or xsl:import will have to be
<klanz> referred to by a ds:Reference previous to the ds:Reference in question
<klanz> (the one including/importing the other stylesheets).
<fjh>
<scribe> ACTION: magnus to work the text in the proposal to the req doc [recorded in]
<trackbot> Created ACTION-106 - Work the text in the proposal to the req doc [on Magnus Nyström - due 2008-11-18].
magnus: Can this go in 1.next or would it have to wait for 2.0?
scantor: If it is a new type then maybe a separate document namespace that could be used with 1.1 and 2.0
fjh: Raises the question: If own
namespace and separate doc or wait for 2.0?
... Maybe can be split off as separate piece of work and get it out earlier.
<scantor> it is an #other, so it has to be in a separate namespace to add it to the 1.x schema
<magnus> Yes, you're right, Scott.
<fjh> Example file and empty XPath
<fjh>
fjh: Maybe leave for a while to get feedback from public review?
<fjh> konrad notes references on key lengths etc RSA-PSS paper
<fjh> Profiling XPath for XML Schema
<fjh>
<fjh> XSL Streaming
<fjh>
fjh: Any volunteer to look at this?
<scribe> ACTION: pdatta to look at XSL streaming [recorded in]
<trackbot> Created ACTION-107 - Look at XSL streaming [on Pratik Datta - due 2008-11-18].
<fjh> XPointer element scheme
<fjh>
klanz: Xpointer element scheme could be a simple yet rich way of selecting document subtrees
<scantor> +1
klanz: would not need transform chains at all.
scantor: Don't reject just because it maybe not can deal with all use cases...?
klanz: Maybe Xpointer element
scheme could be required for 1.1?
... before inventing something why not use it?
<klanz>
<fjh> scantor notes qualified names may not be supported
fjh: Skip transform primitives for now.
<fjh> transform primitives
klanz: Maybe define simple set of transforms primitives?
<fjh>
fjh: If we don't canonicalize, do some of the concerns around WS go away?
klanz: Maybe some things should
be part of transforms, like prefix rewriting.
... Advantages in large set of simple transforms, for app developers
<fjh> ck bal
fjh: Brian has question about level 0, 1 ... is this below the lowest level and other is for Konrad: What's next?
klanz: If we decide for 1.1. a need for WS normalization and backwards compat signatures then this could be useful.
<pdatta> whitespace removal and namespace prefix writing should be attributes of canonilicalization transform
fjh: Please comment on today's discussions items, especially 1.1 and roadmap. | http://www.w3.org/2008/11/11-xmlsec-minutes.html | CC-MAIN-2016-40 | refinedweb | 1,753 | 73.07 |
C++ Break Statement in Loop Program
Hello Everyone!
In this tutorial, we will learn how to demonstrate the concept of break statement in loops, in the C++ programming language.
Code:
#include <iostream> using namespace std; int main() { cout << "\n\nWelcome to Studytonight :-)\n\n\n"; cout << " ===== Program to understand the break keyword ===== \n\n"; // Local variable declaration and initialization: int n = 10; // do loop execution do { cout << "Value of variable n is : " << n << endl; n = n + 1; if (n == 15) { // terminate the loop and execute the next statement following it. cout << "\n\nExecuting the break statement and terminating the loop.\n\n"; break; } } while (n < 20); cout << "The value at which the loop got terminated is : " << n << "\n\n\n"; return 0; }
Output:
We hope that this post helped you develop a better understanding of the concept of break statement in loops, in C++. For any query, feel free to reach out to us via the comments section down below.
Keep Learning : ) | https://studytonight.com/cpp-programs/cpp-break-statement-in-loop-program | CC-MAIN-2021-04 | refinedweb | 162 | 62.51 |
On 30/10/13 17:14, Torsten Bögershausen wrote: > On 2013-10-30 18.01, Vicent Martí wrote: >> On Wed, Oct 30, 2013 at 5:51 PM, Torsten Bögershausen <tbo...@web.de> wrote: >>> There is a name clash under cygwin 1.7 (1.5 is OK) >>> The following "first aid hot fix" works for me: >>> /Torsten >> >> If Cygwin declares its own bswap_64, wouldn't it be better to use it >> instead of overwriting it with our own? > Yes, > this will be part of a longer patch. > I found that some systems have something like this: > > #define htobe64(x) bswap_64(x) > And bswap_64 is a function, so we can not detect it by "asking" > #ifdef bswap_64 > .. > #endif > > > But we can use > #ifdef htobe64 > ... > #endif > and this will be part of a bigger patch. > > And, in general, we should avoid to introduce functions which may have a > name clash. > Using the git_ prefix for function names is a good practice. > So in order to unbrake the compilation error under cygwin 17, > the "hotfix" can be used.
Advertising
heh, my patch (given below) took a different approach, but .... ATB, Ramsay Jones -- >8 -- Subject: [PATCH] compat/bswap.h: Fix redefinition of bswap_64 error on cygwin MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Since commit 452e0f20 ("compat: add endianness helpers", 24-10-2013) the cygwin build has failed like so: GIT_VERSION = 1.8.4.1.804.g1f3748b * new build flags CC credential-store.o In file included from git-compat-util.h:305:0, from cache.h:4, from credential-store.c:1: compat/bswap.h:67:24: error: redefinition of 'bswap_64' In file included from /usr/include/endian.h:32:0, from /usr/include/cygwin/types.h:21, from /usr/include/sys/types.h:473, from /usr/include/sys/unistd.h:9, from /usr/include/unistd.h:4, from git-compat-util.h:98, from cache.h:4, from credential-store.c:1: /usr/include/byteswap.h:31:1: note: previous definition of \ ‘bswap_64’ was here Makefile:1985: recipe for target 'credential-store.o' failed make: *** [credential-store.o] Error 1 Note that cygwin has a defintion of 'bswap_64' in the <byteswap.h> header file (which had already been included by git-compat-util.h). In order to suppress the error, ensure that the <byteswap.h> header is included, just like the __GNUC__/__GLIBC__ case, rather than attempting to define a fallback implementation. Signed-off-by: Ramsay Jones <ram...@ramsay1.demon.co.uk> --- compat/bswap.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compat/bswap.h b/compat/bswap.h index ea1a9ed..b864abd 100644 --- a/compat/bswap.h +++ b/compat/bswap.h @@ -61,7 +61,7 @@ static inline uint32_t git_bswap32(uint32_t x) # define ntohll(n) (n) # define htonll(n) (n) #elif __BYTE_ORDER == __LITTLE_ENDIAN -# if defined(__GNUC__) && defined(__GLIBC__) +# if defined(__GNUC__) && (defined(__GLIBC__) || defined(__CYGWIN__)) # include <byteswap.h> # else /* GNUC & GLIBC */ static inline uint64_t bswap_64(uint64_t val) -- 1.8.4 -- To unsubscribe from this list: send the line "unsubscribe git" in the body of a message to majord...@vger.kernel.org More majordomo info at | https://www.mail-archive.com/git@vger.kernel.org/msg38739.html | CC-MAIN-2017-04 | refinedweb | 523 | 61.83 |
Inline functions in C
By Darryl Gove-Oracle on Jan 28, 2015
Functions declared as
inline are slightly more complex than might be expected. Douglas Walls has provided a chapter-and-verse write up. But the issue bears further explanation.
When a function is declared as
inline it's a hint to the compiler that the function could be inlined. It is not a command to the compiler that the function must be inlined. If the compiler chooses not to inline the function, then the function will be left with a function call that needs to be resolved, and at link time it will be necessary for a function definition to be provided. Consider this example:
#include <stdio.h> inline void foo() { printf(" In foo\n"); } void main() { foo(); }
foo:
$ cc -o in in.c Undefined first referenced symbol in file foo in.o ld: fatal: symbol referencing errors. No output written to in
This can be worked around by adding either "static" or "extern" to the definition of the inline function.
If the function is declared to be a
static inline.
Another approach is to declare the function as
extern inline. In this case the compiler may generate inline code, and will also generate a global instance of the function. Although multiple global instances of the function might be generated in all the object files, only one will be remain in the executable after linking. So declaring functions as
extern inline is more space efficient.
This behaviour is defined by the standard. However, gcc takes a different approach, which is to treat
inline functions by generating a global function and potentially inlining the code. Unfortunately this can cause multiply-defined symbol errors at link time, where the same
extern inline function is declared in multiple files. For example, in the following code both in.c and in2.c include in.h which contains the definition of
extern inline foo()....
$ gcc -o in in.c in2.c ld: fatal: symbol 'foo' is multiply-defined:
The gcc behaviour for functions declared as
extern inline is also different. It does not emit an external definition for these functions, leading to unresolved symbol errors at link time.
For gcc, it is best to either declare the functions as
extern inline and, in additional module, provide a global definition of the function, or to declare the functions as
static inline and live with the multiple local symbol definitions that this produces.
So for convenience it is tempting to use
static inline for all compilers. This is a good work around (ignoring the issue of duplicate local copies of functions), except for an issue around unused code.
The keyword
static:
void error_message(); static inline unused() { error_message(); } void main() { }
Compiling this we get the following error message:
$ cc -O i.c "i.c", line 3: warning: no explicit type given Undefined first referenced symbol in file error_message i.o
Even though the function call exists in code that is not used, there is a link error for the undefined function
error_message(). The same error would occur if
extern inline was used as this would cause a global version of the function to be emitted. The problem would not occur if the function were just declared as
inline because in this case the compiler would not emit either a global or local version of the function. The same code compiles with gcc because the unused function is not generated.
So to summarise the options:
- Declare everything
static inline, and ensure that there are no undefined functions, and that there are no functions that call undefined functions.
- Declare everything
inlinefor Studio and
extern inlinefor gcc. Then provide a global version of the function in a separate file. | https://blogs.oracle.com/d/tags/inline | CC-MAIN-2015-14 | refinedweb | 619 | 55.44 |
A simple and highly customisable star rating component for Vue
Star Rating Component for Vue 2.x
Need more than stars? Check out vue-rate-it with hundreds of different raters built in!
A simple, highly customisable star rating component for Vue 2.x.
Features:
- SVG stars - scale without loss of quality.
- Customisable rating increments.
- Customisable colors.
- Customisable number of stars.
- Create read-only stars.
Usage
Via NPM
Install via npm:
npm install vue-star-rating
Then require in your project:
var StarRating = require('vue-star-rating');
or ES6 syntax:
import StarRating from 'vue-star-rating'
Then you can register the component globally:
Vue.component('star-rating', StarRating);
Or in your
Vue component:
components: { StarRating }
You can then use the following markup in your project:
<star-rating></star-rating>
Via CDN
You may also include
vue-star-rating directly in to your webpage via Unpkg. Simply add the following script tag:
<script src=""></script>
You will need to register the component by doing:
Vue.component('star-rating', VueStarRating.default);
You may also register the component locally via the components option.
Getting Started
To get started with
vue-star-rating you will want to sync the rating values between the component and parent, you can then take a look at the props and custom events section of the docs to customise your
star-rating component.
Syncing Rating Values with V-Model for Vue 2.2 +
vue-star-rating supports
v-model when using Vue 2.2 and above, which is the simplest way to keep your ratings in sync:
<star-rating</star-rating>
See this example on JSFiddle
Syncing Rating Values when using Vue 2.1.x and below
If you are using Vue 2.1.x or below the following is the equivelent to the
v-model example above:
<star-rating @</star-rating>
See this example on JSFiddle
Docs
Props
The following props can be passed to the component:
General Props
These props provide general functionailty to the star rating component
Style Props
These props are used to style the star rating component
Important: Vue requires you to pass numbers and boolean values using
v-bind, any props that require a number or bool should use
v-bind: or the colon (
:) shorthand.
Props Example
<star-rating v-bind: </star-rating>
Custom Events
vue-star-rating fires the following custom events, simply use
v-on:event or the
@ shortand to capture the event.
Custom Events Example
<star-rating @</star-rating>
Then in your view model:
new Vue({ el: '#app', methods: { setRating: function(rating){ this.rating= rating; } }, data: { rating: 0 } });
Note: When writing methods to capture custom events, the rating param is automatically passed to the method. If you need to declare methods with multiple paramaters you will need to use
$event to pass the rating to the method:
<star-rating @</star-rating>
IE9 Support
vue-star-rating supports IE 9+; make sure you place the following in the
head of your webpage to ensure that IE is in standards mode:
<meta http- | https://vuejsexamples.com/a-simple-and-highly-customisable-star-rating-component-for-vue/ | CC-MAIN-2019-22 | refinedweb | 501 | 51.18 |
How to reverse a string with C# .NET
October 28, 2020 2 Comments
This is a straightforward and basic task to implement: given a string input to a function we want to return its reverse.
There’s a wide range of solutions to this problem and here we’ll go through 3 of them using C#:
- the built-in
Reverseextension function
- the
AggregateLINQ operator
- bare-bones solution based on a for-loop
Here are the three implementations:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Algorithms { public class StringReverse { public string ReverseString(string input) { return ReverseStringWithReverse(input); //return ReverseStringWithAggregate(input); //return ReverseStringWithLoop(input); } private string ReverseStringWithReverse(string input) { var reverse = input.Reverse(); //return string.Join("", reverse); return string.Concat(reverse); //or in one line string.Concat(input.Reverse()) } private string ReverseStringWithAggregate(string input) { return input.Aggregate("", (c1, c2) => c2 + c1); } private string ReverseStringWithLoop(string input) { string reversed = ""; for (int i = input.Length - 1; i >= 0; i--) { reversed += input[i]; } return reversed; } } }
In
ReverseStringWithReverse we take the incoming string and apply the built-in
Reverse() extension method on it. It returns a collection of
chars, i.e. not the reversed string. To join those chars into a string we can call
string.Join or
string.Concat.
Join takes a delimiter which is an empty string in this case as we don’t want to put any extra character in between the characters when they are joined. The
Concat function is more straightforward to use, we can just pass in the array collection.
In
ReverseStringWithLoop we iterate through the input string starting at the back. We build the reversed string character by character and return the result.
ReverseStringWithAggregate is a bit more “exotic” and uses the
Aggregate LINQ operator. I only put it here in case you’d like to show your familiarity with this accumulator function in an interview. If you don’t know how this operator works then you can check out this post for an example. The empty string is a seed which is basically the starting point for building the reversed string.
This overload of the
Aggregate function will operate on an
IEnumerable<char> as the source string is dissected into its characters. We specified the seed as a string type so the overall result from this extension function will also be a string.
We start with an empty string and apply a function on the source string defined by
(c1, c2) => c2 + c1
This is the accumulator function and accepts two parameters: the first one, i.e.
c1 will be of the same type as the seed, i.e. a string. The second one, i.e.
c2 will be the same type as each element in the dissected string, i.e. a char. The accumulator function returns the same type as the seed, i.e. a string which is simply built up gradually as
c2 + c1
…i.e. take the character and add it to the growing string
c1.
Let’s try to understand this function using the input string “hello”.
So we start with an empty string as
c1 and take the first character from the source char collection, i.e. ‘h’. We get
"" + 'h' = "h" as the resulting string which will be fed as the c1 string input into the next iteration. So next c1 will be “h” and c2 ‘e’ and we return ‘e’ + “h”, i.e. “eh”. “eh” is taken as c1 in the next round and ‘l’ as the character input, ‘l’ + “eh” will give “leh”. The function continues until we arrive at “olleh”. If we set the seed to “world” then that will be value of c1 in the very first iteration and the end result will be “ollehworld”.
It is probably overkill to use the
Aggregate extension for a problem like this but it’s a good opportunity to demonstrate your familiarity with this relatively rarely used function in an interview setting. | https://dotnetcodr.com/tag/net-2/ | CC-MAIN-2021-49 | refinedweb | 661 | 56.66 |
On Sun, Jan 27, 2002 at 05:38:52PM -0600, pac@xxxxxxxxxxxxxx wrote:
> On Mon, Jan 28, 2002 at 10:18:57AM +1100, Keith Owens wrote:
> > >> That is normal with any recent 2.4 kernel, it applies to all
> > >> filesystems, not just XFS. You can even mount different file system
> > > Doesn't this seem BAD for an OS to allow?
> > The Linux VFS gurus have said they want this. If you disagree, please
> > take it up on the vfs or kernel mailing lists, it is out of our
> > control.
>
> Is there any legitimate reason you would want to do this? I dont
> want to scream at them if there is a good reason for it. What is the
> opinion of the FS developers here?
It's for example useful for chroot. You can mount a single file system
in multiple chroots. There is also the related feature of mount --bind
which allows to do the same thing for directories and files. Again
it is useful for chroots.
2.5 also allows you to change that "namespace" per process, extending the
usage outside chroots (that is a feature inspired by plan9)
-Andi | http://oss.sgi.com/archives/xfs/2002-01/msg02607.html | CC-MAIN-2015-27 | refinedweb | 191 | 82.65 |
Suppose we have a range [m, n] where 0 <= m <= n <= 2147483647. We have to find the bitwise AND of all numbers in this range, inclusive. So if the range is [5, 7], then the result will be 4.
To solve this, we will follow these steps −
i := 0
while m is not n, then
m := m/2, n := n / 2, increase i by 1
return m after shifting to the left i times.
Let us see the following implementation to get a better understanding −
#include <bits/stdc++.h> using namespace std; class Solution { public: int rangeBitwiseAnd(int m, int n) { int i = 0; while(m != n){ m >>= 1; n >>= 1; i++; } return m << i; } }; main(){ Solution ob; cout << (ob.rangeBitwiseAnd(5,7)); }
5 7
4 | https://www.tutorialspoint.com/bitwise-and-of-numbers-range-in-cplusplus | CC-MAIN-2021-25 | refinedweb | 126 | 81.83 |
Building a custom key observer to switch layers ↩
- Creating a basic controller object
- Adding a callback function
- Adding an observer for key events
- The event info dictionary
- Observing one particular key
- Switching layers when a key is pressed
- Setting the script as a start-up script
RoboFont has an interface for defining keyboard shortcuts or “Hot Keys” for menu items, the Menu Preferences. With a bit of code, we can also create custom Hot Keys for actions that are not available in the UI.
In this example, we’ll show how to use an observer to make the Glyph Editor jump to the
foreground layer when the
f key is pressed.
Creating a basic controller object
We’ll start by creating a new Python object, using a
class definition.
class JumpToForeground(object): def __init__(self): print("Initialized!") JumpToForeground()
In the above script, a new
__init__. The last line of the script calls the
__init__ function is a special one, you’ll notice that it’s automatically run when the object is constructed — if everything worked correctly you should see a printed output of the word Initialized! showing that the
__init__ function was called.
So here’s the plan — now that we have a definition for a new object, let’s make it do something useful:
- have the object observe for a notification from RoboFont that a key has been pressed
- define a callback function in our object that should be executed when that notification comes in
Adding a callback function
Let’s start by adding the callback function,
keyWasPressed, which will contain the code that should be run when a notification comes in:
class JumpToForeground(object): def __init__(self): print("Initialized!") def keyWasPressed(self, info): print(info) JumpToForeground()
Adding an observer for key events
And then let’s add an observer to listen in for a notification.
To observe for notifications, start by importing
addObserver from
mojo.events at the top of your script, as seen below. Then, instead of simply printing something in the
__init__ function, go ahead and run the
addObserver function at startup.
from mojo.events import addObserver class JumpToForeground(): def __init__(self): addObserver(self, "keyWasPressed", "keyDown") def keyWasPressed(self, info): print(info) JumpToForeground()
You’ll notice that
addObserver needed three arguments:
- the
selfwill tie our new
- the name of the callback function that should be run when the correct notification comes in (in this case
keyWasPressed)
- the name of the notification that we wish to observe for (in this case
keyDown)
I found this
keyDownnotification name by running the Event Observer extension and taking note of the notifications that were broadcast when typing a key when a glyph window was open.
The event info dictionary
Now, when you run the script, nothing will happen at first, but when you press a key down in a glyph window, a dictionary of
info about the event will be printed to the output:
{ 'event': NSEvent: type=KeyDown loc=(476.078,629.277) time=354798.6 flags=0x100 win=0x10b7cb190 winNum=46377 ctxt=0x0 chars="a" unmodchars="a" repeat=0 keyCode=0, 'notificationName': 'keyDown', 'tool': <__main__.ScalingEditTool object at 0x112c82be0>, 'view': <DoodleGlyphView: 0x10b7d64d0>, 'glyph': <RGlyph 'P' ('foreground') at 4621436856> }
There’s a lot going on in there, but there’s really a lot of useful information about what just happened! Among other things, notification lets us know which glyph the event occurred in, and which characters had been typed.
Observing one particular key
We only want to take action when the
f key is pressed, so let’s make a few changes to the script.
from mojo.events import addObserver class JumpToForeground(): def __init__(self): addObserver(self, "keyWasPressed", "keyDown") def keyWasPressed(self, info): event = info["event"] characters = event.characters() if characters == "f": print("f was pressed!") JumpToForeground()
If you run this updated script you’ll notice two things: a message is printed only if you type the
f key, but the entire
info dictionary is still being printed even though we’re not asking for it any longer! This is because our script only uses the
addObserver function and doesn’t
removeObserver yet when it’s no longer needed. So, each time you run the script you’ll be adding yet another copy of the object which will keep running until RoboFont has been quit.
In the end this is what we want, our final script will be run one time on startup and will continue to run in the background waiting for the
keyDown event to happen. But, while you’re working on writing the script you’ll need to restart RoboFont each time you wish to run any revised code to kill off any older versions that are still running in memory.
Once you’ve done that you should notice that the script only responds to the
f key.
Switching layers when a key is pressed
It needs one last thing, we can import the
SetCurrentLayerByName function from
mojo.UI to call when the
f key is pressed:
from mojo.events import addObserver from mojo.UI import SetCurrentLayerByName class JumpToForeground(): def __init__(self): addObserver(self, "keyWasPressed", "keyDown") def keyWasPressed(self, info): event = info["event"] characters = event.characters() if characters == "f": SetCurrentLayerByName("foreground"). | https://doc.robofont.com/documentation/how-tos/building-a-custom-key-observer/ | CC-MAIN-2019-13 | refinedweb | 864 | 54.66 |
Overview
Atlassian Sourcetree is a free Git and Mercurial client for Windows.
Atlassian Sourcetree is a free Git and Mercurial client for Mac.
Squad leader README. When in doubt, you'll probably want to use
@Keep.
Additionally, through the magic of Android AAR libraries, this library contains common recipes for libraries that are out there. When you add this library to your Gradle build, these configurations automatically get applied when ProGuarding your app, which means you need less configuration and less headaches.
Using the library
Squad leader is available on Maven Central, so this should be easy. Just add a dependency to your Gradle build file like this:
dependencies { ... compile 'nl.littlerobots.squadleader:squadleader:<insert-latest-version>' ... }
You can now annotate classes that you do not want to have touched by ProGuard just by annotating the appropriate class, field or method:
import nl.littlerobots.squadleader.Keep; import nl.littlerobots.squadleader.KeepName; public class Example { @KeepName // this field will be stripped if it's unused in your code public String stringTheory; @Keep // this field will be kept, even if it's unused public boolean myBool; }
or
@Keep // this class is not stripped or obfuscated public class Example { public String stringTheory; public boolean myBool; }
ProGuard rules for other libraries will be automatically applied when you run ProGuard as part of a release build.
Contributing
You are very welcome to contribute additional rule files to this project.
If you are a library author and you publish an
.aar, there's no need to contribute here; you can include the ProGuard rules using the (undocumented?)
consumerProguardFiles in your library. Consumers of your library will thank you :)
For libraries that are published as a jar contributions are welcome. When contributing please:
- Add a new rules file under
src/main/rulesand include all ProGuard configuration needed for the library, even if some of that is already in other rules files. The ProGuard rules should be as specific as possible!
- Add the new rule file in
build.gradleto the existing set of rules.
- If possible, extend the
verificationproject so that you can verify that your rule works, by looking at the ProGuard mapping.txt (Suggestions on automating this are very welcome).
- Send a pull request with your changes, describing what it should do.
It's also OK to create an issue if the above is too challenging.
Related projects
The android proguard snippets project already has collected a bunch of ProGuard files to include manually in your project. If you are missing a recipe in Squad Leader, check out that project and file an issue if a particular recipe should be added to this library.
Get in touch
Hit me up on Google+, Twitter or through the contact page on the Little Robots website.
Licence <> | https://bitbucket.org/littlerobots/squadleader | CC-MAIN-2018-34 | refinedweb | 458 | 55.03 |
Is there a way to load a csv file for use inside the load script. I tried to browserify csvtojson npm package. But after browserify i am getting errors inside the browserified javascript file.
How to load a csv file
Hi Braj,
csvtojson uses async JS code and promises, at least since version 2.x, which unfortunately is not currently supported by k6. See issue #882 for details.
You might be able to get v1 of it working, although I found another CSV parsing library which seems to be simpler and works well out-of-the-box with k6 (without Browserify):
You can use it like so:
import Papa from "./papaparse.min.js"; const data = open("./data.csv"); export function setup() { return Papa.parse(data, { header: true }); } export default function(results) { for (let row of results.data) { console.log(`Name: ${row.firstName} ${row.lastName}`) } };
Also note that parsing CSV is relatively straightforward in plain JavaScript, so if you can avoid adding another dependency and write it yourself, that would be preferable in order to reduce memory usage during the test’s runtime and improve overall performance. | https://community.k6.io/t/how-to-load-a-csv-file/251 | CC-MAIN-2019-43 | refinedweb | 186 | 55.84 |
?
Total weight is 490 gr . Can SOLO carry this weight?
is there any SONY QX1 mount available for SOLO ? such as image in previous page ?
where i can find it ?
@Michael Kaba
What to you have to do to set up the QX1 and get its address?
@Jermey Is the WiFI module you all were working on available for purchase?
@Luke run following script:
#!/usr/bin/python
from pysony import SonyAPI
QX_ADDR = '' # camera address
camera = SonyAPI(QX_ADDR)
camera.actTakePicture()
it take a single shot.
@Daniel McKinnon: Hey, love the idea! Ive been trying to figure out how to get the pysony working on my raspberry and could use some help. I'm a little new at python so its probably something really simple. I got the program all installed and I can connect to my QX1 through the WiFi, but when I try to type in a api into the command prompt, it does one of two things. It will either give me the TypeError: string indices must be integers, not str, or it will sit there and try but not give any feed back. Any help is appreciated!
@ Jeremy, thanks for the update on delivery dates. Will your module link to the SOLO's WiFi connection and then use MavLink commands to the SOLO Tx and Android Tablet, I ask as I'm curious to know if there will be any range limits?
@ Justin, yes, I believe the HX90V should work, as it's compatible with Sony's Remote API system. Check out this link that shows all of the cameras that are compatible with our WiFi Map module :
@ Keith Sorry for the late response, we anticipate our WiFi module to be available by mid November. | https://diydrones.com/profiles/blogs/would-you-like-to-capture-professional-quality-photos-with-solo?commentId=7447824%3AComment%3A1405364 | CC-MAIN-2021-49 | refinedweb | 287 | 82.75 |
view raw
So I have an assignment for my C++ class. Basically we have to create a 3x3 multidimensional array, calculate the sum of rows, sum of columns, sum of diagonal values and sum of anti-diagonal values, I usually just input 1 2 3 4 5 6 7 8 9 as values as a starting point.
Now, I'm not trying to be rude but my teacher is not very good, we basically spend 2 hours on a single problem without her doing much explaining. Other than that I started with C++ Primer and Programming: Principles and Practice Using C++ so I believe I'll be able to learn a lot on my own.
Anyhow my questions are probably quite stupid, but if anyone feels like helping, here they are:
for (i = 0; i < row_num; ++i)
for (j = 0; j < col_num; ++j)
if (i + j == row_num - 1)
anti-diagonal += A[i][j];
int sumRows[row_num] = { 0 };
#include "../../std_lib_facilities.h"
#include <iostream>
using namespace std;
#define row_num 3 //no. of rows
#define col_num 3 //no. of columns
int main()
{
int i = 0;
int j = 0;
int diagonal = 0;
int antidiagonal = 0;
int sumRows[row_num] = { 0 };
int sumCol[col_num] = { 0 };
int A[row_num][col_num];
//Input to matrix
for(i=0; i<row_num; i++)
for (j = 0; j < col_num; j++)
{
cout << "A[" << i << "]" << "[" << j << "]: ";
cin >> A[i][j];
sumRows[i] += A[i][j];
sumCol[j] += A[i][j];
}
cout << endl;
//Print out the matrix
for (i = 0; i < row_num; i++)
{
for (j = 0; j < col_num; j++)
cout << A[i][j] << '\t';
cout << endl;
}
//prints sum of rows
for (i = 0; i < row_num; i++)
cout << "Sum of row " << i + 1 << " "<< sumRows[i] << endl;
//prints sum of columns
for (j = 0; j < row_num; j++)
cout << "Sum of column " << j + 1 << " " << sumCol[j] << endl;
//Sum of diagonal values
for (i = 0; i < row_num; i++)
diagonal += A[i][i];
//Sum of antidiagonal values
for (i = 0, j = 2; i < row_num, j >= 0; i++, j--)
antidiagonal += A[i][j];
/*for(i=0; i<row_num; i++)
for (j = 2; j >= 0; j--)
{
antidiagonal += A[i][j];
}
*/
cout << "\nSum of diagonal values: " << diagonal << endl;
cout << "Sum of antdiagonal values: " << antidiagonal << endl;
return 0;
}
1) Your commented out loop sums all values, not just those along the antidiagonal.
2) It is different from your approach in that it will iterate over every value in the matrix, but then it will only add to the total if it detects it is in one of the appropriate cells. Your solution only iterates over the appropriate cells and doesn't have to evaluate any
ifs, so it will be more efficient. However, you need to change your loop condition to
i < row_num && j >= 0. Using a comma here will discard the result of one of the checks.
3)
int sumRows[row_num] = { 0 }; initializes the whole
sumRows array with 0's. | https://codedump.io/share/TX2CsAk0IMfl/1/c-for-loops-and-multidimensional-arrays | CC-MAIN-2017-22 | refinedweb | 477 | 54.19 |
Android: Loading and playing videos from different sources
Posted by Dimitri | Feb 15th, 2011 | Filed under Featured, Programming
.
To load and play videos, we are going to use Android’s VideoView class. The easiest way to do that in Eclipse, is to use the interface editor. Just select the main.xml file and then, drag and drop a VideoView element inside the screen. After that, go to the Properties tab and give it an ID that will be used later to identify the VideoView at the code.
This is how to add the VideoView to the application's interface.
The code to play videos on Android using the VideoView class will always be the same, what differs is the part that loads the videos from a given source. To avoid repeating the same code over and over throughout the post, here’s the basic structure that plays a video file, without the loading part:
/*Imports and package declarations omited*/ public class PlayVideo extends Activity { private VideoView vView; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { //sets the Bundle super.onCreate(savedInstanceState); //sets the context setContentView(R.layout.main); //get the VideoView from the layout file vView = (VideoView)findViewById(R.id.vview); //use this to get touch events vView.requestFocus(); /*This is where you put the code that loads *the video file*/ //... //enable this if you want to enable video controllers, such as pause and forward vView.setMediaController(new MediaController(this)); //plays the movie vView.start(); } }
Here’s how it works: a VideoView variable (vView) is declared at the fourth line. At the moment the Activity is created, the VideoView object is initialized with the data contained at the layout.xml file (line 16).
After that, the Activity requests focus, so the VideoView object can respond to touch events. Then, there’s the part where the video is loaded, which will be explained at the next sections of this post. Lastly, the method setMediaController() is called to display the Play, Pause and Seek buttons at the bottom of the video. This line isn’t required, and you can leave the code without it case you want to hide the playback options from the user. Line 29 sets the video to play when this Activity is launched. Again, this isn’t necessary to make it work, and case you want the video to start paused, simply don’t add this line.
This is how the Activity needs to be set up with the VideoView object to play the video files, now for the loading part…
To load videos from the SD card, we need to put a video file inside it. To add the video file to a SD card of an emulated device, go to the DDMS perspective in Eclipse, a device at the the “Devices” tab, find the ‘sdcard’ folder and then, press the Push file into the device button.
After selecting the device, find the 'sdcard' folder and click the 'Push file into the device' button, as shown.
Just select the video file at the next dialog. Now, to load the video from the SD card and play it, we need to call the setVideoPath method of the vView object, like this:
//load video named "test30fps" video from the root of the SD card vView.setVideoPath("/sdcard/test30fps.mp4");
Replace line 23 in the code at the beginning of the post with the above.
Since the code is going to access the SD card, it is necessary to add a permission to the Android Manifest file:
<uses-permission android:</uses-permission>
Add this line right after the one that contains the android:versionName on it.
Loading images from a the ‘Resources’ folder or a remote server
To load videos from the ‘Resources’ (‘res’) folder, we need to have a video file inside it, at the raw subfolder. If this folder isn’t already there, you must create it. This can be accomplished in Eclipse, by right clicking the res folder and then selecting: New->Folder. Then just drag and drop the video file in there. You will end up with something like this:
The video file has to be placed inside the 'raw' folder.
The method required to load a video from the Resources folder or from a remote location is going to be different – we can’t simply call the setVideoPath() like before. The video is going to be passed as an URI (Uniform Resource Identifier), which is an address to an internet resource. For that, we need to declare a String variable at the beginning of the code, to store the path of the file. Instead, the method that needs be used is the setVideoURI(), which takes an URI as a parameter. So, here’s the code to load a video from the Resources folder.
public class PlayVideo extends Activity { //creates a string to store the video location private String vSource; @Override public void onCreate(Bundle savedInstanceState) { //... //replace line 23 with these lines of code //loads video from the Resources folder //set the video path vSource ="android.resource://fortyonepost.com.vv/" + R.raw.test30fps; //set the video URI, passing the vSourse as a URI vView.setVideoURI(Uri.parse(vSource)); //... } }
To do it from a remote server, a real Android device is going to be required, because loading a video from a remote server doesn’t work on an emulated device. And finally, here’s the code to load a video from a remote server:
public class PlayVideo extends Activity { //creates a string to store the video location private String vSource; @Override public void onCreate(Bundle savedInstanceState) { //... //replace line 23 with these lines of code //loads video from remote server //set the video path vSource ="rtsp://v6.cache1.c.youtube.com/CjYLENy73wIaLQnF4qJzpSt4nhMYESARFEIJbXYtZ29vZ2xlSARSBXdhdGNoYMDFmvL1wMysTQw=/0/0/0/video.3gp"; //set the video URI, passing the vSourse as a URI vView.setVideoURI(Uri.parse(vSource)); //... } }
Don’t forget to add the following line to the Manifest file of the app, so it can access the Internet:
<uses-permission android:</uses-permission>
Add this line right after the one that contains the android:versionName on it.
Note: it is also possible to use URIs to load video files from the SD card. The process is exactly the same, what will change is the path used to create the URI (it must point to the SD card).
Here’s the source code:
Download
thanks..
To add the video file to a SD card of an emulated device..when i press the Push file into the device button.it shows an
error:Failed to push selection: Read-only file system
so please give me suggestions….
I have never seen this happen before. Are you trying to push the file into the root of the SD card? Maybe the folder you are trying to push your video file into doesn’t have the write (w) permission. Under the File Explorer tab, find the Permissions column. What are the permissions there? Is your directory marked as d–rwxr-x?
this code works perfectly…
but when i install apk on emulator….i am geeting this message “sorry,this video cannot played”…
please anyone can helps!
Be sure that you are writing the path right, “android.resource://com.yourpackage/”, i got the same message until i fix that
thanks for this kind of tutorial. keep it up man……..
It says there are 3 errors with the script:
setContentView(R.layout.main); main cannot be resolved or is not a field
(new MediaController(this)); MediaController cannot be resolved to a type
vView = (VideoView)findViewById(R.id.vview); vview cannot be resolved or is not a field
Maybe you need to add the following import:
import android.widget.MediaController;
That should solve the second error. As for the other two, have you added a VideoView to the main.xml file? If not, do it and name it vview. Also, define the package your class is using by typing package plus the name of the package your Activity was placed into, something like: package com.something.example.
If you have already done that, and the errors are still appearing, try this:
– Delete the auto generated R class (inside the “gen” folder)
– On Eclipse select the project folder, and then click on Project->Clean…
Well, I used this to load a video from the resources, and everything works until the video start playing. when I click start on the controller, the video starts, but at the same time I get the “the application has ended unexpectadly” message, and the application crashes.
Great tutorial. In the DDMS i get an error says “buffer count(4) is too low. increase to 12” and the “sorry video cant be displayed.” please help.
i m getting the same problem… buffer count(4) is too smal increased to 12……any answer u get..
When I am trying to give out the url like youtube.com videos it is saying that sorry video cannot be displayed, can i know the reason and wt to be included inorder to play those videos… thank you
The regular Youtube URLs can’t be used with the code featured on this tutorial, because the videos must be encoded on the 3gp format (or any other format compatible with the VideoView). Take a look at the video URL in the PlayVideoRemote Activity.
The URL there was obtained from, and not from.
Hey! Nice tutorial… but I’m having a small problem. I hope you can help me out!
Everything seems to be fine but when the video runs I can only hear the audio and I see a black screen.. The rest is fine, I can even see the media controllers!
That’s weird. I have no idea what could be causing this. Where was the app being executed? On a real or at an emulated device? Has anyone else experienced the same problem?
it will not playing also your link it shows sorry,this video cannot be played.
I get an error message saying the video cannot be played :(
For everyone having problems playing the videos from the SD card using the example project, please keep in mind that the video file must be placed on the root of the SD card before trying to play it. The example app won’t copy the video to the card by itself. Also, be sure to check this comment from Yotes, to make sure the path to the video file is the correct one.
Hi, thanks for the tutorial! Its cool. But i got a problem, everything work perfectly. But my video is not showing, however the background music of my video still can be hear. Just except the video wont appear. Has anyone else experienced the same problem? Please help me :(
Test your application on any mobile, it’ll work fine…..sometimes it does not work on emulator.
Test your application on any mobile, it’ll work fine…..sometimes it does not work on emulator.
Can any one tell how to play sever side videos…
i play the video through this video but i am facing the problem that’s video will not show only audio comes. how to recitifiy this problem as soon as possible my video format is 3gp
plz can any one tell me how to develop live streaming tv in android
i wanna code for live streaming tv in android
Thanks for this tutorial,nice one.
hi
hye…i wanna ask…can it loading video from apps like tiny cam monitor app? | http://www.41post.com/3024/programming/android-loading-and-playing-videos-from-different-sources | CC-MAIN-2019-47 | refinedweb | 1,918 | 71.24 |
This post is the fifth in a series.
In the first two posts, I described some of the core functions for dealing with generic data types:
map,
bind, and so on.
In the third post, I discussed “applicative” vs “monadic” style, and how to lift values and functions to be consistent with each other.
In the previous post, I introduced
traverse and
sequence as a way of working with lists of elevated values.
In this post, we’ll finish up by working through a practical example that uses all the techniques that have been discussed so far.
Here’s a list of shortcuts to the various functions mentioned in this series:
mapfunction
returnfunction
applyfunction
liftNfamily of functions
zipfunction and ZipList world
bindfunction
traverse/
MapMfunction
sequencefunction
filter?
The example will be a variant of the one mentioned at the beginning of the third post:
Let’s break this down into steps:
First we’ll need to transform the urls into a list of actions, where each action downloads the page and gets the size of the content.
And then we need to find the largest content, but in order to do this we’ll have to convert the list of actions into a single action containing a list of sizes.
And that’s where
traverse or
sequence will come in.
Let’s get started!
First we need to create a downloader. I would use the built-in
System.Net.WebClient class, but for some reason it doesn’t allow override of the timeout.
I’m going to want to have a small timeout for the later tests on bad uris, so this is important.
One trick is to just subclass
WebClient and intercept the method that builds a request. So here it is:
// define a millisecond Unit of Measure type [<Measure>] ms /// Custom implementation of WebClient with settable timeout type WebClientWithTimeout(timeout:int<ms>) = inherit System.Net.WebClient() override this.GetWebRequest(address) = let result = base.GetWebRequest(address) result.Timeout <- int timeout result
Notice that I’m using units of measure for the timeout value. I find that units of measure are invaluable to distinguish seconds from milliseconds. I once accidentally set a timeout to 2000 seconds rather than 2000 milliseconds and I don’t want to make that mistake again!
The next bit of code defines our domain types. We want to be able to keep the url and the size together as we process them. We could use a tuple, but I am a proponent of using types to model your domain, if only for documentation.
// The content of a downloaded page type UriContent = UriContent of System.Uri * string // The content size of a downloaded page type UriContentSize = UriContentSize of System.Uri * int
Yes, this might be overkill for a trivial example like this, but in a more serious project I think it is very much worth doing.
Now for the code that does the downloading:
/// Get the contents of the page at the given Uri /// Uri -> Async<Result<UriContent>> let getUriContent (uri:System.Uri) = async { use client = new WebClientWithTimeout(1000<ms>) // 1 sec timeout try printfn " [%s] Started ..." uri.Host let! html = client.AsyncDownloadString(uri) printfn " [%s] ... finished" uri.Host let uriContent = UriContent (uri, html) return (Result.Success uriContent) with | ex -> printfn " [%s] ... exception" uri.Host let err = sprintf "[%s] %A" uri.Host ex.Message return Result.Failure [err ] }
Notes:
Failure.
use client =section ensures that the client will be correctly disposed at the end of the block.
asyncworkflow, and the
let! html = client.AsyncDownloadStringis where the download happens asynchronously.
printfns for tracing, just for this example. In real code, I wouldn’t do this of course!
Before moving on, let’s test this code interactively. First we need a helper to print the result:
let showContentResult result = match result with | Success (UriContent (uri, html)) -> printfn "SUCCESS: [%s] First 100 chars: %s" uri.Host (html.Substring(0,100)) | Failure errs -> printfn "FAILURE: %A" errs
And then we can try it out on a good site:
System.Uri ("") |> getUriContent |> Async.RunSynchronously |> showContentResult // [google.com] Started ... // [google.com] ... finished // SUCCESS: [google.com] First 100 chars: <!doctype html><html itemscope="" itemtype="" lang="en-GB"><head><meta cont
and a bad one:
System.Uri ("") |> getUriContent |> Async.RunSynchronously |> showContentResult // [example.bad] Started ... // [example.bad] ... exception // FAILURE: ["[example.bad] "The remote name could not be resolved: 'example.bad'""]
mapand
applyand
bind
At this point, we know that we are going to be dealing with the world of
Async, so before we go any further, let’s make sure that we have our four core functions available:
module Async = let map f xAsync = async { // get the contents of xAsync let! x = xAsync // apply the function and lift the result return f x } let retn x = async { // lift x to an Async return x } let apply fAsync xAsync = async { // start the two asyncs in parallel let! fChild = Async.StartChild fAsync let! xChild = Async.StartChild xAsync // wait for the results let! f = fChild let! x = xChild // apply the function to the results return f x } let bind f xAsync = async { // get the contents of xAsync let! x = xAsync // apply the function but don't lift the result // as f will return an Async return! f x }
These implementations are straightforward:
asyncworkflow to work with
Asyncvalues.
let!syntax in
mapextracts the content from the
Async(meaning run it and await the result).
returnsyntax in
map,
retn, and
applylifts the value to an
Asyncusing
return.
applyfunction runs the two parameters in parallel using a fork/join pattern. If I had instead written
let! fChild = ...followed by a
let! xChild = ...that would have been monadic and sequential, which is not what I wanted.
return!syntax in
bindmeans that the value is already lifted and not to call
returnon it.
Getting back on track, we can continue from the downloading step and move on to the process of converting the result to a
UriContentSize:
/// Make a UriContentSize from a UriContent /// UriContent -> Result<UriContentSize> let makeContentSize (UriContent (uri, html)) = if System.String.IsNullOrEmpty(html) then Result.Failure ["empty page"] else let uriContentSize = UriContentSize (uri, html.Length) Result.Success uriContentSize
If the input html is null or empty we’ll treat this an error, otherwise we’ll return a
UriContentSize.
Now we have two functions and we want to combine them into one “get UriContentSize given a Uri” function. The problem is that the outputs and inputs don’t match:
getUriContentis
Uri -> Async<Result<UriContent>>
makeContentSizeis
UriContent -> Result<UriContentSize>
The answer is to transform
makeContentSize from a function that takes a
UriContent as input into
a function that takes a
Async<Result<UriContent>> as input. How can we do that?
First, use
Result.bind to convert it from an
a -> Result<b> function to a
Result<a> -> Result<b> function.
In this case,
UriContent -> Result<UriContentSize> becomes
Result<UriContent> -> Result<UriContentSize>.
Next, use
Async.map to convert it from an
a -> b function to a
Async<a> -> Async<b> function.
In this case,
Result<UriContent> -> Result<UriContentSize> becomes
Async<Result<UriContent>> -> Async<Result<UriContentSize>>.
And now that it has the right kind of input, so we can compose it with
getUriContent:
/// Get the size of the contents of the page at the given Uri /// Uri -> Async<Result<UriContentSize>> let getUriContentSize uri = getUriContent uri |> Async.map (Result.bind makeContentSize)
That’s some gnarly type signature, and it’s only going to get worse! It’s at times like these that I really appreciate type inference.
Let’s test again. First a helper to format the result:
let showContentSizeResult result = match result with | Success (UriContentSize (uri, len)) -> printfn "SUCCESS: [%s] Content size is %i" uri.Host len | Failure errs -> printfn "FAILURE: %A" errs
And then we can try it out on a good site:
System.Uri ("") |> getUriContentSize |> Async.RunSynchronously |> showContentSizeResult // [google.com] Started ... // [google.com] ... finished //SUCCESS: [google.com] Content size is 44293
and a bad one:
System.Uri ("") |> getUriContentSize |> Async.RunSynchronously |> showContentSizeResult // [example.bad] Started ... // [example.bad] ... exception //FAILURE: ["[example.bad] "The remote name could not be resolved: 'example.bad'""]
The last step in the process is to find the largest page size.
That’s easy. Once we have a list of
UriContentSize, we can easily find the largest one using
List.maxBy:
/// Get the largest UriContentSize from a list /// UriContentSize list -> UriContentSize let maxContentSize list = // extract the len field from a UriContentSize let contentSize (UriContentSize (_, len)) = len // use maxBy to find the largest list |> List.maxBy contentSize
We’re ready to assemble all the pieces now, using the following algorithm:
Uri list)
Uris into a list of actions (
Async<Result<UriContentSize>> list)
List<Async>into a
Async<List>.
List<Result>into a
Result<List>. But the two bottom parts of the stack are wrapped in an
Asyncso we need to use
Async.mapto do this.
List.maxByon the bottom
Listto convert it into a single value. That is, transform a
List<UriContentSize>into a
UriContentSize. But the bottom of the stack is wrapped in a
Resultwrapped in an
Asyncso we need to use
Async.mapand
Result.mapto do this.
Here’s the complete code:
/// Get the largest page size from a list of websites let largestPageSizeA urls = urls // turn the list of strings into a list of Uris // (In F# v4, we can call System.Uri directly!) |> List.map (fun s -> System.Uri(s)) // turn the list of Uris into a "Async<Result<UriContentSize>> list" |> List.map getUriContentSize // turn the "Async<Result<UriContentSize>> list" // into an "Async<Result<UriContentSize> list>" |> List.sequenceAsyncA // turn the "Async<Result<UriContentSize> list>" // into a "Async<Result<UriContentSize list>>" |> Async.map List.sequenceResultA // find the largest in the inner list to get // a "Async<Result<UriContentSize>>" |> Async.map (Result.map maxContentSize)
This function has signature
string list -> Async<Result<UriContentSize>>, which is just what we wanted!
There are two
sequence functions involved here:
sequenceAsyncA and
sequenceResultA. The implementations are as you would expect from
all the previous discussion, but I’ll show the code anyway:
module List = /// Map a Async producing function over a list to get a new Async /// using applicative style /// ('a -> Async<'b>) -> 'a list -> Async<'b list> let rec traverseAsyncA f list = // define the applicative functions let (<*>) = Async.apply let retn = Async.retn // define a "cons" function let cons head tail = head :: tail // right fold over the list let initState = retn [] let folder head tail = retn cons <*> (f head) <*> tail List.foldBack folder list initState /// Transform a "list<Async>" into a "Async<list>" /// and collect the results using apply. let sequenceAsyncA x = traverseAsyncA id x /// Map a Result producing function over a list to get a new Result /// using applicative style /// ('a -> Result<'b>) -> 'a list -> Result<'b list> let rec traverseResultA f list = // define the applicative functions let (<*>) = Result.apply let retn = Result.Success // define a "cons" function let cons head tail = head :: tail // right fold over the list let initState = retn [] let folder head tail = retn cons <*> (f head) <*> tail List.foldBack folder list initState /// Transform a "list<Result>" into a "Result<list>" /// and collect the results using apply. let sequenceResultA x = traverseResultA id x
It will be interesting to see how long the download takes for different scenarios, so let’s create a little timer that runs a function a certain number of times and takes the average:
/// Do countN repetitions of the function f and print the time per run let time countN label f = let stopwatch = System.Diagnostics.Stopwatch() // do a full GC at the start but not thereafter // allow garbage to collect for each iteration System.GC.Collect() printfn "=======================" printfn "%s" label printfn "=======================" let mutable totalMs = 0L for iteration in [1..countN] do stopwatch.Restart() f() stopwatch.Stop() printfn "#%2i elapsed:%6ims " iteration stopwatch.ElapsedMilliseconds totalMs <- totalMs + stopwatch.ElapsedMilliseconds let avgTimePerRun = totalMs / int64 countN printfn "%s: Average time per run:%6ims " label avgTimePerRun
Let’s download some sites for real!
We’ll define two lists of sites: a “good” one, where all the sites should be accessible, and a “bad” one, containing invalid sites.
let goodSites = [ "" "" "" "" ] let badSites = [ "" "" "" "" ]
Let’s start by running
largestPageSizeA 10 times with the good sites list:
let f() = largestPageSizeA goodSites |> Async.RunSynchronously |> showContentSizeResult time 10 "largestPageSizeA_Good" f
The output is something like this:
[google.com] Started ... [bbc.co.uk] Started ... [fsharp.org] Started ... [microsoft.com] Started ... [bbc.co.uk] ... finished [fsharp.org] ... finished [google.com] ... finished [microsoft.com] ... finished SUCCESS: [bbc.co.uk] Content size is 108983 largestPageSizeA_Good: Average time per run: 533ms
We can see immediately that the downloads are happening in parallel – they have all started before the first one has finished.
Now what about if some of the sites are bad?
let f() = largestPageSizeA badSites |> Async.RunSynchronously |> showContentSizeResult time 10 "largestPageSizeA_Bad" f
The output is something like this:
[example.com] Started ... [bad.example.com] Started ... [verybad.example.com] Started ... [veryverybad.example.com] Started ... [verybad.example.com] ... exception [veryverybad.example.com] ... exception [example.com] ... exception [bad.example.com] ... exception FAILURE: [ "[example.com] "The remote server returned an error: (404) Not Found.""; "[bad.example.com] "The remote name could not be resolved: 'bad.example.com'""; "[verybad.example.com] "The remote name could not be resolved: 'verybad.example.com'""; "[veryverybad.example.com] "The remote name could not be resolved: 'veryverybad.example.com'""] largestPageSizeA_Bad: Average time per run: 2252ms
Again, all the downloads are happening in parallel, and all four failures are returned.
The
largestPageSizeA has a series of maps and sequences in it which means that the list is being iterated over three times and the async mapped over twice.
As I said earlier, I prefer clarity over micro-optimizations unless there is proof otherwise, and so this does not bother me.
However, let’s look at what you could do if you wanted to.
Here’s the original version, with comments removed:
let largestPageSizeA urls = urls |> List.map (fun s -> System.Uri(s)) |> List.map getUriContentSize |> List.sequenceAsyncA |> Async.map List.sequenceResultA |> Async.map (Result.map maxContentSize)
The first two
List.maps could be combined:
let largestPageSizeA urls = urls |> List.map (fun s -> System.Uri(s) |> getUriContentSize) |> List.sequenceAsyncA |> Async.map List.sequenceResultA |> Async.map (Result.map maxContentSize)
The
map-sequence can be replaced with a
traverse:
let largestPageSizeA urls = urls |> List.traverseAsyncA (fun s -> System.Uri(s) |> getUriContentSize) |> Async.map List.sequenceResultA |> Async.map (Result.map maxContentSize)
and finally the two
Async.maps can be combined too:
let largestPageSizeA urls = urls |> List.traverseAsyncA (fun s -> System.Uri(s) |> getUriContentSize) |> Async.map (List.sequenceResultA >> Result.map maxContentSize)
Personally, I think we’ve gone too far here. I prefer the original version to this one!
As an aside, one way to get the best of both worlds is to use a “streams” library that automatically merges the maps for you.
In F#, a good one is Nessos Streams. Here is a blog post showing the difference between streams and
the standard
seq.
Let’s reimplement the downloading logic using monadic style and see what difference it makes.
First we need a monadic version of the downloader:
let largestPageSizeM urls = urls |> List.map (fun s -> System.Uri(s)) |> List.map getUriContentSize |> List.sequenceAsyncM // <= "M" version |> Async.map List.sequenceResultM // <= "M" version |> Async.map (Result.map maxContentSize)
This one uses the monadic
sequence functions (I won’t show them – the implementation is as you expect).
Let’s run
largestPageSizeM 10 times with the good sites list and see if there is any difference from the applicative version:
let f() = largestPageSizeM goodSites |> Async.RunSynchronously |> showContentSizeResult time 10 "largestPageSizeM 108695 largestPageSizeM_Good: Average time per run: 955ms
There is a big difference now – it is obvious that the downloads are happening in series – each one starts only when the previous one has finished.
As a result, the average time is 955ms per run, almost twice that of the applicative version.
Now what about if some of the sites are bad? What should we expect? Well, because it’s monadic, we should expect that after the first error, the remaining sites are skipped, right? Let’s see if that happens!
let f() = largestPageSizeM badSites |> Async.RunSynchronously |> showContentSizeResult time 10 "largestPageSizeM_Bad" f
The output is something like this:
[example.com] Started ... [example.com] ... exception [bad.example.com] Started ... [bad.example.com] ... exception [verybad.example.com] Started ... [verybad.example.com] ... exception [veryverybad.example.com] Started ... [veryverybad.example.com] ... exception FAILURE: ["[example.com] "The remote server returned an error: (404) Not Found.""] largestPageSizeM_Bad: Average time per run: 2371ms
Well that was unexpected! All of the sites were visited in series, even though the first one had an error. But in that case, why is only the first error returned, rather than all the the errors?
Can you see what went wrong?
The reason why the implementation did not work as expected is that the chaining of the
Asyncs was independent of the chaining of the
Results.
If you step through this in a debugger you can see what is happening:
Asyncin the list was run, resulting in a failure.
Async.bindwas used with the next
Asyncin the list. But
Async.bindhas no concept of error, so the next
Asyncwas run, producing another failure.
Asyncs were run, producing a list of failures.
Result.bind. Of course, because of the bind, only the first one was processed and the rest ignored.
Asyncs were run but only the first failure was returned.
The fundamental problem is that we are treating the
Async list and
Result list as separate things to be traversed over.
But that means that a failed
Result has no influence on whether the next
Async is run.
What we want to do, then, is tie them together so that a bad result does determine whether the next
Async is run.
And in order to do that, we need to treat the
Async and the
Result as a single type – let’s imaginatively call it
AsyncResult.
If they are a single type, then
bind looks like this:
meaning that the previous value will determine the next value.
And also, the “swapping” becomes much simpler:
OK, let’s define the
AsyncResult type and it’s associated
map,
return,
apply and
bind functions.
/// type alias (optional) type AsyncResult<'a> = Async<Result<'a>> /// functions for AsyncResult module AsyncResult = module AsyncResult = let map f = f |> Result.map |> Async.map let retn x = x |> Result.retn |> Async.retn let apply fAsyncResult xAsyncResult = fAsyncResult |> Async.bind (fun fResult -> xAsyncResult |> Async.map (fun xResult -> Result.apply fResult xResult)) let bind f xAsyncResult = async { let! xResult = xAsyncResult match xResult with | Success x -> return! f x | Failure err -> return (Failure err) }
Notes:
Async<Result<'a>>directly in the code and it will work fine. The point is that conceptually
AsyncResultis a separate type.
bindimplementation is new. The continuation function
fis now crossing two worlds, and has the signature
'a -> Async<Result<'b>>.
Resultis successful, the continuation function
fis evaluated with the result. The
return!syntax means that the return value is already lifted.
Resultis a failure, we have to lift the failure to an Async.
With
bind and
return in place, we can create the appropriate
traverse and
sequence functions for
AsyncResult:
module List = /// Map an AsyncResult producing function over a list to get a new AsyncResult /// using monadic style /// ('a -> AsyncResult<'b>) -> 'a list -> AsyncResult<'b list> let rec traverseAsyncResultM f list = // define the monadic functions let (>>=) x f = AsyncResult.bind f x let retn = AsyncResult.retn // define a "cons" function let cons head tail = head :: tail // right fold over the list let initState = retn [] let folder head tail = f head >>= (fun h -> tail >>= (fun t -> retn (cons h t) )) List.foldBack folder list initState /// Transform a "list<AsyncResult>" into a "AsyncResult<list>" /// and collect the results using bind. let sequenceAsyncResultM x = traverseAsyncResultM id x
Finally, the
largestPageSize function is simpler now, with only one sequence needed.
let largestPageSizeM_AR urls = urls |> List.map (fun s -> System.Uri(s) |> getUriContentSize) |> List.sequenceAsyncResultM |> AsyncResult.map maxContentSize
Let’s run
largestPageSizeM_AR 10 times with the good sites list and see if there is any difference from the applicative version:
let f() = largestPageSizeM_AR goodSites |> Async.RunSynchronously |> showContentSizeResult time 10 "largestPageSizeM_AR 108510 largestPageSizeM_AR_Good: Average time per run: 1026ms
Again, the downloads are happening in series. And again, the time per run is almost twice that of the applicative version.
And now the moment we’ve been waiting for! Will it skip the downloading after the first bad site?
let f() = largestPageSizeM_AR badSites |> Async.RunSynchronously |> showContentSizeResult time 10 "largestPageSizeM_AR_Bad" f
The output is something like this:
[example.com] Started ... [example.com] ... exception FAILURE: ["[example.com] "The remote server returned an error: (404) Not Found.""] largestPageSizeM_AR_Bad: Average time per run: 117ms
Success! The error from the first bad site prevented the rest of the downloads, and the short run time is proof of that.
In this post, we worked through a small practical example. I hope that this example demonstrated that
map,
apply,
bind,
traverse, and
sequence are not just academic abstractions but essential tools in your toolbelt.
In the next post we’ll working through another practical example, but this time we will end up creating our own elevated world. See you then! | https://fsharpforfunandprofit.com/posts/elevated-world-5/ | CC-MAIN-2020-34 | refinedweb | 3,506 | 57.98 |
#include <Texture.h>
Inheritance diagram for Track::Texture:
Also loads images from a file. Can find the filename from a stream.
Definition at line 26 of file Texture.h.
Load filename from a stream.
Definition at line 22 of file Texture.cpp.
Take given filename.
Definition at line 29 of file Texture.cpp.
Definition at line 36 of file Texture.cpp.
Definition at line 42 of file Texture.cpp.
Bind the texture so it can be used in OpenGL.
Definition at line 52 of file Texture.cpp.
Delete the OpenGL texture object with the given name.
This is static to meet boost::shared_ptr requirements.
Definition at line 69 of file Texture.cpp.
Get a reference to the filename containing the texture's image data.
Definition at line 47 of file Texture.cpp.
Load the file and specify mipmap textures from it.
Definition at line 85 of file Texture.cpp.
Create the OpenGL texture obect.
Definition at line 74 of file Texture.cpp.
Load the texture without binding it.
Loads the image file into an OpenGL texture. After the texture has been loaded, has no effect. Requires an OpenGL context.
Definition at line 61 of file Texture.cpp.
Generated at Mon Sep 6 00:41:19 2010 by Doxygen version 1.4.7 for Racer version svn335. | http://racer.sourceforge.net/classTrack_1_1Texture.html | CC-MAIN-2017-22 | refinedweb | 216 | 72.53 |
H E A L T H Y
L I V I N G
H E A L T H Y
P L A N E T
natural awakenings
magazine
The Better Brain Diet Eat Right to Stay Sharp
Palate Pleasers Six Powerhouse Foods for Kids
Himalayan Salt Himalayan Healing Power
Thyroid Disease The Bold Truth
March 2013 | GoNaturalAwakenings.com
March 2013
1
Live happier, healthier, and more intentionally.
MAY 4-5, 2013 GEORGIA WORLD CONGRESS CENTER Join your peers and spend the weekend listening to some of the most inspiring authors of today in a unique setting at the I Can Do It! Atlanta Georgia Conference.
DOREEN VIRTUE
BRIAN L. WEISS
KRIS CARR
DR. WAYNE W. DYER
CHERYL RICHARDSON
BE ENTERTAINED‌GET EDUCATED. Incredible wisdom from cutting-edge authors and speakers in the mindful spirituality, health, holistic, and sustainability lifestyles movement.
These trendsetting speakers will inspire you with topics like: Personal Transformation Relationships Community Empowerment Spirituality
Health Mindfulness Lifestyle and so much more!
Act Now! Seats are Limited and this Event Will Sell Out!
2
Register online at Call 800-654-5126 or visit
Printed on recycled paper to protect the environment
March 2013
3
Natural Awakenings is your guide to nutrition, fitness, personal growth, sustainable and “green” living, organic food, Buy Local, the Slow Food and Slow Money movements, creative expression, wholistic health care, and products and services that support a healthy lifestyle for people of all ages.
~ Features ~ 12
Publisher Carolyn Rose Blakeslee, Ocala
Editors Sharon Bruckman S. Alison Chabonais Linda Sechrist
Design + Production Stephen Gray-Blancett Carolyn Rose Blakeslee Jessi Miller, Contact Us 352-629-4000 Fax 352-351-5474 GoNaturalAwakenings@gmail.com P.O. Box 1140, Anthony, FL 32617 Subscriptions Mailed subscriptions are available for $36/ year. Digital is free. Pick up the printed version at your local health food stores, area Publix and Sweetbay stores, and other locations—that’s free, too. Natural Awakenings Gainesville/Ocala/The Villages is published every month in full color. 20,000 copies are distributed to health food stores, public libraries, Publix and Sweetbay stores, medical offices, restaurants and cafes, and other locations throughout North Central Florida. Natural Awakenings cannot be responsible for the products or services herein. To determine whether a particular product or service is appropriate for you, consult your family physician or licensed wholistic practitioner.
Gardening Without (Much) Money
by David Y. Goodman, UF/IFAS Master Gardener
14
The Better Brain Diet
by Lisa Marshall
15
The Healing Power of Silence
16
The “WINS” of Change
17
Ceviche
18
Yin & Tonic
by Melody Murphy
Eat Right to Stay Sharp
by Robert Rabbin
by Paula Koger, RN, MA, DOM
by Clark Dougherty, LMT
Home is Where the Heart Is
20
Six Powerhouse Foods for Kids
by Susan Enfield Esrey
With Palate-Pleasing Tips
22
The Bold Truth of Thyroid Disease
23
The Gift of Empathy
by Margret Aldrich
by Dr. Michael J. Badanek, DC, BS, CNS, DACBN
How to Be a Healing Presence
26
The Birthright of Human Beings
28
At Peace in Your Mind
29
The Healing Power of Himalayan Salt
by David Wolf
by Rev. Bill Dodd
by Nuris Lemire, MS, OTR/L, NC
4
Printed on recycled paper to protect the environment
~ Departments ~ NewsBriefs 6 HealthBriefs 8 CommunityResource Guide 30 CalendarofEvents 32 Coupons/Special Offers 39
April in Paris
Advertising & Submissions ADVERTISING n To advertise with us or request a media kit, please call 352-629-4000 or email GoNaturalAwakenings@gmail.com. n Design services are available, FREE (limited time offer). n Advertisers are included online FREE and receive other significant benefits including FREE “Calendar of Events” listings (normally $15 each). n For information on our Coupons/Special Offers page: Visit. EDITORIAL AND CALENDAR SUBMISSIONS n For article submission guidelines, please visit. n Calendar: visit /news.htm. n Email all items to GoNaturalAwakenings@gmail.com. MATERIALS DUE n Deadline for all materials is the 15th of the month (i.e. March 15th for the April issue).
Read us online! n Free, easy, instant access n The same magazine as the print version with enhancements n Ads and story links are hot-linked
April 13-20 Just $3,295/person double occupancy *, INCLUDES n Round-trip air fare Orlando-Paris n Accommodations during our entire stay (no packing and moving) n Guided tours with all admission paid (no waiting in lines) n Two exquisite wine dinners n All group transportation, airport transfers, etc. n and much more—please see website for details. * KING-SIZED BED $3,885/single occupancy Info: 352-286-1779 naturalawakeningsncfl.com/paris.html Still accepting last-minute travelers but please CALL TODAY!
March 2013
5
newsbriefs Gainesville MedSpa Relocates
North Florida Medical Area
G
ainesville MedSpa is the first Chiropractic Health Center to join the North Florida Medical Community. This is the only office providing chiropractic, physical therapy, and massage therapy in this mainstream medical community. After serving the northwest Gainesville community for six years, Dr. Angela Leone and her team of Licensed Massage Therapists have joined the practice of Dr. Lian at the Oriental Healing Center (located behind Red Lobster). Chiropractor Dr. Angela Leone, and leading massage therapist Wendy Noon, are gifted practitioners who use gentle hands-on and instrument techniques to achieve healthy balance for their patients. Massage techniques vary from pregnancy massage to hot stone. Ms. Noon is extending a special offer through April 29, 2013 of $49 for a one-hour massage. She says, “Your specific needs can be met with personalized attention and care. With evenings and weekends available, scheduling is flexible and easy.” Gainesville MedSpa’s new location is 7003 NW 11th Place, Suite 5, Gainesville 352-374-0909. For more information, visit www. gainesvillemedspa.com.
6
Qi Activation
May 25-28, Orlando Convention Center
A
fter 65 events and 40,000 attendees, Qi Activation, formerly known as Qi Revolution, has upgraded the curriculum to what people said in surveys was “most useful in life.” Besides Qigong exercises and breathing techniques, the four-day Qi Activation event will focus on food healing and will devote an hour each to food-based protocols for cancer, diabetes and heart disease. The Qi Activation seminar this year will also introduce Qigong foot reflexology for on-the-spot pain relief and endocrine boosting effects. The clinical applications are in addition to the Qigong/Energy components of the four-day, total immersion experience. Qigong breathing techniques are often described as “the best
natural high” and Qi activator, hence the name of the event. Activation is a biological process and part of enlightenment. The root chakra point, when activated, releases dormant energy (called Kundalini) up the spine, boosting the endocrine system and therefore our longevity. This is perhaps the first longevity conference that speaks about, and facilitates the experience of, the dormant energy hidden within our nervous system. Qigong Practitioner Jeff Primack and 100 other instructors will be leading the group practices. Participants can expect to learn and experience several breathing techniques, Qigong strength training, and more. Special guest, Medical Qigong Master, Jerry Allan Johnson, will speak about the future of energy medicine within the Western model. Other gifted healers and speakers will be in attendance, including American New Thought minister Michael Beckwith. Attendees may participate for one, two, three, or all four days’ training for only $129. The event is non-denominational and open to all people. For therapists, 32 CE hours (massage) and 24 PDA hours (acupuncture) are available. The event is fun, experiential, and educational. Seating is limited. For tickets or more information, call 800298-8970 or visit. com. Be sure to book your hotel early, as it sells out rapidly. Visit www. QiActivation.com for recommended hotels and rates.
Printed on recycled paper to protect the environment
vv.”
NaturalOrder coaching & organizing
Helen Kornblum, MA m, M A Helen Kornblu
Contact me at 352.871.4499 or naturalorder@cox.net to explore how coaching can help your student—and you! ©2012 Natural Order Organizing. All rights reserved.
Neuromuscular Massage by Design Patricia Sutton LMT, NMT, CRT MA22645 Refresh
u Rejuvenate u Revive u Relax Renew u Replenish
• Certified Neuromuscular Massage • Cranial Release Technique • ETPS Acupuncture • Most Insurance Accepted + PIP + WorkerComp • Referrals from Physicians + Chiropractors Accepted
20% Discount:
Pre-Purchase of 4 or More Sessions Treating the pain you were told you would have to live with: Back & neck pain ~ Post-surgical pain ~ Fibromyalgia ~ Migraine ~ TMJ
Call Today (352)
694-4503 1920 SW 20th Place, Suite 202, Ocala FL 34471
March 2013
7.
8
Why We Need More Vitamin C
R
esearchers at the Linus Pauling Institute at Oregon State University, a leading global authority on the role of vitamin C in optimum health, found.
Printed on recycled paper to protect the environment
Yoga at
$10/class, Thursdays
8:30-9:30am Beginning Yoga 9:45-10:45am Chair Yoga
Private Lessons Also Available Annie Osterhout, BS, E-RYT, IAYT
315-698-9749 OsterhoutYoga@yahoo.com
Not So Nice Rice
N
ew research by the nonprofit Consumers Union (CU), which publishes Consumer Reports, may cause us to reconsider what we place in our steamer or cookpot. Rice—a staple of many diets, vegetarian or not—is frequently contaminated with arsenic, a known carcinogen that is also believed to interfere with fetal development. Rice contains more arsenic than grains such as oats or wheat because it is grown in water-flooded conditions, and so more readily absorbs the heavy metal from soil or water than most plants. Even most U.S.-grown rice comes from the south-central region, where crops such as cotton were heavily treated with arsenical pesticides for decades. Thus, some organically grown rice in the region is impacted, as well. CU analysis of more than 200 samples of both organic and conventionally grown rice and rice products on U.S. grocery shelves found that nearly all contained some level of arsenic; many with alarmingly high amounts. There is no federal standard for arsenic in food, but there is a limit of 10 parts per billion in drinking water, and CU researchers found that one serving of contaminated rice may have as much arsenic as an entire day’s worth of water. To reduce the risk of exposure, rinse rice grains thoroughly before cooking and follow the Asian practice of preparing it with extra water to absorb arsenic and/or pesticide residues; and then drain the excess water before serving. See CU’s chart of arsenic levels in tested rice products at Tinyurl.com/ ArsenicReport.
Wainwright’s RAW Milk Glass Ju g
Free-Roaming gs Brown & Pastel Eg
$4.50 plus deposit*
$3.25 dozen*
Massage Reflexology Acupuncture
Now located at the “Yamassee Tribal Trading Post”
“Holistic products for all God’s masterpieces”
352-486-1838 • 380 South Court Street • Bronson • FL License #MM27383
*Raw milk/farm eggs sold for animal consumption per FL law
Reeser’s Nutrition Center, Inc. / ReesersNutritionCenter.com Do you suffer from any of the following symptoms?
n A.D.D.
n
n
n
Parasites n Sinusitis n Candidiasis n Crohn’s Disease n Substance Abuse n Insomnia n Fibromyalgia n Shingles
Cirrhosis of the Liver Immune Disorder n Impotence/Prostrate n Chronic Fatigue Syndrome n Osteoporosis/Arthristis n Menopausal Syndrome n Multiple Sclerosis n High Blood Pressure n Irritable Bowel Syndrome
Free Initial Consultation with CNHP. Offering: n
Nutritional Analysis
n Adrenal/Thyroid
n
Metabolic DHEA REAMS Analysis n Oral Chelation n Gluten Free Foods n Hormone Testing n Detoxification n Vitamins / Herbals n n
Enzyme Therapy Blood Analysis n Alkaline Water n Hair Analysis n Weight Loss n Homeopathic n Saliva Test n Drug Tests n BMI Analysis n
10% Every Day Discounts on Vitamin Supplements (Restrictions Apply) 3243 E. Silver Springs Blvd., Ocala / 352-732-0718 / 352-351-1298
March 2013
9
healthbriefs Dining App for Special-Needs Diets
F
ood be able their meals from restaurants.
E
ating yogurt could reduce the risk of developing high blood pressure (hypertension), according to new research presented at the American Heart Association 2012 Scientific Sessions. During their 15-year study, researchers followed more than 2,000 volunteers who did not initially have high blood pressure and reported on their yogurt consumption at three intervals. Participants who routinely consumed at least one six-ounce cup of low-fat yogurt every three days were 31 percent less likely to develop hypertension.
Bad Fats Are Brain-Busters ew who consumed the highest amounts of saturated fat, such as that found in red meat, exhibited worse overall cognition and memory than peers who ate the lowest amounts. Women who consumed mainly monounsaturated fats, such as olive oil, demonstrated better cognitive scores over time.
10
Waste Water Cuts Fertilizer Use
T
Yogurt Hinders Hypertension
N
Dishpan Plants
he.
Printed on recycled paper to protect the environment
High Springs Emporium The Only Rock Shop in N. Central Florida Chakra balancing among the crystals with Crystal Tone singing bowls - $20 TUCSON TREASURES
Bio-Identical Hormone Replacement Therapy
Uruguay amethyst, Gemmy rhodochrosite and Peruvian epidote; Pakistani green herderite; Arizona chrysocolla; aegerine with smoky quartz from Malawi; huge selection of beautiful spheres & much more!
F
or women experiencing distressing menopause and postmenopause symptoms such as hot flashes, hormone replacement therapy (HRT) is sometimes considered in order to replace waning estrogen and progesterone. However, there are unresolved questions about synthetic HRT, including its potential cause of breast cancer and serious side effects that can include depression, weight gain, and high blood pressure. Most women in the U.S. are unaware of bio-identical hormone replacement therapy (BHRT). BHRT is derived from plant sources, mimics the function of human hormones, and produces significantly fewer side effects. Why do so few health care providers offer BHRT? One simple answer is that natural hormones cannot be patented. Pharmaceutical makers alter estrogen and progesterone molecules from their natural structures; this allows them to obtain patents. It is important to obtain a baseline bone density test and lipid panel (total, HDL, LDL cholesterol and triglycerides) when beginning BHRT. For more information on BHRT, visit
Experience optimal health naturally! 352-291-9459
11115 SW 93rd Ct Rd, Suite 600, Ocala, Florida 34481 Mon, Wed, Thurs, Fri 8 – 5 Tuesday 9-6 Closed every day from 12-1
Stone of the Month - Aquamarine
All Aquamarine 20% off through MARCH!
660 N.W. Santa Fe Blvd. High Springs, FL
386-454-8657
Monday-Saturday 11-6
•
Sunday noon-5
In network BC/BS for acupuncture, chiropractic and massage
Kristin Shiver, DC Dean Chance, DC 507 NW 60th Street, Suite A • Gainesville, FL 32607 • 352-271-1211
BC/BS network
March 2013
11
Gardening Without (Much) Money by David Y. Goodman, UF/IFAS Marion County Master Gardener
“R
eally, when it comes right down to it, gardening costs more money than it saves,” a friend said recently, giving me a knowing look. He continued, “I mean, I suppose if you count in. For. These” tall peppers might feel good, but between transplant shock, light differences, and their often root-bound condition, they’ll often get out-produced by the seeds you plant. For the price of one or two of those pepper transplants, you can buy enough seeds to plant 50 directly into the ground. Now, about those bugs. What do we do with those? Well, there’s this awesome chemical, see, and it’s non-toxic,
12
and it makes cutworms decapitate themselves, vaporizes caterpillars and magically turns aphids into ladybugs … and it’s only $50 a pint … and I’m totally just kidding! We’re not spending money, remember? We need to change our attitude aboutdaboom! Dead! You can also find plenty of info on cheap insect repellents/killers online. Garlic, red pepper, and plain old dish soap Gardeners. Plant and save heirloom seeds. Put up rain barrels. See what’s growing great for your neighbors and plant that. Get seed from the bulk bins at the organic market (that’s where I got my fava beans and rye, among other things). Learn to like okra and zucchini. And never, ever give up. David Goodman is a Master Gardener, writer, musician, artist and father, as well as the creator of FloridaSurvivalGardening.com, an online resource for people who are serious about growing food in Florida.
Printed on recycled paper to protect the environment
Ecological Preserve
Organic Farm
Farm Stead Saturday Every Saturday 9am-3pm
HIGH-FLYING COMEDY
March 21 - April 14
Prince Charm
A ZANY FAIrYtALE
March 9-10 & 16-17
Starter plants for sale Country store: Gifts, books, gourmet spreads and jellies Playground
Now Available in the Store Tracy Lee Farms Grass-Fed Beef Prices vary depending on the cut
March 30, 9-3
Spring Garden Kickoff
Demonstrations, Workshops, 1,500+ seedlings Free admission, $3/workshop
On the Outdoor Stage
April 20, 9-3
Spring Sustainability and Natural Foods Gala Music, Demonstrations, Wonderful food Gift Certifica tes On Sale
$1 admission, $1/food sample Come hungry and expect to have fun!
Cash or checks only. We do not accept credit cards. Please do not bring pets. No smoking on farm. Store Hours 9am-3pm • Open 7 days/week
6411 NE 217th Place Citra, FL Email catcrone@aol.com
Call 352-595-3377 for more information
March 2013
13
The Better Brain Diet
Aim for three weekly servings of fatty fish. Vegetarians can supplement meals with 1,000-1,500 milligrams daily of DHA, says Isaacson.
Eat Right To Stay Sharp by Lisa Marshall
W
ithiterraneantype such as white bread or sugar-
14
sweetened sodas can eventually impair the metabolization of sugar (similar to Type 2 diabetes), causing blood vessel damage and hastened aging. A high-carb diet has also been linked to increased levels of beta-amyloid, a fibrous plaque that harms brain cells. A 2012 Mayo Clinic study of 1,230 people ages 70 to 89 found that those who ate the most carbs had four times the risk of developing MCI than those that ate the least. Inversely, a small study by University of Cincinnati researchers found that when adults with MCI were placed on a low-carb diet for six weeks, their memories improved. Choose fats wisely: Arizona neurologist Dr. Marwan Sabbagh, co-author of The Alzheimer’s Prevention Cookbook, points to numerous studies suggesting a link between saturated fat in cooking oil, cheese and processed meats and increased risk of Alzheimer’s. “In animals, it seems to promote amyloid production in the brain,” he says. In contrast, those who did not. Rich in antioxidant flavonoids, blueberries may even have what Sabbagh calls “specific anti-Alzheimer’s and cell-saving properties.” Isaacson highlights the helpfulness of green leafy vegetables, which are loaded with antioxidants and brainboosting B vitamins. One recent University of Oxford study of 266 elderly people with mild cognitive impairment found that those taking a blend of vitamins B12, B6 and folate daily showed significantly less brain shrinkage over a two-year period than those near Boulder, CO. Connect at Lisa@LisaAnnMarshall.com.
Printed on recycled paper to protect the environment
The Healing Power of Silence by Robert Rabbin
O
ne day I disappeared into reveal another heart that knows how Silence … It was more than to meet life with open arms. Silence grace, an epiphany or a mystiknows that thoughts about life are cal union; it was my soul’s homecoming, not life itself. If we touch life through my heart’s overflowing love, my mind’s Silence, life touches us back intimately eternal peace. In Silence, I experienced and we become one with life itself. freedom, clarity and joy as my true self, Then the mystery, wonder, beauty and felt my core identity and essential nature sanctity becomes our life. Everything as a unity-in-love with all creation, and but wonderment falls away; anger, fear realized it is within this and violence disapessence that we learn When I return from silence pear as if they never to embody healing in existed. our world. Knowing SiI am less than when I lence is knowing our This Silence entered: less harried, self and our world belongs to us all—it for the first time. We is who and what we fearful, anxious and only have to be still are. Selfless silence until that Silence knows only the present egotistical. Whatever the comes forth from moment, this incredwithin to illumiible instant of pure life gift of silence is, it is one nate and embrace when time stops and of lessening, purifying, us, serving as the we breathe the high-alteacher, teaching and titude air we call love. softening. The “I” that path, redeeming and Let us explore Silence as a way of knowing returns is more loving than restoring us in love. In this truthand being, which we filled moment, know, which we are. the “I” who left. we enter our Self Silence is within. fully and deeply. It is within our breath, ~ Rabbi Rami Shapiro We know our own like music between beauty, power and thoughts, the light in magnificence. As the embodiment of our eyes. It is felt in the high arc of birds, the rhythm of waves, the innoSilence, we are perfection itself, a treacence of children, the heart’s deepest sure that the world needs now. Right emotions that have no cause. It is seen now the Universe needs each of us to in small kindnesses, the stillness of be our true Self, expressing the healing nights and peaceful early mornings. power of our heart, in Silence. It is present when beholding a loved one, joined in spirit. As a lifelong mystic, Robert Rabbin is an In Silence, we open to life and innovative self-awareness teacher and life opens to us. It touches the center author of The 5 Principles of Authentic of our heart, where it breaks open to Living. Connect at RobertRabbin.com.
Vegetarian & Regular Cuisine Drawings of Your Spirit Meet your Guides and Angels Aqua-Chi Chair Massage Aura Photography Tarot, Psychic, and Astrological Readings Healing Sessions Ear Candling Merchants Past Life Regression Handmade Jewelry I ncense Rocks From Around the World Candles & MUCH, MUCH MORE WE ARE NOT AFFILIATED WITH ANY OTHER PSYCHIC GATHERINGS
See What Planting A Seed Can Accomplish
Start with your ad in Natural Awakenings magazine and watch your business grow. Natural Awakenings is published monthly in full color and distributed throughout north central Florida, enabling you to reach your target audience. Together we will create the ideal package for your marketing needs. Design is included.
Your Healthy Lifestyle Multimedia Resource in Print, Online and Mobile
FOR RESULTS Call 352-629-4000
March 2013
15
The “WINS” of Change by Dr. Paula Koger, RN, MA, DOM
“We would rather be ruined than change.” —W.H. Auden
O
ur present perception is creating our present and future reality. I call this the Habitual Box. We are in a gridlock, because what is happening in our body, mind, and life is a clear reflection of the hidden mind. Shankar Vedantam, science writer at The Washington Post and author of The Hidden Mind, shares massive amounts of data confirming that subliminal information from media and our surroundings are programming and influencing our unconscious. Do you wonder why it is so difficult to change or get out of the box? According to Dr. Bruce Lipton, cellular biologist and author of The Biology of Perception, 95% of the information that controls our behaviors, choices and cellular function has been locked in the unconscious and becomes what runs our body/mind activities. This becomes our disease. Because the unconscious is such a strong force comprised of memories and data stored in the neurotransmitters and the very memory of cell systems of the body, it is the majority—majority rules. We have been trained by our family dynamics and culture to suffer. Our challenge is how to become the master of our fate, the captain of our soul. Even if we learn to quiet the mind, exercise, and eat right, many things don’t change. Left unresolved, the patterns— according to many experts including Dr.Ryke Hamer—may become cancer and other diseases.
16
Here is how the programmed mind behaves. I had a patient who was responding very well to acupuncture and other modalities for treatment of back pain. In four treatments she was, by her account, 75% improved. Suddenly she announced she was going to have surgery. She had quit what was working, had surgery, and is now in a nursing home. I have often asked myself what causes people to make these choices. It seems obvious we are driven by unconscious needs, habits, and programs. I was with a group of people at a social function who were talking about their illnesses. One man said he was having his sixth surgery for skin cancer. I dared to risk speaking up and said maybe it is time to find out why they are reappearing and do something about the cause. That statement was a “big hit.” Another woman was proudly talking about how much Medicare had paid to fix her eye after three surgeries had failed. She said this as she lit up a cigarette. What shall we do? Shall we leave it as it is and die for our unwillingness to take charge of identifying and releasing the programs, traumas, behaviors, and environmental factors that are causing our limitations? On the other hand, we can enjoy suffering with the masses of sufferers and fit into the Habitual Box by having our own story to tell. We can continue to be sociopolitical robots. I will tell you my story. It is perhaps not like many stories. I am usually not the hit of the party at gatherings where people talk about their illnesses. Most people don’t seem eager to hear I have healed myself
from autoimmune disease, arthritis, elevated cancer indicators, skin cancer, thyroid dysfunction, and Lymes disease, and that I live an active, healthy, productive life as I continue to address the “issues in the tissues” and other factors that contribute to the causes of disease. Many turn a deaf ear when I say thousands of people have improved their health by healing their hidden minds and energy imbalances. Can we afford to federally fund the consequences of unconsciousness? I don’t use my Medicare benefits other than eye exams and annual checkups even though I have paid for these benefits all my life. I will use them eventually if necessary, but it won’t be through self-neglect. Dr. Koger will be presenting a free “How to Change Your Cellular Biology” workshop on March 30th from 3-5pm in Ocala. For details and reservations, call 941-539-4232 (www. WealthOfHealthCenter.com).
TIRED OF SO-SO ADVERTISING RESULTS? BEST DEAL IN THE AREA: Supplement your ad in Natural Awakenings with News Briefs and/or articles. Educate and inform your existing and future customers! CONTACT US FOR DETAILS: 352-629-4000 GoNaturalAwakenings@gmail.com We work for you.
Printed on recycled paper to protect the environment
Ceviche by Clark Dougherty
T
In a medium-sized glass or ceramic (non-reactive) bowl, combine lime juice, lemon juice, ginger and olive oil. Add sliced fresh fish, tossing to coat. Cover and refrigerate for at least 4 hours (overnight is okay). The citric juices will “cook” the fish, which should appear white and opaque. Drain and discard half the liquid from bowl. Mix in cilantro, onion and tomato. Season to taste with salt and pepper. Serve with crispini, hearty crackers, tortilla chips, or toast points; atop thinly sliced baguettes; or on a bed of Romaine lettuce leaves with hard-boiled egg wedges. Enjoy!
his is a popular South American dish made entirely from fresh ingredients. It can be served as an appetizer (dip or spread) or salad. And no, there are no “cooking” instructions— the fish is cured by the citrus juices. Take care to use a ceramic or glass bowl for a safe, quick curing process.
1 cup fresh-squeezed lime juice ¼ cup fresh-squeezed lemon juice 1 tsp. grated fresh ginger 2 tbsp. extra virgin olive oil 1 lb. fresh firm fish fillets (sea bass, flounder, tilapia), sliced (¼” thick by 1” long) ½ cup chopped fresh cilantro ½ cup sliced green onion 1 red onion, thinly sliced 1 or 2 finely chopped Roma tomatoes
March 2013
17
in & Tonic by Melody Murphy
Home Is Where the Heart Is
B
artow, Florida, is the little town where my parents did most of their growing up. It’s about a hundred miles south of here. One of my grandmothers still lives there; the other one is currently staying in Ocala, but still has her house there. The parents of my dearest friends, sisters Biddy Thatcher and Toad Sawyer (of last summer’s boat trip), also grew up in Bartow. Mr. Thatcher-Sawyer, in fact, introduced my parents. So I have a lot for which to thank Bartow. Though I only lived there for a year, when I was six, I’ve spent a great deal of my life there—enough that I consider it my hometown. I think the places you love in childhood will always feel like home. Especially if you keep returning to them throughout your life. But Bartow is special. I love it not just out of stubborn nostalgia, but genuinely and with present delight. Bartow looks like a hybrid of Mayberry and Bedford Falls, as painted by Norman Rockwell. The first time I took Puck Finn (also of last summer’s boat trip) there 20 years ago, she said in wonder, “It’s like Brigadoon. It could be any time at all from the ‘30s through the ‘80s.” That was in the ‘90s. It takes Bartow a while to catch up to the present. And that is why I love it. As the seat of Polk County, Bartow has two courthouses, the old one and the “new” one, but no movie theatre.
18
It’s coming along with restaurants, but you still have to drive to a neighboring town to do any real shopping. People say there isn’t much to do there, but I’ve always found plenty to do. When I visit, I have my favorite spots of pilgrimage. There are the two duck ponds, each near a grandmother’s house, where I grew up feeding the ducks. (And still do.) One has the old sycamore I used to climb ... am still tempted to climb.
There’s the park full of old live oaks where I played as a child. (And as a young adult; Puck Finn will recall the unfortunate seesaw incident of a nottoo-bygone year.) I go there now not to swing or slide, but to admire the Florida Cracker rose garden or the way sunlight slants through the Spanish moss. There’s the turn-of-the-century ice cream shop downtown where I buy an ice cream cone and go sit under my favorite ancient live oak on the old courthouse lawn to enjoy it. Across Main Street, there’s the quaint little gift shop I always pop into and can find the best presents ... or a little something for myself. There’s the old cemetery, older
than Polk County itself, where people born in the 1700s and the veterans of every war since then are buried. I played there as a child with the boy who lived across the street from my grandparents. My grandfather called him “The Rascal.” The Rascal and I would venture through the woods behind his house, climb the low stone wall around the cemetery, and go exploring. An old cemetery full of big trees, tall gravestones, and large monuments is an excellent place to play hide and seek. This may be part of the reason why I like old cemeteries. When you grow up playing in them, they lose their fear factor. I still go there to walk around and read the crumbling old stones and enjoy the quiet. I take a lot of pictures when I visit Bartow. I think it’s because I want to preserve so many moments in time, just as Bartow does—and because the tree-lined streets of beautiful old houses, the shops on Main Street, the old courthouse and cemetery, the duck ponds and the park are really lovely, and ask to be captured as snapshots for remembrance. Bartow is a lovely old town, but it’s at its most beautiful in springtime. Known poetically as “The City of Oaks and Azaleas,” that’s a true statement. The azaleas are glorious in spring. So are the camellias, plumbago, bougainvillea, hibiscus, jacaranda and tabebuia trees; there isn’t a time of year when Bartow isn’t beautifully in bloom with something, but spring is really its finest hour. And oh, the orange trees! Citrus is big doings in Polk County, so groves and citrus trees are everywhere. When they bloom in springtime, it’s pure heaven. I would never miss a pilgrimage to Bartow in orange blossom season. Next month, I’ll share some more “snapshots” of some recent sojourns in Bartow. I make my pilgrimages there for more than just the orange blossoms— and every time, there is something to delight me and reaffirm my feeling that you can, indeed, go home again. I’ll take you along in April.
Printed on recycled paper to protect the environment
HIPPODROME THEATRE
Alternative Wholistic Health Care Solving problems... naturally Michael Badanek, DC, BS, CNS, DACBN, DCBCN, DM(P)
N O O M E H T ’ O G KIN DZICK BY TOM DAUVID SHELTON YD IRECTED B
D
on stage february 22-march 17 discount previews feb 20 & 21
Board Certified in Clinical Nutrition, Certified in Applied Kinesiology, and Promoter of Alternative Complementary Medicine. 30 Years of Clinical Practice
Autoimmune disorders, Lyme disease, Autism, ADD/ADHD, Musculoskeletal conditions, Heavy metal toxicity, Cardiovascular & endocrine conditions, Nutritional deficiencies/testing. Courtesy consultations available (352) 622-1151 3391 E. Silver Springs Blvd., Suite B Ocala, FL 34470
THEHIPP.ORG | 352.375.HIPP | 25 SE 2ND PLACE | GAINESVILLE
A Simple Solution For Rejuvenation
Incredible products, astonishing prices.
Featured Product of the Month
Life Force tea
A customer favorite! Our Life Force tea will bring you a new sense of energy and clarity and allow you to feel more present in your body all while detoxifying your system gently. Results you will feel right away!
“After!” DT - Bellingham, WA
Herbal Teas &Tinctures • Natural Skin Care • Wellness Oils
1.866.607.2146
Using organic and wildcrafted herbs. Made in the USA. Same Day Shipping, free on all orders over $35. Get 10% off your first order when you use the discount code NACHIT
We know our products are making a difference in people’s lives because our customers call, write and email to tell us so! And they continue to recommend our products to their friends and family. We couldn’t.
alternativewholistichealth.com ocalaalternativemedicine.com March 2013
19
healthykids
Six Powerhouse Foods for Kids With Palate-Pleasing Tips by Susan Enfield Esrey
Aiolo-
20
gist antioxi-
dant delicious healthy smoothie. Chia seeds: This South American grain (the most researched variety is Salba seeds) may be the world’s healthiest, says Sears.. Susan Enfield Esrey is the senior editor of Delicious Living magazine.
Printed on recycled paper to protect the environment
{
}
a fresh take on healthy living
vitamins | supplements | health foods most items
20%
o f f e V e ry d ay !
352.509.6839 VitalizeNutrition.com 4414 SW College Rd, Ocala | Market Street at Heath Brook | 1 mi. W of 75 by Panera
• • • • • • • • • •
Himalayan Salt Room FAR-Infrared Sauna Facials Body Wraps Microdermabrasion Medicinal Teas Gemstones and Necklaces Himalayan Salt Lamps Vitamins and Supplements Massage Therapy
... and much more!
Experience optimal health naturally! 352-291-9459
11115 SW 93rd Ct Rd, Suite 600, Ocala, Florida 34481 Mon, Wed, Thurs, Fri 8 – 5 Tuesday 9-6 Closed every day from 12-1
ShingleX Soothing formula relieves pain, helps heal the sores, and reduces scarring. ShingleX soothes the pain of shingles lesions, helps prevent and pull out infection, protects, minimizes scarring, reduces length of illness. Testimonials online. 4-ounce jar Just $29.95+$6 S/H. To order, call 352-286-1779 or visit. Resale inquiries invited from natural practitioners and dermatologists.
March 2013
21
The Bold Truth of Thyroid Disease by Dr. Michael J. Badanek, DC, BS, CNS, DACBN, DCBCN, DM(P)
H
ealth care is shifting significantly and is ripe for changes in the balance of power and the paradigms of our therapeutic interventions. For nearly a century, allopathic medicine has hailed itself as “the gold standard,” and other approaches have either submitted to or been crushed by their ongoing political/scientific manipulations. Despite their proclamation of intellectual and therapeutic superiority, 180,000-220,000 iatrogenic (medically-induced) deaths occur in the U.S. per year (500-600 per day), and drug-related morbidity and mortality are estimated to cost more than $136 billion per year. (Holland EG, Degruy FV, Drug-induced disorders. Am Fam Physician. 1997:56(7): 1781-8, 17912.) In addition, it’s well documented that most medical allopathic physicians are unable to provide accurate diagnoses due to pervasive inadequacies in medical training. Currently one out of six women in the U.S. experience some type of thyroid dysfunction. Conventional allopathic medicine has totally failed in both the clinical diagnostic and treatment pictures of thyroid disease. It is time for the American consumer to wake up and understand that you cannot treat symptoms without effectively finding the root cause(s) of the problem and then addressing the cause to relieve/eliminate the symptoms and disease. Controversy In the allopathic medical paradigm, much confusion exists regard-
22
ing a common but “mysterious” and “enigmatic” condition known as hypothyroidism, or low thyroid function. The basis for the confusion within the allopathic medical community about hypothyroidism is primarily two-fold: first, they rely on the wrong test (TSH) as the main basis for laboratory assessment; second, they use incomplete treatment (T4 without T3), defying the known physiology of the thyroid gland, which makes at least two hormones rather than one. Hypothyroidism’s converse—hyperthyroidism and Graves disease—is well understood, easily diagnosed, and readily treated. However, because the medical treatment for hyperthyroidism often leaves patients in a hypothyroid state, affected patients transition from clarity (they are clearly ill due to the disease process), into “mystery” (hypothyroidism) wherein they feel ill due to incomplete/inaccurate treatment. One might get the impression that perpetual confusion is at times the goal of the medical profession: we certainly see this with the management of hypertension, depression, diabetes mellitus, psoriasis, and other inflammatory/autoimmune conditions. For people who seek clarity, it is available. Basic physiology The hypothalamus produces thyrotropin-releasing hormone (TRH) which stimulates the anterior pituitary gland to make thyroid-stimulating hormone (TSH), which stimulates the thyroid gland to produce thyroxine (T4, approximately 85% of thyroid gland hormone production) and triiodothyronine (T3, approximately 15% of thyroid gland hormone production). In the periphery, the prohormone
T4 is converted to active T3 by deiodinase enzymes. Stress, glucagon, and environmental toxins (originating most commonly from plastics and flame retardants) impair production of T3 and/ or increase production of reverse T3, which is either inert or inhibitory to the action of T3. If the thyroid gland begins to fail, then TSH levels increase as the body attempts to stimulate production of thyroid hormones from a failing gland, hence the association of elevated blood TSH levels with “primary hypothyroidism.” Thyroid hormones have many different functions in the body, and one of the chief effects is contributing to maintenance of the basal metabolic rate, or the speed of reactions within the body and the temperature of the body. An insufficiency of thyroid hormone adversely effects numerous biochemical reactions and body/organ functions, hence the myriad of clinical presentations. Clinical presentation of hypothyroidism In his classic book Biochemical Individuality, the author, Dr. Roger Williams, noted that “a wide variation in thyroid activity exists among ‘normal’ human beings.” Clearly, some patients do not make enough thyroid hormone to function optimally; or perhaps more precisely, they make enough thyroid hormone (T4) but do not efficiently convert it to the active form (T3) in the periphery. Further complicating the picture is that some patients make appropriate amounts of TSH, T4 and T3 but they make excess of inactive reverse T3 (rT3) which puts them into a physiologic state of hypothyroidism despite adequate glandular function. Patients may have one or more of the following:
Printed on recycled paper to protect the environment
fatigue, depression, cold hands and feet (excluding Raynaud’s syndrome, which is a part of peripheral vascular disease), dry skin, menstrual irregularities, infertility, premenstrual syndrome (PMS), uterine fibroids, excess menstrual bleeding, low basal body temperature, weak fingernails, sleep apnea and increased need for sleep, slow heart rate, easy weight gain and difficult weight loss (thus, predisposition to overweight and obesity), hypercholesterolemia, slow healing, decreased memory and concentration, frog-like husky voice, low libido, recurrent infections, hypertension (especially diastolic hypertension), poor digestion (due to insufficient gastric production of hydrochloric acid), delayed Achilles return (due to delayed muscle relaxation), carotenodermia (yellowish skin), vitamin A deficiency, gastroesophageal acid reflux, constipation, and predisposition to small intestine bacterial overgrowth (SIBO) due to slow intestinal transit. Of these manifestations, cold hands and feet, low basal body temperature, slow heart rate, and delayed Achilles return are the most specific. Some very competent physicians will, following proper patient evaluation, treat with thyroid hormone based on the clinical presentation of the patient without dependency upon laboratory findings.der a courtesy consultation.
The Gift of Empathy
How to Be a Healing Presence
W
by Margret Aldrich
hentaking, “Allowing into our heart the other person’s suffering doesn’t mean we suffer with them, because that means shifting the focus of our attention to our own experience. Rather, it means we recognize the experience as fully human, and behold the beauty of it in all its aspects, even when difficult.” Margret Aldrich is a former associate editor of Utne Reader.
March 2013 Licensed No. 2425, the Florida Commission for Independent Education
352-371-2833
COMING IN APRIL
Natural Awakenings’
SPECIAL ISSUE GREEN LIVING Celebrate the possibilities of sustained healthy living on a flourishing Earth.
Shape Body, Mind and Spirit • Color Therapy • Acupuncture • Electronic Gem Therapy • Biofeedback • Voice mapping/Clear • Homeopathic Injection Therapy for facial Mind Technology rejuvenation • Emotional Transformation Therapy
Dr. Paula Koger DOM 2007 Top 5 Doctors in Bay Area 941 539 4232 Rainbow Natural Medicine wealthofhealthcenter.com
Buy into the For more information about advertising and how you can participate, call 352-629-4000
24
community
… Support our advertisers
Printed on recycled paper to protect the environment
Tickets:
March 2013
25
The Birthright of Human Beings by David Wolf
I
n self-development circles, we commonly hear appeals to be aware of our emotions, feel our feelings, and experience our experiences. Certainly such expressions represent vital principles for conscious living. They signify consciousness itself. To the extent that we’re not aware of what’s happening inside us, we’re less than conscious of parts of ourselves. Thus, consciousness of our sensations, feelings, and thoughts is an essential foundation for selfrealization. Relatedly, the capacity to effectively communicate our experiences is a characteristic of a developed intrapersonal and interpersonal life.
Learning from a Newborn Experience and expression, though, do not constitute the totality of a purposeful and fulfilling human life. After all, babies are masterful at experiencing and expressing their experience. Their anger, happiness, pain and sadness are communicated
Grow Your Business Naturally with Natural Awakenings.
Easy & affordable. Starting at just $19.95/month!
How much is it costing you NOT to grow your business?.
26
without pretension. Certainly we can appreciate the authenticity of the newborn, especially as such genuineness tends to become elusive to many of us as we enter adolescence and adulthood. We can understand, however, that the consciousness of most very young children is not the full embodiment of self-realization. Consider qualities such as empathy for others, or the ability to voluntarily forego immediate gratification for a longer term goal. These are traits of a developed person that a small child tends to lack. It’s rare, for instance, for a mother to hear from her infant, “I understand that you’ve had a particularly stressful day, and you’re feeling rather irritated. So, I’ll patiently wait for a few hours, without crying or complaint, until you feed me.”
Purposeful Living
As spiritual beings having a human experience, it is our responsibility (while being grounded in our experience), to cultivate a sense of purpose—a purpose that recognizes and addresses our eternal spiritual nature, beyond the temporary attractions and repulsions of the material body and mind. Such a sense of purpose provides a context for understanding our experiences, for utilizing our cognitive, emotional, and physical experiences for the sublime purpose of consciousness-raising, of realizing our essential identity, apart from designations related to that which is impermanent.
Express Emotions … Less?
Nurturing conscious awareness is
paramount in determining the extent to which expression of emotion is lifeenriching or life-alienating. What you express connects with the principle of conscious choice. Sometimes in the personal growth environment, I sense an attitude that assumes or implies that the goal or purpose is to express our emotions more. It’s true that for some people the process of consciousness-raising will look like being more expressive, emotionally and otherwise. But for others, the process of self-development will look like expressing emotions less—for some people, expressing thoughts, emotions, etc., can be an avoidance, a diversionary drama, from their internal life. So, the vital principle is about living from conscious choice—from inspiration rather than from fear. Fear of being rejected can cause us to not authentically express, and fear can also cause us to express and share not from a place of courage, but rather to evade genuinely meaningful and productive dialogue. Thus, whether we’re silent and internal, or verbally, emotionally expressive, in itself, in my view, is not the key factor. The essential principle is to be conscious, at choice. Spirit thrives when we experience our experience, in a childlike way, while also enhancing the natural philosophical capacity that is the birthright human beings. David B. Wolf, Ph.D., L.C.S.W., is the founder of Satvatove Institute (www. Satvatove.com), an international personal and organizational development company with headquarters in Alachua, Florida. The author of Relationships That Work: The Power of Conscious Living, he conducts transformative communication and personal growth seminars worldwide, as well as individual and group coaching. He has published books and articles in a variety of fields, including mantra meditation and child protection, and is the director of the Satvatove School of Transformative Coaching.
Printed on recycled paper to protect the environment
Desire
“Like” our Natural Awakenings Facebook page for breaking news about health, the earth, and upcoming events. HEALTHY LIVING HEALTHY PLANET feel good live simply laugh more
Live Simply
FREE
& Enjoy
Relax and Refresh
HOLIDAY
YOGA 3 Easy Poses
BREATHE
These five components each work together to create what we want in Thoughts life via physics wave theory. One Beliefs cannot create a desire directly from Felt Emotions outward actions without first aligning thoughts, beliefs, and felt emotions. Just like an echo in a canyon—when you yell “1,2,3,4” into Outward Actions the canyon you do not hear back “5,6,7,8.” You hear exactly “1,2,3,4.” This isn’t negotiable; it’s physics wave theory. If one desires (wants something)—health for example but doesn't think, believe, or feel health to be possible for them, physics alignment is not present and long term health cannot be created and/or maintained. My book Why Stuff Happens in Life—the Good and the Bad (WSH) explains this in great detail.
INTO BEING The Ins & Outs of Better Health
Why “Stuff” Happens (WSH) in Life—the Good & the Bad Keywords: Natural Awakenings Gainesville, Ocala, The Villages Facebook is a registered trademark of Facebook, Inc.
To advertise your north-central Florida business in
by Stephanie Keller Rohde & End The Clutter ETC® 8961 SW 96 Lane—Unit D Ocala, FL 34481-6670 Toll-free (24/7) Recorded Message: 888-223-1922 Eastern Time Business Hours: 352-873-2100 Print Books: E-books: Teaching the Physics Components of Life—vibrant health, financial independence with wealth, unconditional loving relationships, and any (and every) life situation… endtheclutter@cfl.rr.com We do create our own personal unique reality every second of every day via physics wave theory whether we currently know (or like) this fact or not—again, it’s not negotiable, it’s physics—and we can always create differently starting right now.
JUST CALL US! We create a personalized marketing plan, targeting YOUR CUSTOMERS YOUR NEEDS
352-629-4000
this tion Men and ad 25 ea$ v i e c n re unt o disco first your cing. pri visit
Consultation Scheduling Times: 10:00 AM—Noon including lunch after the session—slow cooked veggies, beans, and whole grain brown rice (or animal protein), and fresh raw fruit for dessert. (Yes, there is such a thing as a free lunch if you believe it to be possible...) 1:30 PM—3:30 PM 4:00 PM—6 PM
March 2013
27
At Peace in Your Mind by Rev. Bill Dodd
H
ave you ever asked yourself what might make your life better? With the present hectic pace and demands of modern life, we often feel stressed and overworked. Wouldn’t you like to have a truly better life with more time for yourself? A little peace and harmony for each of us would make us feel more spiritually connected and more relaxed overall. Meditation provides relief to sensory overload by allowing the mind to be quiet. Getting the mind to rest takes some time and practice, but it is worth it. It even gives us better focus on a daily basis. For some, meditation can positively affect physical health. Even a simple 10- or 15-minute exercise in meditation can help us to overcome stress and find true inner peace and balance.
Meditation can also help us to understand our own mind. We can learn how to transform our thoughts from negative to positive, from disturbed to peaceful. Overcoming negativity and cultivating constructive thoughts is the purpose of the transforming meditations in the Buddhist tradition. Through meditative practices, we ultimately can get to a truly deeper state of self-awareness. With a quiet mind we free our overall awareness. And we ultimately find, after significant practice, that we can meditate at any time and anywhere, accessing the inner calm no matter what’s going on around us. We also find that we can better temper our reactions to things in life. Many people put off practicing meditation because they contend they don’t have 30 or 40 minutes to devote to the practice. Unfortunately, these stressed-out people who don’t have
enough time to meditate are the ones who in fact need it the most. Once you learn how to truly meditate, the rest of the day will start to go much more smoothly with fewer difficulties. Even if we don’t find the time to go to a meditation class weekly, after a little meditation practice, we find that we can begin to settle our minds and have some beautiful inner peace. All we have to do is take less than 15 minutes before going to bed and follow our breath coming in and going out. It is best to close our eyes and focus our attention on that place slightly above and between our eyes (the “third eye”). Besides feeling better inside, meditation sends positive thoughts to people and circumstances around us. It also allows us to visualize what we’d like to bring into our lives through affirmations for peace, health, prosperity and happiness. People who are beginning meditative practices can use simple efforts. Basic simple practices such as walking or running can help us center our minds and improve our efforts in meditation. We simply need to set aside a short time each day to create physical or mental benefit in our lives. Another example of meditative practices is using guided visualizations where we can see scenes of peace and love in our lives. We can envision the perfect job or relationship and affirm, see, and feel these truths in our lives right now. Ultimately meditation will help us to center ourselves and to become successful on a regular basis. We will become exceptionally happy in our lives. And we deserve it. Reverend Bill Dodd is co-minister of Trinity of Light Spiritual Center. Services are held Sunday at 10am at the College of Central Florida, Enterprise Building #101. Meditation Class led by Mary Dodd is held on Thursday at 7pm at the Ocala Inner center. Trinity of Light combines Eastern and Western omnicultural philosophy in meditationcentered practices. Contact Trinity of Light at 352-502-0253.
28
Printed on recycled paper to protect the environment
Himalayan Salt by Nuris Lemire, MS, OTR/L, NC
E
veryone knows someone who suffers from constant headaches. Many have family members who complain of lethargy brought about by bouts of insomnia or just restless sleep. Depression abounds in the masses almost as frequently as irritability. Many times people are just not able to put a finger on why they suffer from all these things. They look to sleep aids or anti-depressants. It is human nature to want to know why something is happening, to figure out the piece of the puzzle that they are missing and remedy the issue. We live in the technology age, a time where nearly every home has a computer (or three), flat screen television, fluorescent kitchen lights, cell phone(s), tablet(s), microwave and other electric appliances. It’s a time when homes have begun to literally bristle with ways to make people’s lives “simpler.” It’s also a time of some of the worst electronic pollution imaginable. Not just from planes, trains, and automobiles, but from the everyday things being used to help our “simpler” lifestyles continue. These amazingly sharp televisions, irreplaceable cell phones, and convenient microwaves are creating environments toxic to humans’ wellbeing through an overabundance of free radicals. Little by little, these free radical positive ions accumulate in the body, creating additional stress on the precious homeostasis (balance) that the body struggles to maintain. In recent years, more information has been surfacing about the
negative side effects of free radicals and how they relate to our health. Normally bonds don’t split in a way that leaves a molecule with an odd, unpaired electron. When weak bonds split, however, free radicals are formed. These new molecules are very unstable, reacting with other compounds in an attempt to snag excess electrons with the goal of becoming stable. Typically they’ll go for the nearest stable molecule, taking its electron—and in so doing, will create a chain reaction in an organism of molecules stealing electrons from other, more stable molecules. Eventually, this process causes damage in the organism on a cellular level which can present itself in many different ways. There are natural ways to negate the effects of free radicals, but not everybody has the luxury of going to the beach or sitting on a porch during a thunderstorm. Increasing antioxidants can help as well, because antioxidants will donate an electron while still maintaining molecular stability. Enter pink Himalayan salt. Himalayan salt is the only substance with antioxidant properties that work in all areas in the human body. Himalayan salt not only has 84 elements and trace minerals, but it is also easily absorbed by the body, becoming readily available shortly after consumption. It is molecularly stable and able to neutralize free radicals without becoming part of the chain reaction. Not only does it have more elements and trace minerals than sea salt and refined salt, but it helps to lower blood pressure, unlike either of the above. It can be used in baths to aid with detoxification, relaxation, and increased circulation, as well as be a replacement for table salts. This amazing natural substance is available in both bath and food grades as well as in soothing lamps to purify the air.
Himalayan salt lamps release negative ions when heated to help combat free radicals in the air, binding to and neutralizing them. They help to reduce humidity indoors and they provide a soothing soft light, making them great as night lights while still functioning as natural air purification. There have been studies on light waves and colors showing how the colors can improve mood and increase positive emotions. Animals, too, are keenly aware of the benefits and will often lie close to the lamps. Himalayan salt lamps are like a “beach in a bottle.” The benefits of natural Himalayan crystal salt include: regulating the water content throughout the body; promoting a healthy pH balance in the cells, particularly the brain cells; promoting blood sugar health and helping to reduce the signs of aging; assisting in the generation of hydroelectric energy in cells in the body; supporting respiratory health; promoting sinus health; prevention of muscle cramps; promoting bone strength; regulating sleep; supporting your libido; promoting vascular health; and, in conjunction with water, it is actually essential for the regulation of the blood pressure. Lemire Clinic is introducing the Himalayan Salt Room Ocala. The Himalayan Salt Room is a therapy which mimics the ancient Himalayan salt mines and the salt caves in Europe. This therapy consists of a 45-minute treatment in which you simply relax and breathe. The Himalayan Salt Room is comprised of pink Himalayan salt on all surfaces with ionized air for breathing treatments. Research has proven the therapeutic values of salt caves and their positive influence in the treatment of diseases including asthma, bronchitis, inflammation of the sinuses, lungs and large intestine, emphysema, duodenal and gastric ulcers, and general nervousness and exhaustion. Contact Lemire Clinic (352-291-9459,. com) for additional information, upcoming specials, or to purchase a beautifully crafted healing salt lamp.
March 2013
29
CommunityResourceGuide Acupuncture
Fitness.
Winning Harmony CounselingTM James R. Porter, Ph.D., LMHC, MH10992 Gainesville, Alachua 352-514-9810, Be Yourself. Finally. Dr. Porter draws from modern culture, 12+ years of advanced clinical training, 2 years of formal breath and body training, and a lifetime of formal and autodidactic spiritual training to create a counseling experience that will energize those wanting to address nearly any mental, emotional, or life issue.
Biologic Dentistry Dr. Cornelius A. Link, DDS 2415 SW 27th Ave., Ocala / 352-237-6196.
Botanical Salon & Day Spa Haile Village Spa & Salon 5207 SW 91st Terrace, Gainesville / 352-335-5025 We are a full service AVEDA hair salon for every type of hair and offer extensions, fashion forward color, and designer haircuts. We also specialize in ORGANIC skin-care and cosmetics for facials, makeovers, and skin treatments. We offer both spa and medical grade massage, acupuncture, detox body wraps, body scrubs, body contouring, lypossage, natural nail manicures, pedicures and waxing. Like us on Facebook for weekly Salon and Spa specials!.
30
Holistic Medicine Hanoch Talmor, M.D. Gainesville Holistic Center 352-377-0015 We support all health challenges and the unlimited healing potential of God’s miracle: your body. Chelation, Nutrition, Cleansing, Homeopathy, Natural Energy Healing, Detoxification, Wellness Education and more. James E. Lemire, M.D., FAAFP Nuris Lemire, MS, OTR/L, NC The Lemire Clinic.
Massage Clark Dougherty Therapeutic Massage Clinic 415 NE 25th Ave., Ocala 352-694-7255 / Offering a variety of therapeutic massage techniques for pain relief, improved flexibility, and other wonderful benefits. PIP and WorkComp always accepted, also group/private insurance in some instances. All credit cards accepted. Gift certificates are available for holidays and birthdays with 25% discount on a second session. MA27082, MM9718.
Physics of Life & Health Stephanie Keller Rohde, End The Clutter ETC® Toll-free 24/7 message, 888-223-1922. Direct line (business hours), 352-873-2100. Web site: Print books: eBooks: My books and I teach how to create anything in life (vibrant health, wealth, unconditionally loving relationships, etc.) that an individual desires and currently does not yet have.
Printed on recycled paper to protect the environment.
For $66/month, 65,000 readers will see your Community Resource Guide listing here. Call today! 352-629-4000
The Frugal Wine Snob
The blog about wines that taste like a million bucks, but cost less than $20.
Grow Your Practice Naturally with Natural Awakenings! The cost of an ad in the “Community Resource Guide�
is less than a daily cup of Starbucks. How much is it costing you not to grow your business? Call 352-629-4000.
CURLY HAIR SPECIALIST! Late Hours By Appt.
Open Tuesday to Saturday
Featuring All-Nutrient Organic Hair Color Earth friendly 10% off first visit * Sustainable products Dimensional color * with selected stylists Waxing and facials Independent Consultant 500 S.W. 10th Street, Suite 303 Ocala, Florida 34471 352-351-8991
Keratin Treatment with no formaldehyde and no smell!
March 2013
31
calendarofevents February 7-March 3 “A Funny Thing Happened on the Way to the Forum,” musical comedy stage production. Ocala Civic Theatre, 4337 E. Silver Springs Blvd., Ocala, 352-236-2274,. February 22-March 17 “King of the Moon,” comedy stage production. Hippodrome Theatre, 25 SE 2nd Pl., Gainesville, 352-375-HIPP,. Friday, March 1 Aumakhua-Ki™ Healing Level 1 with Rev. Ojela Frank, LMT. 12 noon, online course. For information about the new daily course, cost, and preregistration: 352-239-9272,. March 1-4 Krishna Das “The Heart of Devotion” Retreat including Kirtan and Yoga workshops. $175. Hindu Temple of Central Florida, Casselberry, FL. Tickets and info: 321-439-8353,. Saturday, March 2 * Buddha Card Readings with Rev. Steve Henry. 12-5pm, $20/mini reading, $30/half hour, $60/full hour. Call to sign up or walk in. High Springs Emporium, 660 NW Santa Fe Blvd, High Springs, 386-454-8657, www. highspringsemporium.net. * Create Conscious Community through skill building, fun personal growth games, and powerful introspection. 1-6pm. Sacred Earth Center, 1029 NW 23rd Ave, Gainesville, FL 32609. patrickmangum@yahoo.com or 386937-6491 to register. * Introduction to Traditional Yoga with Chandresh Workshop, 11am12:30pm, free. Bliss Yoga Center, 1738 SE 58th Ave., Ocala, BlissYogaCFL.com. * Raspberry Ketones, African Mango, 7 Keto, Red Palm Oil, Green Coffee Bean Extract, are metabolic boosters to bust fat. Free consultation; call for appointment. Reesers Nutrition
32
Center, 3243 E. Silver Springs Blvd, Ocala, 352-732-0718,. * RawSome: Introduction to Eating Raw class, 11-1, $45. Held at Unity of Ocala’s Unity House, 101 Cedar Rd., Ocala. Registration required: 352-3612666, Lenore@lenoremacary.com. Sunday, March 3 Rev. Marita Graves, New Thought Minister and Mastery of Language teacher, will speak at the 11am service. All are invited to stay for Potluck Lunch. At 1pm, a Playshop experience on “Sacred Communication” will be facilitated by Rev. Marita. Love offering. Unity of Gainesville, 8801 NW 39th Ave., Gainesville, 352-373-1030, Monday, March 4 Meet the Doctor and Patient Information. 6pm, free. Call for reservation. Lemire Clinic, 11115 SW 93rd Ct Rd., Suite 600, Ocala, 352-291-9459,. Tuesday, March 5 Aumakhua-Ki™ Healing Level-1 Certification, online course begins. Register at. Wednesday, March 6 Metabolic Balance All Natural Weight Loss. No pills, no shakes, no injections, no craving, no hunger. Free consultation. Call for appointment. Reesers Nutrition Center, 3243 E. Silver Springs Blvd, Ocala, 352-732-0718,. March 8-10 Transformative Communication and Self-Empowerment Seminar facilitated by Dr. David Wolf, author of Relationships That Work, and Marie Glasheen, professional transformative coach. Information/register: dharm. khalsa77@gmail.com, 352-222-6331,. Saturday, March 9 * “Chakra Balancing with Crystals”
Introductory Workshop and Sessions with Sharron Britton. Workshop 121:30, sessions 2-5:30. Workshop $20, sessions $10. High Springs Emporium, 660 NW Santa Fe Blvd, High Springs, 386-454-8657,. * “Gracefully Adjusting to Later Years with Happiness and Enthusiasm” workshop with Andrew and Ingrid Crane. 9am. RSVP by March 6 to Cara Owens, Vitalize Nutrition Company, Ocala, 352-509-6839,. March 9-10 * Marion County Master Gardeners expo. $1/person. 8-5 Saturday, 9-4 Sunday, Marion County Fairgrounds, 2232 NE Jacksonville Rd., Ocala. * Reiki Level II with Ojela Frank, LMT, in Ocala. Saturday 10-5:30, Sunday 12-4:30. Information: 352-2399272,. March 9-10 and 16-17 “Prince Charmless,” youth stage production, outdoor stage. Ocala Civic Theatre, 4337 E. Silver Springs Blvd., Ocala, 352-236-2274,. Sunday, March 10 Dr. Denise D’angelo Jones, speaker and singer/musician, 11am, love offering. Topic: living in the now and trusting intuition by blessing others with our unique spiritual gifts of sacred service. Unity of Gainesville, 8801 NW 39th Ave., Gainesville, FL 32606. 352-373-1030,,. bandcamp.com. Monday, March 11 * Cancer FREE Naturally lecture with author Jean Sumner. 6pm, free. Call for reservation. Lemire Clinic, 11115 SW 93rd Ct Rd., Suite 600, Ocala, 352-291-9459,. * Energy Activations for Awakening with Rev. Ojela Frank, LMT, (MA60322), all day, online by Skype video call or local sessions in Ocala, Register at, 352-239-9272.
Printed on recycled paper to protect the environment
Wednesday, March 13 * All-in-one-step total body cleanse. Antioxidant, anti-aging, immune support, intestinal health, weight Loss. Free consultation; call for appointment. Reesers Nutrition Center, 3243 E. Silver Springs Blvd, Ocala, 352-732-0718,. * Healthy Wednesday. Featured Film: “Cut Poison Burn,” documentary illuminating the truth about cancer treatment. Meditation at 6pm, potluck supper at 6:30, film at 7. $5/person. Unity of Ocala, 101 Cedar Rd., Ocala,. Thursday, March 14 Green Smoothie Workshop, Demonstration, and Tasting. 6pm, free. Call for reservation. Lemire Clinic, 11115 SW 93rd Ct Rd., Suite 600, Ocala, 352291-9459,. Saturday, March 16 * A Grand Metaphysical/Wellness Fair. 10-4. Explore options in healing, ways to heightened energy, inner beauty and wholeness. Unity of Gainesville, 8801 NW 39th Ave., Gainesville, FL 32606, 352-373-1030,. * Baby Yoga Class. 11-11:45am, free. Held at Gainesville’s Headquarters Library. 352-339-2212,. * “Esoteric Healing and Crystals” Workshop and sessions with Fran Oppenheimer, RN, LMT and certified Esoteric Healer. Workshop presentation 11am-12:30pm, $20. Sessions 1-5:30, $20. High Springs Emporium, 660 NW Santa Fe Blvd, High Springs, 386-4548657,. * Psychic/Medium Spiritual Development Class. 2-4:30pm. Includes meditation, lesson, practice. $25. Held at Unity of Gainesville, 8801 NW 39th Ave. International Foundation for Spiritual Knowledge,, 407-673-9776. * Toddler Yoga Class, 11:45am12:15pm, free. Held at Gainesville’s Headquarters Library. 352-339-2212,. Sunday, March 17 Rev. Marty Dow, “The Power of
Love,” with guest musician Michelle Manderino. Unity of Gainesville, 8801 NW 39th Ave., Gainesville, FL 32606. 352-373-1030,,. Monday, March 18 * Are You Digging Your Grave With Your Fork? Lecture with Nuris Lemire, MS, OTR/L, NC. 6pm, Free. Call for reservation. Lemire Clinic, 11115 SW 93rd Ct Rd., Suite 600, Ocala, 352291-9459,. * Spiritualist service. What happens to our loved ones when they pass over? Who are our Spirit Guides? What are the principles Spiritualists follow? What exactly are spiritualist messages? 10am with Rev. Diane King & Rev. Roger Blom. Unity of Ocala, 101 Cedar Road, Ocala,. Wednesday, March 20 * Live Blood Analysis. $60, call for appointment. Lemire Clinic, 11115 SW 93rd Ct Rd., Suite 600, Ocala, 352291-9459,. * Wellness consultation on Irritable Bowel Syndrome and 24-hour urinalysis for biochemical evidence of what foods your body is having a difficult time digesting and assimilating. Free consultation; call for appointment. Reesers Nutrition Center, 3243 E. Silver Springs Blvd, Ocala, 352-732-0718,.
Gold, 386-341-6260,. Saturday, March 23 * “Crystals for Balance and Grounding” Workshop with Sharron Britton. 2-4pm, $20. Call to sign up. High Springs Emporium, 660 NW Santa Fe Blvd, High Springs, 386-4548657,.
Now enrolling toddlers ages 18 months to 3 years!
"Free the child's potential, and you will transform him into the world." -Maria Montessori
16515 NW US HWY 441 Alachua. Fl 32615 (386) 418-1316 littlelotuspreschool.com ●
Lic# F08AL0791
Thursday, March 21 Dreams: The Language of Spirit workshop. Group Coaching session. $10, 6pm. Call for reservation. Lemire Clinic, 11115 SW 93rd Ct Rd., Suite 600, Ocala, 352-291-9459, www. LemireClinic.com. March 21-April 14 “Boeing Boeing,” comedy stage production. Ocala Civic Theatre, 4337 E. Silver Springs Blvd., Ocala, 352-2362274,. March 22-24 Divine Healing Hands Training Program. 9am-10pm, with Master Ellen and Master Sha. Ocean Center, 101 N. Atlantic Ave., Daytona Beach.. Geho
Ongoing Psychic Medium Spiritual Development Classes Next Class:
Saturday, March 16, 2:00 p.m. Visit for details Check our complete program on the website.
March 2013
33
calendarofevents * The Erasables in concert. 7:30pm, $15. Band will be performing tunes from their album “Heads in the Sand,” and debuting new material from their upcoming release. Unity of Gainesville, 8801 NW 39th Ave., Gainesville, FL 32606. 352-373-1030,, www. erasables.net. Sunday, March 24 Guest speaker David Charles Drew, Unity Minister, “What Does It Mean To Be BLESSED?” David was a radio and TV broadcaster, business trainer and seminar leader before being led to the ministry. 11am. Unity of Gainesville, 8801 NW 39th Ave., Gainesville, FL 32606. 352-373-1030, March 23-24 Kanapaha Spring Festival. 9-5 Saturday, 10-4 Sunday. Kanapaha Botanical Springs, 4700 SW 58th Drive Gainesville. March 25-26 Auditions for “Guys and Dolls,” musical stage production, 7pm. Director: Greg Thompson. Ocala Civic Theatre, 4337 E. Silver Springs Blvd., Ocala, 352-236-2274,. March 26-31 Satvatove Advanced Seminar Experience. Six days of courageous introspection and self-empowerment, facilitated by Dr. David Wolf and Marie Glasheen. Information/register:dharm. khalsa77@gmail.com, 352-222-6331,. Wednesday, March 27 Signs and Symptoms Analysis. Any time any of the organs and system of the body are out of balance, there are signs and symptoms. Once identified, a specific-to-you treatment is possible. Free consultation; call for appointment. Reesers Nutrition Center, 3243 E. Silver Springs Blvd, Ocala, 352-732-0718,.
34
Thursday, March 28 * Energy Activations for Awakening with Rev. Ojela Frank, LMT, (MA60322), all day, online by Skype video call or local sessions in Ocala, Register at, 352-239-9272. * Raw Food Class. $10, 6pm. Call for reservation. Lemire Clinic, 11115 SW 93rd Ct Rd., Suite 600, Ocala, 352-291-9459,. com. * You Have the Power to Heal Yourself. 6:30-9:30pm with Master Ellen. $25 at the door, $20/pre-register. Soul Essentials, 805 E. Ft. King St., Ocala. Geho Gold, 386-341-6260, www. BeHealedWithin.com. Saturday, March 30 * 13th Wholistic Health and Community Fair, FREE, 10-4, indoors, Sunshine Park Mall, 2400 S. Ridgewood Ave., South Daytona.. * “Changing Cellular Biology with Light Medicine” workshop with Dr. Paula Koger, DOM. 3-5pm, FREE. One person will receive a complimentary assessment. Reservations: 941-5394232. * Little Lotus House Preschool Open House. 2-6pm, FREE. 16515 NW U.S. Hwy. 441, Alachua, 352-3392212,. * “Make a Joyful Sound,” Crystal Singing Bowl Healing Session. 1-5pm, $20. Call to sign up. High Springs Emporium, 660 NW Santa Fe Blvd, High Springs, 386-454-8657,. * Spring Garden Kickoff. 9-3, $3/workshop/person, garden tours, snacks, seedlings for sale. Crones Cradle Conserve, 6411 NE 217th Pl., Citra, 352-595-3377,. April 4-12 “Sex Please, We’re Sixty,” comedy stage production. Ocala Civic Theatre, 4337 E. Silver Springs Blvd., Ocala, 352-236-2274,.
Saturday, April 6 Eco Agro Trails Run. Registration:. Information: ecoagrotrails@gmail.com. Held at Crones Cradle Conserve, 6411 NE 217th Pl., Citra, 352-595-3377,. April 6-7 Prenatal Yoga Teacher Training Workshop with Carmella Cattuti, 10am-6pm. YA and/or Nursing CEUs. Bliss Yoga Center 1738 SE 58th Ave., Ocala, BlissYogaCFL.com Monday, April 8 Energy Activations for Awakening with Rev. Ojela Frank, LMT, (MA60322), all day, online by Skype video call or local sessions in Ocala, Register at, 352-239-9272. Tuesday, April 9 Satvatove Institute School of Transformative Coaching is now accepting applications for the semester starting September, 2013. Classes are approved by the International Coach Federation (ICF). Syllabus:. com/syllabus.pdf. Information: 386418-8840, April 13-14 Spring Expo. Free admission. Saturday 11-9 (jazz and cuisine samples for sale 5-9), Sunday 10-4. Door prizes. Home/garden/business expo. The India Cultural Hall, NE 36th Ave. (two blocks north of Silver Springs Blvd.), Ocala.. Saturday, April 20 * Aumakhua-Ki™ Healing LEVEL-1 Certification with Rev. Ojela Frank, LMT, 10am-4pm, $50, The Martial Arts Center, Ocala. Register at www. aumakhua-ki.com, 352-239-9272. * Spring Sustainability and Natural Foods Gala. 9-3, $1/person admission, $1/sample. Garden tours, music, exhibits. Crones Cradle Conserve, 6411 NE 217th Pl., Citra, 352-595-3377,.
Printed on recycled paper to protect the environment
April 21-22 Aumakhua-Ki™ Healing LEVEL- 2 Certification with Rev. Ojela Frank, LMT, 10am, $100, The Martial Arts Center, Ocala. Register at, 352-239-9272. Sunday, April 28 Introduction to Initiation Healing® with Fabiola Kindt, LMT, 12-5:30pm, $30, The Martial Arts Center, Ocala, 352239-9272,.
Bliss Yoga Center of Central Florida A Place for Yoga, Wellness, Spiritual Study and Practice
Bliss Yoga Center
ONGOING
1738 Baseline Road 352-694-YOGA (9642)
Sundays * A Course in Miracles, 9:30am; Master Mind Healing Circle, 10am; Inspiring Message, Meditation and Music, 11am; Children and Youth education classes, 11am; Nursery care provided. Love offering. Unity of Gainesville, 8801 NW 39th Ave., Gainesville, 32606, 352-373-1030, * Celebrating Community and Inspiring Message/ Science of Mind and Spirit. Meditation 9:45am, Celebration/Message 10:30am, Youth and Children’s Celebration 10:30am. Love offering. OakBrook Center for Spiritual Living, 1009 NE 28 Ave, Ocala, FL, * Celebration and Meditation, 10am. Farmers Market and MasterMind group afterwards. Unity of Ocala, 101 Cedar Rd., Ocala,. * Trinity of Light Spiritual Service and Meditation, 10am, College of Central Florida, Enterprise Bldg. RoomBring this Ad for a 101, 352-502-0253, Trinityoflightholders@aol.com. 10% Senior/Student Discount
FREE 5 Day Trial Bring this ad for a
✁
FREE 5 Day Trial
✁
Mondays Bring thisSenior/Student Ad for a FREE 5Discount Day Trial * Abraham Study Group, 6pm; A Course in Miracles, 10% 10% Senior/Student Discount 7:30pm. Unity of Gainesville, 8801 NW 39th Ave., Gainesville, 32606, 352-373-1030, * Bliss Yoga Welcomes Annie Osterhout, ERYT to the Center. Iyengar Style Yoga classe, 5:30-6:30pm Beginners, GET A MEMBERSHIP EXPERIENCE 6:30-7:45pm Intermediate. Bliss Yoga Center, 1738 SE 58th Whole Body free training $ Ave., Ocala, BlissYogaCFL.com.
49
GET A MEMBERSHIP EXPERIENCE Whole Body Vibration EXPERIENCE Vibration /mo. free measurements low impact • kind to joints • tone & firm free training $ low Whole Impact Body
49
Monday-Friday free use of free measurements Belly-dancing, fitness, yoga classes, personal training infrared sauna /mo. GET MEMBERSHIP freeAuse of as early as 5:30am, as late as 7:30pm. Hip Moves, 708 NW infrared free alkaline water $ sauna 23rd Ave, Gainesville, 352-692-0132,. free alkaline/mo. water No Contract • No Hidden Fees No Contract • No Hidden Fees Tuesdays
49
Now accepting some kind toVibration joints insurances including tone &low firmImpact Silver and Fit. kind to joints tone & firm
training 3131 SW College Rd, SuiteFree 301, Ocala, FL 34474 • Phone: 352-304-5571 3131 SW College Rd, Suite 301, Ocala, FL 34474 • Phone: 352-304-5571
Aumakhua-Ki™ Healing Level-1 Certification, ONLINE course. Register at. Tuesday-Saturday Therapeutic Bodywork, Energy Healing with Ojela Frank, LMT (MA60322), at Hyde-Away Salon, Ocala. Session by Appointment, 352-239-9272,. Wednesdays * Aumakhua-Ki™ Healing Level-1 Certification, ON
Free measurements Free use of infrared sauna Free alkaline water No Contract • No Hidden Fees
3131 SW College Rd., Suite 301, Ocala FL 34474
352-304-5571
March 2013
35
“Discover the Power Within You” Our spiritual community offers practical, spiritual teachings to empower abundant and meaningful living. We welcome you!
LINE course. Register at. * Meditation, Visioning, and Healing Service, 6-7pm. Love offering. OakBrook Center for Spiritual Living, 1009 NE 28 Ave, Ocala, FL,. * Silent Unity meditation, 12-12:30pm. Unity of Ocala, 101 Cedar Rd., Ocala,.
11am Sunday-Inspiring Message, Meditation & Music Also UniKids, UniTeens, Youth Of Unity classes (Nursery care provided on Sundays) … a positive path for spiritual living ... 8801 NW 39th Avenue, Gainesville, FL 32606 352-373-1030—
Eastern & Western
OMNICULTURAL SPIRITUALITY Spiritual Services and Meditation sundays aT 10aM
Meditation Classes Thursdays aT 7PM
The College of Central Florida
Ocala Inner Center,
3100 SW College Road,
205 So. Magnolia Ave, Ocala, FL
Enterprise Building #101,
trinityoflightholders@aol.com
Ocala, FL 34474
352.502.0253
Thursdays * Beginning Yoga, 8:30-9:30am, All About Art, Belleview. Information: Annie Osterhout, 315-698-9749, www. OsterhoutYoga.com. * Chair Yoga, 9:45-10:45am, All About Art, Belleview. Information: Annie Osterhout, 315-698-9749,. Fridays Reiki Healing with Dee Mitchell, 7pm, first and third Fridays. Unity of Gainesville, 8801 NW 39th Ave., Gainesville, 32606, 352-373-1030, Saturdays Farmstead Saturdays. Free, 9-3. Crones Cradle, 6411 NE 217 Pl, Citra. 352-595-3377,. Calendar of Events listings are free for our advertisers and just $15/listing for non-sponsors. To publicize your event, visit.
Acne Relief
Experience the Power of Divine Healing Hands
with Dr. and Master Zhi Gang Sha
World-Renowned Soul Healer, Soul Leader, Divine Channel
and Master Ellen Logan
Divine Channel and Disciple of Dr. and Master Sha Dr. Sha is an important teacher and a wonderful healer with a valuable message about the power of the soul to influence and transform all life. – Dr. Masaru Emoto, The Hidden Messages in Water
Master Ellen Logan Divine Channel
New York Times Bestseller!
Divine Healing Hands are helping people around the world experience relief from chronic pain, boost energy and stamina, increase mobility and agility, and even improve chronic conditions. Visit YouTube.com/ZhiGangSha to see hundreds of personal soul healing miracles. You can receive Divine Healing Hands blessings at these live events or through the new Divine Healing Hands book. Each copy is a healing treasure offering blessings to the reader.
You Have the Power to Heal Yourself with Master Ellen Thursday, March 28, 6:30–9:30 pm, $25, pre-register $20 Soul Essentials, 805 East Ft. King St., Ocala 34471
Divine Healing Hands Training Progam with Master Ellen and Master Sha Friday–Sunday, March 22-24, 9 am–10 pm, $625 Live in Daytona Beach. • Master Sha will join by webcast from Mumbai! Ocean Center, 101 N. Atlantic Ave., Daytona Beach 32118 Become a powerful healer when you receive Divine Healing Hands transmission from Master Ellen! Unique and Extraordinary Training Program! • Apply at DivineHealingHands.com
More than an invitation ... a sacred calling! Information: Geho at 386.341.6260, Institute of Soul Healing & Enlightenment™ 888.3396815 • DrSha.com • Facebook.com/DrAndMasterSha • DivineHealingHands.com
36.
Printed on recycled paper to protect the environment
Feel Better, Lose Weight, Increase Energy and Mental Clarity People using detoxified iodine have reported relief from:
ONL $ Y 4 $ 5 sh 6 wee ippi k
March 2013
37
TURN YOUR PASSION INTO A BUSINESS Own a Natural Awakenings Magazine! • • • • •
Low Investment Work from Home Great Support Team Marketing Tools Meaningful New Career
Phenomenal Monthly Circulation Growth Since 1994. Now with 3.6 Million Monthly Readers in:* Denver/Boulder, CO Hartford, CT Fairfield County, CT* New Haven/ Middlesex, CT Washington, DC Daytona/Volusia/ Flagler, FL NW FL Emerald Coast Ft. Lauderdale, FL Jacksonville/ St. Augustine, FL Melbourne/Vero, FL Miami & Florida Keys Naples/Ft. Myers, FL North Central FL* Orlando, FL Palm Beach, FL Peace River, FL Sarasota, FL Tampa/St. Pete., FL FL’s Treasure Coastoston, MA Western, MA Ann Arbor, MI Grand Rapids, MI East Michigan Wayne County, MI Minneapolis, MN Asheville, NC* Charlotte, NC Raleigh/Durham/ Chapel Hill, NC Mercer County, NJ Monmouth/Ocean, NJ* North NJ North Central NJ Somerset/Middlesex Counties, NJ South NJ Santa Fe/ Albuquerque, NM Las Vegas, NV* Long Island, NY Manhattan, NY Rockland/ Orange Counties, NY
Printed on recycled paper to protect NaturalAwakeningsMag.com
• Westchester/ Putnam Co’s., NY • Central OH • Oklahoma City, OK • Portland, OR • Bucks/Montgomery Counties, PA • Harrisburg, PA • Lancaster, PA • Lehigh Valley, PA • Northeastern PA* Houston, TX • North Texas • San Antonio, TX • Richmond, VA • Southwestern VA • Seattle, WA • Madison, WI* • Milwaukee, WI • Puerto Rico *Existing magazines the for sale environment
Discounts & COUPONS
Give yourself and your loved ones gifts of health, wellbeing, and sustainability while supporting our local economy. Shop locally!
EXP. NOTICE:
These Special Offers are good for this month only, unless otherwise stated.
50% off haircut & style w/
HIRE SKIPPY. Farm Stead Saturday, 9-3 every week. Fun for the whole family. FREE! 6411 NE 217th Pl., Citra 352-595-3377
Grow Your Business Naturally with Natural Awakenings.
Easy & affordable.
conditioner first-visit clients. Treat yourself to a New YOU for the New Year!
She can find $$$ for YOU in your closet and garage! The expert in what to “Keep-eBay-Donate!” CONTACT on Facebook: HIRE SKIPPY. Twitter: @SueMorris8. Call: 352-857-2046.
Starting at just $19.95/month!
FREE
Acupuncture consultation. 352-271-1211 507 NW 60 Gainesville
How much is it costing you NOT to grow your business?.
Advertisers!
Less than a mile west of I-75. Next to Panera.
Coupons start at $19.99 monthly
352-509-6839 4414 SW College Rd., #1520 Market Street at Heath Brook
INSTRUCTIONS:
1. Visit
2. Select your ad package 3. Email your logo, contact information, and special offer. It’s okay to change your offer each month. Changes must be received by the 15th. Questions? 352-629-4000 NaturalAwakeningsGainesvilleOcalaTheVillages
20% discount on pre-purchase of 5 or more massage sessions Clark Dougherty Therapeutic Massage Clinic / MM 9718 MA 27082 / 352-694-7255
Nature’s Way Organic Salon & Spa, 4620 E. Silver Springs Blvd. Suite 502, 352-2365353,
INTRODUCES
Whole Life Coaching
We offer group and individual Coaching Sessions to help you take the next steps in your life, nutritionally, spiritually and emotionally. Our coaches will suit up and take action with YOU and your activities. 11115 SW 93rd Ct. Rd., Suite 600, Ocala 352-291-9459
Bring this ad for 20% discount
Ayurveda Health Retreat
\
Yoga, vegetarian cooking classes, musical performances, trips (Costa Rica in May), yoga teacher certification, much more. Retreats and health services 365 days/year. 352-870-7645,
Alachua Integrative Medicine
14804 NW 140th St / Alachua 386-418/1234. Chiropractic, Mental Health Counseling, Massage, MORE. Meeting the medical needs of your whole family—naturally
FREE classes / consultations, every Wednesday.
20% Discount:
Your special offer here.
Larry Veatch, M.S., M.B.A.
Call for appointment. Reesers Nutrition Center, 3243 E. Silver Springs Blvd., Ocala, 352-732-0718, 351-1298,.
(
(
Pre-Purchase of 4 or More Sessions Patricia Sutton, LMT, NMT, CRT, MA22645 Neuromuscular Massage By Design / 352-694-4503 Board Certified Life Coach; Licensed Mental Health Counselor. 352-359-0071, larryv8@cox.net Larry has 33 years’ experience helping others via individual and group sessions. Call today!
March 2013 Save Money on a Healthy Lifestyle!
6
39
Do People Naturally Confide In You And Come To You For Guidance? Do You Wish You Knew How To Give Your Wisdom To Others? The Satvatove School Of Transformative Coaching Is For Those Who Are Ready To Take Their Natural Helping/Coaching Propensity To The Next Level Of Excellence! Our Mission Is To Empower Empathy-Driven Individuals Through A Rigorous Training In The Principles, Tools And Skills Of Life Transformation Coaching “Because of the incredible coaching skills I gained from Principles and Practices of Transformative Coaching, I’ve had the confidence to step up and establish my Life Coaching practice.” - David Aycrigg- New Zealand
Dr. David Wolf is the founder of Transformative Coaching and author of Relationships That Work: The Power Of Conscious Living
GRADUATES OF THE SATVATOVE SCHOOL OF TRANSFORMATIVE COACHING: • Master Powerful Coaching Skills • Develop Confidence To Use Their Gifts To Make A Powerful Difference For Others • Cultivate Their Natural Talents As A Stand For Personal Growth For Everyone They Meet • Engage Intensively In The Adventure Of Self-Realization All This, While Developing A Career Deeply Aligned With Their Highest Sense Of Purpose “I received world-class training from Satvatove Institute's School of Transformative Coaching as well as profound personal growth and learning. Perfect for anyone dealing with clients, patients, students or humans of any kind : )” - Patrick Mangum- Florida
Find out if Transformative Coaching can help you optimize your natural tendencies for supporting & empowering others. Register for a FREE Coaching/Coach Training consultation at:
ACSTH 40
Approved Coach Specific Training Hours
International Coach Federation Printed on recycled paper to protect the environment OR CALL NOW 1-386-418-8840 | https://issuu.com/gonaturalawakenings/docs/march2013naturalawakeningsonline?mode=embed&viewMode=presentation&layout=http%3A%2F%2Fskin.issuu.com%2Fv%2Flight%2Flayout.xml&showFlipBtn=true&pageNumber=12 | CC-MAIN-2022-27 | refinedweb | 14,154 | 55.95 |
Use Lambdas Instead of Anonymous Classes In Java
Another useful feature introduced since Java 8 is the possibility to use lambdas instead of anonymous classes. Here is an example:
Imagine you have the following list of names:
List<String> names = Arrays.asList("James", "diana", "Anna");
If you want to sort it alphabetically ignoring the case, you would have to use a Comparator and implement its compare method in an anonymous class like this:
Collections.sort(names, new Comparator<String>() { @Override public int compare(String o1, String o2) { return o2.compareToIgnoreCase(o2); } });
You can accomplish exactly the same with a lambda in a much more concise way:
Collections.sort(names, (a, b) -> a.compareToIgnoreCase(b));
The complete test class will look like this:
import java.util.Arrays; import java.util.Collections; import java.util.List; public class Test { public static void main(String[] args) { List<String> names = Arrays.asList("James", "diana", "Anna"); Collections.sort(names, (a, b) -> a.compareToIgnoreCase(b)); System.out.println(names); } }
The above will print the names sorted ignoring the case of the first letter:
[Anna, diana, James] | http://knowledgebasement.com/use-lambdas-instead-of-anonymous-classes-in-java/ | CC-MAIN-2021-43 | refinedweb | 180 | 51.34 |
Hello,
I have a user export dump of 9 MB of oracle 7.3.4 on SCO-UNiX.When I try to
import into a exportor's default tablespace,it occupies the space of 500 Mb+
200MB of index tablespace.but if I import into importer's default tablespace
import takes the space of 1.3GB.
Why it should be so.Import on both tablespaces are working fine.
That is interesting!
How big is this tables in the tablespace?
What are default parameters for tables/ablespaces?
Did you make the option compress=y when you made an export?
[Edited by kgb on 08-07-2001 at 06:28 AM]
Try these
Check if the import stops for long time at
some table while importing
Check the storage parameters of those imported tables.
Correct them if necessary in the original tables and then
make a fresh export dump using "Compress=Y"
Hope it wrks
Regards
Shruti
I think compress=y is also the default if unspecified.
I actually had an import that failed because of this.
When set to compress=n the import worked.
It seems the initial extent it was creating was too big. It doesn't seem like this parameter would affect the problem you are having but it can't hurt to try .
Forum Rules | http://www.dbasupport.com/forums/showthread.php?14238-howto-disable-dbms-job&goto=nextoldest | CC-MAIN-2017-30 | refinedweb | 217 | 75.91 |
Concurrency with LMAX Disruptor – An Introduction
This article introduces the LMAX Disruptor and talks about how it helps to achieve software concurrency with low latency. We will also see a basic usage of the Disruptor library.
2. What is a Disruptor?
Disruptor is an open source Java library written by LMAX. It is a concurrent programming framework for the processing of a large number of transactions, with low-latency (and without the complexities of concurrent code). The performance optimization is achieved by a software design that exploits the efficiency of underlying hardware.
2.1. Mechanical Sympathy
Let’s start with the core concept of mechanical sympathy – that is all about understanding how the underlying hardware operates and programming in a way that best works with that hardware.
For example, let’s see how CPU and memory organization can impact software performance. The CPU has several layers of cache between it and main memory. When the CPU is performing an operation, it first looks in L1 for the data, then L2, then L3, and finally, the main memory. The further it has to go, the longer the operation will take.
If the same operation is performed on a piece of data multiple times (for example, a loop counter), it makes sense to load that data into a place very close to the CPU.
Some indicative figures for the cost of cache misses:
2.2. Why not Queues
Queue implementations tend to have write contention on the head, tail, and size variables. Queues are typically always close to full or close to empty due to the differences in pace between consumers and producers. They very rarely operate in a balanced middle ground where the rate of production and consumption is evenly matched.
To deal with the write contention, a queue often uses locks, which can cause a context switch to the kernel. When this happens the processor involved is likely to lose the data in its caches.
To get the best caching behavior, the design should have only one core writing to any memory location (multiple readers are fine, as processors often use special high-speed links between their caches). Queues fail the one-writer principle.
If two separate threads are writing to two different values, each core invalidates the cache line of the other (data is transferred between main memory and cache in blocks of fixed size, called cache lines). That is a write-contention between the two threads even though they’re writing to two different variables. This is called false sharing, because every time the head is accessed, the tail gets accessed too, and vice versa.
2.3. How the Disruptor Works
Disruptor has an array based circular data structure (ring buffer). It is an array that has a pointer to next available slot. It is filled with pre-allocated transfer objects. Producers and consumers perform writing and reading of data to the ring without locking or contention.
In a Disruptor, all events are published to all consumers (multicast), for parallel consumption through separate downstream queues. Due to parallel processing by consumers, it is necessary to coordinate dependencies between the consumers (dependency graph).
Producers and consumers have a sequence counter to indicate which slot in the buffer it is currently working on. Each producer/consumer can write its own sequence counter but can read other’s sequence counters. The producers and consumers read the counters to ensure the slot it wants to write in is available without any locks.
3. Using the Disruptor Library
3.1. Maven Dependency
Let’s start by adding Disruptor library dependency in pom.xml:
<dependency> <groupId>com.lmax</groupId> <artifactId>disruptor</artifactId> <version>3.3.6</version> </dependency>
The latest version of the dependency can be checked here.
3.2. Defining an Event
Let’s define the event that carries the data:
public static class ValueEvent { private int value; public final static EventFactory EVENT_FACTORY = () -> new ValueEvent(); // standard getters and setters }
The EventFactory lets the Disruptor preallocate the events.
3.3. Consumer
Consumers read data from the ring buffer. Let’s define a consumer that will handle the events:
public class SingleEventPrintConsumer { ... public EventHandler<ValueEvent>[] getEventHandler() { EventHandler<ValueEvent> eventHandler = (event, sequence, endOfBatch) -> print(event.getValue(), sequence); return new EventHandler[] { eventHandler }; } private void print(int id, long sequenceId) { logger.info("Id is " + id + " sequence id that was used is " + sequenceId); } }
In our example, the consumer is just printing to a log.
3.4. Constructing the Disruptor
Construct the Disruptor:
ThreadFactory threadFactory = DaemonThreadFactory.INSTANCE; WaitStrategy waitStrategy = new BusySpinWaitStrategy(); Disruptor<ValueEvent> disruptor = new Disruptor<>( ValueEvent.EVENT_FACTORY, 16, threadFactory, ProducerType.SINGLE, waitStrategy);
In the constructor of Disruptor, the following are defined:
- Event Factory – Responsible for generating objects which will be stored in ring buffer during initialization
- The size of Ring Buffer – We have defined 16 as the size of the ring buffer. It has to be a power of 2 else it would throw an exception while initialization. This is important because it is easy to perform most of the operations using logical binary operators e.g. mod operation
- Thread Factory – Factory to create threads for event processors
- Producer Type – Specifies whether we will have single or multiple producers
- Waiting strategy – Defines how we would like to handle slow subscriber who doesn’t keep up with producer’s pace
Connect the consumer handler:
disruptor.handleEventsWith(getEventHandler());
It is possible to supply multiple consumers with Disruptor to handle the data that is produced by producer. In the example above, we have just one consumer a.k.a. event handler.
3.5. Starting the Disruptor
To start the Disruptor:
RingBuffer<ValueEvent> ringBuffer = disruptor.start();
3.6. Producing and Publishing Events
Producers place the data in the ring buffer in a sequence. Producers have to be aware of the next available slot so that they don’t overwrite data that is not yet consumed.
Use the RingBuffer from Disruptor for publishing:
for (int eventCount = 0; eventCount < 32; eventCount++) { long sequenceId = ringBuffer.next(); ValueEvent valueEvent = ringBuffer.get(sequenceId); valueEvent.setValue(eventCount); ringBuffer.publish(sequenceId); }
Here, the producer is producing and publishing items in sequence. It is important to note here that Disruptor works similar to 2 phase commit protocol. It reads a new sequenceId and publishes. The next time it should get sequenceId + 1 as the next sequenceId.
4. Conclusion
In this tutorial, we have seen what a Disruptor is and how it achieves concurrency with low latency. We have seen the concept of mechanical sympathy and how it may be exploited to achieve low latency. We have then seen an example using the Disruptor library.
The example code can be found in the GitHub project – this is a Maven based project, so it should be easy to import and run as is. | https://www.baeldung.com/lmax-disruptor-concurrency | CC-MAIN-2019-22 | refinedweb | 1,120 | 54.93 |
I had already looked through this post:
Python: building new list from existing by dropping every n-th element, but for some reason it does not work for me:
I tried this way:
def drop(mylist, n):
del mylist[0::n]
print(mylist)
n
drop([1,2,3,4],2)
[2, 4]
[1, 3]
def drop(mylist, n):
new_list = [item for index, item in enumerate(mylist) if index % n != 0]
print(new_list)
drop([1,2,3,4],2)
[2, 4]
[1, 3]
In your first function
mylist[0::n] is
[1, 3] because
0::n means first element is 0 and other elements are every nth element after first. As Daniel suggested you could use
mylist[::n] which means every nth element.
In your second function index is starting with 0 and
0 % 0 is 0, so it doesn't copy first element. It's same for third element (
2 % 2 is 0). So all you need to do is
new_list = [item for index, item in enumerate(mylist) if (index + 1) % n != 0]
Tip: you may want to use
return instead of
print() in functions like these. | https://codedump.io/share/e3670dzv9YcG/1/python-how-to-remove-every-n-th-element-from-list | CC-MAIN-2017-17 | refinedweb | 187 | 73.41 |
Hybrid View
Buffered Ext.data.Store issues
Buffered Ext.data.Store issues
1) If I use guaranteeRange(0, myPageSize-1) on a Store (Ajax proxy), and the server returns no rows, I don't consider this to be an error. The framework begs to differ (start > end error). Your examples use this to load stores that are buffered, so I expect that this is how I'm supposed to do it. Is this correct, or is no rows returned from a query really a case that requires a hard exception? Sometimes a lookup returns nothing, and that's OK. Perhaps "tryGuaranteeRange()" is more appropriate for real world use?
2) Try using the Buffered Grid example on the sencha site in IE9 (not infinite scrolling example). Click in the paging space of the scroller. Scroll thumb doesn't move, rows don't update. DRAG the thumb, and it scrolls. This doesn't happen in the infinite scroll example, for reasons I can't determine.
3) I'd love to know what "Record was not found and store said it was guaranteed" means? I got that running the infinite scrolling example in IE9 on the sencha site this morning.
stevil
1) Agreed... just because its requested a specific range to guarantee doesnt mean the server-side actually had that range. We'll revisit this.
2) We're aware of this problem and actively tracking it. Basically the scroller is as wide as the div that contains it. IE says oh there is no visible space and won't allow you to scroll it.
3) Somehow the record has been purged out of the prefetched data before it should have been. If you can help us pinpoint how to reproduce this it would help us track it down.Aaron Conran
@aconran
Sencha Architect Development Team
I have been facing the same issue. Just couldn't avoid the error "Record was not found and store said it was guaranteed" . Attaching the sample code.
Code:
Ext.Loader.setConfig({enabled: true}); Ext.Loader.setPath('Ext.ux', '../ux/'); Ext.require([ 'Ext.grid.*', 'Ext.data.*', 'Ext.data.BufferStore', 'Ext.util.*', 'Ext.grid.PagingScroller' ]); Ext.onReady(function(){ Ext.define("thm", {extend: "Ext.data.Model", fields: [{name:'pgNo',type:'string'}]}); var storeConfig = new Ext.data.BufferStore({ model: 'thm', pageSize: 20, buffered: true, proxy: { type:"thm_proxy", url: "ivf/dummyurl", extraParams: { total: 1000 }, reader: { root: 'pages', totalProperty: 'totalCount' } } }); var grid = new Ext.grid.GridPanel( { width: 150, height: 300, store: storeConfig, verticalScrollerType: 'paginggridscroller', loadMask: true, invalidateScrollerOnRefresh: false, viewConfig: { //trackOver: false }, renderTo: Ext.getBody(), columns: [{ dataIndex: 'pgNo', align: 'center', flex:1 }] } ); // trigger the data store load storeConfig.guaranteeRange(0, 19); }); Custom proxy which gives me back a json of the records containing row numbers Ext.namespace("xcp.ivf"); (function() { Ext.define("xcp.ivf.ThmProxy", { extend: "Ext.data.ServerProxy", alias: 'proxy.thm_proxy', constructor : function(config) { xcp.ivf.ThmProxy.superclass.constructor.call(this, config); }, doRequest: function(operation, loadCallback, scope) { var me = this, writer = me.getWriter(), request = me.buildRequest(operation, loadCallback, scope), args = [], params = request.params, reader = me.getReader(); var i = 1; var j = operation.start; var jsonObj = { "totalCount": 1000, "pages":[{pgNo:(++j).toString()}] }; for (; i < operation.limit; i++) { jsonObj.pages[i] = {pgNo:(++j).toString()}; } var readData = reader.read(jsonObj); console.log("start,limit :" + operation.start + "," + operation.limit); var records = readData.records ? readData.records : []; var operationCfg = { action: "read", success:true, complete:true }; Ext.apply(operation,operationCfg); operation.resultSet = Ext.create('Ext.data.ResultSet', { records: records ,total : 1000 }); operation.setStarted(true); loadCallback.call(scope, operation, args, true); } }); })();
1) Load the buffer-grid example.
2) Immediately, click the source code link over the grid.
3) IE9 will put a warning up about the file not being safe. Wait 30 seconds, and answer.
4) At some point in time, you'll then see that message.
It's weird, true, but it happens to me all the time. Now, is it a "real world" use case? I doubt it. I wouldn't ding you for getting hit by a browser interfering with you, which it seems this is. That said, it might help to flush out the behavior.
If I can come up with more information, I'll relay it to you here!
stevil
It occurs to me very frequently. What is the significance of guaranteeRange() call. Should'nt it be fine if the store gets the guaranteed no of records from the proxy ?
What is the right proxy to use if am simulating data generation at the client side. I have a custom server proxy which gives back data without server fetch. But the error we discussed keeps occurring. I do not want to load all the data in a single shot at the client side. It should be loaded as I scroll. Can a MemoryProxy fit this scenario ?
This snippet is from the onGuaranteedRange function of Ext.data.Store:
Code:
end = ((totalCount - 1) < me.requestEnd) ? totalCount - 1 : me.requestEnd) ... me.guaranteedEnd = end;
Happens to me even with an empty data set in the JSON. | http://www.sencha.com/forum/showthread.php?132384-Buffered-Ext.data.Store-issues&mode=hybrid | CC-MAIN-2014-10 | refinedweb | 825 | 61.63 |
This is an independent test suite for fictional compoment 'demo'. The suite is intended to be reference example for JATS - Just A Test System.
JATS defines test suite format, which is a directory tree consisting of individual tests. These individual tests can in principle be implemented in any language, but for now shellfu-bash-jat is the only available library.
Direct dependencies are:
All of the above have their own dependencies, so if you want to install everything manually, follow instructions on their pages.
Most tests should work without installation. That is, just cloning this repo should be enough. OTOH, in production environment--if you want to ensure integrity of the tests and eg. have them be able to report their own version, instaling the suite is recommended.
Manual installation consists of:
make sudo make install
For Fedora-like distros, this suite and its dependencies are available in COPR projects netvor/jats and netvor/shellfu.
yum install yum-plugin-copr yum copr enable netvor/shellfu yum copr enable netvor/jats yum install jats-demo jattool
Note that older systems like RHEL-6 don't have the COPR plugin, so you will need to add repositories manually. There's a script to help you with this step on CentOS-6 & RHEL-6.
Also note that in order to minimize dependencies on testing machine, install just jattool-minimal package, which contains only the bare minimum needed for running tests.
Sorry, but since author of the tools does not know how to create at least remotely proper Debian repository, .deb packages are available on-demand only. See Contact section in main README.
To show list of installed tests:
jattool tfind /usr/share/jats
Each JAT test is a directory, so above should give you list of directories: you
can then run any of them using
jattool runtest, eg.:
jattool runtest /usr/share/jats/suite/logging/etype/pass
should give you something like this:
test.INFO: id: jats://my.example.org/foodept/barpkg//logging/etype/pass test.INFO: version: 0.0.3 session.START phase.START test.INFO: CMD: false assert.PASS: false is still false test.INFO: CMD: true assert.PASS: true is still true assert.PASS: math still works phase.END.PASS session.FINALIZE.PASS
I won't go into details; I'll tell you just enough to get you started, but be aware that (mostly) everything is (mostly) documented and primary ways to get help (actually more like reference, but helps) using sfdoc tool, which should be on your workstation by now.
Tests normally only consist of one important file, named ... you guessed it... test. (There's also main.fmf, but that only contains meta-data, which is not even really used these days.)
$ tree src/extension/xcase src/extension/xcase ├── main.fmf └── test
So open that file: it's a Bash script with extra "enhancements": you'll see things like:
shellfu import jat shellfu import xcase
Shellfu platform brings modularity to Bash, so the names above are names
of modules.
jat is a module name. And you can get reference on the module
sfdoc jat
Since this is Bash, modules contain just functions and variables. And since Bash has no namespaces, an important convention for (almost) all modules is in place:
foomust be named by
foo__prefix,
foomust be named by
FOO__prefix.
Eg. an initializing function from module bar would have to be called
bar__init().
NOTE: At the time of this writing, the test creation kit is not finished, so if you really need new test, you can just copy another one.
In order to avoid duplication of work and unnecessary frustration, take following steps:
Before you start, contact maintainer and inform them that you are planning to write a test. You can do this by filing an issue in Pagure repo or by contacting the maintainer directly.
Read Shellfu coding style; tests need to follow this.
Be aware that the JATS project is in early stage (
v0.0.*), and
some (most?) pieces of coding style and conventions are not yet
written down. A more consistent documentation is expected to arrive
before
v0.1.0. | https://pagure.io/jats-demo/tree/master | CC-MAIN-2020-05 | refinedweb | 684 | 65.62 |
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 05.01.10 08:36, Martin Aspeli wrote: > +1. It puts the final nail in the Zope 3 coffin and allows a reborn > vampire to emerge from slumber.
Advertising? Possible solution: If all of the ZTK is in the namespace zope someday, why don't we call the ZTK "Zope", as it seems to be the heart of all these webframeworks? Then we can tell a story where there are different cool webframeworks based on Zope (former ZTK) which is a well defined set of libraries to do component-based web-development. juh -----BEGIN PGP SIGNATURE----- Version: GnuPG v2.0.10 (Darwin) Comment: Using GnuPG with Mozilla - iEYEARECAAYFAktC9VUACgkQPUzUEFbILMTiaACeKozFqtbZadk7qVRfKnoXvagY 6XUAnid2GsCtrOhkUL3SHmOK0rD6vplU =YT9A -----END PGP SIGNATURE----- _______________________________________________ Zope-Dev maillist - Zope-Dev@zope.org ** No cross posts or HTML encoding! ** (Related lists - ) | https://www.mail-archive.com/zope-dev@zope.org/msg32259.html | CC-MAIN-2017-04 | refinedweb | 136 | 55.74 |
Problem Statement:
Gradle Build failed in Windows 10 Operating System due to additional policy applied in network layer and firewall. This same setup is working fine in Mac book and Windows 7 Operating System. The following issue happens when execute through terminal mode. If I run it in intelliji ide, Getting ntlm authentication error even though ntlm domain property set.
Where :
Build File:
Error Meassge 1: Plugin ID was not found in any of the following issue.
- Gradle core plugins (plugin is not in ‘org.gradle’ namespace)
- Plugin Repositories (could not resolve plugin artefact ‘orglspringframework.boot.gradle.plugin:2.2.4 RELEASE’)
Error Message 2:
Build file ‘build.gradle’ line: 10
Could not compile build file build.gradle’.
startup failed:
build file ‘build.gradle’: 10: all buildscript {} blocks must appear before any plugins {} blocks in the script
Searched in the following repositories:
Other Errors:
The following list options are getting failed randomly highlighted the below build.gradle details:
- plugins {}
- buildscript {}
- publishing {}
- contracts {}
Other Observations:
Tested same machine with only project has build.gradle with
dependencies {} and it is building the project. But other case it is not working. | https://discuss.gradle.org/t/gradle-build-failed-in-windows-10-operating-system/35153 | CC-MAIN-2022-21 | refinedweb | 188 | 50.23 |
The QWebPage class provides an object to view and edit web documents. More...
#include <QWebPage>
Inherits QObject.
This class was introduced in Qt 4.4. QWebPage::mainFrame(). For example, the load(), setUrl() and setHtml() unctions has loaded completely. Its argument, either true or false, indicates whether or not the load operation succeeded..
See also QWebFrame.
This enum describes the types of extensions that the page can support. Before using these extensions, you should verify that the extension is supported by calling supportsExtension().
Currently there are no extensions.
This enum describes the options available to QWebPage's findText() function. The options can be OR-ed together from the following list:
The FindFlags type is a typedef for QFlags<FindFlag>. It stores an OR combination of FindFlag values.
This enum defines the delegation policies a webpage can have when activating links and emitting the linkClicked() signal.
This enum describes the types of navigation available when browsing through hyperlinked documents.
This property holds whether QWebPage should forward unsupported content through the unsupportedContent signal.
If disabled the download of such content is aborted immediately.
By default unsupported content is not forwarded.
Access functions:
This property holds how QWebPage should delegate the handling of links through the linkClicked() signal.
The default is to delegate no links.
Access functions:
This property holds whether the page contains unsubmitted form data.
By default, this property is false.
Access functions:
This property holds the page's palette.
The background brush of the palette is used to draw the background of the main frame.
By default, this property contains the application's default palette.
Access functions:
This property holds the text currently selected.
By default, this property contains an empty string.
Access functions:
See also selectionChanged().
This property holds the size of the viewport.
The size affects for example the visibility of scrollbars if the document is larger than the viewport.
By default, for a newly-created Web page, this property contains a size with zero width and height.
Access functions:
Constructs an empty QWebView with parent parent.
Destroys the web page.().
Returns the number of bytes that were received from the network to render the current page.
See also totalBytes().
This function is called when the web content requests a file name, for example as a result of the user clicking on a "file upload" button in a HTML form.
A suggested filename may be provided in suggestedFile. The frame originating the request is provided as parentFrame.
This function is called whenever WebKit encounters a HTML object element with type "application/x-qt-plugin". The classid, url, paramNames and paramValues correspond to the HTML object element attributes and child elements to configure the embeddable.
See also acceptNavigationRequest().
Returns the frame currently active.
See also mainFrame() and frameCreated().
This signal is emitted when the user decides to download a link. The url of the link as well as additional meta-information is contained in request.
See also unsupportedContent().
This virtual function can be reimplemented in a QWebPage subclass to provide support for extensions. The option argument is provided as input to the extension; the output results can be stored in output.
The behavior of this function is determined by extension.
You can call supportsExtension() to check if an extension is supported by the page.
By default, no extensions are supported, and this function returns false.
See also supportsExtension() and Extension.
Finds the next occurrence of the string, subString, in the page, using the given options. Returns true of subString was found and selects the match visually; otherwise returns false.
Similar to QWidget::focusNextPrevChild it focuses the next focusable web element if next is true; otherwise the previous element is focused.
Returns true if it can find a new focusable element, or false if it can't.
This signal is emitted whenever the page creates a new frame.
This signal is emitted whenever the document wants to change the position and size of the page to geom. This can happen for example through JavaScript.
Returns a pointer to the view's history of navigated web pages..
This function is called whenever a JavaScript program running inside frame calls the alert() function with the message msg.
The default implementation shows the message, msg, with QMessageBox::information..
This function is called whenever a JavaScript program tries to print a message to the web browser's console.
For example in case of evaluation errors the source URL may be provided in sourceID as well as the lineNumber.
The default implementation prints nothing..
The default implementation uses QInputDialog::getText.
This signal is emitted whenever the user clicks on a link and the page's linkDelegationPolicy property is set to delegate the link handling for the specified url.
By default no links are delegated and are handled by QWebPage instead.
See also linkHovered().
This signal is emitted when the mouse is hovering over a link. The first parameter is the link url, the second is the link title if any, and third textContent is the text content. Method is emitter with both empty parameters when the mouse isn't hovering over any link element.
See also linkClicked().
This signal is emitted when a load of the page is finished. ok will indicate whether the load was successful or any error occurred.
See also loadStarted().
This signal is emitted when the global progress status changes. The current value is provided by progress and scales from 0 to 100, which is the default range of QProgressBar. It accumulates changes from all the child frames.
See also bytesReceived().
This signal is emitted when a new load of the page is started.
See also loadFinished().
Returns the main frame of the page.
The main frame provides access to the hierarchy of sub-frames and is also needed if you want to explicitly render a web page into a given painter.
See also currentFrame().
This signal is emitted whenever the visibility of the menubar in a web browser window that hosts QWebPage should be changed to visible.
This signal is emitted when for example the position of the cursor in an editable form element changes. It is used inform input methods about the new on-screen position where the user is able to enter text. This signal is usually connected to QWidget's updateMicroFocus() slot.
Returns the QNetworkAccessManager that is responsible for serving network requests for this QWebPage.
See also setNetworkAccessManager().
Returns the QWebPluginFactory that is responsible for creating plugins embedded into this QWebPage. If no plugin factory is installed a null pointer is returned.
See also setPluginFactory().
This signal is emitted whenever the page requests the web browser to print frame, for example through the JavaScript window.print() call.
See also QWebFrame::print() and QPrintPreviewDialog.
This signal is emitted whenever this QWebPage should be updated and no view was set. dirtyRect contains the area that needs to be updated. To paint the QWebPage get the mainFrame() and call the render(QPainter*, const QRegion&) method with the dirtyRect as the second parameter.
See also mainFrame() and view().
This signal is emitted whenever the content given by rectToScroll needs to be scrolled dx and dy downwards and no view was set.
See also view().
This signal is emitted whenever the selection changes.
See also selectedText().
Sets the QNetworkAccessManager manager responsible for serving network requests for this QWebPage.
See also networkAccessManager().
Sets the QWebPluginFactory factory responsible for creating plugins embedded into this QWebPage.
Note: The plugin factory is only used if the QWebSettings::PluginsEnabled attribute is enabled.
See also pluginFactory().
Sets the view that is associated with the web page.
See also view().
Returns a pointer to the page's settings object.
See also QWebSettings::globalSettings().
This signal is emitted when the statusbar text is changed by the page.
This signal is emitted whenever the visibility of the statusbar in a web browser window that hosts QWebPage should be changed to visible.
This virtual function returns true if the web page supports extension; otherwise false is returned.
See also extension()..
This signal is emitted whenever the visibility of the toolbar in a web browser window that hosts QWebPage should be changed to visible.
Returns the total number of bytes that were received from the network to render the current page, including extra content such as embedded images.
See also bytesReceived()..
See also action().
Returns a pointer to the undo stack used for editable content.
This signals is emitted when webkit cannot handle a link the user navigated to.
At signal emissions time the meta data of the QNetworkReply reply is available.
Note: This signal is only emitted if the forwardUnsupportedContent property is set to true.
See also downloadRequested().
Updates the page's actions depending on the position pos. For example if pos is over an image element the CopyImageToClipboard action is enabled.
This function is called when a user agent for HTTP requests is needed. You can re-implement this function to dynamically return different user agent's for different urls, based on the url parameter.
The default implementation returns the following value:
"Mozilla/5.0 (%Platform%; %Security%; %Subplatform%; %Locale%) AppleWebKit/%WebKitVersion% (KHTML, like Gecko, Safari/419.3) %AppVersion"
In this string the following values are replaced at run-time:
Returns the view widget that is associated with the web page.
See also setView().
This signal is emitted whenever the page requests the web browser window to be closed, for example through the JavaScript window.close() call. | http://doc.trolltech.com/4.4/qwebpage.html | crawl-002 | refinedweb | 1,564 | 51.44 |
This meter is just plan bad. I bought it to use with some solar projects. It works ok for things like say measuring a 20V panel but anything else it just seems to not work. I have the same problem of a negative reading on a battery or showing no voltage not matter what setting I try. Doesn't read any small things acurately, was not happy I spend a good chunk of change for something so bad.
(Caveat: under testing I found that it did not seem to work reliably much under 2.8V at 8 MHz).
Voltage Clock Current (MHz) (mA) 5.0 16*a 16.5 4.0 16 9.1 3.3 16 6.7 3.0 16 6.0 2.5 16 1.0 did not run 5.0 8*b 12.3 4.0 8 5.5 3.3 8 3.7 3.0 8 3.3 2.8 8 3.0 2.5 8 0.4 did not run*a Low fuse = 0xFF*b Low fuse = 0xE2
Voltage Clock Current (MHz) (mA) 5.0 16*a 16.5 4.0 16 9.1 3.3 16 6.7 3.0 16 6.0 2.8 16 5.5 2.5 16 4.8 2.4 16 4.6 2.3 16 4.3 2.2 16 4.1 2.1 16 3.8 2.0 16 did not run 5.0 8*b 12.3 4.0 8 5.5 3.3 8 3.7 3.0 8 3.3 2.8 8 3.0 2.5 8 2.7 2.4 8 2.5 2.3 8 2.4 2.2 8 2.3 2.1 8 2.1 2.0 8 2.0*a Low fuse = 0xFF*b Low fuse = 0xE2
I disabled brown-out detection
#include <avr/sleep.h> void setup() { for (int i = 0; i <= A5; i++) { pinMode (i, OUTPUT); digitalWrite (i, LOW); } // disable ADC ADCSRA = 0; // turn off various modules PRR = 0xFF; set_sleep_mode (SLEEP_MODE_PWR_DOWN); sleep_enable(); sleep_cpu (); }void loop() { }
My measurements previously indicated configuring the pins as outputs made a difference, but we are talking around 1 microamp, not milliamps.
One of the most important considerations is to ensure a defined level on all I/O pins. A floating pin will give a significant increase in the overall power consumption.
Basically any "standard" CMOS input stage is an inverter and will consume non-trivial power if the input is somewhere in the middle of the range (the "forbidden region"). Here non-trivial means its an issue for battery-powered circuitry in sleep mode - something on the scale of 1mA might flow from that one input circuit when the whole chip is supposed to be shutdown (a few uA usually).
9.10.6 Port PinsWhen entering a sleep mode, all port pins should be configured to use minimum power. The most important is then to ensure that no pins drive resistive loads. In sleep modes where both the I/O clock (clkI/O) and the ADC clock (clkADC) 79 for details on which pins are enabled. If the input buffer is enabled and the input signal is left floating or have an analog signal level close to VCC/2, the input buffer will use excessive power. | https://forum.arduino.cc/index.php?topic=138473.msg1042839 | CC-MAIN-2021-17 | refinedweb | 546 | 88.02 |
Created on 2007-08-14 22:35 by christian.heimes, last changed 2008-01-06 22:29 by admin. This issue is now closed.
The patch renames __builtins__ to __builtin__ in the C and Python sources and renames builtins to builtin in the C code.
Missing:
* documentation update
* 2to3 fixer
Thanks!
(Though I wish you'd left the C variable names alone, the patch is unnecessarily big this way.)
I am also wondering about some semantic endcases; in 2.x, it is *possible* to have __builtin__ and __builtins__ point to different place, and I am going to do some soul-searching to make sure that's not a loss of functionality.
No need to update the patch, I just have to think about it some more.
Personally I prefer to have one and just one way to spell a variable. I'd find it confusing to have __builtin__ (singular form) but a C variable named builtins (plural form). I changed it for aesthetic and consistency reasons.
I've thought this over very carefully, and I want something different --
I want to keep both concepts, but I want to rename __builtins__ to
__rootns__ (i.e. Root namespace), indicating its purpose. This will
prevent further confusion while not conflating the two different features. | http://bugs.python.org/issue1774369 | CC-MAIN-2014-42 | refinedweb | 211 | 75.1 |
Implements a powerful analytics library using Redis bitmaps.
Project description?
This library is very easy to use and enables you to create your own reports easily.
Using Redis bitmaps you can store events for millions of users in a very little amount of memory (megabytes). You should be careful about using huge ids (e.g. 2^32 or bigger) as this could require larger amounts of memory. # Delete the temporary AND operation active_2_months.delete()
As something new tracking hourly is disabled (to save memory!) To enable it as default do:
import bitmapist bitmapist.TRACK_HOURLY = True
Additionally you can supply an extra argument to mark_event to bypass the default value:
mark_event('active', 123, track_hourly=False)
Developer: Amir Salihefendic ( )
License: BSD
Project details
Release history Release notifications
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/bitmapist/3.96/ | CC-MAIN-2019-09 | refinedweb | 146 | 57.37 |
Riddler: Can You Beat MLB Recods?
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
FiveThirtyEight’s Riddler Express
From Taylor Firman comes an opportunity to make baseball history:
This year, Major League Baseball announced it will play a shortened
60-game season, as opposed to the typical 162-game season. Baseball is
a sport of numbers and statistics, and so Taylor wondered about the
impact of the season’s length on some famous baseball records.
Some statistics are more achievable than others in a shortened season.
Suppose your true batting average is .350, meaning you have a 35
percent chance of getting a hit with every at-bat. If you have four
at-bats per game, what are your chances of batting at least .400 over
the course of the 60-game season?2 And how does this compare to your
chances of batting at least .400 over the course of a 162-game season?
Plan
This riddle should be pretty straight forward to solve statistically and
with simulations, so I will do both.
Setup
knitr::opts_chunk$set(echo = TRUE, comment = "#>", cache = FALSE, dpi = 400) library(mustashe) library(tidyverse) library(conflicted) # Handle any namespace conflicts. conflict_prefer("filter", "dplyr") conflict_prefer("select", "dplyr") # Default 'ggplot2' theme. theme_set(theme_minimal()) # For reproducibility. set.seed(123)
Statistical solution
This is a simple binomial system: at each at bat, the player either gets
a hit or not. If their real batting average is 0.350, that means the
probability of them getting a hit during each at bat is 35%. Thus,
according the the Central Limit Theorem, given a sufficiently large
number of at bats, the frequency of a hit should be 35%. This is because
the distribution converges towards the mean. However, at smaller
sample-sizes, the distribution is more broad, meaning that the observed
batting average has a greater chance of being further away from the true
value.
First, let’s answer the riddle. The solution is just the probability of
observing a batting average of 0.400 or greater. The first value is
computed using
dbinom() and the second cumulative probability is
calculated using
pbinom(), setting
lower.tail = FALSE to get the
tail above 0.400.
num_at_bats <- 60 * 4 real_batting_average <- 0.350 target_batting_average <- 0.400 prob_at_400 <- dbinom(x = target_batting_average * num_at_bats, size = num_at_bats, prob = real_batting_average) prob_above_400 <- pbinom(q = target_batting_average * num_at_bats, size = num_at_bats, prob = real_batting_average, lower.tail = FALSE) prob_at_400 + prob_above_400 #> [1] 0.06083863
Under the described assumptions, there is a 6.1% chance of reaching a
batting average of 0.400 in the shorter season.
For comparison, the chance for a normal 162-game season is calculated
below. Because $0.400 \times 162 \times 4$ is a non-integer value, an
exact 0.400 batting average cannot be obtained. Therefore, only the
probability of a batting average greater than 0.400 needs to be
calculated.
num_at_bats <- 162 * 4 real_batting_average <- 0.350 target_batting_average <- 0.400 prob_above_400 <- pbinom(q = target_batting_average * num_at_bats, size = num_at_bats, prob = real_batting_average, lower.tail = FALSE) prob_above_400 #> [1] 0.003789922
Over 162 games, there is a 0.4% chance of achieving a batting average of
at least 0.400.
Simulation
The solution to this riddle could also be found by simulating a whole
bunch of seasons with the real batting average of 0.350 and then just
counting how frequently the simulations resulted in an observed batting
average of 0.400.
A single season can be simulated using the
rbinom() function where
n
is the number of seasons to simulate,
size takes the number of at
bats, and
prob takes the true batting average. The returned value is a
sampled number of hits (“successes”) over the season from the binomial
distribution.
The first example shows the observed batting average from a single
season.
num_at_bats <- 60 * 4 real_batting_average <- 0.350 target_batting_average <- 0.400 rbinom(n = 1, size = num_at_bats, prob = real_batting_average) / num_at_bats #> [1] 0.3375
The
n = 1 can just be replaced with a large number to simulate a bunch
of seasons. The average batting average over these seasons should be
close to the true batting average.
n_seasons <- 1e6 # 1 million simulations. sim_res <- rbinom(n = n_seasons, size = num_at_bats, prob = real_batting_average) sim_res <- sim_res / num_at_bats # The average batting average is near the true batting average of 0.350. mean(sim_res) #> [1] 0.3500121
The full distribution of batting averages over the 1 million simulations
is shown below.
tibble(sims = sim_res) %>% ggplot(aes(x = sims)) + geom_density(color = "black", fill = "black", adjust = 2, alpha = 0.2, size = 1.2, ) + geom_vline(xintercept = target_batting_average, color = "tomato", lty = 2, size = 1.2) + scale_y_continuous(expand = expansion(mult = c(0.01, 0.02))) + theme(plot.title = element_text(hjust = 0.5)) + labs(x = "1 million simulated season batting averages", y = "probability density", title = "Distribution of simulated batting averages in a 60-game season")
The answer from the simulation is pretty close to the actual answer.
mean(sim_res >= 0.40) #> [1] 0.060813
One last visualization I want to do demonstrates why the length of the
season matters to the distribution. Instead of using
rbinom() to
simulate the number of successes over the entire season, I use it below
to simulate a season’s-worth of individual at bats, returning a vector
of 0’s and 1’s. I then plotted the cumulative number of hits at each at
bat and colored the line by the running batting average.
The coloring shows how the batting average was more volatile when there
were fewer at bats.
sampled_at_bats <- rbinom(60*4, 1, 0.35) tibble(at_bat = sampled_at_bats) %>% mutate(i = row_number(), cum_total = cumsum(at_bat), running_avg = cum_total / i) %>% ggplot(aes(x = i, y = cum_total)) + geom_line(aes(color = running_avg), size = 1.2) + scale_color_viridis_c() + theme(plot.title = element_text(hjust = 0.5), legend.position = c(0.85, 0.35)) + labs(x = "at bat number", y = "total number of hits", color = "batting average", title = "Running batting average over a simulated season")
The following two plots do the same analysis many times to simulate many
seasons and color the lines by whether or not the final batting average
was at or above 0.400. As there are more games, the running batting
averages, which are essentially biased random walks, regress towards the
true batting average. (Note that I had to do 500 simulations for the
162-game season to get any simulations with a final batting average
above 0.400.)
simulate_season_at_bats <- function(num_at_bats) { sampled_at_bats <- rbinom(num_at_bats, size = 1, prob = 0.35) tibble(result = sampled_at_bats) %>% mutate(at_bat = row_number(), cum_total = cumsum(result), running_avg = cum_total / at_bat) } tibble(season = 1:100) %>% mutate(season_results = map(season, ~ simulate_season_at_bats(60 * 4))) %>% unnest(season_results) %>% group_by(season) %>% mutate( above_400 = 0.4 <= running_avg[which.max(at_bat)], above_400 = ifelse(above_400, "BA ≥ 0.400", "BA < 0.400") ) %>% ungroup() %>% ggplot(aes(x = at_bat, y = cum_total)) + geom_line(aes(group = season, color = above_400, alpha = above_400), size = 0.8) + geom_hline(yintercept = 0.4 * 60 * 4, color = "tomato", lty = 2, size = 1) + scale_color_manual(values = c("grey50", "dodgerblue")) + scale_alpha_manual(values = c(0.1, 1.0), guide = FALSE) + scale_x_continuous(expand = c(0, 0)) + theme(plot.title = element_text(hjust = 0.5), plot.subtitle = element_text(hjust = 0.5), legend.position = c(0.85, 0.25)) + labs(x = "at bat number", y = "total number of hits", color = NULL, title = "Running batting averages over simulated 60-game seasons", subtitle = "Blue lines indicate a simulation with a final batting average of at least 0.400.")
>. | https://www.r-bloggers.com/2020/07/riddler-can-you-beat-mlb-recods/ | CC-MAIN-2020-45 | refinedweb | 1,217 | 50.73 |
Fuzzy matching is a general term for finding strings that are almost equal, or mostly the same. Of course almost and mostly are ambiguous terms themselves, so you’ll have to determine what they really mean for your specific needs. The best way to do this is to come up with a list of test cases before you start writing any fuzzy matching code. These test cases should be pairs of strings that either should fuzzy match, or not. I like to create doctests for this, like so:
def fuzzy_match(s1, s2): ''' >>> fuzzy_match('Happy Days', ' happy days ') True >>> fuzzy_match('happy days', 'sad days') False ''' # TODO: fuzzy matching code return s1 == s2
Once you’ve got a good set of test cases, then it’s much easier to tailor your fuzzy matching code to get the best results.
Normalization
The first step before doing any string matching is normalization. The goal with normalization is to transform your strings into a normal form, which in some cases may be all you need to do. While
'Happy Days' != ' happy days ', with simple normalization you can get
'Happy Days'.lower() == ' happy days '.strip().
The most basic normalization you can do is to lowercase and strip whitespace. But chances are you’ll want to more. For example, here’s a simple normalization function that also removes all punctuation in a string.
import string def normalize(s): for p in string.punctuation: s = s.replace(p, '') return s.lower().strip()
Using this
normalize function, we can make the above fuzzy matching function pass our simple tests.
def fuzzy_match(s1, s2): ''' >>> fuzzy_match('Happy Days', ' happy days ') True >>> fuzzy_match('happy days', 'sad days') False ''' return normalize(s1) == normalize(s2)
If you want to get more advanced, keep reading…
Regular Expressions
Beyond just stripping whitespace from the ends of strings, it’s also a good idea replace all whitespace occurrences with a single space character. The regex function for doing this is
re.sub('\s+', s, ' '). This will replace every occurrence of one or more spaces, newlines, tabs, etc, essentially eliminating the significance of whitespace for matching.
You may also be able to use regular expressions for partial fuzzy matching. Maybe you can use regular expressions to identify significant parts of a string, or perhaps split a string into component parts for further matching. If you think you can create a simple regular expression to help with fuzzy matching, do it, because chances are, any other code you write to do fuzzy matching will be more complicated, less straightforward, and probably slower. You can also use more complicated regular expressions to handle specific edge cases. But beware of any expression that takes puzzling out every time you look at it, because you’ll probably be revisiting this code a number of times to tweak it for handling new cases, and tweaking complicated regular expressions is a sure way to induce headaches and eyeball-bleeding.
Edit Distance
The edit distance (aka Levenshtein distance) is the number of single character edits it would take to transform one string into another. Thefore, the smaller the edit distance, the more similar two strings are.
If you want to do edit distance calculations, checkout the standalone editdist module. Its
distance function takes 2 strings and returns the Levenshtein edit distance. It’s also implemented in C, and so is quite fast.
Fuzzywuzzy
Fuzzywuzzy is a great all-purpose library for fuzzy string matching, built (in part) on top of Python’s difflib. It has a number of different fuzzy matching functions, and it’s definitely worth experimenting with all of them. I’ve personally found
ratio and
token_set_ratio to be the most useful.
NLTK
If you want to do some custom fuzzy string matching, then NLTK is a great library to use. There’s word tokenizers, stemmers, and it even has its own edit distance implementation. Here’s a way you could combine all 3 to create a fuzzy string matching function.
from nltk import metrics, stem, tokenize stemmer = stem.PorterStemmer() def normalize(s): words = tokenize.wordpunct_tokenize(s.lower().strip()) return ' '.join([stemmer.stem(w) for w in words]) def fuzzy_match(s1, s2, max_dist=3): return metrics.edit_distance(normalize(s1), normalize(s2)) <= max_dist
Phonetics
Finally, an interesting and perhaps non-obvious way to compare strings is with phonetic algorithms. The idea is that 2 strings that sound same may be the same (or at least similar enough). One of the most well known phonetic algorithms is Soundex, with a python soundex algorithm here. Another is Double Metaphone, with a python metaphone module here. You can also find code for these and other phonetic algorithms in the nltk-trainer phonetics module (copied from a now defunct sourceforge project called advas). Using any of these algorithms, you get an encoded string, and then if 2 encodings compare equal, the original strings match. Theoretically, you could even do fuzzy matching on the phonetic encodings, but that’s probably pushing the bounds of fuzziness a bit too far. | https://streamhacker.com/tag/phonetic/ | CC-MAIN-2017-34 | refinedweb | 830 | 62.68 |
:sdrhodus wrote @ Wed, 30 Mar 2005 13:17:46 +0000: : :> I know that Matt and myself almost regularly do various NFS testing, :> and lots of the time the testing does involve using fsx. Though any :> outside validity testing is always welcome. : :This happens on my NFS over tcp mount, :the server is an via epia with 256MB RAM. : :$ /usr/src/test/stress/fsx/dotest :Chance of close/open is 1 in 100000 :truncating to largest ever: 0x2abbd1 :truncating to largest ever: 0x3abe49 :truncating to largest ever: 0x3b1956 :truncating to largest ever: 0x3e2816 :nfs server morex:/data: not responding :nfs server morex:/data: is alive again :truncating to largest ever: 0x3e8ae7 :nfs server morex:/data: not responding :nfs server morex:/data: is alive again :truncating to largest ever: 0x3f959f :nfs server morex:/data: not responding :Segmentation fault : : :Andy Ok, Andrew, see if FSX still fails with this patch. I think some of the recent work I did broke the ftruncate() code. I was hoping that the recent TCP issue was the cause but I can get fsx to seg-fault occassionally still and it happens on a UDP mount so there's definitely a bug still in there. The issue here is that ftruncate() does some buffer flushing before it issues the setattr RPC. The buffer flushing can feed back (because RPC responses from the server often include attribute information) and confuse the NFS client's notion of the file's size. I give this about a 70% chance of fixing the problem. The code interactions are very complex so I don't know for sure. -Matt Matthew Dillon <dillon@xxxxxxxxxxxxx> Index: nfs_vnops.c =================================================================== RCS file: /cvs/src/sys/vfs/nfs/nfs_vnops.c,v retrieving revision 1.38 diff -u -r1.38 nfs_vnops.c --- nfs_vnops.c 17 Mar 2005 17:28:46 -0000 1.38 +++ nfs_vnops.c 6 Apr 2005 04:41:57 -0000 @@ -736,13 +736,23 @@ return (EROFS); /* - * We run vnode_pager_setsize() early (why?), - * we must set np->n_size now to avoid vinvalbuf - * V_SAVE races that might setsize a lower - * value. + * This is nasty. The RPCs we send to flush pending + * data often return attribute information which is + * cached via a callback to nfs_loadattrcache(), which + * has the effect of changing our notion of the file + * size. Due to flushed appends and other operations + * the file size can be set to virtually anything, + * including values that do not match either the old + * or intended file size. + * + * When this condition is detected we must loop to + * try the operation again. Hopefully no more + * flushing is required on the loop so it works the + * second time around. THIS CASE ALMOST ALWAYS + * HAPPENS! */ - tsize = np->n_size; +again: error = nfs_meta_setsize(vp, ap->a_td, vap->va_size); if (np->n_flag & NLMODIFIED) { @@ -750,30 +760,28 @@ error = nfs_vinvalbuf(vp, 0, ap->a_td, 1); else error = nfs_vinvalbuf(vp, V_SAVE, ap->a_td, 1); - if (error) { - np->n_size = tsize; - vnode_pager_setsize(vp, np->n_size); - return (error); - } } - /* - * np->n_size has already been set to vap->va_size - * in nfs_meta_setsize(). We must set it again since - * nfs_loadattrcache() could be called through - * nfs_meta_setsize() and could modify np->n_size. - * - * (note that nfs_loadattrcache() will have called - * vnode_pager_setsize() for us in that case). + /* + * note: this loop case almost always happens at + * least once per truncation. */ - np->n_vattr.va_size = np->n_size = vap->va_size; + if (error == 0 && np->n_size != vap->va_size) + goto again; + np->n_vattr.va_size = vap->va_size; break; } } else if ((vap->va_mtime.tv_sec != VNOVAL || vap->va_atime.tv_sec != VNOVAL) && (np->n_flag & NLMODIFIED) && vp->v_type == VREG && - (error = nfs_vinvalbuf(vp, V_SAVE, ap->a_td, 1)) == EINTR) + (error = nfs_vinvalbuf(vp, V_SAVE, ap->a_td, 1)) == EINTR + ) { return (error); + } error = nfs_setattrrpc(vp, vap, ap->a_cred, ap->a_td); + if (error == 0 && np->n_size != vap->va_size) { + printf("NFS ftruncate: server disagrees on the file size: %lld/%lld/%lld\n", tsize, vap->va_size, np->n_size); + goto again; + } if (error && vap->va_size != VNOVAL) { np->n_size = np->n_vattr.va_size = tsize; vnode_pager_setsize(vp, np->n_size); | https://www.dragonflybsd.org/mailarchive/users/2005-04/msg00174.html | CC-MAIN-2017-09 | refinedweb | 642 | 55.13 |
You already noticed the functions print and println for printing to the terminal.
To read input from the terminal, we use the readString() function. It prints a prompt, then waits for the user to enter a line. The result of the function is a string, so you may have to convert it to a number. Here is an example (drinks.kts):
import org.otfried.cs109.readString var name = readString("What's your name? ").trim() var answer = readString("Hi $name, would you like a beer? ").trim().toLowerCase() if (answer == "yes" || answer == "y") { var num = readString("How many beer will you have? ").toInt() if (num > 5) println("That sounds a bit excessive!") else if (num < 2) println("Don't be shy...") else println("Here you are.") } | http://otfried.org/courses/cs109/tutorial-read-terminal.html | CC-MAIN-2018-05 | refinedweb | 124 | 78.96 |
This action might not be possible to undo. Are you sure you want to continue?
BLACK MAGIC AND ITS CURE. The jinn are real and they can indeed harm humans, . PRESCRIBED MEANS OF WARDING OFF SIHR(WITCHCRAFT) BEFORE IT HAPPENS: What are the prescribed means of warding off sihr before it happens?. we obey. (We seek) Your forgiveness, our Lord, and to You is the return (of all)., Aba aynin Abd al- Azeez ibn Baaz (may Allaah have mercy on him), vol. 8
And all of you beg Allaah to forgive you all. The believing women are forbidden to show any of their beauty to non-mahrams. their sisters in Islam). or their sister s sons. but not from one of them. p. and whoever wears seashells [for protection from the evil eye] may Allaah not protect him.HOW TO PROTECT ONESELF AGAINST THE EVIL EYE: Praise be to Allaah. and will protect you from the punishment of Allaah in the Hereafter. because Allaah says (interpretation of the meaning): O you who believe! Enter perfectly in Islam (by obeying all the rules and regulations of the Islamic religion) and follow not the footsteps of Shaytaan (Satan). and to draw their veils all over Juyoobihinna (i. he is less likely to be affected by the evil eye and other kinds of harm from the devils of mankind and the jinn. And let them not stamp their feet so as to reveal what they hide of their adornment. apron). Whoever wears an amulet is guilty of shirk. there is no doubt that when a person is close to Allaah. O Messenger of Allaah. According to another report. always remembering Him (dhikr) and reading Qur aan. al-Falaq and al-Naas). With regard to wearing Qur aanic verses or certain shapes. necks and bosoms) and not to reveal their adornment except to their husbands. 277) With regard to dealing with the evil eye and hasad (destructive envy). You should know that hijaab is obligatory. He said. that you may be successful [al-Noor 24:31] Obeying Allaah s command to observe hijaab will protect you from the evil eye by Allaah s Leave in this world. Soorat al-Faatihah and Aayat al-Kursiy [al-Baqarah 2:255]. O believers. . Verily. to follow all the commandments and heed all the prohibitions. or outer palms of hands or one eye or dress like veil. faces. (Tafseer Ibn Katheer. and the Prophet (peace and blessings of Allaah be upon him) accepted his bay ah. or their husband s sons. their bodies. Imaam Ahmad narrated in his Musnad from Uqbah ibn Aamir (may Allaah be pleased with him) that the Prophet (peace and blessings of Allaah be upon him) said: Whoever wears an amulet.e. and no one has the right to choose the rulings that they like and leave those for which they feel no inclination. Then he took it in his hand and broke it. headcover. or their fathers. He is wearing an amulet. you accepted the bay ah of nine and not from this one.Ayn wa l-Hasad. or their sons. or their husband s fathers. or old male servants who lack vigour. 1/566). The Prophet (peace and blessings of Allaah be upon him) used to seek refuge with Allaah for himself. or their brothers or their brother s sons. Allaah says (interpretation of the meaning): and not to show off their adornment except only that which is apparent (like both eyes for necessity to see the way. or their (Muslim) women (i. gloves. (From Fataawa al. he is to you a plain enemy [al-Baqarah 2:208] Ibn Katheer said: Allaah commands His believing slaves to adhere to all the rulings and laws of Islam. a group came to the Messenger of Allaah (peace and blessings of Allaah be upon him) and he accepted the bay ah [allegiance] of nine of them. He said. They said. and the greatest means of seeking refuge that is available to the Muslim is reading the Book of Allaah. or small children who have no sense of feminine sex. or the (female) slaves whom their right hands possess. above all the Mi wadhatayn (the last two Soorahs of the Qur aan. may Allaah not fulfil his need.e.
Al-Albaani said. al-Khattaabi said: What is meant here is every disease or harm that a person may suffer such as insanity or mental disturbance. One of the best treatments is the use of ruqyah.inshaAllah the sick person . from every devil and every poisonous reptile. No. and then the man who was affected would wash himself with (the water). al-Salaam. its isnaad is saheeh. because it will be like a stronghold for him. Bismillaahi arqeeka min kulli shay in yu dheeka. in the name of Allaah I perform ruqyah for you). It was narrated that Aa ishah (may Allaah be pleased with her) said: The Messenger of Allaah (peace and blessings of Allaah be upon him) commanded me. With regard to the meaning of laammah (translated here as bad ). (Narrated by al-Bukhaari. aynin laammah (I seek refuge in the perfect words of Allaah. 4056) Undoubtedly. bismillaahi arqeek (In the name of Allaah I perform ruqyah for you. 5297) And it was narrated that Aa ishah (may Allaah be pleased with her) said: The man who cast the evil eye would be commanded to do wudoo . 4/162). Ahaadeeth al-Anbiyaa . 3282) These are some of the du aa s and treatments which offer protection by Allaah s leave from the evil eye and from destructive envy (hasad). or he commanded (the people) to use ruqyah to deal with the evil eye. Yes. are you ill? He said. in Saheeh Sunan Abi Dawood. He said: Your father [i. So everyone should strive to recite these adhkaar. and from every bad eye). min sharri kulli nafsin aw aynin haasid Allaahu yashfeek. (narrated by al-Bukhaari.e. 3382. which the Messenger of Allaah (peace and blessings of Allaah be upon him) permitted for protection from the evil eye and he instructed people to use it. **VERSES FROM THE HOLY QURAN TO BE RECITED WHEN A PERSON IS UNDER A SPELL OR EVIL INFLUENCE: If a person is under a spell or evil inflence the following ayats are to be read. See Zaad al-Ma aad by Ibn al-Qayyim.. by Allaah s Leave. We ask Allaah to protect us from that. (Narrated by Muslim. when a person persists in reciting the adhkaar (dhikr) for morning and evening. And Allaah knows best. from everything that is harming you. and the adhkaar for going to sleep. from the evil of every soul or envious eye may Allaah heal you. (Narrated by Muslim. 3120). al-Tibb. (Narrated by Abu Dawood. al-Tibb. al-Dhikr wa l-Du aa. He said. 4881) It was narrated that Ibn Abbaas (may Allaah be pleased with them both) said: The Prophet (peace and blessings of Allaah be upon him) used to seek refuge with Allaah for al-Hasan and al-Husayn. this will have a great effect in protecting him from the evil eye. and others. It was narrated from Abu Sa eed that Jibreel came to the Prophet (peace and blessings of Allaah be upon him) and said: O Muhammad.
Place your hands over the forehead of the sick person. 1...Fantastic.Marvellous.verse 255(full ayat ul kursi) 4.(You can also blow it in the water and give it to the sick person).verse 70 8. Surah Al_Mu munum >.Mind Blowing.. Surah Ya-Sin >..Splendid.I 'm So Thankful To You 4 This Favour..read the following ayaths near his/her ears without any interruption in between and blow onto the sick person... Surah Al-Anbiya >..verse 9 9.shall be free from such evil influence. Surah Al-Baqarah >..SurahAl-Fatih>..I Really Appreciate Of Your Hardworking.. Surah Al-Nisa >-verse 54 5.verse 39 6.verse 17-20 3.verse 51 **Taken from the book >-..Excellent ..ks 4 Providing Us So Beneficial Info Well. Surah Al-Kahf >..verse 18 7. I Have Also Too Many Words Relating To This Topic And I Wanna Include Them Also ..Superb And Knowledgeable Words..! Than.....full 2...abdul mundhir khaleel ibn ibrahim amen Ayesha Thanks 4 Tag Me Here Dear. Surah Al-Mulk >.Outstanding.verse 4 10.. Make Wudhu(even the sick person) face towards Qibla(even the sick person)... Surah Al-Qalam >.The Jinn And Human Sickness Abdul Mundhir Khaleel Ibn Ibrahim Ameenthe jinn and human sickness . Surah Al-Baqarah >..
As each verse was recited. namely Surah al-Falaq and Surah al-Nas. I used to recite these two Surahs (and blow my breath) over him and make him rub his body with his own hand. scholars mention that the recitation of the Mu¶awwazatayn (the two Quls: al-Falaq and alNas) is very beneficial in the removing of and protection from black magic. According To Islam In the name of Allah.So Here's I 'm Going To Tell You About More Of Black Magic. At the eleventh knot. 4728) Apart from these two Surahs. One should make a habit of reciting these especially when retiring to bed and after the Fardh prayers. A Jew by the name of Labid ibn Asim who outwardly posed to be a believer (munafiq) carried out black magic on the Messenger of Allah (Allah bless him & give him peace). and last two verses of Surah al-Baqarah is also very beneficial. the knots untied miraculously. no. At times the Messenger of Allah (Allah bless him & give him peace) felt he had accomplished something yet he had not done so and vice versa. the Jews would have turned me into a donkey (m: out of black magic). The Messenger of Allah (Allah bless him & give him peace) was also afflicted with black magic. He took the hair of the Messenger of Allah (Allah bless him & give him peace) and made eleven knots and placed it under a rock in a well called Zarwan. (See: Tafisir Ibn Kathir & Ma¶arif al-Qur¶an) Thus.. There are many virtues of these two Surahs mentioned in the Ahadith. The effect of this was that it created uncertainty in the mind of the Messenger of Allah (Allah bless him & give him peace) as to whether he had done or not done certain things (although this had no effect on his religious and prophetic obligations). Ka¶b al-Ahbar (Allah be pleased with him) states: ³Had it not been for the phrases that I recite regularly. Ayat al-Kursi. It was said to him: ³What are these phrases?´ He replied: Transliteration: ³A¶uzu bi wajhillah al-Adhim alladhi laysa shay¶un a¶dhamu minhu wa bi kalimatillah attammati allati la yujawizuhunna barrun wa la fajir wa bi asmaillah al-husna kulliha ma alimtu . for its blessings. Black magic (sihr) is something that definitely exists and causes harm to people. The Messenger of Allah (Allah bless him & give him peace) together with the Companions (Allah be pleased with them all) went to the well and removed the knotted hair. When his illness was aggravated. The angel Jibra¶il informed the Messenger of Allah (Allah bless him & give him peace) as to what had occurred and came down with the two Surahs. he would recite the Mu¶awwizat (Surah al-Falaq & Surah an-Nas) and blow over himself. Most Compassionate. Most Merciful. the famous Tibi¶i. Sayyida A¶isha (Allah be pleased with her) narrates that whenever the Messenger of Allah (Allah bless him & give him peace) would become ill. the Messenger of Allah (Allah bless him & give him peace) was relieved from the effects of this black magic.´ (Sahih al-Bukhari. Moreover.. the recitation of Surah al-Fatiha.
There are also other remedies besides the above. but time does not allow me to mention them all. and which He has spread (over the earth or universe). if the relations of the husband and wife turn sour.´ Translation: ³I seek the protection of Allah the Great. This type of understanding is incorrect. in that they deceive people in making them believe that they have some sort of black magic done upon them.´ (Sahih al-Bukhari. the above supplication can be very beneficial in the removing of the effect of black magic. then the parents begin to regard it to be the cause of black magic.minha wa ma lam a¶lam min sharri ma khalaqa wa bara¶a wa zara¶a. will not be affected by poison or magic on the day he eats them. I would like to state that undoubtedly black magic is something that exits. One should not be too hasty in concluding that the cause of a problem is black magic. And in the case of being afflicted with it. the consuming of Ajwa dates has been prescribed by the Messenger of Allah (Allah bless him & give him peace) as a remedy for black magic. thus they are charged with a massive sum for the treatment. from the evil of everything He (Allah) created. Also. Amir ibn Sa¶d narrates from his father that the Messenger of Allah (Allah bless him & give him peace) said: ³He who eats seven Ajwa dates every morning. to which He has given existence. and I seek the protection of all the beautiful names of Allah. 2/541. And I seek the protection of the perfect words of Allah which no man. thus one may resort to any of them. Secondly. if there is substantial evidence such as the sudden break of illness. than whom there is nothing greater. Finally Before parting. 2737) Thus. If a child refuses to marry someone whom the parents want him/her to marry. then one may determine whether it is the cause of black magic or otherwise. Black magic is regarded to be the cause behind every minor and major illness. no. black magic has nothing to do with the problem. no. one should be very careful in these matters. many people have made it a business. He. However. etc. for in it rests the benefit of this world and the hereafter. Similarly.´ (Recorded by Imam Malik in his al-Muwatta. People have made thousands in this business. the first assumption is that it must be black magic that was carried out by such and such person. those of them which I know and those which I do not know. due to this. Thus. but it is observed that many people experience some type of downfall or illness and quickly jump to the conclusion that somebody has carried out black magic and start pointing fingers at others. one must primarily turn to Allah Most High and resort to the remedies mentioned in the . Do not be too hasty in determining that the cause behind the problem is black magic. virtuous or evil. because more often than not. can even transcend. 5130) The above are just some of the methods in removing the effect of black magic that have been prescribed in the Sunnah.
They disputed with him in an investigat. The earth opened up and swallowed the rebels alive. but their wives and children as well. there are some critical and fundamental differences. evoking the curse of Allah. but he prayed that their sons and wives would be cursed too! Islam tries to harm not only the evangelists. While Muhammad was ruling in Medina a delegation of about 60 Christians from the Najran Valley in North Yemen visited him. kill. then one should only turn to those who are god-fearing and pious. because Jesus taught Christians not to test God. However. Not only did he pray for the curse of Allah to be against the Bishop and his men. One can read Muhammad¶s basic answers to the Christians in Sura al-e-Imran 3:33-64 The delegation from Najran would not compromise with Muhammad and deny the Son of God or disown his atoning death on the Cross. and invoke the curse of Allah on those who lie!" Perhaps. We no longer live under the law of the Old Covenant but are confirmed in the Covenant of Grace by our Lord Jesus Christ. This is in complete contrast to command of Jesus who said. or destroy their enemies. Muslims implement prayers in the form of black magic to injure. They seek their divine care to prevent physical harm as well as spiritual protection for their family¶s faith.ory dialogue for two or three days in the mosque (Masjid) at Medina. Yet.. . Muhammad remembered the Judgment of Yahweh against Korah and his men that occurred during the days of Moses (Numbers.1 A bishop and his scholars wanted to know what kind of a spirit Muhammad had. He accepted essential facts of the life of Christ. Also. Muhammad tried greatly to compromise with the Christians in order to win them for Islam without forsaking the principles of his faith. Muhammad said. We read in Sura al-eImran 3:61 "Come! let us gather together. Everyone who serves God among Muslims prays and commits all their family members to Jesus every day. Matthew 5:44 The curse of Allah dissolves before all who live under the redeeming blood of Jesus ..our sons and your sons. The bishop and his delegation did not accept the Muhammad¶s superstition. Muhammad altered the basis for Yahweh¶s judgment against the men of Korah. if the help of others is sought. But I tell you: Love your enemies and pray for those who persecute you.16:1-35). The men of Korah were rebelling against the leadership of Moses while the Christians from Najran were making a peaceful inquiry.Qur¶an and Sunnah. ourselves and yourselves: Then let us earnestly pray.. "Let us pray and so lay the curse of Allah upon the ones who lie!" This is a destructive prayer. Muhammad was upset and said that the Christian and the Muslims should be exposed to the Judgment of Allah immediately. It is essential to remember the extent of what Muhammad did. Yet he rejected Christ¶s divinity and crucifixion. Also. our women and your women. damage. in an Islamic way.
The spirit of Islam is a power which. By contrast. let him be accursed. by the revelation of the supposed Angel Gabriel. cemeteries.'" Matthew 4:7 But this challenge of Muslims against Christians.Jesus said to him. However. according to the Qur'an. It is evident from the Qur'an and the Hadith that Jinn are the creations of Allah and are made from Fire.. but on the evil spirit of hatred and cursing ± may this evil spirit be totally drive it out! Black Magic and evil Jinn both exist in Islam and have been proven by the Quran and Hadith. "On the other hand. Jinn do not generally get involved with the humans unless they are disturbed or powered by the spirits. Good Muslim Jinn tend to live in isolated places where they can worship Allah without disturbance and this can be in the Masjid. Because of their fiery nature there are more evil Jinn hence disbelievers and are also referred to as Shaytaans.. Like Angels they cannot be seen by the norm. The Prophet of Allah (Allah bless him & give him peace) advised the Muslims to pray µAllahumma Inni A¶oothubika Minal Khuboosi Wal Khabaa¶ith¶ (Oh Allah we ask for your protection from the evil male and female Shaytaans) [Hisn ul Hasin]. not on the Muslims themselves. These words from Apostle Paul can be understood as a curse upon the spiritual bondage of Islam. Evil Jinn tend to stay in impure places like the toilets etc. Christianity has a different Spirit as evidenced by the words of the Apostle Paul in Galatians. so I say again now.al human eye. They can commit havoc if interfered with but generally keep themselves to themselves. usually remote areas. He wanted them all to be saved even when they cursed and stoned him. 'You shall not put the Lord your God to the test. Such a prayer duel was renewed in Berlin in 1989! Long letters of curses and even death threats some times reach those who serve God among Muslims. it is written. They live in the world and take their place where it suits them. As we have said before. Christ died upon the Calvary¶s cross for everyone and opened the door of grace and salvation for all humankind. Galatians 1:8-9 Paul did not curse unbelievers or peaceful inquirers. There are some spiritual scholars who can control Jinn and the Jinn have given Bay¶ah to them but the true scholars do not publicise this fact. Paul fought against was every evil spirit which tried to bring the Church under the bondage of the Law or which sought to diminish the truth of Grace by Faith. or an angel from heaven. woods etc. continues even today. But even though we. should preach to you a gospel contrary to that which we have preached to you. has brought more than a billion Muslims under the bondage of Islamic Law. . nor did he hate opposing Jews or Gentiles. let him be accursed. if any man is preaching to you a gospel contrary to that which you received.
Ikhlas. Black Magic . µA Jew by the name of Labid ibn Asim who outwardly posed to be a believer (Munafiq) carried out black magic on the Messenger of Allah (Allah bless him & give him peace). There are also other remedies for curing black magic as mentioned in the Ahadith: 'Sayyida A¶isha (Allah be pleased with her) narrates: . knots untied miraculously. The Messenger of Allah (Allah bless him & give him peace) together with the Companions (Allah be pleased with them all) went to the well and removed the knotted hair. namely Surah al-Falaq and Surah an-Nas. [See: Tafsir Ibn Kathir & Ma¶arif al-Qur¶an] The Cure For Black Magic The above teaches us that black magic exists and what the remedy for it is.A Myth? Black magic does exist and it was even performed on the Prophet of Allah (Allah bless him & give him peace). At the eleventh knot. As each verse was recited. Kafiroon. Falaq & Naas) from the Quran and this will prevent any Jinn from coming near you. the Messenger of Allah (Allah bless him & give him peace) was relieved from the effects of this black magic. The angel Jibra¶il informed the Messenger of Allah (Allah bless him & give him peace) as to what had occurred and came down with the two Surahs.The best protection from evil Jinn is to not go to any false person but to recite the Ayatul Qursi and the 4 Quls (Surahs.
A clear sign of false money-making Taweez is when set charges are placed and are usually . Dodgy Peers And Shaykhs? Illiteracy and ignorance is the root to all evil. then there is nothing wrong with using them. such as seeking the help of the devil and other such matters. 5130] Also the use of Taweez (Amulets) is permissible as long as it is written in Arabic and contains vers. hence it may consist of utterances of disbelief. When his illness was aggravated. When in fact. They may consist of black magic. 6/363] The reason why non-Arabic charms have been forbidden is because one will be unaware of their meaning. disbelief or impermissible invocations. if they consist of Quranic verses or prescribed supplications (Duas). no.´ [Radd al-Muhtar. will not be affected by poison or magic on the day he eats them.´ [Sahih al-Bukhari. They then go to false and ignorant so called Peer/Sufi Babas who speak the language they want to hear and then charge them extremely large fees for the solutions to their problems. for its blessings.es of the Quran and Allah¶s name and this is explained in the famous Hanafi book of Fiqh as follows: ³Using of amulets (Taweez) will not be permissible if they are written in a non-Arabic language. in that its meaning is unknown.´ [Sahih al-Bukhari. Many people who are illiterate or ignorant believe that because they may be going through challenging times in their lives they can pick out a scapegoat and therefore blame an outside interference (namely Jinn) for the reasons for their problems. Amir ibn Sa¶d narrates from his father that the Messenger of Allah (Allah bless him & give him peace) said: µ³He who eats seven Ajwa dates every morning.. the consuming of Ajwa dates has been prescribed by the Messenger of Allah (Allah bless him & give him peace) as a remedy for black magic. I used to recite these two Surahs (and blow my breath) over him and make him rub his body with his own hand. However.. it is their lack of knowledge or lack of guidance for their children that has led to the problems.³Whenever the Messenger of Allah (Allah bless him & give him peace) would become ill.. he would recite the Mu¶awwizat (Surah al-Falaq & Surah an-Nas) and blow over himself. 4728] Also. no.
All Muslims should be aware that whilst Black Magic exists Allah and His Messengers have also shown us the remedy for it. A person must be aware that a Peer or Sufi must have four qualities for them to be qualified as a Shaykh: 1. 3. Sunnah and the consensus of the classical scholars. May Allah protect us all from these people. How Do You Suss Out Fake Shaykhs/Peers? The only way to recognise false peers is to recognise the true teachings of Islam and therefore to understand the people who belong to Allah. People who have had experience with such situations have related that the following are among the signs of a person who is possessed by jinn (or Satan): Strong repulsion when hearing Qur aan or Aathaan (call for prayers). You can recognise fake Shaykhs and peers when you yourself have the understanding of Islam or are closely linked to true scholars and therefore can be guided. which is explained above.e he must have the true beliefs of the Quran.. Muslims when faced with problems should first of all check medical opinion and also look at themselves to see whether their upbringing of their children is according to Islam and hence not waste money on false Shaykhs or Peers. especially when Qur aan is recited for the . They cannot be people who sit at home and do not attend the Masjids for prayers as this is an obligation for the Muslims. He must not be an open wrongdoer and therefore must follow the Shariah such as praying Salah with congregation. They cannot be people who have no knowledge of the laws of Allah but they are people who practice even the smallest Sunnah of The Prophet of Allah (Allah bless him & give him peace). 2. He must be of the correct beliefs of Ahl e Sunnah i.onsciousness and/or epileptic attacks. So Who¶s A True Shaykh/Peer Then? One must be aware that Only Allah has the power to cure and whilst the pious have the ability to prescribe the methods Allah has shown it is still the will of Allah that makes things happen. 4. He must have enough knowledge of the Shariah that he knows the Halal and the Haram and knows basic jurisprudence so that he is aware on how to fulfil his basic obligations. One of the key aspects of understanding people of Allah is that they will be people who openly and secretly practice the Shariah without caring for the world and its materials. He must be given permission (Ijazah) by his Shaykh and his Shaykh all the way to the Prophet (May Allah bless him and grant him peace) so that true virtue can be obtained.extravagant compared to the service provided and when these facts are advertised by either the TV or leaflets or magazines.. does not perform any wrong acts openly against the Shariah. One should avoid these false people and instead revert to praying five times a day. Episodes of losing c. recite the Quran and look for the solution by asking Allah for help.
As for curing this condition the following steps are recommended: Putting one s trust in Allah with sincere belief that He is the only cure for everything.possessed person. as indicated in the Qur aan by the following verse (interpretation of the meaning): "And from these (angels) people learn that by which they cause separation between a man and his wife. The jinn who possesses him might speak when Qur aan is recited for the possessed person. For example. Frequent miscarriage for pregnant women. It might be due to physiological or psychological reasons. Reading Qur aan and known supplications expressing seeking refuge. 2:102). Tendency to avoid people accompanied by out-of-the-norm behavior.. Different attitude in the house from that which is outside the house.. Thinking or imagining one has done something when in reality one has not. Inability to have sexual intercourse with one s spouse. Complete loss of appetite for food. the most important and effective . It should be noted that if a person experiences some of the above symptoms this does not necessarily mean that he is either possessed by a jinn or struck by black magic. love changes quickly to extreme hatred. Sudden change in behavior without obvious reason. Frequent nightmares during sleep." (Al-Baqarah. a person will feel that he is missing his family when is outside the house but when he goes home.. Madness. Sudden obedience and/or love for a particular person.
it says: "If I had the knowledge of the unseen. is recommended along with them. and Taha (20:65-69). The leaves should be crushed. and the rest is used to give him a bath..of which is sura 113 and 114. as well as the opening chapter of the Qur aan. Al-Falaq and Al-Naas. which are: in surah Al-Baqarah (2:102). The possessed person drinks some of the water.h. the verses which mention magic. which is. This is based on the belief that no one knows the future or the unseen except God almighty. disbelieved in what has been revealed to Muhammad. Removing the elements of magic as was done by the Prophet when he was struck by black magic by a Jewish man called Lubaid Ben Al. which is contrary to reality. The following verses from the Qur aan are then recited: verse Al-Kursi (2:255). surah Al-Kafiroon (109). if not possible. any dates will suffice.Aasim. defined as seeking the help of demons to perform some. Concerning this. has. That is why the Quran asserts that even Muhammad does not know the unseen. Thus. in fact. then mixed them with water enough for taking a bath. Thus Islam condemns magic. the Holy Quran say: "Suleiman (Solomon) did not disbelieve. 113.even what is called the horoscope or luck or reading one's palm to foretell the future is also prohibited in Islam. Al-A raaf (3:117-119). however.b. Islam considers magic to be an act of blasphemy. and no evil would . To cure black magic some have successfully used seven lotus-tree leaves. the Prophet of Islam p. which were used to cure the Prophet himself.u. said: Whoever goes to a fortune teller (a soothe sayer) or a diviner and believes him. In the light of the above definition. In Islam this is part of magic. by the will of Allaah. Al-Ikhlaas. Eating seven Aa liya Al-Barniy dates (among the dates of Al-Madinah) first thing in the morning. Surah 112.thing harmful against somebody. surah 112. I should have secured abundance for myself. 114.. Cupping--removing excess blood. AlFatihah. but the devils disbelieved teaching men magic" (2:102) In an authentic saying. It is sometimes defined as deception by showing something to an audience. Supplications Magic is an old human practice. Yunus (10:79-82).
Thus Islam has closed the door for practicing magic. In another tradition. Almost all messengers of God were granted miracles as a proof of their authenticity. was himself exposed to the effect of magic. simply because it is against its teachings. but they could not thus harm anyone except by Allah's leave. And how bad indeed was that for which they sold their own selves if they but knew" (2:101-2).have touched me" (7:188). teaching men magic and such things that came down at Babylon to the two angels Harut and Marut. defecting from the battle-field (without a justified reason) and slandering chaste.b. Prophet Muhammad p. he was accused by some of his opponents to be practicing magic. How could you explain this? This is true. devouring the orphan's wealth. Again. which Allah made cool and peaceful to him. And indeed they knew that its practitioner would have no share in the Hereafter. the Quran says: "And when there came to them a Messenger from Allah confirming what was with them. Although Solomon was the Prophet and Messenger of God. Jesus Christ could heal the blind and the leper and bring back the dead to life. Magic is from devils while miracles are from God. While magic is always harmful. miracles are real while magic is sometimes deceptive. killing the human self which Allah prohibited except with right. If we contemplate these acts we find that miracles are totally different from magic. On the other hand. unwary believing women.b. To name only a few: Moses was granted the staff by which he could divide the sea and make water gush from rocks.u. a party of those who were given the scripture threw away the book of Allah behind their backs as if they did not know. Those who claimed this could not distinguish between magic and miracles. magic. and they learn that which harms them rather than profits them. and it is deceptive and harmful. Let us now review some of the verses of the Holy Quran that refer to magic: In Chapter two verse 101102. says: "Avoid the seven deadly acts which are: ascribing partners to God. eating usury. so don't disbelieve.h. but God saved him from the spell of magic through the repeated . And from them (magicians) people learn that through which they would cause separation between a person and his spouse. Abraham was flung in the middle of a huge raging fire. It may be said that the Prophet Muhammad p. And they followed what the devils gave out falsely of magic of the reign of Solomon. miracles are useful. but neither of these two (angles) taught anyone (such things) until they had said: we are only for trial.h. for Solomon did not disbelieve but the devils disbelieved. When these divine miracles are rejected other miracles are imposed to inflict severe punishments on rejecters. God is described in the Quran as the knower of the unseen and the manifest (6:73) and as the holder of the keys of the unseen (6:59).u.
after the five daily prayers . Say: He is Allah. the One! Allah.. And from the evil of the envious when he envies. Two questions are pertinent in context: How to protect one's self from magic? And how to treat a person under the spell of magic? Prophet Muhammad p. From the evil of the sneaking whisper.b. the Merciful .b. who was a human like other humans. This made it easier for his followers to imitate him. translated as follows: .u. the eternally besought of all! He begets not nor was begotten..b. and from the evil of malignant witchcraft. And there is none comparable unto Him. provided us with the recipe through which we can protect ourselves from magic. Of the jinn and of mankind. We shall be immune from magic if we recite . the Beneficent.h. 113 and 114 And here is their translation: (112) Unity In the name of Allah. The God of mankind.h. These chapters are also recommended to be recited three times after the dawn prayer and three times after the sunset prayer. From the evil of the darkness when it is intense. This took place to confirm the humility of Muhammad p.h.u.the last three chapters of the Holy Quran which are number 112. The King of mankind. encouraged us to recite the greatest verse in the Quran called the verse of the Throne. (114) Mankind In the name of Allah the beneficent. the Merciful Say I seek refuge in the in the Lord of daybreak From the evil of that which he created. Who whispers in the hearts of mankind.u. (113) Daybreak In the name of Allah the Beneficent.remembrance of God and the recitation of some chapters and verses of the Holy Quran. the Merciful Say: I seek refuge in the Lord of mankind. Secondly Prophet Mohammed p.
Prophet Mohammed p.u. "Allah tasks not a soul beyond its scope. and we obey. (Grant us) Your forgiveness. and He is never weary of preserving them. . they will suffice him). For it (is only) that which it has earned. This means that they will protect him from every evil. Unto you is the journeying" (2:285). You are our Patron. This verse should be recited after each and every one of the five daily prayers and before going to bed. Who is he that intercedes with Him save by His leave? He knows that which is in front of them and that which is behind them. Again seeking refuge in Allah and remembering his name is an effective protection against all evils including magic.b. 2. Neither slumber nor sleep overtakes Him. The Prophet p. also encouraged us Muslims to recite the last two verses of Chapter two at the beginning of every night whose translation is as follows: "The Messenger believes in that which has been revealed unto him from his Lord and (so do) the believers. Two main supplications are recommended in this respect. absolve us and have mercy on us.h. our Lord. He is the sublime. I seek refuge in the complete words of Allah from the evils of what He created. the Tremendous" (2:225). so grant us victory over the disbelieving folk" (2:286). while they encompass nothing of His knowledge save what He will. Our Lord! Condemn us not if we forget. and the Eternal. and against it (only) that which it has deserved.u.h. the Alive. or miss the mark! Our Lord! Lay not on us such a burden as you did lay on those before us! Our Lord! Impose not on us that which we have not the strength to bear! Pardon us. Unto Him belongs whatever is in the heavens and whatever is in the earth.b."Allah! There is no God save Him. Each one believes in Allah and His angles and His scriptures and His messengers and they say: We hear. said: (whoever recites the last two verses of the chapter called the Cow. They are: 1. His chair encompasses the heavens and the earth. In the name of Allah through whose name nothing on earth or in heaven can cause any harm.
It remains to mention how we can treat a person under the spell of magic. being heedless of the dangers and harm that they inflict. sallallahu alayhe wa sallam.W. Magic is a destructive act. if they but knew. Believers should avoid magic and magicians. killing a living being whose life has been declared sacred by Allah without justification. and therefore Islam warns against it. As Muslims it is imperative to understand these evil-filled practices and to protect. take precautions to heed the danger they represent and attempt to expose their false allegations. It can be categorized as either sorcery. The following evidence from the Qur'an and Sunnah has asserted this ruling. Sorcery can only be performed with the aid of devils whose help is attained when the performer attributes them as partners to Allah in worship. And how bad indeed was that for which they sold their own selves. . then no harm or evil will approach the reciter by the grace of Allah (S. answered: 'Making anyone or any thing a partner of Allah. on the one hand. sallallahu alayhe wa sallam. practicing magic. Allah says: 'And indeed they knew that the buyers of it (magic) would have no share in the Hereafter. disappear or change. innocent. or as illusionism. and slandering chaste. Ruling Both sorcery and illusionism are unlawful in Islam.' The Companions asked: 'O Messenger of Allah! What are these things' He. Illusionism does not involve polytheism.. said: 'Avoid seven most dangerous things. ourselves from them. radhiallahu anhu. which is magic that uses the power of evil spirits for evil purposes.. practicing usury.T). misappropriating the property of an orphan. awed and fearful at the unknown and mystical.If these two prayers are recited three times in the beginning of the day and in the beginning of the night. It is possible. It is a sin because it implies an act of disobedience. which is the skill of performing tricks in which you seem to make things appear. but may none-the-less lead one astray. All in all. as if by magic. running away from the infidels in a battle.' [The Qur'an 2:102] Abu Hurairah. to learn magic so that one can use the same tactics. the best cure is to recite the Quran and seek God's help. Magic Having the power to do supernatural and seemingly impossible things is referred to as 'magic'. related that 'The Prophet. For thousands of years people have been fascinated.
as it disturbs the emotional balance.believing women. and Jundub Ibn Abdullah. alayhes salam. The Prophet. can attain protection from magic.' Umar ibn al-Khattab sent messages to his viceroys in those countries under Islamic rule ordering them to kill all sorcerers. sallallahu alayhe wa sallam. Also. What is unlawful. by their magic. Allah says in the Qur'an: ' And from these (angels) people learn that by which they cause separation between man and his wife. their ropes and their sticks. appeared to him as though they moved fast. Recite verses 285 and 286 of the Surah of al-Baqarah. Fact or Fiction An illusion has an effect on the onlookers that seemingly make things or happen when in reality. even to the extent that it can cause sexual impotence. however is to use magic as a means to break a spell because this is likely to be done by the aid of devils. It may also make the affected person go insane. they do not. radhiallahu anhum. But more specifically we can recite the following verses and sayings: Whoever recites verse 255 of the Surah of al-Baqarah (No 2) before going to bed. for this is the punishment ordained by Allah. said: 'Kill every sorcerer.' (Bukhari and Muslim) Ordained Punishment According to Islamic law. sallallahu alayhe wa sallam. Allah sends him a keeper that protects him against the devils until he wakes up. Another allowable method would be to use medicines lawfully prescribed for the particular case under examination.' (Qur'an 20: 66). Hafsah Bint Umar. Abdullah Ibn Umar. seeking refuge with Him and putting trust in Him. Musa. Protection From Magic Holding fast to Allah. said: 'Nay. we should do what is right in the sight of Allah. but they could not thus harm anyone except by Allah's leave. This was later confirmed by Uthman Ibn Affan. . and turn away from sin. Spells can have a genuine effect that can manipulate the body. throw you (first)! Then behold. the penalty that awaits every sorcerer is death.' (2: 102) Breaking a Magic Spell The best way to break a spell is by reciting assigned verses from the Qur'an and to utter specific invocations specially worded by the Prophet.
and most of them are liars. Who lends an ear (to the devils and they pour what they may have heard of the Unseen from the angels). it involves using devils and holding fast to them. Allah says in the Qur'an: 'Shall I inform you (O people!) Upon whom the devils) descend' They descend on every lying. which is unique to Allah. These rulings also apply to people who claim knowledge of. The problem is that what people believe is true. He is the All-Hearing. This means that any one who believes that he possesses such knowledge is certainly claiming the acquisition of a Divine attribute that Allah (alone) possesses. People who attend fortune-telling assemblies are divided into three groups: . has been embellished or changed. the All-Knowing. sinful person.. Some people are fascinated and impressed by observing those who cannot miss the opportunity to make fortunes out of imparting their fabrications.' Say the following three times: 'In the name of Allah. Ruling: Fortune-telling is considered 'Shirk Akbar' (the major and serious form of polytheism) for two reasons.' (26:221-223) This knowledge of what the angels may have said is then passed to the people who are often prepared to believe what the fortune-teller says. a ritual that can only be perfected when the performer is in complete submission to that damned species.Say: 'I seek refuge with Allah?s perfect words from the evil of what He has created. A fortune-teller uses devils who eavesdrop in the Heavens. Second. nor can they perceive when they shall be resurrected. First. The Danger of Attending Fortune-Telling Assemblies In recent years. This is a form of polytheism. such as geomancers. Whose mention is a protection against whatsoever harm is on the Earth or in the Heavens. the unseen. the number of fortune-tellers has dramatically increased. it implies the acquisition of knowledge of the Unseen. palmists. (alone). only being outnumbered by those who attend their assemblies and believe what they are told. Verily.. shell-diviners. etc. omitting the truth. 'Say: 'None in the Heaven and the Earth knows the Ghaib (unseen) except Allah.' (Qur?an 27: 65).' Fortune-Telling Fortune-telling is the belief that some people possess the ability of telling other people what will happen to them in the future by using magical or mystical methods.
Those who believe in the prophecies of the fortune-tellers and go to ask them about the future. These people are regarded as disbelievers since they deny the truthfulness of the Qur'an: 'Say: None in the Heavens and the Earth Knows the Ghaib (Unseen) except Allah. Such a weighty undertaking could pose a risk to himself. if someone uncertain that he is capable to take on such a task and accomplish it perfectly. People in this group are sinful and their prayers are not accepted for forty days. and result in failure that may likely tempt people even further. These types of people publicize that fortune-tellers only offer misguidance that can make believers go astray. Thanks ALLAH HAFIZ!!! . However.' (27: 65) Those who go to fortune-tellers and only ask them in order to examine the truthfulness of their prophecies.Those who go to fortune-tellers to ask them about the future without truly believing in their falsehoods and without having the slightest intention of disclosing their falsehood to the public. then disclose their deceit to the public. he should not attempt it. | https://www.scribd.com/doc/47289807/BLACK-MAGIC-AND-ITS-CURE | CC-MAIN-2017-34 | refinedweb | 7,949 | 76.32 |
Introduction
In this tutorial, we'll take a look at how to get the number of days between two dates in Python.
We'll be using the built-in
datetime package, that allows you to really easily work with
datetime objects in Python.
Creating a Datetime Object
As datetime is a built-in module, you can access it right away by importing it at the top of your Python file.
You can construct
datetime objects in a few different ways:
from datetime import datetime date_string = "1 January, 2021" now = datetime.now() # Create Datetime based on system clock dt1 = datetime(day=1, month=1, year=2021) # Create Datetime with given arguments dt2 = datetime.strptime(date_string, "%d %B, %Y") # Create Datetime from String
There are certain rules to follow when it comes to Converting Strings to Datetime in Python.
Get Number of Days Between Dates in Python
Trying to measure the numbers of days between dates without using the datetime module is a deceptively complex task - between accounting for leap years and the number of days in each month, trying to create your own implementation is nonsensical.
With
datetimehowever, it becomes trivial.
You can simply subtract a
date or
datetime from each other, to get the number of days between them:
from datetime import datetime date1 = datetime.now() date2 = datetime(day=1, month=7, year=2021) timedelta = date2 - date1 print(timedelta)
This returns a
timedelta object, which contains
days,
seconds and
microseconds and represents the duration between any two
date/
time or
datetime objects.
Printing this object will return the days, hours, minutes, seconds and microseconds to that event:
149 days, 5:22:52.255124
If you're not interested in some of these metrics, you can specify which of them you'd like to access with
timedelta.days,
timedelta.seconds and
timedelta.microseconds:
now = datetime.now() new_years = datetime(day=1, month=1, year=2022) countdown = new_years - now print('Today is: ', now) print('New Year is on: ', new_years) print('Days until New Years: ', countdown.days)
Here, we've assigned the days between
now and
new_years into
countdown, which is a
timedelta object.
Then, we can simply access the
days parameter of that object to get the number of days between them. This results in:
Today is: 2021-02-01 18:35:12.272524 New Year is on: 2022-01-01 00:00:00 Days until New Years: 333
Adding and Subtracting Days Using TimeDelta
What if instead of trying to subtract two known dates from each other, you wanted to add or subtract a time-frame? For example, a customer subscribed to your service for a monthly fee. You'll want to remind them to renew it after a 30 days.
You can construct a time-frame for those 30 days, using
timedelta and add or subtract that from any other
datetime object:
from datetime import datetime, timedelta now = datetime.now() thirty_days = timedelta(days=30) print('In 30 days: ', now + thirty_days) print('30 days ago: ', now - thirty_days)
This results in:
In 30 days: 2021-03-03 18:41:49.922082 30 days ago: 2021-01-02 18:41:49.922082
This is an incredibly useful feature when trying to implement scheduling, or retrieving database entries based off a moving window (such as the trailing 30 days).
Conclusion
In this tutorial, we've covered everything you need to know about getting the number of days between two dates in Python.
We've worked with
datetime objects and
timedelta to achieve this functionality. | https://stackabuse.com/python-get-number-of-days-between-dates/ | CC-MAIN-2021-17 | refinedweb | 579 | 60.55 |
Ahoy there lads, I am in need of some help. I have a JSON file exactly like this:
{
"name": "Tori Black",
"age": "27",
"hobbies": "Skiing",
"name": "Jenna Jameson",
"age": "42",
"hobbies": "Jumping"
...
}
>> my_dict["Tori Black"]
>> [27, "Skiing"]
my_dict = dict([elem[1], elem[2]] for elem in open('data.json'))
your json file is not a valid mapping ... you cannot have duplicate keys in a json mapping ... you will need to manually iterate over the lines ... this solution assumes your file is laid out exactly the same as your example
def get_items(fname): with open(fname) as fh: for line in fh: if line.strip().startswith('"name"'): key = line.split(":")[-1].strip('" \n,') yield key,[next(fh).split(":")[-1].strip('" \n,') for _ in range(2)] my_dict = dict(get_items("badjson.json")) print my_dict["Jenna Jameson"] | https://codedump.io/share/VHuFfRsDjQCj/1/map-a-json-file-into-a-dictionary | CC-MAIN-2018-17 | refinedweb | 134 | 69.79 |
WebKit Bugzilla
The Protocols and Formats Working Group has been updateding Public Working
Drafts of the Accessible Rich Internet Applications (WAI-ARIA) suite. The Roadmap describes accessibility of interactive Web content using rich technologies such as AJAX and DHTML.:
Basically, in combination with the tabindex fixes recommended in bug 7138, this allows for rich web applications to be developed with accessible tree views, menubars, tab panels, grids, sliders and other advanced widgets.
This has been implemented in Mozilla since Firefox 1.5 See
Other major vendors will be supporting this technology.
Other major vendors … starting with Opera:
ARIA can now be used without namespaces in text/html.
For more info see the FAQ:
Confirmed the bug as an enhancement request. Personally, I would like to see it implemented.
Not just Mozilla and Opera.
IE 8 beta 1 now has ARIA support:
How can we move this up the chain so that it gets addressed?
<rdar://problem/5785134>
This work is dependent on refactoring our accessibility code to be cross-platform. I don't think we should bake in more Mac-specific code to do ARIA before that refactoring is complete. Our first goal should be to get the accessibility code from Objective-C to C++ so that GTK and Windows can get unblocked on adding their support (e.g., MSAA on Windows).
Once we've done that we should be able to add an ARIA implementation with mostly cross-platform code.
This would be an excellent Google Summer of Code project.
It's great this is getting attention. However, a Summer of Code project won't get you that far. Roughly 20% of the mappings to Universal Access and other APIs won't be straightforward.
This implementors guide helps provide some idea of what's involved:
We don't have Universal Access mappings documented yet. Opera is partly down the road of implementing ARIA via Universal Access and Mozilla is thinkingg about it.
I hope we can work to define common UA mappings.
*** Bug 23018 has been marked as a duplicate of this bug. ***
Safari 4 says it has ARIA support:
So wouldn't that means WebKit does too?
Looks like there are some loose ends still. Namely, 'aria-required' attribute is not implemented, and some ARIA roles are not implemented, too. I don't know how much these loose ends are important in practice.
Unfortunately, the latest beta of Safari4 supports a very limited set of ARIA roles and states. Such trivial roles as "alert" are not supported yet. Also, ARIA landmarks and live regions are not exposed by the engine yet.
So, this bug is far from being addressed.
Also worth noting that the aria role "presentational" and the aria state "aria-hidden" do not appear to be implemented or working. This makes hiding things from the screen reader impossible.
(In reply to comment #13)
> Also worth noting that the aria role "presentational" and the aria state
> "aria-hidden" do not appear to be implemented or working. This makes hiding
> things from the screen reader impossible.
Try role="presentation".
Also, do things not get hidden from the screen reader when display: none or visibility: hidden are used? If you look at the 4th question under, it shows that aria-hidden is advisory, allowing DOM-based ATs to retrieve changes to whether something is hidden. However, it is preferred that ATs can use another API to determine visibility and changes to visibility. IOW, using display: none or visibility: hidden is the right way to hide something from a screen reader.
.
(In reply to comment #15)
> .
Since this is becoming a discussion unto itself, I suggest filing a separate bug and attaching a testcase with recommended behavior. We should take the specific issue and deal with it there. Feel free to CC me. There might not yet be a way in ARIA to do what you are asking.
ARIA support has been in for several years now. Please close. | https://bugs.webkit.org/show_bug.cgi?format=multiple&id=12132 | CC-MAIN-2016-26 | refinedweb | 659 | 65.62 |
Although I don’t normally deal with typeglobs or the symbol table, I need to understand them for the tricks I’ll use in later chapters. I’ll lay the foundation for advanced topics including dynamic subroutines and jury-rigging code in this chapter.
Symbol tables organize and store Perl’s package (global) variables, and I can affect the symbol table through typeglobs. By messing with Perl’s variable bookkeeping I can do some powerful things. You’re probably already getting the benefit of some of these tricks without evening knowing it.
Before I get too far, I want to review the differences between package and lexical variables. The symbol table tracks the package variables, but not the lexical variables. When I fiddle with the symbol table or typeglobs, I’m dealing with package variables. Package variables are also known as global variables since they are visible everywhere in the program.
In Learning Perl and Intermediate
Perl, we used lexical variables whenever possible. We declared
lexical variables with
my and those
variables could only be seen inside their scope. Since lexical variables
have limited reach, I didn’t need to know all of the program to avoid a
variable name collision. Lexical variables are a bit faster too since Perl
doesn’t have to deal with the symbol table.
Lexical variables have a limited scope, and they only affect that part of the program. This
little snippet declares the variable name
$n twice in different scopes, creating two
different variables that do not interfere with each other:
my $n = 10; # outer scope my $square = square( 15 ); print "n is $n, square is $square\n"; sub square { my $n = shift; $n ** 2; }
This double use of
$n is not a
problem. The declaration inside the subroutine is a different scope and
gets its own version that masks the other version. At the end of the
subroutine, its version of
$n
disappears as if it never existed. The outer
$n is still
10.
Package variables are a different story. Doing the same thing with
package variables stomps on the previous definition of
$n:
$n = 10; my $square = square( 15 ); print "n is $n, square is $square\n"; sub square { $n = shift; $n ** 2; }
Perl has a way to deal with the double use of package variables,
though. The
local built-in temporarily
moves the current value,
10, out of the
way until the end of the scope, and the entire program sees the new value,
15, until the scope of
local ends:
$n = 10; my $square = square( 15 ); print "n is $n, square is $square\n"; sub square { local $n = shift; $n ** 2; }
We showed the difference in Intermediate Perl. The
local version changes everything including the
parts outside of its scope while the lexical version only works inside its
scope. Here’s a small program that demonstrates it both ways. I define the
package variable
$global, and I want to
see what happens when I use the same variable name in different ways. To
watch what happens, I use the
show_me
subroutine to tell me what it thinks the value of
$global is. I’ll call
show_me before I start, then subroutines that do
different things with
$global. Remember
that
show_me is outside of the lexical
scope of any other subroutine:
#!/usr/bin/perl # not strict clean, yet, but just wait $global = "I'm the global version"; show_me('At start'); lexical(); localized(); show_me('At end'); sub show_me { my $tag = shift; print "$tag: $global\n" }
The
lexical subroutine starts by
defining a lexical variable also named
$global. Within the subroutine, the value of
$global is obviously the one I set.
However, when it calls
show_me, the
code jumps out of the subroutine. Outside of the subroutine, the lexical
variable has no effect. In the output, the line I tagged with
From lexical() shows
I'm the global version:
sub lexical { my $global = "I'm in the lexical version"; print "In lexical(), \$global is --> $global\n"; show_me('From lexical()'); }
Using
local is completely
different since it deals with the package version of the variable. When I
localize a variable name, Perl sets aside its current value for the rest
of the scope. The new value I assign to the variable is visible throughout
the entire program until the end of the scope. When I call
show_me, even though I jump out of the
subroutine, the new value for
$global
that I set in the subroutine is still visible:
sub localized { local $global = "I'm in the localized version"; print "In localized(), \$global is --> $global\n"; show_me('From localized'); }
The output shows the difference. The value of
$global starts off with its original version. In
lexical(), I give it a new value but
show_me can’t see it;
show_me still sees the global version. In
localized(), the new value sticks even
in
show_me. However, after I’ve called
localized(),
$global comes back to its original
values:
At start: I'm the global version In lexical(), $global is --> I'm in the lexical version From lexical: I'm the global version In localized(), $global is --> I'm in the localized version From localized: I'm in the localized version At end: I'm the global version
Hold that thought for a moment because I’ll use it again after I introduce typeglobs.
No matter which part of my program I am in or which package
I am in, I can always get to the package variables as long as I preface
the variable name with the full package name. Going back to my
lexical(), I can see the package version of
the variable even when that name is masked by a lexical variable of the
same name. I just have to add the full package name to it,
$main::global:
sub lexical { my $global = "I'm in the lexical version"; print "In lexical(), \$global is --> $global\n"; print "The package version is still --> $main::global\n"; show_me('From lexical()'); }
The output shows that I have access to both:
In lexical, $global is --> I'm the lexical version The package version is still --> I'm the global version
That’s not the only thing I can do, however. If, for some odd
reason, I have a package variable with the same name as a lexical
variable that’s currently in scope, I can use
our (introduced in Perl 5.6) to tell Perl to
use the package variable for the rest of the scope:
sub lexical { my $global = "I'm in the lexical version"; our $global; print "In lexical with our, \$global is --> $global\n"; show_me('In lexical()'); }
Now the output shows that I don’t ever get to see the lexical version of the variable:
In lexical with our, $global is --> I'm the global version
It seems pretty silly to use
our that way since it masks the lexical
version for the rest of the subroutine. If I only need the package
version for part of the subroutine, I can create a scope just for it so
I can use it for that part and let the lexical version take the
rest:
sub lexical { my $global = "I'm in the lexical version"; { our $global; print "In the naked block, our \$global is --> $global\n"; } print "In lexical, my \$global is --> $global\n"; print "The package version is still --> $main::global\n"; show_me('In lexical()'); }
Now the output shows all of the possible ways I can use
$global:
In the naked block, our $global is --> I'm the global version In lexical, my $global is --> I'm the lexical version The package version is still --> I'm the global version
Each package has a special hash-like data structure called the symbol table, which comprises all of the typeglobs for that package. It’s not a real Perl hash, but it acts like it in some ways, and its name is the package name with two colons on the end.
This isn’t a normal Perl hash, but I can look in it with
the
keys operator. Want to
see all of the symbol names defined in the
main package? I simply print all the keys for
this special hash:
#!/usr/bin/perl foreach my $entry ( keys %main:: ) { print "$entry\n"; }
I won’t show the output here because it’s rather long, but when I
look at it, I have to remember that those are the variable names without
the sigils. When I see the identifier
_, I have to
remember that it has references to the variables
$_,
@_, and
so on. Here are some special variable names that Perl programmers will
recognize once they put a sigil in front of them:
/ " ARGV INC ENV $ - 0 @
If I look in another package, I don’t see anything because I haven’t defined any variables yet:
#!/usr/bin/perl foreach my $entry ( keys %Foo:: ) { print "$entry\n"; }
If I define some variables in package
Foo, I’ll then be able to see some
output:
#!/usr/bin/perl package Foo; @n = 1 .. 5; $string = "Hello Perl!\n"; %dict = { 1 => 'one' }; sub add { $_[0] + $_[1] } foreach my $entry ( keys %Foo:: ) { print "$entry\n"; }
The output shows a list of the identifier names without any sigils attached. The symbol table stores the identifier names:
n add string dict
These are just the names, not the variables I defined, and from this output I can’t tell which variables I’ve defined. To do that, I can use the name of the variable in a symbolic reference, which I’ll cover in Chapter 9:
#!/usr/bin/perl foreach my $entry ( keys %main:: ) { print "-" x 30, "Name: $entry\n"; print "\tscalar is defined\n" if defined ${$entry}; print "\tarray is defined\n" if defined @{$entry}; print "\thash is defined\n" if defined %{$entry}; print "\tsub is defined\n" if defined &{$entry}; }
I can use the other hash operators on these hashes, too. I can
delete all of the variables with the same name. In the next program, I
define the variables
$n and
$m then assign values to them. I call
show_foo to list the variable names in the
Foo package, which I use because it
doesn’t have all of the special symbols that the
main package does:
#!/usr/bin/perl # show_foo.pl package Foo; $n = 10; $m = 20; show_foo( "After assignment" ); delete $Foo::{'n'}; delete $Foo::{'m'}; show_foo( "After delete" ); sub show_foo { print "-" x 10, $_[0], "-" x 10, "\n"; print "\$n is $n\n\$m is $m\n"; foreach my $name ( keys %Foo:: ) { print "$name\n"; } }
The output shows me that the symbol table for
Foo:: has entries for the names
n and
m, as
well as for
show_foo. Those are all of
the variable names I defined; two scalars and one subroutine. After I use
delete, the entries for
n and
m are
gone:
----------After assignment---------- $n is 10 $m is 20 show_foo n m ----------After delete---------- $n is 10 $m is 20 show_foo
By default, Perl variables are global variables, meaning that I can access them from
anywhere in the program as long as I know their names. Perl keeps track
of them in the symbol table, which is available to the entire program.
Each package has a list of defined identifiers just like I showed in the
previous section. Each identifier has a pointer (although not in the C sense) to a slot for each
variable type. There are also two bonus slots for the variables
NAME and
PACKAGE, which I’ll use
in a moment. The following shows the relationship between the package,
identifier, and type of variable:
Package Identifier Type Variable +------> SCALAR - $bar | +------> ARRAY - @bar | +------> HASH - %bar | Foo:: -----> bar -----+------> CODE - &bar | +------> IO - file and dir handle | +------> GLOB - *bar | +------> FORMAT - format names | +------> NAME | +------> PACKAGE
There are seven variable types. The three common ones are
the
SCALAR,
ARRAY, and
HASH, but Perl also has
CODE for subroutines
(Chapter 9 covers subroutines as data),
IO for file and directory handles, and
GLOB for the whole thing. Once I have
the glob I can get a reference to a particular variable of that name by
accessing the right entry. To access the scalar portion of the
*bar typeglob, I access that part almost like
a hash access. Typeglobs are not hashes though; I can’t use the hash
operators on them and I can’t add more keys:
$foo = *bar{SCALAR} @baz = *bar{ARRAY}
I can’t even use these typeglob accesses as lvalues:
*bar{SCALAR} = 5;
I’ll get a fatal error:
Can't modify glob elem in scalar assignment ...
I can assign to a typeglob as a whole, though, and Perl will figure out the right place to put the value. I’ll show that in Aliasing,” later in this chapter.
I also get two bonus entries in the typeglob,
PACKAGE and
NAME, so I can always tell from which variable
I got the glob. I don’t think this is terribly useful, but maybe I’ll be
on a Perl Quiz Show someday:
#!/usr/bin/perl # typeglob-name-package.pl $foo = "Some value"; $bar = "Another value"; who_am_i( *foo ); who_am_i( *bar ); sub who_am_i { local $glob = shift; print "I'm from package " . *{$glob}{PACKAGE} . "\n"; print "My name is " . *{$glob}{NAME} . "\n"; }
Although this probably has limited usefulness, at least outside of any debugging, the output tells me more about the typeglobs I passed to the function:
I'm from package main My name is foo I'm from package main My name is bar
I don’t know what sorts of variable these are even though I have
the name. The typeglob represents all variables of that name. To check
for a particular type of variable, I’d have to use the
defined trick I used earlier:
my $name = *{$glob}{NAME}; print "Scalar $name is defined\n" if defined ${$name};
I can alias variables by assigning one typeglob to another. In this
example, all of the variables with the identifier
bar become nicknames for all of the variables
with the identifier
foo once Perl
assigns the
*foo typeglob to the
*bar typeglob:
#!/usr/bin/perl $\n"; $bar = 'Bar scalar'; @bar = 6 .. 10; print "Scalar is <$foo>, array is <@foo>\n";
When I change either the variables named
bar or
foo,
the other is changed too because they are actually the same thing with
different names.
I don’t have to assign an entire typeglob. If I assign a reference
to a typeglob, I only affect that part of the typeglob that the
reference represents. Assigning the scalar reference
\$scalar to the typeglob
*foo only affects the
SCALAR part of the typeglob. In the next line,
when I assign a
\@array to the
typeglob, the array reference only affects the
ARRAY part of the typeglob. Having done that,
I’ve made
*foo a Frankenstein’s
monster of values I’ve taken from other variables:
#!/usr/bin/perl $scalar = 'foo'; @array = 1 .. 5; *foo = \$scalar; *foo = \@array; print "Scalar foo is $foo\n"; print "Array foo is @foo\n";
This feature can be quite useful when I have a long variable name
but I want to use a different name for it. This is essentially what the
Exporter module does when it imports symbols into my
namespace. Instead of using the full package specification, I have it in
my current package.
Exporter takes the variables from
the exporting package and assigns to the typeglob of the importing
package:
package Exporter; sub import { my $pkg = shift; my $callpkg = caller($ExportLevel); # ... *{"$callpkg\::$_"} = \&{"$pkg\::$_"} foreach @_; }
Before Perl 5.6 introduced filehandle references, if I had to pass a
subroutine a filehandle I’d have to use a typeglob. This is the most
likely use of typeglobs that you’ll see in older code. For instance, the
CGI module can read its input from a filehandle I
specify, rather than using
STDIN:
use CGI; open FH, $cgi_data_file or die "Could not open $cgi_data_file: $!"; CGI->new( *FH ); # can't new( FH ), need a typeglob
This also works with references to typeglobs:
CGI->new( \*FH ); # can't new( FH ), need a typeglob
Again, this is the older way of doing things. The newer way involves a scalar that holds the filehandle reference:
use CGI; open my( $fh ), $cgi_data_file or die "Could not open $cgi_data_file: $!"; CGI->new( $fh );
In the old method, the filehandles were package variables so they couldn’t be lexical variables. Passing them to a subroutine, however, was a problem. What name do I use for them in the subroutine? I don’t want to use another name already in use because I’ll overwrite its value. I can’t use local with a filehandle either:
local( FH ) = shift; # won't work.
That line of code gives a compilation error:
Can't modify constant item in local ...
I have to use a typeglob instead. Perl figures out to assign the
IO portion of the
FH typeglob:
local( *FH ) = shift; # will work.
Once I’ve done that, I use the filehandle
FH just like I would in any other situation.
It doesn’t matter to me that I got it through a typeglob assignment.
Since I’ve localized it, any filehandle of that name anywhere in the
program uses my new value, just as in my earlier
local example. Nowadays, just use filehandle
references,
$fh, and leave this stuff
to the older code (unless I’m dealing with the special filehandles
STDOUT,
STDERR, and
STDIN).
Using typeglob assignment, I can give anonymous subroutines a name. Instead of dealing with a subroutine dereference, I can deal with a named subroutine.
The
File::Find module takes a callback function to select files from a list of
directories:
use File::Find; find( \&wanted, @dirs ); sub wanted { ... }
In
File::Find::Closures, I have several
functions that return two closures I can use with
File::Find. That way, I can run common
find tasks without recreating the
&wanted function I need:
package File::Find::Closures; sub find_by_name { my %hash = map { $_, 1 } @_; my @files = (); ( sub { push @files, canonpath( $File::Find::name ) if exists $hash{$_} }, sub { wantarray ? @files : [ @files ] } ) }
I use
File::Find::Closures by importing the
generator function I want to use, in this case
find_by_name, and then use that function to
create two anonymous subroutines: one for
find and one to use afterward to get the
results:
use File::Find; use File::Find::Closures qw( find_by_name ); my( $wanted, $get_file_list ) = find_by_name( 'index.html' ); find( $wanted, @directories ); foreach my file ( $get_file_list->() ) { ... }
Perhaps I don’t want to use subroutine references, for whatever
reasons. I can assign the anonymous subroutines to typeglobs. Since I’m
assigning references, I only affect subroutine entry in the typeglob.
After the assignment I can then do the same thing I did with filehandles
in the last section, but this time with named subroutines. After I
assign the return values from
find_by_name to the typeglobs
*wanted and
*get_file_list, I have subroutines with those
names:
( *wanted, *get_file_list ) = find_by_name( 'index.html' ); find( \&wanted, @directories ); foreach my file ( get_file_list() ) { ... }
In Chapter 9, I’ll use this trick with
AUTOLOAD to define subroutines on the fly or to
replace existing subroutine definitions.
The symbol table is Perl’s accounting system for package variables,
and typeglobs are the way I access them. In some cases, such as passing a
filehandle to a subroutine, I can’t get away from the typeglob because I
can’t take a reference to a filehandle package variable. To get around
some of these older limitations in Perl, programmers used typeglobs to get
to the variables they needed. That doesn’t mean that typeglobs are
outdated, though. Modules that perform magic, such as
Exporter, uses them without me even knowing about it.
To do my own magic, typeglobs turn out to be quite handy.
Chapters 10 and 12 of Programming Perl, Third Edition, by Larry Wall, Tom Christiansen, and Jon Orwant describe symbol tables and how Perl handles them internally.
Phil Crow shows some symbol table tricks in “Symbol Table Manipulation” for Perl.com:.
Randal Schwartz talks about scopes in his Unix Review column for May 2003:.
Get Mastering Perl now with O’Reilly online learning.
O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers. | https://www.oreilly.com/library/view/mastering-perl/9780596527242/ch08.html | CC-MAIN-2020-45 | refinedweb | 3,377 | 65.15 |
Tutorial: Python Executable in Project Properties, accessed from the Project menu. Wing 101 does not have projects and Python environment is configured instead with Configure Python in the Edit menu.
An easy way to determine the value to use for Python Executable is to start the Python you wish to use with Wing and type the following at Python's >>> prompt:
import sys sys.executable
You will need to Restart Shell from the Options menu into the shell, such as:
import sys sys.getrefcount(i)
Note that Wing offers auto-completion as you type and shows call signature and documentation in the Source Assistant tool. Use the Tab key to enter a selected completion. Other keys can be set up as completion keys with the Editor > Auto-completion > Completion Keys preference.
You can create as many instances of the Python Shell tool as you wish by right-clicking on a tool tab and selecting Insert Tool. Each one will run in its own process space. | https://wingware.com/doc/intro/tutorial-check-python | CC-MAIN-2019-35 | refinedweb | 165 | 62.07 |
Styling Flow Applications
Vaadin uses Cascading Style Sheets (CSS) to separate the appearance of the user interface from its logic. Themes, which are a feature of the Vaadin Design System, are the standard way to organize styles in a Vaadin application.
For further reading, see Using Themes in the Vaadin Design System.
To style your application and components, you should be comfortable writing CSS. The CSS tutorials on MDN Web Docs are a great way to learn the basics of CSS.
Styling Views and Custom Components
Views and custom components, extending from
Component, are rendered in the global style scope.
You can apply traditional CSS styling techniques to them.
The most common technique is to add CSS classes to the components in the view and target those classes in your style sheets.
@CssImport("./styles/my-view.css") public class MyView extends VerticalLayout { public MyView() { addClassName("my-view"); H1 heading = new H1("My View Title"); heading.addClassName("heading"); Paragraph text = new Paragraph("Thanks for stopping by. Not much to see here. Click the button below to go back to start."); Button backButton = new Button("Go Back"); backButton.addClassName("back-button"); add(heading, text, backButton); } }
See Importing Style Sheets for details about the
@CssImport annotation.
Now, the actual style sheet could be as follows:
.heading { margin-top: 0; } p { /* Assuming we are using the Lumo theme. If not, fall back to 1.2em */ font-size: var(--lumo-font-size-l, 1.2em); } .back-button { background-color: var(--lumo-shade-90pct); }
Importing Style Sheets
Style sheets can be either external or bundled, as described later.
You should be familiar with Style Scopes to know whether you need to import a style sheet to the global scope or to a component scope.
To learn where CSS files should be placed in your project, see Loading Resources.
Bundled Style Sheets
Use the
@CssImport annotation to import style sheets which are in your application source folder.
Bundled style sheets are included in the application bundle during a production build, together with other client-side resources.
Bundling is recommended for styles that change together with the application logic or component implementations, as the browser can cache them as a single unit of related resources.
// Import a style sheet into the global scope @CssImport("./styles/shared-styles.css") public class MyApplication extends Div { }
The
@CssImport annotation can also be used to import component-specific style sheets.
// Import a style sheet into the local scope of the TextField component @CssImport(value = "./styles/text-field.css", themeFor = "vaadin-text-field")
External Style Sheets
The
@StyleSheet annotation can be used to import style sheets from an external URL, or from a URL within your application.
The latter type of URLs are prefixed with
context://, which points to the root of the public resources folder of your application.
External/linked style sheets can be used to import styles without including the contents in the application bundle. This allows the browser to load and cache the style sheet independently from the rest of the application.
External style sheets need to be accessible from a URL, and should be placed in the public resource folder in your web application. They can also come from outside your web application, for example from a different domain or a content delivery network (CDN).
@StyleSheet("context://custom-font.css") @StyleSheet("") public class MyApplication extends Div { }
Styling Templates
When using component templates, you can define styles directly in the templates, without need to reference CSS files. See Styling Templates. | https://vaadin.com/docs/latest/application/styling | CC-MAIN-2022-27 | refinedweb | 580 | 55.95 |
* Raspberry Pi
– 1 * Network cable (or USB wireless network adapter)
– 1 * Rotary Encoder module
– Jumper wires
Experimental Principle
Most rotary encoders have 5 pins with three functions of turning left, turning right and pressing down. Pin 4 and Pin 5 are switch wiring terminals used to press. They have no difference with buttons previously used, so we will no longer discuss them in this experiment. Pin 2 is generally connected to ground. Pin 1 and Pin 3 are first connected to pull-up resistor and then to microprocessor. In this experiment, they are connected to GPIO0 and GPIO1 of Raspberry Pi. When we rotate left and right, there will be pulse inputs in pin 1 and pin 3.
The figure shows, if both GPIO0 and GPIO1 are at high level, it indicates the switch rotates clockwise; if GPIO0 is at high level but GPIO1 is at low level, it indicates the switch rotates anti-clockwise. Therefore, during programming, you only need to check the state of pin 3 when pin 1 is at high level, then you can tell whether the switch is rotates clockwise or anti-clockwise.
Experimental Procedures
Step 1: Build the circuit
Raspberry Pi Rotary Encoder
GPIO0 ———————————- CLK
GPIO1 ———————————- DT
3.3V ———————————– +
GND ———————————– GND
Step 2: Edit and save the code (see path/Rpi_SensorKit_code/17_RotaryEncoder/ rotaryEncoder.c)
Step 3: Compile
gcc rotaryEncoder.c -lwiringPi
Step 4: Run
./a.out
Now, gently spin the knob of the rotary encoder to change the value of the variable in the above program, and you will see the value printed on the screen. When you spin it clockwise, the value will increase; when counterclockwise, the value will decrease.
Summary
Through this lesson, you have been familiar with the principle of rotary encoder and preliminarily mastered the interruption programming way of Raspberry Pi. Interruption is a very important concept and is widely used in modern computers. Interruption greatly reduces the CPU load.
rotaryEncoder.c
#include <stdio.h> #include <string.h> #include <errno.h> #include <stdlib.h> #include <wiringPi.h> #define SWPin 0 #define RoAPin 1 #define RoB; } while(1){ rotaryDeal(); printf("%d\n", globalCounter); //printf("%d\n",globalCounter); } return 0; }
Python Code
#!/usr/bin/env python import RPi.GPIO as GPIO import time RoAPin = 11 # pin11 RoBPin = 12 # pin12) GPIO.add_event_detect(BtnPin, GPIO.FALLING, callback=btnISR)() | https://learn.sunfounder.com/lesson-18-rotary-encoder/ | CC-MAIN-2021-39 | refinedweb | 384 | 57.57 |
package
SERVLETS
.
InsertServlet.java:3: package javax.Servlet does not exist
import javax.Servlet.*;
^
InsertServlet.java:4: package javax.Servlet.http does not exist
import.... The package java.Servlet.* does not exist. It is written as javax.servlet.*. Similarly
: package javax.servlet does not exist
import javax.servlet.*;
^
InsertServlet.java:4: package javax.servlet.http does not exist
import javax.servlet.http.
SERVLETS
InsertServlet.java:3: package javax.servlet does not exist
import javax.servlet.*;
^
InsertServlet.java:4: package javax.servlet.http does not exist
import
servlets
what is the architecture of a servlets package what is the architecture of a servlets package
The javax.servlet package provides interfaces and classes for writing servlets.
The Servlet Interface
The central
servlets
in detail javax.servlet.http package
The javax.servlet.http package supports the development of servlets that use the HTTP protocol. The classes in this package extend the basic servlet functionality to support various HTTP
servlets
servlets Hi
what is pre initialized servlets, how can we achives?
When servlet container is loaded, all the servlets defined in the web.xml file does not initialized by default. But the container receives
the servlets
what is diff between generic servlets and httpservlets what is diff between generic servlets and httpservlets
Difference between GenericServlet and HTTPServlet:
1)GenericServlet belongs to javax.servlet package
Checking if a file or directory exist
Checking if a file or directory exist
In this section you will learn how to check whether a file or a directory exist
or not. The " java.io " package provide a method exist()
which return true or false. This method
servlets
on the amount of data you can send and because the data does not show up on the URL you can send passwords. But this does not mean that POST is truly secure
servlets
, HttpServlet provides a default implementation for all those methods that does nothing
servlets
servlets how can I run java servlet thread safety program using tomcat server? please give me a step by step procedure to run the following program
my program is
A DEMO PROGRAM FOR THREAD SAFETY.
package serv;
import
i have problem with this query... please tell me the resolution if this .........
i have problem with this query... please tell me the resolution if this ......... select length(ename)||' charecters exist in '||initcap(ename)||'s name'
as "names and length" from emp
resolution for prog
resolution for prog import java.lang.*;
class Current{
public static void main(String ar[]){
Thread t = Thread.CurrentThread();
System.out.println("current thread"+t);
System.out.println("thread name"+t.getName());
}
}
i got
import package.subpackage.* does not work
import package.subpackage.* does not work I have 3 class files.
A.java
B.java
C.java
Below is the code block
A.java:-
package com.test...()
{
System.out.println("funA");
}
}
B.java:-
package com.test;
public
resolution problem in java
resolution problem in java I designed project in java in my PC when run the same project in some other PC i can't fully view my java forms.Some said that it is resolution problem
Servlets Programming
Servlets Programming Hi this is tanu,
This is a code for knowing... to store that value and where?
package counter;
import java.io.IOException... visit the following links:
Servlets Books
servlets can best be used. By no means does this book cover all the uses of servlets; such a book could never exist. Servlets are a lightweight/heavyweight...
Servlets Books
The package keyword
package if the Java source file does not include a package
statement...
The package keyword
The package in java programming language
is a keyword that is used to define
ipad screen resolution pixels
ipad screen resolution pixels Hi! Can you tell the exact size of the iPad in pixels ..including height & width.
Thanks Very Much!
Finally find it on the apple website...
The iPad display has a screen resolution
Servlets Program
Servlets Program Hi, I have written the following servlet:
[code]
package com.nitish.servlets;
import javax.servlet.*;
import java.io.*;
import java.sql.*;
import javax.sql.*;
import oracle.sql.*;
public class RequestServlet
Determining if a File or Directory exist
does not exist : false
Download
this example...
Determining if a File or Directory Exist
...;or directory does not exist
System.out.println("
what is the resolution for the bellow error?
what is the resolution for the bellow error? pe Exception report
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException
Java file exist
;or Directory exist.");
}
else... checks whether the
file exists or not.
Output
File or Directory does
Accessing Database from servlets through JDBC!
that are implemented and extended by all servlets.
While the javax.servlet.http package...
Java Servlets - Downloading and Installation
Java
Servlets are what is the duties of response object in servlets
servlets
servlets why we are using servlets
servlets
what are advantages of servlets what are advantages of servlets
Please visit the following link:
Advantages Of Servlets
setting of image resolution on jsp - JSP-Servlet
setting of image resolution on jsp How can i set resolution of images on my jsp page?When i enlarge the image it becomes fade? is there any solution for its setting
servlets deploying - Java Beginners
servlets deploying how to deploy the servlets using tomcat?can you...,
package javacode;
import java.io.*;
import javax.servlet.*;
import...);
}
}
------------------------------------------------------- This is servlets
servlets - JSP-Servlet
;This is servlets code.
package javacode;
import java.io.*;
import java.sql.... servlets. Hi friend,
employee form in servlets...
----------------------------------------------
Read
java servlets with database interaction
java servlets with database interaction hai friends i am doing a web... from RUsersInfo");
boolean exist=false;
while(rs.next...))
exist=true;
}
out.println("<html>
servlets - JSP-Servlet
is as follows:
package javacode;
import java.io.*;
import java.sql.... servlets link , read more and more information about servlet. how to compile and how to run servlets program.This is running program but you are not able
servlets - Servlet Interview Questions
information.
package javacode;
import java.io.*;
import javax.servlet.*;
import... for more information.
Servlets
Servlets How to check,whether the user is logged in or not in servlets to disply the home page
servlets - JSP-Servlet
; Hi
package javacode;
import java.io.*;
import javax.servlet....("");
}
}
---------------------------------------------------
Read for more information.
servlets - Servlet Interview Questions
:
--------------------------------
package...
package javacode;
import javax.servlet.*;
import javax.servlet.http....
------------------------------------------
Read for more Details - JSP-Servlet
.
in navigator windwo your project displayed.
check there src folder exist.
right - Servlet Interview Questions
servlets scenario....if i am requesting a google page from clent1 and client2....
does the init() will be called by all the clients seperately or it will be called by only one and will be used by the others. init - Java Beginners
the
clientImpl get methods.
Here is my package and servlet. I am confused how to create object and where to edit in servlet file!
package mlclientinterface;
Can
SERVLETS
servlets
the servlets
Servlets | http://www.roseindia.net/tutorialhelp/comment/91306 | CC-MAIN-2014-52 | refinedweb | 1,154 | 68.87 |
/* Set file access and modification times. Copyright (C) 2003,. */ /* derived from a function in touch.c */ #include <config.h> #include "utimens.h" #include <errno.h> #include <fcntl.h> #include <sys/time.h> #include <unistd.h> #if HAVE_UTIME_H # include <utime.h> #endif /* Some systems (even some that do have <utime.h>) don't declare this structure anywhere. */ #ifndef HAVE_STRUCT_UTIMBUF struct utimbuf { long actime; long modtime; }; #endif /* Some systems don't have ENOSYS. */ #ifndef ENOSYS # ifdef ENOTSUP # define ENOSYS ENOTSUP # else /* Some systems don't have ENOTSUP either. */ # define ENOSYS EINVAL # endif #endif #ifndef __attribute__ # if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 8) || __STRICT_ANSI__ # define __attribute__(x) # endif #endif #ifndef ATTRIBUTE_UNUSED # define ATTRIBUTE_UNUSED __attribute__ ((__unused__)) #endif /* Set the access and modification time stamps of FD (a.k.a. FILE) to be TIMESPEC[0] and TIMESPEC[1], respectively. FD must be either negative -- in which case it is ignored -- or a file descriptor that is open on FILE. If FD is nonnegative, then FILE can be NULL, which means use just futimes (or equivalent) instead of utimes (or equivalent), and fail if on an old system without futimes (or equivalent). If TIMESPEC is null, set the time stamps to the current time. Return 0 on success, -1 (setting errno) on failure. */ int gl_futimens (int fd ATTRIBUTE_UNUSED, char const *file, struct timespec const timespec[2]) { /* Some Linux-based NFS clients are buggy, and mishandle time stamps of files in NFS file systems in some cases. We have no configure-time test for this, but please see <> for references to some of the problems with Linux 2.6.16. If this affects you, compile with -DHAVE_BUGGY_NFS_TIME_STAMPS; this is reported to help in some cases, albeit at a cost in performance. But you really should upgrade your kernel to a fixed version, since the problem affects many applications. */ #if HAVE_BUGGY_NFS_TIME_STAMPS if (fd < 0) sync (); else fsync (fd); #endif /* There's currently no interface to set file timestamps with nanosecond resolution, so do the best we can, discarding any fractional part of the timestamp. */ #if HAVE_FUTIMESAT || HAVE_WORKING_UTIMES struct timeval timeval[2]; struct timeval const *t; if (timespec) { timeval[0].tv_sec = timespec[0].tv_sec; timeval[0].tv_usec = timespec[0].tv_nsec / 1000; timeval[1].tv_sec = timespec[1].tv_sec; timeval[1].tv_usec = timespec[1].tv_nsec / 1000; t = timeval; } else t = NULL; if (fd < 0) { # if HAVE_FUTIMESAT; # endif } #endif if (!file) { #if ! (HAVE_FUTIMESAT || (HAVE_WORKING_UTIMES && HAVE_FUTIMES)) errno = ENOSYS; #endif /* Prefer EBADF to ENOSYS if both error numbers apply. */ if (errno == ENOSYS) { int fd2 = dup (fd); int dup_errno = errno; if (0 <= fd2) close (fd2); errno = (fd2 < 0 && dup_errno == EBADF ? EBADF : ENOSYS); } return -1; } #if HAVE_WORKING_UTIMES return utimes (file, t); #else { struct utimbuf utimbuf; struct utimbuf const *ut; if (timespec) { utimbuf.actime = timespec[0].tv_sec; utimbuf.modtime = timespec[1].tv_sec; ut = &utimbuf; } else ut = NULL; return utime (file, ut); } #endif } /* Set the access and modification time stamps of FILE to be TIMESPEC[0] and TIMESPEC[1], respectively. */ int utimens (char const *file, struct timespec const timespec[2]) { return gl_futimens (-1, file, timespec); } | http://opensource.apple.com/source/gnutar/gnutar-450/gnutar/lib/utimens.c | CC-MAIN-2015-48 | refinedweb | 497 | 66.23 |
About files in the "src" directory: -- Change all #include <config.h> to #include "config.h". -- On config.h (which I must edit by hand): -- I had to put in #ifndef CONFIG_H #define CONFIG_H ... #endif /* CONFIG_H */ -- I am worrying about constructs such as /* Define to `unsigned' if <sys/types.h> doesn't define. */ #undef size_t because, if not edited, it means the name is undefined. Those I changed to /* Define to `unsigned' if <sys/types.h> doesn't define. */ #if 0 #undef size_t #endif -- I could not find any instance of the HAVE_DONE_WORKING_REALLOC_CHECK name in the sources. -- Same problem as before: If one merely writes #define FOO_BAR, there are later illegal used of type #if FOO_BAR. Therefore either the text of this file should be changed to "Define to 1 if ..." or all uses should be of the form #if ... defined(FOO_BAR) ... -- Some missing macros in the new config.hin (shown with my values) #define LOCALEDIR ":" -- Important as MacOS use ":" here. /* The location of the simple parser (bison.simple). */ #define XPFILE "bison.simple" /* The location of the semantic parser (bison.hairy). */ #define XPFILE1 "bison.hairy" -- It says that VERSION isn't used in Bison, but it is used by version() in getargs.c. So #define VERSION "1.28a" ----------------------- File complain.h: Add #include "system.h" (because of the macro __attribute__). File files.h: Add #include "system.h" (because of the macro PARAMS). I get a lot of warnings: Warning : identifier 'bool' redeclared system.h line 163 typedef int bool; -- xstrdup() was not in src, but in lib/xstrdup.c. Then it includes <sys/types.h> which is not necessary, at least not under ISO C. Also xstrdup does not have a prototype. -- xrealloc() was not in src, but in lib/xmalloc.c. Then it includes <sys/types.h> which is not necessary, at least not under ISO C. -- I also had to include from lib the files getopt.c and getopt1.c. -- Because some C library files show up as though they were project files, I think you might have used #include "..." instead of the correct #include <...> at some places in the code. -- It is not clear to me, what is complain(), a warning, that is, something that will produce a compiled output, or an error, something that will abort compilation? -- I still had to use my stuff around exit(): void Exit(int status); #define exit Exit void Exit(int status) { done(); /* Was registred by atexit() */ longjmp(main_env, (status == 0)? INT_MAX : status); } A more clever way would have been to register another function with atexit() which is doing a longjump, but that way I cannot pick up the status that exit() gets as an argument. -- File bison.s1: -- The arguments of the #line directives have been lost. I entered: line 2: #line 3 "bison.simple" line 240: #line 241 "bison.simple"¨ line 614: #line 615 "bison.simple" -- As before, I added to bison.simple: #if __MWERKS__ && macintosh #define YYSTACK_USE_ALLOCA #include <alloca.h> #include <stdlib.h> #endif before the first YYSTACK_USE_ALLOCA in that file. (And because of that my #line numbers become different than if this stuff wasn't put in these files.) -- But after doing those changes, the rpcalc example from the bison docs compiled as before. -- I will pack down my altered sources and mail them to you so that you can check the diff's (I do not have access to the program "diff" so this is the only way). I will have to fiddle around a bit more with the code in order to see that it is all right. Hans Aberg | http://lists.gnu.org/archive/html/bug-bison/2000-10/msg00028.html | CC-MAIN-2015-18 | refinedweb | 594 | 77.84 |
When we are working on big projects or with groups of developers, we often find that our code is messy, difficult to read, and hard to extend. This is especially true after time passes and we come back and look at it again—we have to try to be in the same mindset where we were when we wrote it.
So what a lot of people have done is they have created CSS architectures to help to style their code so that CSS becomes more readable. SMACSS—i.e., Scalable and Modular Architecture for CSS—aims to do just that. It’s a particular set of CSS architecture guidelines from Jonathan Snook that I’ve adopted.
Now, the architectural approach of SMACSS is a bit different from a CSS framework like Bootstrap or Foundation. Instead, it’s a set of rules, more like a template or guide. So let’s dive into some CSS design patterns to find out how we can use them to make our code better, cleaner, easier to read, and more modular.
Every SMACSS project structure uses five categories:
- Base
- Layout
- Modules
- State
- Theme
Base
In SMACSS, base styles define what an element should look like anywhere on the page. They are the defaults. If you’re using a reset stylesheet, this ensures that your resulting styles are the same across browsers despite the differences among their internal, hard-coded base CSS defaults.
In a base style, you should only include bare element selectors, or those with pseudo-classes, but not with class or ID selectors. (You should have really good reason to put class or ID inside it, maybe only if you are styling a third-party plugin’s elements and you need to override the default styling for that particular element.)
Here is an example of how a base file unit should look:
html { margin: 0; font-family: sans-serif; } a { color: #000; } button { color: #ababab; border: 1px solid #f2f2f2; }
So it should include default sizes, margins, colors, borders, and any other default values you plan to use across your website. Your typography and your form elements should have unified styles which appear on every page and give a feel and look that they are part of the same design and theme.
SMACSS or not, I highly recommend avoiding the use of
!important as much as possible, and not to use deep nesting, but I will talk more about that later in this post. Also if your practice is to use reset CSS, this is the place where you should include it. (I prefer to use Sass, so I just include it at the top of the file, rather than having to copy it in or refer to it separately from each page’s
<head> element.)
Layout
Layout styles will divide the page into major sections—not sections like navigation or maybe the accordion, for example, but really top-level divisions:
These layouts will hold multiple CSS modules like boxes, cards, unordered lists, galleries, and the like, but I will talk more about modules in the next section. Let’s consider an example web page to see what we can split into layouts:
Here we have header, main, and footer. These layouts have modules like links and logo on the header at the top, boxes and articles on main, and links and copyright for the footer. We usually give layouts an ID selector, as they don’t repeat on the page and they are unique.
Also you should prefix rules for layout styles with the letter
l to distinguish them from module styles. Usually here you would style things specific to layout, like border, alignments, margins, etc. Also the background of that part of the page could make sense, even if it doesn’t seem to be quite as layout-specific.
Here is an example of how it should look:
#header { background: #fcfcfc; } #header .l-right { float: right; } #header .l-align-center { text-align: center; }
You can also add these helpers for alignments which you can use to easily position elements by just adding the appropriate class to its child or to align its text.
For another example, you could use some default margins on a layout box, like
.l-margin having a margin of
20px. Then, wherever you want padding for some container, element, card, or box, you just add the
l-margin class to it. But you want something reusable:
.l-full-width { width: 100%; }
Not something internally coupled like this:
.l-width-25 { width: 25px; }
I want to take a moment to talk about naming conventions in SMACSS. If you’ve never heard of the concept of namespacing in CSS, it’s basically adding the name to the beginning of another element to help distinguish it from anything else. But why do we need this?
I don’t know if you’ve ever run into the following problem. You’re writing CSS and you have a label on something—you put in whatever styles you like, and call your class
.label. But then you come to another element later on, and you also want it to be
.label, but style it differently. So two different things have the same name—a naming conflict.
Namespacing helps you resolve this. Ultimately, they are called the same thing on one level, but they have a different namespace—a different prefix—and thus can represent two different styles:
.box--label { color: blue; } .card--label { color: red; }
Module
Like I mentioned earlier, SMACSS modules are smaller bits of code that are reusable on the page, and they are part of a single layout. These are parts of CSS that we want to store in a separate folder, as we will have a lot of these on a single page. And as a project grows, we can split using folder structure best practices, i.e., by modules/pages:
So in the previous example, we had an article, which can be a module on its own. How should CSS be structured here? We should have a class
.article which can have child elements
title and
text. So to be able to keep it in the same module, we need to prefix the child elements:
.article { background: #f32; } .article--title { font-size: 16px; } .article--text { font-size: 12px; }
You may notice that we are using two hyphens after the module prefix. The reason is that sometimes module names have two words or their own prefixes like
big-article. We need to have two hyphens in order to tell what part of it is the child element—e.g. compare
big-article-title to
big-article--title and
big-article--text.
Also, you can nest modules inside modules if a particular module takes a large portion of the page:
<div class="box"> <div class="box--label">This is box label</div> <ul class="box--list list"> <li class="list--li">Box list element</li> </ul> </div>
Here, in this simple example, you can see that
box is a module and
list is another module inside it. So
list--li is a child of the
list module and not of the
box.
One of the key concepts here is to use two selectors max per each CSS rule, but in most scenarios to have only one selector with prefixes.
This way, we can avoid duplicating rules and also having extra selectors on child elements with the same names, thus improving speed. But it also helps us avoid using the unwanted
!important-style rules, which are a sign of poorly structured CSS projects.
Good (note the single selector):
.red--box { background: #fafcfe; } .red-box--list { color: #000; }
Bad (note the repetition within selectors and the overlapping reference method):
.red .box { background: #fafcfe; } .red .box .list { color: #000; } .box ul { color: #fafafa; }
State
What state defines in SMACSS is a way to describe how our modules look in different dynamic situations. So this part is really for interactivity: We want different behavior if an element is considered to be hidden, expanded, or modified. For example, a jQuery accordion will need help defining when you can or can’t see an element’s content. It helps us to define an element’s style at a specific time.
States are applied to the same element as layout so we are adding an additional rule which will override previous ones, if any. The state rule is given precedence, as it’s the last one in the chain of rules.
As with layout styles, we tend to use prefixes here. This helps us to recognize them and to give them priority. Here we use the
is prefix, as in
is-hidden or
is-selected.
<header id="header"> <ul class="nav"> <li class="nav--item is-selected">Contact</li> <li class="nav--item">About</li> </ul> </header>
.nav--item.is-selected { color: #fff; }
Here,
!important may be used, as state is often used as a JavaScript modification and not at render time. For example, you have element that’s hidden on page load. On button click, you want to show it. But the default class is like this:
.box .element { display: none; }
So if you just add this:
.is-shown { display: block; }
It will remain hidden even after you add the
.is-shown class to the element via JavaScript. This is because the first rule is two levels deep and will override it.
So you can instead define the state class like this:
.is-shown { display: block !important; }
This is how we distinguish state modifiers from layout ones, which apply only on a page’s initial load. This will work now while maintaining the advantages of minimal selectors.
Theme
This one should be the most obvious, as it’s used to contain the rules of the primary colors, shapes, borders, shadows, and such. Mostly these are elements which repeat across a whole website. We don’t want to redefine them each time we create them. Instead we want to define a unique class which we only add on later to a default element.
.button-large { width: 60px; height: 60px; }
<button class="button-large">Like</button>
Don’t confuse these SMACSS theme rules with base ones, since base rules target only default appearance and they tend to be something like resetting to default browser settings, whereas a theme unit is more of a type of styling where it gives the final look, unique for this specific color scheme.
Theme rules can also be useful if a site has more than a single style or perhaps a couple of themes used in different states and therefore can be easily changed or swapped during some events on a page, e.g. with a theme-switch button. At the very least, they keep all theme styles in one place so you can change them easily and keep them nicely organized.
CSS Organization Methodologies
I’ve covered some of the key concepts of this CSS architecture idea. If you want to learn more about this concept you can visit the official website of SMACSS and get deeper into it.
Yes, you can probably use more advanced methodologies like OOCSS and BEM. The latter covers almost the complete frontend workflow and its technologies. But some may find BEM selectors too long and overwhelming and also too complicated to use. If you need something simpler that’s easier to pick up and to incorporate into your workflow—and also something that defines ground rules for you and your team—SMACSS is a perfect fit.
It will be easy for new team members not only to understand what previous developers did, but also to start working on it instantly, without any differences in coding style. SMACSS is just a CSS architecture and it does what it says on the tin—nothing more and nothing less.
Understanding the Basics
What are the different types of CSS?
There are three types. Inline CSS is placed directly on an HTML element's style attribute. Internal CSS sits inside style tags in the HTML header. External CSS is a separate file sourced by an HTML file, avoiding duplication both within and between the HTML pages on a website.
What is meant by "CSS template"?
CSS templates are usually specific layouts defined such that we can use them on multiple pages or even websites. Sometimes they go beyond layout, defining a set of rules for specific types of elements like modals and buttons, or even groups of them. Some also define default styles for HTML elements.
Why is CSS so important?
CSS is absolutely a must in modern day web pages. Without it, web pages are just plain text and pictures on a blank background. It not only gives style to the page, but also organizes layout and provides effects and animations—so it's important for interactivity as well.
What are the advantages of using CSS?
One of the main advantages is to have all styles in one place rather than having them across a whole web page on every element. It gives us more formatting options and helps optimize both page load time and code reuse.
Why is scalability so important?
In general, scalability is important in order to stay extensible and maintainable as a project grows. With CSS in particular, if we don't write scalable and modular code, it quickly grows out of control, becoming hard to understand and to work on, especially for newcomers. Hence the need for SMACSS. | https://www.toptal.com/css/smacss-scalable-modular-architecture-css?utm_source=CSSWeekly&utm_campaign=Q3 | CC-MAIN-2018-43 | refinedweb | 2,243 | 71.65 |
2028Re: Auto-generated namespaces
Expand Messages
- Nov 8, 2002Duncan, Paul
Thanks for the responses. My follow on question is this: my client
code accesses a WSDL file like so:
$soap =
SOAP::Lite->service('');
..... #initialize @val and pass it to the service
$res = $soap->echoStructArray(\@val);
If "brook" is defined in my WSDL, shouldn't this be sufficient? It
appears that even if "brook" is defined and has it's own namespace,
SOAP::Lite still generates "namespaces.soaplite.com/perl" in the
response. So far, the only way I've been able to get my WSDL to agree
with the returned SOAP is to put "brook" in the
"namespaces.soaplite.com/perl" namespace.
In a follow-on to this post, Paul said I can use the maptype method to
specify my own namespaces. I see where I can do this for the request
(I could just add $soap->maptype(...) into the code above), but how do
I use maptype to change the namespace of the response? Do I need to
rewrite my CGI server to somehow manipulate the namespaces in the SOAP
envelope? Or can I somehow add it to my echoStructArray code?
Thanks
--- In soaplite@y..., Duncan Cameron <dcameron@b...> wrote:
> On 2002-11-07 Martin McFly wrote:
> >Another question:
> >
> >Is there a way to control the namespaces generated in a SOAP
envelope?
> >
> >I've noticed that SOAP::Lite as a server (I used the extremely simple
> >CGI server example) generates namespaces automatically to some degree.
> > For example, I have a server that dispatches to a .pm with the
> >following code:
> >
> >Server code:
> >
> >use SOAP::Transport::HTTP;
> >
> >$obj = SOAP::Transport::HTTP::CGI->new();
> >$obj->dispatch_to('c:/Inetpub/Scripts/WSDL/Interop', 'Interop',
> >'Interop::echoStructArray')
> > -> handle;
> >
> >Package code:
> >
> >sub echoStructArray {
> > my $self = shift;
> > my $input = shift;
> > $val[0] = SOAP::Data->type("SOAPStruct")->value({"varInt"=>1,
> >"varFloat"=>1.1, "varString"=>"summ 1"});
> > $val[1] = SOAP::Data->type("SOAPStruct")->value({"varInt"=>22,
> >"varFloat"=>22.22, "varString"=>"summ 22"});
> > $val[2] = SOAP::Data->type("SOAPStruct")->value({"varInt"=>333,
> >"varFloat"=>333.33, "varString"=>"summ 333"});
> > return SOAP::Data->name("return" => \@val);
> >}
> >
> >This results in the following SOAP being returned:
> >
> ><:SOAPStruct[3]"
> >xsi:
> ><item xsi:
> ><varFloat xsi:1.1</varFloat>
> ><varString xsi:summ 1</varString>
> ><varInt xsi:1</varInt>
> ></item> etc....
> >
> >The thing that is puzzling me is where namesp2 came from. SOAP::Lite
> >seems to have auto-generated this namespace of
> >"xml.apache.org/xml-soap", and used it throughout the SOAP response.
>
> SOAPStruct is associated automatically with the xml.apache.org/xml-soap
> namespace. If you don't want that namespace then don't use
> type('SOAPStruct') or type it as something else. What is appropriate
> depends on your destination system.
>
> >Thus, if I were writing a WSDL file, I would be forced to use
> >"xml.apache.org/xml-soap" in order for my namespaces to agree.
> >
> >Similarly, if I change my .pm file to the following (all I'm doing is
> >changing "SOAPStruct" to an arbitrary name "brook"):
> >
> >sub echoStructArray {
> > my $self = shift;
> > my $input = shift;
> > $val[0] = SOAP::Data->type("brook")->value({"varInt"=>1,
> >"varFloat"=>1.1, "varString"=>"summ 1"});
> > $val[1] = SOAP::Data->type("brook")->value({"varInt"=>22,
> >"varFloat"=>22.22, "varString"=>"summ 22"});
> > $val[2] = SOAP::Data->type("brook")->value({"varInt"=>333,
> >"varFloat"=>333.33, "varString"=>"summ 333"});
> > return SOAP::Data->name("return" => \@val);
> >}
> >
> >then the resulting SOAP response is:
> >
> ><:brook[3]"
xsi:
> ><item .... etc.
> >
> >Notice in this example that namesp2 has now changed to
> >"namespaces.soaplite.com/perl"!!! How can I control what namespace is
> >generated in the envelope? I'm sure there's a simple answer to this
> >question, I just haven't been able to figure it out.
>
> Now you have specified a type of 'brook' without any definition of
> what that type is. SOAP::Lite has to put it in a namespace so has
> put it in its own one.
>
> If you're confused by this then you probably need to clarify what
> your destination system is expecting.
>
> Regards,
> Duncan Cameron
- << Previous post in topic Next post in topic >> | https://groups.yahoo.com/neo/groups/soaplite/conversations/messages/2028 | CC-MAIN-2015-27 | refinedweb | 672 | 58.28 |
Post your Comment
DATE
DATE I have the following as my known parameter Effective Date... of calcultion starts
My question is how to find the date of Thursday
This cycle repeats based on every cut off day
Here is an example that displays
JSP date example
Hibernate criteria date between Example
Hibernate criteria date between Example Hibernate criteria date between Example
I want example of hibernate criteria date between with source code.
Share me the url.
Thanks
Example of Hibernate criteria date
Date Example
Date Example
In this section we are discussing about the specific date
using the Date class object, retrieving milliseconds from the Date object,
elapsed time, date
Hibernate Criteria Max Date Example
Hibernate Criteria Max Date Example How to write example program... the following links:
Example: Hibernate Criteria Max Date.
Check the tutorial... for finding max Date in Java program then check the following links:
Example
Date Formay - Date Calendar
Date Formay Sir,
How to comapare two different date format in java. Hi friend,
Code to compare two different date
import...))
System.out.print("Current date(" + new SimpleDateFormat("dd/MM/yyyy").
format
Simple Date example
Simple Date example
In this section we have presented a simple Date example
that shows how you can use different constructors of Date. We can construct the
Date
Formatting Date for a Locale Example
Formatting Date for a Locale Example
This example shows how to format Date using... use for formatting and parsing dates. It allows for formatting date into text
Mysql Date from Date
; date.
Understand with Example
The Tutorial illustrate an example from 'DateTime in Mysql'. To grasp this
example, we use date(current_trimestamp ( )) query... Mysql Date from Date
date print
date print how can i print the date in jsp page in the following formate month-date-year.
(example. march 8 2012
struts2.2.1 date Format example
struts2.2.1 date Format example.
In this example, We will discuss about the different type of date format
using struts2.2.1.
Directory structure of example.
1- index.jsp
<html>
<head>
<title>Date
Date Tool Example
Date Tool Example
This Example shows you how
to display date and time velocity. ... and properties.
Date date = cal.getTime():
Here
we created Date
date_diff
date_diff
date_diff alias DateTime::diff returns the difference between two... [, bool $absolute ] )
Parameters
datetime - The date to compare to.
absolute - Whether to return absolute difference. Defaults to FALSE.
Example
Simple Date Format Example
Following is a simple date format example made using Format class. We have
uses a pattern of special characters to date and time format.
In this example... is a simple Date Format Example:
import java.text.*;
import java.util.*;
public
Date Field Midlet Example
Date Field MIDlet Example
This example illustrates how to insert date field in your form. We... static variable DATE which is 0. We are taking both DateField
variable
Date Format Example
Date Format Example
This example shows how to format Date using Format class... for formatting and parsing dates. It allows for formatting date into text
Mysql Date no Time
.
Understand with Example
The Tutorial illustrate an example 'Date no Time' in Mysql . In this Example,
the date(now( ) ) return you the current date with no time...
Mysql Date no Time
Example of Date class
Example of Date class
We can use Date class to use current date. In this program we are creating a Date object and
by using it we are going to display the current date
Parsing Date Example
Parsing Date Example
This example shows how to parsing date using Format class... and parsing dates. It allows for formatting date into text , parsing text into date
php date function - Date Calendar
php date function Hi,
I am new to PHP. I am trying to get date from database. But, every time the date under 1970, it changes to 1970. Im totally confuced.thank u in advance.
For example :
database: date format
NSLog Date example code
and then used the NSLog function to print the date on the console.
//
// ...{
today= [NSDate date];
NSLog(@"the current date is %@",today);
}
@end
JSP date example
JSP date example
...;
The heart of this example is Date() function of the java.util... the current date and time.
So the following code accomplish="
Simple date formatter example
Simple date formatter example
In this section of simple date formatter example we...
class to convert the date into the specified format. There are various constructors
date_parse
by strtotime()
Example of Parse Date Function in PHP:
<?php
print_r(date...date_parse() in PHP
date_parse function returns associative array with detailed information about given date. It returns information about the date on success
Parsing Date And Time Example
Parsing Date And Time Example
This example shows how to parsing date and time using Format... for formatting and parsing dates. It allows for formatting date into text , parsing
Post your Comment | http://roseindia.net/discussion/22216-Parsing-Date-Example.html | CC-MAIN-2015-32 | refinedweb | 809 | 57.57 |
General Questions
What are the goals of XFire?
- Create a flexible SOAP framework, where any processing mechanismcan be plugged in.
- Be SOAP 1.2 and WS-I 1.1 compliant. Also to offer support for non-RPC/Encoded SOAP 1.1 services.
- Intuitive, easy to use API.
- Be Fast.
- Allow many different binding methods (traditional java types, OGNL, Castor, JaxME, etc).
- Create a processing model where your web service model and your java model can develop independently (see the Aegis Module).
- Modules for WS-Security and WS-Adressing support.
Technical Questions
Why is XFire producing invalid XML?
XFire is based on StAX and not all StAX implementations work correctly. See the Dependency Guide for information on how to choose a stax implementation.
Why aren't RPC/Encoded services supported by the Java Module?
For interoperability, WS-I basic profile basically says that trying to support RPC/encoded services is an interopability nightmare. And they're right! It isn't easy.
However, the basic framework to support RPC/Encoded services is in place. Vote for or contribute patches on bug XFIRE-425 if you need this.
Is XFire DOM Based?
XFire is structured so that in most cases the SOAP document does not need to be cached in memory at all. It is able to do this by using StAX - the streaming XML API.
What is this java.lang.NoSuchMethodError: javax.xml.namespace.QName.<init>(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String
V Exception?
Several application servers (WebSphere and WebLogic, for example) include an older version of the QName class. XFire (as well as XMLBeans and Stax) require the new version. WebLogic usage has been documented, WebSphere will be similar.
When I try to run the examples I get "The build cannot continue because of the following unsatisfied dependency: javamail-1.3.2.jar"
Due to Sun licensing restrictions we can't redistribute the javamail jar. You must download it and put it in your local maven repository - "~/.maven/javamail/jars/javamail-1.3.2.jar".
Interoperability
Can XFire act as a client to the Google Web Service?
No, because it does not support RPC/Encoded services (see above).
Can XFire work with .NET/PHP/Perl/Python client/server?
Yes, but you must ensure that your services are created and consumed with the document/literal style.
See PHP Interoperation for more details.
How can I add custom handler to my XFire client ( generated or dynamic ) ?
You can add handlers with following code :
Generated client :
Dynamic client:
I got java.lang.ClassCastException at javax.xml.transform.TransformerFactory.newInstance(Unknown Source) when accessing service WSDL
This exception is cased by presents of different xalan versions in classpath. To fix this problem, you have to make sure that correct one will be used, but removing the other one or by setting java property with points to valid one, like : -Djavax.xml.transform.TransformerFactory=org.apache.xalan.processor.TransformerFactoryImpl | http://docs.codehaus.org/display/XFIRE/FAQ | CC-MAIN-2015-22 | refinedweb | 486 | 52.05 |
89180/how-to-save-a-pandas-dataframe-to-a-pickle-file
Hi Guys,
I am new to the Pandas module. I want to save the Dataframe in a pickle file. How can I do that?
Hi@akhtar,
Python pickle module is used for serializing and de-serializing a Python object structure. Any object in Python can be pickled so that it can be saved on disk. You can use the below commands to save the Dataframe in a pickle file.
import pandas as pd
df = pd.DataFrame({"foo": range(5), "bar": range(5, 10)})
pd.to_pickle(df, "./dummy.pkl")
g1 here is a DataFrame. It has a hierarchical index, ...READ MORE
Try this:
for name in df['Name']:
...READ MORE
You can use the append method provided by pandas ...READ MORE
You can do this using the code ...READ MORE
suppose you have a string with a ...READ MORE
You can also use the random library's ...READ MORE
Syntax :
list. count(value)
Code:
colors = ['red', 'green', ...READ MORE
can you give an example using a ...READ MORE
Hi@akhtar,
There is no inbuilt function available to ...READ MORE
Hi@akhtar,
Hierarchical Data Format (HDF) is a set ...READ MORE
OR
Already have an account? Sign in. | https://www.edureka.co/community/89180/how-to-save-a-pandas-dataframe-to-a-pickle-file | CC-MAIN-2020-50 | refinedweb | 207 | 79.56 |
I’ve read that <fstream> predates <exception>. Ignoring the fact that exceptions on fstream aren’t very informative, I have the following question:
It’s possible to enable exceptions on file streams using the exceptions() method.
ifstream stream; stream.exceptions(ifstream::failbit | ifstream::badbit); stream.open(filename.c_str(), ios::binary);
Any attempt to open a nonexistent file, a file without the correct permissions, or any other I/O problem will results in exception. This is very good using an assertive programming style. The file was supposed to be there and be readable. If the conditions aren’t met, we get an exception. If I wasn’t sure whether the file could safely be opened, I could use other functions to test for it.
But now suppose I try to read into a buffer, like this:
char buffer[10]; stream.read(buffer, sizeof(buffer));
If the stream detects the end-of-file before filling the buffer, the stream decides to set the failbit, and an exception is fired if they were enabled. Why? What’s the point of this? I could have verified that just testing eof() after the read:
char buffer[10]; stream.read(buffer, sizeof(buffer)); if (stream.eof()) // or stream.gcount() != sizeof(buffer) // handle eof myself
This design choice prevents me from using standard exceptions on streams and forces me to create my own exception handling on permissions or I/O errors. Or am I missing something? Is there any way out? For example, can I easily test if I can read sizeof(buffer) bytes on the stream before doing so?
Failbit set when trying to read from file – why?
I’m trying to write a function that automatically formats XML-Strings; but I’m already failing when I try to read text from a file and write it into another one. When I use my function sortXMLString()
Loading file in C++, failbit is set and I can’t figure out why [duplicate]
Possible Duplicate: Failing to read file loaded with ifstream The output of the following file is: 00100. This indicates to me that failbit is set. The problem is I can’t figure out why it is set. A
C++ istream EOF does not guarantee failbit?
I read a question on Stack Overflow where the eofbit for the istream file is set but the failbit is not. In that case file is true and file.eof() is true but file.good() is false. For example with a f
Why is the failbit being set. File seems to have printed fine
I have a piece of code that does the work it is intended to do but I have doubts about failbit. Th catch block always runs although the file is displayed on the screen. When eof is reached why is fail
Why does not seekg(0) clear the eof state of stream?
I would like to know if and why seekg(0) is not supposed to clear the eofbit of a stream. I am in a point where I have already read all the stream, thus EOF has been reached (but no failbit is set yet
std::getline throwing when it hits eof
std::getline throws exception when it gets an eof. this is how I am doing. std::ifstream stream; stream.exceptions(std::ifstream::failbit|std::ifstream::badbit); try{ stream.open(_file.c_str(), std::i
Can read(2) return zero when not at EOF?
According to the man page for read(2), it only returns zero when EOF is reached. However, It appears this is incorrect and that it may sometimes return zero, perhaps because the file is not ready to b
ifstream sets failbit on declaration
I don’t really understand why this is happening at all. I’m trying to open a file to read some data into my program but failbit gets set instantly, having moved error messages around it seems that fai
failbit not being set when seekg seeks past end of file (C++,Linux)
I’m seeing what I think is odd behaviour of istream::seekg. Specifically, it appears to NOT set the failbit when I seek to a point that is clearly way off the end of the file. From what I can tell in
What is a better way to read a file until it ends than using istream eof?
I have read that using istream eof is buggy and not a formal way of writing code, so what is a better code to use? For example, I have the following code: using namespace std; //I’ve heard this is
Answers
The failbit is designed to allow the stream to report that some operation failed to complete successfully. This includes errors such as failing to open the file, trying to read data that doesn’t exist, and trying to read data of the wrong type.
The particular case you’re asking about is reprinted here:
char buffer[10]; stream.read(buffer, sizeof(buffer));
Your question is why failbit is set when the end-of-file is reached before all of the input is read. The reason is that this means that the read operation failed – you asked to read 10 characters, but there weren’t sufficiently many characters in the file. Consequently, the operation did not complete successfully, and the stream signals failbit to let you know this, even though the available characters will be read.
If you want to do a read operation where you want to read up to some number of characters, you can use the readsome member function:
char buffer[10]; streamsize numRead = stream.readsome(buffer, sizeof(buffer));
This function will read characters up to the end of the file, but unlike read it doesn’t set failbit if the end of the file is reached before the characters are read. In other words, it says “try to read this many characters, but it’s not an error if you can’t. Just let me know how much you read.” This contrasts with read, which says “I want precisely this many characters, and it’s an error if you can’t do it.”
EDIT: An important detail I forgot to mention is that eofbit can be set without triggering failbit. For example, suppose that I have a text file that contains the text
137
without any newlines or trailing whitespace afterwards. If I write this code:
ifstream input("myfile.txt"); int value; input >> value;
Then at this point input.eof() will return true, because when reading the characters from the file the stream hit the end of the file trying to see if there were any other characters in the stream. However, input.fail() will not return true, because the operation succeeded – we can indeed read an integer from the file.
Hope this helps!
EDIT: Outdated by @absence approach. Also I added another answer with more research.
I can’t use <fstream> effectively with built-in exceptions for what I think it’s a bad design choice. Leaving them disabled my workaround is doing custom exception throwing:
// Code assertion: the filename should exist and be readable ifstream stream; stream.open(filename.c_str(), ios::binary); if (stream.fail()) // Any error during opening is exceptional throw fstream::failure(); char buffer[10]; stream.read(buffer, sizeof(buffer)); if (stream.fail() && !stream.eof()) // This is an exceptional event throw fstream::failure(); if (fstream.eof()) // Nothing exceptional here ; // handle eof myself
Using the underlying buffer directly seems to do the trick:
char buffer[10]; streamsize num_read = stream.rdbuf()->sgetn(buffer, sizeof(buffer));
Improving @absence’s answer, it follows a method readeof() that does the same of read() but doesn’t set failbit on EOF. Also real read failures have been tested, like an interrupted transfer by hard removal of a USB stick or link drop in a network share access. It has been tested on Windows 7 with VS2010 and VS2013 and on linux with gcc 4.8.1. On linux only USB stick removal has been tried.
#include <iostream> #include <fstream> using namespace std; streamsize readeof(ifstream &stream, char* buffer, streamsize count) { // This consistently fails on gcc (linux) 4.8.1 with failbit set on read // failure. This apparently never fails on VS2010 and VS2013 (Windows 7) streamsize reads = stream.rdbuf()->sgetn(buffer, count); // This rarely sets failbit on VS2010 and VS2013 (Windows 7) on read // failure of the previous sgetn() stream.rdstate(); // On gcc (linux) 4.8.1 and VS2010/VS2013 (Windows 7) this consistently // sets eofbit when stream is EOF for the conseguences of sgetn(). It // should also throw if exceptions are set, or return on the contrary, // and previous rdstate() restored a failbit on Windows. On Windows most // of the times it sets eofbit even on real read failure stream.peek(); return reads; } #define BIGGER_BUFFER_SIZE 200000000 int main(int argc, char* argv[]) { ifstream stream; stream.exceptions(ifstream::badbit | ifstream::failbit); stream.open("<big file on usb stick>", ios::binary); char *buffer = new char[BIGGER_BUFFER_SIZE]; streamsize reads = readeof(stream, buffer, BIGGER_BUFFER_SIZE); if (stream.eof()) cout << "eof" << endl << flush; delete buffer; return 0; }
Bottom line: on linux the behavior is more consistent and meaningful. With exceptions enabled on real read failures it will throw on sgetn(). On the contrary Windows will treat read failures as EOF most of the times. | http://w3cgeek.com/why-is-failbit-when-eof-on-read-is-there-a-way-out.html | CC-MAIN-2019-04 | refinedweb | 1,543 | 64 |
Hyperlinks (or simply links) are an integral part of the web. There are 3 options to open hyperlinks in Flutter. So, in this article, we will see how to open Flutter Hyperlinks on the Web and Mobile.
How to open Flutter Hyperlinks on Web and Mobile?
Flutter for the web doesn’t allow importing the url_launcher package. If you needed to open a link, you had to use the dart:html package or dart:js. Since the dev channel of Flutter allows targeting the web platform, not much has changed when it comes to opening links. You can still use the above-mentioned packages if the plan is only to target the web. If you plan to target web and mobile you need to use the universal_html package.
1) Opening a link with a dart:html would be like:
import 'dart:html' as html; void htmlOpenLink() { String url = ''; html.window.open(url, '_blank'); }
2) Opening a link using dart:js would be like:
First, edit the index.html file inside the web folder (located on the root level of your Flutter project).
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>hyperlinks_demo</title> <script type="application/javascript"> function openLink(url, target) { window.open(url, target); } </script> </head> <body> <script src="main.dart.js" type="application/javascript"></script> </body> </html>
Then you have the function that opens the link:
import 'dart:js' as js; void jsOpenLink() { String url = ''; js.context.callMethod('openLink', [url, '_blank']); }
As you can see, this would be more tricky to pull off than the previous example but actually does the same thing. However, in the JS function openLink, more functionality can be added if needed.
3) If you plan to target multiple platforms (web and mobile), then the approach would be to use the universal_html package and the url_launcher.
import 'package:url_launcher/url_launcher.dart'; import 'package:universal_html/html.dart' as html; import 'package:flutter/foundation.dart'; void openLink() async { String url = ''; if(kIsWeb) { html.window.open(url, '_blank'); } else { if(await canLaunch(url)) { launch(url); } } }
A quick explanation for the above code:
- We’ve imported the needed packages (url_launcher – will enable us to open links on mobile devices, universal_html – will enable us to open links from the web browsers, and foundation will help us decide if our code is running in a web browser or not)
- We’ve defined the URL we want to open
- We check if the code is running in the web browser using kIsWeb, and if it is, then we use the window.open method.
- Otherwise, we check if we can launch the URL (we can still be on a desktop or other type of device) using the async method canLaunch. The reason we’re awaiting is its boolean result. If it returns true, then we call the launch method that will do its magic on the device we’re on.
Options 1 and 2 are fine if you’d like to only target the web platform. If you want to target all the platforms, then option 3 would be the way to go.
Safari issues on iOS and macOS:
The above methods won’t work on Safari (iOS and macOS) if any of the openLink functions are called after waiting for an async operation to end (the call is not synchronized). The solution is to detect if we’re on Safari and if so to just change the window.location.href. Example 2 becomes:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>hyperlinks_demo</title> <script type="application/javascript"> function openLink(url, target, isAsync=false) { var is_safari = /^(?!.*chrome).*safari/i.test(navigator.userAgent.toLowerCase()); if (is_safari && isAsync) { window.location.href = url; } else { window.open(url, target); } } </script> </head> <body> <script src="main.dart.js" type="application/javascript"></script> </body> </html>
Link Target Options
In the above examples, we’ve used _blank as a target window for our URL. Here are the few target options you have when it comes to open a link in the web browser:
- _blank – specifies a new window
- _self – specifies the current frame in the current window
- _parent – specifies the parent of the current frame
- _top – specifies the top-level frame in the current window
- A custom target name of a window that exists
Now that you’ve got an insight on opening links in Flutter, you can also put a CustomCursor on the widgets that are going to open those, so it makes it more straightforward.
Conclusion:
Thanks for being with us on a Flutter Journey!
So, in this article, we have seen how to open Flutter Hyperlinks on the Web and Mobile.. | https://flutteragency.com/open-flutter-hyperlinks-on-web-and-mobile/ | CC-MAIN-2021-43 | refinedweb | 766 | 61.67 |
You may already be using Maven, a build tool that attempts to put structure around your build environment. As part of this, Maven comes with a very rich set of plugins that provide enhanced functionality such as running JUnit tests; building .jar, .war, and .ear files; and generating reports like JCoverage, Clover, PMD, or Simian. However, what happens when your favorite tool doesn't have a corresponding Maven plugin? This is where writing your own Maven plugin allows you to add new functionality to Maven.
This article will cover creating a "Hello World" plugin for Maven. We will demonstrate the various aspects of Maven plugin development, starting with a simple "Hello World" goal, introducing the use of Java code in goals, and finally generating a web report. This article assumes you have already downloaded and installed the latest version of Maven. For more information about using Maven, please read Rob Herbst's ONJava article "Developing with Maven."
All of the source code for this article is available as a .zip file. Just download and unzip it to a convenient location.
Our first example is a very simple plug-in that will emit "Hello World" to the console when you run maven helloworld.
maven helloworld
Let's look at what makes up a plugin. In the step1 directory there are two files, project.xml and plugin.jelly. The project.xml file is your standard Maven POM (Project Object Model) file. Because there is no Java code, or any resources, it is a very short file. The plugin.jelly file is the heart of your plugin. The extension .jelly means that the plugin is written using Jelly, a XML-based scripting language that is similar to the one used by Ant. Indeed, Ant syntax can be used directly inside of Jelly scripts! More information is available in the ONJava article "Using the Jakarta Commons, Part 2."
When you look at plugin.jelly you can see how simple it is:
<project
xmlns:
<goal name="helloworld"
description="Emit Hello World">
<ant:echo
</goal>
</project>
As you can see, we are just using the Ant tag echo to send "Hello World" to the console! We import the namespace ant with the XML xmlns:ant="jelly:ant". You can think of a namespace as a Java import statement for Jelly.
echo
ant
xmlns:ant="jelly:ant"
namespace
From the directory step1, install the plugin by entering maven plugin:install.
maven plugin:install
c:\[your dir]\step1\maven plugin:install
At the end of the output from the console, you will see that it has copied a file to your plugins directory.
plugin:install:
[copy] Copying 1 file to C:\java\maven\plugins
BUILD SUCCESSFUL
Total time: 3 seconds
Finished at: Tue Feb 03 19:00:01 CET 2004
You are now ready to run your plugin. On the command line, enter the following (this is the Windows version):
c:\[your dir]\step1\maven -g
You will see a long list of all the goals available to Maven. The goals with a description are meant to be used by users; the goals without a description are internal goals for Maven. You should see your plugin has been registered:
[helloworld] : Emit Hello World
Now go ahead and run the plugin. Enter:
c:\[your dir]\step1\maven helloworld
You should see on the console a "Hello World" message like this:
__ __
| \/ |__ _Apache__ ___
| |\/| / _` \ V / -_) ' \ ~intelligent projects~
|_| |_\__,_|\_/\___|_||_| v. 1.0-rc2-SNAPSHOT
helloworld:
[echo] Hello World
BUILD SUCCESSFUL
Total time: 1 seconds
Finished at: Tue Feb 03 19:06:18 CET 2004
If you want to generate the typical Maven documentation for the plugin, you use the site command:
site
c:\[your dir]\step1\maven site
Notice it generates all of the typical Maven documentation in step1/target/docs/. All the functionality of Maven that you would use in any other type of project is also available in a plugin project. There is nothing special that you need to configure to run unit tests, code coverage reports, etc.
This is all well and good, but what if want to customize the message emitted when you enter maven helloworld? We can parameterize the plugin by providing a plugin.properties file. Look at step2/plugin.properties:
helloworld.message=Hello out there!
Notice the helloworld.message property? This is the default value used by the plugin. The plugin.properties file provides defaults for the plugin to use. If you want to customize this plugin property, then in your project.properties file, specify a different value, such as helloworld.message=My custom hello world message.
helloworld.message
helloworld.message=My custom hello world message
If you open step2/plugin.jelly, you will now see that the message has been replaced with ${helloworld.message}. Any parameter you need to replace can be done with the ${} syntax, just like in Ant!
${helloworld.message}
${}
When packaging this plugin, Maven needs to know to package the new plugin.properties file. Look at step2/project.xml and you can see we are explicitly including the various plugin-related files:
<resources>
<resource>
<directory></directory>
<includes>
<include>plugin.jelly</include>
<include>plugin.properties</include>
<include>project.properties</include>
<include>project.xml</include>
</includes>
</resource>
</resources>
Go ahead and compile the step2 version of the plugin by switching to the step2 directory and running the install goal:
install
c:\helloworld\step2\maven plugin:install
The output should look something like this:
jar:jar:
[jar] Building jar: C:\clients\jn\html\
helloworld\step2\target\helloworld-plugin-2.0.jar
[copy] Copying 1 file to C:\java\maven\
repository\helloworld-plugin\plugins
plugin:uninstall:
[delete] Deleting 1 files from
C:\java\maven\plugins
[delete] Deleting 8 files from
C:\java\maven\plugins
[delete] Deleted 2 directories from
C:\java\maven\plugins
plugin:install:
[copy] Copying 1 file to
C:\java\maven\plugins
BUILD SUCCESSFUL
Did you notice in the output that you compiled a .jar that was set to version 2.0, and that the plugin:install goal deleted the older 1.0 version of the plug-in? Maven is smart enough to delete all other versions of this plugin when you install a new one.
plugin:install
Go ahead and run the plugin. You will see that it will emit Hello out there! if you don't have helloworld.message specified in your project.properties. | http://www.onjava.com/pub/a/onjava/2004/03/17/maven.html | CC-MAIN-2014-52 | refinedweb | 1,064 | 55.95 |
In our previous post, we made a model predict if a motor is faulty with its audio recording data. We feed the model with the audio time series data, achieved a decent testing accuracy of 0.9839. In this post, we will discover feeding the model with extracted features from the time series data. The final prediction accuracy improved to 100% with our test WAV file.
The Mel-frequency cepstrum (MFC) is a representation of the short-term power spectrum of a sound, Mel-frequency cepstral coefficients (MFCCs) are coefficients that collectively make up an MFC, MFC wiki.
Enough for the theory, let’s take a look at it visually.
In order to extract MFCC feature from our audio data, we are going to use the Python librosa library.
First, install it with pip
pip install librosa
We are going to use a siren sound WAV file for the demo. Download the siren_mfcc_demo.wav from the Github here and put in your directory
In a Python console/notebook, let’s import what we need first
import librosa import librosa.display import matplotlib.pyplot as plt import numpy as np plt.style.use('ggplot')
Then let’s extract the MFCC features
def feature_normalize(dataset): mu = np.mean(dataset, axis=0) sigma = np.std(dataset, axis=0) return (dataset - mu) / sigma siern_wav = "./siren_mfcc_demo.wav" sound_clip,s = librosa.load(siern_wav) sound_clip = feature_normalize(sound_clip) frames = 41 bands = 20 window_size = 512 * (frames - 1) mfcc = librosa.feature.mfcc(y=sound_clip[:window_size], sr=s, n_mfcc = bands)
feature_normalize function is same as the last post, which normalizes the audio time series to be around 0 and have standard deviation 1.
Let’s visualize the MFCC features, it is a numpy array with shape (bands, frames) i.e. (20, 41) in this case
librosa.display.specshow(mfcc, x_axis='time') plt.show()
This is the MFCC feature of the first second for the siren WAV file. The X-axis is time, it has been divided into 41 frames, and the Y-axis is the 20 bands. Did you notice any patterns in the graph? We will teach our model to see this pattern as well later.
The model structure will be different from the previous post since the model input changed to
MFCC features.
Notice one model input shape matches with one MFCC feature transposed shape (frames, bands) i.e. (41, 20). Mfcc feature is transposed since the RNN model expects time major input.
For the complete source code, check out my updated GitHub. Feel free to leave a comment if you have a question.Share on Twitter Share on Facebook | https://www.dlology.com/blog/one-simple-trick-to-improve-the-motor-acoustic-classifier/ | CC-MAIN-2020-24 | refinedweb | 431 | 67.25 |
Last Updated on
This is a project spotlight with Artem Yankov.
Could you please introduce yourself?
My name is Artem Yankov, I have worked as a software engineer for Badgeville for the last 3 years. I’m using there Ruby and Scala although my prior background includes use of various languages such as: Assembly, C/C++, Python, Clojure and JS.
I love hacking on small projects and exploring different fields, for instance two almost random fields I’ve looked at were Robotics and Malware Analysis. I can’t say I became an expert, but I did have a lot of fun. A small robot I built looked amazingly ugly but it could mirror my arms motion by “seeing” it through MS Kinect.
I didn’t do any machine learning at all until the last year when I finished Andrew Ng’s course on Coursera and I really loved it.
What is your project called and what does it do?
The project is called hapsradar.com and it’s an event recommendation site focused on what’s happening right now or in the near future.
I am a terrible planner of my weekends and I usually find myself wondering what to do if I suddenly decided to do something outside of my home/internet. The typical algorithm for me to find out what’s going on was to go to sites like meetup.com and eventbrite, browse through tons of categories, click lots of buttons and read list of the current events.
So when I finished machine learning course and started to look for projects to practice my skills I thought that I could really automate this event seeking process by fetching event lists from those sites and then building recommendation based on what I like.
The site is very minimalistic and currently provides events only from two sites: meetup.com and eventbrite.com. A user needs to rate at least 100 events before recommendation engine kicks in. Then it runs every night and trains using user likes/dislikes and then trying to predict events user might like.
How did you get started?
I started just because I wanted to practice my machine learning skills and to make it more fun I chose to solve a real problem I had. After some evaluation I decided to use python for my recommender. Here’s the tools I used:
- Pandas
- Scikit-Learn
- PostgreSQL
- Scala / PlayFramework (for events fetcher and website)
Events are fetched using standard APIs provided by meetup.com and eventbrite.com and stored in postgresql. I emailed them before I started my crawlers to double-check if I can do such a thing, specifically because I wanted to run this crawlers every day to keep my database updated with all the events.
The guys were very nice about that and eventbrite even bumped up my API rate limit without any questions. And meetup.com has a nice streaming API that allows you to subscribe to all the changes as they happening. I wanted to crawl yelp.com as well since they have event lists, but they prohibited this completely.
After I had a first cut of the data I built a simple site that displayed the events within some range of a given zip code (I currently only fetch events for the US).
Now the recommender part. The main material to build my features were the event title and event description. I decided that things like time of the day when event is happening, or how far it is from your home won’t add much of a value because I just wanted a simple answer to the question: is this event relevant to my interests?
Idea #1. Predict topics
Some of the fetched events have tags or categories, some of them don’t.
Initially I thought I should try to use the tagged events to predict tags for untagged events and then use them as training features. After spending some time on that I figured it might not be a good idea. Most of the tagged events had just 1-3 tags and they often were very inaccurate or even completely random.
I think eventbrite allows clients to type anything as a tag and people are just not very good at coming up with the good words. Plus the number of tags per event was usually low and wasn’t enough for judging about the event even if you used human intelligence 🙂
Of course it was possible to find already accurately classified text and use it for predicting topics, but that again, posed a lot of additional questions: Where to get classified text? How relevant it would be to my events descriptions? How many tags I should use? So I decided to find another ideas.
Idea #2. LDA Topic modeling
After some research I found an awesome python library called gensim which implements LDA (Latent Dirichlet Allocation) for topic modelling.
It’s worth noting that the use of topics here is not meant topics defined in English like “sports”, “music” or “programming”. Topics in LDA are probability distributions over words. Roughly speaking it finds clusters of words that come together with the certain probability. Each such cluster is a “topic”. You then feed the model a new document and it’s inferring topics for it as well.
Using LDA is pretty straight forward. First, I cleaned the documents (in my case document is event’s description and title) by removing stop English words, commas, html tags, etc. Then I build dictionary based on all events descriptions:
from gensim import corpora, models
dct = corpora.Dictionary(clean_documents)
Then I filter very rare words
dct.filter_extremes(no_below=2)
To train model all documents need to be converted into bag of words:
corpus = [dct.doc2bow(doc) for doc in clean_documents]
And then model is created like this
lda = ldamodel.LdaModel(corpus=corpus, id2word=dct, num_topics=num_topics)
Where num_topics is a number of topics that need to be modelled on the documents. In my case it was 100. Then to convert any document in form of bag of words to its topics representation in form of sparse matrix:
x = lda[doc_bow]
So now I can get a matrix of features for any given event and I can easily get a training matrix for the events user rated:
docs_bow = [dct.doc2bow(doc) for doc in rated_events]
X_train = [lda[doc_bow] for doc_bow in docs_bow]
That looked like more or less decent solution, using SVM (Support Vector Machine) classifier I got about 85% accuracy and when I looked at predicted events for me it did look quite accurate.
Note: Not all classifiers support sparse matrixes and sometimes you need to convert it to a full matrix. Gensim has a way to do that.
gensim.matutils.sparse2full(sparse_matrix, num_topics)
Idea #3. TF-IDF Vectorizer
Another idea I wanted to try for building features was TF-IDF vectorizer.
Scikit-learn supports it out-of-the-box and what’s it’s doing is assigning a weight for each word in the document based on frequency of this word in the document divided by the frequency of the word in a corpus of the documents. So the weight of the word will be low if you see it very often and that allows to filter out the noise. To build vectorizer out of all the documents:
from sklearn.feature_extraction.text import TfidfVectorizer
vectorizer = TfidfVectorizer(max_df=0.5, sublinear_tf = True, stop_words='english')
vectorizer.fit(all_events)
And then to transform given set of documents to their TF-IDF representation:
X_train = vectorizer.transform(rated_events)
Now, when I tried to feed that to a classifier that was really taking a long time plus results were bad. That’s actually not a surprise because in this case almost every word is a feature. So I started to look for a way to select best performing features.
Scikit-learn provides methods SelectKBest to which you can pass a scoring function and a number of features to select and it performs the magic for you. For scoring I used chi2 (chi-squared test) and I won’t say you exactly why. I just empirically found that it performed better in my case and put “study a theory behind chi2” in my todo bucket.
from sklearn.feature_selection import SelectKBest, chi2
num_features = 100
ch2 = SelectKBest(chi2, k=num_features)
X_train = ch2.fit_transform(X_train, y_train).toarray()
And that’s it. X_train is my training set.
Training classifier
I’m not happy to admit that but there wasn’t much science involved in how I chose classifier. I just tried bunch of them and choose the one that performed best. In my case it was SVM. As for the parameters I used Grid Search to choose the best ones and all of that scikit-learn provides out of the box. In code it looks like this:
clf = svm.SVC()
params = dict(gamma=[0.001, 0.01,0.1, 0.2, 1, 10, 100],C=[1,10,100,1000], kernel=["linear", "rb"])
clf = grid_search.GridSearchCV(clf,param_grid=params,cv=5, scoring='f1')
I chose f1-score as a scoring method just because it’s the one I more or less understand. Grid Search will try all combination of the parameters above, perform cross-validations and find the parameters that performs best.
I tried to feed this classifier both X_train with topics modelled with LDA and TF-IDF + Chi2. Both performed similarly, but subjectively it looked like TF-IDF + Chi2 solution generated better predictions. I was pretty much satisfied with the results for the v1 and spent the rest of the time fixing website’s UI.
What are some interesting discoveries you made?
One of the things I learnt is that if you are building a recommendation system and expect your users to come and rate a bunch of things at once so it can work – you are wrong.
I tried the site on my friends and although rating process seemed very easy and fast to me it was pretty hard to make them spend few minutes clicking a “like” button. Although It was alright since my main goal was to practice skills and build a tool for myself I figured if I want to make something bigger out of it I need to figure out how to make rating process simpler.
Another thing I learnt is that in order to be more efficient I need to understand algorithms more. Tweaking parameters is way more fun when you understand what you are doing.
What do you want to do next on the project?
My main problem currently is UI. I want to keep it minimalistic, but I need to figure out how to do the rating process more fun and convenient. Also events browsing could be better.
After this part is done I’m thinking to search for new sources of events: conferences, concerts, etc. Maybe I’ll add a mobile app for that as well.
Learn More
- Project: hapsradar.com
Thanks Artem.
Do you have a machine learning side project?
If you have a side project that uses machine learning and want to be featured like Artem, please contact me.
but we can get data to try code? Is it possible to download code in one file
Wow! I found this idea so cool. It inspired me to develop my own side project! Thanks for sharing this story, Jason!
Glad to hear it.
Hi Jason,
I was looking for some ideas in recommendation system using deep learning/neural networks. I was not able to find one in your blog. It will be great if you could discuss it in your blog.
Thanks for the suggestion. | https://machinelearningmastery.com/project-spotlight-with-artem-yankov/ | CC-MAIN-2019-47 | refinedweb | 1,941 | 72.36 |
bijection value causing JSF Error. Misuse, or misunderstandJames Hays Feb 7, 2007 11:57 AM
I'm getting the following error reported from JSF in certain situations. I have found a solution, but I wanted to dump out my code to the group to see if you guys have seen this issue and help me determine if this is an issue in seam, or if I'm just misusing or not understanding this particular concept.
What I have is a simple form application. This particular piece is a search form. I simply want to submit my form, have seam inject it into my bean component, which is an entity bean, and complete an action. Simple stuff. I'm not doing anything crazy or extreme here. Let me show you the code that does work and then I'll make a simple modification to show what doesn't work.
First, let's look at my Entity Bean.
@Entity @Name("profileRecord") public class ProfileRecord implements Serializable { @Id @GeneratedValue private long id; private String workAuthorizationNumber; private String proposalNumber; }
This is a simple 3 field bean. I've removed the getters/setters from this posting.
My listener looks like this:
@Name("search") @Stateless public class SearchAction implements Search { @Logger private Log log; @In(required=false) private ProfileRecord profileRecord; public String search() { log.info("Running Search"); return null; } }
And, my xhtml.
>
This code works as expected. My issues arise when I change the field name in my action listener. My understanding is that I should be able to modify my action listener to have a differently named variable for profileRecord. I should be able to do that either by writing
@In(required=false) private ProfileRecord searchRecord;
or
@In(value="searchRecord", required=false) private ProfileRecord profileRecord;
And then changing my xhtml to
>
If I make any of those changes and deviate from my original example, I get the error stating.
value could not be converted to the expected type
I'm taking this as a JSF error and not a seam error based on a previous thread replied to by Gavin that stated that this particular error string was coming from JSF. I can't find that thread back at the moment though. Sorry.
Am I misunderstanding the purpose and the abilities of injection here? My understanding is that each injection or outjection (bijection) dumps these components in a type of component cloud that other components can pull from or put to. If I specify a value for a bijection annotation, that name is what is stored as the link to that component. If I don't specify a value, the field name is used as default. Which would lead me to believe that all three of my examples should work the same.
Please, help clarify my understanding here. I've searched the forums and Google and have had limited success in finding anything regarding this issue. I've also looked in the demos and have seen numerous times where the examples do what I'm doing and it has worked as expected, yet mine will not.
Thanks,
James
1. Re: bijection value causing JSF Error. Misuse, or misundersMike Quilleash Feb 7, 2007 4:26 PM (in response to James Hays)
I believe that Seam is not finding your component after the change.
Your component has @Name("profileRecord") so it is always accessed via this name.
The value on the @In is for when your variable name does not match the Seam component name. So using your example I think this would work
@In( value="profileRecord" )
private ProfileRecord searchRecord;
Here you're saying "although my field is called searchRecord, the actual component I want to inject is called profileRecord".
HTH.
2. Re: bijection value causing JSF Error. Misuse, or misundersJames Hays Feb 7, 2007 5:53 PM (in response to James Hays)
Thanks for the reply. I'm still having issues though. I changed my searchAction to contain
@In(value="profileRecord", required=false) private ProfileRecord searchRecord;
if my xhtml contains
<div style="text-align: right;"><label>WA #:<h:inputText</label></div> <div style="text-align: right;"><label>Proposal #:<h:inputText</label></div>
I continue to get the value cannot be converted error. which makes sense to me.
if I leave the xhtml to read
<div style="text-align: right;"><label>WA #:<h:inputText</label></div> <div style="text-align: right;"><label>Proposal #:<h:inputText</label></div>
It seems to work.
If I understand this correctly, there will be no way for me to inject a property named searchRecord of type ProfileRecord into an action from my xhtml. My xhtml will always have to represent the ProfileRecord entity by specifying #{profileRecord.blah}. This just doesn't seem right.
How can I represent two different entity components on the same page in the same scope? One option would be to create them in a factory to create a default object so it is already as a component. That seems noisy though. Along those lines, I would think I could also specify
@In(create=true) private ProfileRecord searchRecord;in my action and then use #{searchRecord} in my xhtml, but that doesn't seem to work either. I still get the value could not be created error.
I'm assuming that I am still missing something critical.
Thanks.
3. Re: bijection value causing JSF Error. Misuse, or misundersPete Muir Feb 8, 2007 5:14 AM (in response to James Hays)
Use @Role on the entity bean.
4. Re: bijection value causing JSF Error. Misuse, or misundersMike Quilleash Feb 8, 2007 5:16 AM (in response to James Hays)
I think you've kinda got it a bit backward. Basically Seam has a big map of components that are available. These components are defined either in components.xml with or more usually with the @Name annotation.
For accessing pure components these are the only names that are available for you to use in EL and for injection via @In. So you can't put #{searchRecord.xxx} in an EL expression because there is no component called searchRecord. Similarly @In looks for components by using the field/method name unless it is specified explicitly by @In( value="" ).
To get your example to work you have to leave the name as profileRecord in the .xhtml or use some method of creating a profileRecord alias. Putting <factory auto- would probably have the effect you are after.
It sounds like you might be trying to achieve something similar to what I am at the moment. I'm trying to create a searchTemplate.xhtml facelet template that wraps all the common layout and action hooks of a standard search screen (parameters, grid, search button, rows returned display, pagination buttons etc). Then I'll use the template in a real view page and just populate the parameter grid and data grid definition. On the model side I want to implement all the common logic and magic in a reusable component and allow overriding with custom logic per page (custom validation, grid population etc).
So I want do have component per search screen but then access the current search screen in my search template with #{searchBean}.
If anyone has any experience doing this I'd be interested to hear about it. | https://developer.jboss.org/thread/134291 | CC-MAIN-2018-13 | refinedweb | 1,203 | 54.93 |
The Data Science Lab
Clustering data is the process of grouping items so that items in a group (cluster) are similar and items in different groups are dissimilar. After data has been clustered, the results can be analyzed to see if any useful patterns emerge. For example, clustered sales data could reveal which items are often purchased together (famously, beer and diapers).
If your data is completely numeric, then the k-means technique is simple and effective. But if your data contains non-numeric data (also called categorical data) then clustering is surprisingly difficult. For example, suppose you have a tiny dataset that contains just five items:
(0) red short heavy
(1) blue medium heavy
(2) green medium heavy
(3) red long light
(4) green medium light
Each item in the dummy dataset has three attributes: color, length, and weight. It's not obvious how to determine the similarity of any two items. In this article I'll show you how to cluster non-numeric, or mixed numeric and non-numeric data, using a clever idea called category utility (CU).
Take a look at the screenshot of a demo program in Figure 1. The demo clusters the five-item example dataset described above. Behind the scenes, the dataset is encoded so that each string value, like "red," is represented by a 0-based integer index. The demo sets the number of clusters to use, m, as 2. After clustering completed, the result was displayed as [0, 1, 1, 0, 1]. This means item (0) is in cluster 0, item (1) is in cluster 1, item (2) is in cluster 1, item (3) is in cluster 0, and item (4) is in cluster 1.
In terms of the raw data, the resulting clustering is:
k=0
(0) red short heavy
(3) red long light
k=1
(1) blue medium heavy
(2) green medium heavy
(4) green medium light
The CU value of this clustering is 0.3733 which, as it turns out, is the best possible CU for this dataset. If you look at the result clustering, you should get an intuitive notion that the clustering makes sense.
This article assumes you have intermediate or better programming skill with a C-family language but doesn't assume you know anything about clustering or category utility.
The demo is coded in Python, the language of choice for machine learning. But you shouldn't have too much trouble refactoring the code to another language if you wish. The entire source code for the demo is presented in this article, and the code is also available in the accompanying download.
Understanding Category Utility
The CU of a given clustering of a dataset is a numeric value that reflects how good the clustering is. Larger values of CU indicate a better clustering. If you have a goodness-of-clustering metric such as CU, then clustering can be accomplished in several ways. For example, in pseudo-code, one way to cluster a dataset ds into m clusters is:
initialize m clusters with one item each
loop each remaining item
compute CU values if item placed in each cluster
assign item to cluster that gives largest CU
end-loop
This is called a greedy agglomerative technique because each decision is based on the current best CU value (greedy) and the clustering is built up one item at a time (agglomerative).
The math definition of CU is shown in Figure 2. The equation looks intimidating but is simpler than it appears. The calculation is best explained by example.
In the equation, C is a clustering, A is an attribute, such as "color," and V is a value, such as "red". The equation has two summation terms. The right-most summation for the demo dataset is calculated as:
red: (2/5)^2 = 0.160
blue (1/5)^2 = 0.040
green: (2/5)^2 = 0.160
short: (1/5)^2 = 0.040
medium: (3/5)^2 = 0.360
long: (1/5)^2 = 0.040
light: (2/5)^2 = 0.160
heavy: (3/5)^2 = 0.360
sum = 1.320
This sum is an indirect representation of how well you could do by guessing values without any clustering. For example, for an unknown item, if you guessed the color is "red," your probability of being correct is 2/5.
The left-hand summation is similar except that you look at each cluster separately. For k = 0:
red: (2/2)^2 = 1.000
blue (0/2)^2 = 0.000
green: (0/2)^2 = 0.000
short: (1/2)^2 = 0.250
medium: (0/2)^2 = 0.000
long: (1/2)^2 = 0.250
light: (1/2)^2 = 0.250
heavy: (1/2)^2 = 0.250
sum = 2.000
And then for k = 1:
red: (0/3)^2 = 0.000
blue (1/3)^2 = 0.111
green: (2/3)^2 = 0.444
short: (0/3)^2 = 0.000
medium: (3/3)^2 = 1.000
long: (0/3)^2 = 0.000
light: (1/3)^2 = 0.111
heavy: (2/3)^2 = 0.444
sum = 2.111
These sums are also indirect measures of how well you could do by guessing values, but this time conditioned with clustering information.
The P(Ck) values mean, "probability of cluster k." Because cluster k = 0 has 2 items and cluster k = 1 has 3 items, the two P(C) values are 2/5 = 0.40 and 3/5 = 0.60 respectively. The P(Ck) values adjust for cluster size. The 1/m term is a scaling factor that takes the number of clusters into account.
The last step when calculating CU is to put the terms together according to the definition:
CU = 1/2 * (0.40 * (2.000 - 1.320) + 0.60 * (2.111 - 1.320))
= 0.3733
A CU value is a measure of how much information you gain by a clustering. Larger values of CU mean you've gained more information, and therefore larger CU values mean better clustering. Very clever! Ideas similar to CU have been around for decades, but to the best of my knowledge, the definition I use was first described in a 1985 research paper by M. Gluck and J. Corter.
The Demo Program
To create the demo program, I used Notepad. The demo code was written using the Anaconda 4.1.1 distribution (Python 3.5.2 and NumPy 1.14.0), but there are no significant dependencies so any Python 3x and NumPy 1x versions should work.
The overall structure of the program is:
# cat_cluster.py
import numpy as np
def cat_utility(ds, clustering, m): . . .
def cluster(ds, m): . . .
def main():
print("Begin clustering demo ")
. . .
print("End demo ")
if __name__ == "__main__":
main()
I removed all normal error checking, and I indented with two spaces instead of the usual four, to save space.
Program-defined function cat_utility() computes the CU of a encoded dataset ds, based on a clustering, with m clusters. Function cluster() performs a greedy agglomerative clustering using the cat_utility() function.
All the control logic is contained in a function main(). The function begins by setting up that source data to be clustered:
raw_data = [['red ', 'short ', 'heavy'],
['blue ', 'medium', 'heavy'],
['green', 'medium', 'heavy'],
['red ', 'long ', 'light'],
['green', 'medium', 'light']]
I decided to use a list instead of a NumPy array-of-arrays style matrix. In a non-demo scenario you'd read raw data into memory from a text file. Although it's not apparent, the demo program assumes your data has been set up so that the first m items are different because these items will act as the first items in each cluster.
Next, the demo sets up encoded data:
enc_data = [[0, 0, 1],
[1, 1, 1],
[2, 1, 1],
[0, 2, 0],
[2, 1, 0]]
In a non-demo scenario you'd want to encode data programmatically, or possibly encode by dropping the raw data into Excel and then doing replace operations on each column.
Next, the raw and encoded data are displayed like so:
print("Raw data: ")
for item in raw_data:
print(item)
print("Encoded data: ")
for item in enc_data:
print(item)
Clustering is performed by these statements:
m = 2
print("Start clustering m = %d " % m)
clustering = cluster(enc_data, m)
print("Done")
print("Result clustering: ")
print(clustering)
Almost all clustering techniques, for both numeric and non-numeric data, require you to specify the number of clusters to use. After clustering, the CU of the result clustering is computed and displayed:
cu = cat_utility(enc_data, clustering, m)
print("CU of clustering %0.4f \n" % cu)
The demo concludes by displaying the raw data in clustered form:
print("Clustered raw data: ")
print("=====")
for k in range(m):
for i in range(len(enc_data)):
if clustering[i] == k:
print(raw_data[i])
print("=====")
Computing Category Utility
The code for function cat_utility() is presented in Listing 1. The logic follows the example calculation by hand I explained previously. Most of the code sets up all the various counts of data items.
def cat_utility(ds, clustering, m):
# category utility of clustering of dataset ds
n = len(ds) # number items
d = len(ds[0]) # number attributes/dimensions
cluster_cts = [0] * m # [0,0]
for ni in range(n): # each item
k = clustering[ni]
cluster_cts[k] += 1
for i in range(m):
if cluster_cts[i] == 0: # cluster no items
return 0.0
unique_vals = [0] * d # [0,0,0]
for i in range(d): # each att/dim
maxi = 0
for ni in range(n): # each item
if ds[ni][i] > maxi: maxi = ds[ni][i]
unique_vals[i] = maxi+1
att_cts = []
for i in range(d): # each att
cts = [0] * unique_vals[i]
for ni in range(n): # each data item
v = ds[ni][i]
cts[v] += 1
att_cts.append(cts)
k_cts = []
for k in range(m): # each cluster
a_cts = []
for i in range(d): # each att
cts = [0] * unique_vals[i]
for ni in range(n): # each data item
if clustering[ni] != k: continue
v = ds[ni][i]
cts[v] += 1
a_cts.append(cts)
k_cts.append(a_cts)
un_sum_sq = 0.0
for i in range(d):
for j in range(len(att_cts[i])):
un_sum_sq += (1.0 * att_cts[i][j] / n) \
* (1.0 * att_cts[i][j] / n)
cond_sum_sq = [0.0] * m
for k in range(m): # each cluster
sum = 0.0
for i in range(d):
for j in range(len(att_cts[i])):
if cluster_cts[k] == 0:
print("FATAL LOGIC ERROR")
sum += (1.0 * k_cts[k][i][j] / cluster_cts[k]) \
* (1.0 * k_cts[k][i][j] / cluster_cts[k])
cond_sum_sq[k] = sum
prob_c = [0.0] * m # [0.0, 0.0]
for k in range(m): # each cluster
prob_c[k] = (1.0 * cluster_cts[k]) / n
left = 1.0 / m
right = 0.0
for k in range(m):
right += prob_c[k] * (cond_sum_sq[k] - un_sum_sq)
cu = left * right
return cu
The function begins by determining the number of items to cluster and the number of attributes in the dataset:
n = len(ds) # number items
d = len(ds[0]) # number attributes/dimensions
Because these values don't change, they can be calculated just once and passed to the function as parameters, at the expense of a more complex interface.
The function computes the number to items assigned to each cluster. If any cluster has no items assigned, the function returns 0.0 which indicates a worst-possible clustering:
for i in range(m):
if cluster_cts[i] == 0: # cluster has no items
return 0.0
An alternative is to return a special error value such as -1.0 or throw an exception. The right-hand unconditional sum of squared probabilities term is calculated like so:
un_sum_sq = 0.0
for i in range(d):
for j in range(len(att_cts[i])):
un_sum_sq += (1.0 * att_cts[i][j] / n) \
* (1.0 * att_cts[i][j] / n)
Here att_cts[i][j] is a list-of-lists where [i] indicates the attribute (0, 1, 2) for (color, length, weight) and [j] indicates the value, for example (0, 1, 2) for (red, blue, green). The indexing is quite tricky but you can think of function cat_utility() as a black box because you won't have to modify the code except in rare scenarios.
Using Category Utility for Clustering
At first thought, you might think that you could repeatedly try random clusterings, keep track of their CU values, and then use the clustering that gave the best CU value. Unfortunately, the number of possible clusterings for all but tiny datasets is unimaginably large. For example, the demo has n = 5 and k = 2 and there are 15 possible clusterings. But for n = 100 and k = 20, there are approximately 20^100 possible clusterings which is about 1.0e+130 which is a number far greater than the estimated number of atoms in the visible universe!
The code for function cluster() is presented in Listing 2. The most important part of the function, and the code you may want to modify, is the initialization:
working_set = [0] * m
for k in range(m):
working_set[k] = list(ds[k])
clustering = list(range(m))
The clustering process starts with a copy of the first m items from the dataset. The initial clustering is [0, 1, . . m-1] so the first items are assigned to different clusters. This means that it's critically important that the dataset be preprocessed in some way so that the first m items are as different as feasible.
def cluster(ds, m):
n = len(ds) # number items to cluster
working_set = [0] * m
for k in range(m):
working_set[k] = list(ds[k])
clustering = list(range(m))
for i in range(m, n):
item_to_cluster = ds[i]
working_set.append(item_to_cluster)
proposed_clusterings = []
for k in range(m): # proposed
copy_of_clustering = list(clustering)
copy_of_clustering.append(k)
proposed_clusterings.append(copy_of_clustering)
proposed_cus = [0.0] * m
for k in range(m):
proposed_cus[k] = \
cat_utility(working_set,
proposed_clusterings[k], m)
best_proposed = np.argmax(proposed_cus)
clustering.append(best_proposed)
return clustering
Instead of preprocessing, an alternative approach is to programmatically randomize, but doing so is surprisingly tricky. Data preprocessing is a key task in most machine learning scenarios.
The loop that performs the clustering agglomeration is:
for i in range(m, n):
item_to_cluster = ds[i]
working_set.append(item_to_cluster)
# consruct k proposed new clusterings
# compute CU of each proposed
# assign item to best option
The demo code processes each of the non-initial data items in order. You should either preprocess the source data so that the items are in a random order, or you can programmatically walk through the dataset in a random order.
The demo code uses a pure greedy strategy. An alternative is to use what's called epsilon-greedy. Instead of always selecting the best alternative (the option that gives the largest CU value), you can select a random item with a small probability. This approach also inserts some randomness into the clustering process.
Wrapping Up
Data clustering is an NP-hard problem. Loosely, this means there is no way to find an optimal clustering without examining every possible clustering. Therefore, the demo code is not guaranteed to find the best clustering.
One way to increase the likelihood of an optimal clustering is to cluster several times with different initial cluster assignments and using different orders when processing the data. You can programmatically keep track of which initialization and order sequence gives the best result (largest CU value) and use that result.
The technique presented in this article can be used to cluster mixed numeric and non-numeric data. The idea is to convert numeric data into non-numeric data by binning. For example, if data items represent people and one of the data attributes is age, you could bin ages 1 through 10 as "very young," ages 11 through 20 as "teen" and so | https://visualstudiomagazine.com/articles/2018/04/01/clustering-non-numeric-data.aspx | CC-MAIN-2020-16 | refinedweb | 2,604 | 64.51 |
0
So I got past my last problem using new[],
but now I seem to have a new one...
I created a char***, var.
The goal was to build each dimension of the array to be different sizes at different times,
based on separate user input...
Here is the code:
#include<iostream> using namespace std; int main(){ char*** var; int ar1,*ar2,x,y,len; char inp[80]; cout<< "var[x]: x = "; cin>> ar1; var=new char**[ar1]; ar2 = new int[ar1]; for(x=0;x<ar1;x++){ cout<< "var["<< x<< "][y]: y = "; cin>> ar2[x]; var[x]=new char*[ar2[x]]; for(y=0;y<ar2[x];y++){ cout<< "var["<< x<< "]["<< y<< "]*: val = "; cin>> inp; len=0; while(inp[len]!='\0'){ len++; } var[x][y]=new char[len + 1]; var[x][y]=inp; } } cout<< "\n\nNew Array:\n"; for(x=0;x<ar1;x++){ for(y=0;y<ar2[x];y++){ cout<< " "<< x<< " , "<< y<< " = "<< var[x][y]<< endl; } } return 0; }
this is what happens:
C:\c>tsiz var[x]: x = [b]2[/b] var[0][y]: y = [b]2[/b] var[0][0]*: val = [b]hello[/b] var[0][1]*: val = [b]somevalue[/b] var[1][y]: y = [b]3[/b] var[1][0]*: val = [b]anothervalue[/b] var[1][1]*: val = [b]moredata[/b] var[1][2]*: val = [b]ofdifferentsizes[/b] New Array: 0 , 0 = ofdifferentsizes 0 , 1 = ofdifferentsizes 1 , 0 = ofdifferentsizes 1 , 1 = ofdifferentsizes 1 , 2 = ofdifferentsizes C:\c>
the first part seems to be working,
but when I set a value to var[x][y], it seems to change all of the values...
under New Array it should expectedly show all of the values of different lengths that I put into the array, and each spot in the array should be just large enough to hold that data.
What am I doing wrong here?
I can't seem to get the values to be set correctly...
any help is appreciated | https://www.daniweb.com/programming/software-development/threads/175386/allocation-issue | CC-MAIN-2017-17 | refinedweb | 324 | 61.9 |
In this article, we will walk through marshalling data to and from XML, using a XML data-binding API. The first question is, why? Why not use SAX or DOM? Personally, when I sit down to work with XML, I get frustrated with the amount of code that you need to write to do simple things.
I came across JDOM and found it to be something I was looking for. DOM is built to be language-agnostic, and hence doesn't feel very "Java-like." JDOM does a great job in being DOM, in a way I would like to use it in Java.
For some applications, I don't want to even think about "parsing" data. It would be so nice if I could have a Java object to work with, and have it saved off as an XML representation to share, or store. This is exactly what XML data-binding can do for us. There are a few frameworks to help us do this, but we will walk through Castor, an open source framework from Exolab. Castor is a data-binding framework, which is a path between Java objects, XML documents, SQL tables, and LDAP directories. Today, we will work with Castor XML, the XML piece of the Castor project
We will discover the different aspects of Castor XML as we develop an Address Book XML document. We will create, read, and modify this XML document via the data-binding framework.
All of the code from this article should work with any JVM supporting the Java 2 platform.
We will walk through the following tasks:
Let's get to work, building a "person" for the Address Book, which will sit between an XML representation and a Java object representation.
First of all, let us generate an XML representation of a person:
<person>
<name>Michael Owen</name>
<address>222 Bazza Lane, Liverpool, MN</address>
<ssn>111-222-3333</ssn>
<home.
Now that we have defined a person in XML, we need to generate a Java object that maps to this definition. To make things easy, we can follow a convention and create get and set methods which match the names of the elements in the XML document. If an element name is name, the corresponding methods in the Java object will be getName() and setName(). When elements have hyphens (such as home-phone), the corresponding method will uppercase the first letter after the hyphen. So, home-phone becomes getHomePhone(). With this in mind, let's look at Person.java:
name
getName()
setName()
home-phone
getHomePhone();
}
// -- used by the data-binding framework
public Person() { }
// --;
}
}
It's pretty simple so far: a simple XML document, a simple JavaBean. Now we will use Castor to read in that XML and return a JavaBean. Here is where we see the power of the framework. We are reading in XML, yet to us, it looks like we are just working with a normal JavaBean.
Here is the code that reads the XML into the JavaBean, and displays information on the person:
person
import org.exolab.castor.xml.*;
import java.io.FileReader;
public class ReadPerson {
public static void main(String args[]) {
try {
Person person = (Person)
Unmarshaller.unmarshal(Person.class,
new FileReader("person.xml"));
System.out.println("Person Attributes");
System.out.println("-----------------");
System.out.println("Name: " + person.getName() );
System.out.println("Address: " + person.getAddress() );
System.out.println("SSN: " + person.getSsn() );
System.out.println("Email: " + person.getEmail() );
System.out.println("Home Phone: " +
person.getHomePhone() );
System.out.println("Work Phone: " +
person.getWorkPhone() );
} catch (Exception e) {
System.out.println( e );
}
}
}
Related Reading
Java and XML, 2nd Ed.
By Brett McLaughlin
Table of Contents
Index
Sample Chapter
Full Description
Read Online -- Safari
The magic is in the Unmarshaller class, and in this example, the static method unmarshal(). You simply give the method the XML document from which to read, and the Java object that will be instantiated. The framework then automatically goes through the XML, uses reflection to look for methods that match the conventions that we mentioned before, and set() the values in the instantiated Java object. Then we can talk to the Person class to call any methods that we wish. Notice that there are no SAX event handlers, and no need to walk the DOM tree. You don't even really know that you are using XML!
Unmarshaller
static method unmarshal()
set()
Person
We have discussed unmarshalling (reading) XML into a Java object. We can also create XML by simply marshalling a Person object out to a file. Ever had to go from a DOM to a file? This is a lot nicer!
Here is the code that will generate a person in the file bob_person.xml:
bob_person.xml
import org.exolab.castor.xml.*;
import java.io.FileWriter;
public class CreatePerson {
public static void main(String args[]) {
try {
// -- create a person to work with
Person person = new Person("Bob Harris",
"123 Foo Street", "222-222-2222",
"bob@harris.org", "(123) 123-1234",
"(123) 123-1234");
// -- marshal the person object out as a <person>
FileWriter file = new FileWriter("bob_person.xml");
Marshaller.marshal(person, file);
file.close();
} catch (Exception e) {
System.out.println( e );
}
}
}
In this source file we instantiate a person passing in initial values. Then we use the Marshaller class to write out this person as an XML document to the bob_person.xml file.
import org.exolab.castor.xml.*;
import java.io.FileWriter;
import java.io.FileReader;
public class ModifyPerson {
public static void main(String args[]) {
try {
// -- read in the person
Person person = (Person)
Unmarshaller.unmarshal(Person.class,
new FileReader("person.xml"));
// -- change the name
person.setName("David Beckham");
// -- marshal the changed person back to disk
FileWriter file = new FileWriter("person.xml");
Marshaller.marshal(person, file);
file.close();
} catch (Exception e) {
System.out.println( e );
}
}
}
Just like that we modify a person, again without having to work with any XML-specific APIs. Now that we have a person, let's move on to setting up an Address Book.
Pages: 1, 2
Next Page
© 2017, O’Reilly Media, Inc.
(707) 827-7019
(800) 889-8969
All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners. | http://www.onjava.com/pub/a/onjava/2001/10/24/xmldatabind.html | CC-MAIN-2017-51 | refinedweb | 1,023 | 57.37 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.