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 |
|---|---|---|---|---|---|
Package::Subroutine - minimalistic import/export and other util methods
Exporting functions from a module is very simple.
; package Recipe::Condiment; use Package::Subroutine ; sub import { export Package::Subroutine _ => qw/required optional var/ }
You can import too.
; import Package::Subroutine 'Various::Types' => qw/string email/
And you can build a relay for your subroutines.
; package SubRelay ; sub import { export Package::Subroutine FooModule => qw/foo fun/ ; export Package::Subroutine BarPackage => qw/bar geld/ ; do_export() }
To export not directly from import the method export_to_caller exists.
; sub do_export { export_to_caller Package::Subroutine(2)->('_' => 'mystuff') }
And you can get and compare version numbers with this module.
; say "SOTA" if version Package::Subroutine 'Xpose::Nature' => 0.99 ; say "SOTA" if version Package::Subroutine 'Protect::Whales' >= 62.0
Sure, installation of a coderef is possible too.
; install Package::Subroutine 'Cold::Inf' => nose => sub { 'hatchie' }
Test if a subroutine is defined.
; (isdefined Package::Subroutine('Cold::Inf' => 'tissue')||sub{})->()
As a helper exists a method which lists all subroutines in a package.
; print "$_\n" for Package::Subroutine->findsubs('Cold::Inf')
import,mixin and export
This module provides two class methods to transfer subs from one namespace into another.
mixin is an alias for import with the addition to import all subroutines from a namespace.
The way this module works is very simple, so it is possible that it does not work for you under all circumstances. Please send a bug report if things go wrong. You are also free to use the long time available and stable alternatives. Anyway I hope this package finds its ecological niche.
A possible use case for this module is an situation where a package decides during load time from where the used functions come from. In such a case Exporter is not a good solution because it is bound to
use and
@ISA what makes things a little bit harder to change.
The inport or export needs at least two arguments. The first is a package name. Second argument is a list of function names.
It is safest, if the package was loaded before you transfer the subs around.
There is a shortcut for the current namespace included because you shouldn't write
export Package::Subroutine __PACKAGE__ => qw/foo bar/
Things go wrong, because you really export from __PACKAGE__:: namespace and this is seldom what you want. Please use the form from synopsis with one underscore, when the current package is the source for the subroutines.
You can change the name of the sub in the target namespace. To do so, you give a array reference with the sourcename and the targetname instead of the plain string name.
package Here; export Package::Subroutine There => [loosy => 'groovy']; # now is There::groovy equal Here::loosy import Package::Subroutine There => [wild => 'wilder']; # and There::wild -> Here::wilder
The purpose of mixin is that your code can distinguish between functions and methods. The convention I suggest is to use
mixin for methods and
import for the rest. Calling mixin without the list of method names imports all subs from the given namespace.
export_to_caller
This method takes the level for the caller function call and returns a code reference which wraps the
exporter function curried with the specified target namespace.
export_to
The right tool to export subroutines into an arbitrary namespace. The argument here is a package name, the target for the export. It works like
export_to_caller and returns a code reference. These should be called with the source namespace and the subroutine names.
exporter
The methods above are using one function. This function is usable with full qualified name or is simply imported.
It takes three arguments, first is the target namespace, second is the source namespace and the third is a list of method names to move around.
version
print Package::Subroutine->version('Package::Subroutine');
This is a evaled wrapper around UNIVERSAL::VERSION so it will not die. You have seen in synopsis how a check against a version number is performed.
install
This mehod installs a code reference as a subroutine. First argument is the namespace, second the name for the subroutine and third is the coderef.
isdefined
This method returns like UNIVERSAL::can a code reference or
undef for a function. As argument is the full quallified function name allowed or a pair of package name and function name.
findsubs
This method returns a list or an array with all defined functions for a given package.
findmethods
Simliar to findsubs but reads all classes in
@ISA plus UNIVERSAL. Class::ISA is used for the task to list all subclasses.
I know this package does not much, what is not possible with core functionality or other CPAN modules. But for me it seems to make some things easier to type and hopefully the code a little bit more readable.
The
methods method has much more features than findmethods.
Thank you, ysth from perlmonks for your suggestions. Without you this would have never arrived in CPAN. :) (He was also not sure if this should happen anyway.)
Perl has a free license, so this module shares it with this programming language.
Copyleft 2006-2012 by Sebastian Knapp <rock@ccls-online.de> | http://search.cpan.org/dist/Package-Subroutine/lib/Package/Subroutine.pm | CC-MAIN-2015-22 | refinedweb | 856 | 64.81 |
How can I make Cantata-Qt to work with EGLFS on Raspberry Pi2?
Hi,
I built Qt to work with EGLFS on my Raspberry Pi2 according to
these instructions.
This works fine, as I can run the various standard Qt example projects.
Because it has a Qt frontend, I selected Cantata as a simple yet powerful
music player, which I built from natively on my Pi2 from
this source version for Qt without KDE.
It builds well, but upon launching, I get the following error:
pi@pi2:~/cantata-master/build$ cantata QXcbConnection: Could not connect to display Aborted
I tried to set the eglfs platform as follows:
export QT_QPA_PLATFORM=eglfs
Then running it again this time gives:
pi@pi2:~$ cantata libEGL warning: DRI3: xcb_connect failed libEGL warning: DRI2: xcb_connect failed libEGL warning: DRI2: xcb_connect failed Could not initialize egl display Aborted
Any one knows what is going on here? Does the above error mean that libEGL is trying to use the XCB library? Why does it need the XCB library, since I don't want to use X11 but EGLFS?
What do I need to change to make Cantata-Qt work with EGLFS then?
Many, many thanks if you know the answer and are willing to share it here!
Try to cantata with eglfs option
cantata -platform eglfs
Hi, tomasz3dk,
Thanks for reacting.
I tried cantata -platform eglfs too, but gives the same error as when using export QT_QPA_PLATFORM=eglfs
Why is it using xcb_connect? That's for XCB, no?
Other suggestions? ^^
Probably you crosscompiled qt with xcb support and not with eglfs. If you want to quick deploy cantata on raspberry you can use image from this site, or build your own image and sdk starting with instructions on this site. Hope it will be useful for you.
@tomasz3dk
I cross-compiled Qt for use with EGLFS according to this wiki. I have tested it to work with all the demo applications in the Qt directory, specifically those requiring openGL, thus Qt is OK.
Not knowing how to setup the cantata build for cross-compiling, I compiled it natively, i.e. directly on the Pi2. The default build settings are for a Qt5 build without KDE, but apparently it requires X11 or XCB which I don't want to use.
The cantata package in the official Debian jessie repository is for use with KDE which I also don't want.
@Diracsbracket said in How can I make Cantata-Qt to work with EGLFS on Raspberry Pi2?:
Not knowing how to setup the cantata build for cross-compiling, I compiled it natively, i.e. directly on the Pi2
I think that maybe this is the reason that cantata requires xcb, check which version of Qt was used when you compiled natively on rpi(crosscompiled and deployed to device or this directly from rootfs).
@tomasz3dk
I uninstalled all Qt packages that were on my Pi, and resync'ed it with the sysroot on the build server and relaunched the build.
Now, I don't get the xcb error messages any longer, but the usual "Unable to query physical screen size...." I also get when I run the Qt examples requiring GL, which work.
cantata -platform=eglfs
Unable to query physical screen size, defaulting to 100 dpi.
To override, set QT_QPA_EGLFS_PHYSICAL_WIDTH and QT_QPA_EGLFS_PHYSICAL_HEIGHT (in millimeters).
Although I don't get any error message this time, I also don't get anything else. Nothing happens, and there is no cantata process in the background either...
So, I got a little bit closer, but still not completely there yet...
I looked into cantata main.cpp file from sources and there are some lines that might cause this
if (Settings::self()->firstRun()) { InitialSettingsWizard wz; if (QDialog::Rejected==wz.exec()) { return 0; } } MainWindow mw; #if defined Q_OS_WIN || defined Q_OS_MAC app.setActivationWindow(&mw); #endif // !defined Q_OS_MAC app.loadFiles(); if (!Settings::self()->startHidden()) { mw.show(); }
Maybe comment out lines about "first run", and "start hidden" and leave just only:
Mainwindow mw; mw.show();
and try to compile again, run and see what's happen.
@
Thanks! I tried what you suggested, but gives same result.
Since my Qt Creator's cross-compiling environment is set up correctly, I also tried cross-compiling it on my build host which also runs Qt Creator by creating a CMake toolchain file and passing it to cmake. The build succeeds, but again, with the same result (as expected of course, since the native build didn't work either).
What a waste of time...
In any case, thanks for your kind suggestions @tomasz3dk
No problem ;). Since you abandoned idea with cantata, maybe you will write your own fronted for mpd? | https://forum.qt.io/topic/72645/how-can-i-make-cantata-qt-to-work-with-eglfs-on-raspberry-pi2 | CC-MAIN-2017-47 | refinedweb | 776 | 62.98 |
Join the community to find out what other Atlassian users are discussing, debating and creating.
In this article I would like to talk about logging information about a ScriptRunner script execution. This information must be used later for identifying the cause of the errors in the script .
I tested all code in Jira 7.8.0 and ScriptRunner 5.3.9.
Suppose, that you have come to a project, which began some time before, or you have already written tens of scripts and now you can see errors in the atlassian-jira.log file.
For example, what can you say about this error?
2018-03-17 11:43:04,891 http-nio-8080-exec-17 ERROR admin 703x1504x1 16n2j3n 127.0.0.1 /secure/WorkflowUIDispatcher.jspa [c.o.s.jira.workflow.ScriptWorkflowFunction] Script function failed on issue: BP-2, actionId: 951, file: <inline script>
java.lang.NullPointerException: Cannot invoke method getKey() on null object
at Script1.run(Script1.groovy:4)
It is an inline script. It was executed on a transition with actionId 951. A getKey() method was executed on some object and the object was null. Ok. Now we have to find the script. Where to find it? We have first to identify, what actionId 951 is and even after we identified it, we still do not know, if the script is in a condition, validator or post function. Moreover we do not know, why the object was null. We have no info on it.
Or let's say we have this error:
2018-03-17 17:07:31,325 http-nio-8080-exec-22 ERROR admin 1027x4968x1 gj4xqt: 0, Size: 0
at java_util_List$get$6.call(Unknown Source)
at ru.matveev.UtilHelper.getIndexOutOfBoundsException(UtilHelper.groovy:13)
at ru.matveev.UtilHelper$getIndexOutOfBoundsException.call(Unknown Source)
at ru.matveev.alexey.main.postfunctions.pfNPE.run(pfNPE.groovy:10)
This one looks better. We know that the error was thrown in the ru.matveev.UtilHelper.getIndexOutOfBoundsException method, which was called by pfNPE.groovy and we even know, where the pfNPE file is in the file system. But we still do not know, where to find the ru.matveev.UtilHelper file. And we still do now know, why the IndexOutOfBOundsException was thrown. Ok. Let's see first the pfNPE.groovy file:
package ru.matveev.alexey.main.postfunctions
import ru.matveev.UtilHelper
List<String> stringList = new ArrayList<>()
UtilHelper.getIndexOutOfBoundsException(stringList)
Looking at the file we still can not understand, where to look for the UtilHelper file.
I think we need to do something with our scripts to make them talk to us and to other people in our project.
1. We need to define the folder structure of our script repository.
I prefer to have its own folder for each ScriptRunner object type. For example, post functions will be in the ru/matveev/alexey/main/postfunctions folder, listeners will be in the ru/matveev/alexey/main/listeners and so on. It will let us categorize our scripts and find required scripts easier (though there are exceptions to this rule. I am planning to talk about it in another article).
2. We need to provide the package for each script, according to its path.
For example, for our pfNPE.groovy we provided:
package ru.matveev.alexey.main.postfunctions
It means that our file is placed in the ru/matveev/alexey/main/postfunctions folder. And it also means, that the UtilHelper.groovy file is placed in the ru/matveev folder.
3. We need to define a Logger in our scripts.
You can find how to define a logger in ScriptRunner here. But I prefer to use the slf4j. I like the syntaxis. You can write to a log like this:
log.debug("var1: {}, var2: {}", var1, var2)
The logger will let us later to turn on/off debugging info from our scripts. For a script in a file system we can use this.getClass() to define the logger. For example, for the pfNPE.groovy file the logger would be like this:
def log = LoggerFactory.getLogger(this.getClass())
For an inline script, first of all, I always fill the Note field:
Then when I set a logger, I define, what the script is and where it would be placed, if the script was saved in the file system. In the screenshot above, the inline script is a listener, that is why the logger would be like this (I added ".inline" to the end, so that I know, that the script is inline):
def log = LoggerFactory.getLogger("ru.matveev.alexey.main.listeners.NPElistener.inline")
4. At the beginning of the script set a log, that the script started, and at the end of the script set a log, that the script has ended.
It is not a must for a script in the file system, but it is a must for an inline script. For an inline script, if it is a condition, validator or post function script, I also provide the workflow name, initial status, transition name and the Note. For example, like this:
log.info("MyWorkflow:IN Progress:In Progress:OutOfIndexBoundsPF in")
....
log.info("MyWorkflow:IN Progress:In Progress:OutOfIndexBoundsPF out")
Here is an example of an inline script:
import org.slf4j.LoggerFactory;
def log = LoggerFactory.getLogger("ru.matveev.alexey.main.postfunctions.OutOfIndexBoundsPF.inline")
log.info("MyWorkflow:IN Progress:In Progress:OutOfIndexBoundsPF in")
List<String> stringList = new ArrayList<>()
def key = stringList.get(0)
log.info("MyWorkflow:IN Progress:In Progress:OutOfIndexBoundsPF out")
I need to turn on the INFO level for my ru.matveev.alexey.main.postfunctions.OutOfIndexBoundsPF.inline logger in System -> Logging and Profiling. Then my logs will look like this:
2018-03-17 15:32:36,888 http-nio-8080-exec-9 INFO admin 932x3626x1 sxyxed 127.0.0.1 /secure/WorkflowUIDispatcher.jspa [r.m.a.m.postfunctions.OutOfIndexBoundsPF.inline] MyWorkflow:IN Progress:In Progress:OutOfIndexBoundsPF in
2018-03-17 15:32:36,895 http-nio-8080-exec-9 ERROR admin 932x3626x1 sxyxed 127.0.0.1 /secure/WorkflowUIDispatcher.jspa [c.o.s.jira.workflow.ScriptWorkflowFunction] *************************************************************************************
2018-03-17 15:32:36,896 http-nio-8080-exec-9 ERROR admin 932x3626x1 sxyxed 127.0.0.1 /secure/WorkflowUIDispatcher.jspa [c.o.s.jira.workflow.ScriptWorkflowFunction] Script function failed on issue: BP-2, actionId: 951, file: <inline script>
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java_util_List$get$6.call(Unknown Source)
at Script17.run(Script17.groovy:5)
Now I know that the error was in MyWorkflow:IN Progress:In Progress:OutOfIndexBoundsPF, because I entered the script but I did not leave it.
I usually put the in and out messages for scripts in the file system as well. I provide only the script name. It would be like this:
log.info("pfNPE in")
...
log.info("pfNPE out")
5. Provide debug messages with the values of variables.
Let's see the contents of the UtilHelper.groovy file:
package ru.matveev.alexey.main.helpers
import java.util.Random
public class UtilHelper {
public static String getRandomElement(List<String> value) {
Random rand = new Random()
int max = 5
def index = rand.nextInt(max);
return value.get(index)
}
}
I think it is a good idea to log all input variables to a method and values of all variables in the method. That is why let's rewrite our file like this:
package ru.matveev.alexey.main.helpers
import java.util.Random
import org.slf4j.LoggerFactory;
public class UtilHelper {
private static final LOG = LoggerFactory.getLogger("ru.matveev.alexey.main.helpers.UtilHelper")
public static String getRandomElement(List<String> value) {
LOG.debug("getRandomElement in. value: {}", value)
Random rand = new Random()
int max = 5
def index = rand.nextInt(max);
LOG.debug("index: {}", index)
return value.get(index)
}
}
We need to set the DEBUG level for the ru.matveev.alexey.main.helpers.UtilHelper in the System -> Logging and Profiling. After that we will have the following logs:
2018-03-17 18:54:00,664 http-nio-8080-exec-2 INFO admin 1134x121x1 pr8c2n 127.0.0.1 /secure/WorkflowUIDispatcher.jspa [r.m.a.main.postfunctions.pfNPE] pfNPE in
2018-03-17 18:54:00,687 http-nio-8080-exec-2 DEBUG admin 1134x121x1 pr8c2n 127.0.0.1 /secure/WorkflowUIDispatcher.jspa [r.m.a.main.helpers.UtilHelper] getRandomElement in. value: [0, 1, 2]
2018-03-17 18:54:00,687 http-nio-8080-exec-2 DEBUG admin 1134x121x1 pr8c2n 127.0.0.1 /secure/WorkflowUIDispatcher.jspa [r.m.a.main.helpers.UtilHelper] index: 4
2018-03-17 18:54:00,693 http-nio-8080-exec-2 ERROR admin 1134x121x1 pr8c2n 127.0.0.1 /secure/WorkflowUIDispatcher.jspa [c.o.s.jira.workflow.ScriptWorkflowFunction] *************************************************************************************
2018-03-17 18:54:00,694 http-nio-8080-exec-2 ERROR admin 1134x121x1 pr8c2n: 4, Size: 3
at java_util_List$get$1.call(Unknown Source)
at ru.matveev.alexey.main.helpers.UtilHelper.getRandomElement(UtilHelper.groovy:25)
at ru.matveev.alexey.main.helpers.UtilHelper$getRandomElement.call(Unknown Source)
at ru.matveev.alexey.main.postfunctions.pfNPE.run(pfNPE.groovy:12)
Now we can see that we entered the pfNPE file. Then we entered the getRandomElement method in UtilHelper. We can see the value of the value variable. We can see the value of the index variable and now we understand, why we have the error. We also know, where to find all necessary scripts.
I would like to add, that there are two types of errors: errors, which are visible in the logs (all kinds of exceptions) and errors, which are not visible. The second type of errors is more tricky, because the user just tells you, that the flow of your program goes wrong. For example, if a user is assigned to an issue, the user must receive a email. But the user does not receive it. You look in the logs and you can see no errors. And now you have to define, what goes wrong. In this case you turn on debugging and try to see, what is wrong. If you structured your folders and defined loggers, then you can turn on the debug mode for one script or for a category of your scripts or for all your scripts. For all your scripts you would just set the DEBUG log level for the ru.matveev.alexey.main package. While you are trying to find what went wrong, the logging of variable values will not be enough. You would want to know in what conditions you entered and what blocks of the program were executed. You can, of course, put the log statements after each program flow actions, but in the end your code would become unreadable. That is why, you should put the log statements wisely. Do not forget that the readability of your code is as important as logging.
Alexey Matveev _Appfire_Community Leader
Senior Product Architect
Appfire
Moscow
1,562 | https://community.atlassian.com/t5/Jira-articles/Logging-in-ScriptRunner/ba-p/752758 | CC-MAIN-2022-05 | refinedweb | 1,791 | 60.11 |
//**************************************
// Name: Save Embedded Resource to File
// Description:To save an Embedded Resource and save to file. This will take any embedded resource and save it to any filename you want.
// By: Victor Boba (from psc cd)
//**************************************
' Notes:
' The file that you add to the project has to have the Build Action
' property changed to "Embedded Resource" for this to work. This will add the file
' to the project as a resource and not a compiled item.
'
Dim ResStream As System.IO.Stream
' This is the name of your applications namespace followed by the name of the file that's embedded.
' So if your namespace is "MyProject" and the name of the file is "BlankDatabase.mdb" then
' the value for the sResPath would be "MyProject.BlankDatabase.mdb".
Dim sResPath As String = "AnimalControl.db.mdb"
Dim NewFilePathName As String = sPath
Dim numBytesRead As Integer = 0
' Get the Embedded Resource
ResStream = System.Reflection.Assembly.GetExecutingAssembly.GetManifestResourceStream(sResPath)
Dim numBytesToRead As Integer = CInt(ResStream.Length)
Dim bytes(ResStream.Length) As Byte
While numBytesToRead + 1 > 0
Dim n As Integer = ResStream.Read(bytes, numBytesRead, numBytesToRead)
' The end of the file has been reached.
If n = 0 Then
Exit While
End If
numBytesRead += n
numBytesToRead -= n
End While
' Save the resource to file
Dim fs As New FileStream(NewFilePathName, FileMode.Create)
fs.Write(bytes, 0, bytes.Length)
fs. | http://planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=2268&lngWId=10 | CC-MAIN-2018-05 | refinedweb | 222 | 67.45 |
How do I stop and reverse on same bar?
I'm looking for the approach to close a trade and reverse direction. My first attempt to do this was in
next():but it seems that a trade execution breaks us from the next. If tried the following in the strategy:
if position: if condition: self.close() if not position: if condition: self.buy() elif condition: self.sell()
From what I can see, we seem to not revisit the
if not position:until the next bar. What is the appropriate way to handle this?
- backtrader administrators
The platform cannot forbid the execution of the 2nd condition.
The problem is that the position is not zero as revealed by the 1st test. The orders will be executed in the broker once you are out of
How do I set the order size in
Strategy next()?
I have
position.sizeof current position and I know I can call
self.buy(size=int)or
self.sell(size=int). Is there a way I can call the sizer from this point in the strategy? The goal being to increase the size enough to trigger a position reversal.
Appears I have
self.getsizing()here if I understand correctly what it is doing. I'm looking for portfolio value after closing the currently open trade which should include some unrealized profit or loss.
This 'next' reverse position. It buys/cover short on Mondays and sell/go short on Wednesdays. Is it what you are looking for?
def next(self): pos_size = self.broker.getvalue() // self.data.close[0] if self.data.datetime.date().weekday() == 0: # BUY condition if self.position: self.close() self.order = self.buy(size=pos_size) if self.data.datetime.date().weekday() == 2: # SELL condition if self.position: self.close() self.order = self.sell(size=pos_size)
Also it buys/sells on close of the day.
I think what I have failed to mention is that I want this to happen on the same bar.
I believe I can accomplish that by either buying or selling in the opposite direction of the current position, but am trying to apply the sizer logic to calculate the new order size. ie
self.position.size + sizer()
In your example above, doesn't
self.broker.getvalue()return a monetary value of the account? It was my understanding that
sizeparameter passed to the
self.buy()or
self.sell()was expecting an integer number of shares/contracts? Not true?
@RandyT This script buys & sells on the same bar. Here is the output (one buy and one short) from modified script with the log function:
Starting Portfolio Value: 100000.00 2016-06-01 Open Pos, 0; Price 210.2700; Lev Val 100000.0000 Val 100000.00; Cash 100000.00, 2016-06-01 ORDER CREATED, Price 210.27; SELL, 475 2016-06-02 Open Pos, -475; Price 210.9100; Lev Val 99696.0000 Val 99696.00; Cash 199878.25, 2016-06-03 Open Pos, -475; Price 210.2800; Lev Val 99995.2524 Val 99995.25; Cash 199878.25, 2016-06-06 Open Pos, -475; Price 211.3500; Lev Val 99486.9990 Val 99487.00; Cash 199878.25, 2016-06-06 LONG CLOSED, Price 211.35; SOLD, -475 2016-06-06 ORDER CREATED, Price 211.35; BUY, 470 2016-06-07 OPERATION PROFIT, GROSS -513.00, NET -513.00 2016-06-07 Open Pos, 470; Price 211.6800; Lev Val 99642.0929 Val 99642.09; Cash 152.50, 2016-06-08 Open Pos, 470; Price 212.3700; Lev Val 99966.3939 Val 99966.39; Cash 152.50, 2016-06-08 SHORT CLOSED, Price 212.37; BOUGHT, 470 2016-06-08 ORDER CREATED, Price 212.37; SELL, 470 2016-06-09 OPERATION PROFIT, GROSS 479.39, NET 479.39
Trade report comes bar later , but it is a bt thing.
Formula for position size:
pos_size = self.broker.getvalue() // self.data.close[0]
It will be integer number of shares based on current funds and stock price. Somehow forum recognizes
//as a comment but it is not.
I'll give this another try to see if I can replicate your behavior. From what I saw,
trading on daily timeframe, I saw the trade for the reversal getting executed on the next day after the exit of the previous position.
Also, my sizer is more complicated than just number of shares per equity. I have created a VaR sizer which returns an integer number of contracts to purchase based on VaR of current market. So I really need to access the sizer() value at this point to determine order size..
- backtrader administrators
As mentioned by @ab_trader orders are executed on the same bar if you set
coc=Truein the broker. If not the bar is considered closed and order execution is deferred until the next bar. Two orders issued on the same bar with
Marketexecution policy should be executed also on the same bar (be it the next or the current bar)
The system does a check of submitted orders before accepting them. To avoid for example having 2 consecutive orders which would go over the actual cash reserves on the same bar. If tries to take into account that if a long position is closed cash will be re-injected into the system to let you operate with another
buy.
Deactivation of the check can be achieved in the broker with
checksubmit=False
Sizers are called internally by
buyand
sell(
closeuses the actual existing position) but a
Sizercan be subclassed to provide complex functionality.
In that documentation page there are examples of how the modification of
_getsizingachieves policies, like for example reversing a position or keeping it
longonly. | https://community.backtrader.com/topic/24/how-do-i-stop-and-reverse-on-same-bar | CC-MAIN-2017-51 | refinedweb | 940 | 70.09 |
This article is really a precursor to cool things you can do with calculus such as the persuit curve which is used in air-to-air missiles, and rocket launch equations.
Let's revisit some calculus topics you most likely haven't touched on in a while and use Python to take a refresher, and go over common derivatives and rules used.
This is intended to be a calculus tutorial, but you won't use an online calculator such as Wolfram-Alpha, which requires an API. Also useful if you ever want to write your own code, or just do painless calculations. This is also a great way to check that your calculations done by hand are accurate. I will go over through differentiation rules in the easiest way possible, providing examples which you can execute using python.
The areas covered in this how to install SymPy, and go through the following:
I will use Lagrange's derivative notation (such as 𝑓(𝑥), 𝑓′(𝑥), and so on) to express formulae as it is the easiest notation to understand whilst you code along with python. Whilst it is more common to use the Leibniz notation, (d/dx), it didn't feel natural when running differential equations in Python.
This post will use SymPy, which is a Python library. It is also possible to use the SciPy library, but SymPy prints the output in an easy to read way, and is more useful in getting a grasp of differentiation and integration.
To install it, open up the terminal and run the following command:
pip install sympy
I would strongly recommend writing the python code in a new Jupyter Notebook, which comes with the Anaconda distribution.
I will go through some differentiation rules first, as a quick refresher to some Calculus topics that you probably have forgotten a long time ago.
The power rule states:
Which is self-explanatory if you have ever taken a calculus class. So let's take a simple example, and go through the steps by hand;
This is a good, easy example to test out with the SymPy library. To implement this in python, first import the library, and declare a variable that you will use within your functions. The snippet below shows how to declare a single variable function:
import sympy as sp x = sp.Symbol('x')
The final step is to get the derivation by running the code below:
sp.diff(x**3)
Which outputs:
You will notice that the output equation comes out in a nice print format. If you want to get the second order differential, f''(x), you can simply include x twice within the
command:command:
diff
sp.diff(x**3,x,x)
Where 6x is the second order differential, or put in a hand-written way:
Let's go through a quick example by hand:
So running this in python will give you the following:
sp.diff(sp.sin(x)*(2*x**2+2))
The quotient rule helps allows us to efficiently find the derivative of one function divided by another function, such that:
So, let's go through a quick example by hand:
and this is what it looks like when we do this in Python:
sp.diff((sp.sin(x))/x)
Try this by hand, and then run it in python:
The quotient rule is very similar to the product rule, except with changing the plus to a minus, and the extra step of dividing by the g(x)^2 step.
As mentioned earlier, I have chosen to use Langrangian notation to go through these rules. The chain rule for some reason gets more over-complicated than it needs to be. The formula is shown below:
So let's go through an example by hand:
The inner function, g(𝑥) is 𝑥^2 +1 which when differentiated is 2𝑥. The outer function is f(𝑥) is (stuff)^7, which when differentiated turns to 7*(stuff)^6.
So following this logic, and here is the hand calculation:
Which is pretty straghtforward when using the chain rule formula. This is what this looks like when run in python:
sp.diff((x**2+1)**7)
And that is pretty much it. Try to calculate by hand the following examples if you want good practice:
and,
For more indepth explanation of the chain rule, check Aaron Schlegel's post on the Chain Rule.
and, using the chain rule, while giving e an exponent of g(x),
Let's go through a quick example:
and the code for that will look like:
sp.diff(sp.exp(3*x))
This covers all the differentiaiton rules you would have memorised in your calculus class. With all that, let's look at something called Partial Derivatives:
A partial differential equation (PDE) differs from the Ordinary Differential equations we have looked at so far, as PDEs contain multivariable functions. The difference being is that you take derivatives of one variable at a time.
Let's start with a two variable function and find their partial derivatives:
Now how do I do this in Python you might ask? The first step is to declare your variables 𝑥 and 𝑦 like so:
x, y = sp.symbols('x y') f = x**4 * y
In the above, I have assigned the function as a variable, so as not to rewrite this variable every time I take a derivative.
Taking the partial derivative in respect to x:
sp.diff(f, x)
And taking the partial derivative in respect to y:
sp.diff(f, y)
You can also take the derivatives with respect to many variables one after the other within the same line of code:
sp.diff(f,x,y)
x, y, z = sp.symbols('x y z') f = x**3 * y * z**2
The remaining part now is as before:
sp.diff(f, x)
sp.diff(f, y)
sp.diff(f, z)
And that's pretty much it on the derivatives side. However, these aren't actual functions useful in Python code, this is more of a homework thing.
What is the point of calculating differential equations in my Python code if I can't plug in the numbers? SymPy gives us a function to do just that!
This very handy function is called
, where you substitute numbers where you have placed symbols., where you substitute numbers where you have placed symbols.
lambdify
Let's do a quick example:
f = 2*x**3+4*x f_prime = sp.diff(f) f_prime
So I have set up f_prime, but I want to substitute 𝑥 with the number 2. We now use our handy little function here:
f_prime = sp.lambdify(x, f_prime) f_prime(2)
>> 28
And there you have it. Let's do another example with multiple symbolic variables
f = x**3 * y * z**2 F = sp.lambdify([x,y,z], f) F(1,2,3)
>> 18
And with this, you now have a python library for finding derivatives and turning them into functions.
Have fun!
Integrals deserve an article of their own, and will be the part 2, followed by Series Expansion and SymPy plots.
After that, I will only do articles on the applications of calculus such as the persuit curve, rocket launch equations, orbital mechanics, or anything useful for Kerbal Space Program's kOS mod, which allows you to automate specific tasks. This is probably the easiest way to immediately apply calculus functions with Python.
These are the the websites which I have heavily referenced to make this revision cheat sheet. I would recommend visiting these sites, especially Taking Derivatives In Python which goes through the same rules.
Create your free account to unlock your custom reading experience. | https://hackernoon.com/how-to-do-calculus-with-python-derivatives-cheat-sheet-part-1-zfv3uno | CC-MAIN-2021-17 | refinedweb | 1,277 | 60.85 |
06 December 2011 08:31 [Source: ICIS news](recasts, adds details throughout) SINGAPORE (ICIS)--A power failure halted production at some petrochemical facilities at ?xml:namespace>
KP Chemical, however, continues to run its aromatics facilities at the site that can produce 775,000 tonne/year of paraxylene (PX) and 230,000 tonnes/year of orthoxylene (OX), said another company source.
But there are concerns about a possible shortage of feedstock that might arise with the shutdown of SK Energy’s crackers.
No word yet from SK Energy about any reduction on contract volumes, they said.
Among other plants that stopped operations because of the power outage include Samsung BP’s 600,000 tonne/year acetic acid plant and Asia Acetyls Co’s (Asacco) 210,000 tonne/year vinyl acetate monomer (VAM) plant.
“Now we are checking the mechanical processes,” said a company source, adding that restart of both plants may take one or two days or possibly longer.
“The downstream units such as purified terephthalic acid (PTA) are also shut therefore there’s no big impact on the acetic acid market yet,” said the source.
Samsung BP Chemicals is a joint venture between Samsung and BP Chemicals, while Asacco is a joint venture between BP, Dow and Samsung.
Samsung also had to shut down its 200,000 tonnes/year PTA No 1 and 450,000 tonnes/year No 2 PTA unit as a result of the power outage, a company source said.
The company expects the outage to last no longer than two days, the source added.
Another PTA producer Hyosung Petrochemical shut its 420,000 tonnes/plant unit in
“We are in the process of restarting,” the source added.
Additional reporting by Samuel Wong, Helen Lee, Felicia Loo, Quintella Koh, Chow Bee Lin, Mahua Chakravarty, Bohan Loh and Becky | http://www.icis.com/Articles/2011/12/06/9514195/power-outage-hits-south-koreas-ulsan-petrochemical-hub.html | CC-MAIN-2015-14 | refinedweb | 300 | 56.39 |
It’s obvious that inexperienced software developer will make more mistakes, but even the best engineers make them. Mistakes in code reviewing happen all the time! When we push our change (for example by creating pull request) and reviewer requests changes, it usually means that we’d failed in self-reviewing. Or when our code had been approved by reviewer and after merging it, it caused some bug, it means that both reviewer and we’d failed in reviewing. But really, hard to blame anyone, it just should be a lesson for both. In this post I want to write about some lessons I’ve learnt.
Mistakes in code review
From my experience it seems that mistakes in code review usually come not from mistakes from reading changed code, but from not reading code that wasn’t changed. By this I mean that it’s important to check the context of reviewed code and other relevant places. For example the author forgot to change the name of a method in all necessary places - commit looks good, but the code doesn’t work.
Also viewing the bigger picture is important - maybe achieving the same purpose could be done in an easier way? Sometimes it’s good to take a time and think how you could design the solution by yourself. Of course, your design can be all wrong, but in that case you will learn more. And of course, you don’t have the same amount of time as an author to think about all details.
When reviewing it’s also hard to come up with code which should be written but it wasn’t, for example not all exceptions where caught or someone forgot to commit a new file with whole functionality (yep, this happens!).
Performance when querying database
One of standard mistakes is getting records from database or other resource, using loop instead of having one query to get all resources, for example:
users = [] for user_id in user_ids_list: users.append(User.objects.get(id=user_id))
Here for all
ids in
user_ids_list we perform a query like this:
SELECT * FROM USERS WHERE ID = ?;
So we have to access database many times (length of
user_ids_list actually) to get all users we want.
It could be fixed like this:
users = User.objects.filter(id__in=user_ids_list)
(Actually in Python it will return a QuerySet instead of a list, but here it’s not relevant).
This is an example of using
filter method in Django ORM, but I’m sure that every decent ORM
contains a similar method. This will run a query like this:
SELECT * FROM USERS WHERE ID IN ?;
So it will access database one time and get all records we wanted.
Learn your ORM - it should contain methods or functions to perform more complicated queries instead
of relying on loops. You should know how to perform filtering, grouping and getting distinct
records from database with corresponding functions. If you don’t use any ORM be
sure to use words like
IN,
GROUP BY,
DISTINCT in your queries.
Reviewing refactored code when rename was performed
Reviewing code which was refactored is sometimes quite hard.
Usually refactor option in IDEs perform well when changing name of method or class.
When using static typed or compiled language, it’s usually quite obvious when
renaming wasn’t performed well, but still when code reviewing you
should pay attention. There can be some situations where
method or class name is put into non-source file (like some
xml or
config), for example
in performing dependency injections in
Java’s Spring framework. So it’s good practice to check if after change,
there is no old name in code - just use
grep or a search option in your IDE.
Code reviewing when name was changed becomes harder when two classes, methods or variables
switched names. Then
grep will not be so helpful and you have carefully go through diff.
When using frameworks not all code has to be in source files.
Tests which test nothing
The tests are as important as the code, so you also should check them carefully. Each test name should indicate what is tested, so if you are unsure, maybe it’s time to ask an author. Also there should be at least one assertion in each test.
Sometimes everything looks good, like here:
def test_get_names_every_user_has_name(self): users = self.service.get_users() for user in users: self.assertIsNotNone(user.name)
It happens that this test tests exactly nothing. What will happen if
self.service.get_users() returns
an empty collection? No assertion will be checked, so what’s the point of this test?
There is an easy fix:
def test_get_names_every_user_has_name(self): users = self.service.get_users() self.assertEquals(len(users), 10) # or self.assertNotNone(users) for user in users: self.assertIsNotNone(user.name)
When doing assertions in a loop it’s important to check if looped collections has an expected size.
Summing up
Code review is an art and it takes time to become experienced enough to become proficient in it. There are plenty details, corner cases, things which should be well thought out. On the other side there is time - we don’t want to spend more time than the author… The most beautiful thing about checking ones code is whenever you’re experienced or not, you can still learn many things from reading code. | https://vevurka.github.io/dsp17/quality/code_review_mistakes/ | CC-MAIN-2018-39 | refinedweb | 890 | 71.04 |
Hey guys I have just started c++ yesterday and I am now on Switch case and functions.
I made this little program:
Code:#include <iostream> using namespace std; void playgame(); void loadgame(); void playmultiplayer(); void exit(); int main() { int answer; cout << "1. Play A New Game\n" << "2. Load A Saved Game\n" << "3. Play Multiplayer\n" << "4. Exit\n"; cin >> answer; switch (answer) { case 1: playgame(); break; case 2: loadgame(); break; case 3: playmultiplayer(); break; case 4: exit(); break; default: cout << "Error Invalid Choice Closing!\n"; break; } cin.get(); } void playgame() { cout << "We Are Starting A New Game\n"; } void loadgame() { cout << "Loading A Saved Game\n"; } void playmultiplayer() { cout << "Searching For A Opened Server\n"; } void exit() { cout << "What A Quiter! Come On Be A Man!\n"; }
When I run it, it works perfectly fine it displays everything. But when I go to enter a option like say I hit a 1 to "play a game" the program exits really fast without printing anything to the screen. Just wanted to know how I could fix this thank you guys.
I got this code from the tutorials "Switch case" but wanted to see if I could get it to work with functions to see how much I knew so far. OH Excellent Tutorials glad I found this site.
--Mustang1968kid 17yr. | https://cboard.cprogramming.com/cplusplus-programming/72486-need-help-functions.html | CC-MAIN-2017-13 | refinedweb | 221 | 81.63 |
Arrays
From HaskellWiki array and don't modify the original one. This makes possible to use Arrays in pure functional code along with lists. "Boxed" means that array elements are just ordinary Haskell (lazy) values, which are evaluated on demand, and can even contain bottom (undefined) value. You can learn how to use these arrays at and I recommend that you read this before proceeding to rest of this page
Nowadays three Haskell compilers - GHC, Hugs and NHC - ship with the same set of Hierarchical Libraries, and these libraries contain a new implementation of arrays which is backward compatible with the Haskell'98 one, but which has far more features. Suffice.
1 Quick reference) it again. The type declaration in the second line is necessary because our little program doesn't provide enough context to allow the compiler to determine the concrete type of `arr`.
4 Mutable arrays in ST monad (module Data.Array.ST)
In the same way that IORef has its more general cousin STRef, IOArray has a more general version STArray (and similarly, IOUArray is parodied by STUArray). These array types allow one to work with mutable arrays in the ST monad:
import Control.Monad.ST import Data.Array.ST buildPair = do arr <- newArray (1,10) 127 :: ST s (STArray s Int Int) a <- readArray arr 1 writeArray arr 1 216.
5 DiffArray (module Data.Array.Diff) combines the best of both worlds - it supports interface of IArray and therefore can be used in a pure functional way, but internally uses the efficient update of MArrays.
How does this trick work? DiffArray has a pure external interface, but internally.
8 The Haskell Array Preprocessor (STPP)
9 :-) | http://www.haskell.org/haskellwiki/index.php?title=Arrays&oldid=3026 | CC-MAIN-2014-15 | refinedweb | 279 | 54.52 |
Implementing the Basic Folder Object Interfaces
The procedure for implementing a namespace extension is similar to that for any other in-process Component Object Model (COM) object. All extensions must support three primary interfaces that provide Windows Explorer with the basic information needed to display the extension's folders in the tree view. However, to make full use of the capabilities of Windows Explorer, your extension must also expose one or more optional interfaces that support more sophisticated features, such as shortcut menus or drag-and-drop, and provide a folder view.
This document discusses how to implement the primary and optional interfaces that Windows Explorer calls for information about the contents of your extension. For a discussion of how to implement a folder view and how to customize Windows Explorer, see Implementing a Folder View.
- Basic Implementation and Registration
- Handling PIDLs
- Implementing the Primary Interfaces
- Implementing the Optional Interfaces
- Working With the Default Shell Folder View Implementation
Basic Implementation and Registration
As an in-process COM server, your DLL must expose several standard functions and interfaces:
These functions and interfaces are implemented in the same way as they are for most other COM objects. For details, see the COM documentation.
Registering an Extension
As with all COM objects, you must create a class identifier (CLSID) GUID for your extension. Register the object by creating a subkey of HKEY_CLASSES_ROOT\CLSID named for the CLSID of your extension. The DLL should be registered as an in-process server and should specify the apartment threading model. You can customize the behavior of an extension's root folder by adding a variety of subkeys and values to the extension's CLSID key.
Several of these values apply only to extensions with virtual junction points. These values do not apply to extensions whose junction points are file system folders. For further discussion, see Specifying a Namespace Extension's Location. To modify the behavior of an extension with a virtual junction point, add one or more of the following values to the extension's CLSID key:
- WantsFORPARSING. The parsing name for an extension with a virtual junction point will normally have the form ::{GUID}. Extensions of this type normally contain virtual items. However, some extensions, such as My Documents, actually correspond to file system folders, even though they have virtual junction points. If your extension represents file system objects in this way, you can set the WantsFORPARSING value. Windows Explorer will then request your root folder's parsing name by calling the folder object's IShellFolder::GetDisplayNameOf method with uFlags set to SHGDN_FORPARSING and pidl set to a single empty pointer to an item identifier list (PIDL). An empty PIDL contains only a terminator. Your method should then return the root folder's ::{GUID} parsing name.
- HideFolderVerbs. The verbs registered under HKEY_CLASSES_ROOT\Folder normally are associated with all extensions. They appear on the extension's shortcut menu and can be invoked by ShellExecute. To prevent any of these verbs from being associated with your extension, set the HideFolderVerbs value.
- HideAsDelete. If a user attempts to delete your extension, Windows Explorer will instead hide the extension.
- HideAsDeletePerUser. This value has the same effect as HideAsDelete but on a per-user basis. The extension is hidden only for those users who have attempted to delete it. The extension is visible to all other users.
- QueryForOverlay. Set this value to indicate that the root folder's icon can have an icon overlay. The folder object must support the IShellIconOverlay interface. Before Windows Explorer displays the root folder's icon, it will request an overlay icon by calling one of the two IShellIconOverlay methods with pidlItem set to an empty PIDL.
The remaining values and subkeys apply to all extensions:
- To specify the display name of the extension's junction point folder, set the default value of the extension's CLSID subkey to an appropriate string.
- When the cursor hovers over a folder, an infotip is typically displayed that describes the contents of the folder. To provide an infotip for your extension's root folder, create an InfoTip REG_SZ value for the extension's CLSID key, and set it to an appropriate string.
- To specify a custom icon for your extension's root folder, create a subkey of the extension's CLSID subkey named DefaultIcon. Set the default value of DefaultIcon to a REG_SZ value containing the name of the file that contains the icon, followed by a comma, followed by a minus sign, followed by the index of the icon in that file.
- By default, the shortcut menu of your extension's root folder will contain the items defined under HKEY_CLASSES_ROOT\Folder. The Delete, Rename, and Properties items are added if you have set the appropriate SFGAO_XXX flags. You can add other items to the root folder's shortcut menu, or override existing items, much as you would for a file type. Create a Shell subkey under the extension's CLSID key, and define commands as discussed in Extending Shortcut Menus.
- If you need a more flexible way to handle the root folder's shortcut menu, you can implement a shortcut menu handler. To register the shortcut menu handler, create a ShellEx key under the extension's CLSID key. Register the handler's CLSID as you would for a conventional Creating Shell Extension Handlers.
- To add a page to the root folder's Properties property sheet, give the folder the SFGAO_HASPROPSHEET attribute and implement a property sheet handler. To register the property sheet handler, create a ShellEx key under the extension's CLSID key. Register the handler's CLSID as you would for a conventional Creating Shell Extension Handlers.
- To specify the attributes of the root folder, add a ShellFolder subkey to the extension's CLSID subkey. Create an Attributes value, and set it to the appropriate combination of SFGAO_XXX flags.
The following table lists some commonly used attributes for root folders.
The following example shows the CLSID registry entry for an extension with a display name of MyExtension. The extension has a custom icon that is contained in the extension's DLL with an index of 1. The SFGAO_FOLDER, SFGAO_HASSUBFOLDER, and SFGAO_CANDELETE attributes are set.
HKEY_CLASSES_ROOT CLSID {Extension CLSID} (Default) = MyExtension InfoTip = Some appropriate text DefaultIcon (Default) = c:\MyDir\MyExtension.dll,-1 InProcServer32 (Default) = c:\MyDir\MyExtension.dll ThreadingModel = Apartment ShellFolder Attributes = 0xA00000020
Handling PIDLs
Every item in the Shell namespace must have a unique PIDL. Windows Explorer assigns a PIDL to your root folder and passes the value to your extension during initialization. Your extension is then responsible for assigning a properly constructed PIDL to each of its objects and providing those PIDLs to Windows Explorer on request. When the Shell uses a PIDL to identify one of your extension's objects, your extension must be able to interpret the PIDL and identify the particular object. Your extension must also assign a display name and a parsing name to each object. Because PIDLs are used by virtually every folder interface, extensions commonly implement a single PIDL manager to handle all these tasks.
The term PIDL is short for an ITEMIDLIST structure or a pointer to such a structure, depending on context. As declared, an ITEMIDLIST structure has a single member, an SHITEMID structure. An object's ITEMIDLIST structure is actually a packed array of two or more SHITEMID structures. The order of these structures defines a path through the namespace, in much the same way that c:\MyDirectory\MyFile defines a path through the file system. Typically, an object's PIDL will consist of a series of SHITEMID structures that correspond to the folders that define the namespace path, followed by the object's SHITEMID structure, followed by a terminator.
The terminator is an SHITEMID structure, with the cb member set to NULL. The terminator is necessary because the number of SHITEMID structures in an object's PIDL depends on the location of the object in the Shell namespace, and the starting point of the path. In addition, the size of the various SHITEMID structures can vary. When you receive a PIDL, you have no simple way of determining its size or even the total number of SHITEMID structures. Instead, you must "walk" the packed array, structure by structure, until you reach the terminator.
To create a PIDL, your application needs to:
- Create an SHITEMID structure for each of its objects.
- Assemble the relevant SHITEMID structures into a PIDL.
Creating an SHITEMID Structure
An object's SHITEMID structure uniquely identifies the object within its folder. In fact, a type of PIDL used by many of the IShellFolder methods consists of just the object's SHITEMID structure, followed by a terminator. The definition of an SHITEMID structure is:
The abID member is the object's identifier. Because the length of abID is not defined and can vary, the cb member is set to the size of the SHITEMID structure, in bytes.
Because neither the length nor the content of abID is standardized, you can use any scheme you want to assign abID values to your objects. The only requirement is that you cannot have two objects in the same folder with identical values. However, for performance reasons, your SHITEMID structure should be DWORD-aligned. In other words, you should construct your abID values such that cb is an integral multiple of 4.
Typically, abID points to an extension-defined structure. In addition to the object's ID, this structure is often used to hold a variety of related information, such as the object's type or attributes. Your extension's folder objects can then quickly extract the information from the PIDL instead of having to query for it.
- Persistable. The system frequently places PIDLs in various types of long-term storage, such as shortcut files. It can then recover these PIDLs from storage later, possibly after the system has been rebooted. A PIDL that has been recovered from storage must still be valid and meaningful to your extension. This requirement means, for instance, that you should not use pointers or handles in your PIDL structure. PIDLs containing this type of data will normally be meaningless when the system later recovers them from storage.
- Transportable. A PIDL must remain meaningful when transported from one computer to another. For example, a PIDL can be written to a shortcut file, copied to a floppy disk, and transported to another computer. That PIDL should still be meaningful to your extension running on the second computer. For instance, to ensure that your PIDLs are transportable, use either ANSI or Unicode characters explicitly. Avoid data types such as TCHAR or LPTSTR. If you use those data types, a PIDL created on a computer running a Unicode version of your extension will not be readable by an ANSI version of that extension running on a different computer.
The following declaration shows a simple example of a data structure.
The cb member is set to the size of the MYPIDLDATA structure. This member makes MYPIDLDATA a valid SHITEMID structure, in and of itself. The rest of the members are equivalent to the abID member of an SHITEMID structure and hold private data. The dwType member is an extension-defined value that indicates the type of object. For this example, dwType is set to TRUE for folders and FALSE otherwise. This member allows you, for instance, to quickly determine whether the object is a folder or not. The wszDisplayName member contains the object's display name. Since you would not assign the same display name to two different objects in the same folder, the display name also serves as the object ID. In this example, wszDisplayName is set to 40 characters to guarantee that the SHITEMID structure will be DWORD-aligned. To limit the size of your PIDLs, you can instead use a variable-length character array and adjust the value of cb accordingly. Pad the display string with enough '\0' characters to maintain the structure's DWORD alignment. Other members that might be useful to put in the structure include the object's size, attributes, or parsing name.
Constructing a PIDL
Once you have defined SHITEMID structures for your objects, you can then use them to construct a PIDL. PIDLs can be constructed for a variety of purposes, but most tasks use one of two types of PIDL. The simplest, a single-level PIDL, identifies the object relative to its parent folder. This type of PIDL is used by many of the IShellFolder methods. A single-level PIDL contains the object's SHITEMID structure, followed by a terminator. A fully qualified PIDL defines a path through the namespace hierarchy from the desktop to the object. This type of PIDL starts at the desktop and contains one SHITEMID structure for each folder in the path, followed by the object and the terminator. A fully qualified PIDL uniquely identifies the object within the entire Shell namespace.
The simplest way to construct a PIDL is to work directly with the ITEMIDLIST structure itself. Create an ITEMIDLIST structure, but allocate enough memory to hold all the SHITEMID structures. The address of this structure will point to the initial SHITEMID structure. Define values for the members of this initial structure, and then append as many additional SHITEMID structures as you need, in the appropriate order. The following procedure outlines how to create a single-level PIDL. It contains two SHITEMID structures—a MYPIDLDATA structure followed by a terminator:
- Use the CoTaskMemAlloc function to allocate memory for the PIDL. Allocate enough memory for your private data plus a USHORT (two bytes) for the terminator. Cast the result to LPMYPIDLDATA.
- Set the cb member of the first MYPIDLDATA structure to the size of that structure. For this example, you would set cb to sizeof(MYPIDLDATA). If you want to use a variable-length structure, you will have to calculate the value of cb.
- Assign appropriate values to the private data members.
- Calculate the address of the next SHITEMID structure. Cast the address of the current MYPIDLDATA structure to LPBYTE, and add that value to the value of cb determined in step 3.
- In this case, the next SHITEMID structure is the terminator. Set the structure's cb member to zero.
For longer PIDLs, allocate sufficient memory and repeat steps 3-5 for each additional SHITEMID structure.
The following sample function takes an object's type and display name and returns the object's single-level PIDL. The function assumes that the display name, including its terminating null character, does not exceed the number of characters declared for the MYPIDLDATA structure. If that assumption turns out to be erroneous, the StringCbCopyW function will truncate the display name. The g_pMalloc variable is an IMalloc pointer created elsewhere and stored in a global variable.
LPITEMIDLIST CreatePIDL(DWORD dwType, LPCWSTR pwszDisplayName) { LPMYPIDLDATA pidlOut; USHORT uSize; pidlOut = NULL; //Calculate the size of the MYPIDLDATA structure. uSize = sizeof(MYPIDLDATA); // Allocate enough memory for the PIDL to hold a MYPIDLDATA structure // plus the terminator pidlOut = (LPMYPIDLDATA)m_pMalloc->Alloc(uSize + sizeof(USHORT)); if(pidlOut) { //Assign values to the members of the MYPIDLDATA structure //that is the PIDL's first SHITEMID structure pidlOut->cb = uSize; pidlOut->dwType = dwType; hr = StringCbCopyW(pidlOut->wszDisplayName, sizeof(pidlOut->wszDisplayName), pwszDisplayName); // TODO: Add error handling here to verify the HRESULT returned // by StringCbCopyW. //Advance the pointer to the start of the next SHITEMID structure. pidlOut = (LPMYPIDLDATA)((LPBYTE)pidlOut + pidlOut->cb); //Create the terminating null character by setting cb to 0. pidlOut->cb = 0; } return pidlOut;
A fully qualified PIDL must have SHITEMID structures for every object from the desktop to your object. Your extension receives a fully qualified PIDL for your root folder when the Shell calls IPersistFolder::Initialize. To construct a fully qualified PIDL for an object, take the PIDL that the Shell has assigned to your root folder, and append the SHITEMID structures that are needed to take you from the root folder to the object.
Interpreting PIDLs
When the Shell or an application calls one of your extension's interfaces to request information about an object, it will usually identify the object by a PIDL. Some methods, such as IShellFolder::GetUIObjectOf, use PIDLs that are relative to the parent folder and are straightforward to interpret. However, your extension will probably also receive fully qualified PIDLs. Your PIDL manager must then determine which of your objects that PIDL is referring to.
What complicates the task of associating an object with a fully qualified PIDL is that one or more of the initial SHITEMID structures in the PIDL might belong to objects that lie outside your extension in the Shell namespace. You have no way of interpreting the meaning of the abID member of those structures. What your extension must do is to "walk" the list of SHITEMID structures, until you reach the structure that corresponds to your root folder. From then on, you will know how to interpret the information in the SHITEMID structures.
To walk the PIDL, take the first cb value and add it to the address of the PIDL to advance the pointer to the start of the next SHITEMID structure. It then will be pointing to that structure's cb member, which you can use to advance the pointer to the start of the next SHITEMID structure, and so on. Each time you advance the pointer, examine the SHITEMID structure to determine whether you have reached the root of your extension's namespace.
Implementing the Primary Interfaces
As with all COM objects, implementing an extension is largely a matter of implementing a collection of interfaces. This section discusses the three primary interfaces that must be implemented by all extensions. They are used for initialization and to provide Windows Explorer with basic information about the contents of the extension. These interfaces, plus a folder view, are all that is required for a functional extension. However, to fully exploit the features of Windows Explorer, most extensions also implement one or more of the optional interfaces.
IPersistFolder Interface
The IPersistFolder interface is called to initialize a new folder object. The IPersistFolder::Initialize method assigns a fully qualified PIDL to the new object. Store this PIDL for later use. For instance, a folder object must use this PIDL to construct fully qualified PIDLs for the object's children. The folder object's creator can also call IPersist::GetClassID to request the object's CLSID.
Typically, a folder object is created and initialized by its parent folder's IShellFolder::BindToObject method. However, when a user browses into your extension, Windows Explorer creates and initializes the extension's root folder object. The PIDL that the root folder object receives through IPersistFolder::Initialize contains the path from the desktop to the root folder that you will need to construct fully qualified PIDLs for your extension.
IShellFolder Interface
The Shell treats an extension as a hierarchically ordered collection of folder objects. The IShellFolder interface is the core of any extension implementation. It represents a folder object and provides Windows Explorer with much of the information needed to display the contents of the folder.
IShellFolder is typically the only folder interface other than IPersistFolder that is directly exposed by a folder object. While Windows Explorer uses a variety of required and optional interfaces to obtain information about the contents of the folder, it obtains pointers to those interfaces through IShellFolder.
Windows Explorer obtains the CLSID of your extension's root folder in a variety of ways. For details, see Specifying a Namespace Extension's Location or Displaying a Self-Contained View of a Namespace Extension. Windows Explorer then uses that CLSID to create and initialize an instance of the root folder and query for an IShellFolder interface. Your extension creates a folder object to represent the root folder and returns the object's IShellFolder interface. Much of the remainder of the interaction between your extension and Windows Explorer then takes place through IShellFolder. Windows Explorer calls IShellFolder to:
- Request an object that can enumerate the contents of the root folder.
- Obtain various types of information about the contents of the root folder.
- Request an object that exposes one of the optional interfaces. Those interfaces can then be queried for additional information, such as icons or shortcut menus.
- Request a folder object that represents a subfolder of the root folder.
When a user opens a subfolder of the root folder, Windows Explorer calls IShellFolder::BindToObject. Your extension creates and initializes a new folder object to represent the subfolder and returns its IShellFolder interface. Windows Explorer then calls this interface for various types of information, and so on until the user decides to navigate elsewhere in the Shell namespace or close Windows Explorer.
The remainder of this section briefly discusses the more important IShellFolder methods and how to implement them.
EnumObjects
Before displaying the contents of a folder in the tree view, Windows Explorer must first determine what the folder contains by calling the IShellFolder::EnumObjects method. This method creates a standard OLE enumeration object that exposes an IEnumIDList interface and returns that interface pointer. The IEnumIDList interface allows Windows Explorer to obtain the PIDLs of all the objects contained by the folder. These PIDLs are then used to obtain information about the objects contained by the folder. For further details, see IEnumIDList Interface.
CreateViewObject
Before the contents of a folder are displayed, Windows Explorer calls this method to request a pointer to an IShellView interface. This interface is used by Windows Explorer to manage the folder view. Create a folder view object and return its IShellView interface.
The IShellFolder::CreateViewObject method is also called to request one of the optional interfaces, such as IContextMenu, for the folder itself. Your implementation of this method should create an object that exposes the requested interface and returns the interface pointer. If Windows Explorer needs an optional interface for one of the objects contained by the folder, it will call IShellFolder::GetUIObjectOf.
GetUIObjectOf
While basic information about the contents of a folder is available through the IShellFolder methods, your extension can also provide Windows Explorer with various kinds of additional information. For instance, you can specify icons for the contents of a folder or an object's shortcut menu. Windows Explorer calls the IShellFolder::GetUIObjectOf method to attempt to retrieve additional information about an object that is contained by a folder. Windows Explorer specifies which object it wants the information for, and the IID of the relevant interface. The folder object then creates an object that exposes the requested interface and returns the interface pointer.
If your extension allows users to transfer objects with drag-and-drop or the clipboard, Windows Explorer will call IShellFolder::GetUIObjectOf to request an IDataObject or IDropTarget interface. For details, see Transferring Shell Objects with Drag-and-Drop and the Clipboard.
Windows Explorer calls IShellFolder::CreateViewObject when it wants the same sort of information about the folder itself.
BindToObject
Windows Explorer calls the IShellFolder::BindToObject method when a user attempts to open one of your extension's subfolders. If riid is set to IID_IShellFolder, you should create and initialize a folder object that represents the subfolder and return the object's IShellFolder interface.
GetDisplayNameOf
Windows Explorer calls the IShellFolder::GetDisplayNameOf method to convert the PIDL of one of the folder's objects into a name. That PIDL must be relative to the object's parent folder. In other words, it must contain a single non-NULL SHITEMID structure. Because there is more than one possible way to name objects, Windows Explorer specifies the type of name by setting one or more SHGDNF flags in the uFlags parameter. One of two values, SHGDN_NORMAL or SHGDN_INFOLDER, will be set to specify whether the name should be relative to the folder or relative to the desktop. One of the other three values, SHGDN_FOREDITING, SHGDN_FORADDRESSBAR, or SHGDN_FORPARSING, can be set to specify what the name will be used for.
You must return the name in the form of an STRRET structure. If SHGDN_FOREDITING, SHGDN_FORADDRESSBAR, and SHGDN_FORPARSING are not set, return the object's display name. If the SHGDN_FORPARSING flag is set, Windows Explorer is requesting a parsing name. Parsing names are passed to IShellFolder::ParseDisplayName to obtain an object's PIDL, even though it might be located one or more levels below the current folder in the namespace hierarchy. For example, the parsing name of a file system object is its path. You can pass the fully qualified path of any object in the file system to the desktop's IShellFolder::ParseDisplayName method, and it will return the object's fully qualified PIDL.
While parsing names are text strings, they do not necessarily have to include the display name. You should assign parsing names based on what will work most efficiently when IShellFolder::ParseDisplayName is called. For instance, many of the Shell's virtual folders are not part of the file system and do not have a fully qualified path. Instead, each folder is assigned a GUID and the parsing name takes the form ::{GUID}. Regardless of what scheme you use, it should be able to reliably "round trip." For instance, if a caller passes a parsing name to IShellFolder::ParseDisplayName to retrieve an object's PIDL, and then passes that PIDL to IShellFolder::GetDisplayNameOf with the SHGDN_FORPARSING flag set, the caller should recover the original parsing name.
GetAttributesOf
Windows Explorer calls the IShellFolder::GetAttributesOf method to determine the attributes of one or more items contained by a folder object. The value of cidl gives the number of items in the query, and aPidl points to a list of their PIDLs.
Because testing for some attributes can be time consuming, Windows Explorer typically restricts the query to a subset of the available flags by setting their values in rfgInOut. Your method should test for only those attributes whose flags are set in rfgInOut. Leave the valid flags set and clear the remainder. If more than one item is included in the query, set only those flags that apply to all items.
ParseDisplayName
The IShellFolder::ParseDisplayName method is in some sense a mirror image of IShellFolder::GetDisplayNameOf. The most common use of this method is to convert an object's parsing name into the associated PIDL. The parsing name can refer to any object that lies below the folder in the namespace hierarchy. The returned PIDL is relative to the folder object that exposes the method and is usually not fully qualified. In other words, although the PIDL can contain several SHITEMID structures, the first will either be that of the object itself or the first subfolder in the path from the folder to the object. The caller will have to append this PIDL to the folder's fully qualified PIDL to obtain a fully qualified PIDL for the object.
IShellFolder::ParseDisplayName can also be called to request an object's attributes. Because determining all the applicable attributes can be time consuming, the caller will set only those SFGAO_XXX flags that represent information that the caller is interested in. You should determine which of those attributes are true for the object, and clear the remaining flags.
IEnumIDList Interface
When Windows Explorer needs to enumerate the objects that are contained by a folder, it calls IShellFolder::EnumObjects. The folder object must create an enumeration object that exposes the IEnumIDList interface and return that interface pointer. Windows Explorer will then typically use IEnumIDList to enumerate the PIDLs of all the objects contained by the folder.
IEnumIDList is a standard OLE enumeration interface and is implemented in the usual way. Remember, however, that the PIDLs that you return must be relative to the folder and contain only the object's SHITEMID structure and a terminator.
Implementing the Optional Interfaces
There are a number of optional Shell interfaces that your extension's folder objects can support. Many of them, such as IExtractIcon, allow you to customize various aspects of the way the user views your extension. Others, such as IDataObject, allow your extension to support features such as drag-and-drop.
None of the optional interfaces are exposed directly by a folder object. Instead, Windows Explorer calls one of two IShellFolder methods to request an interface:
- Windows Explorer calls a folder object's IShellFolder::GetUIObjectOf to request an interface for one of the objects contained by the folder.
- Windows Explorer calls a folder object's IShellFolder::CreateViewObject to request an interface for the folder itself.
To provide the information, the folder object creates an object that exposes the requested interface and returns the interface pointer. Windows Explorer then calls that interface to retrieve the needed information. This section discusses the most commonly used optional interfaces.
IExtractIcon
Windows Explorer requests an IExtractIcon interface before it displays the contents of a folder. The interface allows your extension to specify custom icons for the objects that are contained by the folder. Otherwise, the standard file and folder icons will be used. To provide a custom icon, create an icon extraction object that exposes IExtractIcon and return a pointer to that interface. For further discussion, see the IExtractIcon reference documentation or Creating Icon Handlers.
IContextMenu
When a user right-clicks an object, Windows Explorer requests an IContextMenu interface. To provide shortcut menus for your objects, create a menu handler object and return its IContextMenu interface.
The procedures for creating a menu handler object are very similar to those used to create a menu handler Shell extension. For details, see Creating Context Menu Handlers or the IContextMenu, IContextMenu2, or IContextMenu3 reference.
IQueryInfo
Windows Explorer calls the IQueryInfo interface to retrieve an infotip text string.
IDataObject and IDropTarget
When your objects are displayed by Windows Explorer, a folder object has no direct way to know when a user is attempting to cut, copy, or drag an object. Instead, Windows Explorer requests an IDataObject interface. To allow the object to be transferred, create a data object and return a pointer to its IDataObject interface.
Similarly, a user might attempt to drop a data object on a Windows Explorer representation of one of your objects, such as an icon or address bar path. Windows Explorer then requests an IDropTarget interface. To allow the data object to be dropped, create an object that exposes an IDropTarget interface and return the interface pointer.
Handling data transfer is one of the trickier aspects of writing namespace extensions. For a detailed discussion, see Transferring Shell Objects with Drag-and-Drop and the Clipboard.
Working With the Default Shell Folder View Implementation
Data sources that use the default Shell folder view object (DefView) must implement these interfaces:
Optionally, they can also implement IPersistFolder3. | https://msdn.microsoft.com/en-us/library/cc144093(v=vs.85).aspx | CC-MAIN-2016-30 | refinedweb | 5,092 | 53.21 |
Basic Example
The first example to look at is a complete (although somewhat trivial)
application. It uses
PBServerFactory() on the server side, and
PBClientFactory() on the client side.
1 2 3 4 5 6 7 8 9 10 11from twisted.spread import pb from twisted.internet import reactor class Echoer(pb.Root): def remote_echo(self, st): print 'echoing:', st return st if __name__ == '__main__': reactor.listenTCP(8789, pb.PBServerFactory(Echoer())) reactor.run()
1 2 3 4 5 6 7 8 9 10 11 12 13from twisted.spread import pb from twisted.internet import reactor from twisted.python import util factory = pb.PBClientFactory() reactor.connectTCP("localhost", 8789, factory) d = factory.getRootObject() d.addCallback(lambda object: object.callRemote("echo", "hello network")) d.addCallback(lambda echo: 'server echoed: '+echo) d.addErrback(lambda reason: 'error: '+str(reason.value)) d.addCallback(util.println) d.addCallback(lambda _: reactor.stop()) reactor.run()
First we look at the server. This defines an Echoer class (derived from
pb.Root), with a method called
remote_echo().
pb.Root objects (because of
their inheritance of
pb.Referenceable, described
later) can define methods with names of the form
remote_*; a
client which obtains a remote reference to that
pb.Root object will be able to
invoke those methods.
The
pb.Root-ish object is
given to a
pb.PBServerFactory
(). This is a
Factory object like
any other: the
Protocol objects it creates for new
connections know how to speak the PB protocol. The object you give to
pb.PBServerFactory() becomes the
root object, which
simply makes it available for the client to retrieve. The client may only
request references to the objects you want to provide it: this helps you
implement your security model. Because it is so common to export just a
single object (and because a
remote_* method on that one can
return a reference to any other object you might want to give out), the
simplest example is one where the
PBServerFactory is given the root object, and
the client retrieves it.
The client side uses
pb.PBClientFactory to make a
connection to a given port. This is a two-step process involving opening
a TCP connection to a given host and port and requesting the root object
using
.getRootObject().
Because
.getRootObject() has to wait until a network
connection has been made and exchange some data, it may take a while,
so it returns a Deferred, to which the gotObject() callback is
attached. (See the documentation on Deferring
Execution for a complete explanation of
Deferreds). If and when the
connection succeeds and a reference to the remote root object is
obtained, this callback is run. The first argument passed to the
callback is a remote reference to the distant root object. (you can
give other arguments to the callback too, see the other parameters for
.addCallback() and
.addCallbacks()).
The callback does:
1object.callRemote("echo", "hello network")
which causes the server's
.remote_echo() method to be invoked.
(running
.callRemote("boom") would cause
.remote_boom() to be run, etc). Again because of the delay
involved,
callRemote() returns a
Deferred. Assuming the
remote method was run without causing an exception (including an attempt to
invoke an unknown method), the callback attached to that
Deferred will be
invoked with any objects that were returned by the remote method call.
In this example, the server's
Echoer object has a method
invoked, exactly as if some code on the server side had done:
1echoer_object.remote_echo("hello network")
and from the definition of
remote_echo() we see that this just
returns the same string it was given:
hello network.
From the client's point of view, the remote call gets another
Deferred object instead of
that string.
callRemote() always returns a
Deferred. This is why PB is
described as a system for
translucent remote method calls instead of
transparent ones: you cannot pretend that the remote object is really
local. Trying to do so (as some other RPC mechanisms do, coughCORBAcough)
breaks down when faced with the asynchronous nature of the network. Using
Deferreds turns out to be a very clean way to deal with the whole thing.
The remote reference object (the one given to
getRootObject()'s success callback) is an instance the
RemoteReference class. This means
you can use it to invoke methods on the remote object that it refers to. Only
instances of
RemoteReference are eligible for
.callRemote(). The
RemoteReference object is the one that lives
on the remote side (the client, in this case), not the local side (where the
actual object is defined).
In our example, the local object is that
Echoer() instance,
which inherits from
pb.Root,
which inherits from
pb.Referenceable. It is that
Referenceable class that makes the object eligible to be available
for remote method calls
remote_* methods they please.
The only thing they can do is invoke those
methods. In particular, they cannot access attributes. From a security point
of view, you control what they can do by limiting what the
remote_* methods can do.
Also note: the other classes like
Referenceable allow access to
other methods, in particular
perspective_* and
view_*
may be accessed. Don't write local-only methods with these names, because then
remote callers will be able to do more than you intended.
Also also note: the other classes like
pb.Copyable do allow
access to attributes, but you control which ones they can see.
You don't have to be a
pb.Root to be remotely callable,
but you do have to be
pb.Referenceable. (Objects that
inherit from
pb.Referenceable
but not from
pb.Root can be
remotely called, but only
pb.Root-ish objects can be given
to the
PBServerFactory.)
Complete Example
Here is an example client and server which uses
pb.Referenceable as a root object and as the
result of a remotely exposed method. In each context, methods can be invoked
on the exposed
Referenceable
instance. In this example, the initial root object has a method that returns a
reference to the second object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20#!/usr/bin/env python # Copyright (c) 2009 Twisted Matrix Laboratories. # See LICENSE for details. from twisted.spread import pb class Two(pb.Referenceable): def remote_three(self, arg): print "Two.three was given", arg class One(pb.Root): def remote_getTwo(self): two = Two() print "returning a Two called", two return two from twisted.internet import reactor reactor.listenTCP(8800, pb.PBServerFactory(One())) reactor.run()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31#!/usr/bin/env python # Copyright (c) 2009 Twisted Matrix Laboratories. # See LICENSE for details. from twisted.spread import pb from twisted.internet import reactor def main(): factory = pb.PBClientFactory() reactor.connectTCP("localhost", 8800, factory) def1 = factory.getRootObject() def1.addCallbacks(got_obj1, err_obj1) reactor.run() def err_obj1(reason): print "error getting first object", reason reactor.stop() def got_obj1(obj1): print "got first object:", obj1 print "asking it to getTwo" def2 = obj1.callRemote("getTwo") def2.addCallbacks(got_obj2) def got_obj2(obj2): print "got second object:", obj2 print "telling it to do three(12)" obj2.callRemote("three", 12) main()
pb.PBClientFactory.getRootObject will
handle all the details of waiting for the creation of a connection.
It returns a
Deferred, which will have its
callback called when the reactor connects to the remote server and
pb.PBClientFactory gets the
root, and have its
errback called when the
object-connection fails for any reason, whether it was host lookup
failure, connection refusal, or some server-side error.
The root object has a method called
remote_getTwo, which
returns the
Two() instance. On the client end, the callback gets
a
RemoteReference to that
instance. The client can then invoke two's
.remote_three()
method.
RemoteReference
objects have one method which is their purpose for being:
callRemote. This method allows you to call a
remote method on the object being referred to by the Reference.
RemoteReference.callRemote, like
pb.PBClientFactory.getRootObject, returns
a
Deferred.
When a response to the method-call being sent arrives, the
Deferred's
callback or
errback
will be made, depending on whether an error occurred in processing the
method call.
You can use this technique to provide access to arbitrary sets of objects.
Just remember that any object that might get passed
over the wire must
inherit from
Referenceable
(or one of the other flavors). If you try to pass a non-Referenceable object
(say, by returning one from a
remote_* method), you'll get an
InsecureJelly
exception
References can come back to you
If your server gives a reference to a client, and then that client gives
the reference back to the server, the server will wind up with the same
object it gave out originally. The serialization layer watches for returning
reference identifiers and turns them into actual objects. You need to stay
aware of where the object lives: if it is on your side, you do actual method
calls. If it is on the other side, you do
.callRemote()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30#!/usr/bin/env python # Copyright (c) 2009 Twisted Matrix Laboratories. # See LICENSE for details. from twisted.spread import pb from twisted.internet import reactor class Two(pb.Referenceable): def remote_print(self, arg): print "two.print was given", arg class One(pb.Root): def __init__(self, two): #pb.Root.__init__(self) # pb.Root doesn't implement __init__ self.two = two def remote_getTwo(self): print "One.getTwo(), returning my two called", two return two def remote_checkTwo(self, newtwo): print "One.checkTwo(): comparing my two", self.two print "One.checkTwo(): against your two", newtwo if two == newtwo: print "One.checkTwo(): our twos are the same" two = Two() root_obj = One(two) reactor.listenTCP(8800, pb.PBServerFactory(root_obj)) reactor.run()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36#!/usr/bin/env python # Copyright (c) 2009 Twisted Matrix Laboratories. # See LICENSE for details. from twisted.spread import pb from twisted.internet import reactor def main(): foo = Foo() factory = pb.PBClientFactory() reactor.connectTCP("localhost", 8800, factory) factory.getRootObject().addCallback(foo.step1) reactor.run() # keeping globals around is starting to get ugly, so we use a simple class # instead. Instead of hooking one function to the next, we hook one method # to the next. class Foo: def __init__(self): self.oneRef = None def step1(self, obj): print "got one object:", obj self.oneRef = obj print "asking it to getTwo" self.oneRef.callRemote("getTwo").addCallback(self.step2) def step2(self, two): print "got two object:", two print "giving it back to one" print "one is", self.oneRef self.oneRef.callRemote("checkTwo", two) main()
The server gives a
Two() instance to the client, who then
returns the reference back to the server. The server compares the
two
given with the
two received and shows that they are the same, and that
both are real objects instead of remote references.
A few other techniques are demonstrated in
pb2client.py. One
is that the callbacks are are added with
.addCallback instead
of
.addCallbacks. As you can tell from the Deferred documentation,
.addCallback is a
simplified form which only adds a success callback. The other is that to
keep track of state from one callback to the next (the remote reference to
the main One() object), we create a simple class, store the reference in an
instance thereof, and point the callbacks at a sequence of bound methods.
This is a convenient way to encapsulate a state machine. Each response kicks
off the next method, and any data that needs to be carried from one state to
the next can simply be saved as an attribute of the object.
Remember that the client can give you back any remote reference you've given them. Don't base your zillion-dollar stock-trading clearinghouse server on the idea that you trust the client to give you back the right reference. The security model inherent in PB means that they can only give you back a reference that you've given them for the current connection (not one you've given to someone else instead, nor one you gave them last time before the TCP session went down, nor one you haven't yet given to the client), but just like with URLs and HTTP cookies, the particular reference they give you is entirely under their control.
References to client-side objects
Anything that's Referenceable can get passed across the wire, in
either direction. The
client can give a reference to the
server, and then the server can use .callRemote() to invoke methods on
the client end. This fuzzes the distinction between
client and
server: the only real difference is who initiates the original TCP
connection; after that it's all symmetric.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16#!/usr/bin/env python # Copyright (c) 2009 Twisted Matrix Laboratories. # See LICENSE for details. from twisted.spread import pb from twisted.internet import reactor class One(pb.Root): def remote_takeTwo(self, two): print "received a Two called", two print "telling it to print(12)" two.callRemote("print", 12) reactor.listenTCP(8800, pb.PBServerFactory(One())) reactor.run()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26#!/usr/bin/env python # Copyright (c) 2009 Twisted Matrix Laboratories. # See LICENSE for details. from twisted.spread import pb from twisted.internet import reactor class Two(pb.Referenceable): def remote_print(self, arg): print "Two.print() called with", arg def main(): two = Two() factory = pb.PBClientFactory() reactor.connectTCP("localhost", 8800, factory) def1 = factory.getRootObject() def1.addCallback(got_obj, two) # hands our 'two' to the callback reactor.run() def got_obj(obj, two): print "got One:", obj print "giving it our two" obj.callRemote("takeTwo", two) main()
In this example, the client gives a reference to its own object to the server. The server then invokes a remote method on the client-side object.
Raising Remote Exceptions
Everything so far has covered what happens when things go right. What about when they go wrong? The Python Way is to raise an exception of some sort. The Twisted Way is the same.
The only special thing you do is to define your
Exception
subclass by deriving it from
pb.Error. When any remotely-invokable method
(like
remote_* or
perspective_*) raises a
pb.Error-derived exception, a serialized form of that Exception
object will be sent back over the wire
callRemote) will have the
callback run with a
errback
Failure object that contains a copy of
the exception object. This
Failure object can be queried to
retrieve the error message and a stack traceback.
Failure is a
special class, defined in
twisted/python/failure.py, created to
make it easier to handle asynchronous exceptions. Just as exception handlers
can be nested,
errback functions can be chained. If one errback
can't handle the particular type of failure, it can be
passed along to a
errback handler further down the chain.
For simple purposes, think of the
Failure as just a container
for remotely-thrown
Exception objects. To extract the string that
was put into the exception, use its
.getErrorMessage() method.
To get the type of the exception (as a string), look at its
.type attribute. The stack traceback is available too. The
intent is to let the errback function get just as much information about the
exception as Python's normal
try: clauses do, even though the
exception occurred in somebody else's memory space at some unknown time in
the past.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32#!/usr/bin/env python # Copyright (c) 2009 Twisted Matrix Laboratories. # See LICENSE for details. from twisted.spread import pb from twisted.internet import reactor class MyError(pb.Error): """This is an Expected Exception. Something bad happened.""" pass class MyError2(Exception): """This is an Unexpected Exception. Something really bad happened.""" pass class One(pb.Root): def remote_broken(self): msg = "fall down go boom" print "raising a MyError exception with data '%s'" % msg raise MyError(msg) def remote_broken2(self): msg = "hadda owie" print "raising a MyError2 exception with data '%s'" % msg raise MyError2(msg) def main(): reactor.listenTCP(8800, pb.PBServerFactory(One())) reactor.run() if __name__ == '__main__': main()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33#!/usr/bin/env python # Copyright (c) 2009 Twisted Matrix Laboratories. # See LICENSE for details. from twisted.spread import pb from twisted.internet import reactor def main(): factory = pb.PBClientFactory() reactor.connectTCP("localhost", 8800, factory) d = factory.getRootObject() d.addCallbacks(got_obj) reactor.run() def got_obj(obj): # change "broken" into "broken2" to demonstrate an unhandled exception d2 = obj.callRemote("broken") d2.addCallback(working) d2.addErrback(broken) def working(): print "erm, it wasn't *supposed* to work.." def broken(reason): print "got remote Exception" # reason should be a Failure (or subclass) holding the MyError exception print " .__class__ =", reason.__class__ print " .getErrorMessage() =", reason.getErrorMessage() print " .type =", reason.type reactor.stop() main()
% ./exc_client.py got remote Exception .__class__ = twisted.spread.pb.CopiedFailure .getErrorMessage() = fall down go boom .type = __main__.MyError Main loop terminated.
Oh, and what happens if you raise some other kind of exception? Something
that isn't subclassed from
pb.Error? Well, those are
called
unexpected exceptions, which make Twisted think that something
has really gone wrong. These will raise an exception on the
server side. This won't break the connection (the exception is
trapped, just like most exceptions that occur in response to network
traffic), but it will print out an unsightly stack trace on the server's
stderr with a message that says
Peer Will Receive PB Traceback, just
as if the exception had happened outside a remotely-invokable method. (This
message will go the current log target, if
log.startLogging was used to redirect it). The
client will get the same
Failure object in either case, but
subclassing your exception from
pb.Error is the way to tell
Twisted that you expect this sort of exception, and that it is ok to just
let the client handle it instead of also asking the server to complain. Look
at
exc_client.py and change it to invoke
broken2()
instead of
broken() to see the change in the server's
behavior.
If you don't add an
errback function to the
Deferred, then a remote
exception will still send a
Failure object back over, but it
will get lodged in the
Deferred with nowhere to go. When that
Deferred finally goes out of scope, the side that did
callRemote will emit a message about an
Unhandled error in
Deferred, along with an ugly stack trace. It can't raise an exception at
that point (after all, the
callRemote that triggered the
problem is long gone), but it will emit a traceback. So be a good programmer
and always add
errback handlers, even if they are just
calls to
log.err.
Try/Except blocks and
Failure.trap
To implement the equivalent of the Python try/except blocks (which can
trap particular kinds of exceptions and pass others
up to
higher-level
try/except blocks), you can use the
.trap() method in conjunction with multiple
errback handlers on the
Deferred. Re-raising an
exception in an
errback handler serves to pass that new
exception to the next handler in the chain. The
trap method is
given a list of exceptions to look for, and will re-raise anything that
isn't on the list. Instead of passing unhandled exceptions
up to an
enclosing
try block, this has the effect of passing the
exception
off to later
errback handlers on the same
Deferred. The
trap calls are used in chained
errbacks to test for each kind of exception in sequence.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21#!/usr/bin/env python # Copyright (c) 2009 Twisted Matrix Laboratories. # See LICENSE for details. from twisted.internet import reactor from twisted.spread import pb class MyException(pb.Error): pass class One(pb.Root): def remote_fooMethod(self, arg): if arg == "panic!": raise MyException return "response" def remote_shutdown(self): reactor.stop() reactor.listenTCP(8800, pb.PBServerFactory(One())) reactor#!/usr/bin/env python # Copyright (c) 2009 Twisted Matrix Laboratories. # See LICENSE for details. from twisted.spread import pb, jelly from twisted.python import log from twisted.internet import reactor class MyException(pb.Error): pass class MyOtherException(pb.Error): pass class ScaryObject: # not safe for serialization pass def worksLike(obj): # the callback/errback sequence in class One works just like an # asynchronous version of the following: try: response = obj.callMethod(name, arg) except pb.DeadReferenceError: print " stale reference: the client disconnected or crashed" except jelly.InsecureJelly: print " InsecureJelly: you tried to send something unsafe to them" except (MyException, MyOtherException): print " remote raised a MyException" # or MyOtherException except: print " something else happened" else: print " method successful, response:", response class One: def worked(self, response): print " method successful, response:", response def check_InsecureJelly(self, failure): failure.trap(jelly.InsecureJelly) print " InsecureJelly: you tried to send something unsafe to them" return None def check_MyException(self, failure): which = failure.trap(MyException, MyOtherException) if which == MyException: print " remote raised a MyException" else: print " remote raised a MyOtherException" return None def catch_everythingElse(self, failure): print " something else happened" log.err(failure) return None def doCall(self, explanation, arg): print explanation try: deferred = self.remote.callRemote("fooMethod", arg) deferred.addCallback(self.worked) deferred.addErrback(self.check_InsecureJelly) deferred.addErrback(self.check_MyException) deferred.addErrback(self.catch_everythingElse) except pb.DeadReferenceError: print " stale reference: the client disconnected or crashed" def callOne(self): self.doCall("callOne: call with safe object", "safe string") def callTwo(self): self.doCall("callTwo: call with dangerous object", ScaryObject()) def callThree(self): self.doCall("callThree: call that raises remote exception", "panic!") def callShutdown(self): print "telling them to shut down" self.remote.callRemote("shutdown") def callFour(self): self.doCall("callFour: call on stale reference", "dummy") def got_obj(self, obj): self.remote = obj reactor.callLater(1, self.callOne) reactor.callLater(2, self.callTwo) reactor.callLater(3, self.callThree) reactor.callLater(4, self.callShutdown) reactor.callLater(5, self.callFour) reactor.callLater(6, reactor.stop) factory = pb.PBClientFactory() reactor.connectTCP("localhost", 8800, factory) deferred = factory.getRootObject() deferred.addCallback(One().got_obj) reactor.run()
% ./trap_client.py callOne: call with safe object method successful, response: response callTwo: call with dangerous object InsecureJelly: you tried to send something unsafe to them callThree: call that raises remote exception remote raised a MyException telling them to shut down callFour: call on stale reference stale reference: the client disconnected or crashed %
In this example,
callTwo tries to send an instance of a
locally-defined class through
callRemote. The default security
model implemented by
pb.Jelly
on the remote end will not allow unknown classes to be unserialized (i.e.
taken off the wire as a stream of bytes and turned back into an object: a
living, breathing instance of some class): one reason is that it does not
know which local class ought to be used to create an instance that
corresponds to the remote object
pb.InsecureJelly exception. Because it occurs
at the remote end, the exception is returned to the caller asynchronously,
so an
errback handler for the associated
Deferred
is run. That errback receives a
Failure which wraps the
InsecureJelly.
Remember that
trap re-raises exceptions that it wasn't asked
to look for. You can only check for one set of exceptions per errback
handler: all others must be checked in a subsequent handler.
check_MyException shows how multiple kinds of exceptions can be
checked in a single errback: give a list of exception types to
trap, and it will return the matching member. In this case, the
kinds of exceptions we are checking for (
MyException and
MyOtherException) may be raised by the remote end: they inherit
from
pb.Error.
The handler can return
None to terminate processing of the
errback chain (to be precise, it switches to the callback that follows the
errback; if there is no callback then processing terminates). It is a good
idea to put an errback that will catch everything (no
trap
tests, no possible chance of raising more exceptions, always returns
None) at the end of the chain. Just as with regular
try:
except: handlers, you need to think carefully about ways in which
your errback handlers could themselves raise exceptions. The extra
importance in an asynchronous environment is that an exception that falls
off the end of the
Deferred will not be signalled until that
Deferred goes out of scope, and at that point may only cause a
log message (which could even be thrown away if
log.startLogging is not used to point it at
stdout or a log file). In contrast, a synchronous exception that is not
handled by any other
except: block will very visibly terminate
the program immediately with a noisy stack trace.
callFour shows another kind of exception that can occur
while using
callRemote:
pb.DeadReferenceError. This one occurs when the
remote end has disconnected or crashed, leaving the local side with a stale
reference. This kind of exception happens to be reported right away (XXX: is
this guaranteed? probably not), so must be caught in a traditional
synchronous
try: except pb.DeadReferenceError block.
Yet another kind that can occur is a
pb.PBConnectionLost exception. This occurs
(asynchronously) if the connection was lost while you were waiting for a
callRemote call to complete. When the line goes dead, all
pending requests are terminated with this exception. Note that you have no
way of knowing whether the request made it to the other end or not, nor how
far along in processing it they had managed before the connection was
lost. XXX: explain transaction semantics, find a decent reference.
Footnotes
- There are a few other classes that can bestow this ability, but pb.Referenceable is the easiest to understand; see 'flavors' below for details on the others.
- This can be overridden, by subclassing one of the Serializable flavors and defining custom serialization code for your class. See Passing Complex Types for details.
- The binary nature of this local vs. remote scheme works because you cannot give RemoteReferences to a third party. If you could, then your object A could go to B, B could give it to C, C might give it back to you, and you would be hard pressed to tell if the object lived in C's memory space, in B's, or if it was really your own object, tarnished and sullied after being handed down like a really ugly picture that your great aunt owned and which nobody wants but which nobody can bear to throw out. Ok, not really like that, but you get the idea.
- To be precise, the Failure will be sent if any exception is raised, not just pb.Error-derived ones. But the server will print ugly error messages if you raise ones that aren't derived from pb.Error.
The naive approach of simply doing
import SomeClassto match a remote caller who claims to have an object of type
SomeClasscould have nasty consequences for some modules that do significant operations in their
__init__methods (think
telnetlib.Telnet(host='localhost', port='chargen'), or even more powerful classes that you have available in your server program). Allowing a remote entity to create arbitrary classes in your namespace is nearly equivalent to allowing them to run arbitrary code.
The
pb.InsecureJellyexception arises because the class being sent over the wire has not been registered with the serialization layer (known as
jelly). The easiest way to make it possible to copy entire class instances over the wire is to have them inherit from
pb.Copyable, and then to use
setUnjellyableForClass(remoteClass, localClass)on the receiving side. See Passing Complex Types for an example. | http://twistedmatrix.com/documents/10.2.0/core/howto/pb-usage.html | CC-MAIN-2015-11 | refinedweb | 4,732 | 57.37 |
Pandas: Extract the day name from a specified date
Pandas Time Series: Exercise-25 with Solution
Write a Pandas program to extract the day name from a specified date. Add 2 days and 1 business day with the specified date.
Sample Solution:
Python Code :
import pandas as pd newday = pd.Timestamp('2020-02-07') print("First date:") print(newday) print("\nThe day name of the said date:") print(newday.day_name()) print("\nAdd 2 days with the said date:") newday1 = newday + pd.Timedelta('2 day') print(newday1.day_name()) print("\nNext business day:") nbday = newday + pd.offsets.BDay() print(nbday.day_name())
Sample Output:
First date: 2020-02-07 00:00:00 The day name of the said date: Friday Add 2 days with the said date: Sunday Next business day: Monday
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Pandas program to generate time series combining day and intraday offsets intervals.
Next: Write a Pandas program to convert integer or float epoch times to Timestamp and Datetime | https://www.w3resource.com/python-exercises/pandas/time-series/pandas-time-series-exercise-25.php | CC-MAIN-2021-21 | refinedweb | 177 | 57.37 |
[Previous: Qt3Support Module] [Qt's Modules] [Next: QAxContainer Module]
The QtTest module provides classes for unit testing Qt applications and libraries. More...
Applications that use Qt's unit testing classes need to be configured to be built against the QtTest module. To include the definitions of the module's classes, use the following directive:
#include <QtTest>
To link against the module, add this line to your qmake .pro file:
CONFIG += qtestlib
See the QTestLib Manual for a detailed introduction on how to use Qt's unit testing features with your applications.
The QtTest module is part of all Qt editions.
[Previous: Qt3Support Module] [Qt's Modules] [Next: QAxContainer Module] | http://doc.trolltech.com/4.3/qttest.html | crawl-002 | refinedweb | 109 | 53.92 |
acosh man page
Prolog
This manual page is part of the POSIX Programmer's Manual. The Linux implementation of this interface may differ (consult the corresponding Linux manual page for details of Linux behavior), or the interface may not be implemented on Linux.
acosh, acoshf, acoshl — inverse hyperbolic cosine functions
Synopsis
#include <math.h> double acosh(double x); float acoshf(float x); long double ac -Inf, a domain error shall occur, and a NaN shall be returned.
Errors
These functions shall fail if:
- Domain Error
The x argument is finite and less than +1.0, or
cosh(),osh(3p), math.h(0p). | https://www.mankier.com/3p/acosh | CC-MAIN-2017-47 | refinedweb | 102 | 55.74 |
Transmitter to send wireless signals. More...
#include <sensors/sensors.hh>
Inherits WirelessTransceiver.
Transmitter to send wireless signals.
Constructor.
Destructor.
Get the category of the sensor.
Connect a signal that is triggered when the sensor is updated.
Returns the Service Set Identifier (network name).
fills a msgs::Sensor message.
Finalize the sensor.
Reimplemented from Sensor.
Reimplemented in WirelessReceiver.
Returns reception frequency (MHz).
Returns the antenna's gain of the receiver (dBi).
Get the sensor's ID.
Initialize the sensor.
Reimplemented from WirelessTransceiver..
Load the sensor with default parameters.
Reimplemented from WirelessTransceiver. the std dev of the Gaussian random variable used in the propagation model.
Get name.
Return true if the sensor needs to be updated.
Get the sensor's noise model for a specified noise type.
Get the sensor's parent's ID.
Returns the name of the sensor parent.
The parent name is set by Sensor::SetParent.
Returns the receiver power (dBm).
Reset the lastUpdateTime to zero.
Get fully scoped name of the sensor.
Set whether the sensor is active or not.
Set the sensor's parent.
Set the update rate of the sensor.
Returns the signal strength in a given world's point (dBm)..
Antenna's gain of the receiver (dBi).
Stores last time that a sensor measurement was generated; this value must be updated within each sensor's UpdateImpl.
Time of the last update.
Node for communication.
Ignition transport node.
Parent entity which the sensor is attached to.
The sensor's parent ID.
Name of the parent.
All the plugins for the sensor.
Pose of the sensor.
Receiver's power (dBm).
Publisher to publish propagation model data.
Pointer to the Scene.
Pointer the the SDF element for the sensor.
Desired time between updates, set indirectly by Sensor::SetUpdateRate.
Pointer to the world. | http://gazebosim.org/api/dev/classgazebo_1_1sensors_1_1WirelessTransmitter.html | CC-MAIN-2017-51 | refinedweb | 294 | 56.93 |
Fl_Input | +----Fl_Output | +----Fl_Multiline_Output
#include <FL/Fl_Output.H>
There is a single subclass, Fl_Multiline_Output, which allows you to display multiple lines of text.
The text may contain any characters except \0, and will correctly display anything, using ^X notation for unprintable control characters and \nnn notation for unprintable characters with the high bit set. It assumes the font can draw any characters in the ISO-Latin1 character set.
The second two forms change the text and set the mark and the point to the end of it. The string is copied to the internal buffer. Passing NULL is the same as "". This returns non-zero if the new value is different than the current one. You can use the second version to directly set the length if you know it already or want to put nul's in the text. | http://www.fltk.org/doc-1.1/Fl_Output.html | CC-MAIN-2017-47 | refinedweb | 139 | 64.81 |
#include <nng/protocol/reqrep0/req.h>
nng_req(7)
NAME
nng_req - request protocol
SYNOPSIS
DESCRIPTION
(protocol, req) The req protocol is one half of a request/reply pattern. In this pattern, a requester sends a message to one replier, who is expected to reply. The request is resent if no reply arrives, until a reply is received or the request times out.
(load-balancing)
The requester generally only has one outstanding request at a time unless
in raw mode (via
NNG_OPT_RAW),
and it will generally attempt to spread work requests to different peer repliers.
Socket Operations
The
nng_req0_open() functions create a requester socket.
This socket may be used to send messages (requests), and then to receive replies.
Generally a reply can only be received after sending a request.
(Attempts to receive a message will result in
NNG_ESTATE if there is no
outstanding request.)
Furthermore, only a single receive operation may be pending at a time.
Attempts to post more receive operations concurrently will result in
NNG_ESTATE.
Requests may be canceled by sending a different request. This will cause the requester to discard any reply from the earlier request, but it will not stop a replier from processing a request it has already received or terminate a request that has already been placed on the wire.
Context Operations
This protocol supports the creation of contexts for concurrent
use cases using
nng_ctx_open().
The
NNG_OPT_REQ_RESENDTIME value may be configured differently
on contexts created this way. following protocol-specific option is available.
NNG_OPT_REQ_RESENDTIME
(
nng_duration) When a new request is started, a timer of this duration is also started. If no reply is received before this timer expires, then the request will be resent. (Requests are also automatically resent if the peer to whom the original request was sent disconnects, or if a peer becomes available while the requester is waiting for an available peer.)
Protocol Headers
This protocol uses a backtrace in the header. This form uses a stack of 32-bit big-endian identifiers. There must be at least one identifier, the request ID, which will be the last element in the array, and must have the most significant bit set.
There may be additional peer IDs preceding the request ID. These will be distinguishable from the request ID by having their most significant bit clear.
When a request message is received by a forwarding node (see
nng_device()), the forwarding node prepends a
32-bit peer ID (which must have the most significant bit clear),
which is the forwarder’s way of identifying the directly connected
peer from which it received the message.
(This peer ID, except for the
most significant bit, has meaning only to the forwarding node itself.)
It may help to think of prepending a peer ID as pushing a peer ID onto the front of the stack of headers for the message. (It will use the peer ID it popped from the front to determine the next intermediate destination for the reply.)
When a reply message is created, it is created using the same headers that the request contained.
A forwarding node can pop the peer ID it originally pushed on the message, stripping it from the front of the message as it does so.
When the reply finally arrives back at the initiating requester, it should have only a single element in the message, which will be the request ID it originally used for the request. | https://nng.nanomsg.org/man/v1.3.2/nng_req.7.html | CC-MAIN-2021-04 | refinedweb | 567 | 52.7 |
Join the 85,000 open source advocates who receive our giveaway alerts and article roundups.
Join a new open source community at biicode
New open source dependency manager on the scene
opensource.com
Get the newsletter
When.
When biicode began, almost two years ago, many risks were taken by both the founders and investors. Our funders invested a lot of money with just a simple prototype in their hands. Our founders quit their safe and well-paying job positions at prestigious universities. The opportunity was huge though, because there are approximately 4 million C/C++ developers, and both languages represent up to almost 20% of the world's code. Moreover, these tools easily become standardized. Once the most popular and reused libraries of a specific programming language are handled with ease and effectiveness by a given dependency manager, this tool naturally becomes the standard.
Given these factors, we moved forward... but decided to keep the code private.
Competition
We knew we had a competitive advantage from the beginning: we are a file-based dependency manager, so there's no need to download humongous libraries or packages when you can point to the specific file you want to depend on and get it. We knew too that we were not alone in trying to provide a dependency manager to the C and C++ communities. RYPPL had existed for a while already, and not only is it an open source project, but its contributors are renowned developers.
To be honest: we were jealous.
We have always welcomed competition, and we thought that having such rivals would only motivate us. However, as open source software advocates and users we knew most part of the community would not only be with them but also contribute to that project. But, we keep seeing and noticing that there wasn't a day that went by in which an open source issue wasn't dealt with. Not only that, but a main purpose of the our tool is for rapid prototyping, and we believe in the pillars of the open source way.
By the end of the summer we knew what we had to do: we had to go open source.
Community
By that time, biicode had a supportive and growing community, and we had been featured on the International Organization for Standardization (ISO) committee's site. We were a relevant player in the sector! But, when "going open source" was brought up in our board meeting, it quickly became clear that everyone was not on the same page. It took the best of what we had to show the benefits of participating, building, and contributing to an open source community. We finally reached an agreement with the investors that said that once 10,000 users were signed up, we would release biicode’s code and welcome the community to its mantainement and improvement.
To some this may be a peculiar way to go open source, but maybe you know stories like it?
We are fully committed and have taken this on as a collective challenge. We are all open source users, advocates, and collaborators now.
Some say that C and C++ are old-school programming languages, so we chose Darth Vader++ to represent us; he might be old-school but he has staying power! See what we're all about, join us, maybe win yourself one of our "I am your father" Tshirts for your code contributions.
5 Comments
Jordi,
Thanks for the great article.
It is very exciting to see dependency tools for C/C++ emerging.
Thanks for sharing the rationale for embracing open source.
May the Force be with you!
Thank you Luis!! We really hope the community backs our project and we are able to move forward with them.
I'm completely unconvinced:
What do you do about namespace clashes ?
Ruby, Python, etc are lazy by design. C++ is not. If I need a library, I download it, and place it in my externals (3rd party, whatever). That way I have complete control. I certainly don't let a tool try to resolve my dependencies for me.
Totally respectful. To me that's a slow and inconvinient workflow. But the again, It's up you. I like my libs in the same space and my deps automatically managed.
Smit-Tay,
You bring a good point, that is worth thinking about; but not an insurmountable obstacle.
We don't need to fully relinquish control to the dependency tool. Yet we could get valuable support so we don't need to deal with the trivial dependency cases (e.g. I need jpeg or boost).
Confronted with a namespace clash, a dependency tool could simply report it to you (the developer), so that you can apply your higher-level knowledge of the interplay between libraries and your code. Maybe then you would resolve the ambiguity by providing additional hints in configuration files.
I would already be happy with a tool that resolves 19 out of the 20 dependencies of my code, and that hints me to figure out a way to disambiguate the remaining one that can not be solved automatically. | https://opensource.com/business/15/1/biicode-open-source-dependency-manager | CC-MAIN-2018-22 | refinedweb | 855 | 63.7 |
WebKit Bugzilla
Folks -
I've attached a testcase that shows that localStorage, as its currently implemented, is not working for pages loaded from file:// URLs or from a local web server (i.e. 'localhost').
I filed a comment on this Mozilla bug (comment #9) wherein I note that the HTML5 specification has the concept of a 'file://' origin - therefore this feature should work for these kinds of origins too.
No idea why '' is failing.
Obviously, the way to run this testcase is to bring the page up, set the value, verify that the value is set, quit your browser, restart and click the button to show the value.
Thanks!!
Cheers,
- Bill
Created attachment 23229 [details]
Testcase showing localStorage not working for file:// or URLs
Forgot to attach the Mozilla bug URL (my comment is #9)
Cheers,
- Bill
As far as I can tell, each file:// url should be its own origin. Can you please confirm this is correct?
I'll look into fixing this in the next couple days (or possibly as part of this work:).
(In reply to comment #3)
> As far as I can tell, each file:// url should be its own origin. Can you
> please confirm this is correct?
That is incorrect. All file URLs inhabit the same origin. Yes, that's a bit unfortunate.
That is unfortunate.
FYI, this is why I thought it might be per file: I guess Mozilla is breaking from the spec?
(In reply to comment #5)
> FYI, this is why I thought it might be per file:
> I guess
> Mozilla is breaking from the spec?
Many of the browser vendors would like to lock down file URL access more. Mozilla is experimenting with a tighter security policy. My understanding is that their experiment is fairly successful. It might be getting to be time to revisit this issue more broadly. For this patch, though, we should stick with WebKit's current security policy. We can always change it later if and when we revise the access policy for file URLs in general.
(As for what the specs say, they are silent on this point. More precisely, they say the behavior is implementation-defined.)
I tried this out on my mac with the nightly build and it all works as expected (including all files sharing the same localStorage namespace). I don't think there's anything left to do here, but I don't have permissions to close the bug.
Marking as fixed per comment #7. | https://bugs.webkit.org/show_bug.cgi?id=20701 | CC-MAIN-2016-30 | refinedweb | 413 | 72.66 |
In this module of Python tutorial, we will learn about Python comments. We will also learn about the different types of Python comments and the way to use them.
Writing Python Comments
Comments in any programming language are used to increase the readability of the code. Similarly, in Python, when the program starts getting complicated, one of the best ways to maintain the readability of the code is to use Python comments. It is considered a good practice to include documentations and notes in the python syntax since it makes the code way more readable and understandable to other programmers as well, which comes in handy when multiple programmers are simultaneously working on the same project.
The code can only explain how it does something and not why it does that, but Python comments can do that. With Python comments, we can make documentations for various explanations in our code itself.
Interested in learning Python? Enroll in our Python Course in Bangalore now!
In this module, we will delve deeper into the concept of comments in Python. Following is the list of topics that are covered in this module.
So, without any further delay, let’s get started.
How to Comment in Python
Lets see how to comment in Python now. Comments are nothing but tagged lines of codes which increase the readability of a code and make it self-explanatory. There are different ways of creating comments depending on the type of comment we want to include in our code. Following are different kinds of comments that can be included in our Python program:
- Single Line Comments
- Docstring Comments
- Multiline Comments
Let’s discuss each one of the above-mentioned comment types, separately.
Single line Python comments are marked with # character. These comments end at the end of the physical line, which means that all characters starting after the # character (and lasts till the end of the line) are part of the comment.
Example:
test= 7 * 2 print (test) #Single-line comment Output: 14
Python has the documentation strings (or docstrings) feature which is usually the first statement included in functions and modules. Rather than being ignored by the Python Interpreter like regular comments, docstrings can actually be accessed at the run time using the dot operator.
It gives programmers an easy way of adding quick notes with every Python module, function, class, and method. To use this feature, we use triple quotes in the beginning of the documentation string or comment and the closing triple quotes at the end of the documentation comment. Docstrings can be one-liners as well as multi-liners.
Example:
def SayFunction(): ”’ Strings written using ”’_”’ after a function represents docstring of func Python docstrings are not comments ”’ print(“just a docstring”) print(“Let us see how to print the docstring value”) print(theFunction.__doc__)
Enrol yourself in Online Python Training in Sydney and give a head-start to your career in Python Programming!
Multiline Comment in Python
Unlike some programming languages that support multiline comments, such as C, Java, and more, there is no specific feature for multiline comments in Python. But that does not mean that it is totally impossible to make multiline comments in Python. There are two ways we can include comments that can span across multiple lines in our Python code.
- Python Block Comments: We can use several single line comments for a whole block. This type of comment is usually created to explain the block of code that follows the Block comment. Python Block comment is the only way of writing a real comment that can span across multiple lines. It is supported and preferred by Python’s PEP8 style guide since Block comments are ignored by Python interpreter or parser. However, nothing is stopping programmers from using the second ‘non-real’ way of writing multiline comments in Python which is explained below.
- Using Docstrings: Docstrings are largely used as multiline comments in Python by many programmers since it is the closest thing to having a multiline comment feature in Python. While it is not wrong to use docstrings when we need to make multiline comments, it is important to keep in mind that there is a significant difference between docstrings and comments. Comments in Python are totally ignored by the Python Interpreter, while docstrings, when used inside the Python function, can be accessed at the run time.
test1= 7 * 2 type(test1) ”’ line one line two line three ”’ Output: 14 line one line two line three
This brings us to the end of this module in Python Tutorial. The next module highlights Python data types. Let’s meet there!
Further, check our Python course and prepare to excel in career with our free Python interview questions listed by the experts. | https://intellipaat.com/blog/tutorial/python-tutorial/python-comments/ | CC-MAIN-2019-51 | refinedweb | 793 | 60.24 |
hello all. i am working on the Fibonacci sequence constructor and i was wondering if i posted wha ti have so far if you could tell me if im on the right trac or not and maybe give me a few pointers to help me get it right heres what i have for code and the assignment so you can see what i have to do
public class FibonacciGenerator { public static int fib(int n) { int fold1=0, fold2=1; public getNumber() for(int i=0; i<n; i++) { int savefold1 = fold1; fold1 = fold2; fold2 = savefold1 + fold2; } return fold1; } }
Write a program that prompts the user for n and prints the nth value in the Fibonacci sequence. Use a class FibonacciGenerator with a method nextNumber .
There is no need to store all values for fn. You only need the last two values to compute the next one in the series:
fold1 = 1;
fold2 = 1;
fnew = fold1 + fold2;
After that, discard fold2 , which is no longer needed, and set fold2 to fold1 and fold1 to fnew . | http://www.javaprogrammingforums.com/algorithms-recursion/363-problem-generating-fibonacci-sequence-java.html | CC-MAIN-2015-32 | refinedweb | 175 | 53.92 |
— You can find the source code for this blog series here .
Over the last several months, I’ve been looking for ways to produce physical outputs from my generative code. I’m interested in the idea of developing real, tangible objects that are no longer bound by the generative systems that shaped them. Eventually I plan to experiment with 3D printing, laser cutting, CNC milling, and other ways of realizing my algorithms in the real-world.
My interest in this began in March 2017, when I purchased my first pen plotter: the AxiDraw V3 by Evil Mad Scientist Laboratories. It’s a fantastic machine, and has opened a whole new world of thinking for me. For those unaware, a pen plotter is a piece of hardware that acts like a robotic arm on which you can attach a regular pen. Software sends commands to the device to raise, reposition, and lower its arm across a 2D surface. With this, the plotter can be programmed to produce intricate and accurate prints with a pen and paper of your choice.
— Early prints, March 2017.
Often, these plotters and mechanical devices are controlled by G-code: a file format that specifies how the machine should lift, move, and place itself over time. For convenience, AxiDraw handles most of the mechanical operation for you, providing an Inkscape SVG plugin that accepts paths, lines, shapes, and even fills (through hatching).
— Tesselations, August 2017
You don’t need to be a programmer to use the AxiDraw pen plotter. You can create SVG files in Adobe Illustrator or find SVGs online to print. However, the machine is very well suited to programmatic and algorithmic line art, as it can run for hours at a time and produce incredibly detailed outputs that would be too tedious to illustrate by hand.
One recent series I developed, Natural Systems , is composed of 4 different algorithms. Each time these algorithms run, they produce different outputs, allowing for an infinite number of unique prints.
— Natural Systems, November 2017
This isn’t a new concept; Vera Molnár, an early pioneer of computer art, was rendering pen plotter prints in the 1960s!
— Vera Molnár, No Title, 1968
In this post, I’ll try to explain some of my workflow when developing new pen plotter prints, and show some of the tools I’ve been building to help organize my process.
Development Environment
So far, all of my work with the AxiDraw has been with JavaScript and an experimental tool I’ve been building, aptly named penplot . The tool primarily acts as a development environment, making it easier to organize and develop new prints with minimal configuration.
:rotating_light: This tool is highly experimental and subject to change as my workflow evolves.
You can try the tool out yourself with
# install the CLI app globally npm install penplot -g # run it, generating a new file and opening the browser penplot test-print.js --write --open
The
--write flag will generate a new
test-print.js file and
--open will launch your browser to
localhost:9966 . It starts you off with a basic print:
:pencil2: See here to see the generated source code of this print.
The generated
test-print.js file is ready to go; you can edit the ES2015 code to see changes reflected in your browser. When you are happy, hit
Cmd + S (save PNG) or
Cmd + P (save SVG) to export your print from the browser.
Geometry & Primitives
For algorithmic work with AxiDraw and its SVG plugin, I tend to distill all my visuals into a series of polylines composed of nested arrays.
const lines = [ [ [ 1, 1 ], [ 2, 1 ] ], [ [ 1, 2 ], [ 2, 2 ] ] ]
This creates two horizontal lines in the top left of our print, each 1 cm wide. Here, points are defined by
[ x, y ] and a polyline (i.e. path) is defined by the points
[ a, b, c, d, .... ] . Our list of polylines is defined as
[ A, B, ... ] , allowing us to create multiple disconnected segments (i.e. where the pen lifts to create a new line).
:triangular_ruler: Penplot scales the Canvas2D context before drawing, so all of your units should be in centimeters.
So far, the code above doesn’t feel very intuitive, but you will hardly ever hardcode coordinates like this. Instead, you should try to think in geometric primitives: points, squares, lines, circles, triangles, etc. For example, to draw some squares in the centre of the print:
// Function to create a square const square = (x, y, size) => { // Define rectangle vertices const path = [ [ x - size, y - size ], [ x + size, y - size ], [ x + size, y + size ], [ x - size, y + size ] ]; // Close the path path.push(path[0]); return path; }; // Get centre of the print const cx = width / 2; const cy = height / 2; // Create 12 concentric pairs of squares const lines = []; for (let i = 0; i < 12; i++) { const size = i + 1; const margin = 0.25; lines.push(square(cx, cy, size)); lines.push(square(cx, cy, size + margin)); }
Once the lines are in place, they are easy to render to the Canvas2D context with
beginPath() and
stroke() , or save to an SVG with the
penplot utility,
polylinesToSVG() .
The result of our code looks like this:
:pencil2: See here for the final source code of this print.
This is starting to get a bit more interesting, but you may be wondering why not just reproduce this by hand in Illustrator. So, let’s see if we can create something more complex in code.
Delaunay Triangulation
A simple starting task would be to explore Delaunay triangulation . For this, we will use delaunay-triangulate , a robust triangulation library by Mikola Lysenko that works in 2D and 3D. We will also use the new-array module, a simple array creation utility.
Before we begin, you’ll need to install these dependencies locally:
# first ensure you have a package.json in your folder npm init -y # now you can install the required dependencies npm install delaunay-triangulate new-array
In our JavaScript code, let’s
import some of our modules and define a set of 2D points randomly distributed across the print, inset by a small margin.
We use the built-in penplot
random library here, which has the function
randomFloat(min, max) for convenience.
import newArray from 'new-array'; import { randomFloat } from 'penplot/util/random'; // ... const pointCount = 200; const positions = newArray(pointCount).map(() => { // Margin from print edge in centimeters const margin = 2; // Return a random 2D point inset by this margin return [ randomFloat(margin, width - margin), randomFloat(margin, height - margin) ]; });
:bulb: I often use
new-array and
map to create a list of objects, as I find it more modular and functional than a for loop.
If we were to visualize our points as circles, it might look like this:
The next step is to triangulate these points, i.e. turn them into triangles. Simply feed the array of points into the
triangulate function and it returns a list of “cells.”
import triangulate from 'delaunay-triangulate'; // ... const cells = triangulate(positions);
The return value is an array of triangles, but instead of giving us the 2D positions of each vertex in the triangle, it gives us the index into the
positions array that we passed in.
[ [ 0, 1, 2 ], [ 2, 3, 4 ], ... ]
For example, to get the 3 vertices of the first triangle:
const triangle = cells[0].map(i => positions[i]); // log each 2D point in the triangle console.log(triangle[0], triangle[1], triangle[2]);
For our final print, we want to map each triangle to a polyline that the pen plotter can draw out.
const lines = cells.map(cell => { // Get vertices for this cell const triangle = cell.map(i => positions[i]); // Close the path triangle.push(triangle[0]); return triangle; });
Now we have all the lines we need to send the SVG to AxiDraw. In the browser, hit
Cmd + S and
Cmd + P to save a PNG and SVG file, respectively, into your Downloads folder.
For reference, below you can see how our original random points have now become the vertices for each triangle:
:bulb: The
random module includes a
setSeed(n) function, which is useful if you want predictable randomness every time the page reloads.
If we increase the
pointCount to a higher value, we start to get a more well-defined edge, and potentially a more interesting print.
:pencil2: See here for the final source code of this print. | http://colabug.com/2117618.html | CC-MAIN-2018-05 | refinedweb | 1,397 | 61.26 |
emulab-devel:bbb73ca6f7dacf27223b994fabb108c3dfef06b8 commits 2017-08-07T16:00:56-06:00 We need to get rid of this! Since BSD jail days we have attempted to partition up the UDP/TCP port range among vnodes as jails and their host shared the same namespace. Originally we supported a range of 256 per experiment which wound up limiting the number of experiments we could instantiate. In order to get a class up and running where we expected a large number of single-vnode experiments, I reduced the range to 32 to allow more experiments, forgetting that we pick a unique port per-vnode from that range to use for sshd. So as a result I limited the number of vnodes per experiment to 32! Did I mention that we need to eviscerate this mechanism with extreme prejudice? <a href="/emulab/emulab-devel/-/issues/323" data-#323</a>.. Rip out some 0-ed out robot code. 2017-07-25T09:11:09-06:00 Mike Hibler hibler@cs.utah.edu A nit that I didn't want getting mixed up with a later meaningful commit. Allow file:// urls for the metdata and image URLs so that offline 2017-07-24T16:53:37-06:00 Leigh B Stoller stoller@flux.utah.edu sites can work around being offline. Add comment. 2017-07-24T16:53:37-06:00 Leigh B Stoller stoller@flux.utah.edu Remove debugging override of PORTAL_ENABLE. 2017-07-17T12:42:28-06:00 Leigh B Stoller stoller@flux.utah.edu Chomp the newline in the ssh pubkey (see previous revision). 2017-07-14T14:40:00-06:00 Leigh B Stoller stoller@flux.utah.edu Return idlestats for active *and* quarantined experiments. 2017-07-14T11:39:09-06:00 Leigh B Stoller stoller@flux.utah.edu Handle error when graphs ajax call fails. 2017-07-14T11:38:31-06:00 Leigh B Stoller stoller@flux.utah.edu Work on issue #302: 2017-07-13T17:54:23-06:00 Leigh B Stoller stoller@flux.utah.edu(); Minor fix. 2017-07-13T07:06:32-06:00 Leigh B Stoller stoller@flux.utah.edu Revert this part of previous commit. not supposed to go in. 2017-07-12T17:42:14-06:00 Leigh B Stoller stoller@flux.utah.edu Improvements to the protogeni fcgid handler: 2017-07-12T16:51:07-06:00 Leigh B Stoller stoller@flux.utah.edu *. Reset a couple of global variables back to default state when 2017-07-12T16:51:07-06:00 Leigh B Stoller stoller@flux.utah.edu invoked (as for long running fcgid daemon). Minor cleanup, reset a couple of global variables back to default state 2017-07-12T16:51:07-06:00 Leigh B Stoller stoller@flux.utah.edu when invoked (as for long running fcgid daemon). One "last" tweak for FBSD 10 install. 2017-07-12T16:16:36-06:00 Mike Hibler hibler@cs.utah.edu Recognize that you must use FBSD 10 kernel in FBSD 10 MFS. 2017-07-12T15:59:27-06:00 Mike Hibler hibler@cs.utah.edu | https://gitlab.flux.utah.edu/emulab/emulab-devel/-/commits/bbb73ca6f7dacf27223b994fabb108c3dfef06b8?format=atom | CC-MAIN-2022-05 | refinedweb | 505 | 53.17 |
OneNote 2013 Text Importer.zip
Hi John, any chance you'd share the source for this updated version? I've written a store app which imports evernote files to OneNote via the API but it can't do headers. It seems like whatever code you're using is pulling in headers just fine. I know it (probably) won't work for windows store apps but I'd like to write an importer like yours for evernote files.
the code is here: blogs.msdn.com/…/source-code-for-the-text-importer-for-onenote.aspx
It uses the 2007 namespace IIRC – the only changes I made over time were updates to the namespace for new versions of OneNote.
I just found this tool via a Google search for "import text files to Onenote." I can't wait to try this.
I have OneNote 2010 on one machine, and OneNote 2013 on another, and I could use either machine to do my importing. (I'll be importing into a notebook on OneDrive.)
Do you have any suggestion for whether I should use 2010 vs. 2013?
Thanks.
Either should work. They are essentially the exact same tool – one just uses the 2010 namespace and the other 2013.
Thanks! Worked great.
Downloaded and initiated .exe okay, but after browsing for the folder with the text files I wanted to import, the app would go no further. Applying it to OneNote 2010.
You need the 2010 importer instead of 2013: blogs.msdn.com/…/the-text-importer-powertoy-gets-updated-for-onenote-2010.aspx
(I still need to update this to import to either app).
Thanks for this tool – worked like a champ!
Seems like this ought to be a feature already built into OneNote.
Or at least a mechanism to transfer Outlook notes directly to OneNote
Wow! Worked like a charm. THANK YOU!!!!!!!
Niiiiice!!! Thank you!!!! You're the man!
Exactly what I needed – genius! Thanks.
Thanks – you saved me a lot of work!
Great!! can delete the files once the import is complete?
Nice idea, but this tool doesn't support local codepages (aka ANSI). It imports mojibake.
This was SUCH a super help – thanks for your time and energy John!!! | https://blogs.msdn.microsoft.com/johnguin/2014/03/07/a-second-final-beta-of-the-text-file-importer-for-onenote-2013/ | CC-MAIN-2017-22 | refinedweb | 366 | 85.59 |
How to play music on the background while running a MIDlet
This article explains how to play music in your MIDlet, and the effects of running a MIDlet (both with and without music player functionality) while the device music player is running.
Series 40
Series 40 DP 2.0
Introduction
Series 40 devices can often run MIDlets while using the device music player to play audio in the background - although this may slow down MIDlet execution, and in lower end/older devices may not be possible at all! If the MIDlet plays audio the background device music player will stop. Depending on how the MIDlet code is written, the background music may restart when the MIDlet stops playing the file or it may restart only when the MIDlet is closed.
This article shows how to implement audio playback using the Mobile Media API (JSR-135), and how to control whether or not background audio is restarted after the MIDlet player finishes (using MMAPI Player states).
How to play an MP3 file
MMAPI uses the Player class and several controls for managing and controlling playback. VolumeControl is used for controlling the playback volume.
The following code shows how to play a local MP3 file:
try {
InputStream is = getClass().getResourceAsStream("/song.mp3");
if (player == null) player = Manager.createPlayer(is, "audio/mp3");
player.addPlayerListener(this);
player.realize();
vc = (VolumeControl)player.getControl("VolumeControl");
player.start();
} catch (IOException ioe) {
// Exception handling
} catch (MediaException me) {
// Exception handling
}
There is more detail on using the VolumeControl in the article MIDlet volume control in Series 40 and S60 devices.
MMAPI Player life cycle
A Player has five states: UNREALIZED, REALIZED, PREFETCHED, STARTED, CLOSED. These states are defined in the MMAPI specification and they provide programmatic control over operations.
The image below explains the states and the state transition methods of the Player. Understanding the Player states is important for having control of the resources your MIDlet is reserving and also for minimizing the lag time before playback starts.
How to check for current Player state
Player events can be used for checking the current state of the Player:
// The MIDlet must implement PlayerListener and PlayerListener must be added to the player
public class PlayerTest extends MIDlet implements CommandListener, ItemStateListener, PlayerListener {
...
player.addPlayerListener(this);
...
public void playerUpdate(Player player, String event, Object eventData) {
if (player.equals(myPlayer)) {
System.out.println("event: " + event);
if (event.equals("volumeChanged")) {
// Do something with the volume change.
}
}
}
How to allow background audio to restart
Background audio will restart if the Player is closed, and all resources are released:
player.close(); // Player closes and goes to CLOSED state.
Background audio will not resume if the Player is "stopped"
try {
player.stop(); // Player stops and it goes to PREFETCHED state.
} catch (MediaException me) {
}
Verifying background player behaviour when running a MIDlet
The PlayerTest MIDlet can be used for demonstrating how background music is affected by the player state. The MIDlet plays back an MP3 file included in the MIDlet JAR file. There are commands for stopping the playback (Player goes to PREFETCHED state) or closing the Player (Player goes to CLOSED state).
The stopping behaviour can be tested using the following steps.
- Start the music player first and start playing a music file.
- Put the music player to background.
- Start the PlayerTest MIDlet and select Play command to start MIDlet audio playback.
- When the music starts, the music player stops its playback.
The restart behaviour can be tested using either of the following steps.
- Select Stop in the MIDlet. Music playback is stopped (Player goes to PREFETCHED state). The background music player does NOT continue playback.
- Select Close in the MIDlet. Music playback is stopped (Player goes to CLOSED state) and the background music player continues playback.
The image below shows, how the Player states are shown in the MIDlet UI:
Example application
PlayerTest.zip containing sources, PlayerTest.jad and PlayerTest.jar
Hamishwillee - Subedited/Reviewed
Hi
I have reviewed and subedited this, mostly for structure and clarity. Mosty I wanted to make it more clear in the introduction what the article covers. I also think it helps to spell out what you need to do to ensure playback resumes /stops rather than explaining this in the section on verifying the behaviour (hence split it out into its own section).
Can you please confirm you are happy with the changes and it still captures what you wanted to say.
Thanks for the article - I think it is both interesting and useful.
RegardsHamish
hamishwillee 14:15, 23 April 2013 (EEST) | http://developer.nokia.com/community/wiki/How_to_play_music_on_the_background_while_running_a_MIDlet | CC-MAIN-2014-15 | refinedweb | 752 | 56.25 |
Hi all,
I’m a bit stuck with optix prime at the moment. I’ve basically used all of the API calls from the examples, and hardcoded a single triangle into my test program. I still can’t get a hit. My code is below, can anyone tell me what I am doing wrong ? I’m running out of things to try ;)
I compiled it using:
nvcc -std=c++11 -I/opt/optix/NVIDIA-OptiX-SDK-3.6.3-linux64/include -L/opt/optix/NVIDIA-OptiX-SDK-3.6.3-linux64/lib64 -loptix -loptix_prime test.cpp -o test
#include <optix_prime/optix_primepp.h> #include <vector_types.h> #include <iostream> using Hit = struct HitStruct { float t; int triId; float u; float v; }; using Ray = struct RayStruct { float3 origin; float tmin; float3 dir; float tmax; }; optix::prime::Context context; optix::prime::Model model; int main(void) { using namespace optix::prime; context = Context::create(RTP_CONTEXT_TYPE_CPU); model = context->createModel(); float3 v1 {0, 3, 1}; float3 v2 {-1, 3, -0.5}; float3 v3 {1, 3, -0.5}; float3 vlist[3] = {v1, v2, v3}; int3 t1 {1, 2, 3}; const int num_tris = 1; const int num_vertices = 3; model->setTriangles(num_tris, RTP_BUFFER_TYPE_HOST, &t1, num_vertices, RTP_BUFFER_TYPE_HOST, &vlist); model->update( 0 ); // generate a ray at the origin in the y direction float3 origin {0, 0, 0}; float3 direction {0, 1, 0}; Ray r {origin, 0, direction, 1e8}; Hit h; const int num_rays = 1; const int num_hits = 1; Query query = model->createQuery(RTP_QUERY_TYPE_CLOSEST); query->setRays(num_rays, RTP_BUFFER_FORMAT_RAY_ORIGIN_TMIN_DIRECTION_TMAX, RTP_BUFFER_TYPE_HOST, &r); query->setHits(num_hits, RTP_BUFFER_FORMAT_HIT_T_TRIID_U_V, RTP_BUFFER_TYPE_HOST, &h); query->execute(0); std::cout << h.t << std::endl; std::cout << h.triId << std::endl; std::cout << h.u << std::endl; std::cout << h.v << std::endl; }
and for me, it prints out
-1 -1 0 0
I’m using CUDA 6.5 and Optix 3.6.3 on Ubuntu 14.04 x64 with the default gcc (4.8.2). I have compiled the SDK examples and they seem to work fine.
I’ve also attached two screenshots from meshlab that show the triangle should be hit by a ray from the origin in the y direction.
Thanks!
Edit: I have spent the last day trying to get CUDA6.0 running to test it with as another poster mentioned that OptiX was not compatible with CUDA6.5 (I couldn’t get it working). But while Nvidia don’t support running CUDA 6.0 on 14.04, Ubuntu don’t support 13.04 anymore. So I’m not really sure what to do here. Though, I don’t have the ability to replace the operating system anyway as this is a remote computer I am working on.
It doesn’t seem to me that CUDA 6.5 is the problem though, because I get no warnings/linker errors/exceptions.
Edit Edit: I got CUDA6.0 installed on 14.04 and the program behaves identically to CUDA6.5. So that isn’t the problem. | https://forums.developer.nvidia.com/t/cant-get-optixprimepp-to-register-a-really-simple-hit-sample-program-inside/35059 | CC-MAIN-2022-21 | refinedweb | 485 | 59.7 |
URLs Lead The Way
Matt Layman
・12 min read
Understand Django (3 Part Series).
That explain where the file resides, but it doesn't tell us much about how it works. Let's dig in more.
URLconf In Action
Try to think of the URL configuration as a list of URL paths that Django will attempt to match from top to bottom. When Django finds a matching path, the HTTP request will route to a chunk of Python code that is associated with that path. That "chunk of Python code" is called a view which we will explore more in a bit. For the moment, trust that views know how to handle HTTP requests.
We can use an example URLconf to bring this to life.
# project/urls.py from django.urls import path from application import views urlpatterns = [ path("", views.home), path("about/", views.about), path("contact/", views.contact), path("terms/", views.terms), ]
What's here matches well with the description that I described above: a list of URL paths that Django will try to match from top to bottom. The key aspect of this list is the name
urlpatterns. Django will treat the list in a
urlpatterns variable as the URLconf.
The order on this list is also important. The example doesn't show any conflict between paths, but it's possible to create two different
path entries that can match the same URL that a user submits. I'll show an example of how that can happen after we see another aspect of paths.
We can work through this example to see how this would work for. When considering a URL in a URLconf, Django does not use the scheme (
https://), the domain (), and the leading slash for matching. Everything else is what the URLconf will match against.
- A request to look like
"about/"to the pattern matching process and match the second
path. That request would route to the
views.aboutview.
- A request to look like
""to the pattern matching process and match the first
path. That request would route to the
views.homeview.
Aside: You might notice that Django URLs end with a slash character. In fact, if you attempt to reach a URL like, Django will redirect the request to the same URL with the slash appended because of the
APPEND_SLASHdefault setting. This behavior is because of a Django design philosophy choice.
The
path Before Us
If all I gave you was the example above, I wouldn't fault you if you thought "Wow, Django is dumb. Why isn't
urlpatterns a dictionary like below?"
urlpatterns = { "": views.home, "about/": views.about, "contact/": views.contact, "terms/": views.terms, }
The reason is that
path has more power than I initially revealed. Most of that power is in the first string parameter passed to the function. The string part of
path (e.g.,
"about/") is called the route.
A route can be a plain string as you've seen, but it can include other special structure with a feature called converters. When you use a converter, you can extract information out of a URL that a view can use later. Consider a path like this:
path("blog/<int:year>/<slug:slug>/", views.blog_post),
The two converters in this path are:
<int:year>
<slug:slug>
The use of angle brackets and some reserved names cause Django to attempt extra parsing on a URL. Each converter has some expected rules to follow.
- The
intconverter must match an integer.
- The
slugconverter must match a slug. Slug is a bit of newspaper lingo that appears in Django because Django started as a project out a newspaper in Kansas. A slug is a string that can include characters, numbers, dashes, and underscores.
Given those converter definitions, let's compare to some URLs!- MATCH!- NOPE.- MATCH! Uh, maybe not what we wanted though. Let's look at that soon.
Now we can revisit our ordering problem from earlier. Consider these two paths in different orders:
path("blog/<int:year>/", views.blog_by_year), path("blog/2020/", views.blog_for_twenty_twenty), # vs. path("blog/2020/", views.blog_for_twenty_twenty), path("blog/<int:year>/", views.blog_by_year),
In the first ordering, the converter will match any integer following
blog/, including. That means that the first ordering will never call the
blog_for_twenty_twenty view because Django matches
path entries in order.
Conversely, in the second ordering,
blog/2020/ will route to
blog_for_twenty_twenty properly because it is matched first. That means there's a lesson to remember here:
When including
pathentries that match on ranges with converters, be sure to put them after the more specific entries.
An Abbreviated View Of Views
What do converters do with this extra data? That's hard to explain without touching on views. The next article will cover views in far more depth, but here's a primer.
A view is code that takes a request and returns a response. Using Python's optional type checking, here's an example that will send a
Hello World response.
from django.http import HttpRequest, HttpResponse def some_view(request: HttpRequest) -> HttpResponse: return HttpResponse('Hello World')
The
HttpRequest is Django's translated format of an HTTP request wrapped up in a convenient container class. Likewise,
HttpResponse is what we can use so that Django will translate our response data into a properly formatted HTTP response that will be sent back to the user's browser.
Now we can look at one of the converters again.
path("blog/<int:year>/", views.blog_by_year),
With this converter in place in the route, what would
blog_by_year look like?
# application/views.py from django.http import HttpResponse def blog_by_year(request, year): # ... some code to handle the year data = 'Some data that would be set by code above' return HttpResponse(data)
Django begins to reveal some nice qualities here! The converter did a bunch of tedious work for us. The
year argument set by Django will already be an integer because Django did the string parsing and conversion.
If someone submits
/blog/not_a_number/, Django will return a Not Found response because
not_a_number can't be an integer. The benefit of this is that we don't have to put extra checking logic in
blog_by_year to handle the weird case where
year doesn't look like a number. That kind of feature is real time saver! It keeps your code cleaner and is makes handling more precise.
What about that other strange example that we saw earlier of
/blog/0/life-in-rome/? That would match our pattern from the earlier section, but let's assume we want to match a four digit year. How can we do that? We can use regular expressions.
Regular Expressions Paths
Regular expressions are a programming feature often likened to a chainsaw: they are incredibly powerful, but you can cut off your foot if you're not careful.
Regular expressions can express complex relationships and match patterns in a very concise way. This conciseness often gives regular expressions a bad reputation of being impossible to understand. When used carefully though, they can be a great tool for a job.
One job that a regular expression (which is often abbreviated to "regex") is suited for is matching complex patterns in strings. This sounds exactly like our blog year problem! In our problem, we want to match a four digit integer only. Let's look at a solution that Django can handle and then break down what it means.
As a reminder, this solution will match some URL path like
blog/2020/urls-lead-way/.
re_path("^blog/(?P<year>[0-9]{4})/(?P<slug>[\w-]+)/$", views.blog_post),
This crazy string behaves exactly like our earlier example except that it is more precise about only allowing four digit years. The crazy string also has a name. It is called a regex pattern. When the Django code runs, it will test URL paths against the rules that are defined in this pattern.
To see how it works, we have to know what the parts of the pattern mean. We can explain this pattern one chunk at a time.
- The caret,
^, means "the pattern must start here." Because of the caret, a path that starts like
myblog/...will not work.
blog/is a literal interpretation. Those characters must match exactly.
- The portion inside parentheses
(?P<year>[0-9]{4})is a capture group. The
?P<year>is the name to associate with the capture group and is similar to the right side of the colon in a converter like
<int:year>. The name allows Django to pass on the content in an argument called
yearto the view. The other part of the capture group,
[0-9]{4}, is what the pattern is actually matching.
[0-9]is a character class which means "match any number from 0 through 9." The
{4}means that it must match exactly four times. This is the specificity that
re_pathgives that the
intconverter could not!
- The slash,
/, between capture groups is another literal character to match.
- The second capture group,
(?P<slug>[\w-]+), will put whatever it matches into an argument named
slug. The character class of
[\w-]contains two types of characters.
\wmeans any word character that you might have in a natural language. The other type of character is a literal dash,
-, character. Finally, the plus,
+, character means that the character class must match 1 or more times.
- The last slash is also a literal character match.
- To complete the pattern, the dollar sign,
$, acts like the opposite of the caret and means "the pattern must end here." Thus,
blog/2020/some-slug/another-slug/will not match.
Congratulations! This is definitely the hardest section of this article. If you understood what we did with
re_path, the rest of this should feel very comfortable. If not, please don't fret about it! If you want to know more about regular expressions, know that everything I described in the pattern is not Django specific. Instead, this is Python's built-in behavior. You can learn more about regular expressions from Python's Regular Expression HOWTO.
Knowing that this power with
re_path is there may help you later on your Django journey, even if you don't need it today.
Grouping Related URLs
Up to this point, we've looked at individual routes that you can map in a URLconf. What can we do when a related group of views should share a common path? Why would we want to do this?
Let's imagine you're building an educational project. In your project, you have schools, students, and other education related concepts. You could do something like:
# project/urls.py from django.urls import path from schools import views as schools_views from students import views as students_views urlpatterns = [ path("schools/", schools_views.index), path("schools/<int:school_id>/", schools_views.school_detail), path("students/", students_views.index), path("students/<int:student_id>/", students_views.student_detail), ]
This approach would work fine, but it forces the root URLconf to know about all the views defined in each app,
schools and
students. Instead, we can use
include to handle this better.
# project/urls.py from django.urls import include urlpatterns = [ path("schools/", include("schools.urls"), path("students/", include("students.urls"), ]
Then, in each application, we would have something like:
# schools/urls.py from django.urls import path from schools import views urlpatterns = [ path("", views.index), path("<int:school_id>/", views.school_detail), ]
The use of
include gives each Django app autonomy in what views it needs to define. The project can be blissfully "ignorant" of what the application is doing.
Additionally, the repetition of
schools/ or
students/ is removed from the first example. As Django processes a route, it will match on the first portion of the route and pass the remainder onto the URLconf that is defined in the individual app. In this way, URL configurations can form a tree where the root URLconf is where all requests start, but individual applications can handle the details as a request is routed to the proper app.
Naming URLs
We've looked at the main ways that URLs get defined with
path,
re_path, and
include. There is another aspect to consider. How can we refer to URLs in other places in the code? Consider this (rather silly) view:
# application/views.py from django.http import HttpResponseRedirect def old_blog_categories(request): return HttpRequestRedirect("/blog/categories/")
A redirect is when a user tries to visit a page and is sent somewhere else by the browser. There are much better ways to handle redirects than this example shows, but this view illustrates a different point. What would happen if you want to restructure the project so that blog categories moved from
/blog/categories/ to
/marketing/blog/categories/? In the current form, we would have to fix this view and any other view that referenced the route directly.
What a waste of time! Django gives us tools to give paths names that are independent from the explicit route. We do this with the
name keyword argument to
path.
# project/urls.py from django.urls import path from blog import views as blog_views urlpatterns = [ ... path("/marketing/blog/categories/", blog_views.categories, name="blog_categories"), ... ]
This gives us
blog_categories as an independent name from the route of
/marketing/blog/categories/. To use that name, we need
reverse as its counterpart. Our modified view looks like:
# application/views.py from django.http import HttpResponseRedirect from django.urls import reverse def old_blog_categories(request): return HttpRequestRedirect(reverse("blog_categories"))
The job of
reverse is to look up any path name and return its route equivalent. That means that:
reverse("blog_categories") == "/marketing/blog/categories/"
At least until you want to change it again. 😁
When Names Collide
What happens if you have multiple URLs that you want to give the same
name? For instance,
index or
detail are common names that you may want to apply. We can turn to The Zen of Python for advice.
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
...
Namespaces are one honking great idea -- let's do more of those!
Namespaces might be new to you if you haven't been programming long. They are a shared space for names. Maybe that's clear, but I recall struggling with the concept when I first began to write software.
To make an analogy to something in the real world, let's use trusty buckets. Imagine you have two red balls and two blue balls. Put one color ball in one of two buckets labeled "A" and "B." If I wanted a specific blue ball, I can't say "please give me the blue ball" because that would be ambiguous. Instead, to get a specific ball, I would need to say "please give me the blue ball in bucket B." In this scenario, the bucket is the namespace.
The example that we used for schools and students can help illustrate this idea in code. Both apps had an
index view to represent the root of the respective portions of the project (i.e.,
schools/ and
students/). If we wanted to refer to those views, we'd try to pick the easiest choice of
index. Unfortunately, if you pick
index, then Django can't tell which one is the right view for
index. The name is ambiguous.
One solution is to create your own namespace by prefixing
name with something common like
schools_. The trouble with that approach is that the URLconf repeats itself.
# schools/urls.py from django.urls import path from schools import views urlpatterns = [ path("", views.index, name="schools_index"), path("<int:school_id>/", views.school_detail, name="schools_detail"), ]
Django provides an alterative that will let you keep a shorter name.
# schools/urls.py from django.urls import path from schools import views app_name = "schools" urlpatterns = [ path("", views.index, name="index"), path("<int:school_id>/", views.school_detail, name="detail"), ]
By adding
app_name, we signal to Django that these views are in a namespace. Now when we want to get a URL, we use the namespace name and the URL name and join them with a colon.
reverse("schools:index") == "/schools/"
This is another convenience that Django gives to makes our application development experience easier.
That brings us to a close on the subject of URLs. By now, we've seen how to:
- Make a URL configuration by making a module with a list of
urlpatterns.
- Create URLs with
pathand
re_path.
- Use converters to extract information for views.
- Use regular expressions to express more complex URL data.
- Group related URLs together with
include.
- Refer to a URL by its
name.
- Put related names together in a namespace.
In the next article, we'll dig into views. This article only gave the briefest definition to what a view is. Django gives us very rich options when working with views. We're going to explore:
- View functions
- View classes
- Some built-in supporting views
- Decorators that supercharge views.
If you'd like to follow along with the series, please feel free to sign up for my newsletter where I announce all of my new content. If you have other questions, you can reach me online on Twitter where I am @mblayman.
This article first appeared on mattlayman.com.
Understand Django (3 Part Series)
Do you have your own Gatsby site? Let's brainstorm a dev.to cross-poster
I'd love it if my blog posts were automatically sent to dev.to - wouldn't you?
| https://practicaldev-herokuapp-com.global.ssl.fastly.net/mblayman/urls-lead-the-way-327l | CC-MAIN-2020-16 | refinedweb | 2,886 | 67.76 |
Introduction
1. RPC/encoded
2. RPC/literal
3. Document/encoded
4. Document/literal).
RPC/encoded
Take the method in Listing 1 and run it through your favorite Java-to-
WSDL tool, specifying that you want it to generate RPC/encoded WSDL.
You should end up with something like the WSDL snippet in Listing 2.
<portType name="PT">
<operation name="myMethod">
<input message="myMethodRequest"/>
<output message="empty"/>
</operation>
</portType>
<binding .../>
<!-- I won't bother with the details, just assume it's RPC/encoded. -->
Now invoke this method with "5" as the value for parameter x and "5.0"
for parameter y. That sends a SOAP message which looks something like
Listing 3.
For the most part, for brevity, I ignore namespaces and prefixes in the
listings in this article. I do use a few prefixes that you can assume are
defined with the following namespaces:
• xmlns:xsd=""
• xmlns:xsi=""
• xmlns:soap=""
There are a number of things to notice about the WSDL and SOAP
message for this RPC/encoded example:
Strengths
Weaknesses
WS-I compliance
The RPC/literal WSDL for this method looks almost the same as the
RPC/encoded WSDL (see Listing 4). The use in the binding is changed
from encoded to literal. That's it.
<portType name="PT">
<operation name="myMethod">
<input message="myMethodRequest"/>
<output message="empty"/>
</operation>
</portType>
<binding .../>
<!-- I won't bother with the details, just assume it's RPC/literal. -->
What about the SOAP message for RPC/literal (see Listing 5)? Here there
is a bit more of a change. The type encodings have been removed.
Weaknesses
• You still cannot easily validate this message since only the <x
...>5</x> and <y ...>5.0</y> lines contain things defined in a
schema; the rest of the soap:body contents.
<message name="myMethodRequest">
<part name="x" element="xElement"/>
<part name="y" element="yElement"/>
<message name="empty"/>
<portType name="PT">
<operation name="myMethod">
<input message="myMethodRequest"/>
<output message="empty"/>
</operation>
</portType>
<binding .../>
<!-- I won't bother with the details, just assume it's document/literal.
-->
Strengths
Weaknesses
Document/literal wrapped
Before I describe the rules for the document/literal wrapped pattern, let
me show you the WSDL and the SOAP message in Listing 8 and Listing 9.
<portType name="PT">
<operation name="myMethod">
<input message="myMethodRequest"/>
<output message="empty"/>
</operation>
</portType>
<binding .../>
<!-- I won't bother with the details, just assume it's document/literal.
-->
The WSDL schema now has a wrapper around the parameters (see Listing
9)..
Strengths
Weaknesses
From a WSDL point of view, there's no reason the wrapped pattern is tied
only to document/literal bindings. It could just as easily be applied to an
RPC/literal binding. But this would be rather silly. The SOAP message
would contain a myMethod element for the operation and a child myMethod
element for the element name. Also, even though it's legal WSDL, an
RPC/literal part should be a type; an element part is not WS-I compliant.
So far, this article has given the impression that the document/literal
wrapped style is the best approach. Very often that's true. But there are
still cases where you'd be better off using another style.
Imagine that, along with the method you've been using all along, you
have the additional method in Listing 10.
WSDL 2.0 will not allow overloaded operations. This is unfortunate for
languages like the Java language which do allow them. Specs like JAX-RPC
will have to define a name mangling scheme to map overloaded methods
to WSDL. WSDL 2.0 merely moves the problem from the WSDL-to-SOAP
mapping to the WSDL-to-language mapping..
With this node definition, you could construct a tree whose root node -- A
-- points to node B through both its left and right links (see Figure 1).
The standard way to send data graphs is to use the href tag, which is part
of the RPC/encoded style (Listing 13)..
Summary
There are four binding styles (there are really five, but document/encoded
is meaningless). While each style has its place, under most situations the
best style is document/literal wrapped. | https://tr.scribd.com/document/45781010/Web-Services-Styles | CC-MAIN-2019-30 | refinedweb | 690 | 56.25 |
Introduction:
Here I will explain how to bind dropdownlist using JQuery ajax or JSON in asp.net.
Here I will explain how to bind dropdownlist using JQuery ajax or JSON in asp.net.
Description:
In previous articles I explained Bind gridview using JQuery in asp.net and AutoComplete textbox with JQuery using asp.net. Now I will explain how to bind dropdownlist using JQuery or JSON in asp.net.
In previous articles I explained Bind gridview using JQuery in asp.net and AutoComplete textbox with JQuery using asp.net. Now I will explain how to bind dropdownlist using JQuery or JSON in asp.net.
To implement this concept first design table in database and give name as Country as shown below
After completion table design enter some of Country details in database to work for our sample AutoComplete textbox with database in asp.net and call asp.net page methods in JQuery.
Now open code behind file and add following namespaces
After that write the following code
C#.NET Code
VB.NET Code:
Now run your application and check the output that would be like this
Download sample code attached
20 comments :
This same code is not working without database
i.e., with static data of list, it is not working.
Please give me solution.
sir ur wats wrong wid ur web site,no body can see the demo and download the code
it's working for us please check your internet connection and network permissions..
sir ur site is not looking good now and also it has design like menu bar wrong going on.This site is very helpful to every1,please check ur blog sir.and i cannot see the demo and also download the code.
may b network permissions does not allowed during office timing.but i will check my pc.thanks 4 reply.
thank you so much nice example
It is not worked with content page
it will work in all pages. Please check your code and check the path what u have given to access the values...
Sir,thanx for this code, it working fine. But my requirement is that the dropdownlist should populate on a btn click. I tried to write same code in $(#btnID).click() but its not working for single click for double click data gets binded to ddl. Please Help!
Hello sir,
How to populate one dropdownlist to another using Jquery or json ?
The values comes in dropdownlist without refreshing page.
But now how to see values of selected index. Because we have disabled auto post back.
Thanks,
Parag.
sir i m creating dropdown dynamically using javascript and binded it with my databse but how we can set default text as --select-- and value as 0 in newly created dropdown.
and second thing : i have to remove those item that are already selected from dynamically created dropdown . that mean if i have 4 item in 1st and we have selected one item then the second drop down that is generated dynamically should contain only 3 item(except 1st dropdown selected item).
Thanks
Hi sir I am developing Windows Phone 7 App using phonegap.
i have one drop down list i want data added to ddl by using ajax json webservice .
how to do this ..?
Your way of explanation is appreciable. I like it...
Also share example of google chart sir ur blog is too useful for begineers as well as professionals
Hi Sir,
I have seen in many of the examples we use only web services to fetch the data and bind the controls.
Do we have any other option other than using web services?
Please provide your valuable information...!!!
Thanks in advance.
Can anyone please clarify the above mentioned comment/question?
hi, Thank you.. It worked in single page. But it does not work while using master page and content page. Is there any extra details to work in it ?
hi,
It works in single webform. But not working correctly in master page using webservice.asmx. The data is coming to browser. I saw by inspecting browser. But not showing in dropdown. Please help me. Got stucked.
i have done this code but they are not proprly work
Note: Only a member of this blog may post a comment. | https://www.aspdotnet-suresh.com/2012/07/how-to-bind-dropdownlist-in-aspnet.html?showComment=1382801709112 | CC-MAIN-2021-10 | refinedweb | 709 | 76.22 |
#include <basisCurves.h>
A collection of curves using a particular basis.
Render mode is dependent on both the HdBasisCurvesGeomStyle, refinement level, and the authored primvars.
If style is set to HdBasisCurvesGeomStyleWire, the curves will always draw as infinitely thin wires. Cubic curves will be refined if complexity is above 0, otherwise they draw the unrefined control points. (This may provide a misleading representation for Catmull-Rom and Bspline curves.)
If style is set to HdBasisCurvesGeomStylePatch, the curves will draw as patches ONLY if refinement level is above 0. Otherwise, they draw as the unrefined control points (see notes on HdBasisCurvesGeomStyleWire).
Curves rendered as patches may be rendered as ribbons or halftubes. Curves with primvar authored normals will always render as ribbons. Curves without primvar authored normals are assumed to be round and may be rendered in one of three styles:
Definition at line 71 of file basisCurves.h.
Initialize the given representation of this Rprim. This is called prior to syncing the prim, the first time the repr is used.
reprToken is the name of the representation to initalize.
dirtyBits is an in/out value. It is initialized to the dirty bits from the change tracker. InitRepr can then set additional dirty bits if additional data is required from the scene delegate when this repr is synced. InitRepr occurs before dirty bit propagation.
This callback from Rprim gives the prim an opportunity to set additional dirty bits based on those already set. This is done before the dirty bits are passed to the scene delegate, so can be used to communicate that extra information is needed by the prim to process the changes.
The return value is the new set of dirty bits, which replaces the bits passed in.
See HdRprim::PropagateRprimDirtyBits()
Pull invalidated scene data and prepare/update the renderable representation.
This function is told which scene data to pull through the dirtyBits parameter. The first time it's called, dirtyBits comes from _GetInitialDirtyBits(), which provides initial dirty state, but after that it's driven by invalidation tracking in the scene delegate.
The contract for this function is that the prim can only pull on scene delegate buffers that are marked dirty. Scene delegates can and do implement just-in-time data schemes that mean that pulling on clean data will be at best incorrect, and at worst a crash.
This function is called in parallel from worker threads, so it needs to be threadsafe; calls into HdSceneDelegate are ok. | https://www.sidefx.com/docs/hdk/class_hd_st_basis_curves.html | CC-MAIN-2021-17 | refinedweb | 411 | 55.84 |
netmagTutorial
Build an OpenEMI music app with Echo Nest
The Echo Nest offers a great API for creating apps using content licensed via the OpenEMI initiative. Marc George explains how to use it to build an app to play Gorillaz tracks
This article first appeared in issue 233 of .net magazine – the world's best-selling magazine for web designers and developers.
Last November, EMI Music teamed up with music intelligence platform The Echo Nest to provide developers with access to an incredible collection of music-related assets. Including material from high profile and well-loved artists such as Gorillaz, Pet Shop Boys, Tinie Tempah, Professor Green and many others. This collaboration represents the most extensive collection of licensed music, video and images to ever be made available in this way.
The Echo Nest provides a fantastic developer API that will not only serve up the assets but can also analyse audio tracks and provide detailed metadata about them. If you’re into music, The Echo Nest API has some amazing tools to build mashups and apps with.
The first decision that you’ll need to make is over which of the huge treasure chest of assets you want to make use of in your app. Assets are organised into ‘sandboxes’: individual collections grouped by artist, label or genre. You can get an overview of a sandbox’s contents by browsing the available ones – these range from the Blue Note label’s jazz, to an electronic music retrospective and Robbie Williams’s back catalogue, so quite a few bases are covered!
In order to get access, you’ll need to sign up to the Echo Nest developer programme. When you’ve registered, log in and go to the Sandboxes tab. Click on any of the sandboxes that might take your fancy, then read and agree to the terms, and press the Sign Up button. You might have to wait a little while, but you’ll be sent an email notification when your sandbox access has been approved and then you can start using the API.Client libraries
The API responds to HTTP requests with JSON or XML responses. There are many Echo Nest client libraries available that will construct API requests for you. You’ll find lots on the Downloads page. One thing to watch is that not all of the libraries listed there have implemented the Sandbox API. In this tutorial we’re going to be using PHP, with a fork of Brent Shaffer’s client, which includes the Sandbox methods. The code is hosted on GitHub; if you have Git installed you can clone the repository with:
git clone github.com/theflyingbrush/php-echonest-api.git
If you don’t happen to have Git yet, then download it from the zip link on the same GitHub URL. The PHP client library depends upon cURL support, so you’ll need your PHP install to have been compiled with it. You’re also going to want to run the code examples below in your local L/M/WAMP set-up.Using the API
Create a new project folder on your development server and Git clone the repository into it. If you’ve downloaded the zip, unzip it to your project and rename it php-echonest-api.
To authenticate with the API you’ll need the following pieces of information from your Echo Nest developer account: your API Key, Consumer Key and Shared Secret. All of these can be found on your Account page at the Echo Nest developer centre.
You’ll also need to know the name of the sandbox that you have been given access to. This is found on the Sandboxes tab of your developer account, in the middle column. As an example the Gorillaz sandbox has a key of emi_gorillaz.
The Sandbox API has two different methods: sandbox/list and sandbox/access. The sandbox/list method returns a paginated list of assets and doesn’t require any special authentication (other than your API key, and approved Sandbox access). However, sandbox/access requires additional authentication with OAuth.
Here’s how to instantiate the Sandbox API and authenticate it:
<?php require("php-echonest-api/lib/EchoNest/Autoloader.php"); EchoNest_Autoloader::register(); define("API_KEY", "{YOUR API KEY}"); define("SANDBOX_KEY", "{YOUR SANDBOX KEY}"); define("CONSUMER_KEY", "{YOUR CONSUMER KEY}"); define("SHARED_SECRET", "{YOUR SHARED SECRET}"); $echonest = new EchoNest_Client(); $echonest->authenticate( API_KEY ); $echonest->setOAuthCredentials( CONSUMER_KEY, SHARED_SECRET ); $sandbox = $echonest->getSandboxApi(array("sandbox" => SANDBOX_KEY));?>
Now the $sandbox variable is an authenticated instance of the API, and you can get a list of the contents of the sandbox like this:
<?php $assets = $sandbox->getList(); var_dump($assets);?>
The response from a getList() call is a PHP associative array, with the following keys: status (an array of information about the request), start (the index of the first asset returned), total (the number of assets in the sandbox) and assets (an array of asset descriptions). The assets key points to a subarray, each item describing an available asset. A typical asset looks like this:
Array ( [echonest_ids] => Array ( [0] => Array ( [foreign_id] => emi_artists:track:EMIDD0779716 [id] => TRGHIRC1334BAE7AD6 ) ) [title] => Spitting Out The Demons [filename] => emi_gorillaz/EMIDD0779716.mp3 [release] => D-Sides (Special Edition) [type] => audio [id] => 6aff61700721ca5b9262a06ef8cea717 )
Without parameters, getList() will return up to 15 assets per call, starting from the first one. You can pass an array of options to getList() and modify the default behaviour, which looks like this:
<?php $options = array("results" => 100, "start" => 100); $assets = $sandbox->getList($options); var_dump($assets);?>
Providing there are enough assets in the sandbox, the previous request would return 100 assets starting at the 100th. If there aren’t enough (or indeed any at all), then you’ll end up with a smaller or empty assets array.Retrieving assets
So, now you have some assets to work with, how do you get hold of them? Here, sandbox/access is the method to use, and it accepts one parameter: a unique asset ID. Many assets have only one simple ID, but audio assets can also have echonest_ids that associate assets with tracks in the wider Echo Nest API, and provide interoperability with other sandboxes via Project Rosetta Stone namespacing; read more on this in the documentation online.
So, taking the Spitting Out The Demons asset above, we’d access it with the following code:
<?php $asset = $sandbox->access("6aff61700721ca5b9262a06ef8cea717"); var_dump($asset);?>
The response from this request is an associative array, organised in the same way as a call to getList(), except that the items in assets use only URL and ID keys, URL being the one of interest as it is a link to the actual asset file. Asset links are timestamped, so cannot be cached or used after expiry.Indexing a sandbox
Although the Sandbox API enables us to page through assets using the results and start parameters of getList() it doesn’t provide any facility to search for specific items. If you want to locate a particular asset you’re going to have to make repeated getList() calls until you find it – which is inconvenient, slow, and will devour your API allowance. The approach to take, of course, is to create your own inventory and cache it so you can refer to it later.
There are many ways you can go about accomplishing this, but probably the easiest method is to store your getList() results in a database. After you’ve created a new database, you’ll need to loop over getList() calls, paging through the sandbox and storing the results as you go. In the example below, I’m making use of an existing MySQL connection, database, and an assets table:
<?php $page = 0; $num_assets = 0; do { $list = $sandbox->getList(array("results" => 100, "start" => $page * 100)); foreach($list["assets"] as $asset){ if(!empty($asset["echonest_ids"])){ $track_id = $asset["echonest_ids"][0]["id"]; } else { $track_id = ""; } if(!empty($asset['title'])){ $title = mysql_real_escape_string($asset['title']); } else { $title = "Untitled"; } $sandbox_id = $asset['id']; $type = $asset['type']; $filename = $asset['filename']; $query = "INSERT INTO 'assets' SET 'title' = '" . $title . "', 'sandbox_id' = '" . $sandbox_id . "', 'type' = '" . $type . "', 'filename' = '" . $filename . "', 'track_id' = '" . $track_id . "'"; $success = mysql_query($query) or die(mysql_error()); if($success === true){ $num_assets += 1; } } $page += 1; } while(!empty($list["assets"])); echo "Complete. Retrieved $num_assets assets.";?>
All being well, you should have a full table of assets that you can query against filename, asset type, title or Echo Nest ID. Having a searchable index like this is the cornerstone of building your own apps.
As mentioned earlier, The Echo Nest API can analyse audio and describe it in detail. The Echo Nest Analyzer is described as the world’s only ‘listening’ API: it uses machine listening techniques to simulate how people perceive music.
When you’re working with Sandbox API audio assets, the methods of most use are song/search (part of the Song API), playlist/static (from the Playlist API), and track/profile (part of the Track API). Songs and tracks are conceptually separate: the Song API returns broadly discographic information, where the Track API deals with specific audio data and analysis.
The song/search method enables you to query the Echo Nest database for songs by title or artist, but also those that meet any listening criteria that you may have, including categories like ‘danceability’, ‘energy’, or ‘mood’.
To use the Song API with sandboxes typically involves code like this:
<?php $song_api = $echonest->getSongApi(); $params = array("bucket" => array("id:emi_artists","tracks"), "artist" => "Gorillaz", "limit" => true, "min_danceability" => 0.5); $results = $song_api->search($params); var_dump($results);?>
The critical parameters in the call above are bucket and limit. The sandbox index that you made earlier will have track IDs, rather than song IDs in it, so you’ll need to instruct the Song API to return track IDs. You can do this by passing a two element array to bucket, containing tracks and a Rosetta namespace.
The namespace that you use depends on which sandbox you have access to. So for instance, if you’re working with the Bluenote sandbox, you would use id:emi_bluenote here. (You can check the Project Rosetta Stone entry in the online documentation at the developer centre for further information on this.)
You also need to make sure that results are limited to the namespace, so pass true to the limit parameter also. There’s a wealth of track profile parameters to use, for instance min_danceability as I’ve used here. Again, refer to the documentation for the whole shebang.
Each result returned from a song/search request will contain a track subarray that lists track IDs. Use these IDs to match the track_id in your index database. In this way you can search for a song, look up the track ID in your index and then retrieve the asset using the unique asset ID: playlist/static is interchangeable with song/search, except the songs returned are random and non-repeating.
The track/profile method works in reverse by accepting a track ID and returning not only the high-level information, but also the URL of a beat-bybeat analysis of the entire track. These complete analyses are incredibly detailed and have been used as the basis of some highly impressive Echo Nest hacks.
I’ve put together an example app that employs all of the methods described above. It uses the Gorillaz sandbox, but you’re welcome to download it and then configure it with your own keys if you want to try it out against a different one.
You’ll need an Amazon Product Advertising API developer account for this, because it draws in artwork from there. For fun, I’m visualising the data with three.js, the WebGL library – and it’s only compatible with Google Chrome at the moment.
First the app makes a playlist/static call for Gorillaz tracks in the id:emi_ artists namespace. It then makes a title search against the Amazon API and the iTunes Search API, and tries to find album artwork for each Echo Nest song.
When the data is loaded I use three.js to make a 3D carousel. When a carousel item is clicked, the app looks up the track is in the local index and then makes two calls – the first to track/profile for the high-level audio analysis (danceability, energy, speechiness and tempo), which is then shown as a simple 3D bar graph.
Finally we make a call to sandbox/access to download the associated mp3 and play it. You can preview the app and get the source from GitHub.
Discover 15 stunning examples of CSS3 animation at our sister site, Creative Bloq. | http://www.creativebloq.com/netmag/build-openemi-music-app-echo-nest-4135677 | CC-MAIN-2016-07 | refinedweb | 2,080 | 60.65 |
Hi!> Anyway, in ide_wait_stat(), the "timeout" value is always either > "WAIT_DRQ" (5*HZ/100) or it is "WAIT_READY" (3*HZ/100). And look at > WAIT_READY a bit more: > > #if defined(CONFIG_APM) || defined(CONFIG_APM_MODULE)> #define WAIT_READY (5*HZ) /* 5sec - some laptops are very slow */> #else> #define WAIT_READY (3*HZ/100) /* 30msec - should be instantaneous */> #endif /* CONFIG_APM || CONFIG_APM_MODULE */> > I bet that the _real_ problem is this. That "3*HZ/100" value is just too > damn short. It has already been increased to 5*HZ for anything that has > APM enabled, but anybody who doesn't use APM gets a _really_ short > timeout.> > My suggestion: change the non-APM timeout to something much larger. Make> it ten times bigger, rather than leaving it at a value that us so small> that a single interrupt could make a difference..> > In fact, right now a single timer interrupt on 2.4.x is the difference> between waiting 20ms and 30ms. That's a _big_ relative difference.> > Andrew - unless you disagree, I'd just be inlined to change both the DRQ> and READY timeouts to be a bit larger. On working hardware it shouldn't> matter, so how about just making them both be something like 100 msec (and> leave that strange really big APM value alone).I believe you should get rid of that CONFIG_APM. Its wrong. CONFIG_APMno longer corresponds with "is laptop". You can have laptop with ACPIetc. | http://lkml.org/lkml/2004/1/3/142 | CC-MAIN-2013-48 | refinedweb | 234 | 64.41 |
EAV-Django
EAV-Django is a reusable Django application which provides an implementation of the Entity-Attribute-Value data model.
Entity-Attribute-Value model (EAV), also known as object-attribute-value model and open schema which is used in circumstances where the number of attributes (properties, parameters) that can be used to describe a thing (an "entity" or "object") is potentially very vast, but the number that will actually apply to a given entity is relatively modest.
(See the Wikipedia article for more details.)
EAV-Django works fine with traditional RDBMS (tested on SQLite and MySQL).
Priorities
The application grew from an online shop project, so it is pretty practical and not just an academic exercise. The main priorities were:
- flexibility of data,
- efficiency of queries, and
- maximum maintainability without editing the code.
Of course this implies trade-offs, and the goal was to find the least harmful combination for the general case.
Features
All provided models are abstract, i.e. EAV-Django does not store any information in its own tables. Instead, it provides a basis for your own models which will have support for EAV out of the box.
The EAV API includes:
- Create/update/access: model instances provide standart API for both "real" fields and EAV attributes. The abstraction, however, does not stand in your way and provides means to deal with the underlying stuff.
- Query: BaseEntityManager includes uniform approach in filter() and exclude() to query "real" and EAV attributes.
- Customizable schemata for attributes.
- Admin: all dynamic attributes can be represented and modified in the Django admin with no or little effort (using eav.admin.BaseEntityAdmin). Schemata can be edited separately, as ordinary Django model objects.
- Facets: facet search is an important feature of online shops, catalogues, etc. Basically you will need a form representing a certain subset of model attributes with appropriate widgets and choices so that the user can choose desirable values of some properties, submit the form and get a list of matching items. In general case django-filter would do, but it won't work with EAV, so EAV-Django provides a complete set of tools for that.
Examples
Let's define an EAV-friendly model, create an EAV attribute and see how it behaves. By "EAV attributes" I mean those stored in the database as separate objects but accessed and searched in such a way as if they were columns in the entity's table:
from django.db import models from eav.models import BaseEntity, BaseSchema, BaseAttribute class Fruit(BaseEntity): title = models.CharField(max_length=50) class Schema(BaseSchema): pass class Attr(BaseAttribute): schema = models.ForeignKey(Schema,>> e.colour 'green' >>> e.save() # deals with EAV attributes automatically # list EAV attributes as Attr instances >>> e.attrs.all() [<Attr: Apple: Colour "green">] # search by an EAV attribute as if it was an ordinary field >>> Fruit.objects.filter(colour='yellow') [<Fruit: Apple>] # all compound lookups are supported >>> Fruit.objects.filter(colour__contains='yell') [<Fruit: Apple>]
Note that we can access, modify and query colour as if it was a true Entity field, but at the same time its name, type and even existance are completely defined by a Schema instance. A Schema object can be understood as a class, and related Attr objects are its instances. In other words, Schema objects are like CharField, IntegerField and such, only defined on data level, not hard-coded in Python. And they can be "instantiated" for any Entity (unless you put custom constraints which are outside of EAV-Django's area of responsibility).
The names of attributes are defined in related schemata. This can lead to fears that once a name is changed, the code is going to break. Actually this is not the case as names are only directly used for manual lookups. In all other cases the lookups are constructed without hard-coded names, and the EAV objects are interlinked by primary keys, not by names. The names are present if forms, but the forms are generated depending on current state of metadata, so you can safely rename the schemata. What you can break from the admin interface is the types. If you change the data type of a schema, all its attributes will remain the same but will use another column to store their values. When you restore the data type, previously stored values are visible again.
You can find more examples in the source code: see directory "example/" and the tests.
Data types
Metadata-driven structure extends flexibility but implies some trade-offs. One of them is increased number of JOINs (and, therefore, slower queries). Another is fewer data types. Theoretically, we can support all data types available for a storage, but in practice it would mean creating many columns per attribute with just a few being used -- exactly what we were trying to avoid by using EAV. This is why EAV-Django only supports some basic types (though you can extend this list if needed):
- Schema.TYPE_TEXT, a TextField;
- Schema.TYPE_FLOAT, a FloatField;
- Schema.TYPE_DATE, a DateField;
- Schema.TYPE_BOOL, a NullBooleanField;
- Schema.TYPE_MANY for multiple choices (i.e. lists of values).
All EAV attributes are stored as records in a table with unique combinations of references to entities and schemata. (Entity is referenced through the contenttypes framework, schema is referenced via foreign key.) In other words, there can be only one attribute with given entity and schema. The schema is a definition of attribute. The schema defines name, title, data type and a number of other properties which apply to any attribute of this schema. When we access or search EAV attributes, the EAV machinery always uses schemata as attributes metadata. Why? Because the attribute's name is stored in related schema, and the value is stored in a column of the attributes table. We don't know which column it is until we look at metadata.
In the example provided above we've only played with a text attribute. All other types behave exactly the same except for TYPE_MANY. The many-to-many is a special case as it involves an extra model for choices. EAV-Django provides an abstract model but requires you to define a concrete model (e.g. Choice), and point to it from the attribute model (i.e. put foreign key named "choice"). The Choice model will also have to point at Schema. Check the tests for an example.
Documentation
Currently there is no tutorial. Still, the code itself is rather well-documented and the whole logic is pretty straightforward.
Please see:
- tests, as they contain good examples of model definitions and queries;
- the bundled example ("grocery shop", comes with fixtures);
- the discussion group.
Dependencies
In theory, Python 2.5 to 2.7 is supported; however, the library is only tested against Python 2.6 and 2.7.
You'll also need Django 1.1 or newer and a couple of small libraries: django_autoslug and django_view_shortcuts. This is usually handled automatically by the installer.
Alternatives, Forks
- django-eav
- A fork of eav-django that became a new app. Doesn't seem to be actively developed but is probably better in certain aspects. The original author of eav-django encourages users to give this app a try, too.
Licensing
EAV-Django is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version.
EAV-Django. | https://bitbucket.org/neithere/eav-django/ | CC-MAIN-2014-15 | refinedweb | 1,243 | 57.06 |
17 March 2011 18:01 [Source: ICIS news]
LONDON (ICIS)--?xml:namespace>
Although crude oil prices in the short term have suffered a negative impact from the earthquake in
Moreover, the country will have to compensate for the power loss left from the nuclear generation and some of it will have to come from oil fired electricity power plants, Lambrecht added.
“Once the nuclear disaster is resolved then reconstruction will begin,” said Harry Tchilinguirian, analyst at BNP Paribas.
When reconstruction begins then there will be an increase in demand for gasoline, fuel for heavy machinery and private power, Tchilinguirian added.
Meanwhile, high levels of radiation at the Fukushima Daiichi nuclear facility are causing further difficulties as attempts continue to stop the six reactors at the site from overheating.
Workers were evacuated as radiation levels are now considered fatal, following a series of explosions at the No 1, No 2, No 3 and No 4 reactors since Saturday. Helicopters are being deployed to continue with cooling operations, pouring seawater onto the reactors.
The International Energy Agency (IEA) estimated
Expectations were of a slight contraction in demand of around 100,000 bbl/day for 2011, but it is likely that due to the reconstruction, demand will be flat and may even increase, Tchilinguirian said.
Meanwhile, crude oil futures were being supported by fears that turmoil in
At 16:50 GMT, Mary Brent was trading at $114.02/bbl, up $3.42/bbl from the previous close, while April WTI was trading at $100.93/bbl, up $2.95 | http://www.icis.com/Articles/2011/03/17/9444949/japan-disaster-domestic-crude-oil-demand-to-rise-in-2011-analyst.html | CC-MAIN-2015-11 | refinedweb | 256 | 50.87 |
Are you sure?
This action might not be possible to undo. Are you sure you want to continue?
Washburn and Clark S. Binkley+ ABSTRACT Portfolio theory and asset pricing models have become common tools for analyzing the risk and return of timberland investments. Not surprisingly, problems arise in applying tools developed for financial assets such as stocks to timberlands. In this paper, we discuss some of the problems for estimating the Capital Asset Pricing Model for forest assets, and by implication indicate some fruitful areas for further research. INTRODUCTION The use of portfolio theory and asset pricing models to examine the risk and return of forest assets has become commonplace since Mills and Hoover (1982) first utilized portfolio optimization to examine the capacity of Indiana hardwood forests to diversify a portfolio of traditional financial assets. Subsequent analysts have examined the diversification potential of timberland investments in other geographic regions (e.g. Thomson 1987; Thomson and Baumgartner 1988; Conroy and Miles 1987; Zinkhan and Mitchell 1988; DeForest et ai. 1989). These and other researchers have also applied asset pricing models=generally either Sharpe's (1963) single-index market model (with returns to the overall market portfolio serving as the index) or the Capital Asset Pricing Model (CAPM; Sharpe 1964; Lintner 1965)--to timberland investments to measure their risk and evaluate their performance (e.g. Thomson 1987; Zinkhan 1988; Zinkhan and Mitchell 1988; Cubbage, Harris, and Redmond 1988; Redmond and Cubbage 1988; Binkley and Washburn 1988a, 1988b). These efforts have been fruitful. Two broad, yet apparently fundamental, results have emerged. First, returns for forest assets are weakly correlated with returns for many traditional investments, and therefore timberlands present an opportunity for portfolio diversification. Second, forest assets carry relatively low levels of financial risk. This suggests that investors should demand relatively low rates of return from timberland investments. Significant problems remain, however, in the application of portfolio theory and asset pricing models to forest assets. To fully comprehend the implications of extant analyses, and to design new research for increasing our understanding of the risk and return of timberland investments, these problems must be acknowledged, and resolved. This paper discusses some of these issues. Although most of our results have implications for portfolio analysis and asset pricing models in general, we center our discussion around the CAPM. 1 This research is part of a larger project on the evaluation of investments in southern pine forestry which is sponsored jointly by Yale University, the USDA Forest Service Southeastern Forest Experiment Station, Scott Paper Company, Weyerhaeuser Company, South Carolina National Bank, and First Wachovia Bank and Trust. None of these organizations is responsible for the data, analysis, or conclusions presented here. 2 Ph.D. Candidate, School of Forestry and Environmental Studies, and Professor, School of Forestry and Environmental Studies and School of Organization and Management, Yale University, 205 Prospect St., New Haven, CT 06511.
Following Jensen (1969). If capital markets are in equilibrium. . Risk-free returns are calculated from a proxy for a riskless asset. measures the difference between the return that an asset has actually generated and the retum that is justified by its level of systematic risk. Although these problems are important. the greater the asset's financial risk. those with a beta of zero to earn only the risk-free rate of return. and has confused estimation of the CAPM by confounding the measurement of contemporaneous market and risk-free returns. then the value of alpha is zero. To the contrary. Period-averaging of stumpage prices also induces serial dependence into forestry returns. called the CAPM alpha.S. for example. the model must be estimated from ex post data. growing stock. and bare land values. The slope coefficient. analysts have created synthetic time series based on assumptions about the structure of the forest asset. such as the Standard and Poors Index of 500 common stocks (with dividends reinvested). As expected returns can not be observed. the rate of return on a riskless asset (Rj). and concludes by describing what we consider to be the most important areas for future research.The CAPM specifies an equilibrium relationship between asset its expected rate of return (ERi). The larger the value of beta. The third section discusses these features of CAPM estimation for forest assets. Investors require assets with a beta of one. Given historical data on timberland returns. to earn the overall market rate of return. In some cases. Treasury bills. This obscures some of the variability of forestry returns. and market returns from a proxy for the overall market portfolio. The intercept term. records of returns for actual forest assets rarely exist. different assumptions can produce substantially different estimates of risk and return. Returns for forest assets are calculated from period-average stumpage prices (e. which affects tests of the CAPM assumption that markets for forest assets are informationally efficient.Rm)/var(Rm). Estimation of the CAPM equation (2) requires a time series of historical returns for the asset under study. The final section of the paper summarizes those results we consider to be well supported by theory and data. called the CAPM beta. and the expected risk premium on the market portfolio of all assets in the economy (ERm . they describe an agenda of interesting research questions.g. some additional problems arise in model estimation. The next section discusses the consequences of various approaches for measuring stumpage. the average of prices observed throughout a year). they do not dampen the prospects for further research in this field. historical risk premia for the asset are typically regressed on contemporaneous risk premia for the market portfolio: (2) where the error term e is a random disturbance. and those with a negative beta to earn even less than the risk-free rate. such as 90-day U. measures the systematic or nondiversifiable risk of the asset.Rj): (1) where ~ equals cov(Ri. Unfortunately. In place of historical data.
Even when other assumptions are made. But despite their relative availability. P is the price of stumpage at the conclusion of the period. there are few price series of sufficient length or perceived accuracy for estimation of the CAPM. changes in stumpage price often account for the bulk of variation in returns. Here. even this indirect approach to obtaining forestry returns is hindered. we examine the consequences for the CAPM of two important proxies: (i) bid prices for national forest stumpage in the West. but even they are often of dubious accuracy or not available at all. Harris. CAPM betas can be estimated to a good approximation from rates of change in stumpage price alone. Information on historical holding costs is sketchy. holding costs. the continuous rate of return during period t for any forest asset i (Ri. timber growth. holding costs are negligible. As a consequence.g. which increases the alpha estimate accordingly. and protection from fire and pests). and various holding costs (e. growing stock. Cubbage. This is particularly true outside the South. When data on stumpage values are not available. The other components of forest asset value only affect the estimate of alpha. Stumpage prices are also the most abundant source of data for calculating historical returns to forest assets. The current level of growing stock and bare land values are difficult to observe. Unfortunately. and GSV and BLV are the respective values of the growing stock and bare land at the conclusion of the period. In such cases. As a substitute. regeneration expenses. but should leave the beta unchanged. records of their historical values are essentially non-existent. and even stumpage prices to construct a time series of returns for forest assets.CALCULATING RETURNS FOR FOREST ASSETS Records of historical returns for actual forest assets are not generally available for estimating the CAPM. and (ii) log or lumber prices. Using this method. then all of the variation in forestry returns arises from changes in stumpage price. And the proper assumptions to make are arguable. Stumpage Value Stumpage prices are the most influential determinant of the value of hypothetical forests. forestry returns must be calculated with some proxy measure for price. and timber growth is constant. (They sometimes add a constant rate of timber growth. C is the cost of holding the asset during the period (payable at its conclusion).t) is given by: (3) where H is the volume of stumpage harvested at the conclusion of the period. If one assumes that bare land and growing stock values track stumpage prices. property taxes. and bare land values. . or when they are of dubious accuracy. market-model coefficients estimated from rates of change in stumpage price alone are nearly identical to those obtained with their detailed series of constructed returns. researchers have constructed time series of returns for hypothetical forests from historical values of the assets' component parts: stumpage. and Redmond (1988) and Redmond and Cubbage (1988) have in fact estimated the CAPM from rates of change in stumpage price. Researchers must therefore rely on a series of assumptions about bare land and growing stock values. given their particular assumptions about growing stock and bare land values and holding costs. Historical stumpage prices are the most abundant source of data for calculating forestry returns.) Thomson and Baumgartner (1988) demonstrate that. past research has taken a variety of approaches to measure current and historic values of the key variables. by a dearth of information.
This is not surprising. Thus far. The average price of national forest timber that is actually harvested is a much better measure of the current market price of stumpage. For the commercially important Douglas-fir species (which dominates the Pacific Northwest. Returns for 90-day U. presumably-accurate series of prices for logs or lumber are sometimes used as a substitute for calculating forestry returns.S. and the like. This tends to offset their lower volatility. the CAPM beta estimated from rates of change in cut price is less than one-third the size of that estimated from bid prices. winning bidders are granted several years to harvest their timber. 1984) was used to estimate the model with a first-order autoregressive error. this same estimation procedure is used throughout our analysis. Aside from a relatively small deposit. cut prices are much less volatile than bid prices. ignore the problems of contract termination. standard deviation. because public timber is not sold for immediate harvest. and nearly equate CAPM betas estimated from cut and bid values. The Forest Service reports a so-called "cut price" or the average value of timber harvested in a particular year. bid prices measure expected future timber prices. rates of change in log and lumber price can be used directly as a proxy for rates of change in stumpage price. this price is clearly a more accurate measure of the actual market value of timber in a particular year. cut prices are more highly correlated with the market than are bid prices. In the other western regions. In short. Westside). Log and Lumber Prices. correlation with stock market returns. were used as proxies for returns to the risk-free asset and market respectively. In cases when stumpage prices have not been recorded. using bid prices to estimate the CAPM overstates systematic risk by more than threefold. If current prices are the best estimates of future prices (an assumption supported in the next section). Rather. the bid price of the marginal unit of timber actually harvested will accurately measure current market value. Two approaches can be taken. then in any year the firm will cut all of the timber with a bid price less than or equal to the current market value. however. In other words. Table 1 compares the mean. or when their accuracy is questionable. Consider the case of a profit-maximizing firm which holds an array of contracts to harvest public timber. bid deposits. it appears that using bid prices for national forest sawtimber stumpage to measure current market values substantially overestimates price variability. they do not actually pay for the timber until it is harvested. and CAPM betas calculated from continuous rates of change in annual cut and bid prices for national forest sawtimber stumpage in four western regions. then the maximum likelihood option of the SAS ETS A UTOREG procedure (SAS Institute Inc. Often the only reported prices for stumpage in the West are the successful bids for public timber. Although their mean rates of change are similar. Alternatively. Bid prices for public stumpage are therefore based on the price that buyers expect to prevail when they harvest the timber. Unless noted otherwise. It creates a problem for estimating returns for forest assets. CAPM betas were obtained from estimates of equation (2). not current stumpage values (Rucker and Leffler 1988). as relatively little private stumpage is sold on the open market. and will leave unharvested all of the timber with a higher bid price. forest growth. Stumpage prices can be derived using a conversion surplus approach which deducts processing costs from log or lumber values. few researchers have used log . Hence.Bid Prices for National Forest Stumpage. obtained from Ibbotson Associates (1987). Accepting the argument given above. Treasury bills and the S&P 500 stock market index (with dividends reinvested). Consequently. each with a different bid price. For simplicity. rates of change in cut prices are also less correlated with market returns than are rates of change in bid prices. In western Oregon and western Washington. Ordinary least squares regression was used to estimate the equation if the Durbin-Watson statistic for first-order autocorrelation of the error was within its upper bound for significance at the 0.05 level. If the Durbin-Watson statistic was beyond this bound.
538* 0.419* 0. and may not be perfectly correlated with stumpage prices through time (see. Thus.18 45. The use of log or lumber prices has several practical difficulties.181 * Note: A single asterisk (*) indicates statistical significance at the 0.11 39. and CAPM beta for rates of change in national forest cut and bid prices Price Series Rate of Change (%) Standard Deviation (%) Correlation with Market Returns CAPM Beta Pacific Northwest.194 0. and Haynes (1988).824 1.12 0.58 22.328* 0.10 level of confidence.40 6. Cut and bid prices were obtained from Adams. Eastside (1950-87) Cut Bid Rocky Mountains (1960-87) Cut Bid California (1950-87) Cut Bid 6.330* 0.47 5. correlation with stock market returns.265* 5. rates of return for forest assets calculated from rates of change in log and lumber price will produce misleading estimates of risk and return. standard deviation. Using the conversion surplus approach to estimate stumpage prices from lumber or log prices introduces the need for accurate time series on logging and processing costs.58 43. Data on these variables frequently are less available or accurate than are the stumpage price series themselves.28 5. for example.42 6.07 37.367* 0. Luppold 1984). Jackson.700* 0.TABLE 1. Because of the structure of forest products markets. Table 2 compares the mean. correlation with the stock market.406** 1.--A comparison of the mean. log and lumber prices are typically less volatile than are stumpage prices (Haynes 1977).340* 0. and . Westside (1950-87) Cut Bid Pacific Northwest.993* 1.199* 1. standard deviation.47 16.05 level of confidence.55 0. Mills and Hoover (1982) and Mills (1988) being the primary examples.46 6.99 27. two asterisks (**) at the 0. or lumber prices to calculate forestry returns.169 0.414* 0.52 30.54 5.
two asterisks (**) at the 0.87 5. Jackson.10 level of confidence. and lumber betas are very different.CAPM beta for rates of change in sawtimber stumpage.62 14.058 0.128 0. sawlog.261 ** 0. Oregon and W. Rates of change in lumber prices are more highly correlated with returns to the stock market than are rates of change in either stumpage or lumber prices. and lumber prices of southern pine and Douglas-fir.51 10. the stumpage. 1955-85 Price Series Mean Rate Of Change (%) Standard Deviation (%) Correlation with Stock Returns CAPM Beta --------------------------------------------------------------------------------------~------------------------------ Southern Pine Louisiana Private Stumpage Louisiana Private Sawlogs LumberPPI Douglas-Fir W. Washington Private Sawlogs LumberPPI 4.85 16.649* Note: A single asterisk (*) indicates statistical significance at the 0. correlation with the stock market.22 3. For Douglas-fir. National forest cut prices for Douglas-fir stumpage were obtained from Adams.68 -0.A comparison of the mean.42 4. Use of lumber or log prices to estimate the risk of owning Douglas-fir timber would be very misleading.75 12. ranging from 0.05 level of confidence.137 0. Coincident with this decline in volatility is a decline in the average rate of price change. log.022 -0.181 0.79 8. price volatility declines from stumpage to logs to lumber.368* 0.342 5. Washington National Forest Cut Price W. All other prices were obtained from Ulrich (1987). and CAPM beta for rates of change in sawtimber stumpage. logs. and lumber.649 for lumber.-.13 14. TABLE 2. however.057 for sawlogs to 0.057 0.017 0. standard deviation. Oregon and W. and Haynes (1988). As anticipated. the net result of the differences in volatility and correlation with market returns is surprisingly similar betas for stumpage. and lumber price.229 0.52 -0.08 4. sawlog. What are the consequences of using rates of change in log or lumber price rather than stumpage price to estimate the CAPM? In the case of southern pine. .
its proportion of the forest asset value as a whole. Two approaches are conventional. As a consequence. The lower capital value given by the immediate harvest approach yields a rate of return of 10. Thomson 1987.5 percent compared to 8.2 and returns for 90-day U. We assumed an initial planting density of 400 trees per acre. and the annual rate of return for the forest asset given by each procedure. however. with the capital represented by the growing stock comprising as much as three-quarters of the value of a fully regulated forest asset taken as a whole. Growing stock therefore has no value until it grows to a merchantable size. . Consequently. a typical cost of regenerating one acre. no thinnings. Consequently. Figure 1 compares the three alternative estimates of value by age of growing stock. and consequently influence the CAPM alpha estimate rather than the beta estimate. to measure the current market value of different ages of growing stock. Redmond and Cubbage 1988).Growing Stock Value Forestry is a capital-intensive production enterprise (Binkley 1985). that the market value of growing stock is simply equal to its value if sold for immediate harvest in the stumpage market. 1988b) or implicitly (e. We assumed that all prices and costs would increase at an inflation rate of 4. let alone observe how these values have changed over time (Washburn and Romm (1988) provide one analysis for California). researchers must estimate the capital value of growing stock in order to construct estimates of the returns for forest assets. Binkley and Washburn 1988a. valuing the growing stock at its harvest value will produce a higher rate of return and a higher estimate of alpha. and a harvest age of 30 years.g. According to the appraisers. bare land value was set at $350 per acre (these values were obtained from a survey of forestland appraisers throughout the South that we are presently conducting).8 percent (calculated from the CAPM using a beta of 0. Sawtimber and pulpwood prices were set at $163 per thousand board feet and $19 per cord respectively. Thus. the immediate harvest value understates the value of growing stock and therefore overstates the return for the forest asset.g. the discounted harvest revenue overstates growing stock value and understates forest asset return. we used each method to calculate the value of the growing stock in a 30 acre fully regulated forest of southern pine. Other analysts (e. To compare the two approaches.S. we used current market values reported in our survey of southern forestland appraisers for various ages of young southern pine timber.g. It is difficult. changes over time in growing stock value are crucial for evaluating the risk and return of timberland investments. The discounted value of future harvest revenues is nearly double the immediate harvest value. Yields for both pulpwood and sawtimber were taken from Burkhart et al.1 percent for the discounted harvest income.2 percent respectively.2 and 13.3 percent (the average rate of change in the CPI from 1950 through 1987). Treasury bills and the S&P 500 of 5. (1987) for site 50 land. the choice between these two methods will primarily affect the magnitude of the return for the forest asset rather than its covariance with market returns. Thomson and Baumgartner 1988) have discounted expected future harvest revenues to obtain an estimate of growing stock value. Annual operating costs for the forest as a whole were set at $200. The value of the growing stock calculated as the immediate harvest value will generally be lower than when calculated as the discounted value of future harvest income. Most researchers have assumed. Both approaches assume that the value of growing stock tracks the price of stumpage (although allowing the discount rate to vary over time could cause some slight departures when the discounted harvest revenue approach is used). we used a nominal discount rate of 6. As a benchmark for assessing the accuracy of the two approaches. Conroy and Miles 1987. their average values from 1950 through 1987). Table 3 gives the total value of all ages of growing stock. either explicitly (e. For the discounted cash flow calculations.
.--The immediate harvest value. and the value of discounted future harvest income of different ages of southern pine growing stock in a 30 acre fully regulated forest..) I I Additional Value Attrittributed by Appraisers Harvest Value Years In Ground FIGURE 1.-.Alternative Growing Stock Values 2250 2000 1750 1500 . the market value attributed by southern forestland appraisers.. tA- ~ b Additional Value of Discounted Future Harvest Income 1250 1000 750 500 250 0 0 5 10 15 20 25 30 '---' > :::s ~ (l.
Still other researchers have assumed that bare forestland values change at the rate of inflation (e. substantially lower than they are for the farmland-value assumption. 1988b). where the option to convert land between crop and forest should keep prices for either use closely aligned. Some analysts posit that the value of bare land changes at the same rate as the return for the timber component of the forest asset (e.1 Bare Land value Like the value of growing stock.g. Other researchers have used rates of change in farmland values to measure rates of change in forestland values (e. researchers have made three assumptions about rates of change in bare land value.9 68. Coincident with this decline in mean return and variability is an increasingly negative correlation with market returns.g. This approach finds support in the notion that bare land derives its value from the revenue it generates from timber production. Both the mean and standard deviation of returns for bare land are substantially lower for the rate of change in farmland-value assumption than they are for the timber-return assumption.9 10. As a substitute for actual data. Table 4 compares the alternative risk and return characteristics of bare timberland and of a fully regulated southern pine forest asset in Louisiana.5 10.261 22.0 8.273 65. the timber returns assumption is inappropriate. This approach is valid to the extent that common factors similarly affect farmland and forestland value. There may. The timber-returns assumption results in a much higher CAPM beta for bare forestland than . Mills 1988. be other determinants of bare forestland value.--The consequences of alternative growing stock valuation methods on the rate of return to a 30 acre fully regulated forest of southern pine Growing Stock Valuation Method Growing Stock Value ($) Proportion of Total Value (%) Rate of Return (%) Immediate Harvest Value Forest Appraiser Survey Discounted Future Harvest Income 20. Thus. It is perhaps most applicable in regions such as the South.5 78. Redmond and Cubbage 1988). Binkley and Washburn 1988a.785 39. The choice of assumption for bare land value is consequential. the current value of bare land is difficult to observe and records of its historical values are nearly non-existent.g. measures of asset risk such as CAPM betas that are calculated from timber returns (or rates of change in stumpage price) are assumed to apply to the land component as well. If so.TABLE 3. Past values of bare forestland are backcasted from the the current value with historical rates of change in farmland value. Zinkhan 1988 and Zinkhan and Mitchell 1988 through their analyses of the Southern Timberland Index Fund constructed by Forest Investment Associates ). however. These same measures for the inflation rate assumption are. in turn. Mills and Hoover 1982.
Rates of change in farmland value were calculated from the USDA series for Louisiana. harvest income. standard deviation.118 Note: Timber returns are calculated for a fully regulated southern pine forest managed on a 35 year rotation to produce both pulpwood and sawtimber. and CAPM beta for forestry returns in Louisiana assuming that rates of change in bare land value follow timber returns. .182 -0.25 13. The CPI was used to obtain the inflation rate.38 8.57 8. When we look at the risk and return of a composite timber and land asset. They include changes in the immediate harvest value of the growing stock.182 0.50 6. correlation with stock market returns.073 0.010 0. See Binkley and Washburn (1988a) for a detailed description of the calculations. although the effects of the different bare land assumptions are dampened through the addition of growing stock to the valuation exercise.074 -0.242 -0. the same patterns emerge.50 13.041 -0.62 10.81 3.143 -0. Prices for private stumpage in Louisiana.015 -0.75 -0. and applied to all years. obtained from Ulrich (1987). were used for the analysis. rates of change in farmland value.77 7.50 9. or the inflation rate.backcasting with either rates of change in farmland value or inflation. and various operating costs. 1955-85 Bare Land Value Assumption Mean Return (%) Standard Deviation (%) Correlation with Stock Returns CAPM Beta Bare Land Timber Returns Farmland Inflation Timber and Land Timber Returns Farmland Inflation 10. TAB LE 4.125 0.--A comparison of the mean. Constant weights (37% land and 63% timber) were calculated from 1985 stumpage prices and land values. Returns to the composite timber and land asset were calculated as the weighted average of annual timber and land returns.77 9. regeneration expenses.041 -0.02 4.
an average of prices observed throughout a month. Mismeasurment has led past research to produce biased parameter estimates. Working (1960) demonstrates that the first-order serial correlation in a series of rates of change in arithmetic averages calculated from random values at n regular intervals within the period is equal to (n2 . because stumpage prices are reported as period averages. an annual average calculated from monthly values) is equal to (2n2 + 1)/3n2 of the corresponding variance in rates of change in instantaneous values (e. periodic rates of change were used rather than continuous rates. Consider annual values. Harris. Cubbage. Averaging creates several problems for analyzing timberland returns. Markets for forest assets appear to be inefficient when viewed over periods as short as month. First and second calendar year betas (along with . Zinkhan 1988. Rosenberg 1971). This renders ordinary least squares regression an inefficient estimator for the parameters of asset pricing models. Binkley and Washburn 1988a. annual returns for the market portfolio and risk-free asset are typically measured during single calendar years by the rate of change in their value (including any interim cash payments) from the outset of the year to its conclusion.1)/[2(2n2 + 1)]. This value quickly approaches 0. Some researchers (e.g.25 as n increases. Second. First. 1988b) have related annual-average forest returns to market and risk-free returns during the first calendar year. Period averaging of stumpage prices has also confused the measurement of market and risk-free returns for estimation of the CAPM. and Redmond 1988.g. or year. Thus. Redmond and Cubbage 1988. period averaging introduces spurious first-order serial correlation into the rates of change in the averaged series. quarter. and also produces difficulties for tests of market efficiency which are based on the correlation structure of asset returns (Washburn and Binkley 1989a). The choice is of more than theoretical interest because the two procedures produce vastly different empirical results.g. the CAPM assumes that asset markets are informationally efficient. which suggests that the CAPM may not be an appropriate framework for analyzing short-term forestry returns. For this analysis. that is. there are two sets of calendar year market and risk-free rates of return. Working (1960) demonstrated that the variance of rates of change in a series of arithmetic averages calculated from values at n regular intervals within the period (e. Averaging does not induce any higher-order serial correlation. Period-Average Stumpage Prices Stumpage prices are reported as period averages. rates of change calculated from averaged data are less variable than the corresponding rates of change in instantaneous values. another group of issues arise in using these data to estimate CAPM parameters.ESTIMA TINO THE CAPM FOR TIMBERLAND INVESTMENTS Given a time series of timberland returns. Second. The variance-reduction factor quickly approaches 2/3 as n increases. Zinkhan and Mitchell 1988) have related forest returns to market and risk-free returns during the second calendar year. During the two years spanned by the rate of change in annual-average stumpage price. the measurement of market and risk-free returns is not straightforward. Others (Thomson 1987. This section discusses several of these problems. First. which are most frequently used to analyze forest assets. Annual forestry returns are calculated from rates of change in annual-average stumpage price. We used first and second calendar year market and risk-free returns to estimate the CAPM for rates of change in eleven of the series of annual-average sawtimber stumpage prices analyzed by Redmond and Cubbage (1988). the value at the conclusion of the year). measures of the variability of returns for forest assets must be suitably increased to make them comparable with variability measures of returns for other assets. The precise effect depends on the averaging process (Daniels 1966. In contrast.
period-average forestry returns should be related to period-average market and risk-free returns.2. The choice among the three measures of average market and risk-free returns has little effect on the parameter estimates. and most of them were significant.three other beta estimates that we discuss shortly) for national forest bid price series (we analyzed bid prices rather than cut prices despite the problems of the former in order to make our results comparable with previous research) are compared in Figure 2. and that they should therefore earn less than the riskless rate. however.g. tends to be much smaller when market and risk-free returns are measured over the first calendar year than when they are measured over the second calendar year. Binkley and Washburn 1988a.g. and Cubbage 1988. In general.) In essence. We show that neither of these previous approaches is correct. Use of second calendar year returns biases beta estimates downwards. To summarize. Zinkhan and Mitche111988) substantially underestimates the systematic risk of forest assets. Redmond and Cubbage 1988. The figure also compares the corrected betas those obtained using first and second calendar year returns. but is large for the commercially important softwood species. using first calendar year returns causes an upward bias in beta estimates. (The CAPM betas reported in Tables 1. or (iii) the rate of change in the annual arithmetic mean of market and risk-free asset value calculated from values at the conclusion of each month. The bias is often negligible for the softwoods but severe for the hardwoods. Figure 3 makes the same comparison for the Louisiana prices. the forestry CAPM can be accurately estimated by relating annual-average forestry returns to one of three alternative measures of annual-average market and risk-free returns: (i) the geometric mean of the thirteen twelve-month returns that can be calculated from values of the risk-free asset and market portfolio at the conclusion of each month during two calendar years. Figure 2 compares the three alternative beta estimates for the national forest bid prices. Redmond. the bias caused by using first calendar year market and riskless returns is less severe than that caused by using second calendar year returns. . although for both softwoods and hardwoods. The precise form of the CAPM for period-average values depends on the averaging process. and 4 were estimated with the third measure of average market and risk-free returns. The different calendar years for measuring market and risk-free returns produced contrary estimates of the systematic risk of forest assets. On the other hand. measurement of market and risk-free returns over the second calendar year (e. When market and risk-free returns over the first calendar year were used to estimate the CAPM. 1988b) overestimates the systematic risk. (ii) the arithmetic mean of these same thirteen returns. market and risk-free returns measured over the second calendar year produced negative betas. These estimates suggest the contrary conclusion that holding forest assets entails "negative" systematic risk. This leads one to conclude that ownership of forest assets (especially the softwood species) entails substantial systematic risk. the betas for all eleven of the price series were positive. Each procedure systematically mismeasures the model's explanatory variables. Zinkhan 1988. three of them were significantly different from zero. In another paper (Washburn and Binkley 1989b). The bias for commercially important softwood species. The downward bias is relatively small for the hardwoods. Figure 3 makes the same comparison of betas estimated from private stumpage prices in Louisiana. Harris. Given the process for averaging stumpage prices. we derive the CAPM relationship for rates of change in period-average asset values. This biases the estimates of CAPM parameters. Measurement of the explanatory variables over the first calendar year (e. It shows the same general pattern.
0 1.--A comparison of CAPM betas estimated by relating rates of change in the average annual price of sawtimber stumpage sold on national forests to alternative measures of market and risk-free rates of return.5 1. An asterisk (*) indicates that the estimate is statistically different from zero at the 0.5 Beta Estimate FIGURE 2.5 0.National Forest Sawtimber Stumpage Southern Pine DouglasFir Ponderosa Pine I ~ 1st Calendar Year 2nd Calendar Year Geometric Mean Arithmetic Mean Rate of Change in Arithmetic Mean Western Hemlock * I ~ Eastern Hardwood I Oak Maple -1.0 0. .0 -0.10 level of confidence.
3 -0.3 0.4 Beta Estimate FIGURE 3.2 0.0 0. .1 0.10 level of confidence.1 0.Louisiana Sawtimber Stumpage Southern Pine Ash I 1st Calendar Year ~ 2nd Calendar Year Geometric Mean Arithmetic Mean Rate of Change in Arithmetic Mean I Gum ~ I Oak -0.2 -0.--A comparison of CAPM betas estimated from rates of change in the average annual price of sawtimber stumpage sold on private land in Louisiana to alternative measures of market and risk-free rates of return. An asterisk (*) indicates that the estimate is statistically different from zero at the 0.
To compensate for the spurious serial dependence induced by . that affects the return on all assets. (5) (4) If we condition the expectations operator on "weak-form" information--past departures of actual from equilibrium rates of return--in ex post form the condition becomes: (6) where the expected value of Ctequals zero and cov(q. Using the inflation-based model along with the stock-based model tests the robustness of the efficiency results to the model of equilibrium return. that is. The weak-form efficiency of stumpage markets was evaluated by testing for serial dependence in the residual errors.t + Ct.t = a + ~ Rm . then the CAPM is not an appropriate framework to measure their risk. that the expected future value of the asset is equal to its current value capitalized at its equilibrium rate of return: EPi. An interesting outcome of this procedure was a finding that rates of change in stumpage price are uncorrelated with the realized inflation rate.t + ~ (ERm. We used two variants of the single-index market model of equilibrium return rather than the CAPM. The stock-based market model provides essentially the same test of efficiency as the CAPM (Brenner 1979). Lacking historical data on returns for actual forest assets.t exp[Rf.H 1 = Pi. A testable implication of equation (6) is that departures from equilibrium rates of return are serially independent.t . This counters the common view that timber is a good inflation hedge.Rf. That is.t . and annual-average stumpage prices on rates of change in corresponding period-average values of the S&P 500 or the CPI. The market model postulates a linear relationship between equilibrium returns on individual assets and the value of a common market factor.t = a + ~ Rinf.t) = O. past departures from equilibrium can not be used to identify current departures.t . (7) (8) where Ct is a random error. If markets for forest assets are inefficient. or index. departures of actual from equilibrium rates of return are white-noise. in this case the CAPM. A finding of significant serial dependence is cause to reject a joint hypothesis that markets for forest assets are efficient and that equilibrium rates of return conform to the specified model (Fama 1976). we tested the weak-form efficiency of markets for southern pine sawtimber stumpage (Washburn and Binkley 1989a).Rf.Stumpage Market Efficiency The CAPM implicitly assumes that markets for forest assets are informationally efficient. quarterly-.t . and Ri.t)]· We can equivalently express the efficiency condition in terms of the asset's rate of return: ERi. We selected two alternative indices--returns for the stock market (Rm) and the rate of inflation (Rinf): Stock-based market model Inflation-based market model R. In other words. The market models were estimated using ordinary least squares regression of the rates of change in monthly-. ct+j) equals zero for all j not equal to t.t + q.Rf.~ (ERm. .
On a monthly basis. Monthly and quarterly prices were obtained from Timber Mart South (1987). TABLE 5. . It also suggests that there may be economic gain from short-term harvest flexibility or "playing the market" if the adjustment costs are small. but vary with the time interval for measuring departures from equilibrium rates of stumpage price change.period averaging. The results of the analysis are summarized in Table 5. This short-run inefficiency suggests that a CAPM for forest assets based on short-run. A departure from the equilibrium rate of change over one month tends to be followed by a departure in the opposite direction during the next month. markets for southern pine sawtimber stumpage do not pass this test.25 at the first lag and zero at all subsequent lags. however. monthly data is inevitably misspecified. the hypothesis of serial independence was a correlation coefficient of 0. indicating that stumpage markets are weak-form efficient. Blanks indicate that no data were available to test the model. On annual and quarterly bases.--Results of weak-form efficiency tests of markets for southern pine sawtimber stumpage State MonthlyTMS Price Changes (1977-1987) Stock Based Inflation Based Quarterly TMS Price Changes (1977-1987) Stock Based Inflation Based Annual State-Reported Price Changes (-1955-1987) Stock Based Inflation Based Alabama Arkansas Florida Georgia Kentucky Louisiana Mississippi North Carolina Oklahoma South Carolina Tennesee Texas Virginia I I I I I I I I I I I E I I I I I I I I I I I I I I E E E E I E E E E E E E E E E E E I E E E E E E E E E E E E E E --------------------------------------------------------------------------------------------------------------------- Note: E indicates that weak-form efficiency is not rejected and I indicates that weak-form efficiency is rejected. They are robust with respect to the model of equilibrium rate of return. departures from equilibrium rates were serially independent. annual prices from various state reports.
342. nearly double the beta for southern pine sawtimber stumpage in Louisiana of 0. timberland investments have low systematic risk and therefore comparatively low returns are adequate to justify ownership of forest assets. the CAPM beta. Different assumptions produce different measures of the return and risk of timberland investments. if the bulk of the variation in the return for forest assets results from changes in stumpage price. bare land value. First. CAPM results probably are more reliable for assets that consist primarily of mature stumpage than for those with large bare land or growing stock components. As shown in Table 2. our work to the present has concentrated on southern pine assets. analysis of rates of stumpage price change suggests that there are substantial geographic differences in the return and risk of timberland investments. the hedonic analysis will also indicate how actual market values have changed over time. the measures of the historic risk of timberland investments are more reliable than are the estimates of past risk-adjusted performance. another set of problems arise for estimating the CAPM equation.CONCLUSIONS AND FUTURE RESEARCH The issues discussed in this paper pose important econometric problems for applying the CAPM (along with portfolio theory and other pricing models) to forest assets. We are also designing an hedonic analysis of actual forestland sales in the South to measure directly the current market values of bare land and different ages of growing stock. Once a method for measuring historical forestry returns has been selected. we are conducting a survey of southern forestland appraisers to obtain their perceptions of these values. What are the consequences of using Forest Service cut prices as proxies for market values of stumpage in the West? Do the negative betas for rates of change in sawtimber stumpage price in Maine mean that timberland investments in this region are superior performers. it is possible to obtain reasonable estimates of asset risk. or do lower rates of growth for timber in Maine offset the lower risk. and the cost of holding forest assets.229. Second. Furthermore. and bare land values. Furthermore. timberland investments can diversify a portfolio of traditional financial assets. This errors-in-variables problem has biased estimates of CAPM parameters. the rate of change in the price of spruce sawtimber stumpage in Maine over a similar observation period produces a negative CAPM beta of about -0. growing stock. To the extent that we can obtain data on past sales. Our current efforts are proceeding on four fronts. it is difficult to estimate accurately asset performance as measured by the CAPM alpha. As noted earlier. Two basic results emerge from past work. the lack of information on the actual market value of bare land and growing stock impedes accurate estimation of the return for forest assets. However. Second. Several lines of research are important to strengthen these results. Lack of accurate records describing historical timberland returns forces analysts to construct time series based on assumptions about stumpage. Hence. . The primary source of confusion has been the reporting of stumpage prices as period averages. partly due to the availability of data and partly because of the importance of the region to nontraditional investors. past efforts at applying portfolio theory and asset pricing models to timberland investments provide useful information for investment analysts. the CAPM beta calculated from the rate of change in the cut price of Douglas-fir stumpage sold from national forests in the Pacific Northwest is 0. These initial results merit further attention. Despite the significance of these problems. First. However.3. lacking good data on growing stock value. Because data on stumpage prices are more extensive than data on growing stock and bare land values. which has caused past researchers to mismeasure market and risk-free returns.
rates of change in stumpage price are not related to realized inflation. Consumption. Laxenburg. Burkhart. . "An Intertemporal Asset Pricing Model with Stochastic Consumption and Investment Opportunities. "The Financial Risk of Private Timberland Investments in South Carolina. M. 1988b. These alternative models have not yet been applied to forest assets.L. inflation-adjusted CAPM's (Friend. Simulation of Individual Tree Growth and Stand Development in Loblolly Pine Plantations in Cutover. 1988.S.J. New Haven. and the Capital-Output Ratio. Binkley. The implications of these relationships for measures of forest risk deserve more attention. K. and R. Virginia Polytechnic Institute and State University. Brenner. Zinkhan 1989). it is possible to estimate a theoretical capital value for growing stock or bare land with the risk-free rate of interest without specifying either the required rate of return (or discount rate) for timber capital. an inflation-adjusted CAPM (which assumes that investors are concerned with real rather than nominal returns) would seem to be promising. Daniels. D. the validity of the traditional CAPM is arguable (Ro111977. CT. FWS-1-87. Farrar. Finally. further analysis indicates that timber returns are inversely related to the anticipated component of inflation and directly to the unanticipated component. School of Forestry and Environmental Studies. and the new equilibrium theory (Ibbotson. Yale University.C.F. Eliminating these parameters from the valuation problem has obvious advantages for empirical applications. Washburn.M. However.. In this framework. R. and R. VA.S. holding young timber can be viewed as ownership of either a forward contract or an option for delivery of stumpage at some future date (Washburn 1987.T. and operating costs. Production." Journal of Forestry forthcoming. Several alternative pricing models have been developed. Ross 1976). Diermeier. South. 1985. Blacksburg.. Pacific Northwest Research Station.D. K. Haynes.Third. 1988a. and Losq 1976). Long Run Timber Supply: Price Elasticity. or the expected rate of future stumpage price change. OR. C." Journal of Financial Economics 7:265-296.W. Amateis. and C. Landskroner. including intertemporal CAPM's (Merton 1973. Jackson. 1979. Site-Prepared Areas. "The Sensitivity of the Efficient Market Hypothesis to Alternative Specifications of the Market Model." Journal of Finance 34:915-929. D. we are investigating the use of models for pricing financial options to value forest assets." Unpublished manuscript. __ . Given the common view that timberland is a good hedge against inflation. H. timber growth. and Siegel 1984). Binkley. Breeden 1979). 1987. Ross 1978). Depending upon the stochastic processes for variables such as stumpage price. LITERATURE CITED Adams.L. As noted earlier in our description of the tests for stumpage market efficiency. Inventory Elasticity. School of Forestry and Wildlife Resources Publication No. Portland.S. USDA Forest Service Resource Bulletin PNW-RB-151. C. Austria. "The Diversification Potential of Forestry Investments: A Comment with Examples from the U. International Institute for Applied Systems Analysis WP-85-1O. and Prices of Softwood Products in North America: Regional Time Series Data. 1980. the Arbitrage Pricing Theory (APT. 1950 to 1985. Breeden.E.
J. Chicago." Land 1977. "Risk. Landskroner. Lintner. Merton." Econometrica 41:867-887. E. C.." ~ Science 30:1027-1038. T. F. Luppold. 1989.L.O. W. RG. 1984." Forest Science 23:281-288. R. 1984.H. 1988.. F. R 1988. Hoover. Friend. "A Derived Demand Approach to Estimating the Linkage Between Stumpage and Lumber Markets. "The Demand for Capital Market Returns: A New Equilibrium Theory. 1976. I. 1966." Journal of Finance 31:1278-1297. 1976. J. Haynes.W. Bonds. 1988. M. "The Demand for Risky Assets under Uncertain Inflation." Journal of Forestry 86: 19-24.W. Foundations of Finance.F. Redmond. Jr. and F. W. Cubbage. RW. "The Contribution of Timber Assets to the Returns and Variability of a Mixed Portfolio. NC. Economics 64:325-337.L. University of North Carolina. "Autocorrelation Between First Differences of Mid-Ranges. and T." In press. Jr. "The Biological Beta: Timberland in the Pension Portfolio. Mills. Cubbage.R. "An Econometric Study of the U.E. Losq. "The Valuation of Risk Assets and the Selection of Risky Investment in Stock Portfolios and Capital Budgets. and M. 1965." Financial Analysts Journal 40:22-33." University of Georgia Agricultural Experiment Stations Research Report No. J." Land Economics 58:33-51. W.. and L.B. "Forestland: Investment Attributes and Diversification Potential." 34:215-219. "An Intertemporal Capital Asset Pricing Model. Jr. Mills. Chapel Hill.E. Dierrneier. Redmond. these proceedings.L. Siegel. Econometrica DeForest. Basic Books. "A Critique of the Asset Pricing Theory's Tests.. Harris Jr.W. 562. NY. GA. C. 1969. Athens. Bills and Inflation: 1987 Yearbook." Journal of Financial Economics 4:129-176. and E. and C. Redmond. "Risk and Returns from Timber Investments. and W. . Hardwood Lumber Market. Ibbotson.G. Graduate School of Business.. 1982. Miles." Journal of Business 42: 167-247. Fama. 1977." Unpublished manuscript. Ibbotson Associates.G.H. 1987.S. H. Roll. 1973." Review of Economics and Statistics 47: 13-37. Y.Conroy. 1987. Harris. Daniels. Jensen. Stocks. New York. the Pricing of Capital Assets and the Evaluation of Investment Portfolios. Cubbage. RC. "Measuring Risk and Returns of Timber Investments using the Capital Asset Pricing Model. "Investment in Forest Land: Aspects of Risk and Diversification. IL. c.
" Journal of Economic Theory 13:341-360.A. __ . USDA Forest Service Miscellaneous Publication No. Rocky Mountain Forest Experiment Station. Baumgartner. The 1988 Symposium on Systems Analysis in Forest Resources." Unpublished manuscript.E. 1987. and C. Binkley." Journal of Finance 33:885-901. Sharpe. de Steiguer. R. Consumption. and D.A. J." Unpublished manuscript. NC. Trade. . If Thomson. 1453.S. CT. 1987. 1989a.S. 1971. CA. Berkeley. Washburn. c. NC. 1988. 1964. 1976. New Haven. "To Harvest or Not to Harvest? An Analysis of Cutting Behavior on Federal Timber Sales Contracts." in B. Washburn. Timber Mart South. CT. New Haven. University of California. 1978. Kent and L. "On the Use of Period-Average Stumpage Prices to Estimate Forest Asset Pricing Models. Davis. Kurtz. and Price Statistics: 1950-85. Asheville.L. 1987. CT. "Land Market Incentives for Forestry Investment in California. SAS Institute Inc. S. New Haven. __ ." Unpublished manuscript. eds. Cary. and J. Yale University." Review of Economics and Statistics 70:207-213. "The Value of Timber Capital in the Context of a Forward Contract for Stumpage. "A Simplified Model of Portfolio Analysis. "Capital Asset Prices: A Theory of Market Equilibrium Under Conditions of Risk. Highlands.C. "The Arbitrage Theory of Capital Asset Pricing. SASIETS User's Guide. USDA Forest Service General Technical Report RM-161. 1988. "The Current Status of the Capital Asset Pricing Model (CAPM).L.A. C. Thomson. DC. Version 5 Edition. Rucker. Busby. 1989b.M. 1988. B. 1963. and W. C. Wasburn. 1986 Yearbook. W. "Alternative Specifications and Solutions of the Timber Management Portfolio Problem. __ . NC. 1984. T." in RS. Department of Forestry and Resource Management.H. Ulrich. CO.S." Unpublished manuscript. "Statistical Analysis of Price Series Obscured by Averaging Measures.F. A. Frank Norris. "Informational Efficiency of Markets for Stumpage. Washington. T. Journal of Finance 19:425-442. Fort Collins. Timber Production." Management Science 9:277-293. School of Forestry and Environmental Studies." Journal of Financial and Qantitative Analysis 6: 1083-1094.L. Proceedings of the 1987 Joint Meeting of the Southern Forest Economics Workers and the Mid-West Forest Economists. "Financial Risk and Timber Portfolios for some Southern and Midwestern Species. School of Forestry and Environmental Studies. U.B. Ross. and K. Romm. eds.Rosenberg. Yale University. 1987. School of Forestry and Environmental Studies. Leffler.
and K.Working. 1960. Modern Portfolio Theory. "An Analysis of Timberland from a Modern Portfolio Theory Perspective. "Option Pricing: Timber and Timberland Valuation. Buies Creek. F. NC. H. __ .C. Mitchell.C. Buies Creek. Zinkhan. F. Lundy-Fetterman School of Business. Lundy-Fetterman School of Business. "Forestry Projects. "Note on the Correlation of First Differences of Averages in a Random Chain. Campbell University." Unpublished manuscript. NC. 1988." Econometrica 28:916-918." Southern Journal of Applied Forestry 12:132-135. 1989. Campbell University." Unpublished manuscript. and Discount Rate Selection. 1988. Zinkhan. . | https://www.scribd.com/doc/80241833/Capital-Asset | CC-MAIN-2018-13 | refinedweb | 8,733 | 50.12 |
Python module to provide a manhole in asyncio applications
Project Description.
I’m getting “Address is already in use” when I start! Help!
Unlike regular TCP/UDP sockets, UNIX domain sockets are entries in the filesystem. When your process shuts down, the UNIX socket that is created is not cleaned up. What this means is that when your application starts up again, it will attempt to bind a UNIX socket to that path again and fail, as it is already present (it’s “already in use”).
The standard approach to working with UNIX sockets is to delete them before you try to bind to it again, for example:
import os try: os.unlink('/path/to/my.manhole') except FileNotFoundError: pass start_manhole('/path/to/my.manhole')
You may be tempted to try and clean up the socket on shutdown, but don’t. What if your application crashes? What if your computer loses power? There are lots of things that can go wrong, and hoping the previous run was successful, while admirably positive, is not something you can do..
Change History
- 0.4.2 (3rd March 2017)
- Handle clients putting the socket into a half-closed state when an EOF occurs.
- 0.4.1 (3rd March 2017)
- Ensure prompts are bytes, broken in 0.4.0.
- 0.4.0 (3rd March 2017)
- Ensure actual syntax errors get reported to the client.
- 0.3.0 (23rd August 2016)
- Behaviour change aiomanhole no longer attempts to remove the UNIX socket on shutdown. This was flakey behaviour and does not match best practice (i.e. removing the UNIX socket on startup before you start your server). As a result, errors creating the manhole will now be logged instead of silently failing.
- start_manhole now returns a Future that you can wait on.
- Giving a loop to start_manhole now works more reliably. This won’t matter for most people.
- Feels “snappier”
- 0.2.1 (14th September 2014)
- Handle a banner of None.
- Fixed small typo in MANIFEST.in for the changelog.
- Feels “snappier”
- 0.2.0 (25th June 2014)
- Handle multiline statements much better.
- setup.py pointed to wrong domain for project URL
- Removed pointless insertion of ‘_’ into the namespace.
- Added lots of tests.
- Feels “snappier”
- 0.1.1 (19th June 2014)
- Use setuptools as a fallback when installing.
- Feels “snappier”
- 0.1 (19th June 2014)
- Initial release
- Feels “snappier”
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/aiomanhole/ | CC-MAIN-2018-13 | refinedweb | 415 | 77.43 |
OLPC talk:Wiki
From OLPC
Template for code fragments
Template:Code is based on and requires an entry in MediaWiki:Common.css.
Here is an example: Compare # pwd to
# pwd
It's meant to deal with the difficulty of reading reduced sized text on a gray background, which lowers contrast. Lighter gray and enlarged line-height and font-size should also be used for the <pre> and <tt> tags.
design thoughts
1. Wiki on a server
.Server. [ ---- Internet ] / / | \ \ 1 2 3 4 5 (support editing directly on a server. issues: edit conflicts, bw)
2. Wiki on a mesh
Server [ ---- Internet ] (direct editing of a server-based wiki) | __XO__ (shared net connection) / \ | | / \ / \ -1-2 .. N-M- (support machine-to-machine editing with a mesh portal. issues: portal vis)
3. Wiki locally / offline
(. . . .) | | | | | 1 2 3 4 5 (... connect to server or web infrequently)
interwiki map
I think it should be kept 'small' the map... too many inter-wikis and we'll probably not use them. Also specific olpc-related wikis (like Nepal's, Tuquito, or similar) should be added. 2cts --Xavi 11:32, 19 June 2007 (EDT)
extensions
parser extensions (or rather the ability to do 'if') in some templates would probably simplify and enhance the use of it. Possible collateral damage is making it to cryptic. --Xavi 11:32, 19 June 2007 (EDT)
language
I saw in the special pages, the Special:Withoutinterwiki (labeled 'Pages without language links'). I tried a bit but couldn't get it to work... --Xavi 11:32, 19 June 2007 (EDT)
Shiki_Wiki link colors
The Shiki_Wiki skin, now the default, currently shows "seen" links as gray. This makes them very hard to scan for, as they blend in with the black text. The blue "unseen" links are ok, but once you have seen an article, its links disappear. Since link following is currently our main navigational technique, especially with Search being broken, this seems a very bad thing. Why are we using a non-standard link color anyway? Visual design should make the user experience easier and more pleasant, not cognitively harder. I strongly suggest reverting to browser link coloring. MitchellNCharity 15:12, 2 August 2007 (EDT)
You also now can't tell, based on link color, whether a discussion page exists or not. So you have to hover the mouse, and look to see if the url ends in edit. (observation by Xavi) MitchellNCharity 15:43, 2 August 2007 (EDT)
- This shows up clearly on my monitors -- the gray vs blue for links and the gray vs white for existing vs empty talk pages. talk to the creator to get the colors changed! you can change your own back to monobook, of course, but better to get the skin fixed.... 59.112.162.93 16:57, 2 August 2007 (EDT)
- I think that the "Sugar" skin shouldn't be the default. I see it as a novelty thing, with no other reason for being: while there are reasons for the current Sugar look on the XO's (the dual-screen, power, and other design constrains), these don't apply to a collaborative wiki on the web. It also has some rendering issues with Konqueror. HoboPrimate 17:38, 2 August 2007 (EDT) But I don't want to bring down the effort of the person who did it, it's nicely emulates Sugar's look. HoboPrimate 17:43, 2 August 2007 (EDT)
merges and renames
better nomenclature:
- OLPCWiki: namespace --> OLPC:
- This page : The OLPC Wiki
- The OLPC Wiki --> Welcome
project suggestions
please suggest wikiprojects for this wiki here.
- OLPC Countries
- OLPC India, OLPC Mexico
- FAQ/query-help
- Repair/troubleshooting help
- Customization
- Build updates/installation
- Activities/Libraryes
- Specific wikiprojects for categories? peripherals.
- OLPC India - deployments, distribution, FAQs
- OLPC India - database of partnering organizations (combined with symantic wiki forms)
- OLPC India - content
Google Searching sans ads
As a non-profit, you should be able to get google search on this site without the ads. In google's Custom Search Engine page, there's a checkbox for non-profits to search without ads, and I assume later they ask for the tax-ID number, which is what they used to do.
Dialectric 11:55, 17 January 2008 (EST)
bad wiki!
The wiki looks awful in IE6. 158.59.194.136 10:59, 17 January 2008 (EST)
- I can't even log in! 158.59.194.136 10:59, 17 January 2008 (EST)
I'll check this out in IE6. I test with IE7 on WinXP myself; please post details of any js errors. --Sj talk 13:19, 3 February 2008 (EST)
Requested Extensions
I am very familiar with all of these scripting languages:
- EasyTimeLine
- GraphViz
- Google Maps
- Ogg Handler <== Must have
This would add pizzazz and a picture is worth a thousand words ... at least until the image namespace is all tidied up? — Katie 17:58, 21 January 2008 (EST)
- +1 on the OGG handler, it enables the world to view them as well. ffm 19:41, 21 January 2008 (EST)
- I'll add the above tonight if I can find time. Working on something for Google Spreadsheets at the moment; see below. --Sj leave me a message 10:00, 23 January 2008 (EST)
- Ogg Handler : needs 1.11
- EasyTimeline : needs more hand-tweaking; not quite working atm (renders svg but not png)
- GraphViz : needs testing.
- Google Maps : installed.
Spreadsheet from Google Spreadsheets, via the gspread extension:
Spreadsheet from Google Spreadsheets, via the gspread extension:
EasyTimeline
not working yet
trac extension
<trac>1<> results in ticket #1 (Every Child Needs A Laptop)
Could the ticket number be in small italic parens and the description be first and bolded? Would flow better for style...
Tried to make Template:Trac, failed! Style Nazi 10:26, 23 January 2008 (EST)
graphviz test
<graphviz renderer='neato' caption='Hello Neato'> graph G {
run -- intr; intr -- runbl; runbl -- run; run -- kernel; kernel -- zombie; kernel -- sleep; kernel -- runmem; sleep -- swap; swap -- runswap; runswap -- new; runswap -- runmem; new -- runmem; sleep -- runmem;
} </graphviz>
JS gadgets
Perhaps wikEd editor as a preference gadget would be proper. Katie 02:45, 6 February 2008 (EST)
custom user js
- ( my User:Katie/shikiwiki.js does not seem to load ... is this a skin-specific disabling? Katie 02:50, 6 February 2008 (EST)
Requesting stringfunctions extension
If you have a link to edit another page, I want Laptop per Child&action=edit§ion=new One Laptop per Child to work like One_Laptop_per_Child.
The stringfunctions are all order-n at worst, there are already worse DOS risks.
Homunq 14:34, 27 February 2008 (EST)
- I figured out how do everything I need to, except automatically transform lang-xx to xx, and that can be done with a finite number of templates.Homunq 14:56, 29 February 2008 (EST)
A modest proposal: multilingual portals
The translation infrastructure is in relatively good shape, and there are new non-English pages being made regularly. The last frontier is the stuff outside of the content box; the sidebar and top-bar. Since mediawiki architecture is already a bunch of independent processes (php scripts) accessing the database separately, there is no reason some of these couldn't be serving localized side- and top-bars. For instance, es.wiki.laptop.org could have a Spanish homepage, sidebar, and topbar, but still access the same database of wiki content.
From a quick web search, language is controlled by a single variable. As far as I can see, nobody has yet done what I propose, yet it is feasible. The top bar would just mean replacing the variable checks with a simple subroutine, and the sidebar could be an identical multilanguage sidebar with the correct one shown with css.
Homunq 14:56, 29 February 2008 (EST)
Recent Changes
It would be nice if someone would consider the several independent comments made (in various places) on the recent change in the "Recent Changes" link on the sidebar. Cjl's comment and FGrose's comment. Cjl 18:05, 27 April 2008 (EDT)
Allow upload of odg file format
I'd like to upload a couple of odg (open document graphics) files, which are the originals of some png's I have on the wiki here. Would it be possible to enable that format for upload? -- Tarun 11 August 2008 (EST)
Interwiki map?
Do you have a page where things can be added, or a policy on what is added and what isn't? There is a suggestion on this talk page (a minimalist approach) but that's only one comment.
The simplest solution would be to use the meta:interwiki map, and just add very specifically OLPC related sites to that. --Chriswaterguy 05:19, 22 August 2008 (UTC)
checkuser?
To add. | http://wiki.laptop.org/go/Talk:Wiki | CC-MAIN-2016-26 | refinedweb | 1,448 | 62.68 |
I have already posted Angle Control of Servo Motor using 555 Timer in which I have controlled servo motor using 555 timer and another tutorial about Controlling of Servo Motor using PIC Microcotroller in whcih I have controlled it with PIC microcontroller. And today we are gonna Control Servo Motor with Arduino and will design the simulation in Proteus ISIS. First of all, we will have a look at simple control of servo motor with arduino in proteus ISIS and then we will check the control of servo motor with arduino using buttons in which we will move the servo motor to precise angles using buttons. So, let’s get started with it. 🙂
Simple Control of Servo Motor with Arduino in Proteus
- First of all, open your Proteus ISIS software and design the below simple circuit.
- Servo Motor has three pins, one of them goes to Vcc, other one to GND while the center pin is the controlling pin and goes to any digital pin of Arduino. I have connected the control pin to pin # 4 of my Arduino.
- Next thing we need to do is to design the code for Arduino. So, open your Arduino software and copy paste the below code in it.
#include <Servo.h> Servo myservo; int pos = 0; void setup() { myservo.attach(4); } void loop() { for(pos = 0; pos <= 180; pos += 1) { myservo.write(pos); delay(15); } for(pos = 180; pos>=0; pos-=1) { myservo.write(pos); delay(15); } }
- Now compile this code and get your hex file. Its the same code as given in the Servo folder of Examples in Arduino software.
- Upload your hex file in your Proteus Arduino board.
Note:
- You should read How to get Hex File from Arduino, if you don’t know already.
- Now, run your simulation and you will see that your Servo motor will start moving from 90 degrees to -90 degrees and then back to 90 degrees and will keep on going like this, as shown in below figures:
- Now when you start it , first of all it will show the Position A in above figure then will move anticlockwise and pass the position B and finally will stop at Position C and then it will move clockwise and comes back to Position A after passing Position B.
- In this way it will keep on moving between Position A and C.
- Till now we have seen a simple control of Servo Motor with Arduino in Prtoteus ISIS, now lets have a look at a bit complex control of servo motor with Arduino.
Control Servo Motor with Arduino using Push Buttons
- In the previous section, we have seen a simple Control of Servo Motor with Arduino in which we simply moved Servo motor from 90 degrees to -90 degrees and vice versa. Now I am gonna control Servo motor using five push buttons and each push button will move the Servo motor to a precise angle.
- So, first of all, design a small design as shown in below figure:
- I have added five buttons with Arduino and now with these five buttons I will move Servo motor to 90 , 45 , 0 , -45 and -90 degrees. So, each buttons has its precise angle and it will move the motor to that angle only.
- So, now next thing is the code, copy paste the below code in your Arduino software and get the hex file:
#include <Servo.h> Servo myservo; int degree90 = 8; int degree45 = 9; int degree0 = 10; int degree_45 = 11; int degree_90 = 12; void setup() { myservo.attach(4); pinMode(degree90, INPUT_PULLUP); pinMode(degree45, INPUT_PULLUP); pinMode(degree0, INPUT_PULLUP); pinMode(degree_45, INPUT_PULLUP); pinMode(degree_90, INPUT_PULLUP); } void loop() { if(digitalRead(degree90) == LOW) { myservo.write(180); } if(digitalRead(degree45) == LOW) { myservo.write(117); } if(digitalRead(degree0) == LOW) { myservo.write(93); } if(digitalRead(degree_45) == LOW) { myservo.write(68); } if(digitalRead(degree_90) == LOW) { myservo.write(3); } }
- Upload this hex file to your Arduino board in Proteus and run the simulation.
- Now press these buttons from top to bottom and you will get the below results:
- The above figure is quite self explanatory but still I explain a little.
- In the first figure I pressed the first button and the motor moved to -90 degrees.
- In the second figure I pressed the second button and the motor moved to -45 degrees.
- In the third figure I pressed the third button and the motor moved to 0 degrees.
- In the fourth figure I pressed the fourth button and the motor moved to 45 degrees.
- In the fifth figure I pressed the fifth button and the motor moved to 90 degrees.
- In the sixth figure all buttons are unpressed and the motor remained at the last position.
It was quite simple and hope I explained it quite simply, if you still have any questions then ask in comments and I will try to resolve them. That’s all for today, will see you guys in the next tutorial. Take care !!! 🙂
14 Comments
programs gives error in proteus, even copied from arduino site but no success
invalid opcode 0x9142
soory, invalid opcode 0x9419
You are getting this error in Arduino or Proteus ???
in proteus even tried in proteus 7, normally I used proteus 8
You must be doing some mistake while designing the simulation. Make sure you uploaded the hex file correctly.
sir for simulation arduino is necessary?or we can do it through only software?
Yes you can work only using software.
What’s the meaning of myservo.write(180),(117),(93),(68),(3)?
Good day Sir.
#include <Servo.h> // what is this?
thank you?
my servo motor automatically starts even before pressing the push button ???????
whats the problem
I think you should check it again if its working properly ,because i face the same issue at end i come to know that the motor was not working properly ,its controlling function was damaged.
could you please specify the servo motor specifications ( the servo motor details ) i.e the max, min angles we should set or leave it at default
Thanks for sharing such an informative article.
sir it is good description it work properly
but I need same help in voice Control Dc Motor with Arduino by android phone for my project can you help me
with code please sand to me please please
Thank you. | https://www.theengineeringprojects.com/2015/11/control-servo-motor-arduino-proteus.html | CC-MAIN-2019-51 | refinedweb | 1,051 | 69.62 |
This article appears in the Third Party Products and Tools section. Articles in this section are for the members only and must not be used to promote or advertise products in any way, shape or form. Please report any spam or advertising.
A lot has been written about Microsoft s new data access technology LINQ (Language Integrated Query) since the first preview version has been published. But there are still some interesting aspects to LINQ and its extensibility. This article will introduce a new provider called LINQ to SAP which offers an easy way to retrieve business data from SAP/R3 systems within a .NET application.
With the introduction of the .NET framework 3.5 and the programming language extensions for C# and VB.NET Microsoft began to redefine the way developers would implement data access. Nearly all applications today are querying data from different data sources. Mainly those data sources are SQL databases, XML files or in-memory collections. LINQ offers an universal and standardized approach to access all those data sources using special data providers. The LINQ language syntax strongly resembles that of SQL. The following sample shows how to query data from a string array with LINQ:
string[] names = {"John", "Patrick", "Bill", "Tom"}
var res = from n in names where n.Contains("o") select n;
foreach(var name in res)
Console.WriteLine(name);
This simple LINQ query based on an in-memory collection (array) selects all items in the array names that contain the letter o. Console output: John, Tom . A LINQ introduction is beyond the scope of this article. A very good introduction article can be found on CodeProject.com.
The .NET framework comes with built-in providers for collections and lists (LINQ to Objects), for Microsoft SQL Server databases (LINQ to SQL), for XML files (LINQ to XML) and finally for DataSet object instances (LINQ to DataSet). Beside the standard providers, developers can extend LINQ by creating custom providers to support special data sources. LINQ to LDAP or LINQ to Amazon are examples of such custom providers.
To write a custom LINQ provider one must basically implement two interfaces: IQueryable and IQueryProvider. These interfaces make objects queryable in LINQ expressions. Developing a LINQ provider can be a very complex task, but there a quite some good blog entries on the net explaining the steps in detail.
This article will introduce a new provider called LINQ to SAP from Theobald Software which provides developers with a simple way to access SAP/ R3 systems and their data objects. The software also provides a Visual Studio 2008 Designer to define SAP objects interactively and integrate them in .NET applications.
This section will give you a short explanation and background of SAP objects that are queryable by LINQ to SAP. The most important objects are Function Modules, Tables, BW Cubes and Queries.
A Function Module is basically similar to a normal procedure in conventional programming languages. Function Modules are written in ABAP, the SAP programming language, and are accessible from any other programs within a SAP/ R3 system. They accept import and export parameters as well as other kind of special parameters. The image below shows an example of a Function Module named BAPI_EQUI_GETLIST within the SAP Workbench:
In addition BAPIs (Business-API) are special Function Modules that are organized within the SAP Business Object Repository. LINQ to SAP also allows access to SAP tables. Those are basically straightforward relational database tables. Furthermore the LINQ to SAP Designer allows developers to define and access BW Cubes (Business Cube Cubes) and Queries (SAP Query). BW Cubes are also known as OLAP Cubes. Data are organized in a multidimensional way within a cube. SAP Queries work just like other queries. To indentify a SAP Query uniquely there are three pieces of information necessary: user area (global or local); user group and the name of the query. With the concept of Queries SAP provides a very simple to generate reports, without the need of knowing the SAP ABAP programming language.
In order to use LINQ to SAP and the associated Visual Studio Designer, the .NET library ERPConnect.net from Theobald Software must be installed first. This software is the basic building block between .NET and a SAP/R3 system and provides an easy API to exchange data between the two systems. The company offers a free trial version to download. After installing ERPConnect.net, LINQ to SAP must be installed separately using a setup program (see manual). The provider and the designer are actually extensions to the ERPConnect.net library. The LINQ to SAP provider itself consists of the Visual Studio 2008 Designer and additional class libraries that are bundled within the namespace ERPConnect.Linq.
The setup adds a new ProjectItem type to Visual Studio 2008 with the file extension .erp and is linking it with the designer. Double-clicking the .erp-file will open the LINQ to SAP Designer. The designer supports application developers with the option to automatically generate source code to integrate with SAP objects. For all defined SAP objects in an .erp file, the provider will create a context class which inherits from the ERPDataContext base class. The generated context class contains methods and sub-classes that represent the defined SAP objects. Beside the .erp file, LINQ to SAP designer will save the associated and automatically generated source code in a file with the extension .Designer.cs.
This section shows how to access and obtain data using the function module BAPI_EQUI_GETLIST by creating a LINQ to SAP object. The module is returning an equipment list for pre-defined plants. First of all one must add a new LINQ to SAP file (.erp) to a new or existing Visual Studio 2008 project. By opening the .erp file the LINQ to SAP Designer will start. By double-clicking on the Function item in the toolbox of Visual Studio will add a new SAP object Function Module. In the next step the object search dialog opens and the developer can search for function modules.
Once the selection is made, the LINQ to SAP Designer will show up the Function Module dialog box with all data, properties and parameter definitions of the selected module BAPI_EQUI_GETLIST. The user can now change the naming of the auto-generated method as well as all used parameters.
For each function module the LINQ to SAP Designer will generate a context class method with all additional object classes and structures. If for instance the user defines a method name called GetEquipmentList for the function module BAPI_EQUI_GETLIST, the designer will generate a context class method with that name and the defined method signature. The user can also specify the parameters to exchange. The lower area of the dialog is displaying the SAP typical parameters, like IMPORT, EXPORT, CHANGING and TABLES parameters. LINQ to SAP allows to define default values for SAP parameters. Those parameters can also be used as parameters for the auto-generated context class method as well as for return values. The names for the parameters and the associated structures can also be renamed.
The method signature for the function module defined above looks like this:
public EquipmentTable GetEquipmentList(PlantTable plants)
The context class itself is named SAPContext by default. The context class name, the namespace, the connection settings as well as other flags can be defined in the properties window of the LINQ to SAP Designer. The following code shows how to use the context class SAPContext:
class Program
{
static void Main()
{
SAPContext dc = new SAPContext("TESTUSER", "XYZ");
SAPContext.PlantTable plants = new SAPContext.PlantTable();
SAPContext.PlantStructure ps = plants.Rows.Add();
ps.SIGN = "I";
ps.OPTION = "EQ";
ps.LOW = "3000";
SAPContext.EquipmentTable equipList = dc.GetEquipmentList(plants);
}
}
The procedure for adding a SAP Table is basically the same as for function modules (see above). After adding the SAP Table object from the toolbox in Visual Studio and finding the table with the search dialog, the Table dialog will show up:
In the upper part of the table dialog the user must define the class name for table object for auto-generation. The default name is the name of the table. The lower part shows a data grid with all table fields and their definitions. For each field a class property name can be defined for the auto-generated context class code. The checkbox in the first column selects if the field will be part of the table class.
The figure above shows the definition of the SAP Table object T001W. This tables stores plant information. The class has not been changed, so the designer will create a C# class with the name T001W. In addition the context class will contain a property T001WList. The type of this property is ERPTable<T001W>, which is LINQ queryable data type.
The following code shows how to query the table T001W using the context class:
class Program
{
static void Main()
{
SAPContext dc = new SAPContext("TESTUSER", "XYZ");
dc.Log = Console.Out;
var res = from p in dc.T001WList
where p.WERKS == "3000"
select p;
foreach (var item in res)
Console.WriteLine(item.NAME1);
}
}
To access objects using LINQ to SQL, the provider will generate a context class named DataContext. Accordingly LINQ to SAP also creates a context class called SAPContext. This class is defined as a partial class. A partial class is a type declaration that can be split across multiple source files and therefore allows developers to easily extend autogenerated classes like the context class of LINQ to SAP.
The code sample below shows how to add a partial class (file SAPContext.cs) which adds a new custom method GetEquipmentListForMainPlant to extend the context class generated by the LINQ to SAP designer. This new method calls internally the auto-generated method GetEquipmentList with a pre-defined parameter value. The C# compiler will internally merge the auto-generated LINQtoERP1.Designer.cs with the SAPContext.cs source file.
using System;
namespace LINQtoSAP
{
partial class SAPContext
{
public EquipmentTable GetEquipmentListForMainPlant()
{
SAPContext.PlantTable plants = new SAPContext.PlantTable();
SAPContext.PlantStructure ps = plants.Rows.Add();
ps.SIGN = "I";
ps.OPTION = "EQ";
ps.LOW = "3000";
return GetEquipmentList(plants);
}
}
}
LINQ to SAP also provides the capability to log LINQ query translations. In order to log data the LOG property of the context class must be set with a TextWriter instance, e.g. the console output Console.Out. All LINQ to SAP does is a very rudimentary logging which is restricted to table objects. But it helps developers to get a feeling about what the translated where part looks like.
In overall LINQ to SAP is very simple but yet powerful LINQ data provider and Visual Studio 2008 Designer to use. You also get a feeling on how to develop against a SAP/R3 system using .NET. For more information about the product please check out the homepage of the. | https://www.codeproject.com/Articles/27891/LINQ-to-SAP | CC-MAIN-2018-34 | refinedweb | 1,799 | 57.27 |
IDE - CodeBlocks
Compiler - GNU GCC
Hello,
I ran into a C++ exercise has me stumped. A program is to ask for a sentance, then it splits it up into individual words and puts the sentance back together with ampersands inplace of the white space.
My program is able to take the sentance and show it split into words. However, when it goes to show the sentance with the ampersands it errors and ends with "Process terminated with status -1073741819"
I don't understand how I have errored. Any suggestions would be greatly apprecaited.
My code:
Code:
#include <iostream>
#include <cstring>
using namespace std;
int main(){
char *p;
char string[81];
char string2[81];
cout << "Input a string to parse: ";
cin.getline(string, 81);
p = strtok(string, ", "); // gets first token
strncpy(string2, p, 81); // copies first token to string2
strcat(string2, "&"); // concatenate string "&" to string 2
cout << p << endl; // print out token
while(p != NULL){ // Do until end of sentance
p = strtok(NULL, ", "); // gets next token
strncpy(string2, p, 81); // copies token to string2
strcat(string2, "&"); // concatenate string "&" to string 2
cout << p << endl; // print out token
}
cout << string2 << endl; // print out string2
return 0; | http://cboard.cprogramming.com/cplusplus-programming/145467-string-manipulation-issues-printable-thread.html | CC-MAIN-2015-32 | refinedweb | 194 | 65.25 |
You may have guessed this based on my recent posts, but I’m writing a web application. Some of my stuff is in ASP.NET and some is client-side. This is one of those client-side things. I want to be able to create a pop-up menu. There are a lot of resources out there for creating menus. However they all pretty much have one thing in common. They show you how to create the menu with in-line HTML. In other words, you have to know what your menu is going to look like. In any reasonably complex application this is going to create an explosion of additional stuff in your HTML. What if you have a modular system or role-based access controls and your menu structure comes from a REST call? What I am going to do in this article is show one way to get all this using jQuery.
Let’s start with the basics. I’ve got a web page with the following contents:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>My Test Page</title> <link rel="stylesheet" href=""> <link href="site.css" rel="stylesheet"> </head> <body> <header> <ul> <li id="nav-search"><span class="glyphicon glyphicon-search"></span></li> </ul> </header> <script src=""></script> <script src=""></script> <script src="site.js"></script> </body> </html>
This is a part of a bigger project, but I push functionality like this out to its own set of files while I am developing it. When I’m happy with it, I’ll merge the functionality back into my main application later. All I’ve done here is create a search icon. You can actually run this file (I use Chrome in general for development as I prefer the developer tools, but many people use Firefox and Firebug or Internet Explorer). I do need a little bit of initial styling so that it looks like a toolbar, so I’ve placed the following in the site.css file:
html, body { width: 100%; height: 100%; margin: 0 !important; padding: 0 !important; } header { width: 100%; height: 50px; background-color: #666666; color: #f0f0f0; } header ul { display: block; list-style: none; padding-top: 8px; } header ul li { display: inline; font-size: 28px; }
I’ve also got an empty site.js file. Again – run what you have and make sure it looks good – I do this often as I go along.
Now that I have all the pre-work done, Let’s get down to our task at hand – making a pop-up search box. I like to create a short list of things I have to implement in order to accomplish my desired functionality. In this case:
- Click on the Search button
- Make a DIV with content appear when I click on the Search button
- Make the DIV disappear if I click on the search button again
- Style the DIV so it looks like a talk bubble
As a design goal, I want to create an object for my functionality that I can take the component elsewhere via cut-and paste and minimize code that can be mixed up with other stuff.
My first step is to create an object for my functionality. I’ve got a very good book called Javascript Patterns by Stoyan Stefanov and Chapter 5 covers a pattern called the Namespace Pattern. I highly recommend reading what this book has to say about object creation patterns. I’m going to simplify things in the interest of time – this is not an article on the best way to create objects.
var My = My || {}; My.Searchbox = { Register: function(id) { $(id).css({ 'cursor': 'pointer' }) .click(My.Searchbox.ClickHandler); }, ClickHandler: function(evt) { alert("You clicked Me!"); evt.stopPropagation(); } }; $(document).ready(function() { My.Searchbox.Register('#nav-search'); });
Let’s take a moment to analyze what I have done here. I’ve created a namespace My (using one of the easier patterns from the book). I’ve then created my Searchbox object – this is accessed using normal Javascript dotted notation – My.Searchbox. I’ve created two functions in this object – one called Register that takes an id, and one called ClickHandler that takes an event. In the Register function, I’m adding a bit of CSS to the passed-in id that changes the cursor to something that indicates it is clickable and I’m adding a click handler that is the other function in my object. I’m just alerting that we got here in the ClickHandler.
The other section of the file is the standard jQuery startup method. It basically says “when the DOM is ready for me, run this function”. In my case, I’m calling my Register method with the ID of the search icon. Run this and two things should happen. Firstly, when you hover over the search icon it should look clickable. Then, when you click on it (or – on a touch screen – touch it), you should see an alert. So far, so good. Item number 1 on my desired functionality has been done. Let’s move onto number 2 and number 3.
I like to have a little logic in my brain before I start writing code. In this case the pop-up bubble doesn’t exist yet, so I’m going to have to create it. However, if it already exists, then that means I’ve already clicked on the search icon, so I want to delete the pop-up bubble instead. My logic is something like “check to see if the pop-up bubble exists – if it does, then remove it, otherwise create it” – your standard if-then-else block. I’m expecting to have to make a bunch of these DIV objects, so let’s create a utility method for this in another object. This allows me to re-use it for any DIV I might need to create. I’ve added the following section to my site.js file:
My.Utils = { CreateDiv: function(id, cssClass, left, top, width, height) { return $("<div id='" + id + "' class='" + cssClass + "'></div>") .appendTo('body') .css({ 'display': 'block', 'position': 'absolute', 'left': left + 'px', 'top': top + 'px', 'width': width + 'px', 'height': height + 'px' }); } }
Here I’ve created a new method for creating a DIV. It creates the HTML (a DIV with an ID and a class that are passed in), appends it to the BODY area of my HTML document and then explicitly sets the position and size of the object. This isn’t perfect code. Explicitly, if you specify a left/width or a top/height that would place the DIV outside of the viewport then you won’t see your DIV. I return the created object so that whatever creates it can continue using it (perhaps to add more content or style). Let’s add a small amount of style to the site.css file so we can see our work:
.bubble { border: 1px solid blue; background-color: blue; color: white; }
Also, let’s adjust the ClickHandler – I want to actually see a box appear:
ClickHandler: function(evt) { var clicked = $(evt.currentTarget), CreateDiv = My.Utils.CreateDiv; CreateDiv('searchBox', 'bubble', 80, 100, 300, 100); evt.stopPropagation(); }
Running the result should create a nice blue box on the screen when you click the search icon. It isn’t in the right place and it’s the wrong shape. It also doesn’t go away when you click on the search icon again. Let’s start by making it go away when you click again. In jQuery, the result of a selector is an array. Using the Javascript console in developer tools I can type in any valid javascript. My ID is ‘#searchBox’, so I can type $('#searchBox') in the Javascript console and see the object. Do it before you click on search icon and after. Arrays have a length, so I can use $('#searchBox').length to determine if the search box is visible. This allows me to decide whether to create it or destroy it:
ClickHandler: function(evt) { var clicked = $(evt.currentTarget), id = 'searchBox', CreateDiv = My.Utils.CreateDiv; // Find out how many search boxes there are // -> More than 1, then destroy them if ($('#'+id).length > 0) { $('#'+id).remove(); return; } // If there are no search boxes, then fall through // to here and create one. CreateDiv('searchBox', 'bubble', 80, 100, 300, 100); }
Now you can click on the search icon and the blue box will appear or disappear. Before I can call Items 2 and 3 done I need to have a search box inside of my DIV:
// If there are no search boxes, then fall through // to here and create one. var srch = CreateDiv('searchBox', 'bubble', 80, 100, 300, 100); srch.html("<div class='search'><input type='text' name='search' placeholder='Search'></div>");
That about covers it for items 2 and 3 – I’ve got my search box appearing and disappearing and there is an actual search box inside it. Now let’s move to item 4 – styling. First of all the box isn’t in the right place – it’s probably not the right size either. I have no idea where my designer will place that search icon eventually so I’m going to have to calculate the location. I may have to adjust the size, but for right now, I’m going to guess. I can always use the F12 Developer Tools to adjust the CSS later and then copy the results back into my JavaScript. jQuery provides .position() and several size methods for getting the position and size of a DIV. My CreateDiv method has positioning and size information passed to it. I’ve pretty much ideally set things up for this:
// Compute the size and position relative to what was clicked var left = clicked.position().left - 24, top = clicked.position().top + clicked.height() + 16, width = 300, height = 50; // If there are no search boxes, then fall through // to here and create one. var srch = CreateDiv('searchBox', 'bubble', left, top, width, height);
Again, this is not ideal. What if the search icon was flush with the left side of the screen? Then the left side of the search box would be off the screen. What if the search icon was on the footer or (more commonly) on the right hand side of the screen? All of these are easily handled once you have the basic case done. It’s just a question of calculating the right position for the box.
Now that I have the right position, I want to style the box – I like a border with a drop shadow and curved boxes. I also like a search icon before the box and no border on my search box. This is “just style”, but I’m not a CSS guru. The way I do this is to mess with the style in the developer tools until I get it right and then I cut and paste it into the site.css file. I always have problems with drop shadows, but there are some great references – my favorite is Microsofts MSDN article. I downloaded my search icon from iconfinder.com. This is what I came up with:
.bubble { background-color: white; border: 1px solid #C0C0C0; border-radius: 8px; box-shadow: 2px 2px 2px 2px gray; color: white; } .search { background: url(search-32.png) no-repeat; padding-left: 40px; height: 32px; margin-top: 8px; margin-left: 8px; } .search input { font-size: 18px; border: 0; margin-top: 2px; color: #666666; }
Now that I have a basic pop-up, I want to make it a “chat” bubble. I know – I teased about this in the title and it’s taken me this long to get around to it, but it’s really the last thing to do. In order to make it a chat bubble, I need to add a CSS3 shape. There is a huge list of CSS shapes and css-tricks.com has a habit of showing off these sorts of tricks. In this case, they have a demo on what you can do. I want to position an up triangle in the right place on my search box right under the search icon that is activating the box. To do this I need to use the :before selector in CSS3 for this. As I always do, I write something basic to get the selector into the F12 developer tools, then tweak it and finally copy it back to the file. I started with this:
.bubble:before { content: ''; width: 0; height: 0; border-left: 10px solid transparent; border-right: 10px solid transparent; border-bottom: 10px solid red; }
And my final CSS:
.bubble:before { content: ''; width: 0; height: 0; position: absolute; left: 20px; top: -16px; border-left: 16px solid transparent; border-right: 16px solid transparent; border-bottom: 16px solid #C0C0C0; }
This is almost there. I wanted an outline though, not a solid triangle. This isn’t directly supported, but I’ve got two elements – the bubble outer DIV and the search inner DIV. I can use the search inner DIV to do the same thing in white, like this:
.search:before { content: ''; width: 0; height: 0; position: absolute; left: 22px; top: -14px; border-left: 14px solid transparent; border-right: 14px solid transparent; border-bottom: 14px solid white; }
This is what the resulting search box looks like:
Now I’m ready to integrate this functionality back into my main program. | https://shellmonger.com/2015/03/04/adding-a-pop-up-search-bubble-to-your-web-application/ | CC-MAIN-2017-13 | refinedweb | 2,221 | 72.56 |
Should You Use Schedule C or Schedule K-1 in Your Individual Tax Return
It's the inevitable income tax time again! You will file your personal income tax return on the 15th of April, or the "next business day" if it falls on a weekend or holiday. What income do you need to file on April 15? It is all the money you earned the year before.
Example: Your income is $25,000 for the whole year of 2012. You will file your personal Income Tax on April 15, 2013. In other words, you have 3 1/2 months to put together your tax return and file it on or before the said due date.
There are several tax forms that requires to be filled out. The IRS have many tax forms which has different uses and distinct purposes. Two of them are Schedule C and Schedule K-1. These forms have specific purposes and classifications. You have to choose correctly which form you need to prepare.
What is Schedule C?
Many individuals are small business owners or called a single proprietor. The business is usually managed by the proprietor itself and the business structure is not as complex as a partnership or corporation.
The Internal Revenue Service (IRS) made it easier for small businesses to file its income and expenses during the tax year by using Schedule C. The Schedule C can be found only in your personal income tax return (1040).
The Schedule C is the complete information you will provide to IRS as to how much your business has earned during the year (gross amount). You will also itemize your business expenses, backed with receipts. If there is profit left (net gain or net revenue), it will be added to the rest of your income from other sources during the year.
Your net income from Schedule C is subject to Self-Employment tax. Self-Employment tax is paying your own Social Security and Medicare contribution for both the employee's and the employer's share. Int this case, since you are considered as an employer to yourself, 50% of your self-employment tax becomes deductible in your personal income tax return.
Example 1: I earn money on the side from writing on Hubpages. Since a freelance writer is considered as self-employment, I will use Schedule C when I file my income tax return for the earnings from Hubpages.
Example 2: I sell merchandise to the public, whether on-line or delivering the actual products to my customers. I didn't register my business as a partnership or corporation. Therefore, I will use Schedule C when I file my income tax return.
Example 3: I teach piano lessons or Taekwando on weekends. All the income I received from rendering my services from teaching piano lessons and Taekwando will be on Schedule C.
What is Schedule K-1?
Schedule K-1 is used when you are part owner of a Partnership or S-Corporation. The legal structure of a partnership and S-Corporation is usually owned by two or more persons. There are certain exceptions by owning it 100% yourself. The form Schedule K-1 is the "proof" of your income, expenses or losses from your partnership or S-Corporation business.
Schedule K-1 is also called a "pass-through". It means that all the income from your Partnership or S-corporation earned during the year, whether you took money from those earnings or not, will be taxed on your personal return (1040). It is also the same with the business losses.
By the looks of it, being a partner in a partnership or a stockholder in an S-Corporation, you are really taxed personally on your individual income tax return.
Visit the IRS website at:
Therefore as a taxpayer, you need to know what are the basic tax laws and correct forms to use in order to file your tax return properly.
It is best to consult with your Certified Public Accountant (CPA), Enrolled Agent (EA) or any IRS Certified Tax Preparer if you are not sure how to prepare your Income Tax Return correctly.
Copyright © 2012 The Girls. All rights reserved. Reproduction in whole or in part in any form or medium without permission prohibited.
Related Articles
- How to Get a Federal Tax ID Number in the U.S.
Learn how to get your Federal Tax ID Number
- Can I Take a Loan From My IRA Account?
Can you take a loan from your IRA without paying a penalty? The answer is yes. You can also borrow money from your employer sponsored retirement funds such as 401 (k).
Thank you for such a great info. I was able to come across this online service that allows you to easily edit your PDF documents. () You can fill out PDF form, save it, fax it, and email it. You might want to try, it was good!
Useful hub!!
Thanks for the information. I am going to have to look into this when we file our taxes.
3 | https://hubpages.com/business/Should-You-Use-Schedule-C-or-Schedule-K-1-in-Your-Individual-Tax-Return | CC-MAIN-2018-09 | refinedweb | 840 | 73.37 |
Additional Data
Additional data attached to an event can be predefined or custom.
Predefined data is data that Sentry recognizes and uses to enhance the user experience. For example, Sentry's concept of a user lets us show how many unique users are affected by an issue. Sentry automatically captures predefined data where possible, such as information about the browser, HTTP request, and OS in the browser JavaScript SDK.
Custom data is arbitrary structured or unstructured extra data you can attach to your event.
Tags & Context
Whether predefined or custom, additional data can take two forms in Sentry: tags and context.
Tags are key/value string pairs that are indexed and searchable. They power UI features like filters and tag-distribution maps.
Context includes additional diagnostic information attached to an event. By default, contexts are not searchable, but for convenience Sentry turns information in some predefined contexts into tags, making them searchable.
Predefined Data
The most common types of predefined data (where applicable) are level, release, environment, logger, fingerprint, user, request, device, OS, runtime, app, browser, gpu, monitor, and traces.
To improve searchability, Sentry will turn the data or specific attributes on the data into tags. For example,
level is available as a tag, and so is a user's email via the
user.email tag. If Sentry is captures some predefined data but doesn't expose it as a tag, you can always set a custom tag for it.
Capturing the User
Capturing the user unlocks several features, primarily the ability to look at the users being affected by an issue, as well to get a broader sense of the quality of the application.
using Sentry; SentrySdk.ConfigureScope(scope => { scope.User = new User { Email = "john.doe@example.com" }; });
Users are applied to construct a unique identity in Sentry. Each of these is optional, but one must be present for Sentry to collect data about the user:
id
- Your internal identifier for the user.
username
- The username. Generally used as a better label than the internal ID.
- An alternative (or addition) to a username. Sentry recognizes email addresses and can show things like Gravatars, unlock messaging capabilities, etc.
ip_address
- The IP address of the user. If the user is unauthenticated, Sentry uses the IP address as a unique identifier for the user. Sentry will attempt to pull this from HTTP request data, if available.
Additionally, you can provide arbitrary key/value pairs beyond the reserved names, and Sentry will store those with the user, but the arbitrary key/value pairs are unsearchable.
Setting the Level
You can set the severity of an event to one of five values:
fatal,
error,
warning,
info, and
debug.
error is the default,
fatal is the most severe, and
debug is the least severe.
using Sentry; SentrySdk.ConfigureScope(scope => { scope.Level = SentryLevel.Warning; });
For more details about how to set predefined properties, see the platform-specific documentation.
Custom Data
You can attach arbitrary custom data to an event as tags or context.
As mentioned, tags are searchable key/value pairs attached to events that are used in several places: filtering issues, quickly accessing related events, seeing the tag distribution for a set of events, etc. Common uses for tags include hostname, platform version, and user language.
Most SDKs support configuring tags by configuring the scope:
using Sentry; SentrySdk.ConfigureScope(scope => { scope.SetTag("page.locale", "de-at"); });
Sentry promotes several pieces of predefined data to tags. We strongly recommend you don't set custom tags with these reserved names. But if you do, you can search for them with a special tag syntax.
Context
Custom contexts allow you to attach arbitrary data (strings, lists, dictionaries) to an event. These are unsearchable, but are viewable on the issue page.
using Sentry; SentrySdk.ConfigureScope(scope => { scope.SetExtra("character.name", "Mighty Fighter"); });
In the past, custom context was called "extra" and set via a method like setExtra(), which is deprecated.
Custom data set using
setExtra appears in the "Additional Data" section of an event. By contrast, each key set using
setContext gets its own section on the issue page, with the section title being the key name.
For more details about predefined and custom contexts, see the full documentation on Context Interface.
Context Size Limits
Maximum payload size: There are times when you may want to send the whole application state as extra data. Sentry doesn't recommend this as the application state can be extensive and easily exceed the 200kB maximum that Sentry has on individual event payloads. When this happens, you’ll get an
HTTP Error 413 Payload Too Large message as the server response (when
keepalive: true is set as
fetch parameter), or the request will stay in the
pending state forever (for example, in Chrome).
Sentry will try its best to accommodate the data you send, but Sentry will trim large context payloads or truncate the payloads entirely.
For more details, see the full documentation on SDK data handling.
Unsetting Context
Sentry holds context in the current scope, and thus context clears out at the end of each operation (for example, requests). You can also push and pop your scopes to apply context data to a specific code block or function.
For more details, see the full documentation on Scopes and Hubs.
Debugging Additional Data
You can view the JSON payload of an event to see how Sentry stores additional data in the event. The shape of the data may not exactly match the description above because our thinking around additional data has evolved faster than the protocol.
For more details, see the full documentation on Event Payload. | https://docs.sentry.io/enriching-error-data/additional-data/?platform=javascript | CC-MAIN-2020-34 | refinedweb | 933 | 55.13 |
First, unless you've already done so, you will need
to grab a copy of the Google Web APIs
Developer's Kit () and
create a Google account and obtain a license key []. As I write this, the free license key
entitles you to 1,000 automated queries per day. This is more than
enough for a single IRC channel.
The googleapi.jar file included in the kit
contains the classes that the bot will use to perform Google
searches, so you will need to make sure this is in your classpath
when you compile and run the bot (the simplest way is to drop it into
the same directory as the bot's code itself).
The GoogleBot is built upon the
PircBot Java IRC API (), a
framework for writing IRC bots. You'll need to
download a copy of the PircBot ZIP file, unzip it, and drop
pircbot.jar into the current directory, along
with the googleapi.jar.
TIPFor more on writing Java-based bots with the PircBot Java IRC API, be
sure to check out "IRC with Java and
PircBot" [Hack #35] in IRC
Hacks (O'Reilly) by Paul Mutton.
For more on writing Java-based bots with the PircBot Java IRC API, be
sure to check out "IRC with Java and
PircBot" [Hack #35] in IRC
Hacks (O'Reilly) by Paul Mutton.
Create a file called GoogleBot.java:
import org.jibble.pircbot.*;
import com.google.soap.search.*;
public class GoogleBot extends PircBot {
// Change this so it uses your license key!
private static final String googleKey = "000000000000000000000000000000";
public GoogleBot(String name) {
setName(name);
}
public void onMessage(String channel, String sender, String login,
String hostname, String message) {
message = message.toLowerCase( ).trim( );
if (message.startsWith("!google ")) {
String searchTerms = message.substring(8);
String result = null;
try {
GoogleSearch search = new GoogleSearch( );
search.setKey(googleKey);
search.setQueryString(searchTerms);
search.setMaxResults(1);
GoogleSearchResult searchResult = search.doSearch( );
GoogleSearchResultElement[] elements =
searchResult.getResultElements( );
if (elements.length == 1) {
GoogleSearchResultElement element = elements[0];
// Remove all HTML tags from the title.
String title = element.getTitle( ).replaceAll("<.*?>", "");
result = element.getURL( ) + " (" + title + ")";
if (!element.getCachedSize( ).equals("0")) {
result = result + " - " + element.getCachedSize( );
}
}
}
catch (GoogleSearchFault e) {
// Something went wrong. Say why.
result = "Unable to perform your search: " + e;
}
if (result == null) {
// No results were found for the search terms.
result = "I could not find anything on Google.";
}
// Send the result to the channel.
sendMessage(channel, sender + ": " + result);
}
}
}
Your license key will be a simple string, so you can store that in
the GoogleBot class as googleKey.
You now need to tell the bot which channels to join. If you want, you
can tell the bot to join more than one channel, but remember, you are
limited in the number of Google searches that you can do per day.
Create the file GoogleBotMain.java:
public class GoogleBotMain {
public static void main(String[] args) throws Exception {
GoogleBot bot = new GoogleBot("GoogleBot");. | http://archive.oreilly.com/pub/h/2728 | CC-MAIN-2016-22 | refinedweb | 474 | 66.33 |
I’m pretty new to Ruby on Rails.
I have multiple datapoints that I am saving in my database for a subject
called “quarterback”. All of those datapoints are added together to for
the value “xoi_qb”. This calculation is performed in my model:
def xoi_qb
sum=0
sum+= passing_yards|| 0
sum+= passing_yards|| 0
sum+= qb_rushing|| 0
Each value will change over time, and so the total of the sum, “xoi_qb”,
will change over time. Currently, the total for “xoi_qb” just updates
and the previous total is lost.
What I’d like to do is save each iteration of that total, every time
it’s changed. I don’t want to do a “cron job”, because I don’t want to
create a time-based schedule that performs a rake to see if any changes
were made…I just want that total for each “quarterback” value “xoi_qb”
to be saved to the database each time that I make a change.
That way, each “quarterback” will end up with many “xoi_qb” values that
go up and down in value. Right now, I just want to solve this and then
eventually I’d like to plot the datapoints in a chart (with Highcharts
or something similar). But for now, I just need to know how to save each
“xoi_qb” total with each change.
I have no idea how to do this. | https://www.ruby-forum.com/t/saving-repeated-iterations-to-database/242009 | CC-MAIN-2021-49 | refinedweb | 228 | 76.66 |
Python
Well, what do we see if we run it more than once?
default_append = [] def append(value, l): l.append(value) return l >>> append(1, default_append) [1] >>> append(2, default_append) [1, 2] ...
The solution to this is to use an immutable placeholder value - usually None - as the default argument, and initialize the list inside our function:
def append(value, l=None): if not l: l = [] l.append(value) return l
Recursive imports
When you import a module for the first time, Python creates a new global scope, and executes the code of the module inside it, then assigns that global scope to the name you just imported the module as. If the module you're importing itself has other modules, Python performs the same process for them, and so forth. On subsequent imports of a module, Python simply looks up the module in its internal list of loaded modules, and returns the existing scope.
Where this becomes a problem is if you have a module, a, which imports another module, b, which in turn attempts to import a - in other words, recursive imports. When something imports a, it's executed, causing the import of b. b executes, but when it reaches the 'import a' statement, Python throws an exception - it can't execute a again without creating an infinite loop, and it can't return the a it's currently importing, because it's not finished yet.
This doesn't come up that often, because dependencies usually don't form cycles. But if you're developing a fairly tightly coupled system, you may well encounter this at some point. Sometimes, it's a sign you need to refactor your placement of code in modules to eliminate the loops, but that's not always possible. For example, in part 3 of the Blogging on App Engine series we encountered exactly this problem, with the generators module importing the models module, and vice-versa.
The workaround is simple, but surprising to people used to compiled languages. Suppose we have the following in a.py:
import b def a_func(): return 5 def uses_b(): return b.b_func() + 2 print uses_b()
And the following in b.py:
import a def b_func(): return 10 def uses_a(): return a.a_func() + 2
The solution is to modify one module - whichever is convenient - to move the 'import' statement inside the functions that need to reference the other module. For example, supposing we decide to modify b.py:
def b_func(): return 10 def uses_a(): import a return a.a_func() + 2
This works because at the time b.py is executed, the code in the 'uses_a' function is parsed, but not executed. By the time uses_a() is executed, both modules should have finished importing, so Python can resolve the 'import a' statement inside the function by simply fetching the already-imported module.
Edit: In my original version of this post, I had an example that looked like a recursive import, but wasn't. Python is smarter than me, and only throws an exception if you try to call a function in a recursively imported module where the function hasn't been parsed yet. I updated the example above to demonstrate this.
Iterating over query objects
Now to something App Engine specific. A common mistake - so common it's even shown up in the docs once or twice by accident - is to do something like the following:
entities = Entity.all().filter('foo =', bar) for entity in entities: entity.number += 1 db.put(entities)
The overall pattern here is a good one: Updating a set of entities, then using a batch put to store them back to the datastore in a single operation. It's much more efficient than saving them all individually. The code above, however, does absolutely nothing: No records will be updated. To see why, we need to take a closer look at what happens.
The object returned by the expression "Entity.all().filter('foo =', bar)" is a Query object. Query objects expose several methods to refine the query, but they also act as iterables, meaning you can fetch an iterator from them to iterate over the results of the query. The db.put() function also accepts an iterable, and fetches all its elements, storing the results to the datastore.
What happens here, then is that our 'for' loop gets an iterator object from q and executes its body for each entity returned. Then, db.put also fetches an iterator from q - a new iterator, which executes the query a second time, returning the original, unmodified entities, which db.put happily stores back to the datastore. Not only does this code do nothing, but it does it inefficiently!
The solution is a very small change to our code:
entities = Entity.all().filter('foo =', bar).fetch(1000) for entity in entities: entity.number += 1 db.put(entities)
All we've done here is to switch from using the Query object's iterator protocol to fetching results explicitly. The .fetch() method returns a list of Entity objects. The for loop iterates over them, updating them, and then db.put() takes the same list, containing the entities we already modified, and stores them in the datastore. Since we're operating on the same list of entities in each step, everything works as expected.
Reserved module names
This is an issue that's come up a lot more since we added incoming email support to App Engine. Certain module names are used by the Python standard library, and attempting to use them yourself will lead to problems. A prominent example is 'email'. If you name your own module 'email.py', one of two things will happen, depending on the order of directories in the search path: Either every use of the 'email' standard library module will instead load your module, or vice-versa. Since people writing incoming email support on App Engine typically need to use the real 'email' module, neither option is a good one. Take care not to reuse module names from the Python standard library - and if in doubt, check the module list for confirmation. One easy way to avoid this gotcha is to put all your own code inside a package - then, you only need to check one name for conflicts.
Global variables and aliasing
Python only has two scopes - global, and local. Global scope is the scope of the module your code is in, while local scope is the scope of the current function or method. Python separates the two fairly strictly: Code in a local scope can read global variables, but can't, by default, modify them. Attempts to modify a global variable will lead to aliasing - creation of a local variable by the same name. For example:
>>> a_global = 123 >>> >>> def test(): ... a_global = 456 ... >>> print a_global 123 >>> test() >>> print a_global 123
Python provides a way to explicitly state that you want to modify a global inside a local scope: The global keyword. It works like this:
>>> a_global = 123 >>> >>> def test(): ... global a_global ... a_global = 456 ... >>> print a_global 123 >>> test() >>> print a_global 456
Note, however, that this is generally discouraged: Modifying global variables from within a function is seen as bad practice, and unpythonic. Also, remember that this restriction only prevents modifying the variables themselves, not their contents. For example, modifying a mutable list in the global scope is no problem without a 'global' keyword:
>>> a_list = [] >>> def append_list(x): ... a_list.append(x) ... >>> print a_list [] >>> append_list(123) >>> print a_list [123]
First import of handler modules
To wrap up, we'll cover one final App Engine specific gotcha. The execution model of App Engine Python apps is that the first request to a given request handler module is handled by simply importing the module, cgi-style. Subsequent requests are handled by checking if the module defined a 'main' function. If it did, the main function is executed, instead of re-importing the entire module.
If you want to take advantage of this performance optimisation for requests after the first one, you need to do two things: Define a main() function, and make sure that you call that main function yourself on first import. The second part of this is handled with this bit of boilerplate, which you are probably used to seeing at the bottom of modules:
if __name__ == "__main__": main()
If you omit this bit of code, however, the first import of your module simply parses anything, then does nothing, returning a blank page to your user. Subsequent requests execute main and generate the page as normal, leading to a frustrating debugging experience. So always remember the two line stanza from above!
Got your own tips, tricks, or gotchas? Leave them in the comments!Previous Post Next Post | http://blog.notdot.net/2009/11/Python-Gotchas | CC-MAIN-2013-20 | refinedweb | 1,447 | 62.68 |
Ticket #5197 (closed Bugs: fixed)
Forward declarations from std:: not allowed in libc++
Description
interprocess uses the forward declarations from std::
template <class T> class allocator;
template <class T> struct less;
template <class T1, class T2> struct pair;
template <class CharType?> struct char_traits;
libc++ does not support these. There are various possible fixes. These forward declarations could just be replaced by the headers:
#include <utility> #include <memory> #include <functional> #include <iosfwd>
or we could introduce a macro ( BOOST_ALLOWS_FWD_STD_DECLARATIONS ), or create a detail header for forward declarations.
I am happy to implement any of these, I am interested what the developers of interprocess think.
Attachments
Change History
Changed 5 years ago by chrisj
- attachment interprocess.patch
added
comment:1 Changed 5 years ago by chrisj
The problem of forwarding headers seems to be causing lots of discussion and not a lot of conclusion.
This simple attached patch disables the forwarding for libc++, the only standard library at present that seems to have trouble with them. I would appreciate it if it could be committed.
comment:2 Changed 5 years ago by chrisj
ping.
Would it be possible to get just a libc++ fix submitted for the next version of boost? I would like to have a more complete fix, but I'm unsure of how to do that in a way that isn't going to require huge amounts of code (as interprocess picks classes out of various headers) and will be agreed on by everyone.
comment:3 Changed 5 years ago by igaztanaga
Patch applied to trunk. After a few cycles, it will be merged to release branch
Simple patch to get libc++ working | https://svn.boost.org/trac/boost/ticket/5197 | CC-MAIN-2016-36 | refinedweb | 274 | 60.55 |
Transphporm – a Different Kind of Template EngineBy Zack Wallace
If there is one thing the world needs, it’s definitely another PHP template engine! But wait, this one is different!
Many PHP template engines (Smarty, Blade, Twig…) are little more than abstracted PHP code, making it easier to write loops, if/then/else blocks, and display variables with less verbosity than vanilla PHP. These traditional template engines require the designer to have an understanding of special syntax. The template engine must also be in place and operational in order to parse data and thus completely render the final design. Nothing wrong with this.
Transphporm follows a different approach that is generally known as “template animation”. What this means is that the web designer creates the entire HTML/CSS/JS page including placeholder content such as “Lorem Ipsum”, then the template engine comes along and replaces parts of the DOM with new data before the final render.
The benefit of template animation is that the designer does not have to know the backend code, template language, or any particular special syntax. They can use whatever tools they want to create 100% functional HTML pages.
The server-side software does not even need to function while the designer works. This means the designer doesn’t have to wait for the backend to deliver data for them to work with.
Basically, the designer can work with this:
<h1>A Good Title Here</h1> <p>A subtitle</p> <p>Some awesome text for clients to see.</p>
Instead of this:
<h1>{$futuretitle|upper}</h1> <p>{$futuresubtitle|capitalize:true|default:'Default Text'}</p> <p>{$futureawesometext}</p>
The placeholder content in the first example will be replaced by Transphporm. In the second example, the template engine must be functional and parsing the templates in order to see the final design as the designer envisions it.
Notice how the separation of concerns reaches nearly 100%. There is no special syntax or code that the designer needs to know. On the server-side, Transphporm does not need to have any HTML tags hard-coded. You don’t have logic and code on the front end, and you don’t have presentation and nodes being hard-coded in the backend.
Note: The backend may still produce reasonable HTML tags such as what is created through a WYSIWYG editor. i.e img, a, p, strong, em, etc., but never block level when done right.
Let’s see how this works. If you’d like to follow along, please prepare a new environment.
Installing Transphporm
In the
public folder of our project, we’ll install the package via Composer.
composer require level-2/transphporm:dev-master
Then, we create a new
index.php file with the content:
<?php require 'vendor/autoload.php';
Note: Frequently run
composer update as Transphporm is an active project. It updated a few times during the writing of this article.
Create Your Pages
Transphporm requires no front-end syntax or special code at the design level. We will use a CSS-like selection language to find and replace content before rendering output to the browser.
By the nature of template animation I can theoretically grab any ready-to-go template off the web so long as it is XHTML valid. This means
<meta charset='utf-8' /> and not
<meta charset='utf-8'> as is with current HTML5. Modern practice is to not use self-closing tags, but to be XML-valid, we must. Note that your final render can be HTML5, but the templates you create for Transphporm must be XHTML. This is just the nature of using PHP’s XML methods.
A Transphporm object requires two values. One is valid XHTML markup which represents the designer’s template. It could be an entire page, or just snippets of XHTML to be used in the greater theme. The other is TSS (Transphporm Style Sheet) directives which contain the replacement logic.
Reference the github page for full documentation as I can be only so verbose within the length of this article.
Add this to the
index.php file:
$page = 'home.xml'; $tss = 'home.tss'; $template = new \Transphporm\Builder($page, $tss); echo $template->output()->body;
Now create the
home.xml file with this basic XHTML template:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>HTML5 TEMPLATE</title> <style> body { padding: 20px; font-size:1em; } header nav { background-color:#ACEAD0; padding:15px 10px; } header nav ul { padding:0; } header nav li { display:inline; list-style:none; margin-right:15px; } header nav a { text-decoration:none; } article header h1 { margin-bottom:4px; color:#34769E; font-size:2em; } article header h2 { margin:0; font-size: .8em; color:#555; } article p { font-family:Arial, sans; color:#444; line-height:1.4em; } footer { background-color: #444; padding:10px; } footer p { color:#E2E2E2; } </style> </head> <body> <header> <nav> <ul> <li><a href="#">Home</a></li> <li><a href="#">The Goods</a></li> <li><a href="#">Favorites</a></li> <li><a href="#">Media</a></li> <li><a href="#">Contact</a></li> </ul> </nav> </header> <main> <article> <header> <h1>Page Title</h1> <h2>By Jehoshaphat on Jan 1, 2015</h2> </header> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut voluptas deserunt in quam itaque consequatur at recusandae, veritatis placeat porro cum magni eos iure vero, obcaecati est molestiae quos enim.</p> <p data-Lorem ipsum dolor sit amet, consectetur adipisicing elit. Commodi sed asperiores cum explicabo praesentium, mollitia possimus nam. Aperiam autem doloribus hic. Ex quae quia fugiat, fugit eaque quam adipisci nemo.</p> <ul> <li>A list item 1</li> </ul> </article> </main> <footer> <p>footer stuff</p> </footer> </body> </html>
Now create a
home.tss file with this:
article h1 {content: "My New Page Title"}
The TSS directive is “selecting” the h1 using CSS-like syntax. “Find an h1 that is a child of an article tag”. Note that specificity matters. If you had many article tags or many h1 tags, they would all be selected and changed!
This is especially true for repeating nodes like the
<li>. If there were more than one in our template, each individual list item would be replaced by the entire repeating dataset!
If your
index.php,
home.xml, and
home.tss files have been created correctly, you should be able to open the website and see the template. The template has
<h1>Page Title</h1> but you should actually see “My New Page Title” when rendered in the browser.
Transphporm supports common CSS syntax including:
.classname
tagname.classname
direct > descendant
#id
element[attribute="value"]OR simply
element[attribute]
Methods not supported include
~ and
+.
Beyond these selectors, Transphporm supports pseudo elements including:
element:before
element:after
element:nth-child(n)
element:even
element:odd
You can chain selectors together just like in CSS.
article header > p {content: "First paragraph after the article header section"}
This is the easy stuff and is hopefully straightforward.
At this point, you’re surely thinking “but I don’t want to hard code text in the TSS directive!”
Well, that’s where the fun begins.
Handling Data
Let’s pretend this project is a bit more complicated. You are not likely to have the new
<h1> content hard-coded in a TSS file! And you’ll likely have more than one piece of content to update.
I’m going to create an object called
$data and assign some values to it.
Update
index.php to this:
require 'vendor/autoload.php'; // Some fancy routing to setup the page. $page = 'home.xml'; $tss = 'home.tss'; // Some fancy controller/model action to get data. $data = new stdClass; $data->pagetitle = "Awesome Page"; $data->title = "Article Title"; $data->subtitle = "By Zack"; $template = new \Transphporm\Builder($page, $tss); echo $template->output($data)->body;
Now we have
$data as an object. We also added
$data to the
output() method.
The home.tss file can now be updated to this:
title {content: data(pagetitle)} article h1 {content: data(title)} article h1 > h2 {content: data(subtitle)}
The attribute we use called
content accepts a value called
data(). This is similar to how in CSS you might supply
rgba() as a value for
color.
At this point we can replace any content by utilizing the CSS syntax. Notice how we even replaced content within the
<head> section.
DOM Concerns
At this point, you may be thinking that the designer and programmer don’t have to talk to each other; but on some level they do. The designer must use proper XHTML or the engine will crash (error handling may be improved over time).
You might be wondering what happens if the designer changes the DOM and thus breaks a TSS selection. This can happen, especially if you rely more on the DOM tree than on well-thought-out IDs and classes. I would rather use
id="posttitle" than rely on
main article header > h1 which may not always be set in stone.
Multiple Partials
We can also utilize more than one XML file to assemble the final template.
Here is an example TSS file:
@import 'another.tss'; aside {content: template("sidebar.xml")}
We can use
@import to include other TSS files. We can also use
template() to assign partial xml to the selected node as seen above. Any TSS directives that come after this line can affect the included xml file.
This way, you can carefully craft the importing of xml partials and TSS directives to assemble the final page. Just like CSS, everything compiles top-down.
Not only this, but you can replace content with partial content of the included template. In the above example, I’m including the entire
sidebar.xml file. But what if I only want the
<aside> within that file? Just do this:
aside {content: template("sidebar.xml", "#extra aside")}
This will only pull the
<aside> out from under the element with ID “extra”. The benefit of this is that the designer can still work with complete templates if they want to, even though you may only extract certain elements. It also means that, just as you can combine images together into a single file and use CSS to display them as needed, you can combine template elements in a single file and just extract the parts you need.
Advanced Directives
One concern you might have is that if the designer breaks up the design into many partials, doesn’t that defeat the purpose of template animation because now you need Transphporm to put it back together? Kind of.
This is because the “master” template still contains the designer’s complete mockup. Nothing changes there. The “real” final markup will be within the partials. This makes the designer’s job only slightly more complex as they will have to edit the main design visually, then copy and change things within the partials for production. If they update the primary page, they may have to update partials too.
If you refer back to our basic HTML template, partials could easily be used for the header, the menu, the primary content area, the footer, etc. But placing these in partials doesn’t affect the designer being able to leave the primary base template fully intact and visually complete. The partials will simply replace the placeholder markup later.
And as we just saw, the partials themselves can be part of a larger complex or complete page.
Repeating Data
Transphporm can handle repeat data through the use of a
repeat() attribute.
Our template has an unordered list. We can fill it by using
$data to pass an array of objects. Let’s add an array of fruit objects to
index.php.
$fruits = []; // Master array of all fruits $fruit = new stdClass; $fruit->name = 'Apple'; $fruits[] = $fruit; $fruit = new stdClass; $fruit->name = 'Pear'; $fruits[] = $fruit; $data->fruits = $fruits;
Now in the TSS file:
article ul li {repeat: data(fruits); content: iteration(name)}
If you’ve added the data to
index.php and updated the TSS file, the unordered list should now have two
<li> nodes listing “Apple” and “Pear”.
Before:
<ul> <li>A list item 1</li> </ul>
After:
<ul> <li>Apple</li> <li>Pear</li> </ul>
Notice how we used two attributes “repeat” and “content” separated by a semicolon. Just like setting height, width, color and border in CSS on a single node, you can apply multiple transforms using a single selection with Transphporm.
We passed
data(fruits) to the
repeat function. This will repeat the selected node (the
<li>) including its closing tag. Then, we use
iteration() to tell it what data within each fruit object to display.
Note: beside
data() and
iteration(), there are other transforms available including
format which accepts the values “uppercase”, “lowercase”, “titlecase”, “date”, and can deal with numbers as well.
Attributes
Transphporm can do some fun stuff with attributes.
Let’s say we wanted to hide the
<li> if it equals “Apple”. To do this, we can inspect the current iteration and select based on that.
article ul li:iteration[name='Apple'] {display: none;}
Notice how it works like a psuedo element by using a colon after the
<li> and in square brackets matching a
name=value pair. Notice also that Transphporm can just as easily hide elements with the familiar CSS directive
display:none (though with Transphporm, the elements are fully removed from the DOM, not just hidden).
In our template, the second paragraph has
data-p="yes". Let’s hide it based on that value.
article p[data-p="yes"] {display:none}
Notice how there is no colon after
p here like before when using
iteration, which is a Transphporm function. We are selecting with normal CSS attribute syntax which doesn’t use a colon.
You can also set the content of the attributes themselves. The example from the docs uses a “mailto” link like so:
a:attr(href) {content: "mailto:", iteration(email)}
Again,
attr is a Transphporm function so the colon is used. Also notice “(href)” is a direct selection of the attribute itself, no value is used.
Something cool happens here – content is set to “mailto:” but then we use a comma and the iteration’s value. Transphporm will concatenate multiple values when using a comma, e.g.:
p {content: "This ", "is ", "really ", "long"}
So with the previous “mailto” example, a proper attribute
href="mailto:someemail@example.com" will be assembled.
Headers
Transphporm does not send headers. You will have to use normal PHP functions for that.
The
output() method returns an object with two attributes. One is
body which contains the rendered HTML, the other is
headers which is an array of headers.
The way to set a header is to select the
<html> element and use the built-in pseudo element
:header to set it.
html:header[location] {content: "/another-url"}
To make use of headers set this way, you’ll have to read the array returned by Transphporm, take those values and set them with PHP’s
header() function. Instructions for how to do this are in the docs.
Conditional Changes
It is possible to change elements based on logic in other parts of the application. Let’s say your program has a function like this one:
class Security { public function LoggedIn() { // Some logic return false; } } $data = new Security; // Be sure to pass $data to the output() method as usual
Now you can read this value and determine the appropriate action:
#welcome:data[LoggedIn=""] {display:none}
This could be quite handy!
It should be noted that, with template animation, we usually start with a complete template with all features, then strip away parts that don’t belong. We would build the template with “logged in” features, then remove them from the DOM if not needed.
This is described as a “top down” approach, as opposed to “bottom up” where only minimal markup is present, and we add stuff as needed.
Both approaches work with Transphporm.
Benefits of Decoupled Display and Logic
An advantage of separating display logic from markup is that they become decoupled entirely. This means that any given XML doesn’t have to belong to any given TSS. In fact, some XML could be used with different TSS and some TSS could be used with any other XML.
One example of this is using TSS to repopulate forms. A single TSS could be used to repopulate any given form template. It would look like this:
form textarea {content: data(attr(name))} form input[type="text"]:attr(value) {content: data(attr(name))}
The function
attr(name) reads the “name” attribute of the selected element. If the “name” attribute of the textarea element were “comments”, then it compiles to:
form textarea {content: data(comments)}
data(comments) here is referencing the passed-in
$data object we’ve already used before, but it would work just as well if
$_POST itself were passed instead.
The second line in the above TSS is selecting all form input elements with a type of “text”. It is then specifically selecting the
value attribute itself which is where you would put content when populating a form. The data is, again, coming from
data(xyz) where “xyz” is the
name attribute of the selected element. In turn, the
name attribute will match the data coming in from
$_POST or a
$data object.
The end result is that anywhere you need to repopulate a form, you could simply include one TSS file like so:
import 'form-populate.tss';
As an example of passing
$_POST you might do this in your PHP:
$data->title = "Article Title"; $data->formData = $_POST;
Once
$_POST has been passed in through
$data, a binding feature can specifically link
formData to all the TSS used under that form element.
form {bind: data(formData)} /* Now that formData is bound to form, it can be accessed directly */ form input:attr(value) {content: data(attr(name))}
Binding just means I can call
data(key) rather than
data(formData[key]) because the context of
data() was changed to reference
formData directly.
Language Independence
It should be noted that decoupling means any language can be used to process the TSS files without any change to the templates. The author has built a sister compiler in Javascript that is 100% compatible as far as TSS and XML templates go. Find it on Github at Transjsform.
Challenges
Using template animation takes care of both the designer and the coder. The designer can create their templates and partials without any real concern for the backend or template engine. Only valid XHTML is needed. The programmer, on the other hand, only needs the ability to easily find the DOM elements which need their content replaced.
The programmer and designer will, however, need a planned-out file structure for where to place major and minor templates, partials and so forth.
The person who is not quite taken care of yet is the editor/writer.
It’s fine to have XHTML templates. It’s fine to have TSS logic somewhere. The data can come from a controller and be assembled into a single
$data object. But where do the writers write?
Obviously, some form of editorial interface is going to be required to connect a writer to a particular piece of content/TSS to update it. There is nothing contained in the template itself to inform the backend which nodes require content editing and which do not.
Some form of meta-data will be required to say “this paragraph needs custom data, but this one does not”. The programmer also needs to know which sections will be replaced by a partial. There may even be multiple versions of a partial depending on some other application logic.
Because of this, we can’t really claim that there is a 100% separation between designers and coders, as they still need some level of congruity regarding the overall structure of things.
Make the Editor Learn TSS?
One of the reasons for template animation is to prevent a designer from having to learn a template language or syntax. This is a pointless goal if you are just making a writer learn TSS syntax instead! It would likely be much easier for a designer to learn a template syntax than to teach a writer CSS syntax.
If the designer is also the content editor, then they have to learn TSS anyway, so why not just learn an existing mature template language? If the editor doesn’t know CSS syntax, nothing will be intuitive for them.
Parts of TSS are for assembling the page, other parts for assigning copy. Editors further only need access to some of these transforms. Some transforms may be structural in nature while others content oriented.
A true separation of concerns here must include the editors as well as the programmer and designer. No existing CMS is going to be able to adopt Transphporm as-is. A complicated template could potentially contain hundreds of transformations with lots of various logic paths. The content editors need a WYSIWYG.
All together, this presents an interesting challenge for making Transphporm usable for everyone.
It should be noted that the author is currently working on a parser where an editor could submit Markdown as the content and Transphporm would parse it into HTML for the output. This feature should be added very soon and takes us a step closer to an editing interface.
Caching
Basic caching is being implemented as written about here. Without a cache, PHP currently has to traverse the XHTML and parse TSS for every page load. In its current iteration, this could create a performance issue when using Transphporm.
More from this author
Conclusion
Using CSS-like syntax to select DOM elements is a very fun concept. Designers may find relief from having to learn a new syntax, and they can mock up 100% complete designs with no worry about the backend. This also means one should be able to download any XHTML, ready-made templates and get started relatively quickly with minimal DOM changes.
It’ll be interesting to see how this project matures. The first CMS interface to be created to manage TSS transforms and content editing will be particularly interesting.
If you don’t like the way regular template engines work, maybe Transphporm is more up your alley? Take a look and let us know!
- sarfraznawaz2005
- gggeek
- Zack Wallace
- gggeek
- gggeek
- Tom Butler
- gggeek
- Zack Wallace
- Badumpsss
- Tom Butler
- Tom Butler
- Taylor Ren
- Zack Wallace
- Taylor Ren
- Chris
- Tom Butler
- Chris
- Zack Wallace
- Zack Wallace
- Chris
- Mitch Amiano
- Mitch Amiano
- Anru Chen
- Tom Butler
- Tùng Red
- Tom Butler
- Zack Wallace
- frostymarvelous | https://www.sitepoint.com/transphporm-a-different-kind-of-template-engine/ | CC-MAIN-2017-17 | refinedweb | 3,750 | 63.7 |
rior to Window Mobile 5.0 (WM5) even simple things such as checking battery status, sending an SMS, or programming Pocket Outlook were rather difficult. Fortunately, WM5 came with new managed APIs that expose a phenomenal number of abilities that will greatly enhance mobile applications.
Windows Mobile 5.0 offers many new APIs. Although they are spread across a number of different services, they are all focused on the common goal of improving developer productivity. In this article, I’ll focus on the State and Notification API (SNAPI). Using SNAPI, I’ll build a CallHandler application that automatically sends an SMS to a caller when the call recipient is busy and sets a Task reminder for the call recipient to return the call later.
The inspiration for this application is a new feature of some Nokia phones that ignores a call and sends a customized SMS to the caller (for example, to say that you’ll call back later). The WM5 managed APIs make this kind of application development really simple. In the bargain you will get a useful application for yourself and at the same time learn features of the State and Notification API.
Don’t Worry, Get SNAPI
Here’s the official description of SNAPI from Microsoft.
The State and Notification Broker API provides a unified mechanism for storing device, application, and system-state information. Beyond simply being a unified store, it provides centralized notification architecture, allowing applications to easily register for notification, optionally starting an application in the event that a value of interest should change. The model allows applications to easily share their own state information as well. Windows Mobile 5.0 devices ship with well over 100 different state values available through the State and Notification Broker.
So what does this mean for you? Let’s say you have a Windows Mobile application that is used for data collection. User-entered data must be backed up in this system when the battery level reaches, say, 15 percent. In order to do this you would need a way to check the current battery status?or better still to be notified when the battery level reaches 15 percent. Without WM5 this would be very difficult.
Or suppose you needed to respond to an incoming SMS message on a WM5 device, how would you do it? Prior to WM5 this was not possible using Managed code; the only option was to use P/Invoke. SNAPI makes all of this easy using managed code.
Before you can use SNAPI in your code you need to add references to two assemblies to your code: Microsoft.WindowsMobile and Microsoft.WindowsMobile.Status. This will enable you to access SNAPI and a lot of other useful WM5 APIs. The SystemState class gives you the ability to get the current value of a system state as well as a notification when that state changes. SNAPI provides access to 100+ pieces of state information. You need to figure out which particular state you need to monitor. The object browser (Figure 1) is the perfect way to parse through the wealth of state information provided via SNAPI. It makes sense to browse this list to get an overview of the various system properties that are exposed via SNAPI.
For example, if you wanted to know the current battery state you would capture the value by typing:
SystemState.GetValue(SystemProperty.PowerBatteryStrength)
This would get the remaining battery power level, expressed as a percentage of fully charged. Here I’m using the GetValue function of the SystemState class. It retrieves the value of a System Property using the property as a parameter.
Getting Notified of Changes
An incoming call is, basically, a change in state. Therefore you can employ the SystemState class to notify you when a call is coming in. To monitor a particular SystemState you need to define in your code an instance of the SystemState class and write event handling code for changes. To define an instance in your code you need to add the following line of code just after the default constructor of your form.
Friend WithEvents IncomingCall As New _SystemState(SystemProperty.PhoneIncomingCall)
Here I’m declaring IncomingCall as a new instance of the SystemState class and specifying the property of interest to me, which in this case is PhoneIncomingCall. To handle changes to this SystemProperty (PhoneIncomingCall) you need to write an event handler.
Private Sub CheckCallStatus(ByVal Sender As Object, ByVal Args As ChangeEventArgs) _Handles IncomingCall.Changed MessageBox.Show("Call coming thru :-) ")End Sub
Try it Out!
Open Visual Studio, choose a project type of Smart Device ?>Windows Mobile 5.0 Pocket PC or SmartPhone and choose Device Application as the project template. On the default form that is created, press F7 to start writing code. Add references to the two assemblies, Microsoft.WindowsMobile and the Microsoft.WindowsMobile.Status, to your project and then add the imports statement to the start of your code file.
Imports Microsoft.WindowsMobileImports Microsoft.WindowsMobile.Status
Next, enter the code for the IncomingCall declaration followed by the CheckCallStaus method defined above. Once you’ve completed that, run the application by hitting F5 and choose an actual WM5 device as the target. Your application should load up. Now is the time to make a call to your device to test the application. As soon as an incoming call is detected the code for the call CheckCallStatus will execute, displaying the message “Call coming thru :-)”.
Next, use SystemState in the event handler you just wrote (CheckCallStatus) to retrieve the incoming caller phone number.
PhoneNumber = SystemState.GetValue(SystemProperty.PhoneIncomingCallerNumber)
Add the above line of code as the first line of the method (CheckCallStatus) and edit the text displayed in the MessageBox as shown below:
MessageBox.Show("Incoming Call No: " & PhoneNumber)
You are now able to detect and respond to an incoming call and store the caller phone number. At this stage it’s best to handle situations where errors could creep up. Replace the code in the CheckCallStatus with the following:
If Not _ String.IsNullOrEmpty(SystemState.GetValue(SystemProperty.PhoneIncomingCallerNumber)) Then PhoneNumber = SystemState.GetValue(SystemProperty.PhoneIncomingCallerNumber) Me.BringToFront() ' MessageBox.Show("Incoming Call No: " & PhoneNumber)End If
This new code does two things. First it ensures that only valid phone numbers are stored by checking to see if the value of the incoming phone number is Null or empty. Second, it ensures that the form is brought to the front, in case the user has minimized the application. For now you can see that I’ve commented out the display of the message box, as you are about to learn how to send that same message via SMS instead.
Sending an SMS
In order to send an SMS message you need to use the SmsMessage class. This class is present in the assembly Microsoft.WindowsMobile.PocketOutlook.
Add a reference to this assembly and in your form import the namespace:
Imports Microsoft.WindowsMobile.PocketOutlook
Create a Sub called SendSMSMessage which accepts as string parameter ‘msg’:
Private Sub SendSMSMessage(ByVal msg As String) Dim _smsMessage As New SmsMessage _smsMessage.Body = msg _smsMessage.To.Add(New Recipient(PhoneNumber)) _smsMessage.Send() End Sub
To send an SMS message you need to specify two things: the message text or body and the message recipient(s). In the SendSMSMessage sub, I’ve created an instance of the SmsMessage class called “_smsMessage.” Next I’ve specified a value ‘msg’ as the message body and specified that this message should be sent to a particular phone number by passing the variable ‘PhoneNumber’ to the property “To” of this class by invoking it’s Add method. The application supports multiple recipients and, thus, this ‘To’ property gets the collection of intended message recipients. Next I’ve created a New Recipient Object by passing it the PhoneNumber as a string parameter. Finally, send the SMS message by invoking the Send method of the SmsMessage class. That’s all there is to sending an SMS message from your program.
To add a task to Outlook tasks, you have to create an instance of the OutlookSession class and add the task. The next thing that happens in the above code is the creation of three variables to store the start time, due time, and the reminder time for the task.?including:
- Gets notification of an incoming call and capture information about the call (phone number)
- Sends an SMS
- Creates a task/reminder.
You now need to orchestrate all the above and allow the user to create the message and execute this functionality when he or she chooses.
Add the following controls to the main form of your application.
- TextBox
- Button
Set the TextBox’s text property to “Will call later”.
Set the Button’s text property to Submit.
Double-click the button to add code to its click event and call the two methods defined earlier (SendSMSMessage and SetTaskReminder) one after the other.
SendSMSMessage(TextBox1.Text)SetTaskReminder
That’s it! Run the application by hitting F5 and selecting your WM5 device as the target. The application loads with the default form. To test it, call your phone from another mobile phone. This will invoke the CheckCallStatus method. The variable PhoneNumber will be assigned the value of the incoming caller phone number. If you click the submit button, the message “Will call later” (or whatever you happened to put in the text box) will be sent to the caller. In addition a task/reminder will be created on the receiving phone.
Enhancements to Consider
Some things you might want to do to enhance the code further:
- Provide the user the ability to have a list of common messages such as “In a meeting,” “On another call” etc.
- Add error-handling code to check that the phone number is actually a number. (For example, you want to handle blocked phones such as “Private Caller” or something similar. In addition, you need to trap for land line (POTS) numbers as these will not be able to receive a text message and different countries display numbers in different ways.)
- Enhancing the SMS functionality by giving the user an option for delivery notification.
By now you’ve gotten a good introduction to SNAPI and you’ve seen how it can help you build a more responsive application. There are numerous others such as the Microsoft.WindowsMobile.PocketOutlook.MessageInterception Namespace, which provides classes for SMS message interception or classes to work with the Media Player etc. It is a rich environment that enables one to build a number of interesting applications that were either too difficult or impossible before. | https://www.devx.com/wireless-zone/32305/ | CC-MAIN-2022-27 | refinedweb | 1,760 | 55.64 |
I'm new to Entity Framework, just a question on how EF generate insertion SQL for entity class that has default 0.
This is the data model class:
public class Product { public long ProductID { get; set; } public string Name { get; set; } }
and the underlying table Products in Sql server has identity column on ProductID .
So let's say a controller that use model binding to create a Product object p1, and then we do:
context.Products.Add(p1) //p1.ProductID = 0 for default context.SaveChanges();
My questions are:
Does EF need to send a query to database to get latest primary key in
Products table and then plus 1 to be
p1.ProductID? Isn't that very inefficient as you need to query database for latest existing primary key and then send another insert SQL to insert record?
what does the
Dbset<Product>.add() method really mean? I mean if the object's id is 0, we know it doesn't exist in the database (if id > 0 then we know we are modifying existing record), can't we just add newly created p1 to the database, why we still need to track it?
1.) no, you dont need to get latest object's primary key to determine next Id.
2.)
Primary Key starts from 1 not 0,in EF if you use default identity provider as explained below, EF can manage Primary Key auto, so no need to set
ANY number to that variable. Then,
context.Products.Add(p1) adds value to Local Table (in RAM), after addition
context.SaveChanges(); will trigger to send Local Values to SQL Database.
After SaveChanges you will see correct Id of value
there is a feature to generate auto Id for tables.
[Key]attribute.
string has no auto Id Generator)
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]to auto generator.
ProductIDEF can manage it.
public class Product { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public long ProductID { get; set; } public string Name { get; set; } }
not: if you want string Primary Key (or manually add Id) you should use
[DatabaseGenerated(DatabaseGeneratedOption.None)]
more examples about EF (select EF version from navigator) | https://entityframeworkcore.com/knowledge-base/57156336/how-ef-generate-insertion-sql-for-entity-class-that-has-default-0- | CC-MAIN-2020-40 | refinedweb | 350 | 55.13 |
XForms:Custom Controls
From MDC
[edit] Purpose
You are in the right place if you would like to create your own custom renderings of the XForms controls like
input,
output,
trigger, etc. We will also show you how to create custom controls that work with the XForms model and are automatically updated just like XForms controls. The purpose of this article is to give you enough background information so that you'll be able to get a good start. To really grasp the following information, a good understanding of XForms, XBL, JavaScript and CSS is needed. XPCOM knowledge will certainly not hurt. But even if you are only comfortable with a couple of these technologies, we hope that the possibilities outlined below will inspire you to learn more where you need to.
[edit] Implementation Status
The framework we use in the Mozilla XForms processor is very much a "work in progress". Please keep in mind that just about everything we mention here may change to some degree as we continue to work on it. Work has just started in the W3C XForms Working Group to investigate the custom control issue, so eventually (hopefully?) there will be an "official" and common way to customize your form's user interface across all XForms processors.
[edit] Why Do You Need This
You will probably find that your need for customization will fall into one of the following categories:
- custom presentation - XForms controls as rendered by the Mozilla XForms processor do not provide the right look and feel for you.
- custom data types - existing XForms controls are not able to work properly with your data type
- advanced XForms controls - you need your controls to be able to do more things than traditional XForms controls can do
- new host language - you'd like to support XForms in host languages other than XHTML or XUL
[edit] Custom Presentation
The Mozilla XForms extension cannot anticipate all of the possible use cases that will evolve in web applications and web pages as XForms matures and the user base grows. And with these new uses, more and more flexibility will be desired from the controls. Introducing custom controls into your environment may be just the solution you are looking for. For example, you might want to render images that are held inside an instance document or you would like to show a disabled
trigger when its bound node becomes irrelevant rather than having it not display (the current default behavior).
Every XForms control's presentation has its own XBL binding. In many cases different values provided for the
appearance or
mediatype attributes will determine which XBL binding will be used for a particular XForms control on the form. As mentioned in the spec, the
appearance attribute can be used to influence the look and feel of a control even when all other conditions remain constant. For example, in the Mozilla XForms extension we will render a combobox widget when
appearance='minimal' on a
select1 control. Should the form author instead choose to use
appearance='compact' on this control, we would render a listbox widget. Here is a snippet from our .css file to show the type of CSS rule we would use to make such a determination.
xf|select1[appearance="compact"] { -moz-binding: url('chrome://xforms/content/select-xhtml.xml#xformswidget-select1-compact'); }
The
mediatype attribute can be used by the form author to align the type of presentation with the type of data that the bound instance node contains. For example, if
mediatype='image/*' then the user should see the image that the bytes represent rather than just the byte sequence.
xf|output[mediatype^="image"] { -moz-binding: url('chrome://xforms/content/xforms-xhtml.xml#xformswidget-output-mediatype-anyURI'); }
[edit] Custom Data Types
If you define a new schema data type or you use a built-in data type and find the current XForms control for this type to be insufficient, then you should write a new custom control. For example, if you have an instance node of type
xsd:date and you'd like to see the date displayed in a local format.
In Mozilla, every bound XForms control has a
typelist attribute of
mozType namespace that contains the inheritance chain of data types that we detected. The
mozType namespace is introduced by Mozilla XForms implementation and its URI is. For example, if a control is bound to a node of type
xsd:integer then the
typelist attribute will be
"". This is because
xsd:integer is inherited from the
xsd:decimal data type. We recommend that you use this attribute to create the CSS binding rule for your custom control. This will allow you to bind your custom control for the data type that you are targeting AND any type derived from that target type. So if you want an
input bound to an instance node of type
integer (and all types derived from
integer), you would use:
@namespace xf url(); @namespace mozType url(); xf|input[mozType|typelist~=""] { -moz-binding: url('chrome://xforms/content/input-xhtml.xml#xformswidget-input-integer'); }
[edit] Advanced XForms Controls
There may be times where you need a control that is very specific to your task, but you also want it to work with XForms models and instance nodes just like a regular XForms control. The XForms specification provides for a nice way to do this using XForms binding attributes (like
ref, or
nodeset) on your custom control element. However, the Mozilla XForms implementation currently doesn't support this approach. But there is a way for you to achieve the same result. You can put the XForms controls inside your XBL binding. Note you should take care to make sure that the embedded XForms controls are able to work with the data type of the instance node that your control is bound to. To give you an idea of what we are talking about, it could look something like this:
<content> <xf:input xbl: <xf:input xbl: </content> <implementation> <method name="refresh"> <body> // Here we should refresh custom control. </body> </method> <constructor> // We should redirect calls of input's 'refresh' method to custom control 'refresh' method. var control = this; var refreshStub = function() { control.refresh(); } this.ref1.refresh = refreshStub; this.ref2.refresh = refreshStub; </constructor> <property name="ref1" readonly="true" onget="return this.ownerDocument.getAnonymousElementByAttribute(this, 'anonid', 'ref1');"/> <property name="ref2" readonly="true" onget="return this.ownerDocument.getAnonymousElementByAttribute(this, 'anonid', 'ref2');"/> </implementation>
[edit] New Host Language
The Mozilla XForms implementation currently only supports XForms hosted in XHTML or XUL documents. If you need to have XForms in other kinds of documents like SVG, MathML or some other tag language that Mozilla supports, then you'll need to implement XForms controls for your desired document format. The XForms implementation has base XBL bindings for every XForms control. You can write implementation bindings that will inherit from these base bindings. For example, every
output control implementation extends the base binding
xforms.xml#xformswidget-output-base. The XHTML-specific pieces of our implementation of
output is kept in the
xforms-xhtml.xml#xformswidget-output binding. If you would like to do this kind of heroic work then please contact the Mozilla XForms developers before you start. Hopefully we can help you avoid a lot of frustration and despair :).
[edit] Overview
The Mozilla XForms controls are largely implemented using XBL and the bindings are applied to the individual xforms control tags via CSS. So you can always refer to our source code to get some great examples of how XForms controls can be written. This will also allow you to be up to date with our current approaches (often the result of hard-learned lessons) and that will hopefully help you to more easily write your own controls. To get started, you really only need to know the language where you'd like to use XForms (like XHTML or XUL), some XBL and JavaScript, and the XPCOM interfaces we are exposing for your use.
[edit] Details
[edit] Interfaces
This section describes interfaces you need to know. There are two main groups of interfaces -> callback interfaces that must be implemented by the custom controls and the interfaces that custom controls can use to access the Mozilla XForms engine.
[edit] nsIXFormsUIWidget
Every custom control should implement the
nsIXFormsUIWidget interface. This interface is used by the XForms engine to interact with the underlying control. For example, when the control needs to be updated according to the rules of XForms, the
refresh method will be called by the processor. Below is the structure of the interface. As always, please refer directly to the source code to be sure that you are using the latest, up-to-date version:
extensions/xforms/nsIXFormsUIWidget.idl.
interface nsIXFormsUIWidget : nsIDOMElement { /** * Is called when control should be updated to reflect the value of the bound node. */ void refresh(); /** * Is called when focus is advanced to the XForms element. */ boolean focus(); /** * Is called when control should be disabled. * This really only applies to the submit element. */ void disable(in boolean disable); /** * Is called to get current value of control. */ string getCurrentValue(); }
Notes:
- getCurrentValue() should return the current value of the control as seen by a user. The current value of a control could differ from the value of the bound node in cases where @incremental='false'.
- disable() is called by the XForms processor to indicate to a submit element that it needs to disable/enable due to the beginning/ending of the submission process. Currently it has no meaning outside of this context.
- focus() is used by the processor to tell the control that it is getting focus through one of a variety of ways (i.e. through xf:setfocus action) and that the control needs to ensure that the proper widget is given focus.
With rare exception, your control should only need to implement the
nsIXFormsUIWidget interface. But certain XForms controls need to implement additional interfaces. Such elements include
upload and
case.
[edit] nsIXFormsAccessors
The
nsIXFormsAccessors interface allows access to the value and the state of the instance node that the control is bound to (see
extensions/xforms/nsIXFormsAccessors.idl). Currently interface is:
interface nsIXFormsAccessors : nsISupports { /** * Return value of instance node. */ DOMString getValue(); /** * Set value of instance node. */ void setValue(in DOMString value); /** * Return true if the instance node is readonly as determined by the MDG. */ boolean isReadonly(); /** * Return true if the instance node is relevant as determined by the MDG. */ boolean isRelevant(); /** * Return true if the instance node is required as determined by the MDG. */ boolean isRequired(); /** * Return true if instance node is valid as determined by the MDG. */ boolean isValid(); /** * Return true if the control is bound to an instance node. */ boolean hasBoundNode(); /** * Return the bound instance node. */ nsIDOMNode getBoundNode(); /** * Set the content of the instance node. If aForceUpdate is true then the * XForms model will rebuild/recalculate/revalidate/refresh. */ void setContent(in nsIDOMNode aNode, in boolean aForceUpdate); }
note: setContent() can be used to set place complexContent (mixture of text and element nodes) under the control's bound node. Please see the comments in the source .idl file for more information on using this method.
[edit] XBL Bindings
Most XForms control elements have at least two bindings applied to themselves. One is the base binding that implements the core behavior of the XForms control. The other is the implementation binding that adds the host-language specific representation of the XForms control. An example of the latter is the binding that uses a html:input as the anonymous content of an xforms:input element when this element is hosted in a XHTML document.
Our XForms extension uses the following format for file names. The name of the file where base bindings for a control are placed is
controlfile.xml.
controlfile-xhtml.xml contains the XHTML implementation bindings for the control and
controlfile-xul.xml contains the implementation bindings for when this control is hosted in a XUL document. The following list shows where the base bindings for our XForms controls are defined:
xforms.xml- contains the base bindings for
output,
label,
trigger,
submit,
case,
hint,
alert,
uploadand
repeatXForms controls.
input.xml- contains the base bindings for
input,
secretand
textareaXForms controls.
select.xml- contains the base bindings for
selectand
select1XForms controls (except
minimal/default select1that is hosted in
select1.xmlfile)
range.xml- contains the base bindings for the
rangeXForms control.
xforms.xml also defines the few base bindings that are common for all XForms controls. These are:
xformswidget-general- defines utility properties and methods common for all XForms controls
xformswidget-accessors- defines the methods that are allow the bindings to work with bound instance nodes and the XForms element itself.
xformswidget-base- implements
nsIXFormsUIWidgetsinterfaces.
You are free to choose what type of binding you will extend to provide the foundation for your custom control. This will very likely be one of the implementation bindings or one of the base bindings.
[edit] Example
A collection of custom control examples can be found on XForms:Custom Controls Examples, and you can also see the blog post "Understanding XForms: Customization".
Here is a complete example that defines a new output control that loads its value as an image. It is bound to
<xf:output mimicking the current XForms 1.1 draft:
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" ""> <html xmlns="" xmlns: <head> <title>Custom Image Control Sample</title> <bindings id="xformsBindings" xmlns="" xmlns: <binding id="output-image" extends="chrome://xforms/content/xforms.xml#xformswidget-base"> <content> <html:div> <html:img </html:div> </content> <implementation implements="nsIXFormsUIWidget"> <method name="refresh"> <body> <!-- set the src attribute on the html:img to be the simpleContent of the instance node bound to this control --> var img = document.getAnonymousElementByAttribute(this, "anonid", "content"); img.setAttribute("src", this.stringValue); return true; </body> </method> </implementation> </binding> </bindings> <xf:model> <xf:instance <data> <curimg></curimg> <img label="Firefox"></img> <img label="Thunderbird"></img> <img label="Bugzilla"></img> <img label="Mozilla"></img> </data> </xf:instance> </xf:model> <style type="text/css"> @namespace xf url(); xf|output[ <xf:label>Select image to display: </xf:label> <xf:itemset <xf:label <xf:value </xf:itemset> </xf:select1> <xf:output </body> </html> | http://developer.mozilla.org/en/docs/XForms:Custom_Controls | crawl-001 | refinedweb | 2,354 | 53.31 |
Mocking HTTP requests with Nock
This is a ‘how to’ article on using Nock to mock HTTP requests during tests.
We will look at:
- Why mock HTTP requests during testing?
- What is Nock?
- Code examples of both
nockand
nock.back
When dealing with code that depends on external services maintaining test coverage and writing reliable tests can be challenging. Tests that make real HTTP requests to external services can be error-prone for a variety of reasons. Examples include the exact data returned changing on each request, network connectivity problems, or even rate limiting.
Unless the test is explicitly designed to test an external service’s availability, response time, or data shape, then it should not fail because of an external dependency.
Intercepting and controlling the behaviour of external HTTP requests returns reliability to our tests. This is where Nock comes in.
Nock is an HTTP server mocking and expectations library for Node.js.
Nock can be used to test modules that perform HTTP requests in isolation.
Nock works by overriding Node’s
http.requestfunction. Also, it overrides
http.ClientRequesttoo to cover for modules that use it directly.
Nock allows us to avoid the mentioned challenges by intercepting external HTTP requests and enabling us to either return custom responses to test different scenarios, or store real responses as ‘fixtures’, canned data that will return reliable responses.
Using canned data does come with risks, as it can go stale if not refreshed periodically. Without specific additional tests, or pinned API versioning, this could mean that a change in the shape of the data an API returned would not be caught. It is the developer’s responsibility to make sure practices are in place to avoid this.
An example from my current employer is seen in our end-to-end tests. These use Nock fixtures, as when run during our continuous delivery pipeline they would occasionally suffer from timeout failures. However, each time a developer runs these tests locally the fixtures are automatically deleted and regenerated, keeping them up to date.
Nock is currently used in two main ways:
- Mocking individual responses specified by the developer, uses
nock
- Recording, saving, and reusing live responses, uses
nock.back
Either can be within individual tests. If both are used within the same test file then currently the
nock.back mode must be explicitly set, and reset, before and after use. We will look at this in detail later.
Let’s set up a project, add Nock, then look at
nock and
nock.back with some code examples.
We will be building this example project. It contains some simplistic functions that call a random user generator API, perfect for testing out Nock. It uses Jest as its test runner and for assertions.
Three functions exist in the example to be tested: getting a random user, getting a random user of a set nationality, and getting a random user but falling back to default values if unsuccessful. One example:
const getRandomUserOfNationality = n =>
fetch({n})
.then(throwNon200)
.then(res => res.json())
.catch(e => console.log(e));
As we are using
nock.back then a
nock.js helper file is used, we will look at this later.
The Nock docs explain this pretty well. Many options are available to specify the alteration of the request, whether in the request matched or the response returned. Two examples of this would be the response returned from a successful request, and forcing a 500 response to test a function’s fallback options.
All that would need to be added to an existing test file to start using nock is
const nock = require('nock'); /
import nock from ‘nock';.
In the first test we use a string to match the hostname and path, and then specify a reply code and body. We then add our assertion to the Promise chain of our function call. When the outgoing request from
getRandomUser() is made it matches the Nock interceptor we just set up, and so the reply we specified is returned.
it('should return a user', () => {
nock('')
.get('/api/')
.reply(200, {
results: [{ name: 'Dominic' }],
});
return query
.getRandomUser()
.then(res => res.results[0].name)
.then(res => expect(res).toEqual('Dominic'));
});
Similarly, we mock a call with a specific nationality, though this time we use a RegExp to match the hostname and path.
it('should return a user of set nationality', () => {
nock(/random/)
.get(/nat=gb/)
.reply(200, {
results: [{ nat: 'GB' }],
});
return query
.getRandomUserOfNationality('gb')
.then(res => res.results[0].nat)
.then(res => expect(res).toEqual('GB'));
});
It’s important to note we are using
afterAll(nock.restore) and
afterEach(nock.cleanAll) to make sure interceptors do not interfere with each other.
Finally we test a 500 response. For this we created an additional function that returns a default value if the API call does not return a response. We use Nock to intercept the request and mock a 500 response, then test what the function returns.
it('should return a default user on 500', () => {
nock(/randomuser/)
.get(/api/)
.reply(500);
return query
.getRandomUserGuarded()
.then(res => expect(res).toMatchObject(defaultUser));
});
Being able to mock non-200 response codes, delaying the connection, and socket timeouts, is incredibly useful.
nock.back is used not just to intercept an HTTP request, but also to save the real response for future use. This saved response is termed a ‘fixture’.
In
record mode if the named fixture is present it will be used instead of live calls, and if it is not then a fixture will be generated to be used for future calls.
In our example project only one HTTP call is being made per test, but
nock.back fixtures are capable of recording all outgoing calls. This is particularly useful when testing a complex component that makes calls to several services, or during end-to-end testing where again a variety of calls can be made. A main advantage of using fixtures is that once created they are fast to access, reducing chances of timeouts. As they use real data then mocking the structure of the data is not necessary, and any change can be identified.
As mentioned earlier, it is important to delete and refresh fixtures regularly to ensure they do not go stale.
A current ‘feature’ of
nock.back is that when used in the same test file as standard
nock interceptors they can interfere with each other, unless any
nock.back tests are bookended per test as so:
nock.back.setMode('record');
// your test
nock.back.setMode('wild');
This ensures that any following tests do not unintentionally use the fixtures just generated. If not done then, for example, the 500 response would not be given in our previous test, as the fixture contains a 200 response.
We must first set up a
nock.js helper file. In the example this is doing three things:
- Setting the path of where to save our fixtures to
- Setting the mode to
recordso that we both record and use fixtures when tests are run, rather than the default
dryrunthat only uses existing fixtures but does not record new ones
- Using the
afterRecordoption to perform some actions on our fixtures to make them more human readable
This is then accessible in test files using
const defaultOptions = require('./helpers/nock); /
import defaultOptions from './helpers/nock';.
nock.back can be used with both Promises or Async/Await, examples are given of each. Here we will look at the latter.
it('should return a user', async () => {
nock.back.setMode('record');
const { nockDone } = await nock.back(
'user-data.json',
defaultOptions,
);
const userInfo = await query.getRandomUser();
expect(userInfo).toEqual(
expect.objectContaining({
results: expect.any(Object),
}),
);
nockDone();
nock.back.setMode('wild');
});
We first mark the test as
async, to allow us to use
await. We set the mode to
record. We pass in the name of the file we would like to save our fixtures as, and the defaultOptions set in our
nock.js helper to make them more human readable. On finish this provides us with the
nockDone function, to be called after our expectations are done.
After calling
getRandomUser() we can now compare its result in our expectation. For simplicity of demonstration we just assert that it will contain
results, that itself contains an Object.
After this we set the mode to
wild, as in this case we want to ensure the fixture is not used by other tests.
The fixtures themselves can be seen in the directory specified in the
nock.js helper, and are themselves interesting to look at.
Nock provides a very powerful tool for adding reliability to tests that call external services, and allowing greater test coverage as tests that may previously have been seen as too flaky to implement can be reassessed.
As with any mocks, it is the developer’s responsibility to make sure that mocking does not go too far, and is still possible for the test to fail on a change in functionality, or it is of no value!
Thanks for reading, I hope you found this useful 😁
You may also enjoy:
If you liked this, or anyone else’s post you’ve read today, did you know you can press and hold 👏 to clap up to 50 times? | http://brianyang.com/mocking-http-requests-with-nock/ | CC-MAIN-2018-51 | refinedweb | 1,531 | 56.55 |
j hey i m doing a project
can i create message reader using j2me in nokia phone??
pls give me source code or hint
calculator midlet
calculator midlet give me code calculator midlet in bluetooth application with i wann source code to find out the difference between two dates... (ParseException e) {
e.printStackTrace();
}
}
}
i wann j2me code not java code my dear sirs/friends
J2ME
| Different Size of Font
MIDlet J2ME |
Audio MIDlet J2ME |
Access...
Platform Micro Edition |
MIDlet Lifecycle J2ME
|
jad and properties file in J2ME
| J2ME Hello World Program
| Creating MIDlet Apps for Login in J2ME - MobileApplications
of an image in midlet
when i put this code in midlet it is showing errors.
can...j2me Hi Deepak,
Thank for u earlier suggestion.But i need its date and time when the file was created.But i got solution
Creating Midlet Application For Login in J2ME
Creating MIDlet Application For Login in J2ME
This example show to create the MIDlet application for user login . All
MIDlet applications for the MIDP ( Mobile Information application
j2me application code for mobile tracking system using j2me
Audio MIDlet Example
Audio MIDlet Example
This example illustrates how to play audio songs in your mobile application
by creating a MIDlet. In the application we have created
j2me
j2me how to compile and run j2me program at command prompt
j2me
j2me i need more points about j2me
J2me - MobileApplications
J2me Hi, I would like to know how to send orders linux to a servlet which renvoit answers to a midlet. thank you
J2ME Item State Listener Example
the
ItemStateListener interface in the j2me midlet. The ItemStateListener interface...
J2ME Item State Listener Example
...;class ItemStateListenerMIDlet extends MIDlet{
Tutorial
;
Creating MIDlet Application For Login in J2ME
This example show... variable DATE which is 0.
J2ME Button MIDlet
This example...;
J2ME CheckBox ChoiceGroup MIDlet
This example illustrates how to create - MobileApplications
j2me Hi,
I have developed a midlet application in j2me now i want...,
For more information on J2me visit to :
Thanks Icon MIDlet Example
J2ME Icon MIDlet Example
... element and an array of image element.
In the Icon MIDlet class we are creating...;javax.microedition.midlet.*;
public class SlideImage extends MIDlet{
how to run audio files in net beans using j2me
how to run audio files in net beans using j2me i am running the audioMidlet in net beans. Now where should i place the .wav files inorder to play them
J2ME Crlf Example
J2ME Crlf Example
The given J2ME Midlet, discuss about how to show the messages...;
Source Code of LineBreakExample.java
import Canvas Repaint
J2ME Canvas Repaint
In J2ME repaint is the method of the canvas class, and is used to repaint the
entire canvas class. To define the repaint method in you midlet follow Books
and trends of the J2ME platform, the book uses the source code of several award... of the new Cracking the Code Series, Wireless Programming with J2ME provides a look at the code behind wireless Java applications.
Think of J2ME as a tiny
Radio Button in J2ME
Radio Button in J2ME
In this tutorial you will see the MIDlet Example that is going to
demonstrate, how to create the radio button in J2ME using MIDlet. The radio button
j2me
j2me What is JAD file what is necesary of that
Hi Friend,
Please visit the following link:
JAD File
Thanks
Hi Friend,
Please visit the following link:
JAD File
Thanks Display Size Example
J2ME Display Size Example
In the given J2ME Midlet example, we are going to display the size of the
screen. Like a below given image 1, the midlet will print few items database question
j2me database question **Is there any possibility to install a database into the mobile.
If possible how can i connect it through midlet(j2me)**
pls help me
J2ME Timer MIDlet Example
J2ME Timer MIDlet Example
...;\n");
}
}
in the above source code we...;}
}
}
Download Source Code
Text Example in J2ME
Text Example in J2ME
In J2ME programming language canvas class is used to paint and draw...
in our show text MIDlet Example. We have created a class called CanvasBoxText
error in compiling j2me apllication - Applet
error in compiling j2me apllication hi,
in my j2me application for video,m getting only the audio.i ll send the code.
package src.video... MIDlet implements CommandListener,ItemCommandListener,Runnable,PlayerListener
J2ME - Date Calendar
J2ME sir
i need code of calculator
performing addition, multiplication, division, subtraction
in J2ME
J2ME Read File
of this file by the help of j2me midlet.
For Details you can download the source code and use it on j2me environment...
J2ME Read File
image application
j2me image application i can not get the image in my MIDlet .........please tell me the detailed process for creating immutable image without Canvas project - Java Beginners
j2me project HOW TO CREATE MIDLET WHICH IS A GPRS BASED SOLUTION... SALES DATA FROM THE SERVER.
THIS MIDLET IS FOR THE PROJECT MEDICAL CENTRAL...://
Thanks
Draw Line in J2me
Draw Line in J2me
In this example we are going to show you how to draw a line using J2ME.
Please go through the below given J2ME syntax that includes all the package,
methods
J2ME Record Store MIDlet Example
J2ME Record Store MIDlet Example
... it on the console. In this
example we are using the following code to open, close...;
And the Application is as follows:
Source
J2ME Current Date And Time
J2ME Current Date And Time
This is a simple J2ME form example, that is going to show the current date
and time on the screen. Like core Java J2ME too use the same
J2ME Record Store Example
J2ME Record Store Example
In this Midlet, we are going to read string data and write.... In J2ME a record store consists of a collection of records
and that records remain
j2me -
Rectangle Canvas MIDlet Example
Rectangle Canvas MIDlet Example
... of rectangle in J2ME.
We have created CanvasRectangle class in this example... is as follows:
Source Code of RectangleCanvas.java
Advertisements
If you enjoyed this post then why not add us on Google+? Add us to your Circles | http://roseindia.net/tutorialhelp/comment/86920 | CC-MAIN-2016-18 | refinedweb | 1,012 | 61.26 |
.
There is another type in Python called a tuple that is similar
to a list except that it is immutable. Syntactically, a tuple is a
comma-separated list of values:
>>> tuple = 'a', 'b', 'c', 'd', 'e'
Although it is not necessary, it is conventional to enclose tuples in
parentheses:
>>> tuple = ('a', 'b', 'c', 'd', 'e')
To create a tuple with a single element, we have to include the final
comma:
>>> t1 = ('a',)
>>> type(t1)
<type 'tuple'>
Without the comma, Python treats ('a') as a string in
parentheses:
>>> t2 = ('a')
>>> type(t2)
<type 'str'>
Syntax issues aside, the operations on tuples are the same as the
operations on lists. The index operator selects an element from
a tuple.
>>> tuple = ('a', 'b', 'c', 'd', 'e')
>>> tuple[0]
'a'
And the slice operator selects a range of elements.
>>> tuple[1:3]
('b', 'c')
But if we try to modify one of the elements of the tuple, we get
an error:
>>> tuple[0] = 'A'
TypeError: object doesn't support item assignment
Of course, even if we can't modify the elements of a tuple, we can
replace it with a different tuple:
>>> tuple = ('A',) + tuple[1:]
>>> tuple
(: unpack tuple of wrong size,.
As an exercise, draw a state diagram for this function so that
you can see why it doesn't work.
Most computer programs do the same thing every time they execute,. Python provides a built-in function that
generates pseudorandom numbers, which are not truly random in
the mathematical sense, but for our purposes they will do.
The random module contains a function called random that
returns a floating-point number between 0.0 and 1.0. Each time you
call random, you get the next number in a long series. To see a
sample, run this loop:
import random
for i in range(10):
x = random.random()
print x
To generate a random number between 0.0 and an upper bound like
high, multiply x by high.
As an exercise, generate a random number between low and
high.
As an additional exercise, generate a random integer
between low and high, including both end points.
The first step is to generate a list of random values. randomList takes an integer argument and returns a list of random
numbers with the given length. It starts with a list of n
zeros. Each time through the loop, it replaces one of the elements
with a random number.
The return value is a reference to the complete list:
def randomList(n):
s = [0] * n
for i in range(n):
s[i] = random.random()
return s
We'll test this function with a list of eight elements. For
purposes of debugging, it is a good idea to start small.
>>> randomList(8)
0.15156642489
0.498048560109
0.810894847068
0.360371157682
0.275119183077
0.328578797631
0.759199803101
0.800367163582
The numbers generated by random are supposed to be distributed
uniformly, which means that every value is equally likely.
If we divide the range of possible
values into equal-sized "buckets," and count the number of times a
random value falls in each bucket, we should get roughly the
same number in each.
We can test this theory by writing a program to
divide the range into
buckets and count the number of values in each.
A good approach to problems like this is to divide the problem into
subproblems and look for subproblems that fit a computational pattern
you have seen before.
In this case, we want to traverse a list of numbers and count the
number of times a value falls in a given range. That sounds familiar.
In Section 7.8, we wrote a program that traversed a string and
counted the number of times a given letter appeared.
So, we can proceed by copying the old program and adapting it
for the current problem. The original program was:
count = 0
for char in fruit:
if char == 'a':
count = count + 1
print count
The first step is to replace fruit with t and
char with num. That doesn't change the program;
it just makes it more readable.
The second step is to change the test. We aren't interested
in finding letters. We want to see if num is between
the given values low and high.
count = 0
for num in t:
if low < num < high:
count = count + 1
print count
The last step is to encapsulate this code in a function called
inBucket. The parameters are the list and the values
low and high.
def inBucket(t, low, high):
count = 0
for num in t:
if low < num < high:
count = count + 1
return count
By copying and modifying an existing program, we were able
to write this function quickly and save a lot of debugging
time. This development plan is called pattern matching.
If you find yourself working on a problem you have solved
before, reuse the solution.
As the number of buckets increases, inBucket gets
a little unwieldy. With two buckets, it's not bad:
low = inBucket(a, 0.0, 0.5)
high = inBucket(a, 0.5, 1)
But with four buckets it is getting cumbersome.
bucket1 = inBucket(a, 0.0, 0.25)
bucket2 = inBucket(a, 0.25, 0.5)
bucket3 = inBucket(a, 0.5, 0.75)
bucket4 = inBucket(a, 0.75, 1.0)
There are two problems. One is that we have to make up new
variable names for each result. The other is that we have to
compute the range for each bucket.
We'll solve the second problem first. If the number of buckets
is numBuckets, then the width of each bucket is
1.0 / numBuckets.
We'll use a loop to compute the range of each bucket.
The loop variable, i,
counts from 0 to numBuckets-1:
bucketWidth = 1.0 / numBuckets
for i in range(numBuckets):
low = i * bucketWidth
high = low + bucketWidth
print low, "to", high
To compute the low end of each bucket, we multiply the loop variable
by the bucket width. The high end is just a bucketWidth away.
With numBuckets = 8, the output is:
0.0 to 0.125
0.125 to 0.25
0.25 to 0.375
0.375 to 0.5
0.5 to 0.625
0.625 to 0.75
0.75 to 0.875
0.875 to 1.0
You can confirm that each bucket is the same width, that they don't
overlap, and that they cover the entire range from 0.0 to 1.0.
Now back to the first problem.
We need a way to store eight integers, using the loop variable
to indicate one at a time. By now you should be thinking,
"List!"
We have to create the bucket list outside the loop, because we only
want to do it once. Inside the loop, we'll call inBucket
repeatedly and update the i-eth element of the list:
numBuckets = 8
buckets = [0] * numBuckets
bucketWidth = 1.0 / numBuckets
for i in range(numBuckets):
low = i * bucketWidth
high = low + bucketWidth
buckets[i] = inBucket(t, low, high)
print buckets
With a list of 1000 values, this code produces this bucket list:
[138, 124, 128, 118, 130, 117, 114, 131]
These numbers are fairly close to 125, which is what we expected. At
least, they are close enough that we can believe the random number
generator is working.
As an exercise,
test this function with some longer lists, and see if the
number of values in each bucket tends to level off.
Although this program works, it is not as efficient as it could be.
Every time it calls inBucket, it traverses the entire list. As
the number of buckets increases, that gets to be a lot of traversals.
It would be better to make a single pass through the list and compute
for each value the index of the bucket in which it falls. Then we can
increment the appropriate counter.
In the previous section we took an index, i, and multiplied it
by the bucketWidth bucketWidth instead of
multiplying. That guess is correct.
Since bucketWidth = 1.0 / numBuckets, dividing by bucketWidth is the same as multiplying by numBuckets. If we
multiply a number in the range 0.0 to 1.0 by numBuckets, we get
a number in the range from 0.0 to numBuckets. If we round that
number to the next lower integer, we get exactly what we are looking
for a bucket index:
numBuckets = 8
buckets = [0] * numBuckets
for i in t:
index = int(i * numBuckets)
buckets[index] = buckets[index] + 1
We used the int function to convert a floating-point
number to an integer.
Is it possible for this calculation to produce an index that is out of
range (either negative or greater than len(buckets)-1)?
A list like buckets that contains counts of the number of values
in each range is called a histogram.
As an exercise, write a function called histogram that
takes a list and a number of buckets as arguments and returns
a histogram with the given number of buckets.
Warning: the HTML version of this document is generated from
Latex and may contain translation errors. In
particular, some mathematical expressions are not translated correctly. | http://greenteapress.com/thinkpython/thinkCSpy/html/chap09.html | CC-MAIN-2017-47 | refinedweb | 1,526 | 73.47 |
<script type="text/javascript">
var number = "10";
(function(){
alert(number);
alert(eval('number=22'));
})();
var func = function() {
alert (new Function( 'return (' + number + ')' )());
}
func(); // prints 22.
</script>
It first alerts
10, then alerts
22 then why is it alerting
22 again instead of 10. Does eval function overrides my variable in global scope.
No,
eval isn't executed in the global scope but you don't have a variable named
number in your local scope. So you're changing the global one.
You may see it with this little change :
(function(){ var number; // this will ensure the global number isn't changed alert(number); // this will print "undefined" alert(eval('number=22')); // this won't change the global variable })();
Note that
alert(eval('number=22')); returns the result of the evaluation and
number=22 returns
22. That's why the second alert gives
22.
Since you don't have a variable in your local scope, its changing the global one. Try this one below. It would print 100 instead of 22.
<script type="text/javascript"> var number = 100; (function(){ var number; alert(number); alert(eval('number=22')); })(); function func() { alert (new Function( 'return (' + number + ')' )()); } func(); </script>
don't use it.
If you remove the use of eval what is happening is maybe more obvious - you are redefining the value of the global variable
number inside the first anonymous function:
var number = "10"; (function(){ number = 22; // this is a reference to the global variable `number` })(); var func = function() { alert (new Function( 'return (' + number + ')' )()); // this is another use of eval - don't do this } func(); // prints 22 - expected. | http://m.dlxedu.com/m/askdetail/3/0cd58f50f577f52fa4cffcf47d6114c5.html | CC-MAIN-2018-22 | refinedweb | 265 | 59.94 |
# Pad the encoded string with "+". data += "=" * (4 - (len(data) % 4) % 4) return base64.urlsafe_b64decode(data)
Django has the equivalent function in its django.core.signing library:
def b64_decode(s): pad = '=' * (-len(s) % 4) return base64.urlsafe_b64decode(s + pad)The code from Django's function uses negative modulo to compute the vaule. How do negative modulos work? See this excerpt from:
The mod function is defined as the amount by which a number exceeds the largest integer multiple of the divisor that is not greater than that number. In this case, -340 lies between -360 and -300, so -360 is the greatest multiple LESS than -340; we subtract 60 * -6 = -360 from -340 and get 20: -420 -360 -300 -240 -180 -120 -60 0 60 120 180 240 300 360 --+----+----+----+----+----+----+----+----+----+----+----+----+----+-- | | | | -360| |-340 300| |340 |=| |==| 20 40 Working with a positive number like 340, the multiple we subtract is smaller in absolute value, giving us 40; but with negative numbers, we subtract a number with a LARGER absolute value, so that the mod function returns a positive value. This is not always what people expect, but it is consistent. If you want the remainder, ignoring the sign, you have to take the absolute value before using the mod function. | http://hustoknow.blogspot.com/2013/01/negative-modulos.html | CC-MAIN-2017-51 | refinedweb | 207 | 60.04 |
Hi.
I'm using mod_python 3.1.4, apache 2.0.x/prefork and python2.4.
The following code doesn't work:
from mod_python import apache
import threading
def something():
open('/tmp/thread', 'w').close()
def handler(req):
threading.Thread(target=something).start()
return apache.OK
Browser request successfully hits the handler(), and no errors occure, but
something() is not called (no file on filesystem after request).
If I insert logging statements after thread initialization and a call of
start() thread object looks like this:
<Thread(Thread-1, initial)>
<Thread(Thread-1, started)>
I'm not good with threading and this might be very ordinary situation, dont
really know. Please help.
--
melchakov at gmail.com
CRV-RIPN
-------------- next part --------------
An HTML attachment was scrubbed...
URL: | http://modpython.org/pipermail/mod_python/2005-June/018283.html | CC-MAIN-2018-39 | refinedweb | 125 | 69.68 |
The field width and precision setting may be used for characters and strings as well. However, these have different meaning. See the following code:
char kh [] ="character String";
printf("%-30.10s\n",kh);
The above code would print 10 characters of variable kh in width 30 with left justification. It will print the following:
character
Program illustrates the width and precision setting with numerical data as well as characters and strings:
Illustrates width and precision specification with character and string type data.
#include <stdio.h>
void main()
{
char kh = 'X';
char ch []= "You should master C language";
clrscr();
printf("|%20c|\n", kh); //field width 20, right justification.
printf("|%-20c|\n", kh); // field width 20, left justification.
printf("|%10c|\n", kh);//field width 10, right justification
printf("|%-40s %5c|\n", ch, kh);
printf("|%-40s %-5c|\n", ch, kh);
printf("|%40s|\n", ch);
printf ("|%-40.l7s |\n", ch);
printf("|%-40.10s|\n", ch); /*fieldwidth 40, precision 10, left justified*/
printf("|%-40.4s|\n", ch); //field width 40,precision 4, left justified
printf("|%-.10s|\n", ch); //no field width, precision 10 left
}
The output is given below.
Explanation of the output: Vertical bars are introduced so that the extent of width setting can be noticed. The first line of the output is the result of width setting 20 with right (default) justification. The second line of the output is result of the same width setting with left justification and the third line is the result of the width setting 10 with default justification. The fourth line of output is the result of width setting -40 for string ch and width setting 5 for kh with value X. So, after display of ch, X is displayed with right justification on the next 5 spaces. For the fifth line, the justification of kh is changed to left so it is displayed immediately after 40 spaces. Similarly, in sixth line of the output, the string ch is displayed in 40 spaces with right justification.
The next 4 lines of output are the result of different precision settings. The seventh line of the output is the result of"%-40.17s". It displays 17 characters in width of 40 spaces with left justification. Similarly, in the next line the setting "%-40.10s"displays only 10 characters in width 40 and left justification due to –ve sign. For the last but one line of the output the precision setting is .4 so only 4 characters, i.e., "You" are displayed. If the setting is only"%-. 10 s \n", the display consists of 10 characters, i.e., "You should" and it fills the entire space and there is no empty space because no width specification has been specified.
Program is another example of output of characters and strings values with formatting function.
Illustrates formatting with characters and strings.
#include<stdio.h>
#include<stdlib.h>
int main()
{
char ch = 'x';
char kh[] ="character string";
clrscr();
printf("%5c%5c\n",ch,ch);
printf("%-5c%-5c\n",ch,ch);
printf ("%s\n", kh);
printf("%20.4s\n",kh); /*print 4 characters of kh on right.*/
printf("%-20.4s\n",kh); /*print 4 characters of kh on left.*/
printf("%30.10s\n",kh);
/*The above code means print first10 characters of kh in width 30, with right justification.*/
printf("%-30.10s\n",kh);
/*The above code means print 10 characters of kh in width 30 with left justification.*/
return 0;
}
The expected output is given below
Explanation of the output: The first line of the output is the result of setting field width 5 and right justification. The second line of the output is due to same field width but with left justification. For this, -ve sign is put between % and conversion character c.
The third line is simply an output of the string with the default setting in the computer. For the fourth line of the output, the field width set is 20; however, due to the precision setting .4, it displays only 4 characters with right justification. The next line of the output is the same setting but with negative sign, i.e., left justification. The last but one and the last lines of output are with width setting of 30 and to print 10 characters with right and left justification, | https://ecomputernotes.com/what-is-c/types-and-variables/precision-for-characters-and-strings | CC-MAIN-2019-30 | refinedweb | 709 | 65.42 |
The definition of a business rule typically involves taking data and seeing if it meets certain criteria. In Code Effects, the rule is the criteria expressed as an XML document, and the source object is the data implemented either as a public .NET class, an XML document, or even as a collection of values of defined types.
For rule authoring, the page that hosts the Rule Editor must tell it which class or XML document it should use as a source object. The Rule Editor reflects that class or document; it uses all its declared public value typed properties as rule fields, and qualified public methods as rule actions or in-rule methods unless such properties and methods are decorated with ExcludeFromEvaluationAttribute. There are numerous ways you can create a source object:
Below is the list of elements that make up a source object:
Attributes. Although it is perfectly fine to use a "plain" .NET class as a source object, you would probably want to customize it when used in real life business rules in order to better suit the requirements of your project. Almost all elements of a source object can be customized with Code Effects attributes located in the CodeEffects.Rule.Attributes namespace. For example, consider a Car class:
using CodeEffects.Rule;
namespace Test
{
[Source(MaxTypeNestingLevel = 3)]
[ExternalMethod(typeof(Helper), "HadAccidents")]
[ExternalAction(typeof(Helper), "ChangeOil")]
public class Car
{
// more code to follow...
}
}
Three optional attributes were applied to this class:
Properties. Rule Editor uses all public non-static value type properties and fields of the source object as rule fields, unless those members are of type System.Guid, nullable enum or marked with ExcludeFromEvaluationAttribute. Read more about data types in Code Effects here.
Rule Editor performs a full search of all reference type members of the source object and uses all their value type members not marked with ExcludeFromEvaluationAttribute as rule fields. The optional SourceAttribute (used in the above code sample) contains the property MaxTypeNestingLevel. The search for value type members is performed up to the level set by this property, with a default value of 4. Setting MaxTypeNestingLevel to a higher number may slow the performance of Rule Editor while it renders itself on the page.
To see this in action, add a new property to your source object, give it a type of some large class, add Rule Editor to the page and run the page. Experiment with the value of SourceAttribute.MaxTypeNestingLevel to see the difference in load performance.
To simplify things for rule authors, Rule Editor converts fields and return types of in-rule methods into six simple types: numeric, string, date, time, boolean and enum. For example, if the property of the source object is of type System.Int16, Rule Editor will convert it into numeric when rendering its UI value on the page. During rule evaluation, though, this value will be boxed back into the most appropriate .NET type in order to perform an accurate evaluation. Properties of System.DateTime type will be converted into date fields, System.TimeSpan into time fields, enumerators into enum fields, and so on. This conversion happens automatically.
For strings and nullable properties or method return types, Rule Editor automatically adds isNull and isNotNull operators to the operator menus. The default English display names for those operators are has no value and has any value. Default display names of rule elements such as operators, clauses, and flows can be changed by the use of Help XML. Display names of rule fields can be changed by creating a source object using Source XML or by changing the value of the DisplayName property of the FieldAttribute.
You can use properties of enumerator types as fields. If you don't want certain enumerator items to be used in rules, decorate them with the ExcludeFromEvaluationAttribute class.
Let's add several properties to our Car class:
[Field(ValueInputType = ValueInputType.User,
DateTimeFormat = "MMM dd, yyyy", DisplayName = "Date of sale")]
public DateTime? Sold { get; set; }
[Field(Max = 17, DisplayName = "VIN number")]
public string VIN { get; set; }
[Field(Min = 0, Max = 1000000)]
public decimal Price { get; set; }
public Color Color { get; set; }
Even though the FieldAttribute topic contains detailed descriptions of each of its properties, several things are worth noting here:
In-Rule Methods. Each rule condition must have three elements: field, operator and value:
In the example above, the Brand is a rule field. Code Effects solution implements a feature called in-rule methods, which allow you to use return values of methods as condition fields or values. To qualify, the method must be public and must return a string or a value type (except for System.Guid and nullable enum). If it's not parameterless, the method must take only value types (except for Sytem.Guid) or the source object as parameters, otherwise, the method will be ignored by Rule Editor. Get details by reading the ParameterAttribute topic. In-rule methods can be used in both execution and evaluation type rules.
In this short rule, HadAccidents is a public method of the source object used as a rule field. It can be declared like this:
[Method("Had accidents")]
[return: Return(ValueInputType = ValueInputType.User)]
public bool HadAccidents( [Parameter(ValueInputType.Fields)] string vin)
{
List<Accident> list = VehicleService.GetAccidents(vin);
return list != null && list.Count > 0;
}
Several things to notice in this declaration:
One of the goals of Rule Editor is to simplify things for rule authors. For example, if an in-rule method has no parameters or if it takes the source object type as a parameter, the author won't even know that this is a method and not a field. Consider the simple rule:
To the rule author, the element Resale price appears to be a rule field when in fact it's a method that takes a source object as its only parameter:
[Method("Resale price")]
public decimal GetResalePrice(Car sourceObject)
{
decimal? price = VehicleService.GetPriceByVIN(sourceObject.VIN);
return price == null || price < 0 ? 0 : (decimal)price;
}
Actions. Actions are public methods that return System.Void. They can be declared in a source object or in any other public class. If it's not parameterless, the action must take only value types (except for Sytem.Guid) or the source object as parameters. Otherwise, the method will be ignored by Rule Editor. Get details by reading the ParameterAttribute topic. Actions can be used only in execution type rules.
Refer to the code that declares the Car class. The ExternalActionAttribute "added" the ChangeOil method to the source object as a rule action. That method is declared in the Helper class:
namespace Test
{
public class Helper
{
public Helper() { }
[Action("Change oil")]
public void ChangeOil(Car car)
{
Oil oil = VehicleService.GetOil();
car.Oil.Remove();
car.Oil.Add(oil);
}
}
} | https://codeeffects.com/Doc/Business-Rule-Source-Object | CC-MAIN-2021-31 | refinedweb | 1,120 | 55.64 |
Docs |
Forums |
Lists |
Bugs |
Planet |
Store |
GMN |
Get Gentoo!
Not eligible to see or edit group visibility for this bug.
View Bug Activity
|
Format For Printing
|
XML
|
Clone This Bug
Someone make this work. Gives me sandbox violations from scons.
Created an attachment (id=84686) [edit]
dangerdeep-0.1.1.ebuild
Not so working ebuild.
*** Bug 130191 has been marked as a duplicate of this bug. ***
Created an attachment (id=84851) [edit]
games-simulation/dangerdeep-0.1.1-r1.ebuild
This new ebuild works perfectly on amd64. Can someone test it on x86?
Created an attachment (id=84852) [edit]
files/dangerdeep-destdirs.patch
(From update of attachment 84851 [edit])
-r is for in-portage rev bumps
Should dynamically replace the directories with the variables from games.eclass
(GAMES_BINDIR, GAMES_DATADIR...)
Also, after reading, I suggest the
following src_compile() :
if use amd64
then
USEX86SSE=3
else
if use sse
then
USEX86SSE=1
else
USEX86SSE=-1
fi
fi
scons usex86sse=${USEX86SSE} || die "make failed"
and adding sse to the USE flags.
This will use asm sse optimizations on x86 when sse flag is set, and intrisics
ones by default for amd64 (since all amd64 have sse). According to the post,
the performance boost is quite nice ;)
I built it on amd64. I noticed that
- dangerdeep depends on media-libs/libsdl built with joystick
- I got some access violations caused by scons
I will post the actual ACCESS_VIOLATION when an update is there.
Other than that it builts and runs fine.
Created an attachment (id=85635) [edit]
dangerdeep-0.1.1.ebuild
Created an attachment (id=85636) [edit]
dangerdeep-0.1.1-build.patch
Respect flags and fix sandbox violations
I just tried the new ebuild but it failed with these errors:
* Applying dangerdeep-0.1.1-build.patch ...
[ ok ]
>>> Source unpacked.
>>> Compiling source in /var/tmp/portage/dangerdeep-0.1.1/work/dangerdeep-0.1.1 ...
scons: Reading SConscript files ...
Compiling for Unix/Posix/Linux Environment
KeyError: 'LDFLAGS':
File "SConstruct", line 180:
env.Append(LINKFLAGS = os.environ['LDFLAGS'])
File "/usr/lib64/python2.4/UserDict.py", line 17:
def __getitem__(self, key): return self.data[key]
!!! ERROR: games-simulation/dangerdeep-0.1.1 failed.
Call stack:
ebuild.sh, line 1525: Called dyn_compile
ebuild.sh, line 928: Called src_compile
dangerdeep-0.1.1.ebuild, line 43: Called die
!!! scons failed
I am running amd64 unstable.
Ok, I should have had a closer look.
I didn't have any LDFLAGS specified in my make.conf and that's why it failed.
So I added LDFLAGS in it and now it compiles.
Created an attachment (id=85730) [edit]
dangerdeep-0.1.1-build.patch
You shouldn't have to have it set. Try this one...
It seems to work now, with and without settings the LDFLAGS.
Thank you :)
Created an attachment (id=85740) [edit]
dangerdeep-0.1.1-build.patch
This is probably better. Sorry for spam.
segfaults for me.
Created an attachment (id=94911) [edit]
dangerdeep-0.1.1.ebuild
This doesn't really depend on boost.
Created an attachment (id=94912) [edit]
dangerdeep-0.1.1-build.patch
Use the right compiler.
*** Bug 110121 has been marked as a duplicate of this bug. ***
Created an attachment (id=99472) [edit]
New ebuild
Version 0.2.0 ebuild only tested on ~amd64.
My first try at ebuilds so be gentle ;)
addwrite /usr/include/GL:/usr/include/SDL:/usr/X11R6/lib is pretty evil. Feel
like tracking down why that's needed and fixing it?
Still cores for me right after trying to start a single mission:
0x806ce43 in dangerdeep at ??:0
0x804ebe2 in dangerdeep at ??:0
0xffffe420 in [0xffffe420] at ??:0
0xb7cfa876 in /usr/lib/libfftw3f.so.3 at ??:0
0xb7cfb634 in fftwf_mkplan_dft_ct at ??:0
0xb7cfa9f5cfb679 in fftwf_mkplan_dft_ct at ??:0
0xb7cfb425 in /usr/lib/libfftw3f.so.3 at ??:0
That's fftw-3.0.1-r2
hrm, I'm using sci-libs/fftw-3.1.2, the addwrite is for scons, I'm not really
into python and such but I know it plays silly buggers with the sandbox and
that was the only way I could get it to work. If anyone knows a better way
around it ?
The build patch from 0.1.1 ebuild solves the sandbox problems, adding it back
to 0.2.0 worked here.
I also changed the logic for SSE use, since sse use flag is always filtered on
amd64 ans so cannot be enabled
No segfaults here either with unstable fftw, is one of them ready for
stabilizing to solve the problem?
Created an attachment (id=99508) [edit]
Updated 0.2.0 ebuild
* Removed addwrite
* Added back build patch
* Changed sse logic
Created an attachment (id=99509) [edit]
Build patch updated for 0.2.0
Above patch and ebuild work perfectly for me on ~amd64
Created an attachment (id=99829) [edit]
dangerdeep-artwork license
The license that the artwork is distributed under, it is included in the data
zip, put here for easy of access.
The ebuild is working perfectly here.
Please put it in portage..
In portage. | http://bugs.gentoo.org/130023 | crawl-002 | refinedweb | 839 | 70.29 |
Ticket #1122 (closed bug: fixed)
incorrect orangeom imports in network package
Description
I'm not sure if I'm missing something obvious here, but it seems like the orangeom imports in the Orange.network package simple aren't going to work. In readwrite.py and network.py the import reads as
import orangeom
Surely this should be
from Orange import orangeom
?
Change History
comment:1 Changed 2 years ago by ales
- Status changed from new to assigned
- Owner set to ales
- Component changed from bioinformatics add-on to library
- Milestone set to 2.5
comment:2 Changed 2 years ago by Ales Erjavec <ales.erjavec@…>
- Status changed from assigned to closed
- Resolution set to fixed
Note: See TracTickets for help on using tickets. | http://orange.biolab.si/trac/ticket/1122 | CC-MAIN-2014-15 | refinedweb | 123 | 55.24 |
twicon 0.1.1
twicon #
twicon helps to integrate TW Icon Fonts, into your Flutter apps,
TW Icon Fonts consist of free icons covering topics like sights, products, traffic and so on. They let you to promote your favorite places and cuisines in Taiwan easily.
The icons are designed by a Japanese designer, holoko, and an English designer Rob. They are both living in Taiwan right now. For further information, please visit TW Icon Fonts.
Usage #
Adds
twicon to your pubspec file, run
futter packages get, then you can
import the package:
import 'package:twicon/twicon.dart';
Then you can use these icons in widgets like
Icon,
IconButton and so on:
Icon(TaiwanIcons.taipei101);
You can also run the example project, to view the icons included.
0.1.1 #
- Updates license and documentation.
0.1.0 #
-: twicon: :twicon/twicon.dart';
We analyzed this package on Jan 16, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:
- Dart: 2.7.0
- pana: 0.13.4
- Flutter: 1.12.13+hotfix.5 | https://pub.dev/packages/twicon | CC-MAIN-2020-05 | refinedweb | 177 | 68.67 |
I don’t want to come off like a Google fanboy. But I think that the Braille logo:
is the best Google logo evah. Even better than the Mondrian logo?
Yes, even better than the Mondrian logo. In fact, the Braille logo looks even better than the Seurat logo, which does not exist in our time-space continuum. Maybe I can hit up Dennis Hwang for a signed print some day. If I weren’t a very lazy man with abominable JavaScript skills, I would write a Greasemonkey script to show the Braille logo all the time.
Okay, I’ve gushed, so I want to include something critical of Google to balance it out. Want to hear my least favorite Google url parameter? Okay, it’s “&btnG=Google+Search”. If you type in a random word and press enter, it appears on the end of your url like an uninvited guest. I despise that parameter. It adds no value to my life as a user. If I wrote a Greasemonkey script to always show the Braille logo, I would also write code to drop that godforsaken btnG parameter. It’s a blight on my existence when I just want a simple url to copy-and-paste. 🙂
72 Responses to My favorite logo (Leave a comment)
Seconded, about &btnG=Google+Search (and it’s variations in different languages)
I think your google holiday logos () were also very cute. Too bad they didn’t stay for long. 🙂
Is it me, or do others find it ironic one needs sight to read Google’s Braille logo? It’s a bit like those signs you see on door of some food stores, “sorry, no guidedogs allowed”. 🙂
I think the Braille logo rocked as well! Is there an official place where we can see the different logo styles produced?
Damn that logo scared me. I turn on my computer and open firefox and the first thing to appear is that logo. I was like what? what happened? did someone hack google? lol
That’s why ALT tags > me. I had no idea what I was looking at when I opened up Google yesterday.
And Matt – thanks for inspiring me, I’m now hacking my way through my first Greasemonkey script to try and meet your requests. I’m sure someone will have it done before me, but it’s good practice.
>>hit up Dennis Hwang for a signed print some day
Matt – maybe you are on to a VERY cool idea to raise charity money. I bet a lot of people would donate for a Hwang signed original logo design. I’ll put my money where mouth is and offer $1000 to NetAid or Google.org for one. Rich folks might offer a lot more and that’s even better.
I totally agree. I thought the logo was fabulous. Although it might have been a bit too clever – everyone else at work was like “Huh?” until they had it explained. I look forward to the Morse code logo on 27 April
Best logo “evah?” What are you, a closet Bostonian?
I think the logo is cool, but I don’t know Braille, so I can’t fully appreciate it. Where is Helen Keller when we need her?
I think all of the different Google graphics add a personal touch to the company – a lot of other search engines such as MSN are impersonal
The best ones seem to be the sequence ones that evolve over a number of days (you can see them on Googles website here:)
Agreed. Even if you didn’t know braille, you’d instantly know what that says. Those colors are all you need to recognise Google – perhaps they should patent the use of those colors in that order! (Heinz patented that turquoise color they use on their Baked Beans tins, so I don’t see why not.)
> Okay, it’s “&btnG=Google+Search”. If you type in a random word and press enter, it appears on the end of your url like an uninvited guest.
I don’t think it does…
If you type a random word and click the “Google Search” button, it adds the btnG parameter to your request. However… if you press return or enter, it gets omitted.
Matt, I hate that parameter plus =Google which show up if you use the search button on the results page, rather than the home page. It’s almost certainly in use just for tracking purposes, right? Why not remove it from at least the search results page and assume if you don’t see it, it was a search button there? Whenever I post URL examples, I’m always hunting down and removing all these various parameters to try and get to as close as a “pure” string that everyone else can use and see the same (you know, assuming they’re all in the same country, not running saved preferences, not hitting different data centers — oh my 🙂 )
ladies, here it is:
stripped from any parameters other than q and I just customized it for you.
Enjoy.
You forgot to mention these rejected Google holiday logos 😉
I loved the new logo – it was very creative and whoever thought of that is a genious.. although it can’t be used by disabled people, but it does show that someone care and shows interest.
Google scores another point 😉
Be careful Matt, you will also fall into the recycled news trap, but Google is your badboy so if you don’t blog it, someone else will. This will also place your voice up there with those who are sometimes speaking badly of you. This stuff is extremely interesting…
I also couldn’t help but give props to that Braille logo on my blog last evening BUT I blogged it before you, so you are the one recycling news Mr. Cutts! 😉
Interested in blogging about the insane response to the bland Xmas logo this year in Google groups?
Question: If I put a no follow in the link above does Google see that as a bad paid type link or does it simply ignore it? I am afraid to do anything wrong these days…
Yeah that Mr. Lenssen, I was going to blog that for you, good stuff! 🙂
Easy fix for the URL, use a POST instead of a GET 🙂 Should be pretty easy to do in GM, I think there is a document.forms collection. If the backend can process it is another question…
Sean
Cool, I never knew some countries can see different logos. The story about the UK seeing a poppy for rememberence day that no other country saw interesting. I wonder what else were missing. Is there a Google logo history gallery?
This Logo has to be my all time favorite: But who’s the guy?
MC is one of my favorite artists of all time. You’ll replicas all over my living room.
Matt
This is SPAMZILLA
Whats the game plan with this lol ???
Can we send a Spmmy Award??
Clint
You can use usercontent.css to replace google’s logo permanently.
Gaston Julia. that’s it. that’s the list. 🙂
Clint,
You get nada when you do a site: search on massheros.com… 🙂
I thought the braille logo was pretty cool too. I wonder if blind people liked it as much? 😐
LOL Brian, Done!
:-O
I dunno…I just wasn’t feeling it. And a few people I talked to yesterday didn’t even get it (I had to explain what it was).
If you want to make it even more geeky, why not an ASCII character value logo?
71 111 111 103 108 101
You could really confuse the public then! 🙂
Why doesn’t google sell it’s logo? You know, one day it could say Goo Amazon.com oogle, the next day Goo gopulls.com oogle, etc? It’s really the next step past text ads, right?
like this?
A lot of the special occasion google logos I don’t get. Alt text does have it’s uses. 😉
lol Scott. I guess your website fell into those big holes of Google sandbox. All you could do is get some links from good PR websites.
“I thought the braille logo was pretty cool too. I wonder if blind people liked it as much? :-|”
Too funny! and a little mean..:)
Matt, I need your advice regarding the site Please reply me as soon as possible, because I have a question about the legal disclaimer.
Thanks!
Hi Matt,
The btnG parameter does have at least one function — on the results page, it causes the following search tip to be shown:
Tip: Save time by hitting the return key instead of clicking on “search”
A nice tip for users who always use the mouse to submit forms, instead of pressing enter.
I like the Braille Logo, very original and creative.
I thought that Bigdaddy update affect all, including the logo !!
Definately the best logo so far – neat! Is there anywhere to make suggestions for days/events for Dennis Hwang – just in case we really would like a logo for something?
And here’s the JavaScript from my previous comment with the less-than escaped:
var nodes = document.getElementsByTagName(“input”);
for (var i = 0; i < nodes.length; ++i) {
if (nodes[i].getAttribute(“name”) == “btnG”) {
nodes[i].removeAttribute(“name”);
}
}
at $99 for the catull font I look for as many uses to use it as possible. 🙂
Matt, take a look at this.
There is a monster on the loose, creating large keyword rich auto generated websites..
Ryan, the guy inside the Escher glass bowl is Sergey Brin…
Ahh that makes sense.. I’ve never seen a portrait of sergey. Perhaps if they just put the google logo in the glass It’d have been used. Escher is great.
That one, and “the puddle” are my 2 favorite. They’re in my living room.
Scott, if I’ve approved you once, it passes your comment right through. If you want to leave a “*** DO NOT APPROVE ***” post, I’d do it with a different email address and name.?”
I’m totally with you, Danny. That parameter dates waaaay back, so maybe no one uses it. Or maybe there’s another way to get that data. Or maybe we don’t need that data as much any more (why not just show it to a subsample of people to get the stats that you need?). Either way, me and btnG are at cross-purposes. 🙂
“Once you work at Google, if someone comes to your front door to ask for money, you start thinking “how would I do that in a scalable, robust way?”
Now that is funny Matt :)))
I recognized the Braille logo immediately and thought it was dumb. Braille is tactile, not visual.
is there someplace where we can see a history of logo’s, google has gone through? like a google photo (logo) gallery? I’d be interested in seeing the history of googles logo from the beginning! 🙂
Matt – your find-scalable-charity-giving is a very cool idea for the people who manage Google.org Charities waste a lot of time on low yield bake sales and in inefficient use of volunteers. Scalable? Just chain Dennis to a chair and say “DRAW MAN DRAW!”
Hey REALLY sorry Matt I thought I was doing it the way it was supposed to be posted. Now that you’ve replied in public, I’m sitting here looking for an email (hopeful and ambitious? lol ) Or will you simply not do that, and maybe the scenario should be posted in public in the blog? Either way please let me know, thank you so much for any of your time. And keep up the work on the awesome, and one of the most important blogs available to read on the net!
Yeah I think that logo is the best one yet.
I personally showed all my “geek” friends yesterday who hadnt seen it. 🙂
Here is one to be displayed at the Smithsonian oneday Google Beta
Matt,
Quickly adapted a Greasemonkey script I wrote a while ago to display the Braille logo on the main Google.com page. You can get it at:
Sorry for the double-comment…
Darrell, there’s a brief history of the Google logo at the very bottom of
I agree! I loved yesterday’s Braille logo. I’ve certainly loved many logos, but in terms of high concept that was tops. I’m glad that Google’s logo artwork is so ubiquitous and expected that they can afford to do something edgy like this, where the logo isn’t even legible in the strictest sense. Kudos to Google for taken this chance.
Before you spout your mouth off talk to someone who is blind, a friend of mine who reads ALT tags with his reader was very happy about it. The visual was for the rest of us to bitch and moan about…I guess.
Hi Matt,
In case you didn’t know, there is a widget to personalize the Google logo on the Personalized Home.
The thing is that you can only choose from a list of logos and the Braille one isn’t in the list (yet).
Actually, the source is available, so maybe you can modify it to include the Braille logo?
Yes, modifying that module is very easy.
I’ve modified my version of it to also change the google logo to an MSN or Yahoo one, and change the search box to point to the appropriate search engine as well.
not entirely useful, but neat.
Matt wrote:
[quote?”[/quote]
Actually Matt – I think it is both brilliant & scaleable. Google could sell the ‘original’ artwork at a premium; and do a limited edition of say 1,000 prints @ say $100 – $200 a piece.
Sell the prints via the Google store – and then just donate the money (by my maths thats’ $100K – 200K) to whichever charity is the ‘closest charity’ to the event – eg The Royal Blind society could get the funds from the Braille logo etc.
Charity fundraising is often just as much about awareness (of issues, diseases etc) as it is about raising funds – using the logo this way would achieve both…….
And as there are numerous ‘national’ events which get a special event logo – like ANZAC Day here in Australia – its scaleable across the world.
I agree, Matt, I think the logo was probably the best ever. Do you guys accept suggestions for cool logo’s?
Darrell: Google’s logo history is here
Look like it chopped it off at the less-than brace, I’ll try again – sorry for spam 🙂
// alter-google.com-logo
// ==UserScript==
// @name alter-google.com-logo
// @namespace http:// [removed]
// @description Replace Google.com logo
// @include
// ==/UserScript==
(function() {
var images = document.getElementsByTagName(‘img’);
for (var i = 0; i < images.length; i++){
var img = images[i];
if (img.getAttribute(‘src’) == ‘/intl/en/images/logo.gif’)
{
img.setAttribute(‘src’, ‘PUT YER URL IN HERE 🙂 SIMPLE!’);
img.setAttribute(‘height’, ”);
img.setAttribute(‘width’, ”);
break;
}
}
})();
Ok, that should work if you switch the left and right single quotes for normal single quotes 🙂
“I’m totally with you, Danny. That parameter dates waaaay back, so maybe no one uses it. ”
The browser puts it there automatically if the submit button has a value, since it treats the button like another parameter.
My erm, ‘adult’ search engine has the same problem.
If they left the form saying “submit” instead of “Google Search” then it wouldn’t be appended because the submit button wouldn’t have the value “Google Search”.
Indeed! Everyone in our office loved it.
Can’t wait for the next Googo (Google logo)! How’s that? Can I coin that term now? he he 😉
V
I am a legally blind person (low vision) who can read some Braille. I really appreciated the logo. I knew exactly what it was when I saw it. Braille needs more attention. Not enough people that need it are being taught it. The establishment thinks that if you can read any print at all you don’t need to learn Braille. Because of this there are many illiterate people out there with low vision. Unless you can read exactly like a sighted person you should learn Braille.
typing in the googo.com name looks like some domainer already beat you to it.
Matt:
Thanks for the great work and helpful information.
I am interested in any insites you can give us about dynamic links, spidering and canonicalization. The discussion I would love to see is concerning how database/query driven content is spidered and how to avoid content duplication penalties.
A few years ago I devised a static directory structure to allow our product pages to be indexed correctly. This has worked pretty well and is clearly white hat.
1. Although the products each have a static page in our directory, they can also be pulled up by a query string so is the same content as except the static landing page contains a unique unique header whereas the dynamic version has a common header.
2. may also be diplayed with tracking links, resulting in
Occassionally, I have seen the base URL and the URL with the tracking links show up as 2 separate links. Any information would be great.
Thanks
You can pick any Google logo you like, add this to the Google Personalised Home Page
How the hell can the blind see it to appreciate it?
Dan Freakly, see the following comments above:
Aaron Pratt Said,
January 5, 2006 @ 5:04 am
David Ogletree Said,
January 6, 2006 @ 9:48 am
I love/respect Dr. King, but today’s logo is a tad on the cheesy side.
Hey, I like the Mondrian Logo, but isn’t it against Google Trademark to put their logo on your website?
Google ignore UK Mothers?
Did google.co.uk forget to upload their homage mother’s day logo to the millions of UK Mothers on mothers day Sunday 26th March?
As an American led search giant that makes a point of acknowledging countries customs by changing the google logo to reflect the countries occasions, it seems to have forgotten about Mothersday on Sunday 26th March. So to help you out I have made a google a logo for you .
Regards
Jessica Luthi
I totally agree – GOOGLE is an amzing brand!
It is dynamic, modern, creative and aesthetically appealing. The designers need a good pat on their back’s for this ingenious brand.
Well done GOOGLE! | https://www.mattcutts.com/blog/my-favorite-logo/ | CC-MAIN-2018-17 | refinedweb | 3,092 | 82.24 |
Everything's a box
In this post i'm going to introduce one of the concepts you can use when developing web pages/apps using Theme UI
If you're not familiar with Theme UI take a moment to have a read of the docs... and if you're not familiar with CSS-in-Js perhaps have a read up on that first.
I'm going to talk about one quite complicated but in my opinion unnecessary part of Theme UI and it's something that took me a while to work out since the docs don't really mention this in a clear and concise way.
It's my hope that this post might clarify a couple of things and help lower the barrier to entry when using Theme UI. I won't go into detail about how the CSS properties link to the their respective scales or keys... that's a post for another time.
In the docs you'll see a code snippet like this.
/** @jsx jsx */import { jsx } from 'theme-ui'export default (props) => (<divsx={{fontWeight: 'bold',fontSize: 4,color: 'primary',}}>Hello</div>)
When i first saw this i was like "What the flip is @jsx", and "where's the import for
React" ... and then after a
while i read on and started to understand what
jsx pragma actually is.
The TLDR version is as follows.
When you include
/** @jsx jsx */ in your React component you don't need to import React. This because the
jsx pragma
kind of includes the functionality to transform JSX for us. The
jsx pragma also allows a new "type" of HTML attribute,
it's called the
sx prop which can be applied to any normal HTML element.
With the
sx prop you can now style you UI using Theme UI's super powers.
If you'd like to know about more, have a read of this: What is JSX Pragma
No more naming of CSS classes, or importing global variables 🤢 and in no way will we need to worry about order of specificity 🙌... nice ay!
But...
Importing
jsx and having to explain the
jsx pragma is all a bit unnecessary so i'm proposing we try this another
way.
Instead of doing what the docs say, try this approach instead.
import React from 'react'import { Box } from 'theme-ui'export default (props) => (<Boxsx={{fontWeight: 'bold',fontSize: 4,color: 'primary',}}>Hello</Box>)
You can see from the above that we don't need to import the
jsx pragma and instead we can import React as we normally
would and then use one of the components that ships with Theme UI.... The
<Box />
The Box is technically just a div but if you inspect the below you'll see there's a few things Theme UI does for us which will save us time later.
JavaScript for Box 👇
<Box>I'm a Box</Box>
JavaScript for div 👇
<div>I'm a div</div>
CSS for Box 👇
display: block;box-sizing: border-box;margin: 0;min-width: 0;
CSS for div 👇
display: block;
You can see from the above that the CSS for the
<Box /> includes some resets for us, eg.
box-sizing,
margin and
min-width and whilst in the past we could have used a global CSS file that handles the resets, we don't want to use
global CSS because this is where problems arise.
Global styles and the dreaded
!important are escape hatches. These are work arounds we've developed over the years to
compensate for some of the shortcomings of native CSS. But in the new world of CSS-in-Js these native shortcomings have
been removed which allows us to spend more time focussing on actually building something.
But wait, there's more, here's the
<Flex /> component that ships with Theme UI
JavaScript for Flex 👇
<Flex>I'm a Flex</Flex>
CSS for Flex 👇
display: flex;box-sizing: border-box;margin: 0;min-width: 0;
...and you can see from the CSS snippet that the defaults that come with this component save us the time of adding them
ourselves. e.g
<Flex /> already has
display: flex; Cool ay! 😎
One last thing. Theme UI also allows the Polymorphic
as prop. Poly meaning many, and morphic meaning forms so
you can do things like this.
JavaScript for aside 👇
<Box as="aside">I'm an aside</Box>
CSS for aside 👇
display: block;box-sizing: border-box;margin: 0;min-width: 0;
You'll see if you inspect the "I'm man aside" element that the actual HTML element is in fact an
<aside /> and it
still inherits all the resets from
<Box />
The
as props works with all manner of HTML elements... even inputs:
<Box as="input" placeholder="I'm an input" />
... but don't do as above, use the
<Input /> component instead because it maps to the correct key in the theme object:
forms.input
<Input placeholder="I'm an input" />
So now you know.
Everything's a
<Box />... sort of
Reactions
Newsletter
This is a sign-up to Queen Raae's Gatsby Newsletter because I don't really like people, or emails. She'll let you know when I have something new to share! | https://paulie.dev/posts/2020/07/everythings-a-box | CC-MAIN-2022-05 | refinedweb | 867 | 67.69 |
Using.
Component Playgrounds
You might be wondering “Why would would I need something like this? I can just test my components in the app!” and you’re right. But imagine building a reasonably large application with dozens of routes, hundreds of components and thousands of possible component states. Checking all of these component states manually on the different routes that they are appearing on is a very time consuming task. A component playground solves this by allowing you to display multiple component states next to each other on a single page to give you a much better and quicker overview of how the component will look like in the end.
Another big advantage of using component playgrounds is that it forces you to build reusable components that are isolated from the app’s business logic and layout. That means they don’t depend on any state or actions in your controllers, routes and ideally services, but only on the data and action handlers that are passed into them.
If you want to know more about why component playgrounds are useful in general I recommend reading this great blog post “UI component explorers — your new favorite tool” by Dominic Nguyen that explains the benefits very well.
Installing
ember-freestyle
Installing and configuring
ember-freestyle correctly is unfortunately a
little complicated right now so if you want to take a look at the final
outcome, you can skip forward to the “Using
ember-freestyle”
section for now.
Before we start installing anything we should make sure we know what situation
we would like to be in at the end. Our plan is to use
ember-freestyle to
generate a component playground at the
/freestyle route, that is only
available during development and does not affect the final asset sizes of the
production build.
Let’s start by following the official instructions on the
ember-freestyle
website:
ember install ember-freestyle
- Add
this.route('freestyle');to the
app/router.jsfile
Adjusting the
application template
If you try this in a fresh new Ember app, run the development server using
ember serve and visit you will notice the
first problem: The
ember-freestyle components are appearing underneath the
{{welcome-page}} component:
This is obviously not what we want. To fix this we will need to adjust the
app/templates/application.hbs file and wrap the existing contents in a
condition:
+{{#if onFreestyleRoute}} + {{outlet}} +{{else}} {{!-- The following component displays Ember's default welcome message. --}} {{welcome-page}} {{!-- Feel free to remove this! --}} {{outlet}} +{{/if}}
onFreestyleRoute is a property on the
application controller that will be
set to
true once we visit the
/freestyle route and and back to
false
once we leave it again. This can be implemented in the
app/routes/freestyle.js
file, and since that does not exist yet, we can generate it using
ember generate route freestyle (choose not to overwrite the existing
template!) and then adjusting it like this:
export default Route.extend({ activate() { this._super(...arguments); this.controllerFor('application').set('onFreestyleRoute', true); }, deactivate() { this._super(...arguments); this.controllerFor('application').set('onFreestyleRoute', false); }, });
If you check
/freestyle again you should see that now the only thing that is
displayed is the
ember-freestyle guide. 🎉
Removing
ember-freestyle from the production build
Once you try to ship this to production you might notice another issue: your
asset size has increased significantly, so it seems that
ember-freestyle is
not disabled for production builds by default. Let’s fix this!
According to the
ember-freestyle documentation we are supposed to “blacklist”
the addon in the
ember-cli-build.js file of our app:
module.exports = function(defaults) { let environment = process.env.EMBER_ENV; let pluginsToBlacklist = environment === 'production' ? ['ember-freestyle'] : []; let app = new EmberApp(defaults, { addons: { blacklist: pluginsToBlacklist } }); return app.toTree(); };
Great! Now our asset size is back to normal. Wait… it is smaller now, but still not quite back to what we had before. 🤔
The code above only removes all the components from the build that
ember-freestyle brings with it itself. That means components like
{{freestyle-guide}} and
{{freestyle-usage}}
are no longer part of the production build, but the
freestyle controller,
route and template are still included.
The solution to this problem is moving the
freestyle files into a dedicated
in-repo-addon and then blacklisting that one too. First we generate a new
in-repo-addon using
ember generate in-repo-addon freestyle. After that we
move
app/controllers/freestyle.js to
lib/freestyle/app/controllers/freestyle.js
and do the same for the
freestyle route and template.
Next we will add our new
freestyle in-repo-addon to the
pluginsToBlacklist
list above:
let pluginsToBlacklist = environment === 'production' ? ['ember-freestyle', 'freestyle'] : [];
Finally we need to adjust the paths that
ember-freestyle uses to search for
the code snippets that show how the component is used in a host application.
For that we will add a
snippetSearchPaths property in the
ember-cli-build.js
file:
let app = new EmberApp(defaults, { // ... freestyle: { snippetSearchPaths: ['lib/freestyle/app'], }, });
If you now restart the development server and check the
/freestyle route
you should see that everything is working as before, but if instead you run
ember serve -prod you will notice that you only see a blank page because
the
freestyle controller, route and template are no longer available.
If you would like to use your default 404 page instead you can put the
this.route('freestyle'); call in the
router.js file in a condition
that checks
if (config.environment === 'development').
This leaves us with only the single condition in the
application template and
the
this.route('freestyle'); call in the
router.js file that we ship to
production. While we could put in some effort to remove those too the situation
is good enough and we can finally focus on putting content into our new
component playground! 🎉
Using
ember-freestyle
The good news is that using
ember-freestyle is much easier than setting
it up correctly!
Let’s pretend we are writing a component called
styled-button. We can create
a new file at
app/components/styled-button.js and put the following content
in it:
import Component from '@ember/component'; export default Component.extend({ tagName: 'button', classNames: ['styled-button'], });
In addition to that we’ll add some styles for this button to our
app/styles/app.css file:
.styled-button { border: 1px solid #eee; border-radius: 3px; background-color: #FFFFFF; cursor: pointer; font-size: 15px; padding: 3px 10px; }
Finally we will add the button to our component playground by editing the
lib/freestyle/app/templates/freestyle.hbs template:
{{#freestyle-guide title='Ember Freestyle' subtitle='Living Style Guide'}} {{! ... }} {{#freestyle-section name='Components' as |section|}} {{#section.subsection name='styled-button'}} {{#freestyle-usage 'styled-button-example-1'}} {{#styled-button}}Hello World!{{/styled-button}} {{/freestyle-usage}} {{#freestyle-usage 'styled-button-example-2'}} {{#styled-button}}😀 😎 👍 💯{{/styled-button}} {{/freestyle-usage}} {{/section.subsection}} {{/freestyle-section}} {{/freestyle-guide}}
If we now visit we will see a new
“Components” section in the sidebar on the left that includes our
“styled-button” subsection. Once we click on that we will see our
styled-button usage examples including the snippets there were used to
display them:
As this blog post has gotten much longer than intended already I’ll leave it up to your imagination what other things you can put into such a component playground. In a follow-up post we will soon discuss how to extract subsections into components and how to automatically discover and inject them into the main template.
Finally I would like to thank Chris LoPresto and the other contributors for
working on
ember-freestyle and would encourage you to give it a try! | https://simplabs.com/blog/2018/01/24/ember-freestyle.html | CC-MAIN-2018-39 | refinedweb | 1,274 | 54.63 |
XML Schema Attributes ViewEdit online
The Attributes view for XML Schemas presents the properties for the selected component in the schema diagram. By default, it is displayed on the right side of the editor. If the view is not displayed, it can be opened by selecting it from the menu.
The default value of a property is presented in the Attributes view with blue foreground. The properties that can not be edited are rendered with gray foreground. A non-editable category that contains at least one child is rendered with bold. Bold properties are properties with values set explicitly to them.
Properties for components that do not belong to the current edited schema are read-only but if you double-click them you can choose to open the corresponding schema and edit them.
You can edit a property by double-clicking by pressing Enter. For most properties you can choose valid values from a list or you can specify another value. If a property has an invalid value or a warning, it will be highlighted in the table with the corresponding foreground color. By default, properties with errors are highlighted with red and the properties with warnings are highlighted with yellow. You can customize these colors from the Document checking user preferences.
For imports, includes and redefines, the properties are not edited directly in the Attributes view. A dialog box will open that allows you to specify properties for them.
The schema namespace mappings are not presented in Attributes view. You can view/edit these by choosing Edit Schema Namespaces from the contextual menu on the schema root. See more in the Edit Schema Namespaces section.
The Attributes view has five actions available on the toolbar and also on the contextual menu:
Add
- Allows you to add a new member type to an union's member types category.
Remove
- Allows you to remove the value of a property.
Move Up
- Allows you to move up the current member to an union's member types category.
Move Down
- Allows you to move down the current member to an union's member types category.
Copy
- Copy the attribute value.
Go to Definition
- Shows the definition for the selected type.
- Show Facets
- Allows you to edit the facets for a simple type. | https://www.oxygenxml.com/doc/versions/21.1/ug-editor/topics/xml-schema-diagram-attributes-view-x-editing2.html | CC-MAIN-2019-51 | refinedweb | 379 | 64.91 |
- Author:
- SmileyChris
- Posted:
- October 18, 2009
- Language:
- Python
- Version:
- 1.1
- Score:
- 7 (after 7 ratings)
Nicely output all form errors in one block, using field labels rather than the field attribute
Example?
#
Example:
(My line-formatting is going to get wiped out by the Markdown processor, so you'll have to paste this into an editor and do indenting there.)
` {% if form.errors %}<br /> <br />
{% with form|nice_errors as qq %} {% for error_name,desc in qq.items %}
- {{ error_name }}:
- {{ desc }}
{% endfor %}
{% endwith %}<br /> {% endif %} <br /> `
Since ErrorDict does some auto-HTMLizing of the dict values, this will produce doubly-nested unordered lists.
#
Please login first before commenting. | https://djangosnippets.org/snippets/1764/ | CC-MAIN-2022-27 | refinedweb | 106 | 55.03 |
You can verify this with a simple program, stated below that shows that CryptoStream.Close() is explicitly not required.
The expected result should be 104 since 13 bytes should be allocated. We get 104 with a call to Close() or without calling Close().
1: using System;
2: using System.IO;
3: using System.Security;
4: using System.Security.Cryptography;
5:
6: namespace TestCryptoStream
7: {
8: class Program
9: {
10: static void Main(string[] args)
11: {
12: DESCryptoServiceProvider csp = new DESCryptoServiceProvider();
13: ICryptoTransform trans = csp.CreateEncryptor();
14: MemoryStream ms = new MemoryStream();
15:
16: using (CryptoStream cs = new CryptoStream(ms, trans, CryptoStreamMode.Write))
17: {
18: cs.Write(new byte[100], 0, 100);
19: //cs.Close();
20: }
21: Console.WriteLine(ms.ToArray().Length);
22: }
23: }
24: }
However if you look through the MSDN link at link, it states to explicitly call CryptoStream.Close().
The part which states this at the above MSDN link is:
"You should always explicitly close your CryptoStream object after you are done using it by calling the Close method. Doing so flushes the stream and causes all remain."
This seems to contradict the following bug listed at, which states:
"The behavior change in v2.0 was that Closing and Disposing the CryptoStream should be semantically the same. (See related bug) This change was done for two reasons. First, we have consistency with other BCL streams which act in the same way. Secondly, if Dispose() did not Close(), then we would end up where Disposing a CryptoStream does not cause the final block to be flushed, therefore giving incorrect results."
Shamik Misra
Windows SDK | https://blogs.msdn.microsoft.com/winsdk/2009/11/13/do-you-need-to-explicitly-call-cryptostream-close-to-close-your-cryptostream-object-after-you-are-done-using-it/ | CC-MAIN-2018-39 | refinedweb | 264 | 59.6 |
Tracing a recursive function by hand can be very helpful for understanding the progression of method calls. Examine the following two recursive functions, and attempt to answer the associated questions by tracing the method calls by hand. This is a great time to get out a piece of paper and a writing implement.
def strange(x): if x <= 0: return 1 else: return 5 * strange(x-1) - 2
print(strange(3))?
def weird(x): if x > 0: print(x) if x%2 == 0: weird(x-3) weird(x-2) else: weird(x-1)
weird(8)?
Only when you have fully attempted both exercises by hand, you should run the file
weirdlystrange.py to check your answers.
There are many different ways to reverse a string. In the file
gnirts.py, you’ll find a function called
loop_reverse(s) that uses a
for loop to reverse the string
s. You will also find a function called
recursive_reverse(s) that is only partially complete (i.e., only the base case has been written). Work with your partner to write the recursive function call necessary to finish
recursive_reverse(s).
Slicing Strings
String slicing will likely help you finish
recursive_reverse(s). As a reminder, here are some examples of string slicing.
message = 'hello!' message[1:] #returns 'ello!' message[-1] #returns '!' message[1:-1] #returns 'ello'
In this lab, you’ll be drawing fractal patterns, like this Sierpinski Carpet below.
This part of the warmup will take you through the some of the math required.
Fractals are images that are self-similar. This can be seen in the Sierpinski Carpet by noticing that it contains eight smaller Sierpinski sub-Carpets, arranged around the center square of the image. Just like
picture.draw_square(x,y,side), you can imagine identifying a sub-carpet’s location with its top left corner. If the canvas has width and height of
size, what are the locations of the points A through I, below?
Knowing these locations will be helpful when you work on Part 3 of the lab.
One of your other fractals will be the Koch Snowflake (shown below).
To draw the Koch Snowflake, you’ll be drawing three copies of the “Koch Curve.”
Notice that this doesn’t involve any shapes. Instead, we’ll be drawing lines using the the pen from the
picture module. Below, you’ll see the simplest non-base-case version of the Koch Curve. Imagine your pen starts at point A, facing right. If the straight-line distance from A to E is
length, each of the four line segments has length
length/3. What angles will you need to rotate at points B, C, and D to draw the curve?
Knowing these angles will be helpful when you work on Part 3 of the lab. | https://www.cs.oberlin.edu/~cs150/lab-7/warmup/ | CC-MAIN-2022-21 | refinedweb | 464 | 75.5 |
Bug #3923
Invalid result-document output in Saxon-HE-9.9.0-1
0%
Description
I've tested latest version of Saxon HE and got invalid output with duplicate namespace. The code looks like this:
<?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet <xsl:template <xsl:variable <unit/> </xsl:variable> <xsl:sequence <xsl:result-document <xsl:sequence </xsl:result-document> </xsl:template> </xsl:stylesheet>
Any input xml should be supplied. Stylesheet produces two outputs.
out2.xml for me is like this:
<?xml version="1.0" encoding="UTF-8"?><unit xmlns="x" xmlns:
Note xmlns twice.
History
#1
Updated by Michael Kay 17 days ago
I think this is probably related to bug #3889, which proved very disruptive. Perhaps the patch for that bug wasn't applied correctly on the 9.9 branch, or was inconsistent with some other change.
Current state: I've reproduced the problem, but walking it through in the debugger, I can't see where the excess namespace declaration is coming from. There seems to be a NamespaceReducer in the pipeline that is successfully eliminating duplicate declarations, but somehow this one slips through...
#2
Updated by Michael Kay 17 days ago
There is a rather remarkable error in NamespaceReducer.namespace(), which is present also in 9.8. The code:
for (NamespaceBinding ns : namespaceBindings) { if (isNeeded(ns)) { addToStack(ns); countStack[depth - 1]++; nextReceiver.namespace(namespaceBindings, properties); } }
processes a set of namespace bindings. If any of the namespace bindings is needed, then it outputs all of them.
The ability to pass multiple namespaces in a single call of Receiver.namespace() was introduced in Saxon 9.8, it was found to give significant performance improvements when doing a deep-copy of a tree in which elements had many (like a dozen) in-scope namespaces.
Why this obvious error hasn't caused more problems is anyone's guess.
#3
Updated by Michael Kay 17 days ago
Confirmed that correcting this code fixes the problem. More regression testing is needed before closing the bug, however.
#4
Updated by Michael Kay 16 days ago
- Applies to branch 9.8, 9.9 added
- Fix Committed on Branch 9.8, 9.9 added
I'm currently getting quite a lot of failures in xsl:result-document tests. These are probably the result of unfinished work on bug #3920, but I can't be sure, so I will leave this open until #3920 is settled. However, I am committing this patch for both 9.8 and 9.9 as the code is so obviously wrong.
#5
Updated by Michael Kay 13 days ago
- Category set to XSLT conformance
- Status changed from New to Resolved
- Assignee set to Michael Kay
- Priority changed from Low to Normal
Please register to edit this issue
Also available in: Atom PDF | https://saxonica.plan.io/issues/3923 | CC-MAIN-2018-43 | refinedweb | 461 | 58.28 |
> i merged it up in tip/master, could you please check whether it's ok?> Sorry, though this patch avoids accessing a half-created cgroup, but I foundcurrent code may access a cgroup which has been destroyed.The simplest fix is to take cgroup_lock() before for_each_leaf_cfs_rq.Could you revert this patch and apply the following new one? My box hassurvived for 16 hours with it applied.==========From: Li Zefan <lizf@cn.fujitsu.com>Date: Sun, 14 Dec 2008 09:53:28 +0800Subject: [PATCH] sched: fix another race when reading /proc/sched_debug (via cgroup_rmdir), buthasn't been destroyed (via cgroup_diput).But I found there's another different race, in that reading sched_debugmay access a cgroup which is being created or has been destroyed, and thusdereference NULL cgrp->dentry!task_group is added to the global list while the cgroup is being created,and is removed from the global list while the cgroup is under destruction.So running through the list should be protected by cgroup_lock(), ifcgroup data will be accessed (here by calling cgroup_path).Signed-off-by: Li Zefan <lizf@cn.fujitsu.com>--- kernel/sched_fair.c | 6 ++++++ kernel/sched_rt.c | 6 ++++++ 2 files changed, 12 insertions(+), 0 deletions(-)diff --git a/kernel/sched_fair.c b/kernel/sched_fair.cindex 98345e4..8b2965b 100644--- a/kernel/sched_fair.c+++ b/kernel/sched_fair.c@@ -1737,9 +1737,15 @@ static void print_cfs_stats(struct seq_file *m, int cpu) { struct cfs_rq *cfs_rq; + /*+ * Hold cgroup_lock() to avoid calling cgroup_path() with+ * invalid cgroup.+ */+ cgroup_lock(); rcu_read_lock(); for_each_leaf_cfs_rq(cpu_rq(cpu), cfs_rq) print_cfs_rq(m, cpu, cfs_rq); rcu_read_unlock();+ cgroup_unlock(); } #endifdiff --git a/kernel/sched_rt.c b/kernel/sched_rt.cindex d9ba9d5..e84480d 100644--- a/kernel/sched_rt.c+++ b/kernel/sched_rt.c@@ -1538,9 +1538,15 @@ static void print_rt_stats(struct seq_file *m, int cpu) { struct rt_rq *rt_rq; + /*+ * Hold cgroup_lock() to avoid calling cgroup_path() with+ * invalid cgroup.+ */+ cgroup_lock(); rcu_read_lock(); for_each_leaf_rt_rq(rt_rq, cpu_rq(cpu)) print_rt_rq(m, cpu, rt_rq); rcu_read_unlock();+ cgroup_unlock(); } #endif /* CONFIG_SCHED_DEBUG */-- 1.5.4.rc3 | http://lkml.org/lkml/2008/12/13/203 | CC-MAIN-2014-42 | refinedweb | 316 | 58.48 |
SSL_get_rbio(3) OpenSSL SSL_get_rbio(3)Powered by man-cgi (2021-06-01). Maintained for NetBSD by Kimmo Suominen. Based on man-cgi by Panagiotis Christias.
NAME
SSL_get_rbio, SSL_get_wbio - get BIO linked to an SSL object
LIBRARY
libcrypto, -lcrypto
SYNOPSIS
#include <openssl/ssl.h> BIO *SSL_get_rbio(SSL *ssl); BIO *SSL_get_wbio(SSL *ssl);
DESCRIPTION
SSL_get_rbio() and SSL_get_wbio() return pointers to the BIOs for the read or the write channel, which can be different. The reference count of the BIO is not incremented.
RETURN VALUES
The following return values can occur: NULL No BIO was connected to the SSL object Any other pointer The BIO linked to ssl.
SEE ALSO
SSL_set_bio(3), ssl(7) , bio_rbio(3) | https://man.netbsd.org/SSL_get_rbio.3 | CC-MAIN-2022-40 | refinedweb | 113 | 58.89 |
#include "libavutil/float_dsp.h"
#include "avcodec.h"
#include "put_bits.h"
#include "aac.h"
#include "audio_frame_queue.h"
#include "psymodel.h"
#include "lpc.h"
Go to the source code of this file.
Definition at line 34 of file aacencdsp_init.c.
Referenced by aac_encode_init().
Definition at line 2484 of file aaccoder_mips.c.
Referenced by aac_encode_init().
Definition at line 126 of file aacenc.c.
Referenced by search_for_quantizers_fast(), and search_for_quantizers_twoloop().
Definition at line 897 of file aaccoder.c.
Referenced by aac_encode_init().
List of PCE (Program Configuration Element) for the channel layouts listed in channel_layout.h.
For those wishing in the future to add other layouts:
index: there are three independent indices for SCE, CPE and LFE; they are incremented irrespective of the group to which the element belongs; they are not reset when going from one group to another
Example: for 7.0 channel layout, .pairing = { { 1, 0 }, { 1 }, { 1 }, }, (3 CPE and 1 SCE in front group) .index = { { 0, 0 }, { 1 }, { 2 }, }, (index is 0 for the single SCE but goes from 0 to 2 for the CPEs)
The index order impacts the channel ordering. But is otherwise arbitrary (the sequence could have been 2, 0, 1 instead of 0, 1, 2).
Spec allows for discontinuous indices, e.g. if one has a total of two SCE, SCE.0 SCE.15 is OK per spec; BUT it won't be decoded by our AAC decoder which at this time requires that indices fully cover some range starting from 0 (SCE.1 SCE.0 is OK but not SCE.0 SCE.15).
Definition at line 137 of file aacenc.h.
Referenced by aac_encode_init(). | http://ffmpeg.org/doxygen/trunk/aacenc_8h.html | CC-MAIN-2019-47 | refinedweb | 268 | 70.7 |
14 June 2012 11:24 [Source: ICIS news]
SINGAPORE (ICIS)--Here is Thursday’s end-of-day ?xml:namespace>
CRUDE: July WTI $82.74/bbl, up 12 cents; July BRENT $97.30/bbl, up 17 cents
Crude oil prices were higher in the afternoon as investors await the outcome of an OPEC meeting later on Thursday amid persistent concerns about slowing global oil demand.
NAPHTHA: $738.00-740.00/tonne CFR Japan, up $11.00/tonne
Open-spec naphtha prices rebounded in the afternoon session, supported by renewed spot buying interest. Two deals were settled at $740/tonne CFR Japan for first half of August loading.
BENZENE: $990-1,000/tonne FOB
The inter-month spread for July and August continued to be assessed at a backwardation in a thinly traded market. August’s bid-offer range was heard at $965-995/tonne FOB
TOLUENE: $955-970/tonne FOB
Trading was thin in the afternoon, with a bid for July loading heard at $950/tonne FOB
ETHYLENE: $890-930/tonne CFR NE Asia, down $10/tonne at the low end
Buying ideas for end-June/any July arrival cargoes in Taiwan slipped to $880/tonne CFR Taiwan, but sellers were reluctant to give in on account of poor margins.
PROPYLENE: $1,230-1,260/tonne CFR NE Asia, up $10/tonne at the high end
Two deals for second-half July arrival were concluded – one at $1,230/tonne, and another at $1,240/tonne CFR China. A separate deal was heard done at $1,260/tonne CFR China, while another cargo for first-half July arrival was fixed at $1,260-1,270/tonne CFR | http://www.icis.com/Articles/2012/06/14/9569289/evening-snapshot-asia-markets-summary.html | CC-MAIN-2014-42 | refinedweb | 276 | 59.23 |
On Mon, Dec 19, 2005 at 08:45:45PM -0800, Russ Allbery wrote: > > (TBH, I'd be much happier just making the technical changes necessary to > > ensure /var is mounted early -- keeps the filesystem sane, and it's just > > a simple matter of programming, rather than arguing over what's ugly. > Yeah, I agree with this too.. For (d) and (e) you need special handling; using /run as a tmpfs and setting up /var/run -> /run symlinks on both / and /var. That's pretty special handling, and probably needs something like shared subtrees to be done automatically at upgrade time (). For (c) you could either do the same handling as (d) and (e), or just expect the admin to mount it rw as part of bootup. As far as the "but programmers/admins might be confused" concern goes; adding a brief /run/README at bootup seems feasible. That'd mean: /var is available after: S10checkroot.sh (/var on rootfs) S35mountall.sh (/var local) S40hotplug (/var local, but requires hotplug drivers) S45mountnfs.sh (/var on NFS not mounted before init) /var/run is thus available after one of: S10checkroot.sh S35mountall.sh S36mountvirtfs And /var/run is used before /var is necessarily available by (on my system): S39dns-clean S40networking S41hotplug-net S43portmap Hrm. Special casing in mountvirtfs and mountnfs.sh could be: mountvirtfs: if touch /var/run/.rw_var_run >/dev/null 2>&1; then rm -f /var/run/.rw_var_run elif [ "$EARLY_RUN_FS" ] && [ -d "$EARLY_RUN_FS" ]; then echo "Mounting /var/run tmpfs on $EARLY_RUN_FS..." mount -t tmpfs tmpfs "$EARLY_RUN_FS" ln -s . "$EARLY_RUN_FS/run" mount --bind "$EARLY_RUN_FS" /var touch /var/.bind_var else echo "Error: no early writable filesystem available" # ... fi mountnfs.sh: if [ -e /var/.bind_var ]; then rm -f /var/.bind_var /var/run umount /var fi # ... mount -a at which point you only need to mkdir $EARLY_FUN_FS and ensure /var/run is a symlink to it when setting up that behaviour on upgrade. Alternatively you could just make the directory and "mount --bind $EARLY_RUN_FS /var/run" after mounting /var. (If $EARLY_RUN_FS is /run, you'd have to work out in advance when it's needed so as not to add useless stuff to / when it's not needed; adding a pointless dir to /etc or /lib would likely be okay though) Note that in that scenario programs are FHS compliant in that they only access files throug the /var/run namespace, and if an admin prefers /etc/run or /lib/run, it's just a matter of local configuration rather than recompiling apps. Cheers, aj
Attachment:
signature.asc
Description: Digital signature | https://lists.debian.org/debian-devel/2005/12/msg00953.html | CC-MAIN-2017-51 | refinedweb | 426 | 65.01 |
Arduino XMAS Hitcounter
The bell is held by a strong paperclip. The small paperclip is used to form a kind of arm that is atached to the servo motor.
Note, that you want to bent the paperclip that holds the bell in a way, that already a little shaking generates a ding.
Step 3: Schematics
There is no real schematic. Just attach the servo motor to the Arduino. The servo has three wires:
- yellow or orange: signal
- red: VCC
- brown: GND
The red and the brown one are attached to the according pins on the Arduino (5V and GND). The orange one is wired to pin 2. It will signal the servo in which direction to turn.
You may want to solder small connectors to the wires if the wires do not fit directly into the Arduino or the servo.
Step 4: Programming the Arduino
Arduino
If you are new to the Arduino, it is a small board, fully assembled with a AVR microcontroller. It is well suited for hacking and interacting with your environment. Many things that are hard with microcontrollers are rather easy with Arduino. Some of the advantages:
- no need for a separate programming device (programmer)
- comes with an integrated development environment (IDE)
- runs on any platform, Windows, Mac, Linux.
- easy connection to your PC with USB
- hardware is open source (but the name Arduino is not)
- has a great community
More information can be found at the official Arduino website. Be sure, to check out John’s Arduino instructable for further details on how to get started with Arduino.
What does the software do?
The small piece of software that gets uploaded to the Arduino, controls the servo. It receives single bytes via the serial connection over the USB cable. If it receives a value of 5, it moves the servo arm five times forth and back. So the max value to send is 255.
Program the Ardiuno
So I assume you have downloaded and installed the latest Arduino IDE from Arduino.cc. For now it is version 0010 Alpha.
To drive the servo more comfortably you have to download a library. You can find it on the Arduino Playground. Unzip it and put the folder in …/arduino-0010/hardware/libraries/.
- Attach the Arduino to your PC with the USB cable.
- Open the IDE and start a new sketch. Sketch is Arduino speak for program. Select File -> New.
- Select the appropriate serial device (Tools -> Serial Port). This depends on your environment, for me it is /dev/tty.usbserial-A4001JAh.
- Download the attached source file and paste it into the new sketch. Hit the save button.
- Hit the verify button. This compiles your sketch into a hex file that can be transferred to your Arduino.
- Hit the upload button to transfer your sketch to the Arduino.
Testing
Now your hitcounter is ready for some action. Let’s see if it works.
- Hit the serial monitor button.
- Select the text box next to the send button.
- Hit the tab key and send it.
- By now the servo arm should move forward and back.
Phew. That was the hardest part. For now you can send a byte to the Arduino and the servo waves at you. Next is to find something that you want to trigger the bell.
We are almost done.
Step 5: Make It a Hitcounter
To.
#
# fetch counter
#
import time
import urllib
import serial
# usb serial connection to arduino
ser = serial.Serial(‘/dev/tty.usbserial-A4001JAh’, 9600)
myUrl = ‘’
last_counter = urllib.urlopen(myUrl).read()
while (True):
_ counter = urllib.urlopen(myUrl).read()
_ delta = int(counter) – int(last_counter)
_ print “counter: %s, delta: %s” % (counter, delta)
_ ser.write(chr(ord(chr(delta))))
_ last_counter = counter
_ time.sleep(10).
Step 6: Conclusion.
Source: Arduino XMAS Hitcounter | https://duino4projects.com/arduino-xmas-hitcounter/ | CC-MAIN-2020-45 | refinedweb | 630 | 77.13 |
55191/python-typeerror-object-type-class-str-cannot-passed-to-code
I am trying to run the following code:
from Cryptodome.Cipher import AES
key = '0123456789abcdef'
IV='0123456789abcdef'
mode = AES.MODE_CBC
encryptor = AES.new(key, mode,IV=IV)
text = 'hello'
ciphertext = encryptor.encrypt(text)
But I am getting the following error:
Traceback (most recent call last):
File "F:/Python Scripts/sample.py", line 8, in <module>
ciphertext = encryptor.encrypt(text)
File "F:\Python Scripts\Crosspost\venv\lib\site-packages\Cryptodome\Cipher\_mode_cbc.py", line 178, in encrypt
c_uint8_ptr(plaintext),
File "F:\Python Scripts\Crosspost\venv\lib\site-packages\Cryptodome\Util\_raw_api.py", line 145, in c_uint8_ptr
raise TypeError("Object type %s cannot be passed to C code" % type(data))
TypeError: Object type <class 'str'> cannot be passed to C code
Hey,
Did you miss to encode the IV!
You can try something like this:
key = b'0123456789abcdef'
IV= b'0123456789abcdef' #need to be encoded too
mode = AES.MODE_CBC
encryptor = AES.new(key, mode,IV=IV)
text = b'hello'
ciphertext = encryptor.encrypt(text)
I hope this will work.
You have to pass byte string as values so try encoding the data values to byte and then pass it. Try this:
from Cryptodome.Cipher import AES
key = '0123456789abcdef'
IV='0123456789abcdef'
mode = AES.MODE_CBC
encryptor = AES.new(key.encode('utf8'), mode,IV=IV.encode('utf8'))
text = 'hello'
ciphertext = encryptor.encrypt(text)
A TypeError can occur if the type ...READ MORE
Yes, There is an alternative. You can ...READ MORE
Hey @Ashish, change the emotion_map to the ...READ MORE
Hey @Dipti
This is the list on ...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
You can simply the built-in function in ...READ MORE
In fact, I get a perfectly good ...READ MORE
Refer to the below code:
class Try: ...READ MORE
OR
Already have an account? Sign in. | https://www.edureka.co/community/55191/python-typeerror-object-type-class-str-cannot-passed-to-code?show=55192 | CC-MAIN-2020-45 | refinedweb | 328 | 62.85 |
Today, we will see how to create a list of lists in Python. There are multiple ways to do that. Let’s get started and see some of the methods.
For Loop and the append() method
The first method is quite simple and straightforward. Initially, we create an empty list lst1, then we run a loop and append lists to lst1.
If we want to insert n sublists, then we will have to run a loop n times using the range() function. Let’s understand this concept using an example.
lst1 = [] for i in range(0, 5): lst1.append([]) print(lst1)
Output
[[], [], [], [], []]
Here, the loop runs five times. In each iteration, we append an empty list to lst1, which allows us to create a list of lists, as you can see in the output.
List Comprehension
Another method is to use list comprehension that provides us an easier and a concise way. Let’s see an example.
lst = [[] for i in range(0, 5)] print(lst)
Output
[[], [], [], [], []]
A list comprehension always returns a list whose contents depend upon the expressions in the for loop and if condition (if any).
In the above example, we add a sublist every time the loop runs, and thus, the result contains a list of lists.
NumPy Library
Another method to make a list of lists is to NumPy. It is a powerful library for scientific computations.
It provides several methods and tools to create and work with multidimensional arrays efficiently.
We can make a list of lists using the empty() method of the NumPy library. We need to pass a tuple containing the row size and the column size.
It also takes a data type. By default, it will create an array of type numpy.float64.
Moreover, it returns a ndarray (N-Dimensional array) of fixed size and type. To convert it to a list, we will use the tolist() method.
Consider the following code:
import numpy as np np_array = np.empty((5, 0)) lst = np_array.tolist() print(lst) print(f"Type of np_array: {type(np_array)} and the type of lst: {type(lst)}")
Output
[[], [], [], [], []] Type of np_array: <class 'numpy.ndarray'> and the type of lst: <class 'list'>
We can do the same using the numpy.ndarray() method. Let’s see.
import numpy as np np_array = np.ndarray((5, 0)) lst = np_array.tolist() print(lst)
[[], [], [], [], []]
The map() function
We can also create a list of lists using Python’s built-in map() function. map() takes two arguments: a function and an iterable.
It calls the given function for each item of an iterable and returns an iterator. Consider the following example.
n=5 lst = [None]*n lst = list(map(lambda x: [], lst)) print(lst)
Output
[[], [], [], [], []]
First, we create a list of n elements containing None. Then, we pass this list to map().
Each item of the outer list gets mapped to an empty list using the anonymous function. Finally, we convert the returned iterator (map object) to a list to get a list of lists.
What not to do
We can create a one-dimensional list in the following way.
lst = [None]*n
Here, lst will be of size n, and each item will have the value None. In other words, any value we put inside the square brackets get repeated n times.
So if we put [] inside it, then we will get a list of lists, no? Well, you do, but every item refers to the same object (the first one). Simply put, we get n same sublists. let’s see.
n=5 lst = [[]]*n print(lst) #append an item to the last list lst[n-1].append(3) print(lst)
Output
[[], [], [], [], []] [[3], [3], [3], [3], [3]]
Consider another code.
n=5 lst = [] new_list = [lst for i in range(0, n)] #append an item to the last list new_list[n-1].append(3) print(lst) print(new_list)
This above code also creates five references of the variable lst. So, new_list[0], new_list[1], … new_list[n-1] refer to the same address pointed by lst.
Output
[3] [[3], [3], [3], [3], [3]]
Use lst[:] instead of lst or copy the list explicitly using copy() from the copy module.! | https://maschituts.com/how-to-make-a-list-of-lists-in-python/ | CC-MAIN-2021-10 | refinedweb | 693 | 75.2 |
Leopard: Access Dock from the Keyboard
Posted April 5, 2008 by Rob Rogers in Mac OS X Leopard
You can easily access the Leopard Dock from the keyboard without any help from your mouse. This is handy for all keyboard commandos.
You can access your Dock, regardless of what application you are running. Non laptops use the following combination on your keyboard:
ctrl+F3
Macbook and macbook pro owners will need to invoke the fn key as well:
fn+ctrl+F3
Once the dock is selected, you can use the arrow keys to move to the desired application and and then press the return key to select. You can also type the first letter of the desired app and then hit return (this doesn’t work quite as well if you have multiple apps with the same first letter in the name).
Esc will leave the dock.
About Rob Rogers
View more articles by Rob Rogers
The Conversation
Follow the reactions below and share your own thoughts. | https://www.tech-recipes.com/rx/2842/leopard_access_dock_keyboard/ | CC-MAIN-2018-43 | refinedweb | 167 | 64.75 |
LES: Loyc Expression Syntax.
LES is a C-like language with
{braced blocks} and expressions that end in semicolons; its parser is much simpler than C itself. The output of the LES parser is a list of expressions, in the form of tree structures called Loyc trees. In comparison with the syntax trees inside most compilers, Loyc trees are designed to have an almost LISP-like simplicity.
Here is an example of LES code:
@[#static] fn factorial(x::int)::int { var result = 1; for (; x > 1; x--) { result *= x; }; return result; };
The above code uses a feature called “superexpressions” to make it more readable. The same code can be written without superexpressions as
@[#static] fn(factorial(x::int)::int, { var(result = 1); for((; x > 1; x--), { result *= x }); return(result); });
Or it can be written in “pure prefix notation”, which uses
@identifiers-with-at-signs instead of infix operators:
@[#static] fn(@'::(factorial(@'::(x,int)),int), @`'{}`( var(@'=(result, 1)), for(#tuple(@``, @'>(x, 1), @'--suf(x)), @`'{}`(@'*=(result, x))); return(result); ));
The last form most closely reflects the “real” structure of the code. After reading more about LES and Loyc trees, you will understand why these three forms are equivalent. If you put this code into LeMP.exe along with the following directive:
#importMacros(LeMP.Prelude.Les);
It will be transformed into the following C# code:
static int factorial(int x) { var result = 1; for (; x > 1; x--) result *= x; return result; }
The C# code, in turn, looks like this when printed as LES code:
@[#static] #fn(#int32, factorial, #(#int32 `#var` x), { #var(@``, result = 1); #for(@``, x > 1, x --, result *= x); #return(result); });
Note: A new LES is coming
This document describes LESv2. The design of LESv3 is nearing completion and will be the recommended version going forward. LESv2 looks good - it closely resembles Java/C and is a superset of JSON - but LESv3 is less error-prone to write, mainly because LESv3 uses newline as a terminator so it does not require semicolons after closing braces (or anything else for that matter).
However, because newlines are significant, LESv3 is not a superset of JSON. If you prefer to have a superset of JSON or if you prefer how LESv2 looks, feel free to keep using LESv2 and feel free to voice your opinion on the issue tracker. Both versions of LES are currently available in the .NET NuGet package Loyc.Syntax.dll.
LESv3 doesn’t have a spec yet, but the latest blog post is here and see issue #52. As always, help is wanted to write parsers (and printers) for languages other than C#.
LES for configuration files
As a superset of JSON, LES is useful for configuration files. LES is more compact and flexible than JSON and XML. Compare these representations of the same data:
<?xml version="1.0"?> <root> <owner name="John Smith"> <address city="Calgary" prov="Alberta" country="CA", <vehicle make="Ford" model="Pinto" year="1978" insurerId="1"/> <vehicle make="Toyota" model="Prius" year="2014" insurerId="1"/> </owner> <insurer name="Vehicle Insurance Kings" id="1"> <address city="Calgary" prov="Alberta" country="CA", <phone type="unknown">(403) 555-1234</phone> <phone type="tollfree">(800) 573-8941</phone> </insurer> </root>
{ "owners": [{ "name": "John Smith", "addresses": [ { "city": "Calgary", "prov": "Alberta", "country": "CA", "address": "123 Fake St" } ], "vehicles": [ ["Ford", "Pinto", 1978, {"insurerId": 1}] ["Toyota", "Prius", 2014, {"insurerId": 1}] ] }], "insurers": [ { "name": "Vehicle Insurance Kings", "id": "1", "addresses": [ { "city": "Calgary", "prov": "Alberta", "country": "CA", "address": "321 True Ave" } ], "phones": [ { "type": "unknown", "number": "(403) 555-1234" }, { "type": "tollfree", "number": "(800) 573-8941" } ], } ] }
// One of several possible choices of LES syntax owner "John Smith" { address(city="Calgary", prov="Alberta", country="CA", address="123 Fake St"); vehicle("Ford", "Pinto", 1978, insurerId=1); vehicle("Toyota", "Prius", 2014, insurerId=1); }; insurer "Vehicle Insurance Kings"[id=1] { address(city="Calgary", prov="Alberta", country="CA", address="321 True Ave"); phone("(403) 555-2341", type=unknown); phone("(800) 573-8941", type=tollfree); };
LES works even better for configuration files that contain data that is “code-like” (e.g. conditions, queries, and commands). XML and JSON often require separate parsers for code-like data; for example,
<if condition="$Folder.Length <= 255">...</if>
is not only ugly compared to the LES equivalent
if $Folder.Length <= 255 {...};
but you’d need a separate expression parser, too.
Design goals
- Concision: LES is not XML! It should not be weighed down by its own syntax.
- Familiarity: LES should resemble popular languages, especially C/C++/Java.
- Utility: although LES can represent syntax trees from any language, its syntax should be powerful enough to be the basis for a general-purpose language.
- Light on parenthesis: Less Shift-9ing and Shift-0ing for Less RSI.
- Simplicity: The parser should be as simple as possible while meeting the above goals. Despite its flexibility, the parser recognizes only a fixed syntax, and does not build or use symbol tables.
Grammars
A formal grammar of LES has not yet been published. The actual grammar used for parsing is written in LES and then converted to C# by LeMP. The grammar of LESv3 is a bit more readable. Meanwhile, this document defines LESv2 in an informal manner.
Comments in LES work like C#, C++, Java, and many other languages:
/* This is a multi-line comment. It continues until there's a star and a slash. */ /* A multi-line comment doesn't need multiple lines, of course. */ profit = revenue - /* a comment inside an expression */ expenses; // This is a single-line comment. It has no semantic meaning. // It ends automatically at the end of a line, so you need // more slashes to continue commenting on the next line. /* Multi-line comments can be /* nested */ as you see here. */
Comments can be embeded in Loyc trees. TODO: enhance the LES parser to attach comments to nodes.
Statements & expressions
An LES document is a sequence of “statements” separated, or terminated, by semicolons. In LES, unlike many other languages, there is no distinction between “statements” and “expressions”. However, there is a distinction between “top-level expressions” and “subexpressions”. Also, in some contexts, expressions are separated by semicolons, while in others they are separated by commas. The rules are fairly predictable for C programmers.
By convention, we may say that an expression is a “statement” if it appears at the top level or within a
{braced block}, where it must end with a semicolon. It’s a stylistic issue only; it’s like in English you can say either
Bob made a sandwich; Alice ate it.
or
Bob made a sandwich, and alice ate it.
First, let’s discuss “normal” (sub)expressions. After that we’ll discuss top-level statements, which allow some additional syntax.
Subexpressions
LES supports the following kinds of subexpressions:
- Identifiers. Normal identifiers are similar to other languages, e.g.
foo,
foo2,
_x. LES is a keyword-free language, so words like
ifand
whilethat are keywords in most languages are just normal identifiers in LES. Identifiers can contain apostrophes, except as the first character, so
Toys'R'Usand
Foo'are also valid identifiers. The characters
#and
_are not considered punctuation in LES; they is treated like letters. Thus
__STDC__and
#ifndefare “normal” identifiers in LES.
- Special identifiers. In LES, an identifier can contain any and all Unicode characters. To include special characters in an identifier, use the prefix
@. After
@you can write an identifier composed of digits, letters, and operator characters (
'0'..'9'|'a'..'z'|'A'..'Z'|'_'|'#'|'\''|'~'|'!'|'%'|'^'|'&'|'*'|'-'|'+'|'='|'|'|'<'|'>'|'/'|'?'|':'|'.'|'$'). For example,
@you+me=win!is a single token representing the identifier
you+me=win!. To include really special characters, add backquotes around the identifier text (in addition to
@). Thus
@`{}`represents the identifier named
{}which is the built-in “function” that represents a braced block. Similarly
@>and
@.represent the identifiers “
>” and “
.”. The empty identifier
@``is also permitted, and the backquoted string can include C-style escape sequences such as
@`\n`(newline character #10). If a “normal” identifier is prefixed by
@, the parser is allowed to interpret it as a literal; currently,
@false,
@trueand
@nullare defined as literal values, not identifiers.
- Literals: LES supports literals of primitive types (64 bits or less), including booleans, integers, floating point, booleans and strings (see ‘Literals’).
- Calls: as in C, syntax like
F(A, B)represents a “call”. Calls are a fundamental construct, and they may or may not represent function calls; for example,
#var(int, x)is a call that conventionally represents a declaration of a variable named
x. An operator expression like
A + Bis always parsed into a call like
@+(A, B). LES allows missing arguments, which are represented by the empty identifier
@``, e.g.
F(X, , Z)is short for
F(X, @``, Z)and
F(,)is short for
F(@``, @``). The arguments to a call are separated by
,by convention, but
;is also permitted as a separator.
- Infix operators: LES supports an infinite number of infix operators. The precedence table closely resembles C and JavaScript, so for example
a.b = c + d.e * 5 == f && gis parsed as
(a.b) = (((c + ((d.e) * 5)) == f) && g). Operators consist of a sequence of any of the punctuation characters
'~'|'!'|'%'|'^'|'&'|'*'|'-'|'+'|'='|'|'|'<'|'>'|'/'|'?'|':'|'.'|'$'. There is a set of “built in” operators (which have an entry in the precedence table) and the precedence of additional operators is derived from that table using a short list of rules (e.g.
&|^is defined as having the same precedence as
^.) Finally, infix operators can be derived from non-punctuation characters by writing a backquoted string, e.g.
x `Foo` yis equivalent to
Foo(x, y). The infix operators
>>,
<<,
&,
|and
^are not allowed to be mixed with certain other operators, because their precedence is a potential source of bugs. For example,
x & 7 == 0is considered a syntax error, although the parser will still produce a tree from it (
@&(x, @==(7, 0))). Backquoted operators have a similar restriction (for full details, see “Precedence”).
- Prefix operators: Most infix operators can also be used as prefix operators; the precedence of a prefix operator is not related to the infix operator of the same name (e.g.
x * -y - -zis parsed as
(x * (-y)) - (-z)).
- Suffix operators: LES supports the C prefix/suffix operators
++and
--and any other operators surrounded by
+or
-, e.g.
+++and
-<>-can act as prefix or suffix operators.
- Parenthesized expressions and tuples. You can, of course, use parentheses
(...)for grouping, to override the natural precedence of operators. Tuples are supported too, but each item in a tuple must be separated by semicolons rather than commas as in most languages (there are two reasons for this, explained below under ‘Subtleties’). Tuples represent calls to the identifier
#tuple. Empty parentheses
()are a synonym for
#tuple(),
(foo;)parses as
#tuple(foo)and both
(A; B)and
(A; B;)produce the same syntax tree as
#tuple(A, B).
- Lists: LES supports JSON-style
[lists, in, square, brackets]as a call to
@`[]`. As with argument lists, semicolons are permitted as a terminator, but one must be consistent about whether comma or semicolon is used as a separator.
- Bracket lookup: Typically used for array indexing or map lookup. A bracket expression
L[A, B]is parsed into a call to
@`_[]`, specifically
@`_[]`(L, A, B).
- Generics: The most popular notation for generics,
Foo<T>, is highly ambiguous, so LES uses generic notation invented for D, which involves exclamation marks:
List!Tor
List!(T)are both parsed into
#of(List, T). When parentheses are used, the binary
!operator works differently than most other operators. It is actually an N-ary operator: it puts the left-hand side in a list of length 1, then parses the contents of
(...)as if it were an argument list, appending the arguments to the list. For example,
Foo!(a,b,c)is parsed into
#of(Foo, a, b, c). Please note that
Foo!X.Yis parsed like
(Foo!X).Y.
- Braced blocks: A list of statements in braces is parsed into a call to
@`{}`. The grammar inside a braced block
{...}is identical to that of a list expression
[...]: a list of expressions separated by commas or terminated by semicolons.It makes no difference whether the final expression is followed by a semicolon (
{X}and
{X;}both mean
@`{}`(X)). Empty statements are permitted; they are parsed into
@``(e.g.
{;;}is equivalent to
{ @``; @``; }.
Here is a typical LES subexpression, showing that braced blocks can be embedded in expressions:
function(first_argument, second_argument, third_argument + { substatement(); another_one(x, y, z) } )
You may occasionally see the term “Prefix notation”. Prefix notation is a subset of the expression grammar that includes only identifiers (including special ones), literals, calls, and attributes (introduced below). Any Loyc tree can be expressed in prefix notation; for example,
p = A!B[X,Y] can be expressed in prefix notation as
@=(p, @`_[]`(#of(A, B), X, Y))
and
System.Console.WriteLine("Hello") can be expressed as
@.(@.(System, Console), WriteLine)("Hello")
which means
(@.(@.(System, Console), WriteLine))("Hello").
Top-level expressions
An LES file consists of a list of statements (i.e. top-level expressions) that are separated or terminated by semicolons (
;), as if the file were enclosed in curly braces. It would be possible to allow either
; or
, as a separator, but requiring semicolons allows the parser to catch certain mistakes earlier, without relying on indentation or newlines to choose error messages. For example, without this rule, the error on line 1 would not be detected until the end:
foo(2 * (x = y + z), 0 // line 1 if happy { Smile(); } else { Frown(); };
Every list of expressions in LES is a list of “top-level” expressions (whether it’s an argument list, a tuple, a braced block or the file as a whole). A top-level expression is special: it can have attributes attached to it, and can use the “superexpression” notation.
Attributes
avgSpeed = (@[miles] 0.25) / (@[seconds] 2.68);
Every node in a Loyc tree conceptually has an attribute list, which is a “side channel” for storing additional information. Every top-level expression can begin with a single list of attributes enclosed in
[square brackets]; the contents of the square brackets are parsed the same way as an argument list. For example, in
@[Foo(), X + 1] ++X;
Two attributes,
Foo() and
X + 1, are attached to the prefix expression
++X.
After the optional square brackets there is (an LL(2) decision between)
- A normal subexpression (see the previous section), or
- A superexpression (see the next section)
Superexpressions
In LLLPG notation, we might write the grammar of a superexpression as:
rule SuperExpr @{ TT.ID Expr AfterParticle* };
In other words, it starts with an identifier, followed an expression, followed by zero or more “AfterParticles”, where an
AfterParticle is an identifier, or something in braces, or something in parentheses that is preceded by a space, or a literal.
For example, this LES code contains six superexpressions:
function length(s) { if s == null { return 0; } else { var len; for (len = 0; s[len] != '\0'; len++) {}; return len; }; };
Now that you know what a superexpression looks like, let’s talk about what it means. Quite simply, superexpressions are translated into ordinary calls:
function(length(s), { if(s == null, { return(0); }, else, { var(len); for((len = 0; s[len] != '\0'; len++), {}); return(len); }); }; };
Remember that a superexpression is always a part of a list of expressions, so a superexpression is always terminated by
";",
",", EOF, or one of the closers “)”, “]” or “}”. The last part of a superexpression does not allow “full” expressions, in order to maximize the chances of getting a syntax error if you forget a semicolon after
"}".
This is the key tradeoff of LES. C allows you to write
while (false) {} if (c) {} else {} x++;
with no semicolon after any of the closing braces, but LES requires an explicit signal that each statement is terminating. The above code will only give a parse error when it reaches
++, since operators are not allowed after the first braced block. The correct LES code is
while (false) {}; if (c) {} else {}; x++;
Since LES is a language with no keywords, it’s important to understand how the parser can distinguish superexpressions from subexpressions. Often it’s obvious:
return 0 is not a valid subexpression, so it must be a superexpression.
But there is an important ambiguity. How can LES distinguish a normal expression like
WriteLine("Hello, world!");
from a superexpression like
WriteLine ("Hello, world!"); //?
The answer is very simple: if
'(' is preceded by a space or tab (
' '|'\t'), it is not allowed to represent a function call. For example, both of these statements are syntax errors (the parser will tell you what you did wrong):
// Syntax error. If a function call was intended, remove the space(s) before '('. Console.WriteLine ("Hello, world!"); // Tuples require ';' as a separator. If a function call was intended, remove // the space(s) before '('. Foo (X, Y);
This is based on the observation that in C/C++/C#/Java, most programmers write code like
Console.WriteLine(...); var re = new Regex(...); F(x);
with no space between the identifier and the method being called, but many (albeit fewer) programmers write
if (...) {...} else {...} for (...) {...} lock (...) {...} while (...) {...} switch (...) {...}
with a space between the keyword and the opening paren. So in a language that has no keywords, it seems reasonable, although not ideal, to use a spacing rule to identify whether the first word of an expression is to be treated as a “keyword” or not. Since the compiler will, in most cases, print an error when the spacing rule is not followed, anyone programming in LES will get into the habit of writing the space, or not writing a space, under the correct circumstances.
Note that both of these statements are legal and have virtually the same meaning:
Foo(x); // Subexpression Foo (x); // Superexpression
The only difference is that, in the second case,
x is considered to be inside parentheses (i.e.
Foo (x) is equivalent to
Foo((x)), see ‘Subtleties’).
Forgotten semicolons
LES was actually redesigned to reduce the space of valid superexpressions, so that in most cases, the parser would give a syntax error if there is a missing semicolon after closing braces. For example, a statement like
minOrMax = if (max) Max() else Min(); used to be legal, and no longer is, which allows mistakes like the following to be detected without analyzing newlines or indentation:
while (x < 100) { x *= 2; } Foo(x); // Syntax error do x++ while (Foo(x)) x++; // Syntax error if (c) { c.F(); } var x = 0; // Syntax error if (c) { c.F(); } if x > 0 { return 0 }; // Syntax error
Even so, sometimes when two superexpressions are placed side-by-side, the parser doesn’t see a problem:
while (x < 100) { x *= 2; } return x; // No parse error
There are two main ways to mitigate this lack-of-an-error:
1. Front-end processing: when you write LES code you have some kind of reason to do so - usually you’re going to feed the code into a compiler or other tool (e.g. LeMP) after you’ve written it. Also, superexpressions are designed for a very specific purpose: to simulate constructs like
while loops and
function definitions.
That means that whatever software receives the Loyc tree produced by the LES parser knows it is expecting to see a
while loop with two arguments, an
if statement with 2 or 4 arguments (
if(expr, {...}) or
if(expr, {...}, else, {...})), and so forth.
The symptom of a missing semicolon is a call that receives too many arguments. Therefore, the software that receives a superexpression with too many arguments can assume, if the earlier arguments look reasonable, that a missing comma or semicolon is to blame, and report something like “expected end of statement” at the first unexpected argument:
while (c) { c = F(); } return 0; // ^^^^^^ while loop: expected end-of-statement (did you forget a ';'?)
2. Syntax highlighting: coloring can visually distinguish superexpressions from normal expressions and function calls (supported in Visual Studio):
In this example there are three missing semicolons, but only one of them is a syntax error (you’ll get an error after the
strlen function). The other two—after the
for loop and after the
while loop—are not errors, but they cause the
return “keyword” to be shown in a different color (in this case, black rather than blue).
Precedence rules
TODO: update this section
The operator precedence rules are documented at LesPrecedence.cs.
In short, the name of the operator determines its precedence, starting from the following basis rules:
- Substitute: prefix $ . :
- Primary: binary
. =:, generic arguments
List!(int), suffix
++
--, method calls
f(x), indexers
a[i]
- NullDot: binary
?. ::
- DoubleBang: binary right-associative
!!
- Prefix:
prefix ~ ! % ^ & * - + `backtick`
- Power: binary
**
- Suffix2: suffix
\\
- Multiply: binary
* / % \ >> <<
- Add: binary
+ -
- Arrow: binary right-associative
-> <-
- AndBits: binary
&
- OrBits: binary
| ^
- OrIfNull: binary
??
- PrefixDots: prefix
..
- Range: binary right-associative
..
- Compare: binary
!= == >= > < <=
- And: binary
&&
- Or: binary
|| ^^
- IfElse: binary right-associative
? :
- Assign: binary right-associative
=
- PrefixOr:
|
See the full documentation for the rules about binary
=> ~ <>,
`backtick`, and prefix
/ \ < > ? =.
Literals
LES supports the following kinds of literals:
- 32-bit integers, e.g.
-26. Note that the parser treats ‘-‘ as part of the literal itself (if it makes sense to do so), rather than as an operator, unless you add a space between ‘-‘ and the number. LES supports hex notation (-0x1A) and binary notation (-0b11010). Also, you can put underscores in the number, e.g.
1_000_000.
- 32-bit unsigned integers, e.g.
1234uor
0xFFFF_FFFFU
- 64-bit integers, e.g.
1234L
- 64-bit unsigned integers, e.g.
1234uL
- Double-precision floats, e.g.
18.0or
18d
- Single-precision floats, e.g.
18.0for
18f. Hex literals are also supported, e.g.
0xABp12or
0x0.Cp0
- Booleans:
@trueand
@false
- Void:
@void(refers to
@void.Valuein Loyc.Essentials.dll)
- null, denoted
@null, which (in the context of .NET) has no data type.
- Characters, e.g.
'a'or
'\n'. Characters are Unicode, but under .NET, characters are limited to 16 bits. Hopefully proper 21-bit Unicode characters can be supported somehow, someday.
- Strings, e.g.
"é"or
"ĉheap". LES does not support C#
@"verbatim"strings; instead, it supports triple-quoted strings using either
'''three single quotes'''or
"""three double quotes""".
- Symbols, e.g.
@@fooor
@@`BAM!`(see below)
- Token literals (optional): a token literal is an
@{ at sign, followed by a tree of tokens in braces }. This optional feature is used to store domain-specific languages such as LLLPG inside LES files. LES parsers are not required to support token literals.
There is no literal notation for lists or tuples (note that a tuple such as
(1; "two") is not a “literal”; it is a Loyc tree that some programming languages may or may not interpret as a tuple.) More literal types will probably be added in the future (such as unlimited-size integers, 8-bit and 16-bit ints, byte array literals).
A few languages, including Ruby and LISP, have a symbol data type; symbols are singleton strings, and they are implemented by the
Symbol class in Loyc.Essentials. Symbols have a performance advantage over strings in many cases. The advantage of symbols is that you never have to compare the contents of two Symbols. Since each
Symbol is unique, two
Symbol references are equal if and only if they point to the same heap object. Loyc.Essentials allows derived classes of
Symbol and “private” symbol pools, but LES supports only global symbols. Symbols are a useful alternative to enums.
All three of the syntaxes for strings produce the same data type (System.String), and the two kinds of triple-quoted strings are otherwise identical. Double-quoted strings like
"this one" must be entirely written on a single line, while triple-quoted strings can span an unlimited number of lines.
Double-quoted strings support escape sequences; the syntax is the same as for C and C#:
\nfor newline (linefeed, character 10)
\rfor carriage return (character 13)
\0for null (character 0)
\afor alarm bell (character 7)
\bfor backspace (character 8)
\tfor tab (character 9)
\vfor vertical tab (character 11), whatever that is.
\"for a double quote (character 34)
\'for a single quote (character 39)
\\for a backslash (character 92)
\xCCfor an 8-bit character code (where CC is two hex digits)
\uCCCCfor a 16-bit character code (where CCCC is four hex digits) In modern times, \a, \b and \v are almost never used.
\'is only needed in a single-quoted string to represent the single quote mark itself (
'\''). Any escape sequences that are not on the list (i.e. backslash followed by anything else) are illegal.
I hate the idea of source code changing its meaning when a text editor switches between UNIX (\n), Windows (\r\n), and Macintosh (\r) line endings. Therefore, when a triple-quoted string spans multiple lines, each newline will always be treated as a
\n character, regardless of the actual byte(s) that represent the newline in the source file.
In addition, after a newline, indentation is ignored insofar as it matches the indentation of the first line (the line with the opening triple-quote). For example, in
namespace Frobulator { def PrintHelp() { Console.WriteLine(""" Usage: Frobulate <filename> <options>... Options: --blobify: Blobifies the frobulator. --help: Show this text again."""); }; };
The words “Usage” and “Options” are indented by two spaces. This is compatible with dot-space notation, so the following version is exactly equivalent:
namespace Frobulator { . def PrintHelp() { . . Console.WriteLine(""" . . Usage: Frobulate <filename> <options>... . . Options: . . --blobify: Blobifies the frobulator. . . --help: Show this text again."""); . }; };
I decided that I wanted all the string types to support any string whatsoever. In particular, I wanted it to be possible to store
"'''\r\"\"\"" as a triple-quoted string. Therefore, I decided to support escape sequences inside triple-quoted strings, but the sequences have a different format (with an additional forward slash). The following escape sequences are supported:
\n/for a newline (character 10)
\r/for a newline (character 13)
\\/for a single backslash (character 92)
\"/for a double quote (character 34)
\'/for a single quote (character 39)
\0/for a null character (character 0)
\t/for a tab character (character 9)
Then, to write an escape sequence literally, you must escape the initial backslash, e.g.
'''\\/r/''' represents the three characters
\r/, and
'''\\/\/''' represents
\\/. If the backslash and forward slash are not recognized as part of an escape sequence, they are left alone (e.g.
'''\Q/''' is the same string as
'''\\/Q/''').
Triple-quoted strings do not support unicode escape sequences. Please use the character itself, and note that the recommended encoding for LES files is UTF-8, with or without a “BOM”.
Subtleties
Parentheses & Style
If an expression uses parentheses for grouping, this fact is encoded in the tree by attaching a
#trivia_inParens attribute, unless there is a
'[' token after the opening
(. Thus, for example, the parser produces the same result for
2 * (x+1) and
2 * ([#trivia_inParens] x + 1). Similarly, the parser produces the same result for
2 * x + 1 and
([] 2 * x) + 1.
The C# Loyc tree implementation reserves 8 “style” bits, intended for tracking other style distinctions such as the difference between
11 and
0xB, and the difference between
2 + 2 and
@+(2, 2). These bits are the only mutable state in an LNode.
Style bits also indicate whether commas or semicolons are used as a separator/terminator in argument lists, braced blocks and lists in square brackets. The current implementation sets
BaseStyle = NodeStyle.Statement if and only if semicolons are used.
Comma vs semicolon
There is a slight semantic difference between
, and
;; a comma is always treated as a separator, while a semicolon is a separator or terminator. That is,
{ A; B } and
{ A; B; } both count as two statements. In contrast, while
F(A, B) counts as two arguments,
F(A, B,) counts as three (the third one is missing, and
@`` is inserted as a placeholder in the syntax tree). And while ‘,’ is almost always used to separate arguments (parameters) in an argument list,
; is also allowed, in case the programmer has a stylistic reason to want to use it;
F(A; B;) counts as two arguments, not three. Semicolons and commas cannot be mixed in the same context;
F(A; B, C) is an error.
Why semicolons in tuples?
There are two reasons why elements of a tuple must be separated by semicolons instead of commas:
- The main reason is to make
Foo (X, Y)into a syntax error, which prevents a programmer from accidentally treating
Fooas a one-argument function.
- Note that
Foo(x,)is considered to be a function of two arguments, but
Foo(x;)is considered to be a function of one argument, because comma is a separator while semicolon is a terminator. We need a way to represent tuples of one argument. We could require one-arg tuples to be explicit (
#tuple(x)), but some languages (e.g. Python) offer the syntax
(x,)for this purpose. However, according the logic above,
(x,)should be a tuple of two items in LES, while
(x;)is more logically understood as a tuple of size one.
Grammar classification
The grammar of superexpressions overlaps that of subexpressions, because many infix operators can also be prefix operators; in case of ambiguity, normal expressions win. For example,
X * Y could be parsed as a superexpression meaning
X(*Y), but this does not happen, because normal expressions take priority.
The subexpression grammar of LES is LL(1), if superexpressions are omitted, except that additional error checks are required. LES with superexpressions is “augmented” LL(2). The grammar must be augmented with additional logic because a plain BNF grammar is ambiguous:
- Subexpressions require prioritization over superexpressions to disambiguate the two.
- In an LL(k) parser, specialized code is needed to distinguish “plain” parens
(X+Y)from tuples like
(X+Y;)without resorting to unlimited lookahead.
- Error checking code is required to detect illegal mixing of
,and
;, as in
F(X + 1; Y + 1, Z + 1)
- Traditional LL(1) parsers require a separate rule and terminal (token type) for each precedence level. The LES parser could work this way in theory, with a multitude of different rules and token types, but since there are more than 20 precedence levels, the traditional approach is quite unwieldy. It is much simpler to use the “semantic predicate” feature of a parser generator to collapse all precedence levels into a single rule, and collapse all operators of a particular category (infix, prefix/infix, prefix/suffix) into a single token type.
The spacing rule
Consider a superexpression like
Foo (x);
The original definition of LES decided whether this was a superexpression or not by comparing the character index of the end of the expression
Foo with the character index of
(. The new version of LES uses a slightly simpler rule: checking whether
( is preceded by a space or tab. This can be accomplished with a lexer rule that uses one token type for
"(" and a different one for
" (". The new rule gives a different interpretation in unusual cases like
Foo/* !!! */(x); // This is now considered a function call, not a superexpression
Currently a newline
'\n' does not count as a space; it’s not clear whether this matters.
Just so we’re clear, LES has two spacing rules, usually represented by defining separate tokens for
"(" and
" (":
- A call cannot use
" ("- remove the space before the left parenthesis.
- The particles in a superexpression cannot use
"("- add a space before the left parenthesis.
There are no special spacing rules that involve
'[' or
'{'.
Prefix & suffix precedence
TODO: explain how
x * | y + z parses as
x * (| (y + z)), examine suffix operator behavior.
JSON compatibility
LESv2 was made JSON-compatible via four changes to LES:
- Allow
','as a separator inside
{braces}
- Introduce
[JSON, style, lists]
- Use
@[...]instead of
[...]for attributes (token literals were changed from
@[...]to
@{...}; note that using
@(...)for attributes would not have clashed with token literals, but I felt it would be better to use
@[...]because
[]does not require the shift key, and token literals are a more obscure feature.)
- Do not give an error message for big integers (larger than can fit in 64 bits) (incomplete)
Although LES supports JSON syntactically, the structure of the tree produced by the LES parser is different from that produced by a JSON parser. In particular, LES has no concept of “dictionaries” or “objects”, so a “dictionary” like
{"a":"A", "b":"B"} really means
@`{}`(@:("a","A"), @:("b","B")), i.e. each pair is represented by a call to the binary colon operator.
Using LES in .NET
To use LES in .NET, simply call
LesLanguageService.Value (in Loyc.Syntax.dll) to get an
IParsingService object that supports parsing LES text and printing Loyc trees as LES text. Call
Print(node) to print and
Parse(text) to parse:
IListSource<LNode> code = LesLanguageService.Value.Parse("Jump(); Ship();"); LNode firstStmt = code[0]; string code2 = LesLanguageService.Value.PrintMultiple(code); // "Jump(); Ship();" string first = LesLanguageService.Value.Print(firstStmt); // "Jump();"
You can also call
Tokenize("text") to use the lexer by itself (it implements
ILexer<Token> and
IEnumerator<Token>; just call
NextToken() which returns
Maybe<Token>).
The parser returns a list of Loyc trees (
IListSource
<LNode>). See “Using Loyc trees in .NET”. | http://loyc.net/les/ | CC-MAIN-2019-26 | refinedweb | 5,478 | 54.63 |
Project Server 2010 Class Library and Web Service Reference
Last modified: January 06, 2011
Applies to: Office 2010 | Project 2010 | Project Server 2010 | SharePoint Server 2010
The class library and Web service reference for Microsoft Project Server 2010 includes the public namespaces that are usable by third-party developers.
Web service namespaces have arbitrary names. For example, when you develop with the Project Server Interface (PSI) and create a reference to the Admin.asmx Web service—or the Admin.svc service, you choose a namespace name for programmatic use such as [Admin Web service]. Except for code samples, Web service namespaces in the Project 2010 SDK are indicated in brackets, for example [Admin Web service]. For a more detailed description of documented assemblies, namespaces, and Web services of the PSI, see PSI Reference Overview.
The primary class in each Web service includes the Web methods that provide the functionality of that Web service. Many of the Web methods use or return DataSet objects that are defined by DataSet, DataTable, and DataRow classes in the same Web service. | http://msdn.microsoft.com/en-us/library/ee767707(d=printer,v=office.14).aspx | CC-MAIN-2014-52 | refinedweb | 177 | 51.99 |
/ && make install cleanTo add the package: pkg install postfix
cd /usr/ports/mail/postfix/ && make install clean
pkg install postfix
PKGNAME: postfix
distinfo:
TIMESTAMP = 1511368835
SHA256 (postfix/postfix-3.2.4.tar.gz) = ec55ebaa2aa464792af8d5ee103eb68b27a42dc2b36a02fee42dafbf9740c7f6
SIZE (postfix/postfix-3.2.4.tar.gz) = 4390376
NOTE: FreshPorts displays only information on required and default dependencies. Optional dependencies are not covered.
This port is required by:
===> The following configuration options are available for postfix-3: 299 (showing only 100 on this page)
1 | 2 | 3 »
Update to 3.2.4
Changelog:
*.
* Missing dynamicmaps support in the Postfix sendmail command. This
broke authorized_submit_users settings that use a dynamically-loaded
map type. Problem reported by Ulrich Zehl. [?] 1.0.2. This changes the default
smtpd_tls_eecdh_grade setting to "auto", and introduces a new parameter
tls_eecdh_auto_curves with the names of curves that may be negotiated.
* Stored-procedure support for MySQL databases. Contributed by John Fawcett.
See the mysql_table(5) manpage for details.
* Cidr: table support for if/endif and negation (by prepending ! to a pattern),
just like regexp: and pcre: tables. See the cidr_table(5) manpage for details.
* The postmap command and the inline: and texthash: maps now support spaces in
left-hand field of lookup table source text. Use double quotes (") around a
- PR)
MFH: 2016Q3
- update to 3.1.2]
-.
2) $DATADIR/mailer.conf.postfix can be used by the tools in 1)
MFH: 2016Q 2.11.7
- use target helpers
ChangeLog: 2.11.5
-
Changelog:
20150324
Bugfix (introduced: Postfix 2.6): sender_dependent_relayhost_maps
ignored the relayhost setting in the case of a DUNNO lookup
- grap mail/postfix ports
(I have some rewrites for them)
- Reassign to the heap after sahil@'s bit was taken in for safekeeping
- update to 2.11.4
Changes:
20141025
Bugfix (introduced: Postfix 2.11): core dump when
smtp_policy_maps specifies an invalid TLS level. Viktor
Dukhovni. File: smtp/smtp_tls_policy.c.
20150106
Robustness: don't segfault due to excessive recursion after
a faulty configuration runs into the virtual_alias_recursion_limit.
File: global/tok822_tree.c.
20150115
Safety: stop aliasing loops that exponentially increase the
address length with each iteration. Back-ported from Postfix
3.0. File: cleanup/cleanup_map1n.c.
20150117
Cleanup: missing " in \%s\" in postconf(1) fatal error
messages. Iain Hibbert. File: postconf/postconf_master.c.
Approved by: sahil (implicit)
MFH: 2015Q1
- remove dead mirrors from MASTER_SITES
(a good overview can be taken by viewving the
source of)
- remove MASTER_SITE_SUBDIR, it should be used only for sites defined in
bsd.site.mk
- update conflicts for new postfix-current
- use OPTIONS_SUB
- enable TLS as default [1]
- use USE_OPENSSL instead including Mk/openssl.mk
- use new install instruction
- use new notation for @mode in pkg-plist
- bump PORTREVISON
[1] Users using packages should have the ability to
use TLS from the default package, (this makes the
the postfix-tls port obsolete)
Approved by: sahil (implicit)
MFH: 2015Q1
- install posttls-finger and posttls-finger.man
posttls-finger is handy for many tls related checks
PR: 195293
Submitted by: Darren Pilgrim
Approved by: sahil (implicit)
Finally retire USE_PGSQL
- fix wrong /var/spool/postfix permissions
(broken by commit 372368 ,372370)
- bump PORTREVISION
-
Approved by: sahil (implicit)
- update to 2.11.3
- add CPE support
- use PORTDOCS macro
- remove check for OSVERSION >= 800037
- fix OPENLDAP_VER usage
- set PORTSCOUD
- always call set-permissions in post-install to set correct spool/postfix/*
permissions
this is required with pkg to support non interrupted upgrade
Changes:
========
20140619
Bugfix (introduced: 2001): qmqpd null pointer bug when it
logs a lost connection while not in a mail transaction.
Reported by Michal Adamek. File: qmqpd/qmqpd)
- Update to 2.11.1
- Refactor to support staging [1]
- Support "developer mode" [2]
Submitted by: [1]: ohauer
[2]: mandree
.10.2
Add NO_STAGE all over the place in preparation for the staging support (cat:
mail)
- convert to the new perl5 framework
- convert USE_GMAKE to Uses
Approved by: portmgr (bapt@, blanket)
- Update to 2.10.1>
- adopt optionsNG
- trim historical header
- tighten COMMENT
Approved by: portmgr (bapt)
Update to 2.9.5 and revise the PKGINSTALL script to
distinguish between upgrades and fresh installs. Also,
mark BROKEN when users try to build WITH_LDAP_SASL but
WITHOUT_SASL2..9.4
- extend CONFLICTS
Approved by: sahil (maintainer)
- Update to 2.9.3
- Update to 2.9.2
Update VDA patch and tweak the conditional that
sets IS_INTERACTIVE.
- Update to 2.9.1
- Remove library number from pcre LIB_DEPENDS, as this
port can compile without incident against older pcre
libraries.
Bump pcre library dependency due to 8.30 update
Update to 2.9.0 and revise IS_INTERACTIVE logic to
account for additional situations..8.7
Feature safe: yes
- Restore all patches
- Fix build on FreeBSD 10
- Update to 2.8.5 and point to newer VDA patch
Update to 2.8.4 and use the ports framework to
create USERS and GROUPS. Also remove replace()
function from pkg-install script.
PR: ports/158765
Submitted by: ohauer
Update to 2.8.3 and point to newer VDA patch. Also address
the problem described in ports/155885 by passing additional
parameters to the upstream install script.
Security: CVE-2011-1720
- Update to 2.8.2
- Update to 2.8.1
Reactive VDA support with a new upstream patch released
specifically for Postfix version 2.8.0.
- Unbreak SPF option with new patch for 2.8.0
PR: ports/154465
Submitted by: mm
Feature safe: yes
Set IS_INTERACTIVE if BATCH and PACKAGE_BUILDING are
undefined[1]; also, add missing 'ver' in description
of the PGSQL option[2].
Prompted by: dougb[1], wxs[2]
Feature safe: yes
Update to 2.8.0, tweak CONFLICTS, mark MAKE_JOBS_SAFE
and note that the SPF and VDA options are unavailable
with this release.
Feature safe: yes
Add OPTION for SASL authentication via Dovecot 2.x and
warn users if they erroneously elect both 1.x and 2.x.
No bump of PORTREVISION because the default package is
unchanged.
Update to 2.7.2 and modify pkg-install script to check
whether Postfix is already enabled in mailer.conf[1].
Submitted by: ohauer (via email) [1]
- Remove dead MASTER_SITE
Reported by: distilator
- Update optional SPF patch to version 1.1.0 [1]
- Fix CONFLICTS [2]
PR: ports/151134 [1]
Submitted by: mm@ [1]
Noticed by: pav@ [2]
- Fix IPv6 support in SPF patch
PR: ports/150749
Submitted by: mm@
- Update VDA patch to version 2.7.0 [1]
- Remove "empty variable" assignment from rc script [1]
- Re-introduce optional SPF support [2]
- Remove default DISTNAME assignment from Makefile
- The affected OPTIONS are off by default, so do not
bump PORTREVISION
PR: [1]: ports/147731
[2]: ports/150428
Submitted by: [1]: ohauer@
[2]: mm@
- Update to 2.7.1
- Unset INVALID_BDB_VER; Berkeley DB 5.x is now supported
Approved by: wxs@/itectu@ (mentors, implicit)
- Set INVALID_BDB_VER; upstream does not yet support Berkeley DB 5 [1]
- Remove OPTION for Kerberos IV
- Change my email to @FreeBSD.org
PR: ports/146371 [1]
Reported by: Volodymyr Kostyrko <c.kworr@gmail.com> [1]
Approved by: itetcu@ (mentor)
Servers and bandwidth provided byNew York Internet, SuperNews, and RootBSD
14 vulnerabilities affecting 77 ports have been reported in the past 14 days
* - modified, not new
All vulnerabilities
Last updated:2017-12-10 18:59:21 | https://www.freshports.org/mail/postfix/ | CC-MAIN-2017-51 | refinedweb | 1,191 | 57.16 |
I am attempting to create a TLE from a set of GPS data. I have code with which I generate an Ephemeris using the base from which I edited but my output is roughly the same. I also have a program that accepts data in Earth Centered Earth Fixed (GTOD) and converts is to the Earth Centered Inertia (GCRF) used in the program. It is clear that creating the Ephemeris is simple. However, I am new to Orekit and am unfamiliar with how to create a fit TLE from this data. Note: The base code is in Orekit version 10.2 and mine is updated to 11.2.
Hi @separnell
Welcome to the Orekit forum!
In Orekit, you have two possibilities to generate a TLE:
- Generate the exact TLE of a single orbit. It can be done calling the method
TLE.stateToTLE(SpacecraftState, TLE)
- Generate a TLE that represents and fits an interval of data.
For the second point, which is I think what you want to do, you try something like below. If
your have access to the
List<SpacecraftState> used to initialize the
Ephemeris object, let
sample be the
List<SpacecraftState>.
builder = TLEPropagatorBuilder(tleTemplate, PositionAngle.TRUE, 1.0); fitter = FiniteDifferencePropagatorConverter(builder, 0.001, 1000); fitter.convert(sample, false); prop = TLEPropagator.cast_(fitter.getAdaptedPropagator()) fitted_tle = prop.getTLE()
With
tleTemplate is a
TLE object used to initialize some values like the NORAD ID, the epoch of the TLE, etc. In other words, the keplerian elements of the
tleTemplate can be equal to 0.0.
Best regards,
Bryan
Thanks @bcazabonne for your advice,
I’ve been trying to follow your recommendation have had problems creating the tleTemplate.
(Ran out of embedded media objects)
And I’m getting this error. I presumed there was something incorrect with my date formatting, so I did it differently and got a not implemented error .
Traceback (most recent call last):
File “C:\Users\separ\Desktop\New_Orekit_Orbit_Determination.py”, line 245, in
tleTemplate = TLE(11111, “U”, 2020, 222, “A”, 0, 333, AbsoluteDate(2020, 1, 1, TimeScale(utc)), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
NotImplementedError: (‘instantiating java class’, <class ‘org.orekit.time.TimeScale’>)
(Ran out of links… please bear with me as I try to become a level 1 user…)
What formatting should I be using for the date/ is there some other way to create the tleTemplate?
The problem is the conversion from integer to double. You should initialize the tleTemplate like that:
tleTemplate = TLE(11111, "U", 2020, 222, "A", 0, 333, ref_date, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0, 0.0)
Bryan
That resolved my problem with creating the tleTemplate, I however then encountered the error message that the Jacobian matrix is singular. I have encountered this several times throughout working on this, but it usually fixes itself by just messing with values which doesn’t seem to be working here. What does this mean (from a code issue perspective, I know what a singular or degenerate matrix is mathematically), and how is it actually supposed to be fixed?
I see. Let “ephemeris” be your Ephemeris object, could you try initializing the tleTemplate like that.
tleTemplate = TLE.stateToTLE(ephemeris.propagate(date_start), tleTemplate)
Bryan
I think that’s because for TLE fitting the keplerian elements of the tleTemplate can’t be equal to 0 (while for the stateToTLE they can). So, that’s why I propose to use the stateToTLE method to initialize the template
Sorry for the wrong information in my first message…
I initialized it and end up getting what I think is an error code, though it’s hard to tell as it’s longer than the terminal… here is a clip of it
I have figured out that it happens here in this line:
I used my estimated propagator (creating a spacecraft state alike to that which is required for stateToTLE) in my ephemeris code, could it have changed the nature of it?
I may also have the wrong list of spacecraft states. The one used is generated in the last code block above.
Quick update to anyone who may read and respond to this, I have realized that I did indeed have my spacecraft states incorrect and they are now the list of absolute pv coordinates that it should be, I also seem to need some list of “free parameters” and have otherwise been unable to figure out what this means. I am getting the IllegalArgumentException which makes sense as I am not listing any free parameters.
If it’s possible for you, I’ll need a sample of code in order to run you application and see what’s wrong. Because it’s hard to understand.
By default, all orbital parameters are fitted.
freeParameters are additional parameters that you want to fit. For TLE fitting, it can be the B* parameter.
Bryan
I forgot I could do this now that I’m no longer a level 0 user…
New_Orekit_Orbit_Determination.py (22.2 KB)
And this accepts the Earth Centered Earth Fixed Frame, so here is a data set that can be run with it.
SimulatedObservationsOK.csv (8.1 KB)
The TLE fitting is at the bottom, but it needs all the code to run.
I just found this post:
Generation of TLE - Orekit development - Orekit
And it looks like the approach you are using used an Orbit object for the spacecraft states. The only difficulty is I don’t have an orbit as a spacecraft state, but rather an AbsolutePV coordinate. Is there a different approach that would be better to use, or is there some way to turn my PV coordinates into an orbit rather that I am just not seeing?
Hi,
I solved the argument error. The TLESpacecraftStates needs to be converted to a Java list. You can solve the issue like that:
# Convert to a list states_list = ArrayList() for state in TLESpacecraftStates: states_list.add(state) tleTemplate = TLE(11111, "U", 2020, 222, "A", 0, 333, date_start, 0.0, -138.8546595251871, 0.0, 0.00029131750532795117, 98.24086439196059, 66.12659133154932, -55.56899656065682, 0.0, 0, 0.0) tleTemplate = stateToTLE(estimatedPropagator.propagate(date_start), tleTemplate) builder = TLEPropagatorBuilder(tleTemplate, PositionAngle.TRUE, 1.0) fitter = FiniteDifferencePropagatorConverter(builder, 0.001, 1000) fitter.convert(states_list, False, 'BSTAR')
I added the BSTAR parameter as free parameter. Indeed, I think it is interesting to fit it.
The convert method is now used but another exception is raised: MathIllegalStateException for the Q.R decomposition. This must be investigated.
Bryan
Ok, I solved the second issue.
Because GCRF is an inertial frame, you can use orbits instead of absolute coordinates. Indeed, absolute coordinates were implemented to create spacecraft states defined in non inertial states and to perform the computation in non inertial frame (e.g. trajectory around Lagragian points) Therefore, you can change your lines
pv = TimeStampedPVCoordinates(date, vector_gtod, velocity_gtod) pv_gcrf = gtod.getTransformTo(gcrf, date).transformPVCoordinates(pv) absolute_pv_gcrf = AbsolutePVCoordinates(gcrf, pv_gcrf) TLESpacecraftStates.append(SpacecraftState(absolute_pv_gcrf))
by
from org.orekit.utils import Constants from org.orekit.orbits import CartesianOrbit pv = TimeStampedPVCoordinates(date, vector_gtod, velocity_gtod) pv_gcrf = gtod.getTransformTo(gcrf, date).transformPVCoordinates(pv) TLESpacecraftStates.append(SpacecraftState(CartesianOrbit(pv_gcrf, gcrf, date, Constants.WGS84_EARTH_MU)))
Best regards,
Bryan
Now I have an open question.
Because your initial need is to generate a TLE that fits your GPS data. Maybe you could perform a SGP4 (i.e., TLE-based) orbit determination?
It means that instead of using a numerical model during the orbit determination you can use the SGP4 model. At the end, you will obtain an estimated TLE fitted using the observations.
Also, I saw that your numerical model doesn’t consider any perturbation. Therefore, the accuracy will be very poor… And your fitted TLE will be very inaccurate.
Maybe you can try to replace your propagatorBuilder initialization by
tleTemplate = TLE(11111, "U", 2020, 222, "A", 0, 333, orbit_first_guess.getDate(), 0.0, -138.8546595251871, 0.0, 0.00029131750532795117, 98.24086439196059, 66.12659133154932, -55.56899656065682, 0.0, 0, 0.0) tleInitialGuess = stateToTLE(SpacecraftState(orbit_first_guess), tleTemplate) propagatorBuilder = TLEPropagatorBuilder(tleInitialGuess, PositionAngle.TRUE, estimator_position_scale)
And obtain the estimated (fitted) TLE by using
print(TLEPropagator.cast_(estimatedPropagator).getTLE())
and not the
FiniteDifferencePropagatorConverter!
Just be careful that the outputs will be in TEME frame.
I didn’t try in your application because my Orekit Python version is 10.3 and this functionality was introduced in 11.0. But I think it can be very useful for your need. However, it’s only an advice, your free to try or not
If you want to know more about SGP4 orbit determination you can look at this reference:
Bryan
Thank you for your advice!
In response to your open question, I didn’t do that simply because I didn’t know I could. So, I will investigate that. You mentioned that my numerical propagator doesn’t consider any perturbation… is that specifically in reference to the way I was trying to generate my TLE, or will that effect the accuracy of my Ephemeris as well as it uses a numerical propagator?
I was unable to get this line working:
print(TLEPropagator.cast_(estimatedPropagator).getTLE())
But in comparison with another programs output (FreeFlyer) which we are seeking an alternative to, changing the first three lines made a difference of about 10 meters in comparison which is about 50% closer. So, I think everything is now working. Thanks for all your help! | https://forum.orekit.org/t/creating-a-tle-from-base-code-from-gorgiastro/1849 | CC-MAIN-2022-33 | refinedweb | 1,558 | 56.66 |
authfor authentication,
adminfor basic data manipulation, or
flatpagesfor the dynamic content that tends to be rarely changed. Sometimes you want to use them, but their functionality doesn't completely fit your needs.
You have several options in that case:
- Use custom models with one-to-one or many-to-one relations, creating extensions for existing models. The main drawback of this approach is that those custom models will be editable in the contributed administration separately from the origin or you will need to create custom views to combine everything nicely.
- Use modified duplicates instead of the contributed applications. The main drawback of this case is that it will be hard to manage the updates of the models.
- Use signals to modify the models. This can be too complicated for simple changes.
- Modify the properties of the models on the fly.
INSTALLED_APPSsetting. As Python is an interpreted language and all methods and properties are public, you can access and change them on the fly.
For example, if your task is to rename verbose name of groups to "Roles" and show related users at the list view of contributed administration, then it can be achieved by the following code in some model which application appears somewhere below the
"django.contrib.auth"in the
INSTALLED_APPS.
#!/usr/bin/python
# -*- coding: UTF-8 -*-
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import Group
def modify_group_class():
""" A function modifying the contributed Group model """
# modifying the verbose names
Group._meta.verbose_name = _("Role")
Group._meta.verbose_name_plural = _("Roles")
def display_users(group):
""" A function displaying users for a group """
links = []
for user in group.user_set.all():
links.append(
"""<a href="/admin/auth/user/%d">%s</a>""" % (
user.id,
("%s %s" % ( # show the real name
user.first_name,
user.last_name, # or the username
)).strip() or user.username,
)
)
return "<br />".join(links)
display_users.allow_tags = True
display_users.short_description = _("Users")
# attaching the new function to the Group model
Group.display_users = display_users
# changing the list_display for the Group model
Group._meta.admin.list_display = ("__str__", "display_users")
modify_group_class()
As you might see from this example,
Group._metareturns the
Metaclass and
Group._meta.adminreturns the
Adminclass for the
Groupmodel. You can prove it to yourself by browsing objects in Django shell aka Python IDE.
Use this kind of hacking whenever you reasonably need to change Django core functionalities or some third party modules and have no other choice. However, don't overuse it, 'cause it might lead to difficulties in maintaining the project.
Very nifty approach. Thanks for posting! | http://djangotricks.blogspot.com/2008/03/hacking-contributed-models.html | CC-MAIN-2017-13 | refinedweb | 418 | 51.65 |
Asked by:
New Release: Reactive Extensions v1.0.10425
We are pleased to announce a new release of the Reactive Extensions (Rx). This new release is an exciting step forward for Rx. Not only will you find many new features and improvements, but you will also see that Rx has expanded its offerings.
Beginning with this release, the Rx API will be offered in two forms: stable and experimental. The experimental form of the API will continue to change and evolve at a rapid pace characterized by frequent iteration and constant improvement. At the same time, the experimental portions of the API will be less documented and may change somewhat from release to release. This offering is essentially what Rx is today. Additionally, we will offer a subset of the API which is called the stable API. This portion of the API will not significantly change and will be augmented by documentation, samples, and support. If you want to try out and influence new features then use the experimental API. If you want to take a dependency on Rx in an environment where stability is more important then use the stable API. While the stable API will be available on many platforms, it will only be officially supported on .NET 4.0, Silverlight 4, and Windows Phone 7.
In order to achieve a stable form of the API, we needed to make changes. These changes include changing namespaces to System.Reactive, renaming types and operators, and a few other changes that we include in the release notes. We understand that these changes may be a bit painful: we had to change all of our code, samples, and tests. We also understand that many of the existing samples and videos will now contain out-of-date information and we will work hard to improve this situation. Of course, you may continue to use the previous releases as described in their license, but when you make the investment to change you will gain a great deal. You will be able to use the stable API, get bug fixes without API changes, and perhaps most importantly you will have access to full API documentation once the final release is available on MSDN Data Developer Center and on NuGet.
Your feedback is vital. Please try it out. Kick the tires. Let us know what you think.
Thank you for innovating together with us in the past and we look forward to happy coding together in the future.
Sincerely,The Rx Team
General discussion
All replies
Release Notes:
- Fixed time delay in Window and Buffer operators
- Fixed bug in GroupJoin
- Fixed bug in Merge(n)
- Renamed Window* to Window
- Renamed Buffer* to Buffer
- Renamed Generate* to Generate
- Removed RemoveTimeInterval
- Removed RemoveTimestamp
- Removed Scan0
- Removed Let on TValue
- Ensured parity between Buffer and Window overloads, every overloads exists for both
- Added absolute time scheduling to IScheduler
- Renamed Join (as in the pattern) to When
- Added overload to Sample that takes an IObservable
- Moved TestScheduler to Microsoft.Reactive.Testing
- Created ReactiveTest base type with useful members
- Added state parameter to IScheduler schedule methods
- Added additional overloads for First/Last/Single (OrDefault)
- Added ElementAt
- Added Distinct
- Renamed FromEvent to FromEventPattern
- Added FromEvent which converts from non-standard events to observables
- Added ToEventPattern and IEventPatternSource
- Added ToEvent and IEventSource
- Improved performance of Task.ToObservable
- Removed IEvent, Added EventPattern
- Added ReactiveAssert class with common asserts in Microsoft.Reactive.Testing
- Split release into Experimental and Stable
- - Stable is only available on .NET 4, SL 4, and WP7
- - Marked all parts of the API which are only available in Experimental with the ExperimentalAttribute
- Improved Doc comments
- Fixed a bug in Concat, OnErrorResumeNext, and Catch
- Improved perf of subjects
- Removed VirtualScheduler
- Added VirtualTimeSchedulerBase, VirtualTimeScheduler
- Added HistoricalSchedulerBase, HistoricalScheduler
- Remove extended Action and Func Definitions in System.Reactive for downlevel platforms
- Stopped shipping TPL 3.5
- Temporarily not shipping System.Linq.Async, Ix, and RxJS
- Added documentation for Microsoft.Reactive.Testing
- Changed IScheduler interface, there are new extension methods on Scheduler which expose the old methods, but implementors will need to change; recursive and distributed scheduling
- New Assembly structure:
- - System.Reactive (what used to be CoreEx and Reactive)
- - System.Reactive.Providers (Qbservable, IQbservable, and IQbservableProvider) - Observable.Provider is now Qbservable.Provider
- - System.Reactive.Windows.Forms (all operators, schedulers, etc related to Windows Forms)
- - System.Reactive.Windows.Threading (all operators, schedulers, etc related to WPF)
- - Microsoft.Reactive.Testing (all code to assist in writing tests)
- Third-party Qbservable extensibility
- New namespace structure:
- - System
- - Reactive
- - Linq
- - Disposables
- - Concurrency
- - Joins
- - Subjects
- - Threading
- - Tasks
- - Windows
- - Threading
- - Forms
- - Microsoft
- - Reactive
- - Testing
- MutableDisposable changed to take an assignment policy
- Reduced the memory consumption of CurrentThreadScheduler, VirtualTimeScheduler, HistoricalScheduler, and EventLoopScheduler
- Reduced the memory consumption of many operators
- Added Unit.Default
- Added static class Subject with a few operators for Subjects
- Removed CurrentThreadScheduler.EnsureTrampoline, Added CurrentThreadScheduler.ScheduleRequired
- Added Observer.Synchronize
- Made IObservable compatible with new Async CTP in the Experimental subset
- Using await on IObservable now only returns the last message, if you want the old behavior use ToList first
- Replaced all Subject* with FastSubject*, if you want old behavior then create a subject and use the Subject.Synchronize operator
- Removed publish overloads that take a scheduler
This is a big one!
FYI - A number of teams I've worked with have taken on Ix. Will be a blocker for them adopting this release in the short term.
James Miles
We plan on shipping it again soon. It is a side-effect of recently extensively changing our build system. We haven't ported all of the projects to the new system yet.
Yes, this one is a big one. If people want to continue using old builds for awhile that is great. This release is really about moving to a form of the API that we want for the long term.
Hi Wes!
Exciting news indeed! However, I am probably blind or thick (perhaps both :) ), but where do I find this new drop? From what I can gather, the download link on the Rx page points to the previous release??? Oh yeah, that is another thing - from the dl links where can I see what version number I am downloading???
Niels | @nielsberglund
You are neither blind nor thick ;) We are still in the process of updating NuGet and Microsoft Download Center. We also haven't yet put the link up to the stable version of the release or the new SL 5 release.
You can find links to all of the experimental versions (minus SL 5) at. When you download and run the installer, it very prominently displays the version number.
If we haven't sorted out everything tomorrow then I'll post links to all of the releases here in the interim.
Ok, download center is now updated. You can grab both the experimental and stable bits from there. For those who still need Ix, Linq.Async, System.Threading.DLL or other such stuff they can download version v1.0.2856.0.
I'll work on updating NuGet and the Data Developer Center webpage. Thanks for your patience.
Basically in my case I need to know the actual reason Px extensions (ie. Parallel.ForEach), previously included in v1.0.2856.0. I mean, is it only bcs this new version is experimental, so, focused on Rx only, -or- should we assume that from 1.1 version the same are not included anymore?
Thanks
Adriano
Dear,
After following the Microsoft Techdays in Belgium last week (nice presentation by Bart De Smet by the way), I was planning to start playing with Rx. After downloading the new version and start reading the hands on lab documentation I could not find back the reference "System.CoreEx.dll". Any idea how this comes? I'm using Visual Studio 2010 Professional. I could find back "System.Reactive.dll" in the folder "C:\Program Files\Microsoft Reactive Extensions SDK\v1.0.10425\Binaries\.NETFramework\v4.0"
Thank's for your help.
Thanks Rx Team!
What is the strategy for Observable.Iterate? Completely avoid now and go with the async/await?
The removal of Ix is a real frustration; hopefully the parts I am using I can dummy up myself since this is connected in with async CTP SP1 etc. (I've come too far)
Regards, Fil.
Regards, Fil.
Where is the documentation?
This release is a preview of the stable/experimental structure of Rx. Consider it RC 0 for Rx. The documentation is currently being written and will be available once the final release of v1.0 is made public.
Where is System.CoreEx.dll?
We have removed System.CoreEx.dll in favor of combining it with System.Reactive.dll. The only things which are excluded from that assembly are things which do not exist on all platforms (Expressions, Win Forms, and WPF).
Why was TPL 3.5 removed?
You can continue to use TPL 3.5 from an older release. We have not made any changes to it and so all releases of TPL v3.5 are the same.
Where is Ix and Linq.Async?
They were removed temporarily from the project since our focus was on getting things that will appear in the stable release in their final form. We do not plan to offer Ix and Linq.Async in a stable release at the current time. We may offer them in the experimental release or perhaps as a separate download. We will investigate this. If you have any feedback on what would be most helpful here let us know.
What about Observable.Iterate?
Use the Observable.Create that takes a Func<IObserver<...>, Task> which works exactly the same as Iterate except that it uses async await to drive it.
Regarding Observable.Iterate, I can't see an Observable.Create with this overload. I only see:
public static IObservable<TSource> Create<TSource>(Func<IObserver<TSource>, IDisposable> subscribe); public static IObservable<TSource> Create<TSource>(Func<IObserver<TSource>, Action> subscribe);
(a great solution to create a Observable.Create overload as a replacement to Observable.Iterate BTW!)
Regards, Fil.
- Edited by Fil Mackay Tuesday, May 03, 2011 12:53 AM
Here is the experimental release: couldn't find it, other than to Google "Rx Experimental Release" :)
Regards, Fil.
The Observable.Create overload that I referred to is only in the experimental release until they finalize the await pattern for .NET 4.5.
What about an additional overload (this is actually what I need):This would serially call asyncMethod, passing on all the returned values to the observer. When it returns null, the observer is completed.
public static IObservable<TResult> Create<TResult>(Func<Task<TResult>> asyncMethod);
Regards, Fil.
Regards, Fil.
Where is the documentation?
This release is a preview of the stable/experimental structure of Rx. Consider it RC 0 for Rx. The documentation is currently being written and will be available once the final release of v1.0 is made public.
Actually, scratch this - the existing overloads were fine. I ended up with:
public static IObservable<byte[]> AsyncRead(this Stream stream, int bufferSize = 1 << 16) { return Observable.Create<byte[]>(async (observer, cancelToken) => { var buffer = new byte[bufferSize]; while (!cancelToken.IsCancellationRequested) { var bytesRead = await stream.ReadAsync(buffer, 0, bufferSize); if (bytesRead == 0) { // End of file observer.OnCompleted(); break; } // return read data var outBuffer = new byte[bytesRead]; Array.Copy(buffer, outBuffer, bytesRead); observer.OnNext(outBuffer); } }); }
Regards, Fil.
The documentation will contains conceptual and references docs. For operators, there will be explanations and samples much like you get for the standard query operators in LINQ. If you have particular requests, I know that our doc writers are very interested in hearing from the community about what would be the most useful information to cover and where to focus their energy.
- It is not incorrect to call observer.OnCompleted just unnecessary. In cases where you want to do processing after calling OnCompleted (or OnError for that matter) you will need to do that explicitly. If you make additional calls to observer.OnNext/OnCompleted/OnError then they will be ignored.
I think I may have found a bug. While updating the F# wrapper project, FSharp.Reactive, I noticed that a previously passing test now fails. The test verifies that a F# function wrapped in an Action delegate can be used to subscribe to an observable. The test fails with the following message:
Errors and Failures:
1) Test Failure : ReactiveSpecs.When subscribing to an observable async workflow, it should only raise one item before completion.
Elements are not equal.
Expected:1
But was: 0
at NaturalSpec.Utils.check[a](AssertType assertType, Object a, Object b, a value) in D:\Builds\NaturalSpec\master\src\app\NaturalSpec\Utils.fs:line 65
at NaturalSpec.Syntax.should[a,b,c,d,e](FSharpFunc`2 f, a x, b y) in D:\Builds\NaturalSpec\master\src\app\NaturalSpec\Syntax.fs:line 115
at ReactiveSpecs.When subscribing to an observable async workflow\, it should only raise one item before completion-@45.Invoke(FSharpFunc`2 f, Int32 x, Int32 y) in .\src\FSharp.Reactive.Tests\ObservableSpecs.fs:line 45
at ReactiveSpecs.When subscribing to an observable async workflow, it should only raise one item before completion.() in .\src\FSharp.Reactive.Tests\ObservableSpecs.fs:line 43
2) Test Error : ReactiveSpecs.When subscribing to an observable event, it should raise three items.
System.ArgumentException : Error binding to target method.
at System.Delegate.CreateDelegate(Type type, Object firstArgument, MethodInfo method, Boolean throwOnBindFailure)
at System.Reactive.Linq.Observable.<>c__DisplayClass2c0`2.<FromEvent>b__2be(IObserver`1 observer)
at System.Reactive.AnonymousObservable`1.<>c__DisplayClass1.<Subscribe>b__0()
at System.Reactive.Concurrency.Scheduler.Invoke(IScheduler scheduler, Action action)
at System.Reactive.Concurrency.ScheduledItem`2.InvokeCore()
at System.Reactive.Concurrency.ScheduledItem`1.Invoke()
at System.Reactive.Concurrency.CurrentThreadScheduler.Trampoline.Run()
at System.Reactive.Concurrency.CurrentThreadScheduler.Schedule[TState](TState state, TimeSpan dueTime, Func`3 action)
at System.Reactive.Concurrency.CurrentThreadScheduler.Schedule[TState](TState state, Func`3 action)
at System.Reactive.AnonymousObservable`1.Subscribe(IObserver`1 observer)
at System.ObservableExtensions.Subscribe[TSource](IObservable`1 source, Action`1 onNext)
at ReactiveSpecs.listening with@15TT.Invoke(FSharpFunc`2 f, IEnumerable`1 lst, IObservable`1 obs) in .\src\FSharp.Reactive.Tests\ObservableSpecs.fs:line 17
at ReactiveSpecs.When subscribing to an observable event\, it should raise three items-@27-2.Invoke(IObservable`1 arg20) in .\src\FSharp.Reactive.Tests\ObservableSpecs.fs:line 27
at ReactiveSpecs.When subscribing to an observable event, it should raise three items.() in .\src\FSharp.Reactive.Tests\ObservableSpecs.fs:line 26
Is this expected behavior? If so, how can I use F# with Rx?
Ryan Riley @panesofglass
Ryan,
Can you give me a minimal repro?
Ah, sorry; I meant to include the link to the project:
Specific test cases are at
Ryan Riley @panesofglass
Looks like I might be mistaken. I didn't think I was using anything tricky in my tests, but fsi appears to work fine. I'll re-evaluate what I have in my repo. It's interesting that the tests worked in the previous version, but with the recent changes I made, it could be something else that's causing the test failure.
> #r @"C:\Program Files (x86)\Microsoft Reactive Extensions SDK\v1.0.10425\Binaries\.NETFramework\v4.0\System.Reactive.dll";; --> Referenced 'C:\Program Files (x86)\Microsoft Reactive Extensions SDK\v1.0.10425\Binaries\.NETFramework\v4.0\System.Reactive.dll' > open System;; > open System.Reactive;; > open System.Reactive.Linq;; > Observable.Range(0,3).Subscribe(Action<_>(printfn "%d"));; 0 1 2 val it : IDisposable = System.Reactive.AnonymousObservable`1+AutoDetachObserver[System.Int32] {Disposable = null;} >
Ryan Riley @panesofglass
"Temporarily not shipping System.Linq.Async, Ix, and RxJS"
Is RxJS dead? I have not seen any recent RxJS activity on the MSDN blogs.
Update to my own question, this is a message from Matthew Podwysocki on the KnockoutJS forum:
"It's far from dead at this point and I'm hard at work making sure that
RxJS is a nice mirror of Rx.Net. This included a whole suite of tests
as well. Rx.Net has changed quite a bit in the past couple of months
and I'm the developer on this project at the moment, so please bear
with us. Once the Schedulers have been rewritten, the rest should
easily fall into place." | https://social.msdn.microsoft.com/Forums/en-US/527002a3-18af-4eda-8e35-760ca0006b98/new-release-reactive-extensions-v1010425?forum=rx | CC-MAIN-2016-07 | refinedweb | 2,694 | 50.73 |
One of the biggest complaints that is leveled at C++ is its lack of garbage
collection. Programmers used to more modern languages such as Java find that
programming in C++ is difficult and error prone because you have to manually
manage memory. To some extent they are right, though most die hard C++
programmers would hate to give in entirely to a garbage collecting system.
The idea behind garbage collection is that a runtime system will manage
memory for you. When you need a new object you explicitly create it, but you
never have to worry about destroying it. When there are no more references
left to the object it is eventually automatically destroyed by the runtime
system. This makes complex systems that must dynamically create objects
frequently much easier to code, since you never have to worry about destroying
the objects. This sounds very appealing, so why did I say "most die hard C++
programmers would hate to give in entirely to a garbage collection system?"
The problem is that memory is just one type of resource. There are numerous
other resource types, such as thread or database locks, file handles, Win32 GDI
resources, etc. A GC (garbage collection) system only addresses memory, totally
ignoring the other resource types. In most modern languages that support GC
the programmer is still left to manually manage these other resources. In
contrast, the C++ programmer can easily manage these other resources by wrapping
the resource in an object that uses the RAII (Resource Acquisition Is Initialization)
idiom. When the resource wrapper goes out of scope the destructor will automatically
release the wrapped resource.
At first you might think that adding destructors to objects in a GC langauge
would be enough to allow the best of both worlds. This is almost true. Most
GC languages have no concept of "stack data", so all objects are created on the
heap and are destroyed only when the collector runs. This is non-deterministic,
meaning that you have no idea *when* the collector will run. The result is that
you won't know when the wrapped resource is released, which can be critical for
many resource types. For instance, a thread lock should be held for the absolute
shortest possible time. Hold it longer and you may starve other threads, or even
theoretically cause a deadlock. You simply can't allow the lock to be released
in a non-deterministic manner. So what you really want is a language that supports
GC, stack data and destructors. That's why I said "most die hard C++
programmers would hate to give in entirely to a garbage collecting system."
C++ programmers have become accustomed to using the RAII
idiom to manage memory. They wrap a pointer to an object created with operator
new up in a class that emulates a regular pointer by defining certain operators
such as '->' and '*'. These wrappers are
known as "smart pointers" because they emulate a regular pointer while adding
more intelligent behavior. A classic example of such a smart pointer comes with
the standard C++ library and goes by the name of std::auto_ptr.
This smart pointer was specifically designed to insure that memory is freed if
an exception occurs, but it's not really usable for more complex memory
management. With std::auto_ptr there can be only one "owner",
or pointer referring to an object instance. Copying or assigning an
std::auto_ptr transfers ownership, setting the original
std::auto_ptr to NULL in the process. This
prevents the std::auto_ptr from being used in a standard
container such as std::vector, for instance.
->
*
std::auto_ptr
NULL
std::vector
Many other smart pointer implementations attempt to allow multiple "owners", or
pointers referring to the same object instance, through reference counting. A
reference count is maintained that's incremented when the smart pointer is copied and
decremented when the smart pointer is destroyed. If the ref-count ever reaches
zero the object is finally destroyed. CodeProject includes a couple of smart
pointer implementations that use this
idea.1,2
There's also a version that's undergone thorough peer review that can be found
in the Boost library.3
Reference counted smart pointers are quite handy and work for many situations,
but they aren't as flexible as true garbage collection. The problem is with
circular references. If object A has a ref-counted pointer that points at object B
which has a ref-counted pointer that points back at A then neither object will
ever be destroyed since their ref-counts will never reach zero. It can be difficult
to prevent such circular references.
One approach to fixing this problem is to use a "weak
pointer". A weak pointer is a pointer that references an object, but does not
increment or decrement the ref-count. A regular C++ pointer is a "weak pointer"
but it has a draw back to use. When the ref-count goes to zero the object is
deleted which may leave regular pointers used as weak pointers "dangling". For
this reason another smart pointer type is often used for a weak pointer. This
other smart pointer can cooperate with the ref-counting smart pointer so that
when the object is deleted the "weak pointer" will be automatically set to
NULL, thus preventing dangling pointers.
This works, but still leaves the programmer with the responsibility of spotting
circular references and correcting them. This is not always easy, or even possible,
to do. So, in some cases the C++ programmer is still left wishing that C++ had
a GC system on top of the other facilities it already has.
There are several free and commercial implementations of garbage collectors
written for C/C++ that replace malloc and new respectively. All of these collectors
are known as "conservative" collectors. This means that they err on the side of
caution when trying to determine if there are any remaining pointers referring to
an object. The reason for this is that in C and C++ it's possible to manipulate
a pointer by storing it in other data types, such as unions or integral
types.4 Unfortunately, this means that sometimes
they fail to collect objects that are really no longer in use.
Another problem with such libraries is that they only work on objects
created with special forms of malloc and/or new. Memory that was allocated by third
party libraries, for instance, won't be collected.
So, is there a better solution for C++? This article and
the accompanying code attempts to define a better solution by marrying the
concept of smart pointers with the concept of traditional garbage collection.
The result is a class template called gc_ptr.
gc_ptr
The gc_ptr class addresses the first issue with
traditional GC libraries, namely the ability to be non-conservative. The only
type that needs to be evaluated as a candidate for referring to an object is the
gc_ptr itself. All other types of references to the object are considered to be "weak pointers"
and are not considered. Another benefit to the smart pointer approach here is that the
implementation is made much simpler since the collector doesn't have to try and find references
to the objects, since all such references can be registered with the system at the time of
creation.
The second issue is harder to deal with. The implementation of gc_ptr was originally
based on the implementation for a similar class, circ_ptr, submitted for consideration
to Boost by Thant Tessman.3,5 This original implementation allowed the
circ_ptr to be created with a pointer to any object allocated
by operator new. Unforunately this implementation left a serious hole open for
misuse of the class. The size of the object was registered with the first
creation of a circ_ptr that referred to the object. This size
was used to determine if an object contained other circ_ptrs in
order to find circular references. If a circ_ptr<base>
were to be initialized with a pointer to a derived type because it registered
the size as sizeof(base) the code may fail to recognize that
the object contains another circ_ptr and thus prematurely collect
an object. Using a templatized constructor in the original implementation would have made
it less likely for this to occur since the size could be calculated from the type of pointer passed
to the constructor, but this would not have eliminated the possibility for error as illustrated by the
following code:
circ_ptr
circ_ptrs
circ_ptr<base>
sizeof(base)
base* factory(int i)
{
switch (i)
{
case 1:
return new derived1;
case 2:
return new derived2;
default:
return 0;
}
}
circ_ptr<base> ptr(factory(1));
To actually eliminate this possibility we need to provide a custom way of allocating objects that
are to be garbage collected. The implementation for gc_ptr does this by
providing an overloaded new operator that takes an instance of
gc_detail::gc_t in addition to the size_t. In this overload
the size of the object allocated is stored to enable proper detection of whether or not
an object contains another gc_ptr. With this overload the above example can be coded
safely as (note the unusual syntax for new):
gc_detail::gc_t
size_t
base* factory(int i)
{
switch (i)
{
case 1:
return new(gc) derived1;
case 2:
return new(gc) derived2;
default:
return 0;
}
}
gc_ptr<base> ptr(factory(1));
Objects pointed to by gc_ptr now must be allocated only through the
syntax "new(gc)". The variable "gc
" passed to operator new using this syntax is declared in an unnamed
namespace by the library as a convenience and to prevent violations of the "one definition rule."
Objects allocated through the standard new operator that are used to construct a gc_ptr will throw an immediate
std::invalid_argument
exception. This makes it easy to find such
errors at run time and prevents misuse. Because of this requirement a gc_ptr is not a
direct replacement for regular pointers, but it's still a relatively simple replacement.
All that's needed is for you to change the code that allocates the object.
new(gc)
std::invalid_argument
The interface for using gc_ptr is relatively simple. There are two global methods
that are used to control garbage collection and the gc_ptr class itself.
This is the heart of the collector. When invoked a
mark-and-sweep algorithm is run to find all objects which are currently no
longer in use and then destroys them. The programmer is free to make use of this
method to invoke garbage collection at any point. However, there isn't a
requirement that the programmer ever call this method. The
new(gc) operator will invoke this method automatically if
either a programmer specified threshold (see below) of memory has been allocated
since the last call to gc_collect or if memory has been
exhausted. In most cases this automatic collection should be enough.
gc_collect
This method sets the threshold at which
gc_collect is automatically called by operator
new(gc). Initially the threshold is set to 1024 bytes but may
be changed by this method to optimize performance. There are two interesting
values that may be used in a call to this method. Passing in zero will result in
memory being collected for every invocation of operator
new(gc). This will degrade performance but will insure optimal
use of memory. Passing std::numeric_limits<size_t>::max() will have the opposite effect, turning automatic
collection off entirely, though collect will still be called if memory is exhausted.
This will give the best possible performance but will result in the worst possible use of
memory.
gc_collect
std::numeric_limits<size_t>::max()
An interesting technique could be applied to create a
"parallel garbage collector" by passing in
std::numeric_limits<size_t>::max() to this method to shut
off automatic collection and then coding a thread that periodically calls
gc_collect itself. This may result in
optimal performance and memory use in multithreaded programs.
Constructs a gc_ptr with a NULL reference.
Constructs a gc_ptr to point at an object constructed with operator new(gc).
Constructs a gc_ptr from another gc_ptr. The template definition allows related
types to be copied, though only single inheritance relationships may be used safely
with this implementation. If a solution can be found for multiple inheritance a
future version will do so. For now you should avoid using types that use multiple
inheritance in gc_ptr.
Points a gc_ptr to a new object allocated by operator new(gc).
Points a gc_ptr to the object pointed to by another gc_ptr. Again the template
definition allows related types to be copied but is unsafe for use on types that use
multiple inheritance.
Returns a real C++ pointer to the object pointed to by this gc_ptr. This is an explicit
cast. For safety reasons there is no implicit cast to the real pointer.
Allows the gc_ptr to be derefenced in the same manner that a real C++ pointer would be.
Allows normal "arrow notation" to be used on the gc_ptr in the same manner that a real
C++ pointer would.
Provides simple garbage collection to C++ programmers. The code that implements the
gc_ptr is short and contained in only two files that are easily included in your projects.
Eliminates memory management errors that occur with traditional ref-counted smart pointers
when circular references are encountered.
Provides a safe implementation that's not restricted to "conservative garbage collection".
Provides a flexible interface that allows the programmer to control when garbage is to
be collected, including a simple way to implement "parallel garbage collection".
Easy to use.
Thread safe. When used in a multithreaded program calls
to gc_collect, and thus calls to operator
new(gc), may block if another thread is currently collecting garbage. In practice this
shouldn't cause any noticable speed difference, since both operations are (relatively) slow any
way.
Not as efficient as manual memory management or ref-counted smart pointers.
Requires the use of an overloaded operator
new(gc) for allocation of the objects that are to
be garbage collected. This syntax is non-standard, but the implementation conforms to
the C++ Standard.
Will not work properly with types that use multiple inheritance. This is the most
serious hole in the implementation and simply results in undefined behavior, not in
a compile time error. A solution to this problem is needed so if any programmers
know of one I'd love to hear it.
Pointers to objects returned from operator
new(gc) that are never pointed to by
a gc_ptr will leak. There's no way for the collector to know how to delete such
objects since the object's type is not registered until the first assignment of
a gc_ptr to the object.
Some enhancements that may be provided in the next version include the ability
to use types that use multiple inheritance and to include ref-counting.
The multiple inheritance problem will be hard to solve. The garbage collector must save
a void pointer to the object and the gc_ptr uses only this void pointer internally.
Casting the void pointer to the templated pointer type using
static_cast<> is safe for types that
don't use inheritance or that use only single inheritance, but it's not safe for types that
use multiple inheritance. If any programmers know of a solution to this problem I would
love to hear from them.
static_cast<>
The ref-counting would help to optimize memory usage by destroying objects that don't participate in
circular references immediately instead of only when gc_collect is called. This shouldn't be too difficult
to add to this implementation and was left out only because such uses should be coded with ref-counted
smart pointers instead of gc_ptr in order to optimize the performance of both. This makes ref-counting
in gc_ptr only a minor benefit.
Part Two of this article is now available.
The code presented here was based on the implementation of circ_ptr5
written by Thant Tessman and submitted to Boost.3 The implementation
was refactored to minimize compile time dependencies, address the usage issue that led to new(gc), and to
provide a more efficient collection algorithm. I'm indebted to Thant not only for the original circ_ptr but
for input during the refactoring for my implementation. The code presented here is original, but would not
exist with out the original efforts and later input given by him.
1
A Simple Smart Pointer, an article found
on CodeProject.
2
A Smart Pointer Capable of
Object Level Thread Synchronization and Reference Counting Garbage Collection, an article found
on CodeProject.
3
Boost, an organization of programmers working to produce
quality libraries that undergo extensive peer review to the public domain. Many of these
libraries are hoped to be considered for inclusion in later C++ standards.
4 The standard doesn't
gaurantee which, if
any, integral type a pointer can be placed into, but in practice most platforms allow this, and
it's a common technique used.
5
circ_ptr.zip. This
link requires you to be a member of the Boost eGroup mailing list. See the
Boost3 web site for instructions on. | http://www.codeproject.com/Articles/912/A-garbage-collection-framework-for-C?fid=1859&df=10000&mpp=10&noise=1&prof=True&sort=Position&view=Normal&spc=Relaxed&select=17838&fr=8 | CC-MAIN-2017-17 | refinedweb | 2,839 | 52.6 |
Created
03-22-2018
01:04 PM
Do we have any Data Governance tools for apache phoenix in HDP? As I can see Atlas is not integrated with apache phoenix
Created
03-22-2018
01:59 PM
Hi @Krishna Srinivas
Atlas 0.8 has a data model for HBase which define several components (HBase_namespace, HBase_table, etc). However, there's no automated scrolling of HBase that scroll over all tables and save data in Atlas. You can write a script that do this and update ATlas through it event or REST API.
You have some examples here :...
You can also manually create HBase entity through Atlas UI of you don't have lot of tables | https://community.cloudera.com/t5/Support-Questions/Data-Governance-tools-for-apache-phoenix-in-HDP/m-p/196548 | CC-MAIN-2022-27 | refinedweb | 114 | 73.17 |
Biking data from XML to analysis, part 3
One thing I wanted to do with this data set was experiment with plotting methods. I had already done some exploratory plotting with regular matplotlib, so I had some vague ideas about what I wanted to do.
First I had to select out subsets of data to compare. I knew that there were two types of rides: shorter trips in the city, and longer trips in the suburbs. I was feeling lazy, so I just did a quick threshold with SQL.
import pandas import pandasql import matplotlib.pyplot as plt import matplotlib import seaborn as sns #for prettier plotting import numpy as np #for binning %matplotlib inline #IPython magic df = pandas.read_csv("updated_2013.csv", index_col=0) q="""SELECT * FROM df WHERE Miles <6""" city = pandasql.sqldf(q, locals()) q="""SELECT * FROM df WHERE Miles >5""" suburbs = pandasql.sqldf(q, locals())
Give that story a little more plot!
First, I used seaborn to make two histograms of the average speed, and plot them together in two different colors. Thankfully, the seaborn tutorial had exactly the right example for me to follow, but I’m going to explain a few things that were not obvious to me.
Calculate the range for the binning
If you have more than one data set, this is done by concatenating the dataframes so you can treat the data as one big one.
To do this, the example in the seaborn tutorial used this odd little thing called r_. I didn’t know what that was, so I did some digging and found this post the most useful. I’ll probably be able to remember it now that I know that it’s similar to how slicing works in R.
The actual bins come from using linspace to create an array of linearly spaced points.
The normed=True argument is good here because I didn’t want to worry about the size of the distributions (I knew they weren’t the same).
Show your colors!
I had to look up what the colors were, because in the tutorial they don’t tell you, and it wasn’t obvious to me from the hex code, which color was which dataset. I also didn’t know that you can add the label to the same command where you chose the data set, because initially the legend didn’t show up at all.
Ultimately, I had to add this ridiculously complicated (typical matplotlib) line to tell it to put the legend to the right a little bit. Otherwise who knows if there is a legend, because it is invisible.
max_data=np.r_[cityspeed, suburbspeed].max() bins= np.linspace(0, max_data, max_data+1) plt.hist(cityspeed, bins, normed=True, color="#6495ED", alpha=0.5, label="city") #blue plt.hist(suburbspeed, bins, normed=True, color="#F08080", alpha=.5, label="suburb") #coral plt.xlabel("Mph") plt.ylabel("Fraction") l = plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) #show me the legend!
At the end of all that, I was pretty happy with how this plot turned out.
It’s not surprising that the suburb plot is relatively gaussian with little bit of a tail to the left. What surprised me was how high the average speeds were, even on the relatively short city rides. Personally, I don’t like to ride that fast in the city, because most of the time it is too scary and/or impossible with traffic. But the timestamps give a little more insight into why that’s not always impossible (more on that in part 4).
| https://szeitlin.github.io/posts/biking_data/biking-data-from-xml-to-plots-part-3/ | CC-MAIN-2022-27 | refinedweb | 598 | 65.12 |
Write You Some FP Maths
Another article in a series where I'll be looking at some mathematical concepts and functional programming stuff in JavaScript.
FP FTW!
Semigroups
This time we're looking at Semigroups 🎉
But what are they?
Well, according to Wikipedia:
a semigroup is an algebraic structure consisting of a set together with an associative binary operation.
In non-mathematic terms, and in our case functional programming terms, it's a way to bind/join/concat two things together. Check out the Fantasy Land spec. Pretty simple huh? So let's jump right in!
Wait! As we know JavaScript is not type safe, so it's a good idea to make sure we don't get any unexpected errors, only a
TypeError we can handle if required. So lets create a utility function to get the type of some data:
const getDataType = (a) => { if (a === undefined) { return 'Undefined'; } if (a === null) { return 'Null'; } return (a).name || ((a).constructor && (a).constructor.name); } // In use getDataType('Strings'); // => String getDataType(['Array']); // => Array getDataType({ obj: 'Object' }); // => Object getDataType(5); // => Number getDataType(null); // => Null getDataType(); // => Undefined
Excellent! This can be a useful function in many cases, and we're going to use it in our Semigroup.
What's next?
Well, next we need to actually define our Semigroup. Like a lot of FP stuff, it's a good idea to start with a container. Let's create a container for our initial data and define a
concat method that will be called to bind/join/concat a second piece of data to the first. The concat method will have to return a new container that holds the result of the join, that way the data can continually be reused by calling the concat method again.
const Semigroup = (a) => ({ a, toString: () => `Semigroup(${a})`, concat: (b) => Semigroup(a + b), });
You may notice the
toString method, this is common in many languages to print the contents of a container.
Great! Except it's not so great just yet because if we create a container with an array like to
const oneSemigroup = Semigroup([1]) and try call our concat method with an object
oneSemigroup.concat({ a: 'a' }) our container value will then be
1[object Object]. So let's use some type safety to make sure we are joining the same datatypes.
We do this by adding a guard to our
concat method, making it a guarded function. This simply means the input has to pass some form of validation before the rest of the function is executed. In mathematics these guards are called constraints.
Our guard function should take in both our initial value and the second value to compare types:
const typeGuard = (a, b) => { const aType = getDataType(a); const bType = getDataType(b); if (aType !== bType) { throw new TypeError(`Type mismatch. Expected ${aType} datatype`); } }
Now we're ready to guard up our Semigroup:
const Semigroup = (a) => ({ a, toString: () => `Semigroup(${a})`, concat: (b) => { typeGuard(a, b); return Semigroup(a + b); }, });
Boom💥 Fully guarded function. There's just one super tiny little issue...and it's a big one! If we try to use the add operator
+ on some datatypes we may not get what we expect. For example
{} + {} gives us
[object Object][object Object]. Not that helpful. We need a way to join two of the same datatypes regardless of what their type are. What we're going with here is a simple switch statement that handles various cases. Time for another useful utility function:
const typeSafeConcat = (a, b) => { const type = getDataType(a); switch (type) { case 'Number': case 'BigInt': default: return a + b; case 'String': case 'Array': return a.concat(b); case 'Object': return { ...a, ...b }; case 'Boolean': return Boolean(a + b); case 'Function': throw TypeError('Cannot concat datatype Function'); case 'Symbol': throw TypeError('Cannot concat datatype Symbol'); case 'Null': return null; case 'Undefined': return undefined; } }
Wonderful. We've reached a happy place where we can create a Semigroup and call our
concat method on it as much as we want safe in the knowledge that we'll either get a
TypeError if we do something silly, or get a new Semigroup containing the data we'd expect.
You can find the finished code in this gist.
If you have any questions of feedback feel free to comment 🙂
Happy coding λ
Posted on by:
Ryan Whitlie
Always learning
Discussion
Hi Ryan thanks for the article. My issue with your content is that you have created very monomorphic structure from this.
You are creating global concat to work with all possible inputs in some one 'right' way. Semigroup is just a pair (data:T,concat:T->T->T). In other words you have to have data type and function which for a given two elements create third element, and this function obeys Semigroup rules.
My point is - such hardcoded implementation gives no place for defining custom 'concat' for specific data type. And this is the whole point, I want 'concat' for type T works like that and for type Y differently.
Hello again Maciej, thanks for the comment.
Hhmm you want to have a custom
concatfor type T and another for type Y. This is what I was trying with the
typeSafeConcatmethod, but only with the input of concat, not taking into account the init of Semigroup. The "hard coding" part is necessary in JavaScript as these structures are not built into the language, they have to be defined and then can be abstracted away within a library.
As for this Semigroup being monomophic, that is correct. A Semigroup doesn't have to be polymorphic. My initial thought was if it was, it may disobey the associativity law, but I don't think that's the case. If our "concat' is perhaps a string template, something like
${T}${Y}then I think anything would still obey associativity. Thinking about it from your comment, I think a simple example would be:
And to define a concat per data type, something like this
Is this more what you were thinking?
Thanks again for the comment, it's good to hear more opinions to make me think more :) | https://dev.to/moosch/semigroups-33eh | CC-MAIN-2020-40 | refinedweb | 1,017 | 70.43 |
Created on 2009-11-19 20:54 by james.lingard, last changed 2009-11-19 22:55 by benjamin.peterson. This issue is now closed.
def f((x)=0): pass
gives the following incorrect error message:
SyntaxError: non-default argument follows default argument
"def f((x)): pass" is treated exactly the same as "def f(x): pass", so
it would seem sensible for the same to be true if a default value is
used. But if this syntax is disallowed for some reason, the error
message should be fixed.
This appears to be related to bug #1557232.
[Tested on Python 2.6 (r26:66714, Jun 8 2009, 16:07:29).]
Fixed in r76416. | https://bugs.python.org/issue7362 | CC-MAIN-2020-34 | refinedweb | 113 | 77.53 |
REN command with wildcard
I have a batch file, that has been working properly, which renames files in bulk. Example input:
C:\Test\NW\Residents_20190624135727.csv C:\Test\NE\Residents_20190624135727.csv
The batch file being executed has:
ren C:\Test\NW\Residents_*.csv NorthWest_*.txt ren C:\Test\NE\Residents_*.csv NorthEast_*.txt
and the output, as expected:
NorthWest_20190624135727.txt NorthEast_20190624135727.txt
Where it doesn't seem to work is when I have an input file:
C:\Test\CAN\Residents_20190624135727.csv
and use the same command:
ren C:\Test\CAN\Residents_*.csv Canada_*.txt
the output is:
Canada_ts_20190624135727.txt
while I would expect the output to be:
Canada_20190624135727.txt
In my searching online, I haven't been able to find an explanation to this particular problem. After trying variations of input file names and commands, I believe it has something to do with the length of the file names. Can someone explain why this is happening? can I change the path on Windows machine on CircleCI
On a circleci linux machine I can edit my path in a step doing the following :
steps: - run: name: Setup Path command: | echo 'export PATH="$GOPATH/bin:$PATH"' >> $BASH_ENV
Is there something similar for windows path (in cmd.exe) ?
- How to use CHKDSK tool from C# and have the text displayed in CMD window?
I am trying to use the
chkdsk.exesystem tool found in
C:\Windows\System32\chkdsk.exefrom a C# Winforms app. I want to use the System.Diagnostics.Process Class. I am using the ProcessStartInfo to set the file name to the tool and then using the args property to set my arguments.
So I have tried using
System.Diagnostics.Processwith
ProcessStartInfo. But when the error occurs when the user does not have the permissions the
chkdskwindow immediately closes. So I see the window in the task bar for a moment and then it closes without saying anything. I have tried both
UseShellExecute=trueand
false. Also, I have tried redirecting the output stream but in a Windows app, I would have to display the output stream directly if it fails rather than a CMD window showing the error or the CHKDSK info.
using (Process CHKDSK = new Process()) { CHKDSK.StartInfo.WorkingDirectory = @"H:\"; CHKDSK.StartInfo.FileName = "C:\\Windows\\System32\\chkdsk.exe"; CHKDSK.StartInfo.Arguments = "/r /f C:"; CHKDSK.StartInfo.UseShellExecute = true; //CHKDSK.StartInfo.UseShellExecute = false; CHKDSK.Start(); }
I want the CHKDSK text to be displayed in a CMD window I believe. So if the user does not have permissions the window should tell the user they do not have the permissions like it would using a CMD window and typing
"call chkdsk /r /f C:"I do not want to use start an instance of CMD and pass
chkdskas a parameter. I want to use just the CHKDSK.exe tool
- How to open url with string variables in php code being executed via command prompt
The link has PHP string variables that contain many spaces. However they are being ignored when I run my script in the background from the command line.
Below is the code snippet:
$url = "^&user=xxxx^&password=xxxx^&sender=xxx^&SMSText=".$message."^&GSM=".$phonenumber; $cmd=sprintf( 'start %s',$link); exec( $cmd );
- Custom Excel button macro links break when file is renamed or moved
I have a large Excel spreadsheet with some detailed calculations and need a VBA macro to update the calculations when numbers are changed. I will need to send this file to others outside my company for their use. I wrote a macro to update the calculations and then set up a button that is linked to the macro for users to click to easily update calculations because not everyone who will use this file is Excel or macro savvy. However, when the file is moved or renamed, the buttons don't link to the macro in the current file anymore-they seem to be looking for the previous file. (The macro does not refer to the file name and runs fine when selected from the developer/code/Macros ribbon-just doesn't run from the button.) Any suggestions for fixing the button so the macro will run from the button wherever the file is and whatever it is named? Please send specifics :) I know how to write and use macros but I am primarily a heavy Excel user with a little programming experience. Thank you!
Sub UpdateCircRef() ' ' UpdateCircRef Macro ' Dim updatevalues As Single updatevalues = Range("CircRefDif") Do While updatevalues > 1 Range("CircRefCopyRange").Select Selection.Copy Range("CircRefPasteRange").Select Selection.PasteSpecial Paste:=xlPasteValues updatevalues = Range("CircRefDif") Loop End Sub
We have tried numerous ways to restructure the calculations to avoid macros but the file becomes too big and freezes. Macros are our work around but I won't be able to contact the users to troubleshoot. The spreadsheet contains calculations required for a proposal response, and the RFP and requirements for info to be included and calculation methods was issued by someone who doesn't understand spreadsheets, things that cause a spreadsheet to be large and slow, complications with large files or circular references.
- I am trying to rename multiple files at a time using os.rename
I am trying to rename multiple files using os.rename in win8.1
import os path = "C:\\Users\\Aniket\\Desktop\\Python projects\\p" di = os.listdir(path) os.chdir(path) for file in di : i = 0 file_name , file_ext = os.path.splitext(file) new_name = "file"+str(i)+f"{file_ext}" os.rename(new_name, file) i+=1
I want 6464.txt to be renamed file0.txt. But FileNotFoundError: system can't find the specified file: 'file0.txt'-> '6464.txt' appears. (file0 is new name while 6464 is existing name)
- Error renaming matching files with perl one liner
I want to rename all the files that match a pattern. This kind of one liners usually work for me, but I'm getting some kind of error.
Kind of file names I have: PMSNpoda5718_1p2g_out_fst.txt SCSNpoda5718_1p2g_out_fst.txt
File names I want: PM-SN_poda5718_1p2g_out_fst.txt SC-SN_poda5718_1p2g_out_fst.txt
My first try was:
ls *fst.txt | perl -ne '/^([A-Z][A-Z])([A-Z][A-Z])(poda.*?$)/; system("mv $_ $1-$2_$3")'
But it didn't work.
Finally I came up with a line that prints exactly what I want
ls *fst.txt | perl -lne '/([a-zA-Z]{2})([a-zA-Z]{2})(poda.*?$)/; print "mv $_ $1-$2_$3"'
prints:
mv PMSNpoda5718_1p2g_out_fst.txt PM-SN_poda5718_1p2g_out_fst.txt mv SCSNpoda5718_1p2g_out_fst.txt SC-SN_poda5718_1p2g_out_fst.txt
But when I use it in order to rename the files:
ls *fst.txt | perl -lne '/([a-zA-Z]{2})([a-zA-Z]{2})(poda.*?$)/; system("mv $_ $1-$2_$3")'
I get
sh: $'32mPMSNpoda5718_1p2g_out_fst.txt\E[0m': command not found mv: missing destination file operand after ''$'\033''[01' Try 'mv --help' for more information. sh: $'32mSCSNpoda5718_1p2g_out_fst.txt\E[0m': command not found mv: missing destination file operand after ''$'\033''[01' Try 'mv --help' for more information.
Again but adding echo
ls *fst.txt | perl -lne '/([a-zA-Z]{2})([a-zA-Z]{2})(poda.*?$)/; system("echo mv $_ $1-$2_$3")'
I get
mv h: $'32mPMSNpoda5718_1p2g_out_fst.txt\E[0m': command not found mv h: $'32mSCSNpoda5718_1p2g_out_fst.txt\E[0m': command not found
Can someone point me which is the error so I can understand what I'm doing wrong?
Thanks! | http://quabr.com/56744498/dos-ren-command-with-wildcard | CC-MAIN-2019-30 | refinedweb | 1,217 | 57.87 |
cochl_sense 1.1.0
cochl_sense: ^1.1.0 copied to clipboard
Sense Dart #
API Library for Dart with audio analysis and recognition solutions from Cochlear.ai
Overview #
Sense API enables developers to extract various non-verbal information from an audio input with the power of audio processing and neural network techniques. It is robust against noises and different types of recording environments, so it can be used for analyzing input audio from various IoT devices such as smart speakers or IP cameras, not to mention its potential usage in searching through video clips.
To date, Sense API is the only publicly available API online for machine listening, a rapidly emerging technology. It supports both prerecorded audio and real-time streaming as inputs, and multiple audio encodings are supported including mp3, wav, and FLAC.
1. Add Dependency #
Add this to your package's pubspec.yaml file:
dependencies: cochl_sense: ^1:cochl_sense/cochl_sense.dart';
4. Get API Key #
Go to
Then sign up and get 10 dollars free of charge.
Usage #
Import the library.
import 'package:cochl_sense/cochl_sense.dart'; final apiKey = "< Get api key from >";
1. Analyze audio files
file represents a class that can inference audio coming from an audio file.
An audio file is any source of audio data which duration is known at runtime. Because duration is known at runtime, server will wait for the whole file to be received before to start inferencing. All inferenced data will be received in one payload.
A file can be for instance, a mp3 file stored locally, a wav file accessible from an url etc...
So far wav, flac, mp3, ogg, mp4 are supported.
If you are using another file encoding format, let us know at support@cochlear.ai so that we can priorize it in our internal roadmap.
File implements the following interface :
class file { Future<Result> inference() async => Result; }
When calling inference, a GRPC connection will be established with the backend, audio data of the File will be sent and a Result instance will be returned in case of success (described bellow).
Note that network is not reached until inference method is called.
Note that inference can be called only once per file instance.
To create a file instance, you need to use a fileBuilder instance. fileBuilder is following the builder pattern and calling its build method will create a file instance.
fileBuider implements the following interface :
class fileBuilder { //api key of cochlear.ai projects available at void withApiKey(String apiKey) => fileBuilder; //data reader to the file data void withReader(String reader) => fileBuilder; //format of the audio file : can be mp3, flac, wav, ogg, etc... void withFormat(String format) => fileBuilder; //host address that performs grpc communication. //If this method is not used, default host is used. void withHost(String host) => fileBuilder; //activate or not smart filtering (default false) void withSmartFiltering(Booolean smartFiltering) => fileBuilder; //creates a File instance file build(); }
2. Analyze audio stream
stream represents a class that can inference audio coming from an audio stream.
An audio stream is any source of data which duration is not known at runtime. Because duration is not known, server will inference audio as it comes. One second of audio will be required before the first result to be returned. After that, one result will be given every 0.5 second of audio.
A stream can be for instance, the audio data comming from a microphone, audio data comming from a web radio etc...
Streams can be stopped at any moment while inferencing.
For now, the only format that is supported for streaming is a raw data stream (PCM float32 stream). Raw data being sent has to be a mono channel audio stream.
Its sampling rate has to be given to describe the raw audio data.
For best performance, we recommend using a sampling rate of 22050Hz and data represented as float32.
Multiple results will be returned by calling a callback function.
If you are using another stream encoding format that is not supported, let us know at support@cochlear.ai so that we can priorize it in our internal roadmap.
Stream implements the following interface :
class stream { Stream inference() async* => Result; }
When calling inference, a GRPC connection will be established with the backend, audio data of the stream will be sent every 0.5s. Once result is returned by the server, the callback function is called.
Note that network is not reached until inference method is called.
Note that inference can be called only once per stream instance.
To create a stream instance, you need to use a streamBuilder instance. streamBuilder is following the builder pattern and calling its build method will create a stream instance.
streamBuilder implements the following interface :
class streamBuilder { //api key of cochlear.ai projects available at dashboard.cochlear.ai void withApiKey(String apiKey) => streamBuilder; //data of the pcm stream void withStreamer(Stream<List<num>> streamer) => streamBuilder; //max number of events from previous inference to keep in memory void withMaxEventsHistorySize(int n) => streamBuilder; //sampling rate of the pcm stream void withSamplingRate(int samplingRate) => streamBuilder; //type of the pcm float32 stream void withDataType(String dataType) => streamBuilder; //host address that performs grpc communication. //If this method is not used, default host is used. void withHost(String host) => streamBuilder; //activate or not smart filtering (default false) void withSmartFiltering(Booolean smartFiltering) => fileBuilder; //creates a stream instance stream build(); }
Note that withApiKey, withDataType, withSamplingRate and withStreamer method needs to be called before calling the build method, otherwise an error will be thrown.
3. Result
Result is a class that is returned by both file and stream when calling inference method.
Multiple results will be returned by a stream by calling a callback function. For a file only one result will be returned.
Result implements the following interface :
class Result { //returns all events List<Event> allEvents(); //returns all events that match the "filter function" defined below List<Event> detectedEvents(); //group events that match the "filter function" and shows segments of time of when events were detected Map detectedEventsTiming(); //return only the "tag" of the event that match the "filter" function List detectedTags(); //returns the service name : "human-interaction" or "emergency" for instance String service(); //returns a raw json object containing service name and an array of events Map<String, dynamic> toJson (); //use a filter function : that function takes an event as input and return a boolean. An event will be "detected" if the filter function returns true for that event //the default filter is to consider all events as detected. So by default, allEvents() and detectedEvents() will return the same result bool useDefaultFilter(Event event); //where filter is a function that takes an event in input and returns a boolean bool filter(Event event); }
Note that if you are inferencing a stream, multiple results will be returned. By default, calling allEvents() will only returned the newly inferenced result. It's possible to keep track of previous events of the stream. To do so, call the withMaxEventsHistorySize method on the streamBuilder class. Its default value is 0, and increasing it will allow to "remember" previous events.
4. Event
An event contains the following data :
class Event { //name of the detected event var tag; //probability for the event to happen. Its values is between 0 and 1 var probability; //start timestamp of the detected event since the beginning of the inference var startTime; //end timestamp of the detected event since the beginning of the inference var endTime; } | https://pub.dev/packages/cochl_sense | CC-MAIN-2022-40 | refinedweb | 1,230 | 53.51 |
For an introduction to WSMQ, see my blog category here.
To use WSMQ from a .NET app, you'll need to install WSE 2.0, as WSMQ uses WSE Authentication for security. Get a copy from Microsoft here.
So, how do you create a Queue using WSMQ? The easiest way is through code.
Add a reference to the WSMQ Service (right click References ... Add web reference) in your VS project, then add the following using statements to your class:
using Microsoft.Web.Services2.Security;using Microsoft.Web.Services2.Security.Tokens;using localhost; // Or whatever gets you to the service
Next, create a secure request. If you're going to be calling this multiple times, you may want to wrap this code in a helper method which returns the reference to the service proxy. If you've properly installed WSE, you should see the MessageQueueServiceWse proxy. The code to create the request looks like this:
MessageQueueServiceWse mqs =
Next, create a CreateQueueRequest to create the queue for the first time, your app should only do this of course if it can't open the existing queue using an OpenQueueRequest();
CreateQueueRequest cqr = new CreateQueueRequest();cqr.HasDeadLetter = true;cqr.HasJournal = true;cqr.IsPrivate = false;cqr.QueueName = “My First WSMQ Queue“;mqs.CreateMessageQueue(cqr);
Finally, create a SendQueueRequest to actually send your message:
SendQueueRequest qr =
Now, if you check the Queue XML file in your Queues directory, you should see your message. In this example the message is a simple string, but you can also queue any XML serializable object this way. For example using a serialization helper like this one here, you can serialize an object before adding the serialized XML to the message like so.
qr.Message = SerializationHelper.XmlSerialize(
Finally, to receive your message, just do this:
QueueRequest qr = new QueueRequest();qr.QueueName = “My First WSMQ Queue“;string s = mqs.Receive(qr);
That should get you started, there's more to it, like using asynchronous sending and receiving, but those are the basics...
| http://codebetter.com/blogs/brendan.tompkins/archive/2004/09/02/24247.aspx | crawl-002 | refinedweb | 330 | 56.35 |
In order to get developers to write Java applications, the UI toolkit has to be easy to learn and use, flexible and extensible, perform well, and be easy to deploy. And lets face it, Swing has its share of issues - its slow, hard to use
for beginners, requires a lot of customization, and more. At the same time, Swing is a very powerful user interface package with great flexibility for almost limitless customization. There are a lot of reasons to use Java, but not
without a sufficient UI toolkit. (This discussion is co-hosted by Joshua Marinacci and Jonathan Simon.)
Discussion Moderator:
Jonathan Simon
Showing messages 1 through 148 of 148.
There has been a lot of good discussion about the direction of Swing
on this forum. So far, the suggestions break down into two categories:
suggestions for the community at large, and suggestions for
the Swing team and Sun.
Joshy started a wiki
page for Swing information that I think is a good starting point
for us getting together as a community to make
Swing development easier. I think there are a number of places we can
go from there -- but it's still a good starting point.
I think we are at a point where we could write an open letter from
the Swing community to Sun. This could lead to a a more formalized
dialog with the Swing team and Sun with regards to prioritization of
enhancements and bugs one step up from the "Bug Parade." An open
letter may bring the issue to the forefront with Sun the same way we
have discussed it publicly these past few weeks on this forum.
I'd like people to respond in this thread with suggestions that the Swing team can do as well as what we can do as a community. Next week, we will have a vote and I will post the letter on this forum with the results. After comments and suggestions to the letter, we'll post it on java.net.
-jonathan
The java doc don't help you to use the classes well, because they lack context. Many methods need to be used at the right time, not any old time.
examples help provide some of that context. The ones found in the tutorial or most Swing books are limited, though. They show you how to use one widget in a toy setting. This teaches how to use the widget but not how to build an app. In addition, examples usually lack any discussion of design. Knowing why we structure some code one way helps teach how to handle other widgets in similar circumstances
I think Swing needs something like "Core J2EE Patterns" - a book which discusses complicated examples and explains the hows and the whys.
Why do you say that?
My take is that Sun has to do what only sun can do - and they need to do it fast!
For example, bugs in the core Swing and AWT objects have to be fixed by Sun. Even if the community got together and fixed those bugs, we wouldn'y be legally allowed to distribute them. Other popular topics like increasing performance, decreasing startup time, improving deployment, all fall under this category as well.
On the other hand, things like creating better documentation or examples, we can do. We can also create a Swing wrapper if we really wanted to. We could also make other components like a really happening JTreeTable if we wanted.
Dont get me wrong -- in my perfect world, Swing would come out of the box with all of the components I need that do everything I want, with the grooviest documentation
imaginable.
Its really a question of priorities -- and I think sun should start by doing the stuff that we cant.
Im particularly interested to see how people feel about this topic.
As I've already said here, I always consider the fact that my users dont know my application is Java based to be a strong point. I think that a cross platform application should act appropriately in whatever environment it's running in, not necessarily identical across platforms. This may mean slight modifications in functionality between operating systems.
This gets back to the question of whether native L&F's are more important than Java specific L&F's in general. It also is central to the point of heavyweight vs. lightweight components.
So. I come from the native-L&F's-should-be-perfected-and-Java-L&F's-are-secondary camp. Where does everyone else stand?
-jonathan</>
And why do I have so many things to initialize layout? Why can't layouts just work? Why can't I just nest HBoxLayouts into VBoxLayouts and vice versa (without the explicit panels)? Pain, pain, pain :-(
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.builder.DefaultFormBuilder;
import javax.swing.*;
import java.awt.*;
public class CodeSizeComparison {
public JPanel createFormLayout() {
JTextField name = new JTextField(20);
JTextField phone = new JTextField(20);
JTextField fax = new JTextField(20);
JTextField email = new JTextField(20);
JTextField address = new JTextField(20);
FormLayout layout = new FormLayout("left:pref,4dlu,pref:grow", "");
DefaultFormBuilder builder = new DefaultFormBuilder( layout );
builder.setDefaultDialogBorder();
builder.append( "Name:", name );
builder.append( "Phone:", phone );
builder.append( "Fax:", fax );
builder.append( "Email:", email );
builder.append( "Address:", address );
return builder.getPanel();
}
public JPanel createGridbag:");
GridBagConstraints cc = new GridBagConstraints( 0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.BOTH, null, 0, 0);
Insets labelinsets = new Insets(5, 0, 0, 0 );
Insets fieldinsets = new Insets(5, 4, 0, 0 );
JPanel panel = new JPanel( new GridBagLayout() );
cc.insets = new Insets( 0, 0, 0, 0 );
panel.add( nameLabel, cc );
cc.weightx = 1.0;
cc.gridx = 1;
cc.insets = new Insets( 0, 4, 0, 0 );
panel.add( name, cc );
cc.gridx = 0;
cc.gridy = 1;
cc.weightx = 0.0;
cc.insets = labelinsets;
panel.add( phoneLabel, cc );
cc.gridx = 1;
cc.gridy = 1;
cc.weightx = 1.0;
cc.insets = fieldinsets;
panel.add( phone, cc );
cc.gridx = 0;
cc.gridy = 2;
cc.weightx = 0.0;
cc.insets = labelinsets;
panel.add( faxLabel, cc );
cc.gridx = 1;
cc.gridy = 2;
cc.weightx = 1.0;
cc.insets = fieldinsets;
panel.add( fax, cc );
cc.gridx = 0;
cc.gridy = 3;
cc.weightx = 0.0;
cc.insets = labelinsets;
panel.add( emailLabel, cc );
cc.gridx = 1;
cc.gridy = 3;
cc.weightx = 1.0;
cc.insets = fieldinsets;
panel.add( email, cc );
cc.gridx = 0;
cc.gridy = 4;
cc.weightx = 0.0;
cc.insets = labelinsets;
panel.add( addressLabel, cc );
cc.gridx = 1;
cc.gridy = 4;
cc.weightx = 1.0;
cc.insets = fieldinsets;
panel.add( address, cc );
panel.setBorder( BorderFactory.createEmptyBorder( 10, 10, 10, 10 ) );
return panel;
}
public JPanel createSpring:");
SpringLayout layout = new SpringLayout();
JPanel panel = new JPanel( layout );
panel.setBorder( BorderFactory.createEmptyBorder( 10, 10, 10, 10 ) );
panel.add( nameLabel );
panel.add( name );
panel.add( phoneLabel );
panel.add( phone );
panel.add( faxLabel );
panel.add( fax );
panel.add( emailLabel );
panel.add( email );
panel.add( addressLabel );
panel.add( address );
makeCompactGrid( panel, 5, 2, 0, 5, 5, 5);
return panel;
}
private SpringLayout.Constraints getConstraintsForCell(
int row, int col,
Container parent,
int cols) {
SpringLayout layout = (SpringLayout) parent.getLayout();
Component c = parent.getComponent(row * cols + col);
return layout.getConstraints(c);
}
public void makeCompactGrid(Container parent,
int rows, int cols,
int initialX, int initialY,
int xPad, int yPad) {
SpringLayout layout;
try {
layout = (SpringLayout)parent.getLayout();
} catch (ClassCastException exc) {
System.err.println("The first argument to makeCompactGrid must use SpringLayout.");
return;
}
//Align all cells in each column and make them the same width.
Spring x = Spring.constant(initialX);
for (int c = 0; c < cols; c++) {
Spring width = Spring.constant(0);
for (int r = 0; r < rows; r++) {
width = Spring.max(width,
getConstraintsForCell(r, c, parent, cols).
getWidth());
}
for (int r = 0; r < rows; r++) {
SpringLayout.Constraints constraints =
getConstraintsForCell(r, c, parent, cols);
constraints.setX(x);
constraints.setWidth(width);
}
x = Spring.sum(x, Spring.sum(width, Spring.constant(xPad)));
}
//Align all cells in each row and make them the same height.
Spring y = Spring.constant(initialY);
for (int r = 0; r < rows; r++) {
Spring height = Spring.constant(0);
for (int c = 0; c < cols; c++) {
height = Spring.max(height,
getConstraintsForCell(r, c, parent, cols).
getHeight());
}
for (int c = 0; c < cols; c++) {
SpringLayout.Constraints constraints =
getConstraintsForCell(r, c, parent, cols);
constraints.setY(y);
constraints.setHeight(height);
}
y = Spring.sum(y, Spring.sum(height, Spring.constant(yPad)));
}
//Set the parent's size.
SpringLayout.Constraints pCons = layout.getConstraints(parent);
pCons.setConstraint(SpringLayout.SOUTH, y);
pCons.setConstraint(SpringLayout.EAST, x);
}
public static void main(String[] args) throws Exception {
UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName() );
CodeSizeComparison comp = new CodeSizeComparison();
JFrame frame = new JFrame("Form Layout");
frame.setContentPane( comp.createFormLayout() );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.pack();
frame.setVisible( true );
JFrame gridFrame = new JFrame("Gridbag Layout");
gridFrame.setContentPane( comp.createGridbagLayout() );
gridFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
gridFrame.pack();
gridFrame.setVisible( true );
JFrame springFrame = new JFrame("Spring Layout");
springFrame.setContentPane( comp.createSpringLayout() );
springFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
springFrame.pack();
springFrame.setVisible( true );
}
}
Other parts of Swing just seem hacks generalized half-way. JTable for example seems to be made for displaying row sets from a DB. There are nice bits (the cell editors), but others are lacking (row headers, D&D of columns). I tried to use it for a spread-sheet like system, but then I decided against it.
And what about z-order? Is there any decent way to handle that? Other than removing and readding? And why do things get put at the bottom instead the front? That doesn't seem intuitive or useful to me.
For drawing programs I would suggest an API for handling widgets is a suboptimal approach. See the javax.swing.text package's discussion on use of View/Element instead of JComponent.
I started working in Swing about 9 months ago. I've found the learning curve steep, but not impossible. But there are a lot of loose ends in Swing, and it reduces your productivity because you have to work around them. Couple that with the fact that most business users have Windows machines, and it is hard to make a persuasive pitch to use Swing instead of Visual Studio
One way to make Swing easier is to have something like the J2EE Blueprints program for Swing.
I've blogged about my desire for a guidance book for Swing a few months back.
Just an idea.
Sadly, I've talked to several publishers about an advanced Swing book and they were all convinced there is no market for it. I do think there is a huge need for this, whether there is a market or not is a whole nother question...
I have looked for an advanced Swing book and would have bought it in a second. But I can see the publishers point of view. Here in the Boston area, there are few job postings which list Swing as a desired skill. (well, there a few postings, period. But this was true a 2 years ago as well)
"3.6 focused on 2 major things: the use of Windows L&F on Windows 2000 and XP (and updating the NetBeans design to look cool under those L&Fs), and introducing a brand-new window management system to streamline the way the IDE fits into the natural workflow of development."
Even though the context of this discussion is how to fix Swing -- saying that it can't be fixed is a perfectly valid response. IMHO, its not the case, but its certainly up for discussion.
I agree with you to an extent.
We developers are a strange breed -- we are users and engineers. We are users of the Swing API, but also the engineers responsible for filling in all of the gaps and holes and making sure the end application does what it needs to -- with out without the help of an API.
Now the UI thing is pretty interesting. For a UI toolkit to work -- it has to look and ACT perfectly native right out o fthe box. So the UI thing really is important -- not to us as users but to us as engineers to make sure that the user experience of our users is no differerent with our Java apps than any other desktop application.
And Im squarely on the record saying that the whole cross platform look and feel is a complete joke and cost Swing alot of credibility. Swing apps need to act like native apps. I've always used the benchmark that if a user knows I wrote the application in Java, I've failed. I think the cross platform LAF was an attempt to deemphisize the importance of the native operating systems. | http://www.java.net/cs/user/forum/cs_disc/1437 | crawl-002 | refinedweb | 2,097 | 60.51 |
Sometimes you're so familiar with a class you stop paying attention to it. If you could write the documentation for
java.lang.Foo, and Eclipse will helpfully autocomplete the functions for you, why would you ever need to read its Javadoc? Such was my experience with
java.lang.Math, a class I thought I knew really, really well. Imagine my surprise, then, when I recently happened to be reading its Javadoc for possibly the first time in half a decade and realized that the class had almost doubled in size with 20 new methods I'd never heard of. Obviously it was time to take another look.
Version 5 of the Java™ Language Specification added 10 new methods to
java.lang.Math (and its evil twin
java.lang.StrictMath), and Java 6 added another 10. In this article, I focus on the more purely mathematical functions provided, such as
log10 and
cosh. In Part 2, I'll explore the functions more designed for operating on floating point numbers
as opposed to abstract real numbers.
The distinction between an abstract real number such as π or 0.2 and a Java
double is an important one. First of all, the Platonic ideal of the number is infinitely precise, while the Java representation is limited to a fixed number of bits. This is important when you deal with very large and very small numbers. For example, the number 2,000,000,001 (two billion and one) can be represented exactly as an
int, but not as a
float. The closest you can get in a float is 2.0E9 — that is, two billion.
doubles do better because they have more bits (which is one reason you should almost always use
doubles instead of
floats); but there are still practical limits to how accurate they can be.
The second limitation of computer arithmetic (the Java language's and others') is that it's based on binary rather than decimal. Fractions such as 1/5 and 7/50 that can be represented exactly in decimal (0.2 and 0.14, respectively) become repeating fractions when expressed in binary notation. This is exactly like the way 1/3 becomes 0.3333333... when expressed in decimal. In base 10, any fraction whose denominator has the prime factors 5 and 2 (and no others) is exactly expressible. In base 2, only fractions whose denominators are powers of 2 are exactly expressible: 1/2, 1/4, 1/8, 1/16, and so on.
These imprecisions are one of the big reasons a math class is needed in the first place. Certainly you could define the trigonometric and other functions with Taylor series expansions using nothing more than the standard + and * operators and a simple loop, as shown in Listing 1:
Listing 1. Calculating sines with a Taylor series
public class SineTaylor { public static void main(String[] args) { for (double angle = 0; angle <= 4*Math.PI; angle += Math.PI/8) { System.out.println(degrees(angle) + "\t" + taylorSeriesSine(angle) + "\t" + Math.sin(angle)); } } public static double degrees(double radians) { return 180 * radians/ Math.PI; } public static double taylorSeriesSine(double radians) { double sine = 0; int sign = 1; for (int i = 1; i < 40; i+=2) { sine += Math.pow(radians, i) * sign / factorial(i); sign *= -1; } return sine; } private static double factorial(int i) { double result = 1; for (int j = 2; j <= i; j++) { result *= j; } return result; } }
This starts off well enough with only a small difference, if that, in the last decimal place:
0.0 0.0 0.0 22.5 0.3826834323650897 0.3826834323650898 45.0 0.7071067811865475 0.7071067811865475 67.5 0.923879532511287 0.9238795325112867 90.0 1.0000000000000002 1.0
However, as the angles increase, the errors begin to accumulate, and the naive approach no longer works so well:
630.0000000000003 -1.0000001371557132 -1.0 652.5000000000005 -0.9238801080153761 -0.9238795325112841 675.0000000000005 -0.7071090807463408 -0.7071067811865422 697.5000000000006 -0.3826922100671368 -0.3826834323650824
The Taylor series here actually proved more accurate than I expected. However as the
angle increases to 360 degrees, 720 degrees (4 pi radians), and more, the Taylor series requires progressively more terms for accurate computation. The more sophisticated algorithms used by
java.lang.Math avoid this.
The Taylor series is also inefficient compared to the built-in sine function of a modern desktop chip. Proper calculations of sine and other functions that are both accurate and fast require very careful algorithms designed to avoid accidentally turning small errors into large ones. Often these algorithms are embedded in hardware for even faster performance. For example, almost every X86 chip shipped in the last 10 years has hardware implementations of sine and cosine that the X86 VM can just call, rather than calculating them far more slowly based on more primitive operations. HotSpot takes advantage of these instructions to speed up trigonometry operations dramatically.
Right triangles and Euclidean norms
Every high school geometry student learns the Pythagorean theorem: the square of the length of hypotenuse of a right triangle is equal to the sum of the squares of the lengths of the legs. That is, c2 = a2 + b2
Those of us who stuck it out into college physics and higher math learned that this equation shows up a lot more than in just right triangles. For instance, it's also the square of the Euclidean norm on R2, the length of a two-dimensional vector, a part of the triangle inequality, and quite a bit more. (In fact, these are all really just different ways of looking at the same thing. The point is that Euclid's theorem is a lot more important than it initially looks.)
Java 5 added a
Math.hypot function to perform exactly this calculation, and it's a good example of why a library is helpful. The naive approach would look something like this:
public static double hypot(double x, double y){ return Math.sqrt (x*x + y*y); }
The actual code is somewhat more complex, as shown in Listing 2. The first thing you'll note is that this is written in native C code for maximum performance. The second thing you should note is that it is going to great lengths to try to minimize any possible errors in this calculation. In fact, different algorithms are being chosen depending on the relative sizes of
x and
y.
Listing 2. The real code that implements
Math.hypot
/* * ==================================================== * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. * * Developed at SunSoft, a Sun Microsystems, Inc. business. * Permission to use, copy, modify, and distribute this * software is freely granted, provided that this notice * is preserved. * ==================================================== */ #include "fdlibm.h" #ifdef __STDC__ double __ieee754_hypot(double x, double y) #else double __ieee754_hypot(x,y) double x, y; #endif { double a=x,b=y,t1,t2,y1,y2,w; int j,k,ha,hb; ha = __HI(x)&0x7fffffff; /* high word of x */ hb = __HI(y)&0x7fffffff; /* high word of y */ if(hb > ha) {a=y;b=x;j=ha; ha=hb;hb=j;} else {a=x;b=y;} __HI(a) = ha; /* a <- |a| */ __HI(b) = hb; /* b <- |b| */ if((ha-hb)>0x3c00000) {return a+b;} /* x/y > 2**60 */ k=0; if(ha > 0x5f300000) { /* a>2**500 */ if(ha >= 0x7ff00000) { /* Inf or NaN */ w = a+b; /* for sNaN */ if(((ha&0xfffff)|__LO(a))==0) w = a; if(((hb^0x7ff00000)|__LO(b))==0) w = b; return w; } /* scale a and b by 2**-600 */ ha -= 0x25800000; hb -= 0x25800000; k += 600; __HI(a) = ha; __HI(b) = hb; } if(hb < 0x20b00000) { /* b < 2**-500 */ if(hb <= 0x000fffff) { /* subnormal b or 0 */ if((hb|(__LO(b)))==0) return a; t1=0; __HI; __HI(a) = ha; __HI(b) = hb; } } /* medium size a and b */ w = a-b; if (w>b) { t1 = 0; __HI(t1) = ha; t2 = a-t1; w = sqrt(t1*t1-(b*(-b)-t2*(a+t1))); } else { a = a+a; y1 = 0; __HI(y1) = hb; y2 = b - y1; t1 = 0; __HI(t1) = ha+0x00100000; t2 = a - t1; w = sqrt(t1*y1-(w*(-w)-(t1*y2+t2*b))); } if(k!=0) { t1 = 1.0; __HI(t1) += (k<<20); return t1*w; } else return w; }
Actually, whether you end up in this particular function or one of a few other similar ones depends on details of the JVM on your platform. However, more likely than not this is the code that's invoked in Sun's standard JDK. (Other implementations of the JDK are free to improve on this if they can.)
This code (and most of the other native math code in Sun's Java Development Library) comes
from the open source
fdlibm library written at Sun about 15 or
so years ago. This library is designed to implement the IEE754 floating point precisely and to have very accurate calculations, even at the cost of some performance.
Logarithms in base 10
A logarithm tells you what power a base number must be raised to in order to produce a given value. That is, it is the inverse of the
Math.pow() function. Logs base 10 tend to appear in engineering applications. Logs base e (natural logarithms) appear in the calculation of compound interest, and numerous scientific and mathematical applications. Logs base 2 tend to show up in algorithm analysis.
The
Math class has had a natural logarithm function since Java 1.0. That is, given an argument x, the natural logarithm returns the power to which e must be raised to give the value x. Sadly, the Java language's (and C's and Fortran's and Basic's) natural logarithm function is misnamed as
log(). In every math textbook I've ever read, log is a base-10 logarithm, while ln is a base e logarithm and lg is a base-2 logarithm. It's too late to fix this now, but Java 5 did add a
log10() function that takes the logarithm base 10 instead of base e.
Listing 3 is a simple program to print the log-base 2, 10, and e of the integers from 1 to 100:
Listing 3. Logarithms in various bases from 1 to 100
public class Logarithms { public static void main(String[] args) { for (int i = 1; i <= 100; i++) { System.out.println(i + "\t" + Math.log10(i) + "\t" + Math.log(i) + "\t" + lg(i)); } } public static double lg(double x) { return Math.log(x)/Math.log(2.0); } }
Here are the first 10 rows of the output:
1 0.0 0.0 0.0 2 0.3010299956639812 0.6931471805599453 1.0 3 0.47712125471966244 1.0986122886681096 1.584962500721156 4 0.6020599913279624 1.3862943611198906 2.0 5 0.6989700043360189 1.6094379124341003 2.321928094887362 6 0.7781512503836436 1.791759469228055 2.584962500721156 7 0.8450980400142568 1.9459101490553132 2.807354922057604 8 0.9030899869919435 2.0794415416798357 3.0 9 0.9542425094393249 2.1972245773362196 3.1699250014423126 10 1.0 2.302585092994046 3.3219280948873626
Math.log10() has the usual caveats of logarithm functions: taking the log of 0 or any negative number returns NaN.
Cube roots
I can't say that I've ever needed to take a cube root in my life, and I'm one of those
rare people who does use algebra and geometry on a daily basis, not to mention the occasional foray into calculus, differential equations, and even abstract algebra. Consequently, the usefulness of this next function escapes me. Nonetheless, should you find an unexpected need to take a cube root somewhere, you now can — as of Java 5 — with the
Math.cbrt() method. Listing 4 demonstrates by taking the cube roots of the integers from -5 to 5:
Listing 4. Cube roots from -5 to 5
public class CubeRoots { public static void main(String[] args) { for (int i = -5; i <= 5; i++) { System.out.println(Math.cbrt(i)); } } }
Here's the output:
-1.709975946676697 -1.5874010519681996 -1.4422495703074083 -1.2599210498948732 -1.0 0.0 1.0 1.2599210498948732 1.4422495703074083 1.5874010519681996 1.709975946676697
As this output demonstrates, one nice feature of cube roots compared to square roots: Every real number has exactly one real cube root. This function only returns NaN when its argument is NaN.
The hyperbolic trigonometric functions
The hyperbolic trigonometric functions are to hyperbolae as the trigonometric functions are to circles. That is, imagine you plot these points on a Cartesian plane for all possible values of t:
x = r cos(t) y = r sin(t)
You will have drawn a circle of radius r. By contrast, suppose you instead use sinh and cosh, like so:
x = r cosh(t) y = r sinh(t)
You will have drawn a rectangular hyberbola whose point of closest approach to the origin is r.
Another way of thinking of it: Where sin(x) can be written as (eix - e-ix)/2i and cos(x) can be written as (eix + e-ix)/2 , sinh and cosh are what you get when you remove the imaginary unit from those formulas. That is, sinh(x) = (ex - e-x)/2 and cosh(x) = (ex + e-x)/2.
Java 5 adds all three:
Math.cosh(),
Math.sinh(), and
Math.tanh(). The inverse hyperbolic trigonometric functions — acosh, asinh, and atanh — are not yet included.
In nature, cosh(z) is the equation for the shape of a hanging rope connected at two ends, known as a catenary. Listing 5 is a simple program that draws a catenary using the
Math.cosh function:
Listing 5. Drawing a catenary with
Math.cosh()
import java.awt.*; public class Catenary extends Frame { private static final int WIDTH = 200; private static final int HEIGHT = 200; private static final double MIN_X = -3.0; private static final double MAX_X = 3.0; private static final double MAX_Y = 8.0; private Polygon catenary = new Polygon(); public Catenary(String title) { super(title); setSize(WIDTH, HEIGHT); for (double x = MIN_X; x <= MAX_X; x += 0.1) { double y = Math.cosh(x); int scaledX = (int) (x * WIDTH/(MAX_X - MIN_X) + WIDTH/2.0); int scaledY = (int) (y * HEIGHT/MAX_Y); // in computer graphics, y extends down rather than up as in // Caretesian coordinates' so we have to flip scaledY = HEIGHT - scaledY; catenary.addPoint(scaledX, scaledY); } } public static void main(String[] args) { Frame f = new Catenary("Catenary"); f.setVisible(true); } public void paint(Graphics g) { g.drawPolygon(catenary); } }
Figure 1 shows the drawn curve:
The sinh, cosh, and tanh functions also all appear in various calculations in special and general relativity.
Signedness
The
Math.signum function converts positive numbers into 1.0,
negative numbers into -1.0, and zeroes into zeroes. In essence, it extracts just the sign from a number. This can be useful when you're implementing the
Comparable interface.
There's a
float and a
double version
to maintain the type. The reason for this rather obvious function is to handle special
cases of floating-point math, NaN, and positive and negative zero. NaN is also treated
like zero, and positive and negative zero should return positive and negative zero. For example, suppose you were to implement this function naively as in Listing 6:
Listing 6. Buggy implementation of
Math.signum
public static double signum(double x) { if (x == 0.0) return 0; else if (x < 0.0) return -1.0; else return 1.0; }
First, this method would turn all negative zeroes into positive zeroes. (Yes, negative zeroes are a little weird, but they are a necessary part of the IEEE 754 specification.) Second, it would claim that NaN is positive. The actual implementation shown in Listing 7 is more sophisticated and careful for handling these weird corner cases:
Listing 7. The real, correct implementation of
Math.signum
public static double signum(double d) { return (d == 0.0 || isNaN(d))?d:copySign(1.0, d); } public static double copySign(double magnitude, double sign) { return rawCopySign(magnitude, (isNaN(sign)?1.0d:sign)); } public static double rawCopySign(double magnitude, double sign) { return Double.longBitsToDouble((Double.doubleToRawLongBits(sign) & (DoubleConsts.SIGN_BIT_MASK)) | (Double.doubleToRawLongBits(magnitude) & (DoubleConsts.EXP_BIT_MASK | DoubleConsts.SIGNIF_BIT_MASK))); }
Do less, get more
The most efficient code is the code you never write. Don't do for yourself what experts have already done. Code that uses the
java.lang.Math functions, new and old, will be faster, more efficient, and more accurate than anything you write yourself. Use it.
Resources
Learn
- "Java's new math, Part 2: Floating-point numbers" (Elliotte Rusty Harold, developerWorks, January 2008): Don't miss the second installment of this series, which explores the functions designed for operating on floating-point numbers.
- Types, Values, and Variables: Chapter 4 of the Java Language Specification covers floating point arithmetic.
- IEEE standard for binary floating-point arithmetic: The IEEE 754 standard defines floating-point arithmetic in most modern processors and languages, including the Java language.
java.lang.Math: Javadoc for the class that provides the functions discussed in this article.
- Bug 5005861: A disappointed user requests faster trigonometric functions in the JDK.
- Catenary: Wikipedia explains the history of and math behind the catenary.
- Browse the technology bookstore for books on these and other technical topics.
- developerWorks Java technology zone: Find hundreds of articles about every aspect of Java programming.
Get products and technologies
fdlibm: A C math library for machines that support IEEE 754 floating-point, is available from the Netlib mathematical software repository.
- OpenJDK: Look into the source code of the math classes inside this open source Java SE implementation.. | http://www.ibm.com/developerworks/java/library/j-math1/index.html?ca=drs- | CC-MAIN-2014-42 | refinedweb | 2,878 | 64.41 |
Android.OS.Handler Class
Syntax
public class Handler : Object: (1) to schedule messages and runnables to be executed as some point in the future; and (2) to enqueue an action to be performed on a different thread than your own.
Scheduling messages is accomplished with the Handler.Post(IRunnable), Handler.PostAtTime(IRunnable,Int64), Handler.PostDelayed(IRunnable,Int64), Handler.SendEmptyMessage(Int32), Handler.SendMessage(Message), Handler.SendMessageAtTime(Message,Int64), and Handler.SendMessageDelayed(Message,Int64) methods. The post versions allow you to enqueue Runnable objects to be called by the message queue when they are received; the sendMessage versions allow you to enqueue a Message object containing a bundle of data that will be processed by the Handler's Handler.HandleMessage(Message) method (requiring that you implement a subclass of Handler).
When posting or sending to a Handler, you can either allow the item to be processed as soon as the message queue is ready to do so, or specify a delay before it gets processed or absolute time for it to be processed. The latter two allow you to implement timeouts, ticks, and other timing-based behavior.. This is done by calling the same post or sendMessage methods as before, but from your new thread. The given Runnable or Message will then be scheduled in the Handler's message queue and processed when appropriate.
Requirements
Assembly: Mono.Android (in Mono.Android.dll)
Assembly Versions: 0.0.0.0
Since: Added in API level 1
The members of Android.OS.Handler are listed below. | https://developer.xamarin.com/api/type/Android.OS.Handler/ | CC-MAIN-2019-04 | refinedweb | 251 | 55.64 |
#include <sys/types.h> #include <sys/buf.h> #include <sys/uio.h> #include <sys/aio_req.h> #include <sys/ddi.h> #include <sys/sunddi.h> int aphysio(int (*strat)( struct buf *), int (*cancel)(struct buf *), dev_t dev, int rw, void (*mincnt)(struct buf *), struct aio_req *aio_reqp);
Pointer to device strategy routine.
Pointer to driver cancel routine. Used to cancel a submitted request. The driver must pass the address of the function anocancel(9F) because cancellation is not supported.
The device number.
Read/write flag. This is either B_READ when reading from the device or B_WRITE when writing to the device.
Routine which bounds the maximum transfer unit size.
Pointer to the aio_req(9S) structure which describes the user I/O request.
Solaris DDI specific (Solaris DDI).
aphysio() performs asynchronous I/O operations between the device and the address space described by aio_reqp→aio_uio.
Prior to the start of the transfer, aphysio() verifies the requested operation is valid. It then locks the pages involved in the I/O transfer so they can not be paged out. The device strategy routine, strat, is then called one or more times to perform the physical I/O operations. aphysio() does not wait for each transfer to complete, but returns as soon as the necessary requests have been made.
aphysio() calls mincnt to bound the maximum transfer unit size to a sensible default for the device and the system. Drivers which do not provide their own local mincnt routine should call aphysio() with minphys(9F). minphys(9F) is the system mincnt routine. minphys(9F) ensures the transfer size does not exceed any system limits.
If a driver supplies a local mincnt routine, this routine should perform the following actions:
If bp→b_bcount exceeds a device limit, physio() returns ENOTSUP.
Call aminphys(9F) to ensure that the driver does not circumvent additional system limits. If aminphys(9F) does not return 0, return ENOTSUP.
aphysio() returns:
Upon success.
Upon failure.
aphysio() can be called from user context only.
aread(9E), awrite(9E), strategy(9E), anocancel(9F), biodone(9F), biowait(9F), minphys(9F), physio(9F), aio_req(9S), buf(9S), uio(9S)
Writing Device Drivers for Oracle Solaris 11.2
It is the driver's responsibility to call biodone(9F) when the transfer is complete.
Cancellation is not supported in this release. The address of the function anocancel(9F) must be used as the cancel argument. | http://docs.oracle.com/cd/E36784_01/html/E36886/aminphys-9f.html | CC-MAIN-2015-27 | refinedweb | 396 | 60.31 |
Re: [rest-discuss] Re: WADL pushback
Expand Messages
- View SourceOn 13 Jul 2007, at 02:46, Elliotte Harold wrote:
> A. Pagaltzis wrote:I agree very much. Languages are usually defined as a syntax with a
>
> > Impendance mismatch with my language’s data model is not a
> > feature, it’s a liability.
>
> Serialized formats that are tied to one language are a liability,
> not a
> feature.
>
semantics. What is needed is to disassociate the
syntax from the semantics. If we keep the semantics stable, as we do
by choosing to work with URIs (which are universal names - names
name things), we can change the syntax and allow a natural selection
of syntaxes. JSON with a good mapping could be an interesting syntax.
But in fact JSON is only half way there. Let us look at an example
from the JSON wikipedia page:
{
"firstName": "John",
"lastName": "Smith",
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
},
"phoneNumbers": [
"212 732-1234",
"646 123-4567"
]
}
(Now reading the spec, it says that an "object is an unordered set of
name-value pairs". That means it cannot be a hash map since a hash
map forces only single keys, and there is no restriction there on
single keys. Seems to me that if you map that into an object in a
simplistic way, you are going to loose data.)
Now.
As I mention elsewhere, the other problem is the lack of identity of
things. "firstName" is a relation relating to what we can clearly see
to be a Person object to the string "John". What if somewhere else I
find a french site that has "prenom" and "nom" instead. How can I say
that these two words refer to the same relation? I can't really
because there is so much that is underspecified.
In fact the more I look at the example the more I notice the same
provincialism that lead to all the problems with xmlrpc [1] such as
that XML-RPC not defining a time zone for dates. When working on the
internet you have to think globally, or else you are still stuck in
client-server mode of thinking. Just as the xmlrpc folk never seemed
to have realized that the world may have more than one time zone, so
it is clear that JSON was not designed with the thought that data
would be traveling in a global space with no context (you know on the
web you can link any two resources together, so you don't know ahead
of time where people are going to come from, and how they are going
to mesh up the data). This should not be surprising because
javascript is a scripting language that is meant to only work within
a page. Other provincialisms of the example above is to assume that a
post code is a number. Clearly they have never lived in the UK! Or to
give phone numbers out without a country prefix! Oh my god! people on
the internet may find this information from another country? Well
should they not know that the US prefix is +1? Yeah! I was in Prague
recently and the people there assumed everywhere that you knew not
just the country prefix, but what the local Prague prefix was mean to
be. You want to book a hotel in Prague from another country? You must
be crazy.
Let me rewrite the above example in the Turtle subset of N3, and also
give the person a name:
@prefix : <> .
@prefix contact: <> .
<>
a :Person;
:firstName "John";
:family_name "Smith";
contact:home [
contact:address [
contact:city "New York";
contact:country "New York";
contact:postalCode "10021";
contact:street "21 2nd Street";
]
];
foaf:phone <tel:+1-212-732-1234>, <tel:+1-646-123-4567>;
.
Now this may require a little learning curve - but frankly not that
much - to understand. But it has the following advantages:
1. you can know what any of the terms mean by clicking on them
(append the prefix to the name) and do a GET
2. you can make statements of equality between relations and things,
such as
:firstname = frenchfoaf:prenom .
3. you can infer things from the above, such as that
<> a :Agent .
4. you can mix vocabularies from different namespaces as above, just
as in Java you can mix classes developed by
different organisations. There does not even seem to be the notion
of a namespace in JSON, so how would you reuse the work of others?
5. you can split the data about something in pieces. So you can put
your information about <> at the "
joe" URL, in a restful way, and other people can talk about him at
their URL. I could for example add the following to my foaf file:
<> :knows <
joe#p> .
You can't do that in a standard way in JSON because it does not
have a URI as a base type (weird for a language that wants to be a
web language, to miss the core element of the web! yet it has true,
false and numbers!)
Now that does not mean JSON can't be made to work right, as the
SPARQL JSON result set serialisation does [2]. But it does not do the
right thing by default. A bit like languages before Java that did not
have unicode support by default. You could do the right thing if you
knew a lot. But most people just got into bad habits instead.
Henry
[1] "Some of the many limitations of the MetaWeblog API":
[2]
>
> > If hash maps in my language can only
> > have unique keys, I want a format that enforces this constraint
> > at the parser level, so that ill-formed messages are defined out
> > of existence, freeing me from ever having to deal with them at a
> > higher level in the application.
>
> Serialized formats that restrict what you can say are a liability.
>
> XML usually lets you express what the data actually is, without too
> many
> contortions (at least until overlap rears its head). Hashtables
> don't. :-(
>
Sun Blog:
Foaf name:
- View Source* Elliotte Harold <elharo@...> [2007-07-21 14:52]:
> A. Pagaltzis wrote:Sure. All of the software I’ve written to date will spit stuff
> > * Elliotte Harold <elharo@...> [2007-07-17 01:00]:
> >> You're not supposed to put stuff arbitrary JavaScript into
> >> JSON, but people can and do.
> >
> > Then it’s not JSON anymore and JSON parsers will choke on it.
> > JSON is a computation-free subset of Javascript.
>
> Crackers don't play by the rules. They do not send only
> well-formed messages that adhere to the spec. Secure software
> has to be ready for absolutely any input, not just input that
> follows the spec.
back out if it purports to be JSON but contains Javascript code.
Because *none* of my code that uses JSON is Javascript.
Now how does that fit into your world view?
(And if it were JS, my statement would still hold true because
I wouldn’t use `eval` anyway.)
Let the crackers have at it. They’re not disturbing my sleep.
> That XML is so complex that you really need a true parser toRight. That’s why we had the billion laughs attack, and why XML
> handle it is a feature, not a bug. It discourages and mostly
> prevents the use of porr quality, hand-written solutions to
> handle it.
parsers can be caused to participate in a DDoS or to violate the
privacy of their users if you provide an address for an external
DTD.
Give me a JSON parser any day.
I know, the former is fixed in most parsers. The latter generally
has to be manually disabled from client code; most app developers
forget to toggle it appropriately.
> No one takes an arbitrary XML document and throws it into aThat’s a bug. Such code will fail to reject things that are not
> JavaScript interpreter. People do this with JSON all the time,
JSON.
> the language was deliberately designed to make this possible.Did Crockford actually say that somewhere? Citation?
And if that were so, why would JSON forbid syntactical variants
(such as keys with no quotes around them) that are valid in
Javascript?
Regards,
--
Aristotle Pagaltzis // <>
Your message has been successfully submitted and would be delivered to recipients shortly. | https://groups.yahoo.com/neo/groups/rest-discuss/conversations/topics/9469 | CC-MAIN-2014-15 | refinedweb | 1,377 | 71.55 |
Why Buffer? Because buffers cut you some slack.
Inevitably, in our recent series on microcontroller interrupts, the question of how to deal with actual serial data came up. In those examples, we were passing one byte at a time between the interrupt service routine (ISR) and the main body of code. That works great as long as the main routine can handle the incoming data in time but, as many people noted in the comments, if the main routine takes too long the single byte can get overwritten by a new one.
The solution? Make some storage room for multiple bytes so that they can stack up until you have time to process them. And if you couple this storage space with some simple rules for reading and writing, you’ve got yourself a buffer.
So read on to see how to implement a simple, straightforward circular buffer in C for microcontrollers (or heck, for anything). Buffers are such a handy tool to have in your programming toolkit that you owe it to yourself to get familiar with them if you’re not already.
Buffers
Generally speaking, you’ll want a buffer between two processes whenever they generate or handle data asynchronously or at different instantaneous rates. If data comes in slowly in individual bytes (as letters) but it’s more convenient to handle the data in bigger chunks (as words), a buffer is just what you need. Conversely, you might want to queue up a string from your main routine all at once and let the serial sending routine handle splitting it up into bytes and shuttling them along when it can.
In short, a buffer sits between two asynchronous routines and makes sure that either of them can act when they want without forcing the other routine to wait for it. If one process is a slow and steady tortoise, but the other is a bursty hare that needs to take frequent breaks to catch its breath, the buffer is the place where the data stacks up in the meantime.
The family of buffers that we’ll be interested in are buffers that makes sure that the data comes in and leaves in the same order. That is, we’ll be looking at first-in, first-out (FIFO) buffers. For a simple FIFO you can store your incoming data in the last free slot in an array, and read the data back out from the beginning of that array until you run out of data.
Note what’s great about even this simplest buffer; one process can be reading data off of the front of the array while the other is adding data on the back. They don’t overwrite each other and can both access the array in turns or in bursts. But eventually you run out of space at the end of the array, because the buffer only resets the writing position back to the first array element when it’s been fully read out.
This kind of linear buffer works great for situations where you’re likely to read out everything at once, but when the reading and writing are interleaved as shown here, you can run out of space in the array before it gets cleared out, while at the same time there’s “empty” space that’s already been read out in the front of the array.
The solution is a circular buffer, where the data can wrap back around to the beginning again to use up the extra space. Circular buffers are great because they make use of more of the allocated memory than the linear buffer and still preserve the FIFO ordering.
To make a circular buffer, we’ll need to keep track of the beginning (red) and end (green) of the buffer, and make up some simple rules to deal with wraparound and to keep us from overwriting existing data, but that’s about the gist of it.
Circular Buffers: Empty or.
So we’ll create two additional variables (indexes) to keep track of where the newest and oldest data elements are in our array. When the two indexes are the same, we’ll say that the buffer is empty. Each time we add data to the buffer, we’ll update the “newest” data index, and each time we pull data out, we’ll update the “oldest”.
If the buffer is empty when both of the indexes are the same, when is it full? This gets tricky, because when the array is completely full — every slot is filled — the oldest index and the newest index are equal to each other, which is just exactly the condition we wanted to use to test for it being empty. The easiest way, in my opinion, to deal with this is just to leave one slot empty at all times.
Watch the animation again, and notice that we declare the array “full” when it’s actually got one free space left in it just before the newest (green) index reaches the oldest (red). That is, we declare the buffer to be full when the newest index plus one is equal to the oldest, which keeps them from ever overlapping except when the buffer is empty. We lose the use of one slot in our buffer array, but it makes the full and empty states easy to distinguish.
There are a bunch of other ways to implement a circular buffer. In all, unless you’ve got seriously pressing optimization constraints, any of them are just fine. We’ll stick with “newest index / oldest index” because I find it most intuitive, but feel free to try them all out on your own. Let’s see it in action.
Code
So here’s what we need our code to do:
- Set aside some memory (we’ll use an array) to use for the buffer
- Keep track of the beginning (oldest entry) and the end (newest entry) of the data in our buffer
- Provide functions for storing and retrieving data from the buffer:
- Simplest methods use bytewise access
- Need to update the buffer indexes on read or write
- Nice to pass error codes when full / empty if trying to write / read
Off we go! First, we’ll set up the data.
#define BUFFER_SIZE 16 struct Buffer { uint8_t data[BUFFER_SIZE]; uint8_t newest_index; uint8_t oldest_index; };
If
structs are new to you, don’t fret. They just enable us to keep our three important bits of data together in one container, and to give that container a name, “Buffer”. Inside, we’ve got an array to store the data in, and two variables for the first and last active entries, respectively. Besides the obsessive-compulsive joys of keeping all our data in a nice, tight package, we’ll see that this pays off when we generalize the code a little bit later.
Writing
Now let’s write some data into the buffer. To do so, we first check to see if we’ve got space for a new entry: that is, we make sure that the
newest_index+1 doesn’t run into the
oldest_index. If it does, we’ll want to return a buffer full error. Otherwise, we just store the data in the next slot and update the
newest_index value.
enum BufferStatus bufferWrite(uint8_t byte){ uint8_t next_index = (buffer.newest_index+1) % BUFFER_SIZE; if (next_index == buffer.oldest_index){ return BUFFER_FULL; } buffer.data[buffer.newest_index] = byte; buffer.newest_index = next_index; return BUFFER_OK; }
Here you’ll see the first of two ways to refer to elements within a
struct, the
. (“member”) operator. If we want to refer to the
data array within our buffer
struct, we just write
buffer.data, etc.
Note that when we’re calculating the
next_index, we take the modulo with
BUFFER_SIZE. That does the “wrapping around” for us. If we have a 16-byte buffer, and we are at position fifteen, adding one gives us sixteen, and taking the modulo returns zero, wrapping us around back to the beginning. As we mentioned above, as long as we’re using a power-of-two buffer length, this modulo is actually computed very quickly — even faster than an
if statement would be.
OK, there’s one more (stylistic) detail I’ve swept under the rug. I like to handle the return codes from the buffer as an
enum, which allow us to assign readable names to the return conditions. Using an
enum doesn’t change anything in the compiled code in the end, but it makes it easier to follow along with the program logic.
enum BufferStatus {BUFFER_OK, BUFFER_EMPTY, BUFFER_FULL};
Internally, the compiler is substituting a zero for
BUFFER_OK, a one for
BUFFER_EMPTY, and a two for
BUFFER_FULL, but our code can use the longer text names. This keeps us from going insane trying to remember which return code we meant when returning a two.
Now notice what the return type of our
bufferWrite function is: a
BufferStatus enum. This reminds us that whenever we call that function, we should expect the same
enum — the same mapping from the underlying numbers to their text symbols. Unfortunately, GCC doesn’t typecheck enum values for us, so you’re on your honor here to do the right thing. (Other compilers will throw a warning.)
Reading
The
bufferRead function just about as straightforward. First we check if the
newest_index is the same as the
oldest_index, which signals that we don’t have any data in the buffer. If we do have data, we
enum BufferStatus bufferRead(uint8_t *byte){ if (buffer.newest_index == buffer.oldest_index){ return BUFFER_EMPTY; } *byte = buffer.data[buffer.oldest_index]; buffer.oldest_index = (buffer.oldest_index+1) % BUFFER_SIZE; return BUFFER_OK; }
This brings up an important C programming idiom. We want to get two things back from our
bufferRead function: the oldest byte from the buffer and a return code to go along with it. For reasons lost to time, probably having something to do with efficient programming on prehistoric PDP-8s or something, a C function can only really return a single value. If your function wants to return multiple values (as we do here), you’ve got to get crafty.
We haven’t really dug into pointers in Embed with Elliot, but here’s another standard use case. (For the first, see our post on pointer-based State Machines) The
bufferRead function returns a status code. So where does it store the data it read out of the buffer? Wherever we tell it to!
A pointer can be thought of as a memory address with a type attached to it. When we pass the pointer
uint8_t *byte to our function, we’re passing the memory address where we’d like the function to store our new data. Our main program declares a variable, and then when we call the
bufferRead function, we pass it the address of that variable, and the function then stores the new data into the memory address that corresponds to the variable in
main.
enum BufferStatus status; uint8_t byte_from_buffer; status = bufferRead(&byte_from_buffer); /* and now byte_from_buffer is modified */
The only potentially new thing here is the “address-of” operator,
&. So we call
bufferRead with the location in memory that our main routine is calling
byte_from_buffer, for instance, and the function writes the new byte into that memory location. Back in the calling function, we get our two variables: the
status value that’s passed explicitly, and the
byte_from_buffer that’s written directly into memory from inside the
bufferRead function.
And that’s about it. To recap: we used a
struct to combine the array and its two indices into one “variable”, mostly for convenience. Then we defined an
enum to handle the three possible return conditions from the reader and writer functions and make the return values readable. And finally, we wrote some simple reader and writer functions that stored or fetched data from the buffer, one byte at a time, updating the relevant index variable as necessary.
Refinements and Generalizations
As it stands right now, we’re storing the buffer as a global variable so that it can be accessed by our main routine and the read and write routines. As a result we can’t re-use our code on more than one buffer at a time, which is silly. For instance, if we were using the buffers for USART serial communication, we’d probably want a transmit and receive buffer. And once you get used to buffers, you’ll want them between any of your asynchronous code pieces. So we’ll need to generalize our functions a little bit so that we can define multiple buffers that will work with our reader and writer functions..
Fortunately, it’s easy. Two simple changes will allow us to re-use our
bufferRead and
bufferWrite functions on an arbitrary number of different buffers.
enum BufferStatus bufferWrite(volatile struct Buffer *buffer, uint8_t byte){ uint8_t next_index = (((buffer->newest_index)+1) % BUFFER_SIZE); if (next_index == buffer->oldest_index){ return BUFFER_FULL; } buffer->data[buffer->newest_index] = byte; buffer->newest_index = next_index; return BUFFER_OK; } enum BufferStatus bufferRead(volatile struct Buffer *buffer, uint8_t *byte){ if (buffer->newest_index == buffer->oldest_index){ return BUFFER_EMPTY; } *byte = buffer->data[buffer->oldest_index]; buffer->oldest_index = ((buffer->oldest_index+1) % BUFFER_SIZE); return BUFFER_OK; }
In both instances, instead of relying on a
buffer variable defined in the global namespace, we’re passing it to the function as an argument. Or, more accurately, we’re passing a pointer to a
Buffer structure to the function. We declare the buffer
volatile because we want to update the buffers using interrupt routines later. (See our article on volatile if you need a refresher.)
The other change is how we refer to the buffer
struct‘s elements. The problem is that we don’t pass the
struct itself, but a pointer to that
struct. So what we need is to get (“dereference”) that
struct first, and then access the
data element within it. The cumbersome way to to that goes like this:
(*buffer).data, but since this pattern occurs so often in C, a shortcut notation was developed:
buffer->data.
Receiving
Those two changes aside, the logic of the read and write code is exactly the same. So how do we use these functions? Glad you asked. Let’s take the example of setting up receive and transmit buffers for an AVR microcontroller to shuttle data in and out using its built-in hardware USART and interrupt routines. Once you’ve got a good circular buffer at hand, handling incoming serial data becomes child’s play.
volatile struct Buffer rx_buffer = {{}, 0, 0}; ISR(USART_RX_vect){ bufferWrite(&rx_buffer, UDR0); } int main(void){ uint8_t received_byte; enum BufferStatus status; initUSART(); initUSART_interrupts(); while (1) { status = bufferRead(&rx_buffer, &received_byte); if (status == BUFFER_OK) { /* we have data */ do_something(received_byte); } } }
This isn’t a full-fledged example, but it hits the main elements. The code defines an interrupt service routine (ISR) that simply stashes the received byte into the circular buffer when anything comes in over the serial line. Note that the
bufferWrite function is pretty short, so we’re not going to spend too much time in the ISR, which is what we want. The combination of the interrupt and the chip’s hardware serial peripheral take care of filling up the buffer for us. All that’s left to do in
main() is try to read some data from the buffer, and check the return code to see if we got something new or not.
Because the buffer is shared between the
main() routine and the ISR, it needs to be defined outside of either function, in the global namespace. Note that since we write to one end of the buffer, and read from the other, there’s not as much need to worry about race conditions and atomicity here. As long as the ISR is the only routine that’s writing to our buffer, and we only read from the buffer in
main(), there’s no chance of conflict.
That said, if you want to be doubly sure that your shared volatile variable isn’t getting accessed twice at the same time, or if you’re writing a more general-purpose circular buffer routine, it wouldn’t hurt to wrap up the sections with access to shared variables in an
ATOMIC_BLOCK macro.
Transmitting
Finally, setting up a transmit buffer is a little bit more complicated on the AVR platform, because we’ll need to enable and disable the USART’s data-ready interrupt when the transmit buffer has data or is empty, respectively. Defining a couple convenience functions and checking for the buffer status in the interrupt routine take care of that easily:
static inline void enable_transmission(void){ UCSR0B |= (1<<UDRIE0); } static inline void disable_transmission(void){ UCSR0B &= ~(1<<UDRIE0); } ISR(USART_UDRE_vect){ uint8_t tempy; enum BufferStatus status_tx; status_tx = bufferRead(&tx_buffer, &tempy); if (status_tx == BUFFER_EMPTY){ disable_transmission(); } else { UDR0 = tempy; /* write it out to the hardware serial */ } }
The
UDRE interrupt fires every time the USART data register is empty (“DRE”) so that the ISR pulls a new character off the transmit buffer as soon as it’s able to handle it. Your calling code only needs to pack all the data into the transmit buffer and enable the interrupt one time, without having to wait around for the actual transmission to take place, which takes a long time relative to the fast CPU speed. This is, not coincidentally, a lot like what the Arduino’s “Serial” library functions do for you.
Peeking Inside the Buffer
Finally, there’s one very common use case that we haven’t addressed yet. It’s often the case that you’d like your code to assemble data out of multiple bytes. Maybe each byte is a letter, and you’d like your code to process words. On the reading side, you’d like to stack up data in the buffer until a space character arrives. For this, it’s very convenient to have a function that looks at the most recently added character, but doesn’t change either of the index variables.
We’ll call this function
bufferPeek() and it’ll work like so:
enum BufferStatus bufferPeek(volatile struct Buffer *buffer, uint8_t *byte){ uint8_t last_index = ((BUFFER_SIZE + (buffer->newest_index) - 1) % BUFFER_SIZE); if (buffer->newest_index == buffer->oldest_index){ return BUFFER_EMPTY; } *byte = buffer->data[last_index]; return BUFFER_OK; }
The code should be, by now, basically self-explanatory except for the one trick in defining the
last_index. When the buffer has just wrapped around,
newest_index can be equal to zero. Subtracting one from that (to go back to the last written character) will end up with a negative number in that case. Adding another full
BUFFER_SIZE to the index prevents the value from ever going negative, and the extra factor of
BUFFER_SIZE gets knocked out by the modulo operation anyway.
Once we’ve got this “peek” function, assembling characters into words is a snap. For instance, this code snippet will wait for a space in the incoming data buffer, and then queue up the word as quickly as possible into the output buffer, turning on the transmit interrupt when it’s done.
// Check if the last character typed was a space status = bufferPeek(&rx_buffer, &input_byte); if (status == BUFFER_OK && input_byte == ' '){ while(1) { status = bufferRead(&rx_buffer, &input_byte); if (status == BUFFER_OK){ bufferWrite(&tx_buffer, input_byte); } else { break; } } enable_transmission(); }
Code and Conclusions
All of this demo code (and more!) is available in a GitHub repository for your perusal and tweaking. It’ll work as written on any AVR platform, but the only bits that are specific are the mechanics of handling the interrupts and my serial input/output library. The core of the circular buffer code should work on anything that you can compile C for.
There are all sorts of ways to improve on the buffer presented here. There are also many possible implementations of circular buffers. This article is far too long, and it could easily be three times longer!
But don’t get too bogged down in the details. Circular buffers are an all-purpose tool for dealing with this common problem of asynchronous data creation and consumption, and can really help to decouple different parts of a complex program. Implementing buffers isn’t black magic either, and I hope that this article has whetted your appetite. Go out and look through a couple more implementations, find one you like, and then keep those files tucked away for when you need it. You’ll be glad you did.
If you’ve got favorite bits of buffer code, or horror stories from the trenches, feel free to post up in the comments. We’d love to hear about it.
50 thoughts on “Embed With Elliot: Going ‘Round With Circular Buffers”
Having dabbled with FIFO’s and circular buffers, a couple of notes come to mind:
Use buffer sizes which are a power of two (2n). This allows you to not use division [/%] which can consume precious cpu cycles, especially in embedded applications, but rather ANDing [&] with the buffer size minus one to get the index.
Use
unsignedtypes for the read/write/in/out/rx/tx/oldest_index/newest_index pointers, and have at least one one bit to spare above the buffer size.
Subtracting the
oldest_indexfrom
newest_index[
to_go = newest_index - oldest_index] gives you the number of elements in the FIFO/circular buffer.
Subtracting
to_gofrom the buffer size [
can_go = buffer_size - (newest_index - oldest_index)] gives you the number of elements in the FIFO/circular buffer.
In the previous two tricks, you need to assign the result to a temporary variable and not put it in a conditional expression, as when the oldest/newest pointers wrap around, you can have architecture flags set/cleared which muck up the results of the expression.
can_goand
to_gocan’t be greater than the buffer size. If either are, it is an indication that the structure has been corrupted.
The usual caveats with regard to concurrency and race conditions apply. Generally, writes should only increment the newest_index, while reads should only increment the oldest_index, peeks should leave them untouched.
Reading/writing arbitrary lengths can complicate things a bit, but the general rule is that you can’t read/write more than what’s available.
Power two as in 2 to the power of n, nothing else. *notes SUP/SUB tags are not allowed*
Even with power of two you can use %. Every modern compiler will optimize that to the best operation. The code will then still be generic for non power of two buffers.
Yes, but as Teukka said, the division that can result in the general case might be quite expensive (in terms of clks) eg on limited 8-bit architectures with no HW div.
If this level of optimization is important for your app, you could consider some pre-processor macro magic, so the % is only used with power-of-two buffers (i.e. becomes fast, single op AND in practice) and in other cases replaced with something like “if (index >= BUF_SIZE) index -= BUF_SIZE;”
That would give you fast and optimized ANDs with pow(2) buffers, but still allow generic buffers with just a slight penalty.
Of course, if you’ve already joined the 21st century CortexM or other 32-bit world; chances are great that your micro in fact has fast, single-cycle HW integer division. And then yes, just use the simple % for any buffer sizes.
No need to write a macro — that’s exactly what using modulo does on a reasonable compiler! (At least AVR-GCC) uses the bit-masking trick when the buffer is power-of-two, and resorts to division when it’s any other length.
Using modulo is already optimal / optimized. And painless to boot. Thanks, compiler!
We discovered that % was (relatively) very costly in CPU cycles, just because it only takes one character to type doesn’t mean it’s efficient code. In our case, doing something like while(a > mod) a-=mod was way faster.
It really depends a lot on what you’re doing.
For example, a%b, where a and b are both variables is not easy to optimize.
a%b where either a or b is fixed is much easier. Any decent compiler that sees a % SOMECONSTANT will replace % SOMECONSTANT with a bit mask if SOMECONSTANT is a power of two. Otherwise, it will use the divide operator or whatever operator it determines to be most efficient.
“Subtracting the oldest_index from newest_index [to_go = newest_index – oldest_index] gives you the number of elements in the FIFO/circular buffer.”
No, you need modulo the buffer size here. It’s a circular buffer, the pointers wrap around: if BUFFER_SIZE is 16, then when ‘oldest_index’ hits 15, ‘newest_index’ will be 0 when there’s 1 entry in the buffer, and obviously 0-15 isn’t 1.
“Subtracting to_go from the buffer size [can_go = buffer_size – (newest_index – oldest_index)] gives you the number of elements in the FIFO/circular buffer.”
You can also do ((oldest_index – newest_index)-1) % BUFFER_SIZE. Math works out the same (yay two’s complement) and can be cheaper on certain platforms.
Also I would find the names “write_ptr” (or index) and “read_ptr” much clearer than “newest_index” and “oldest_index”, but maybe that’s just me.
Ah, but that’s the beauty of it, you don’t reset the read_ptr/write_ptr, you let them keep on ticking. Using unsigned and the bit size of the word takes care of the rest. Modulo Buf_size has its place, when you get the actual index into the buffer, and if you use power-of-2 buffer size, you can simplify that to anding with bufsize-1.
Basically, if you have two values on either side of a wraparound of a binary word, you still get the same difference. E.g. you have wrapped around new_index and it’s 2, but old_index is still, say 252. 2-252 is -250 in signed 32-bit maths, but for an
uint8_t(unsigned 8-bit (byte)) it’s 6.
You have an implicit MOD 256 because of the word size. Try it out.
There are two catches tho.
You MUST use an
unsignedinteger type, and you need assign the result to a temporary variable so that the carry/borrow is ignored when you do the expression for the conditional:
to_go = newest_index - oldest_index ; /* Can't merge with the below like: if ((to_go = newest_index - ....) */
if ( to_go > buffer_size )
return ENOPE ;
else
nBytes = min(n, to_go) ; /* Can at most read the # of elements in buffer */
/* Do actual read data movement here */
And the code is remarkably similar for writes, just substitute to_go with can_go and use
buffer_size - (newest_index - oldest_index).
And yeah, I use rdptr and wrptr, I’ve seen in and out in the linux kernel code for kernel fifos.
And they seem to be using this:
len = min(len, fifo->size - fifo->in + fifo->out);rather than subtraction all the way thru;
I like it! But, I feel like it will confuse people who aren’t in-the-know when they read the code. ie. Myself.
Re: zerocommazero:
> I like it! But, I feel like it will confuse people who aren’t in-the-know when they read the code. ie. Myself.
I banged my head against the wall myself coming up with a quick and simple FIFO / circular buffer set of functions for my little OS, until I found an early version of this method in the linux kernel. And it confused me about as much as it did you at first. So lessons to take home for OS and embedded coders and amateurs alike:
o Study how kernels do it, e.g. the Linux kernel at
Kernel coders often work with CPU cycle and other resource consumption restraints.
o Learn the arcane art of “unrolling loops”, the limitations of each data type and how you can make those limitations work for you.
o Learn assembly, if not fluently, at least basically so you can follow what a piece of assembly code does.
o Study what assembly code your C/C++ compiler of choice produces for a given set of HLL code (gcc has the -S option to force it to produce assembly).
o Don’t shy away from doing one step of coding in a HLL, then tweaking the resulting assembly code to perfection.
o For timing-critical applications or when you run into running out of CPU cycles to use, begin the habit of having an 8-charcter wide column in your comments – before the real comments -for clock cycles, and specifying clock cycles in the function header comment. For the AVR, the AVR 8-bit instruction set reference can be found here:
Anyone have more lessons to share?
That assumption bit me in the tail in my current compiler (IAR Embedded Workbench 7.20 for ARM).
I assumed that 255+1 = 0 for an unsigned int8, but in an if statement (and only in an in if statement), the code didn’t work so I still had to use modulo even if technically the int8 could not have a bigger value than 255.
For example:
if (rxBuffer[(rxBufProcPntr+1)%256]==’O’ && rxBuffer[(rxBufProcPntr+2)%256]==’K’ )
Yeah, I missed the fact that you were doing modulo on the assignment/read, not on the indices.
The problem with this is that it saves you a quick instruction on operations that occur infrequently (when getting number of total bytes), at the cost of forcing you to do an extra operation in a time-critical place (the ISR, before reading/writing the actual hardware register).
Then again, if you’ve got the RAM, if the buffer size is 256 the two solutions are identical anyway (which is actually what I do for serial transmit buffers).
It’s probably worth pointing out that there are then 3 ways I can think of to set up the buffer nicely:
1) Use large index variables and modulo on each access (like you suggest).
2) Use index variables and modulo on each increment
3) Directly use uint8_t *rd_ptr, uint8_t *wr_ptr, align the buffer to a higher power of 2 (e.g. for a buffer size of 16, align to 32), then AND the pointer with (~BUFFER_SIZE) after increment.
Each of those has advantages and disadvantages, depending on the platform and the use case.
can_go = buffer_size - (newest_index - oldest_index) ;
Gives you the number of elements which can fit into the buffer.
Darn. Not my day today :(
These articles aren’t light reading for me, but I sure do get a lot out of them. Reading Hackaday when one of these comes up is like:
click
click
click
(Embed with Elliot)……………………………………………
.
.
.
.
(a half an hour later)
click
click
click
“Note that since we write to one end of the buffer, and read from the other, there’s not as much need to worry about race conditions and atomicity here.”
Every time I hear that, my immediate thought is “that means you’ve probably got a race condition you haven’t seen yet.”
And you do. :)
bufferPeek is the culprit. You’re using newest_index twice. Consider the buffer being empty when last_index is calculated. So if oldest_index = 0, and newest_index = 0, last_index ends up being 15.
Now the data comes in immediately after that calculation. So newest_index is now 1. It passes that check, and continues on… and returns data[15], which is nonsense. Oops!
The solution is to grab a local copy of newest_index right away, and do the math on *that*.
e.g.
enum BufferStatus bufferPeek(volatile struct Buffer *buffer, uint8_t *byte){
uint8_t newest_index = buffer->newest_index;
if (newest_index == buffer->oldest_index){
return BUFFER_EMPTY;
}
*byte = buffer->data[(BUFFER_SIZE+newest_index-1) % BUFFER_SIZE];
return BUFFER_OK;
}
I should also point out that you could also just not create the ‘newest_index’ temp – that’d work as well, because after the check, there’s guaranteed to be at least 1 byte in the buffer. If an interrupt comes in, you’ll get 2, and grab the second.
However, that requires you to grab the volatile newest_index twice. Just using a temporary means the compiler will just use the copy it already has.
Damnit!
My original code (what I actually use in my own projects) wraps the functions in an ATOMIC_BLOCK statement, which should beat the race condition down. (I hate it when I say things like “should” in this context too.)
I removed it so that it would compile/run on Arduino, which for some reason doesn’t use the -C99 flags to compile with, even though they could, and ATOMIC_BLOCK uses some tricks from C99.
Your solution is even better. Thanks!
I really, really dislike wrapping ATOMIC_BLOCK stuff just to be safe, because it’s so expensive in terms of potential latency, but obviously if you’ve got the cycles/power to spare, it saves a lot of headaches.
But this is related to the ‘volatile’ keyword article you had: a useful way of dealing with volatiles in a function is to always grab them into a local temporary, and use that local temporary only. If you only use it one time, the compiler will optimize away the temporary, and if you use it more than once, it won’t refetch it and you won’t have race issues.
(Obviously if you want to refetch it – like you’re polling – then you fetch it directly.)
Fair enough. And here the local temp copy (as long as you’ve got fewer than 256 elements in your array) is foolproof as well.
If you need a 16-bit int to refer to the array, the ATOMIC_BLOCK is your only hope. Or, if you know for sure that global interrupts will be enabled otherwise, just wrap in a cli()/sei() pair. Or, if you know which specific interrupt you’re afraid of (as with the USART example) you can just knock that one out specifically for the duration as well.
But again, like you said: where the local copy method works, it’s probably optimal.
Oh, absolutely. And of course, a lot of people don’t understand that what look like atomic operations in C aren’t in any way atomic, or they might be atomic on one architecture, but absolutely not on another. So ATOMIC_BLOCKs are really pretty handy for someone just getting started.
A long, long time ago, I worked with a processor (ADSP2105, ancestor of the Blackfin) which has circular buffering built into the CPU’s I/O engine. The I/O engine would also generate an interrupt if incrementing the index caused a wrap, which was very nice. So the serial I/O engine could jam data into the circular buffer, and when it incremented it past the wrap point, we’d get an interrupt telling us to service the buffer.
The only problem was that when that interrupt went off, you had to service the buffer before another I/O sample arrived, or it would overwrite the beginning of the buffer.
I realized that if I set the I/O to increment by 2 instead of by one, and if I set the buffer length to an odd number, then the first time through the buffer it would use the even indices. Then it would wrap (generating the interrupt) and use the odds. I set the buffer length to 25 (because that is a nice odd number). The first time through I would service the 13 even samples, and the next time I’d service the 12 odds. That gave me a minimum of 12 sample periods to get around to servicing the data before it was at risk (and could have had more time than that by making the buffer bigger, but still odd).
sounds a lot like a ping pong buffer
The most hardcore implementation of uart circular buffer, what I have made for my lib.
“`
ISR(RX0_INTERRUPT, ISR_NAKED)
{
asm volatile(“\n\t” /* 5 ISR entry */
#ifndef USART_UNSAFE_24_CYLCE_INTERRUPT
“push r0 \n\t” /* 2 */
“in r0, __SREG__ \n\t” /* 1 */
#endif
“push r31 \n\t” /* 2 */
“push r30 \n\t” /* 2 */
“push r25 \n\t” /* 2 */
“push r24 \n\t” /* 2 */
“push r18 \n\t” /* 2 */
#ifdef USART_UNSAFE_24_CYLCE_INTERRUPT
“in r18, __SREG__ \n\t” /* 1 */
“push r18 \n\t” /* 2 */
#endif
/* read byte from UDR register */
“lds r25, %M[uart_data] \n\t” /* 2 */
/* load globals */
“lds r24, (rx0_last_byte) \n\t” /* 2 */
“lds r18, (rx0_first_byte) \n\t” /* 2 */
/* tmp_rx_last_byte = (rx0_last_byte + 1) & RX0_BUFFER_MASK */
“subi r24, 0xFF \n\t” /* 1 */
“andi r24, %M[mask] \n\t” /* 1 */
/* if(rx0_first_byte != tmp_rx_last_byte) */
“cp r18, r24 \n\t” /* 1 */
“breq .+14 \n\t” /* 1/2 */
/* rx0_buffer[tmp_rx_last_byte] = tmp */
“mov r30, r24 \n\t” /* 1 */
“ldi r31, 0x00 \n\t” /* 1 */
“subi r30, lo8(-(rx0_buffer))\n\t” /* 1 */
“sbci r31, hi8(-(rx0_buffer))\n\t” /* 1 */
“st Z, r25 \n\t” /* 2 */
/* rx0_last_byte = tmp_rx_last_byte */
“sts (rx0_last_byte), r24 \n\t” /* 2 */
#ifdef USART_UNSAFE_24_CYLCE_INTERRUPT
“pop r18 \n\t” /* 2 */
“out __SREG__ , r18 \n\t” /* 1 */
#endif
“pop r18 \n\t” /* 2 */
“pop r24 \n\t” /* 2 */
“pop r25 \n\t” /* 2 */
“pop r30 \n\t” /* 2 */
“pop r31 \n\t” /* 2 */
#ifndef USART_UNSAFE_24_CYLCE_INTERRUPT
“out __SREG__ , r0 \n\t” /* 1 */
“pop r0 \n\t” /* 2 */
#endif
“reti \n\t” /* 5 ISR return */
: /* output operands */
: /* input operands */
[uart_data] “M” (_SFR_MEM_ADDR(UDR0_REGISTER)),
[mask] “M” (RX0_BUFFER_MASK)
/* no clobbers */
);
}
“`
Something like this is still generating bigger code (and taking more cycles)
“`
ISR(USART_RX_vect){
bufferWrite(&rx_buffer, UDR0);
}
“`
guess why
Well, it’s quite difficult to write a “naked” ISR that’s *not* more efficient than the default shotgun prologue and epilogue.
We use these circular buffers quite a lot in our codes. We call it ringbuffer. IMHO one of the best usage, is for debugging the running system over serial line. We have our own real time operating system, we use a lot of tasks, and we wanted to see whats going on inside the tasks in real time (not just real time, but with as little execution overhead as possible), so the solution is debug ringbuffers, one for every task, and one for the debug task. When a task wants to print out a debug string, than writes in it’s own debug ringbuffer, and writes into the debug task ringbuffer a debug item (id, timestamp, length). The debug task wakes up periodically and checks for debug items, and sends the formatted debug string to the debug output (serial port). Only the debug task waits for the serial port, the normal tasks can run without blocking. It is possible to make dump debug string from interrupt servers.
This is a sample output (115kbaud serial output) of this debug system, the first 4 hexa digit is the integer part of the time stamp the next 2 is the fractional part. The timestamps are in ms. It is a cortexM3 MCU.
[ DBG 0038:CD*] GPIO conf hal 0008000c port 0 pin 3
[ DBG 0038:DE*] GPIO conf hal 0008000d port 0 pin 2
[ DBG 0038:FE*] conf irq a0003
[ DBG 0039:08*] rx buffer memory at 0x20006400 size 512
[ DBG 0039:16*] tx buffer memory at 0x20006600 size 512
[ DBG 0039:23*] rx_rb 20007624 tx_rb 20007644
[ DBG 0039:36*] CFW init reached
[ HWC 0039:4F*] configure 140001 eeprom
[ HWC 0039:59*] phase1 4 phase2 6 phase3 2
[ HWC 0039:68*] act freq 375000 freq 375000 src 96000000 div 256 40602
[ HWC 0039:8A*] GPIO conf hal 00080005 port 0 pin 4
[ HWC 0039:9B*] GPIO conf hal 00080007 port 0 pin 8
[ HWC 0039:AC*] GPIO conf hal 00080006 port 1 pin 5
If you replace the newest_index/oldest_index with counts of total bytes written/read instead, then the code becomes a lot simpler. You only need (count % BUFFER_SIZE) to calculate the appropriate index, and you don’t have the weird edge cases to worry about. Just make sure that your buffer size is a power of 2 so there’s no discontinuity when the count variables overflow.
you don’t need modulo at all, or power of 2 size buffer !!!
Uh, yes you absolutely do. Otherwise you’ll try to access memory past the end of the buffer. C doesn’t care if you try that, it’ll either corrupt the memory outside the buffer area, or it’ll segfault.
And the only other way to avoid the modulo operation is to do it manually with an if statement, which seems to be what you’re doing in your other comments. It’s far messier doing it that way, and there’s absolutely no benefit to it.
Additionally, buffers are usually of fairly arbitrary length. So there’s no reason to avoid going to a power of two, which also makes it more likely you’ll hit an alignment boundary – having a non-power-of-two buffer that the compiler pads out to a power of two *anyway*, wasting the extra, is just silly.
Nice article, there is just one thing i do not agree with, due to the possible waste of memory:
‘The easiest way, in my opinion, to deal with this is just to leave one slot empty at all times.’
There is a better and easier way to do this, simply having a counter that show the number of items in the circular buffer.
By using a counter you make sure you can fill the circular buffer 100%, and not always having at least one empty place, like with your solution.
If you just have a buffer storing integers, it does not make any difference. But often you store more complex objects in the buffer and then the waste of memory is a lot bigger.
Let’s say you have a circular buffer with 16 places, each item in the buffer is a package of data of the size 1k.
With my solution the total buffer would take up 16kB + 2 byte for the counter. (16 bit integer)
Your solution would only take op the 16 kB, but due to having to have an empty place in order to figure out if the buffer is full or empty, you waster 1kB of memory.
Personally i would much rather waste space for 1 integer, instead of 1kB.
When studying computer science, I had this discussion many times with my teacher who prefered your solution.
The funny part was at one of the exam’s the subject i got was …… Circular buffers.
And the external examining teacher, had to tell my teacher my solution actually was the most memory efficient :-)
You were right in your computer science exam.
I also really like the “first entry” + “total length” method, but the code needs to call a lot more modulos. Which is no big deal if the buffer is a power of two length, but will really screw you in terms of CPU usage otherwise. It’s funny how optimizing something as simple as a circular buffer can get really implementation-dependent really fast.
It’s a wash here, like you say, so I went with simple. In general, if your buffer is full of (type A) and you need a (type B) to count them, you’ll win with this architecture if sizeof(type A) < sizeof(type B). You'd be right to use the method presented here if you had a 512-element buffer of 8-bit unsigned integers.
You don’t need modulo at all, simply you have to count the number of push and pop and have the size of the buffer
so the push is like this:
res = RINGBUFFER_OK;
if ( (rb->push_cnt – rb->pop_cnt) != rb->capacity )
{
next = rb->write_ndx;
RB_STORE_ELEMENT( rb, next, arg );
if ( (++next) >= rb->capacity )
{
next = 0;
}
rb->write_ndx = next;
rb->push_cnt++;
}
else
{
res = RINGBUFFER_FULL;
}
return res;
One thing that’s really nice about the newest/oldest pointers version, though, is that the read function only has to know/modify the oldest index, and the write function the newest — they’re already essentially thread-safe.
I’ve also used oldest + length methods, but using the length (or push_cnt – pop_cnt) mixes the read/write variables and functions together in a way that invites race conditions. You can do it if you’re careful, or only using a single UART, or etc.. But you’ll have to think about it.
This solution with the push/pop count is also as thread safe as your code (your code definitely not fully thread safe, in case if you are calling the push from 2 different threads at the same time). The push code only writes the push count and the write index, the pop code only writes the pop count and the read index. The decision about the number of items in the buffer is only made with the push/pop counters, the write/read index is just internal for the push/pop, the pop function never touch (does not read or write) the write index and push function never touch the read index. So this solution is nearly identical to the newest/oldest, just does not need any modulo, and the size of the buffer can any number (regarding the number limit of the cpu). The “modulo” calculating is made with the write/read index comparing against the capacity. The push/pop counter can, and will roll over, but the 2’s complement subtraction will make it perfect.
Just to be clear this is how the pop function works:
res = RINGBUFFER_OK;
if ( rb->push_cnt != rb->pop_cnt )
{
ndx = rb->read_ndx;
RB_LOAD_ELEMENT( rb, ndx, arg );
if ( (++ndx) >= rb->capacity )
{
ndx = 0;
}
rb->read_ndx = ndx;
rb->pop_cnt++;
}
else
{
res = RINGBUFFER_EMPTY;
}
return res;
I don’t get the point. What’s the point of having a write index *and* a push/pop count? They’re completely identical, and it takes twice the operations to handle it since you need to increment both.
Modulo operators are extremely cheap for a power of 2, and if it’s not a power of 2, it’s easy to special-case both the size calculation and the rollover.
No they don’t have to be identical. That’s the point, you can have any number of capacity, and still don’t need any modulo at all. The push/pop count is for detecting the free space or the items in the buffer, the “modulo” is made with the write index, capacity compare.
My first ‘snake’ game was just a circular buffer.
What’s wrong with this way. Integer tests are cheap.
enum BufferStatus bufferWrite(volatile struct Buffer *buffer, uint8_t byte){
uint8_t next_index;
if(buffer->newest_index == BUFFER_SIZE)next_index = 0;
else
next_index = buffer->newest_index+1;
if (next_index == buffer->oldest_index){
return BUFFER_FULL;
}
buffer->data[buffer->newest_index] = byte;
buffer->newest_index = next_index;
return BUFFER_OK;
}
For a non-power of 2 buffer, that’s the best way. But it’s much more complicated for a power-of-2 buffer. You have:
compare
jump if equal
increment
jump past
set to zero
versus
increment
and/bit clear
In an MSP430, for instance, that’s something like 7 or 5 cycles versus 2 (so you also lose the definite timing).
yes I see what you mean. But for general code that can handle any BUFFER_SIZE I like my solution better than a modulo. I know its not pretty code but that’s how i roll.
I would just come up with a macro that autodetects whether it’s a power of 2, use modulo in that case, and use the if/else construct in the other case.
Test it out before you write that macro! I betcha your compiler does the already for you. (AVR-GCC does.)
Try it. If your buffer size is a power of 2, the modulo operator will just be a bit mask, which is simpler and produces more efficient code than your if statement ( which requires a branch, as written)
You don’t need modulo at all, simply you have to count the number of push and pop and have the size of the buffer. I wrote an example push code above
i’ve read it’s not advised to put local variable as you do in interrupts routine and it’s also not advised to call routine from interrupt too .
At least on microchips 8 bits devices ( XC8 documentation )
can somebody give me an answer ?
Please be kind and respectful to help make the comments section excellent. (Comment Policy) | https://hackaday.com/2015/10/29/embed-with-elliot-going-round-with-circular-buffers/ | CC-MAIN-2021-39 | refinedweb | 7,999 | 57.61 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.