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
|
|---|---|---|---|---|---|
I've been playing around with files and streams and just hit a pot hole.
My goal is to be able to input time and date into a file when say someone "clocks in/out". Just a little program that will help me keep up with my time in school.
#include <iostream> #include <fstream> using namespace std; int main() { ofstream a_file ( "example.txt", ios::app); if ( !a_file.is_open() ) { // The file could not be opened } else { // Safely use the file stream } a_file << system("date /t") << "\n" << system("time /t") << "\n"; a_file. close(); }
The problem is that when I open "example.txt" all I get is a zero (0).
I think my problem has to do with I'm inputing an integer instead of a string, since I'm working with a text file. If anyone has some input, I'd enjoy hearing from you.
|
https://www.daniweb.com/programming/software-development/threads/18583/inputing-system-date-t-and-system-time-t-into-a-file
|
CC-MAIN-2018-43
|
refinedweb
| 143
| 83.46
|
A Programming Language with Extended Static Checking
An interesting problem I’ve encountered many times in Java is that of conflicting names. For example, suppose I have the following code:
import wyil.lang.*;
import wyil.lang.Type.*;
...
public static Type T_Bool = new Type.Bool();
This is all well and good. The problem arises when I want to import another class called Type from some package. Suppose the wyjc.lang package contains a class called Type:
Type
wyjc.lang
import wyil.lang.*;
import wyil.lang.Type.*;
import wyjc.lang.*;
...
public static Type T_Bool = new Type.Bool();
public static wyjc.lang.Type WYJC_BOOL = new wyjc.lang.Type.Bool();
This is not really a problem — it’s just annoying. I now have to provide full package information whenever I want to work with one of the Type classes.
What would be really great is to have a more flexible import statement, like [[Python (programming language)|Python]]. For example:
import
import wyil.lang.*;
import wyil.lang.Type.*;
import wyjc.lang.Type as wyjcType;
...
public static Type T_Bool = new Type.Bool();
public static wyjcType WYJC_BOOL = new wyjcType.Bool();
This would be a nice and elegant way to resolve this problem of [[Namespace (computer science)|namespaces]]. So, I think I’ll put something like this in Whiley …
And, it looks like others are complaining as well … see here and.318 seconds.
|
http://whiley.org/2010/10/04/better-namespaces/
|
CC-MAIN-2020-05
|
refinedweb
| 225
| 61.53
|
RECOMMENDED: If you have Windows errors then we strongly recommend that you download and run this (Windows) Repair Tool.
A block of code is set as follows: Function Multiply-Numbers { Param($FirstNum, $SecNum) Try { Write-Host ($FirstNum * $SecNum) } Catch { Write-Host "Error in function, present two numbers to multiply" } } Preface When we wish to draw.
4 * Map win32 error codes to errno values. 5 *. 6 * Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group. 108. {109 error_drive_locked, eacces.
Sometimes basic things like installing the latest Oracle instantclient on the PCs of all of your developers can take considerable time. I typically setup a
The System Error Codes are very broad. This site uses cookies for analytics, personalized content and ads. By continuing to browse this site, you agree to this use.
MESSAGE Error while loading manipulator. I20090611-1540 java.version=1.6.0_16 java.vendor=Sun Microsystems Inc. BootLoader constants: OS=win32, ARCH=x86, WS=win32, NL=en_US Command-line arguments: -os win32 -ws.
Error Handling Excel Vba
Sep 27, 2011 · ERROR_SUCCESS – 0x00070000 – (0) The operation completed successfully. ERROR_INVALID_FUNCTION – 0x80070001 – (1) Incorrect function. ERROR_FILE_NOT_FOUND.
How To Fix Win32 Error Code 1796 (Solved) – Win32 Error Code 1796. Contents. Error 1801 The Printer Name Is Invalid. Wnetaddconnection2 Error Codes ERROR_FULLSCREEN_MODE 1008 0x000003F0 An attempt was made to reference a token that does not exist.
A complete list of system error codes, from code 1 through 15841. Here, too, are meanings for each system error code, plus other ways they may appear.
May 20, 2010. Recently I got the messagebox below with "Error code: 2147500037" when I used Windows 7 to print some settings (in this case the.
The Windows Win32 Error Code 109 are easy to repair. By downloading and running the registry repair tool RegCure Pro, you can quickly and effectively fix this problem and prevent others from occuring. Simply click the links below for your free download.
Downloads. Image Writer does not have any download files registered with Launchpad.
Win32 error 109. Please visit my older post regarding the fix for generic host for win32 process. William January 22, 2008, Xbox Error Code 5 Fix If you're getting a specific error code after. simple mistake.
Revenue growth was however quite strong at 74% overall and 109% for the international business with. development kits for developers to bring their Web,NET, Win32, Android and iOS code to Windows. Developers are also being.
Aug 15, 2016. Windows error codes — source: Microsoft. Pretty exhaustive list of Win32 error codes as of August 2016 — Jean-Marc Duro — — function. ERROR_BROKEN_PIPE = 109, — (#006D) — The pipe has been ended.
Win32 Error Code 109. Contents. Windows Error Codes Lookup. Windows Error Codes List. Use your global user account or local user account to access this server. 1809 The account used is a server trust account.
Fix Win32 Error Code 109 – How to Repair Win32 Error Code 109 Fast – Win32 Error Code 109 is usually caused by a corrupted registry entry. I spent hours looking for a solution to this error and finally I found one. Now my PC is much faster and more importantly I have stopped seeing this error!
Apr 12, 2015 · Open Windows Activation by clicking the Start button , right-clicking Computer, clicking Properties, and then clicking Activate Windows now. Click Show.
using System.Reflection; namespace Microsoft.Win32.Interop { public class ResultWin32 { public static. public const int ERROR_BROKEN_PIPE = 109; /// <summary>. The service has returned a service-specific error code. /// </ summary>
RECOMMENDED: Click here to fix Windows errors and improve system performance
|
http://thesecondblog.com/win32-error-code-109/
|
CC-MAIN-2018-09
|
refinedweb
| 586
| 59.9
|
Technical Support
On-Line Manuals
RL-ARM User's Guide (MDK v4)
#include <rtl.h>
OS_RESULT os_tsk_delete (
OS_TID task_id ); /* Id of the task to delete */
If a task has finished all its work or is not needed anymore, you
can terminate it using the os_tsk_delete function. The
os_tsk_delete function stops and deletes the task identified
by task_id.
The os_tsk_delete function is in the RL-RTX library. The
prototype is defined in rtl.h.
Note
The os_tsk_delete function returns OS_R_OK if the task was
successfully stopped and deleted. In all other cases, for example if
the task with task_id does not exist or is not running, the
function returns OS_R_NOK.
os_tsk_delete_self
#include <rtl.h>
OS_TID tsk3;
__task void task2 (void) {
tsk3 = os_tsk_create (task3, 0);
..
if (os_tsk_delete (tsk3) == OS_R_OK) {
printf("\n'task 3' deleted.");
}
else {
printf ("\nFailed to delete 'task 3'.");
}
}
__task void task3 .
|
http://www.keil.com/support/man/docs/rlarm/rlarm_os_tsk_delete.htm
|
CC-MAIN-2019-30
|
refinedweb
| 142
| 68.67
|
28 February 2012 09:53 [Source: ICIS news]
By Clive Ong
SINGAPORE (ICIS)--Asian acrylonitrile-butadiene-styrene (ABS) producers may hold on to their current offers given high feedstock costs, despite recent falls in values of a major raw material butadiene (BD), traders said on Tuesday.
ABS offers are at a wide range this week at between $2,100-2,250/tonne (€1,575-1,688/tonne) CFR (cost and freight) NE (northeast) ?xml:namespace>
Trades in late February saw prices falling to the low $2,100/tonne
Spot prices of general purpose ABS were assessed at an average of $2,130/tonne CFR NE Asia in the week ending 24 February, down $15/tonne week on week, tracking the decline in BD prices, according to ICIS.
BD spot prices fell $125/tonne week on week to $3,800/tonne CFR NE Asia on 24 February, ICIS data showed.
Resin producers in the region expect buying activities to improve in April, when factories in
“Demand may start to emerge in April but high ABS prices will likely dampen buyers’ enthusiasm,” said a producer in
ABS producers are expected to keep offers in the high $2,100/tonne CFR NE Asia and even at above $2,200/tonne CFR NE Asia levels, as the costs of other main feedstocks used in production, namely, styrene monomer (SM) and acrylonitrile (ACN), remain high, market source said.
“While BD prices have eased other feedstock like styrene and acrylonitrile prices are still high, so the overall costs structure for ABS is still elevated,” said a producer.
Spot ACN prices were stable at an average of $2,175/tonne CFR NE Asia, ICIS data showed.
Styrene prices, on the other hand, averaged $1,470/tonne CFR China on 27 February, up $5/tonne from 24 February, according to ICIS.
ABS demand in the region has slowed down as end-users are balking at the high resin prices, which have been on an uptrend from around $1,800/tonne CFR NE Asia in mid-November 2011.
End-users have secured production contracts for finished goods but have based their resin costs on lower prices in November and December last year. The strong uptrend in ABS prices since caught many of them by surprise, given that the fourth and first quarters of the year are typically characterised by low prices because of low demand.
Negotiations between end-users and clients on possible alteration of end-product prices to reflect higher ABS prices have had limited success so far.
“With end-users now hesitant to pick up ABS resins due to the high prices, overall demand will likely remain slow in the near term,” said a trader in
ABS is a resin used in the manufacturing of office equipment, consumer electronics, toys and in
|
http://www.icis.com/Articles/2012/02/28/9536319/asia-abs-makers-may-keep-high-offers-despite-bd-fall.html
|
CC-MAIN-2015-18
|
refinedweb
| 465
| 55.1
|
Navigate2 method
Navigates the browser to a location that might not be expressed as a URL, such as a pointer to an item identifier list (PIDL) for an entity in the Windows Shell namespace.
Syntaxobject.Navigate2(URL, Flags, TargetFrameName, PostData, Headers)
Parameters
- URL [in]
Type: VariantRequired. A variable or expression that evaluates to the URL of the resource to display, the full path to the file location, or a PIDL that represents a folder in the Shell namespace.
- Flags [in, optional]
Type: VariantA constant or value that specifies a combination of the values defined by the BrowserNavConstants enumeration.
- TargetFrameName [in, optional]
Type: VariantCase-sensitive string expression that evaluates to the name of the frame in which to display the resource. The possible values for this parameter are.
-
Load the link into a new unnamed window.
-
Load the link into the immediate parent of the document the link is in.
-
Load the link into the same window the link was clicked in.
-
Load the link into the full body of the current window.
-
A named HTML frame. If no frame or window exists that matches the specified target name, a new window is opened for the specified link.
- PostData [in, optional]
Type: VariantData, optional]
Type: VariantA String that contains additional HTTP headers to send to the server. These headers are added to the default Internet Explorer headers. For example, headers can specify the action required of the server, the type of data being passed to the server, or a status code. This parameter is ignored if the URL is not an HTTP (or HTTPS) URL.
Return value
Type: Long
Returns one of the following values.
Remarks
See Navigate for additional usage notes.
This method extends the Navigate method to allow for Shell integration; however, this method does not make Navigate obsolete. The original method can still be used for URL navigations.
See also
|
https://msdn.microsoft.com/en-us/library/windows/desktop/aa752094(v=vs.85)
|
CC-MAIN-2016-50
|
refinedweb
| 312
| 55.74
|
You can subscribe to this list here.
Showing
1
results of 1
>>> Daniel Clemente <dcl441-bugs@...> seems to think that:
>
>> 1) A java specific implementation of `semantic-tag-include-filename'
>> to turn 'org.slf4j.Logger' into 'org/slf4j/Logger.java' (or whatever)
>
> This can be hard because:
>1. You have to know the classpath in order to search the directories
>for classes. This is JDEE's work.
>
>2. If the source for a tag is inside a .jar, you can't get a file
>name that points to the .java file inside. You could uncompress that
>.jar temporarily, or also use an anonymous new buffer.
>
>3. Not all classes from the includes have their source code available.
I think you misunderstand what this function needs to do. For C, if
it sees:
#include "moose.h"
then the function returns the lisp string:
"moose.h".
which then refers to EDE's include path to see where moose.h might be.
Thus, I would assume that the Java statement:
import org.slf4j.Logger;
would need to return the lisp string
"org/slf4j/Logger.java"
It doesn't need to find it, only report out a string that represents
fragments of a filename. The file is then found in various paths
later in the system. For example, the EDE project might specify one
path at "/home/myself/myproj/src" under which the Logger.java file
exists, and then it could be found.
[ ... ]
> There has to be code to implement semantic-tag-include-filename for java-mode and call jde-find-class-source-file there. But I don't know what package should do it:
>- Maybe JDEE can always do it; it depends on CEDET anyway
>- CEDET should probably not do it by default, since CEDET does not depend on JDEE and this is very Java-specific. (Mmm... although more Java functionality from JDEE could also be integrated into CEDET instead of replicated).
>- or CEDET could use these JDEE functions just inside that new wrapper you spoke about; something like ede-jde-proj.el. I think this is the best.
I would expect this to be simple, such as:
(concat
(mapconcat 'identity (split-string (semantic-tag-name tag) ".") "/")
".java")
and would exist in one of CEDET's java support sources.
>> 2) We need some sort of EDE/JDEE integration wrapper, like
>> ede-emacs.el perhaps.
>>
>
> So this would be the first step, since point 1) depends on this.
>
> If I understand correctly, the wrapper defines a normal EDE project but internally loads the prj.el and translates each value from prj.el to values which EDE understands. In fact not all values from prj.el will be needed. The translation could even be bidirectional (values from EDE could be stored in prj.el).
> I imagine that EDE could also include wrappers for other project descriptors: a Maven wrapper, ANT wrapper, Eclipse's .project wrapper, ...
>
> I try to learn the theory but I don't have enough practice with JDEE or EDE or eieio to start this. But now I know the next steps to take; thanks for that.
[ ... ]
If the JDEE already knows about project roots, the EDE functions will
be very simple, and just call over. I can put a template together if
someone provides some code for asking of there are any JDE projects
open for a particular directory.
Eric
--
Eric Ludlam: eric@...
Siege: Emacs:
|
http://sourceforge.net/p/cedet/mailman/cedet-devel/?viewmonth=200901&viewday=5
|
CC-MAIN-2014-52
|
refinedweb
| 563
| 76.82
|
Can I resize ui.image pictures in Pythonista?
I know I can do resizing with pillow(i.e. reducing the dimensions of the picture), but to start with I have the picture as a
ui.imageobject. So can I resize it as that (before I send it over to pillow)?
@halloleooo try
import ui ui_image = ui.Image.named('test:Lenna') w,h = ui_image.size ui_image.show() print(w,h) wi = 100 hi = wi*h/w with ui.ImageContext(wi,hi) as ctx: ui_image.draw(0,0,wi,hi) ui_resize = ctx.get_image() print(ui_resize.size) ui_resize.show()
@halloleooo did you see my little script in your other topic "How to debug crash of image script when it's called as extension"
|
https://forum.omz-software.com/topic/7011/can-i-resize-ui-image-pictures-in-pythonista/?
|
CC-MAIN-2022-27
|
refinedweb
| 120
| 54.49
|
Hi!
- DC NIC teaming
- SPNs with IP addresses
- Moving the DFSR conflict folder
- Issuing user certs to unmanageable Apple devices
- DFSR USN Journal recommendations
- Windows 2008 DFS Event Log Messages
- DFSR and object access auditing SACLs
- SID uniqueness
- USN journal loss
- Setting SPN with AD PowerShell
- KCC nomination
- Other random goo
Question
Is NIC teaming recommended on domain controllers?
Answer.
Question
We used to manually create SPNs with IP addresses to allow Kerberos without network name resolution. This worked in Windows XP and 2003 but stopped working in later operating systems. Is this expected?
Answer
Question
I see that the DFSR staging folder can be moved, but can the Conflict and Deleted (\dfsrprivate\conflictanddeleted) folder be relocated? If so, how?
Answer:
Question.
Answer
:
- Duplicate the computer certificate template.
- Then change the subject to “Supply in the Request”
- Then give the template a unique name.
- Make sure that the NDES account and Administrator have security access to the template for Enroll.
- Assign the Template to be issued.
- Then you need to assign the template to one of the purposes in the NDES registry (You might want to use the one for both signing and encrypting). See the blog.
Now you have a certificate with the EKU of Client Authentication and a subject / SAN of the user account, I don’t see why you could not use that for what you need. Not that I have tested this or can test this, mind you…
Question.
Answer%
where you replace ‘%GUID%’ with the volume GUID and ‘ ‘Property Update Successful’ for that GUID.
2B. Raise the USN Journal Size (for all volumes)
WMIC /namespace:\\root\microsoftdfs path dfsrvolumeconfig set minntfsjournalsizeinmb=%MB SIZE%
This will return ‘Property Update Successful’ for ALL the volumes.
3. Restart server for new journal size to take effect in NTFS.
Update 4/15/2011 – On Win2008 or later:
1. Open Windows Explorer.
2. In Tools | Folder Options | View – uncheck ‘Hide protected operating system files’.
3. Navigate to each drive’s ‘system volume information\dfsr\config’ folder (you will need to add ‘Administrators, Full Control’ to prevent access denied error).
4. In Notepad, open the ‘Volume_%GUID%.xml’ file for each volume you want to increase.
5. There will be a set of tags that look like this:
<MinNtfsJournalSizeInMb>512</MinNtfsJournalSizeInMb>
6. Stop the DFSR service.
6. Change ‘512’ to the new increased value.
7. Close and save that file, and repeat for any other volumes you want to up the journal size on.
8. Start the DFSR service back up.
Question
There is a list of DFS Namespace events for Server 2000 at. I was wondering if there is a similar list of Windows 2008 DFS Event Log Messages?
Answer.
Question?
Answer.
Question?
Answer. 🙂:
Question ?
Answer.
Question
How come there is no “Set-SPN” cmdlet in AD PowerShell?
Answer″};{Remove=”SQLservice\finance.corp.
contoso.com:1456″}
We do not have any special handling to retrieve SPNs using Get-AdComputer or Get-Aduser (nor any other attributes – they treat all as generic properties). For example::
Question?”
Answer.
Other random goo
- If you’re going to jailbreak phones, do it with Microsoft – you get a free handset and t-shirt instead of a subpoena.
- The 2011 CES Innovation Honoree awards are out. Holy crap, the Digital Storm Online gaming rig is nom nom nom. I also want the Recon goggles for no legitimate reason.
- SlingBox and Win7 Phone have had a beautiful baby.
- It’s utterly impossible, but Duke Nukem Forever comes out May 3rd. Trailer is not SFW, as you would expect.
Unless it doesn’t.
- Star Wars on Blu-ray coming in September, now up for pre-order. Damn, I guess I have to get Blu-ray. Hopefully Lucas uses the opportunity to remove all midichlorian references.
- The 6 Most Insane Cities Ever Planned. This is from Cracked, so as usual… somewhat NSFW due to swearing.
- Not sure which sci-fi apocalypse is right for you? Use this handy chart.
- It was an interesting week for Artificial Intelligence and gaming, between Starcraft and Jeopardy.
Until next time.
Ned “and return to Han shooting first!” Pyle
|
https://blogs.technet.microsoft.com/askds/2011/01/21/friday-mail-sack-the-gangs-all-here-edition/
|
CC-MAIN-2019-39
|
refinedweb
| 685
| 58.48
|
File .babelrc is Missing
Projects generated with the CLI after upgrading to
@quasar/cliwill not answer to
buildor
devbut instead cite a missing
.babelrcfile when
quasar devis run.
Dev mode.......... spa Quasar theme...... mat Quasar CLI........ v0.17.25 Quasar Framework.. v0.17.20 Debugging......... enabled app:quasar-conf Reading quasar.conf.js +0ms app:dev Checking listening address availability (0.0.0.0:8080)... +5ms ⚠️ Missing .babelrc file...
quasar inforeads as follows.
Operating System Linux(4.9.0-4-amd64) - linux/x64 NodeJs 11.6.0 Global packages NPM 6.10.0 yarn 1.16.0 quasar-cli 0.17.25 vue-cli 3.0.4 cordova 6.0.0 Important local packages quasar-cli 0.17.25 (Quasar Framework CLI) quasar-framework 0.17.20 (Build responsive SPA, SSR, PWA, Hybrid Mobile Apps and Electron apps, all simultaneously using the same codebase) quasar-extras 2.0.9 (Quasar Framework fonts, icons and animations) vue 2.6.10 (Reactive, component-oriented view layer for modern web interfaces.) vue-router 3.0.6 (Official router for Vue.js 2) vuex 3.1.1 (state management for Vue.js) electron 5.0.6 (Build cross platform desktop apps with JavaScript, HTML, and CSS) electron-packager 14.0.1 (Customize and package your Electron app with OS-specific bundles (.app, .exe, etc.) via JS or CLI) electron-builder 20.44.4 (A complete solution to package and build a ready for distribution Electron app for MacOS, Windows and Linux with “auto update” support out of the box) @babel/core 7.5) Networking Host osambojano ens32 192.168.1.4
At first
quasar-frameworkand
quasar-cliwere listed as missing so I rran an
npm i -Son them.
when I ran an
npm lsin the project directory it listed
@babel/coreas a missing peer dependency. Or more particularly
@babel/core@>=7.0.0-beta.50 <7.0.0-rc.0as required by a long list of plugins.
I have schlepped through the upgrade guide too and as well and ran
yarn upgrade quasar@latest.At this point
vue@^2.5.0is named as an unmet dependency so I install it but no matter,
.babelrcremains missing.
But there is still Step 7 to do: remove
.babelrcand create
babel.config.js… Fresh out of ideas other than to repeat
npm remove quasar-cliand
npm i -g @quasar/cli. And but then
angular createremains a command not found.
Any help much thanked.
- nothingismagick last edited by
This is a little confusing. Are you attempting to build a 0.17 project? If not, then I imagine you still have an old copy of
quasar-cliin the global npm or yarn namespace.
- webcodestar last edited by
@nothingismagick said in File .babelrc is Missing:
This is a little confusing. Are you attempting to build a 0.17 project? If not, then I imagine you still have an old copy of
quasar-cliin the global npm or yarn namespace.
He was right. It is because you were using old version.
Uninstall quasar-cli if you have it from <1.0 versions
$ npm uninstall -g quasar-cli
Node.js >= 8.9.0 is required.
$ npm install -g @quasar/cli
Try with above commands.
Thanks for your attention to this
Yes I have Node 12.6.0 (stable) installed.
And so I follow these official guidelines.
Then I call up a fresh terminal session and try to run a
quasar create… which should have replaced
quasar initwith the upgrade.
Typing
quasar createafter the upgrad you get
unknown command. And a project created with
quasar inityields the following still.
app:paths
️ Error. This command must be executed inside a Quasar v0.15+ project folder.
app:paths For Quasar pre v0.15 projects, npm uninstall -g quasar-cli; npm i -g quasar-cli@0.6.5
Note that,
quasar-cliinstead of
@quasar/cli…
But this actually worked for me: I installed globally the optional
@quasar/app`` and then tried as suggested running an
npx quasar devin a troublesome project with its missing
.babelrc. With that the project carries out
quasar devas desired even though quasar-cli and quasar-framework are not found by a
quasar info…
And this is my ugly kludge for now. Sorry for confusion, mine and yours.
- metalsadman last edited by metalsadman
Thanks will take a gander.
In the meantime what does the trick for me for now is npx quasar dev in the project root … applies the globally installed Quasar CLI …
|
https://forum.quasar-framework.org/topic/3930/file-babelrc-is-missing
|
CC-MAIN-2019-43
|
refinedweb
| 740
| 70.8
|
Many of you must have played HiLo game in your childhood. Game may be some sort of similar to it, if not exactly same. It was fun, right?? So what if we are adult now? Let’s play this game once again in our own way. Let’s build a java program for this and start playing this wonderful game HiLo.
Writing HiLo game in Java
In below program, I have tried to simulate the HiLo game in java language. I have set two simple rules for this version of game:
- Guess the secret number in maximum 6 tries.
- The secret number is an integer between 1 and 100, Inclusive.
Everytime you will guess a number below secret number (only JRE knows it), “LO” will be printed. Similarly, wen you guess a number higher than secret number, “HI” will be printed. You have to adjust your next guess such that you are able to guess the right number within six attempts.
package hilo; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Random; public class HiLo { private Random generator; private int generatedNumber; private int numberOfAttempts; BufferedReader reader = null; public HiLo() { generator = new Random(); reader = new BufferedReader(new InputStreamReader(System.in)); } public void start() throws IOException { boolean wantToPlay = false; boolean firstTime = true; do { System.out.println(); System.out.println(); System.out.println("Want to play the game of Hi and Lo??"); if (wantToPlay = prompt()) { generatedNumber = generateSecretNumber(); numberOfAttempts = 0; if (firstTime) { describeRules(); firstTime = false; } playGame(); } } while (wantToPlay); System.out.println(); System.out.println("Thanks for playing the game. Hope you loved it !!"); reader.close(); } private void describeRules() { System.out.println(); System.out.println("Only 2 Rules:"); System.out.println("1) Guess the secret number in maximum 6 tries."); System.out.println("2) The secret number is an integer between 1 and 100, inclusive :-)"); System.out.println(); System.out.println(); } private int generateSecretNumber() { return (generator.nextInt(100) + 1); } private void playGame() throws IOException { while (numberOfAttempts < 6) { int guess = getNextGuess(); if (guess > generatedNumber) { System.out.println("HI"); } else if (guess < generatedNumber) { System.out.println("LO"); } else { System.out.println("Brave Soul, You guessed the right number!! Congratulations !!"); return; } numberOfAttempts++; } System.out.println("Sorry, you didn't guess the right number in six attempts. In other two words, YOU LOST !!!!"); System.out.println("The secret number was " + generatedNumber); } private boolean prompt() { boolean answer = false; try { boolean inputOk = false; while (!inputOk) { System.out.print("Y / N : "); String input = reader.readLine(); if (input.equalsIgnoreCase("y")) { inputOk = true; answer = true; } else if (input.equalsIgnoreCase("n")) { inputOk = true; answer = false; } else { System.out.println("Ohh come on. Even Mr. Bean knows where are 'y' and 'n' in the keyboard?? Please try again:"); } } } catch (IOException e) { e.printStackTrace(); System.exit(-1); } return answer; } private int getNextGuess() throws IOException { boolean inputOk = false; int number = 0; String input = null; while (!inputOk) { try { System.out.print("Please guess the secret number: "); input = reader.readLine(); number = Integer.parseInt(input); if (number >= 1 && number <= 100) { inputOk = true; } else { System.out.println("Really? You didn't read the rules boy. Your number is not between 1 and 100 (" + number + ")."); } } catch (NumberFormatException e) { System.out.println("Invalid input (" + input + ")"); } } return number; } }
Play the HiLo game
Now, the game is ready. Let’s play it.
package hilo; import java.io.IOException; public class PlayGame { public static void main(String[] args) { HiLo hiLo = new HiLo(); try { hiLo.start(); } catch (IOException e) { e.printStackTrace(); } } } Output: Want to play the game of Hi and Lo?? Y / N : y Only 2 Rules: 1) Guess the secret number in maximum 6 tries. 2) The secret number is an integer between 1 and 100, inclusive. Please guess the secret number: 40 LO Please guess the secret number: 60 LO Please guess the secret number: 80 HI Please guess the secret number: 70 LO Please guess the secret number: 75 LO Please guess the secret number: 77 HI Sorry, you didn't guess the right number in six attempts. In other two words, YOU LOST !!!! The secret number was 76
Hope you enjoyed this game.
Happy Learning !!
Feedback, Discussion and Comments
karthick kumar
Nice Code….
|
https://howtodoinjava.com/java/puzzles/hilo-guessing-game-in-java/
|
CC-MAIN-2021-31
|
refinedweb
| 686
| 53.27
|
I get this linker error: "public: void __thiscall rsblsb::Sound::play(void)" (?play@Sound@rsblsb@@QAEXXZ)
if I call system->playSound() from one file. If I call the exact same function from another file, it links correctly and the sound plays no problem.
I’m linking fmodex_vc.lib. I tested in 3 different configurations, and it’s always the same. Both files have .cc extension, both call the playSound function from inside a class member function, both classes are defined in the same namespace.
Any idea how this is even possible?
- oZZ asked 8 years ago
- You must login to post comments
Thoughts:
Clean from inside visual studio. Then quit visual studio and physically delete any intermediate directories, the ncb file, and any other intermediate/auxiliary files. Then open the project and REbuild it. This is mostly just voodoo, and you’ve probably already done it, but I swear it’s helped me sometimes.
The broken file is somehow including a "bad" header that the other files aren’t.
The broken file has bad compile/link settings just for it (e.g. someone changed the build options just for that file, pragmas, rules).
If rsblsb::Sound::play is inline (i.e. defined in a header file), make it a normal non-inline method.
If you’re linking to other libraries that you’ve built, try rebuilding those too.
Compare the mangled signature for FMOD::System::playSound shown in the link error with the mangled signature for the one that links correctly (it should appear somewhere in the .map file if you enable map file generation). If there are multiple versions of the function, you should be able to tell what the difference is by the mangled signature. With GCC you can use the "c++filt" program to decode the mangled names into readable declarations. I’m not sure if there’s a vc equivalent. I’m sure MSDN at least has a dictionary for decoding them by hand. This won’t fix your problem but it should give you an idea where the problem is.
- BananaRaffle answered 8 years ago
|
https://www.fmod.org/questions/question/forum-30597/
|
CC-MAIN-2017-13
|
refinedweb
| 350
| 67.45
|
bundled with Java 1.4 and later. Furthermore, most current XSLT processors written in Java support TrAX, including Xalan-J 2.x, jd.xslt, LotusXSL, and Saxon. The specific implementation included with Java 1.4 is Xalan-J 2.2D10.
Note
Annoyingly, the Xalan-J classes included in Java 1.4 are zipped into the rt.jar archive, so it's hard to replace them with a less buggy release version of Xalan. It can be done, but you have to put the xalan.jar file in your $JAVA_HOME/lib/endorsed directory rather than in the normal jre/lib/ext directory . The exact location of $JAVA_HOME varies from system to system, but it's probably something like C:\j2sdk1.4.0 on Windows. None of this is an issue with Java 1.3 and earlier, which don't bundle these classes. On these systems, you just need to install whatever JAR files your XSLT engine vendor provides in the usual locations, the same as you would any other third-party library.
There are four main classes and interfaces in TrAX that you need to use, all in the javax.xml.transforms package:. 4 through 6 can be repeated for as many different input documents as you want. You can reuse the same Transformer object repeatedly in series, but you can't use it in multiple threads in parallel.
For example, suppose you want to use the Fibonacci stylesheet in Example 17.5 to implement a simple XML-RPC server. The request document will arrive on an InputStream named in and will be returned on an OutputStream named out . Therefore, we'll use javax.xml.transform.stream.StreamSource as the Source for the input document and javax.xml.transform.stream.StreamResult as the Result for the output document. We will assume that the stylesheet itself lives at the relative URL FibonacciXMLRPC.xsl, and that it is also loaded into a javax.xml.transform.stream.StreamSource . The following multithreaded, then the simplest solution is to give each separate thread its own TransformerFactory and Transformer objects. This can be expensive, especially if you frequently reuse the same large stylesheet, because. The Templates class represents the parsed stylesheet, and you can ask the Templates class to give you as many separate Transformer objects as you need. Each of these can be created very quickly by copying the processor's in-memory data structures rather than by reparsing the entire stylesheet from disk or the network. The Templates class itself can be used safely across multiple threads.
For example, you might begin loading and compiling the stylesheet, like this:
TransformerFactory xformFactory = TransformerFactory.newInstance(); Source xsl = new StreamSource("FibonacciXMLRPC.xsl"); Templates stylesheet = xformFactory.newTemplates(xsl);
Then later in a loop, you would repeatedly load documents and transform them like this:
while (true) { InputStream in = getNextDocument(); OutputStream out = getNextTarget(); Source request = new StreamSource(in); Result response = new StreamResult(out); Transformer transform = templates.newTransformer(); transformer.transform(request, response); }
The thread-unsafe Transformer object is local to the while loop; therefore, references to it don't escape into other threads. This prevents the transform() method from being called concurrently. The Templates object may be shared among multiple threads. It is thread safe, so this isn't a problem. Furthermore, all of the time-consuming work is done when the Templates object is created. Calling templates.newTransformer() is very quick by comparison.
This technique is particularly important in server environments in which the transform may be applied to thousands of different input documents, with potentially dozens being processed in parallel in separate threads. Example 17.6 demonstrates with yet another variation of the Fibonacci XML-RPC servlet. This is the first variation that does not implement the SingleThreadModel interface. It can safely run in multiple threads simultaneously ., as in which a Java system property can be set. TrAX picks from them in the following order:
Invoking.parsers.DocumentBuilderFactory= classname
The class named in the META-INF/services/javax.xml.transform.TransformerFactory file in the JAR archives available to the runtime.
Finally, if all of the preceding"?>
This processing instruction is a hint. It is only a hint. Programs are not required to use the stylesheet that Internet Assigned Numbers Authority (IANA) as MIME types must be. It is not endorsed by the relevant W3C specifications for XSLT and attaching stylesheets to XML documents, and it is unlikely to be in the future.
Official registration of an XSLT specific-media-type application/xml+xslt has begun, and this type may be used in the future to distinguish XSLT stylesheets from other kinds of XML documents. However, the registration has not been completed at the time of this writing.
In addition to the required href and type pseudo-attributes, the xml-stylesheet processing instruction can have up to four other optional pseudo-attributes:.
For example, the following xml-stylesheet processing instructions point at two different XSLT stylesheets, one intended for print and found at the relative URL docbook-xsl-1.50.0/fo/docbook.xsl, and the other intended for on-screen display and found at docbook-xsl-1.50.0/html/docbook.xsl. Each is the primary stylesheet for its, the following code fragment attempts to transform the document read from the InputStream in according to an xml-stylesheet processing instruction for print media found in that document's prolog. The title and encoding of the stylesheet are not considered , and thus are that points :
It's possible to test the boolean values of these features for the current XSLT engine with the getFeature() method in the TransformerFactory class:
public abstract boolean getFeature (String Name )
These URLs are just identifiers like namespace URLs. They do not need to be and indeed cannot be resolved. A system does not need to be connected to the Internet to use a transformer that supports these features.
There's no corresponding setFeature() method, because a TrAX feature reflects the nature of the underlying parser. Unlike a SAX feature, it is not something you can just turn on or off with a switch. A processor either supports DOM input or it doesn't. A processor either supports SAX output or it doesn't, and so on.
Example 17.7 is a simple program that tests an XSLT processor's support for the standard JAXP 1.1."); } } }
Followingstandard, custom attributes that control their behavior. Like features, these are also named via URIs. For example, Xalan-J 2.3 defines the following three attributes:., the followingstandard, by using a URIResolver , you can redirect the request to a proxy server, to local copies, or to previously cached copies. This interface, summarized in Example 17.8, returns Source objects for a specified URL and an optional base. It is similar in intent to SAX's EntityResolver except that EntityResolver is based on public and system IDs, whereas this interface is based on URLs and base URLs.. Example 17.9 is a simple URIResolver implementation that looks for a gzipped version of a document (that is, a file name that ends with .gz ). If it finds one, it uses the java.util.zip.GZIPInputStream class to build a StreamSource from the gzipped document. Otherwise, it returns null, and the usual methods for resolving URLs are followed.
import javax.xml.transform.URIResolver; the Transformer objects it creates following:
The stylesheet is syntactically incorrect.
The source document is malformed .
Some external resource that the processor needs to load, such as a document referenced by the document() function or the .class file that implements an extension function, is unavailable.
By default, any such problems are reported by printing them on System.err . You also can provide more sophisticated error handling, reporting, and logging by implementing the ErrorListener interface. This interface, shown in Example 17.10, is modeled after SAX's ErrorHandler interface. Indeed, aside from all of the arguments being TransformerException s instead of SAXException s, it's almost identical.fatal errors, so I just classify them both as "severe." [2]
[2] You could define a custom subclass of Level that did differentiate fatal and nonfatal errors, but because this is not a book about the Logging API, I leave that as an exercise for the reader.
[2] You could define a custom subclass of Level that did differentiate fatal and nonfatal errors, but because this is not a book about the Logging API, I leave that as an exercise for the reader. to which the object will report problems., the following code fragment installs separate LoggingErrorListener s on the TransformerFactory , as well as the Transformer object it creates, which-referenced elsewhere in the stylesheet using the form $ name . Once set, the value of an XSLT variable is fixed and cannot be changed. There is an exception, however: if the variable is defined with a top-level xsl:param element instead of an xsl:variable element, then the default value can be changed before the transformation begins.
For example, the DocBook XSL stylesheets I used to generate this book have a number of parameters that set various formatting options. I
You can change the initial (and thus final) value of any parameter for DOM types such as Node and NodeList . I wouldn't rely on it for anything more complex, such as preceding of the values, but set them either in Example 17.12 provides named constants for all of the property names., the following Java code fragment has the same effect as the preceding provide their own implementations of these interfaces. For example, IDs will be resolved relative to the URL of the stylesheet source.
A DOMSource is a wrapper around a DOM Node . The DOMSource class, shown in Example 17.13, provides methods to set and get the node that serves as the root of the transform, as well as the system and public IDs of that node., transforming document nodes is all that is truly reliable. (It's not even clear that the XSLT processing model applies to anything that isn't a complete document.) In my tests, Xalan-J could transform all, shown in Example 17.14, provides constructors and methods to set and get the node that serves as the root of the transform, as well as the system and public IDs of that node. that an XMLReader reads from a SAX InputSource . . These include streams, readers, writers, strings, and files. What unifies these is that none of them know they contain an XML document. Indeed, on input they may not always contain an XML document, in which case an exception will be thrown as soon as you attempt to build a Transformer or a Templates object from the StreamSource .
The StreamSource class, shown in Example 17.17, provides constructors and methods to get and set the actual source of); }
Avoid specifying both an InputStream and a Reader . If both of these are specified, then which one the processor reads from is implementation dependent. If neither an InputStream nor a Reader is available, then the processor will attempt to open a connection to the URI specified by the system ID. Be sure to(); }
Be sure to specify the system ID URL and only one of the other identifiers ( File , OutputStream , Writer , or String ). If you specify more than one possible target, then which one the processor chooses is implementation dependent.
|
https://flylib.com/books/en/1.131.1.174/1/
|
CC-MAIN-2021-31
|
refinedweb
| 1,881
| 56.66
|
BridJ is a library that lets you call C, C++ and Objective-C libraries from Java as if you were writing native code. It is a recent alternative to JNA.
With the help of JNAerator, it provides clean and unambiguous mappings to C/C++ code and a very straightforward and highly typed API to manipulate pointers, classes, structs, unions...
It bridges Java's gap when it comes to native-world interoperability.
void someFunc(float* values);
float* array = new float[10];
float value = array[4];
someFunc(array);
delete[] array;
import org.bridj.Pointer._
...
@native def someFunc(values: Pointer[Float]): Unit
...
val array = allocateFloats(10)
val value = array(4)
someFunc(values)
// optional : will be eventually called by the Garbage Collector
array.release
import org.bridj.Pointer;
import static org.bridj.Pointer.*;
...
public static native void someFunc(Pointer<Float> values);
...
Pointer<Float> array = allocateFloats(10);
float value = array.get(4);
someFunc(values);
array.release();
Read more about :
In three words : C++, Performance and Usability
BridJ is dual-licensed under a very liberal BSD license and the very liberal Apache 2.0 license.
BridJ is released as a self-contained JAR.
However, it includes a copy of the ASM library and its native library are statically linked with a modified version of Dyncall.
More details here : CreditsAndLicense.
On NativeLibs4Java's mailing-list.
Please read the Change Log and have a look at the CurrentState page.
Binaries are currently available and routinely tested for the following platforms :
... with plans for FreeBSD (help and / or test hardward welcome)
Sure, please read Build.
Please read HowToHelp.
Things BridJ aims at doing better than JNA :
import static org.bridj.Pointer.*;
...
Pointer<Integer> p = pointerToInts(1, 2, 3, 4);
p.set(0, 10);
for (int v : p)
System.out.println("Next value : " + v);
JNA's advantages over BridJ :
BridJ's advantages :
SWIG's advantages :
Please read Who's using BridJ.
Just paste your C header into JNAerator, choose BridJ as runtime and click on JNAerate.
You sure can ! BridJ provides a seamless cross-platform binaries JAR extraction mechanism, which it uses for its own needs.
For detailed information about embedded libraries, please read Libraries Lookup.
You can set the -Dbridj.logCalls=true property or the BRIDJ_LOG_CALLS=1 environment variable.
In this log mode :
Short answer is : you don't need to.
Only Windows x86 has different calling conventions, so @Convention annotations will typically be ignored silently on other platforms.
Simply declare that your function throws LastError, that's it !
You'll get exceptions soon enough ;-)
If you're on Windows x86 (or on 64 bits windows in a 32 bits JVM), this is typically a case of bad calling convention being used for a native function or callback binding. Please triple-check the calling convention (could it be stdcall ?) and add a proper @Convention(Convention.Style.xxx) annotation.
This crash indicates that the program tried to access memory it wasn't supposed to access (for instance someone read at index 100 in an array of 10 elements).
It may also be caused by an invalid calling convention being used, see previous FAQ item)
The tricky part here is that this kind of errors usually does not surface immediately : the crash will typically occur in later calls, giving false leads on where the error actually occurred.
The only reliable way to debug such errors is to make use of a native debugger. On Windows, Visual C++ comes with a very nice debugger and is available for free in its Express edition (under some conditions).
To debug your crash with Visual C++, you should compile your native library in debug mode if possible, then run the java process with the debugger (or attach a debugger to it before any native call is performed). You'll want to turn as many debug checks on as possible in the debugger settings.
Also, it will be easier to set the full path to the debug version of your DLL using a manual path override : if your library is named MyLib in BridJ (the value inside the @Library("MyLib") annotation), you can :
BRIDJ_MYLIB_LIBRARY=c:\...\MyProject\Debug\MyLib.dll
"-Dbridj.MyLib.library=c:\...\MyLib.dll"
You can then check which exact version of your DLL was picked by BridJ by scanning through Visual C++'s "Modules" window.
As far as BridJ is concerned, you may try turning the direct mode off with BRIDJ_DIRECT=0 or -Dbridj.direct=false and see if the issue still happens.
A last option would be to turn BridJ's "protected" mode on, but right now you'd have to recompile it from sources and uncomment the #define ENABLE_PROTECTED_MODE directive in Exceptions.h. Note that protected mode is currently slow and unstable which is why it's not enabled by default ;-).
If BridJ fails to load a library, it can be that :
Getting lots of bug reports is crucial to making BridJ better, so we'd like to encourage you to file issues as you find them without worrying too much about the contents : it's often better for us to have an incomplete report than no report at all, and anyway we'll let you know very politely if your issue comes from a misuse rather than a bug in BridJ.
Here's the issue tracker : NativeLibs4Java's Issues on GitHub.
And here's a guide on How to Submit Bugs.
|
http://code.google.com/p/bridj/wiki/FAQ
|
crawl-003
|
refinedweb
| 891
| 55.74
|
12.8.:
Try running this in Codelens. When a function is invoked in Codelens, the local scope is separated from global scope by
a blue box. Variables in the local scope will be placed in the blue box while global variables will stay in the global
frame. lifetime ends when the function completes its execution.
So it is not possible for a function to set some local variable to a value, complete its execution, and then when it is called again next time, recover the local variable. Each call of the function creates new local variables, and their lifetimes expire when the function returns to the caller.
Check Your Understanding
func-7-1: True or False: Local variables can be referenced outside of the function they were defined in.
- True
- Local variables cannot be referenced outside of the function they were defined in.
- False
- Local variables cannot be referenced outside of the function they were defined in.
func-7-2: Which of the following are local variables? Please, write them in order of what line they are on in the code.
numbers = [1, 12, 13, 4] def foo(bar): aug = str(bar) + "street" return aug addresses = [] for item in numbers: addresses.append(foo(item))
The local variables are
- 33
- Incorrect, look again at what is happening in producing.
- 12
- Incorrect, look again at what is happening in producing.
- There is an error in the code.
- Yes! There is an error because we reference y in the producing function, but it was defined in adding. Because y is a local variable, we can't use it in both functions without initializing it in both. If we initialized y as 3 in both though, the answer would be 33.
func-7-3: What is the result of the following code?
def adding(x): y = 3 z = y + x + x return z def producing(x): z = x * y return z print(producing(adding(4)))
|
https://runestone.academy/runestone/static/fopp/Functions/Variablesandparametersarelocal.html
|
CC-MAIN-2018-51
|
refinedweb
| 321
| 72.97
|
Display all Acct_No's in a subject line of a Form_letter Report.Vijetha Aug 21, 2013 10:53 AM
Hi Everyone,
I have a problem in the reports.
I have created a report which involves a 'Form_Letter' & 'Tabular' Styles.
In the Subject line of the form_letter_text there is a field selected from database-table-column that is as below:
Sub: Issue of Interest certification against ACCT No.:&<ACCT_NO>.
The above &<ACCT_NO> populates the 'Acct No', when enter the Customer_ID in the report parameter:
This works fine if a customer has only one Acct_No.
The problem arises when a customer has more than one Acct_No.
If a Customer has more than 1 account number; say 3 Accounts;
then in the Subject line, 3 Acct_No's should be displayed.
But I'm getting different letter for different 'Acct_No' in 3 different pages.
I want it to display only 1 page instead of 3pages.
All the Acct_Nos of that particular Customer_ID must be displayed in the Subject_Line when i run the report.
Can anybody help me with this?
Thank You.
1. Re: Display all Acct_No's in a subject line of a Form_letter Report.InoL Aug 21, 2013 3:33 PM (in response to Vijetha)
You can use LISTAGG in Oracle 11g:
with accounts as (
select 'acct1' acct_no from dual
union all select 'acct2' acct_no from dual
union all select 'acct3' acct_no from dual)
select listagg(acct_no, ', ') within group (order by acct_no)
from accounts
----------------------
acct1, acct2, acct3
2. Re: Display all Acct_No's in a subject line of a Form_letter Report.Vijetha Aug 22, 2013 5:52 AM (in response to InoL)
Hi InoL ,
Sorry forgot to mention that i'm using Report builder 6i.
3. Re: Display all Acct_No's in a subject line of a Form_letter Report.InoL Aug 22, 2013 1:28 PM (in response to Vijetha)
With Oracle 11g I mean the database version. You can use LISTAGG in a function in the database and call this function from your report.
If you don't have an Oracle 11g database, use STRAGG, which is not a standard Oracle function. You can Google for it.
4. Re: Display all Acct_No's in a subject line of a Form_letter Report.Priyasagi Aug 28, 2013 10:15 AM (in response to InoL)
Hi Vijetha,
Try this,
function accFormula return Char is
accno varchar2(60):=null;
j varchar2(1);
begin
declare cursor c1 is
select rownum,acct_no from accounts where customer_id=:cust_id;
begin
j:='';
for i in c1 loop
if c1%notfound then
exit;
else
accno:=rtrim(accno)||j||i.acct_no;
j:=',';
end if;
end loop;
end;
return (accno);
end;
I think its helpful to you.
|
https://community.oracle.com/message/11156019
|
CC-MAIN-2017-22
|
refinedweb
| 443
| 53.41
|
07 May 2013 18:49 [Source: ICIS news]
HOUSTON (ICIS)--The average price for a gallon of gasoline in the ?xml:namespace>
Diesel prices are projected to average $3.88/gal for April-September, the EIA said in its short-term energy outlook (STEO).
US gasoline prices averaged $3.69/gal last summer, while diesel averaged $3.95/gal.
Looking further ahead, the EIA is projecting a 2013 average price for gasoline at $3.50/gal and a 2014 average price of $3.39/gal. The agency forecasts diesel to average $3.92/gal this year and $3.79/gal in 2014.
In the spot crude oil markets, the EIA is projecting West Texas Intermediate (WTI) to average $93.17/bbl for 2013 and $92.25/bbl for 2014.
The agency is expecting a larger price decrease for Brent crude – and thus a decrease in the spread between the two global market crudes – with Brent forecast to average $105.89/bbl in 2013 and $100.75/bbl in 2014.
The tightening of the spread is due to several pipeline projects expected to come on line in 2014 that should reduce the cost of transporting crude oil to Gulf Coast refiners, the EIA said.
US Henry Hub natural gas prices are forecast to average $3.80/MMbtu in 2013 and $4.00/MMbtu in 2014, the agency
|
http://www.icis.com/Articles/2013/05/07/9665837/us-eia-projects-16-centgal-decrease-in-gasoline-prices-this.html
|
CC-MAIN-2014-49
|
refinedweb
| 226
| 69.99
|
GREPPER
SEARCH
SNIPPETS
USAGE DOCS
INSTALL GREPPER
All Languages
>>
Javascript
>>
get channel id discord js v12
“get channel id discord js v12” Code Answer’s
get channel id discord js v12
javascript by
Crazy Cod
on Jan 02 2021
Comment
0
client.channels.cache.get('id')
discord js v12 get user tag with id
javascript by
Worried Wryneck
on Dec 15 2020
Comment
0
const User = client.users.cache.get("UserID"); //put id instead of "UserID"
Add a Grepper Answer
Javascript answers related to “get channel id discord js v12”
Find channel discord js
discord js channel send
get voice channel of sender discord.js
discord js people in voice channel
how to search for a voice channel within a guild using discord.js
discord.js custom create channel
discord.js leave voice channel
how to get a channelid discord.js
get server by id discord.js
discord.js create channel
discord js get all channels
discord.js message.channel
how to get all the voice channels in discord js
how to create channel in discord.js
discord.js create channel and get id
Discord.js v12 member voiceChannel
Javascript queries related to “get channel id discord js v12”
find channel by name discord.js v12
discord js fetch user
get channel id discord.js
discord.js get channel id
discord.js fetch message
discord js v12 fetchguild
resolveid discord.js
get channel id discord.js 12
get the id of the channel in discord.js
npm discord id to name
how to find channel using id in discord.js v12
get channel by id discord js v12
how do i get the channel id discord.js v12
get channel name with channel id discord js v 13
get channel id discordjs
discord.js get id of channel just made
discord js fetch member
get id of a created channeldiscordjs
discord js channel id
get channel id in discord.js
discord.js v12 find channel by name
finding a channel by name discord.js v12
discord.js v12 get channel
how to get created channel id discord.js
discord.js v12 channel find
get channel discord.js v12
discordjs find channel by name v12 and get its id
fetch channel discord.js
client.users.get is not a function
discord js fetch message
get all messages from channel discordjs v12
discordjs get tag from user id
discord id to username discord.js
discord js how to convert user id to username
discord js id to username
discord.js v12 get name from id
discord js v12 get player username
discord.js v12 chat bot id
message.guild.members.fetch v12
discord fetch user
message.guild.members.cache.foreach(member => { only dming me
how to get the user channel from discordjs
get cahnnel discord js v12
find guild by id discordjs v11
how to find a channel from client discord.js
discord js search channel by name
find channel discord.js
get channel by id discord.js v12
discord js v12 get user tag with id
discord.js v12 get channel by id
discord.js channel id
get all messages from userid discordjs v12
discordjs v12 get channel
get channel id with channel name discord.js
discord check id of a channel with js
message.guild.members.cache
discord.js tag user
discord js tag user
channel id discord.js
get channel name discord.js v12
discord.js channel id
find channel discordjs v12
get channel count discord.js v12
discord.js fetch channel messages
get discord channel by id js
how to get the channel id in discord.js
get channel id from message discord js
get channel id discord js message
discord.js v12 get channel by name
how to get channel id in discord,js
get channel discord.js by id
get channel by id discord js v13
channel by id discord.js
get channel by id discordjs v12
find a channel discord.js
fetch user discord js
discordjs fetch message
get channel id discordjs v12
how to get user from tag discord js
discord.js fetch channel
user id to username discordjs
discord js fetch user name
username from userif discrod js
fetchuser discord.js v12
message.guild.members.fetch() v12
discrod v12 find all users
how to get username of a tagged id in discord.js
message.guild.channel.cache.get
typeerror: message.guild.channels.exists is not a function
message.member.channels.cache.find
how to get message from id discordjs v12
bot.users.cache js node 12
discord.js find all text channels
discord js guide presence member
get channel id discord js
find a channel discord.js v12
get channel id discord js v12
how to get a channel by id discord.js
discord.js how to get channel id
find a channel discord.js v12 by id
discord.js members.fetch()
discord.js 12 set activity
how to connect user client in discord.js 12
discord.js get user tag using id
discord.js how to get the channel id from message
how do i get the channel id code discord.js v12
create channel discord.js v12
discord.js v12 find channel
channel id discord js
get user from message discord js v12
how to find a channel by its name discord.js
discord js get existing channel
get channel from id discordjs v12
how to get channel id discordjs
discord v12 get channel by id
discord.js get channel by id v12.5
how to get channel id discord.js v12
discord.js getting a channel id
discord js get channel id
discordjs find channel by name v12 and get id from fined channel
javascript get channel id
discord.js v12 user tag
get a channel by id discord.js
package.json discord.js v12
get user by discord tag discordjs
discord.js tag user using id
how to get a username from id discord.js
how to get discord info from id discord js
discord.js v12 get username from id
discord js v12 user tag with id
check for channel name discord.js
fetch a channel discord.js v12
guild.member.fetch
client.users.fetch discord.js
discord.js get channel id by name
guild.channels.cache.find
find every channel with name in every guild discord.js
discord.js v12 filter is not defined
fetch channel position discord js
get channel by id discord.js
discord.js v12 get channel by ud
Browse Javascript Answers by Framework
AngularJS
jQuery
Express
Bootstrap
React
Vue
Backbone
Ember
Next.js
Node.js
Ionic
Flutter
More “Kinda” Related Javascript Answers
View All Javascript Answers »
login to discord with token
discord.js v13 send embed
how to see in how many servers your discord bot is d.js
discord.js send text in different channel on server
discord.js all intents
blacklisted word discord.js
discord.js get user by id
get every member of a server discord js
how to make data title case in discord js
title case javascript
how to get client.user.avatar
discord.js display avatar url
discordjs 13 TypeError Valid intents must be provided for the Client.
setpresence discord.js
discord.js kick user
discord js send dm to user
see if discord message is in dm discord.js
discord.js wait seconds
delay in code discord.js
get discord.js role
discord bot status javascript
Find channel discord js
discord.js change bot status
setImage(message.author.displayAvatarURL)
discord javascript how to create a role
how to create an invite discord.js
create a category discord.js
discord.js how to get all guilds
discord.js create unexipable invite
how to create hyperlinks discord.js
discord.js custom create channel
discord.js message on member add
discord.js edit message by id
discord.js mention regex
send a message to a specific channel discord.js
send a message when a bot joins your server discord.js
get channel id discord js v12
discord.js join voice channel
javascript error discord
get message author discord.js
discord js delete message after time
javascript discord bot 8 ball command
how to make a discord.js 8 ball command
discord javascript error cannot find module
discord js user has role
discord bot steaming satus
discord.js channel regex
discord.js role regex
windows 10 toast notifications nodejs
mute everyone in call discord.js
send message to all servers discord.js
how to check if user is typing discord js
how to create channel in discord.js
how to send an embed message discord.js
set a discord js v12 bot activity
How to hthe amount of users online in discordjs
loopback pagination
send file discord js v12
discord.js get all members with role
Install Discord.js
discord.js bot
how to use falix nodes for discord bot
discord.js random message
discord js how to mention bot
discord.js find role by name
how to get a channelid discord.js
discord.js send message to specific channel
discord.js how to edit a message
discord.js leave voice channel
how to check if a message has an attachment discord js
discord.js bot activity
discord.js how to kick a user
discord js duplicate channel
discord.js get username
discord.js how to send a message to all guilds
discord.js get attachment url
Check ratelimit discord js
discord.js arguments
discord js sending a message to a specific channel
discord.js message
discord client.send_message js
discordjs delete all messages in channel
how to check if the user is in a certain guild in discord
Discord.js ban command
discord.js listen for message
dm someone by id discord.js
how to make link in discord.js
how to send emoji as ID discord.js
how to define emojis from your server in discord.js
discord.js empty field
discord bot playing game
Embed Example Discord.js
how to send a message discord.js
If statement discord js
how to test on user reaction discord.js
discord.js remove reaction
discord.js send embed
discord.js rich embed
how to send a message using discord.js
how to define args using param discord.js
discord js send message to specific channel
discord.js button
check if message mentions users discord js
discord js mention
load a config file discordjs
remove role discord.js
how to send a message to a discord server using a bot
discord.js say command embed
get status of a user discord js
send a message using discord.js
Discord embeds
discord message reply
remove a user from a reaction discord.js
discord.js remove every role a user has
Bots latency discord js
discord delete messag
discord js clear message from id
discord js fetch user
how to make a ping in discord.js
discord.js start code
Bots member count discord js
discord.js clean content
how to make a purge command discord.js
discord embed image with file discord js
discord.js on ready
discord.js get user banner
discord.js set playing tag
discord.js setactivity
discord js check if person banned
how to make a bot react to own message js
discord.js set activity
discord.js get first mention
get server by id discord.js
how to search for a voice channel within a guild using discord.js
discord.js get the message before
discord.js mute script
discord buttons
discord.js MessageEmbed
discord.js guildMemberAdd
discord.js
discord.js install
nodejs discord
discord.js edit embed message
delete message discord.js
message delete discord.js
change git commit message
delete discord.js slash command
discord js stats command
bitfield permissions discord,.js
discord.js timeout
server status minecraft javascript
discord.js start
discord js v12 get user tag with id
discord js message
discord.js emoji in embed
discord js bot embed user profile picture
how to reference the bot joining a server in discord.js
discord.js slash commands
discord js add slash command
discord.js lockdown command
discord js lockdown command
discord.js on slash command
how to make a discord bot send a message
farewell discord.js
user icon discord js
discord.js await message
how to unban in discord js
discord js embeded message hyperlink
discord button
discord.js check if user is admin
discord.js remove embed from message
discord.js dm all members
recieve voice channel audio discord.js
discord.js ban user
dm discord.js
discord.js create permanent invite
discord.js get user by username
discord.js guildMemberRemove
dm message collector discordjs
permissions discord.js
Discord.js Get A Bot To Join A Music Chanel
discord js remove reaction from user
discord.js messageUpdate
discord.js bot presence
client missing intents discord.js
how to edit message discord.js
discord delete message
discord bot remove message reaction
checking if a user has a role in discord js
how to use msg.send instead of msg.reply discord.js javascript
discord js channel send
discord.js clear console
send a message discordjs
variable for every user discord.js
discord.js find word inside comment
how to delete a reply in discord.js
slap user discord.js
discord.js create channel and get id
discord.js bot mention
take from your discord bot dms discord js
restart bot discord.js
discord js check if message author is admin
how to send dm to every member in discord with discord.js
kick members node js
discord.js add button to message
kick commands discord.js
discord.js setinterval
discord.js check every x minutes
discord js check every x minutes
how to get a bot online on discord
discord.js presence update
simple kick command discord.js v12
discord.js set role permissions for all channels
spam system discord.js
send a message in every guild discord.js
fivem server discord.js
how to set variable in discord.js
message.channel.name.includes
how to check if a user sent a message in discord js
bot prefix discord.js
set embed color discord.js
discord js on
discord js
discord.js v12 how to set owner commands
discord.js reply to message author
discord javascript error on startup
discord.js add image to embed
discord js presence update
discord.js role commend
This Command Only Server discord.js
discord.py to discord.js converter
discordjs v13 get message content
const { message } = new assert.AssertionError({ actual: 1, expected: 2, operator: 'strictEqual' });
discordjs say command
discord.js reply to message
discord.js add role to user
bot discord comment récupérer la pdp de quelqu'un
discord js mention author
discord js send author a dm
message.author
discord.js delete commend after reply
dm Command discord.js
const { message }
discord.js how to go back a file
get all messages from userid discordjs v12
discord-buttons collector
How to blacklist words with discord.js
discord.js slash commend
récupérer avatar discord bot
hide url in discord.js
status discored jks
how to make your discord bot respond to specific users
custom status discord bot
client.guilds foreach
discord nuke bot online
discord.js v11
blacklist word discord.js
discord.js say command
announcement for all server bot is in
discord.js checker
discord js get specific user from users
install discord js master
discord js dropdown
help source code discord.js
discord js buttons
song discord.js
how to ghost ping on discord
how to do multi ban discord.js
discord.js blank field
delete a channel
swear word javascript + cooldown + delete mesagge discord.js
suggestion discord.js
How do I make a Discord.js-commando command only usable by people with the user IDs I provide?
discord js ping command
bot react message with custom emoji
discord rich embed join button
discord js get badge user
discord.js change role permissions
discord.js mention
dsicrod.js bot answer to himself
discord.js bot credits command
how to make console log hello in discord.js
discord.js create channel
use token id to sign in discord
discord.js ADMINISTRATOR commend
discord js kick command
discord.js mobile status
mute command discord.js v12
delete field embeded discord.js
check if user is streaming discord js
discord.js vs discord.py
discord music bot js source code
discord.js get users tag by id
discord.js admin commands
discord.js visual studio code music bot
CHANGER le STATUT DE JEU de son bot
how to add author to javascript
discord js get all channels
webhook discord.js
discord.js anonymous channel
why is my bot not going online discord.js
welcome discord.js
how to make a discord js bot get its own message id
discord random message
discord.js play song
discord.js dm
discord.js react to message
get the authors username discord.js
how to require token in discord.js without client
How to create a command that receives attributes in Discord in js
random discord.js
Discord.js v12 member voiceChannel
Delete All Channels discord.js
Bot say command discord.js
discord report command
js when you leave
js stop redirect
how to make a leave message in javascript
discord.js calculator command
discord js bot leave voice channel
get voice channel of sender discord.js
discord.js purge
add role to channel discord.js
discord.js lock channel
discord.js message.channel
discord js people in voice channel
discord.js check if member is in server
how to read if a person has send a message on discord.js
how to log all messages discord.js
discord.js ticket system stackoverflow
how to code welcome messages
Discord bot client login
discord.js TypeError: Reactedmsg.delete message using id
command to create react app
create react app
react
create new react app
make react app
how to start react app in windows
react install
react web app create
react create app
create-react-app
how to create the rect project
react app
create readct app
react init
npx create-react-app
how to create react app
react js installation
react start new app
install react
react js installation steps
npm create react app
react simbu
create react app scaffolding
react.js installation
create react project
Install and run react js project...
creat react app
create react js app
react simbu2013 js
switch statement javascript game
c++ switch
java swtch
switch c++
wtich js
js switch case
switch case javascript
string split javascript
javascript setinterval
javascript capitalize words
javascript capitalize string
javascript uppercase first letter
js first letter uppercase
fetchcall
fetch in js
refresh page javascript
window.reload
reload page javascript
reload page in typescript
refresh window js
js actualiser
npm install router dom
install react router dom and save
Router
npm react router dom
react router dom npm
Can't resolve 'react-router-dom'
download react router dom
npm install react-router-dom --save
react router dom IndexRedirect
jquery redirect
How do I redirect to another webpage?
redirect javascript
react routes
react-router-dom
route react
react router dom install
react-router
'react-router-dom'
how to use routes in react js
how to use react router
react-router react-router-dom
react routing
how to do routes react js
add class in loop jquery
jquery each get index
inline style jsx
.innerhtml
Javascript get text input value
javascript loop object
XJavascript:$.ge
javascript trim
try catch in javascript
javascript try catch finally
check node version
node js version
js remove duplicates from array
javascript while
javascript get url
javacript getHTTPURL
get current url js
javascript get current url
js css link create hash link
event listener javascript
uppercase javascript
uppercase string in js
object.keys
js log object keys
object keys javascript
foreach javascript
javascript addeventlistener
javascript to string
tostring javascript
jquery google cdn
jquery link
jQuery ui embed
ajax cdn
ajax src
use jquery
jquery script url
jquery w3school
jquery link cdn
node json stringify
retrieve object array value based on key
Find a value in an array of objects in Javascript
let arr = [ { name:"string 1", value:"this", other: "that" }, { name:"string 2", value:"this", other: "that" } ]; let obj = arr.find(o => o.name === 'string 1'); console.log(obj);
find an object in an array of objects javascript
Finding the array element:
find particular object from array in js
how can search in object in array
js find object from value in array
find in array of objects javascript
javascript search in object array
find array javascript
get date javascript format
javascript date to string format
javascript date format
fecth post json
fetch post json
JS Fetch API Post Request
fetch json post
window.onload
javascript regex email
format date js
local storage javascript
localstorage javascript
jquery onclick function
react fontawesome
npm i axios
axios install
creating user rails and redux
axios
compare dates in js
Javascript compare two dates
js create element
express js basic example
express js example
expressjs hello world
express hello world
hello world expressjs
add style javascript
parseint javascript
javascript string to number
how to update node js version
js string to date
javascript try
javascript try catch
tostring js
number to string javascript
javascript remove from array by index
how to refresh the page using
map object es6
js map over object
map through keys javascript
.map for object javscript
map an array stack overflow
how map on object in javascrtipt
making axios call with headers
header in axios
install react app
install react js
jquery each
js replace all symbols in string
how to generate random string in node js
js replace all
javascript replace all occurrences of string
drop zone js
get image as blob
remove prefix js
exponent form calculator in angular
javascript location redirect
js read xml file
mongoose connection nodejs
for ... in ...
grepper valid base64
uid js
select all child elements javascript
block comment js
detect keypress javascript
get an array with unique values
react document documentMode not found
how to like posts on instagram js
how to draw ellipse in javascript canvas
JS node instal fs
uppercase string in js
How do you wait for 5 seconds in JavaScript?
node js how to basic auth to specific urk
.ignore file nodejs
lesson-3
node sass error
js how to wait until all elements load
fibonacci sums javascript
why does my page reloads on form submission
dockerignore node modules
get average and sum javascript
find single quote and replace in javascript
store array in localstorage
js foreach key value
js map to json
how to reload a module in node.js
js data object length
check if two rectangles overlap javascript canvas
vue deep watch
vuejs bootsrap modal hidden event
javascript Compare two arrays regardless of order
go to page jquery
get query param javascript
typescript get class list for element
find only vowels in string Javascript
angular input change event
mongoose count
get current url angular
get id of clicked element javascript
Is TypeScript slower than JavaScript
Get TimeZone from Client JS
jQuery add table row
Tableau JS api getdata
mongodb nodejs connect localhost
javascript remove first character from array list
Half or Left Triangle Pattern in JavaScript
check if url is http or https javascript
float force loopback
Scrollout js
hover vanilla javascript
Material-ui Accessible icon
lodash remove undefined values from object
json server npm
tailwind in angular
angular datatable reload with pagination
how to print the error massege in js
javascript ean13 checksum generate
.env not working on react
Overflow Debugger
js innerHTML
difference between e.preventdefault and e.stoppropagation and return false
str_word_count php js
ios react native detect locale
use promis with date angular
jquery 1 second after page load
2 taps is required to close keyboad in react native
how to remove last element in js
how to convert variable to string in jquery
To set the text of button using Jquery
check unique object in array javascript site:stackoverflow.com
jquery swap table rows
react native mock
convert decimal to binary javascript
npm err! 503 service unavailable proxy
call json api javascript
chrome design mode console
isPrototypeOf js
js wait command
jquery unfocus
javascript remove style
How to change height of bottom material tab navigator from react-naviagtion
Async/Await
How to use auth in REST API calling
angular current year
Syntax Error: Thread Loader (Worker 0) .eslintrc.js: Environment key "es2021" is unknown at Array.forEach (<anonymous>)
js repeat
js set get first value
lodash json key compare
set default types react
how to add oncklick button react
javascript create object from key value pairs
How can I select all elements without a given class in jQuery?
create array, fill with spaces, convert to string and concat
electron sample question
jquery data attribute
vue js readdir
what are the two ways to create an array in javascript examples?
redirect page on mobile screen size javascript
jsdoc object destructuring
javascript code
Get 7 days Array
react native map array of objects
js string to charcode array
js select and copy on click
VM724:1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
javascript get child element by parent id
javascript deap clone an object
js insert
how to stop background scrolling when popup is open
knex.js migration create
javascript take any number of arguments
prevent paste in input
js get smallest value of array
javascript random boolean
javascript sort map by value
responsive font size react native
hgow to hide scroll bar and add buttons in javascript
django ajax redirect to a view on success
react native datepicker disable future dates
js regex remove html tags
jquery random color array
process.now() nodejs
angular adding delay
how to get element in iframe using javascript
how to remove item from asyncstorage
slice() javascript
fadein fadeout jquery
SAPUI5 formatter Date and Time
gcloud storage cors
summernote mentions ajax
prevent form submit html javascript jquery
jquery get text of input
javascript element edit text
tskill nodejs port
download pdf javascript
how to make javascript progarm that randomly displayes a word
react native onChangeText resize the background image
print array angular
electron hide top bar
automatic compile nodejs when edit
count all items inside 2nd ul using jquery
webpack env argument
multiple path names for a same component in react router
convert string of expression in to expression in javascript
calling javascript functions from unity scripts
check if item exists in localstorage javascript
javascript download csv
jquery each hover
Unexpected end of JSON input while parsing near '...ts-2.3.0.tgz","fileCo'
join on JSON field
Day 24: More Linked Lists hackerrank solution javascript
javascript insert sibling after
How to detect which one of the defined font was used in a web page?
how to access property of an object in javascript
js replace space with underscore
javascript fetch api post
en eternal gloden braid
vue js app component
substring javascript
jqery get text
query mongodb
json parse returns object
html5 store object in localstorage
node.js function
js html object
vuejs vscode unbound breakpoint
iteratea on values map js
angular indexeddb
freecodecamp cdn
Custom jquery validation messages
how to use trim in node js
core.js:12799 Can't bind to 'ngForIn' since it isn't a known property of 'ng-container'.
import react dom
js scroll page horizontally with mouse wheel
number++ * 5
push values to state array class react
how to project specific field mongodb nodejs
regular expression 010+100 answer
js how to sort strings in array
javascript iterate through object attributes
jquery post docs.google.com/forms/ CORS
jquery add class
push element in array javascript
changing state value react
jquery in array
byte to integer js
yyyy-MM-dd'T'HH:mm:ss'Z' in javascript
react import multiple images
javaScript disable submit button until form is fully validated
js copy array into another
reading a json file in c#
get buffer from file
.
|
https://www.codegrepper.com/code-examples/javascript/get+channel+id+discord+js+v12
|
CC-MAIN-2022-05
|
refinedweb
| 4,644
| 57.06
|
I have a CLion C++ project that has the following structure:
project
---->my_includes
| ----> my_own.hpp
---->source
----> my_app
----> my_src.cpp
#include "my_includes/my_own.hpp"
You need to create a
CMakeLists.txt for CLion to be happy. It is enough to declare all the source files, you don't have to convert your scons (or any other build system) to cmake.
You don't even have to write the CMakeLists.txt by hand, you can ask CLion to do it:
File | Import project ... | and then point at the directory containing your project.
Now edit the generated
CMakeLists.txt and add a cmake command to tell CLion where to find the includes (actually to tell the compiler, and CLion will reuse that information).
Since your source files use the include as
#include "my_includes/my_own.hpp", you need to tell cmake the base directory containing directory
my_includes:
include_directories(.)
Where the dot means the same directory as the one containing the
CMakeLists.txt.
I tested with a project reproducing your layout and from
my_src.cpp I can navigate to
my_own.hpp.
Then to build you still have to use scons in a console. It is also possible to add a cmake command,
add_custom_target() that will call your scons (or your make, or whatever), so that you can also navigate from CLion to the build errors.
|
https://codedump.io/share/AepC0bNKMpwS/1/clion-indexer-does-not-resolve-some-includes-in-the-project-directory
|
CC-MAIN-2016-50
|
refinedweb
| 220
| 68.36
|
shown in other instead.
Unigine::Schemer
Schemer is a visual scripting system that allows a developer to create complex sequences of gameplay events without having to script them manually. This way the artists can add interactivity to the world without the help of a programmer. By connecting paths in a flow graph, it is possible to script cutscenes, switches, timers, changes in lighting and much more.
Schemer (as well as Skinner) can either be loaded inside Unigine window or in the external widgets.
Schemer scripts can be found under data/core/systems/schemer folder.
Overview
Schemer flow graph consists of the following entities:
- Blocks are the main entities of the Schemer. They describe events, operations or variables of different types. The gameplay programmers code these actions depending on the project needs and make them available to be used in the Schemer by artists. For example, a block can describe the behavior of the game object, for example, the explosion sequence of a game vehicle.
There is also a number of predefined blocks that perform various arithmetic operations, print a message, etc.
- Nodes are Block units that form the graph sequence; they can be dragged around the graph canvas. That is, while Block is the type of the node that determines what action to do, a node is a block that has been added to the graph to perform this action, given the exact input data. Nodes of the same Block differ in their variables and states.
- Nodes are connected together by Joints. Joints can be of two types:
- Paths are rendered in white. They control the sequence of executing nodes when the Schemer script is run. That is, by moving along the path joints we could trace how the graph is unrolling starting from each possible entry point (the first nodes of the script) and what are the next triggered nodes.
- Links are rendered in green. They simply connect nodes that store values and do not perform anything by themselves.
- The point of connection is called an Anchor. Anchors can be of different shapes (round for output paths from a node and square for input paths into a node).
- Schemer editor is a canvas on which the created graph is drawn. It uses Unigine::Widgets::Graph classes for drawing.
How To Use Schemer Graph
To create a graph, drag the blocks onto editor canvas.
- The first node to start the graph with should always be schemer.entry. The name of this entry point is specified in the world script. By default (in Schemer sample), main name should be specified.
- Put the cursor over the Output anchor and drag the joint to the Input anchor of the next node. Paths that connect Output and Input anchors control a sequence of executing a graph.
- Values that nodes operate on are marked in green. The value on the right side of a node is an output value that contains the result of the operation performed by this node. The value on the right side is an input value. Connect two values to pass a value from one node to another.
After the Schemer graph has been created or modified, click Run button. A script will be generated out of the graph, compiled on-the-fly and run.
You can also save the created script into *.script file to be loaded and edited later or executed at runtime.
Blocks
Inside blocks are functions or snippets of UnigineScript code. The resulting script created from a Schemer graph is made up of code snippets from all blocks put together one after another. When blocks are processed, separate namespaces are created for each of the block to avoid name collisions.
Just like any other script, a block has a number of functions to control its behavior:
- init is for code executed on the Schemer script initialization. It can be used to initialize heavy resources: for example, Skinner loads animations and creates buffers in the init code.
- shutdown is for code executed on the Schemer script shutdown.
Both init() and shutdown() code snippets do not depend on the graph execution sequence. All blocks will be initialized or shout down at once (see the details).
- update is for code executed when the graph is executed and it is the turn for node with the current block to be activated.
- common is for functions and variables that should have a global scope inside of the block.
Any of these functions inside of the block can be omitted, if necessary.
Blocks File Syntax
Blocks are described in a *.blocks file of XML format. For example, the default blocks are contained in the data/core/systems/schemer/blocks/schemer.blocks.
Besides functions to execute, a block also describes its joints:
- Input and output paths ( input_path and output_path) to connect a node with this block to other nodes.
- Input and output links ( input_link and output_link) are used to receive variables from, and pass them to other nodes.
<?xml version="1.0" encoding="utf-8"?> <blocks version="1.00"> <block type="schemer.message"> <input_path>input</input_path> <output_path>output</output_path> <input_link>value</input_link> <init>log.message("schemer.message: block is initialized with a script\n");</init> <shutdown>log.message("schemer.message: block is shut down with a script\n");</init> <update>log.message("schemer.message: %s\n",typeinfo(value));</update> </block> </blocks>
If the code should contain characters like ">" or "&" that are illegal in XML elements, use CDATA to indicate a section ignored by the parser.
<update><![CDATA[ if(a > b) goto output_gt; if(a < b) goto output_lt; goto output_eq; ]]></update>
The available attributes for joints (both paths and links) are as follows:
- label — text at the anchor point
- align — position of the anchor point on the specified side of the node. Possible values are left, right, bottom.
- value — the default value to use.
- mask — bit mask for connecting only the anchors with a matching mask. For a joint to be created between two anchors, at least one bit of masks should match.
Customize Basic Blocks
If you want to customize any of the available blocks, you need to edit data/core/systems/schemer/blocks/schemer.blocks. There, you can modify init, update or shutdown functions written in UnigineSript, add anchors to connect to other nodes, etc.
Adding a Custom Blocks File
If you want to expand the list of predefined blocks, you can add custom blocks files. New blocks can be loaded via loadBlocks(string name) function in the Schemer constructor ( data/core/systems/schemer/schemer.h file).
Available Schemer Blocks
The following blocks are the basic Schemer blocks defined in the data/core/systems/schemer/schemer_blocks.h script.
The following blocks are the predefined Schemer blocks loaded from data/core/systems/schemer/blocks/schemer.blocks file.
How to Run Schemer Script
To run the Schemer from the script (here, without a visual editor), you need to add the code as in the following example. update() function of the script compiled from a graph. It will execute all its nodes one by one in the specified order.
#include <core/scripts/utils.h> #include <core/systems/schemer/schemer.h> /* */ int init() { // Use Schemer namespace. using Unigine::Schemer; // Create a Schemer. Schemer schemer = new Schemer(); // Create Schemer script that will compile an executable script out of the graph. SchemerScript script = new SchemerScript(schemer); // Load the previously created a graph. script.load("samples/schemer/scripts/delay.script"); // Compile the loaded graph into a script. script.compile(); // Run <init></init> code of all blocks used in the script. Here, // constants in schemer.constant blocks are initialized. This line could be omitted, // if not necessary. script.init(); // Run the graph. script.update(script.getEntryID("main")); return 1; }
|
https://developer.unigine.com/en/docs/2.4.1/code/uniginescript/scripts/systems/unigine_schemer?rlang=cpp
|
CC-MAIN-2019-35
|
refinedweb
| 1,278
| 65.83
|
Contents
This section describes a grammar common to any version of CSS (including CSS2). Future versions of CSS will adhere to this core syntax, although they may add additional syntactic constraints.
These all rule sets.
Here is an example. Assume a CSS2 parser encounters this style sheet:
@import "subs.css"; H1 { color: blue } @import "list.css";
The second '@import' is illegal according to CSS2. The CSS2 parser skips }
A block starts with a left curly brace ({) and ends with the matching right curly brace (}). In between there may be any characters, doesn't match the first single must be a list of one or more semicolon-separated (;) declarations. legal CSS2 statement.
P[example="public class foo { private int x; foo(int x) { this.x = x; } }"] { color: red }
A.
To ensure that new properties and new values for existing properties can be added in the future, a UA must skip a declaration with an invalid property name or an invalid value. Every CSS2 property has its own syntactic and semantic restrictions on the values it accepts.
For example, assume a CSS22 parser would honor the first rule and (e.g., px, deg, etc.). After the number '0', the unit identifier is optional.
Some properties allow negative length units, but this may complicate the formatting model and there may be implementation-specific limits. If a negative length value cannot be supported, it should be converted to the nearest value that can be supported., ex, and px.
H1 { margin: 0.5em } /* em: the height of the element's font */ H1 { margin: 1ex } /* ex: the height of the letter 'x' */ P { font-size: 12px } /* px:. or BODY in HTML), 'em' and 'ex' refer to the property's initial value. these rules, the 'text-indent' value of H1 elements will be 36pt, not 45pt, if H1 is a child of the BODY element.
Absolute length units are only useful when the physical properties of the output medium are known. The absolute units are:.
The format of an RGB value in hexadecimal notation is a '#' immediately followed by either three or six hexadecimal characters. The three-digit RGB notation (#rgb) is converted into six-digit form (#rrggbb) by replicating pairs of, (see [COLORIMETRY]).
Conforming UAs may limit their color-displaying efforts to performing a gamma-correction on them. sRGB specifies a display gamma of 2.2 under specified viewing conditions. UAs should adjust the colors given in CSS such that, in combination with an output device's "natural" display gamma, an effective display gamma of 2.2 is produced. See the section on gamma correction for further details. Note that only colors specified in CSS are affected; e.g., images are expected to carry their own color information.
Angle.
|
http://www.w3.org/TR/WD-CSS2/syndata.html
|
CC-MAIN-2018-39
|
refinedweb
| 453
| 59.4
|
I have multiple case classes representing values in DB for ex User which saves user based properties like name / age / address and CallLog which saves timestamp / status_of_call
What i want to achieve
I want to have a helper function which accepts list of models and checks if the list is empty then returns "error" otherwise should return json array of the list.
My Approach
I want to have a trait which groups certain models in it and the helper method will accept either the trait or List of it in order to check or may be have a generic which implements the trait.
Problem
Since implicit writes are tightly coupled with the model class, compiler throws the error on the line
Json.toJson(list)
Since User, CallLog, etc. will be serialized differently, Each Writes[T] will be different for each implementation of your Model trait, so a Writes[Model] has to know about the implementation it is trying to serialize.
It is therefore not possible to have it part of the Model trait, because this information isn't known yet when you define it.
A workaround in your case would be to define your Writes[Model] in the scope of your helper function instead.
An implementation of your helper function could be like this :
import play.api.libs.json.{JsValue, Json, Writes} sealed trait Model case class User(name: String, age: String, address: String) extends Model object User { implicit val userWrites = Json.writes[User] } case class CallLog(timestamp: String, status_of_call: String) extends Model object CallLog { implicit val callLogWrites = Json.writes[CallLog] } implicit val modelWrites = new Writes[Model] { override def writes(o: Model): JsValue = o match { case u: User => Json.toJson(u) case cl: CallLog => Json.toJson(cl) } } def helper(models: Model*): Either[JsValue, String] = models match { case Nil => Right("Error") case _ => Left(Json.toJson(models)) } helper(User("John", "32", "...")) helper(User("John", "32", "..."), CallLog("now", "In progress"))
|
https://codedump.io/share/59NRqBwfWCsu/1/how-to-define-implicit-writes-in-trait
|
CC-MAIN-2018-22
|
refinedweb
| 318
| 52.19
|
Installation and Deployment of AiiDA¶
Supported architecture¶
AiiDA has a few strict requirements, in its current version: first, it will run only on Unix-like systems - it is tested (and developed) in Mac OS X and Linux (Ubuntu), but other Unix flavours should work as well.
Moreover, on the clusters (computational resources) side, it expects to find
a Unix system, and the default shell is required to be
bash.
Installing python¶
AiiDA requires python 2.7.x (only CPython has been tested). It is probable that you already have a version of python installed on your computer. To check, open a terminal and type:
python -V
that will print something like this:
Python 2.7.3
If you don’t have python installed, or your version is outdated, please install a suitable version of python (either refer to the manual of your Linux distribution, or for instance you can download the ActiveState Python from ActiveState. Choose the appropriate distribution corresponding to your architecture, and with version 2.7.x.x).
Installation of the core dependencies¶
Database¶
As a first thing, choose and setup the database that you want to use.
Other core dependencies¶
Before continuing, you still need to install a few more programs. Some of them are mandatory, while others are optional (but often strongly suggested), also depending for instance on the type of database that you plan to use.
Here is a list of packages/programs that you need to install (for each of them,
there may be a specific/easier way to install them in your distribution, as
for instance
apt-get in Debian/Ubuntu -see below for the specific names
of packages to install- or
yum in RedHat/Fedora).
- git (required to download the code)
- python-pip (required to automatically download and install further python packages required by AiiDA)
- ipython (optional, but strongly recommended for interactive usage)
- python 2.7 development files (these may be needed; refer to your distribution to know how to locate and install them)
- To support SQLite:
- SQLite3 development files (required later to compile the library, when configuring the python sqlite module; see below for the Ubuntu module required to install these files)
- To support PostgreSQL:
- PostgreSQL development files (required later to compile the library, when configuring the python psycopg2 module; see below for the Ubuntu module required to install these files)
For Ubuntu, you can install the above packages using (tested on Ubuntu 12.04, names may change in different releases):
sudo apt-get install git sudo apt-get install python-pip sudo apt-get install ipython sudo apt-get install python2.7-dev sudo apt-get install libsqlite3-dev sudo apt-get install postgresql-server-dev-9.1
Note
For the latter line, please use the same version (in the
example above is 9.1) of the
postgresql server that you installed (in this case, to install the server of
the same version, use the
sudo apt-get install postgresql-9.1 command).
If you want to use postgreSQL, use a version greater than 9.1 (the greatest that your distribution supports).
For Mac OS X, you may either already have some of the dependencies above (e.g., git), or you can download binary packages to install (e.g., for PostgreSQL you can download and install the binary package from the official website).
Downloading the code¶
Download the code using git in a directory of your choice (
~/git/aiida in
this tutorial), using the
following command:
git clone ~/git/aiida
(or use
git@bitbucket.org:aiida_team/aiida.git if you are downloading
through SSH; note that this requires your ssh key to be added on the
Bitbucket account.)
Python dependencies¶
Python dependencies are managed using
pip, that you have installed in the
previous steps.
As a first step, check that
pip is at its most recent version.
One possible way of doing this is to update
pip with itself, with
a command similar to the following:
sudo pip install -U pip
Then, install the python dependencies is as simple as this:
cd ~/git/aiida # or the folder where you downloaded AiiDA pip install --user -U -r requirements.txt
(this will download and install requirements that are listed in the
requirements.txt file; the
--user option allows to install
the packages as a normal user, without the need of using
sudo or
becoming root). Check that every package is installed correctly.
Note
This step should work seamlessly, but there are a number of reasons for which problems may occur. Often googling for the error message helps in finding a solution. Some common pitfalls are described in the notes below.
Note
if the
pip install command gives you this kind of error message:
OSError: [Errno 13] Permission denied: '/usr/local/bin/easy_install'
then try again as root:
sudo pip install -U -r requirements.txt
If everything went smoothly, congratulations! Now the code is installed! However, we need still a few steps to properly configure AiiDA for your user.
Note
if the
pip install command gives you an error that
resembles the one
shown below, you might need to downgrade to an older version of pip:
Cannot fetch index base URL
To downgrade pip, use the following command:
sudo easy_install pip==1.2.1
Note
Several users reported the need to install also
libqp-dev:
apt-get install libqp-dev
But under Ubuntu 12.04 this is not needed.
Note
If the installation fails while installing the packages related to the database, you may have not installed or set up the database libraries as described in the section Other core dependencies. file found errors or similar), you may need to
point to the path where the dynamical libraries are. A way to do it is to
add a line similar to the following to the
~/.bashrc and then open
a new shell:
export DYLD_FALLBACK_LIBRARY_PATH=/Library/PostgreSQL/9.3/lib:$DYLD_FALLBACK_LIBRARY_PATH
(you should of course adapt the path to the PostgreSQL libraries).
AiiDA configuration¶
Path configuration¶
The main interface to AiiDA is through its command-line tool, called
verdi.
For it to work, it must be on the system path, and moreover the AiiDA python
code must be found on the python path.
To do this, add the following to your
~/.bashrc file (create it if not already present):
export PYTHONPATH=~/git/aiida:${PYTHONPATH} export PATH=~/git/aiida/bin:${PATH}
and then source the .bashrc file with the command
source ~/.bashrc, or login
in a new window.
Note
replace
~/git/aiida with the path where you installed AiiDA. Note
also that in the
PYTHONPATH you simply have to specify the AiiDA path, while
in
PATH you also have to append the
/bin subfolder!
Note
if you installed the modules with the
--user parameter during the
pip install step, you will need to add one more directory to your
PATH
variable in the
~/.bashrc file.
For Linux systems, the path to add is usually
~/.local/bin:
export PATH=~/git/aiida/bin:~/.local/bin:${PATH}
For Mac OS X systems, the path to add is usually
~/Library/Python/2.7/bin:
export PATH=~/git/aiida/bin:~/Library/Python/2.7/bin:${PATH}
To verify if this is the correct path to add, navigate to this location and
you should find the executable
supervisord in the directory.
To verify if the path setup is OK:
type
verdion your terminal, and check if the program starts (it should provide a list of valid commands). If it doesn’t, check if you correctly set up the
PATHenvironmente variable above.
go in if you correctly set up the
PYTHONPATHenvironment variable in the steps above.
Bash completion¶
verdi fully supports bash completion (i.e., the possibility to press the
TAB of your keyboard to get a list of sensible commands to type.
We strongly suggest to enable bash completion by adding also the following
line to your
.bashrc, after the previous lines:
eval "$(verdi completioncommand)"
If you feel that the bash loading time is becoming too slow, you can instead run the:
verdi completioncommand
on a shell, and copy-paste the output directly inside your
.bashrc file,
instead of the
eval "$(verdi completioncommand)" line.
Remember, after any modification to the
.bashrc file, to source it,
or to open a new shell window.
Note
remember to check that your
.bashrc is sourced also from your
.profile or
.bash_profile script. E.g., if not already present,
you can add to your
~/.bash_profile the following lines:
if [ -f ~/.bashrc ] then . ~/.bashrc fi
AiiDA first setup¶
Run the following command:
verdi install
to configure AiiDA. The command will guide you through a process to configure
the database, the repository location, and it will finally (automatically) run
a django
migrate command, if needed, that creates the required tables
in the database and installs the database triggers..
If the automatic zone detection did not work for you, type instead another valid string. A list of valid strings can be found at but for the definitive list of timezones supported by your system, open a python shell and type:
import pytz print pytz.all_timezones
as AiiDA will not accept a timezone string that is not in the above list.
As a second parameter to input during the
verdi install).:
Insert your timezone: Europe/Zurich Default user email: richard.wagner@leipzig.de Database engine: sqlite3 AiiDA Database location: /home/wagner/.aiida/aiida.db):
Note
When the “Database engine” is asked, use ‘sqlite3’ only if you want to try out AiiDA without setting up a database.
However, keep in mind that for serious use, SQLite has serious limitations!! For instance, when many calculations are managed at the same time, the database file is locked by SQLite to avoid corruption, but this can lead to timeouts that do not allow to AiiDA to properly store the calculations in the DB.
Therefore, for production use of AiiDA, we strongly suggest to setup a
“real” database as PostgreSQL or MySQL. Then, in the “Database engine”
field, type either ‘postgres’ or ‘mysql’ according to the database you
chose to use. See here for the documentation
to setup such databases (including info on how to proceed with
verdi install
in this case).
At the end, AiiDA will also ask to configure your user, if you set up a user
different from
aiida@localhost.
If something fails, there is a high chance that you may have misconfigured the database. Double-check your settings before reporting an error.
Start the daemon¶
If you configured your user account with your personal email (or if in
general there are more than just one user) you will not be able to
start the daemon with the command
verdi daemon start before its configuration.
If you are working in a single-user mode, and you are sure that nobody else is going to run the daemon, you can configure your user as the (only) one who can run the daemon.
To configure the deamon, run:
verdi daemon configureuser
and (after having read and understood the warning text that appears) insert
the email that you used above during the
verdi install phase.
To try AiiDA and start the daemon, run:
verdi daemon start
If everything was done correctly, the daemon should start. You can inquire the daemon status using:
verdi daemon status
and, if the daemon is running, you should see something like:
* aiida-daemon[0] RUNNING pid 12076, uptime 0:39:05 * aiida-daemon-beat[0] RUNNING pid 12075, uptime 0:39:05
To stop the daemon, use:
verdi daemon stop
A log of the warning/error messages of the daemon
can be found in
in ~/.aiida/daemon/log/, and can also be seen using
the
verdi daemon logshow command. The daemon is
a fundamental component of AiiDA, and it is in charge of submitting new
calculations, checking their status on the cluster, retrieving and parsing
the results of finished calculations, and managing the workflow steps.
Congratulations, your setup is complete!
Before going on, however, you will need to setup at least one computer (i.e., on computational resource as a cluster or a supercomputer, on which you want to run your calculations) and one code. The documentation for these steps can be found here.
Optional dependencies¶
CIF manipulation¶
For the manipulation of Crystallographic Information Framework (CIF) files, following dependencies are required to be installed:
First two can be installed from the default repositories:
sudo pip install pycifrw==3.6.2.1 sudo apt-get install jmol
ASE has to be installed from source:
curl > python-ase-3.8.1.3440.tar.gz gunzip python-ase-3.8.1.3440.tar.gz tar -xvf python-ase-3.8.1.3440.tar cd python-ase-3.8.1.3440 setup.py build setup.py install export PYTHONPATH=$(pwd):$PYTHONPATH
For the setting up of cod-tools please refer to installation of cod-tools.
Further comments and troubleshooting¶
For some reasons, on some machines (notably often on Mac OS X) there is no default locale defined, and when you run
verdi installfor the first time it fails (see also this issue of django). To solve the problem, first remove the sqlite database that was created.
Then, run in your terminal (or maybe even better, add to your
.bashrc, but then remember to open a new shell window!):
export LANG="en_US.UTF-8" export LC_ALL="en_US.UTF-8"
and then run
verdi installagain.
[Only for developers] The developer tests of the SSH transport plugin are performed connecting to
localhost. The tests will fail if a passwordless ssh connection is not set up. Therefore, if you want to run the tests:
make sure to have a ssh server. On Ubuntu, for instance, you can install it using:
sudo apt-get install openssh-server
Configure a ssh key for your user on your machine, and then add your public key to the authorized keys of localhsot. The easiest way to achieve this is to run:
ssh-copy-id localhost
(it will ask your password, because it is connecting via ssh to
localhostto install your public key inside ~/.ssh/authorized_keys).
|
https://aiida.readthedocs.io/projects/aiida-core/en/v0.4.1/installation.html
|
CC-MAIN-2020-50
|
refinedweb
| 2,333
| 53.21
|
Convert large Accomplishments class to aspected "container" class
Bug Description
The daemon code has a very large class called Accomplishments. It performs the following sorts of tasks:
* image manipulation
* configuration management
* cache dir setup
* accomplishment management
* trophy file utilities
* UbuntuOne interaction
* one dbus method (that could arguable be moved into the dbusapi code, depending upon how one went about that)
Another option would be to use Twisted's multiservice approach. This would be appropriate for the remote stuff, and for anything that needs to pull from an outside data source (possibly even including configuration).
Of course, a mixture of each approach would be just fine as well.
This has been open for a long time and I am not sure if this is much of a priority so closing the bug.
If someone wants to work on this, feel free to reopen and assign it to yourself.
One way to do this is isolate the functionality in each of the above groups into separate classes (e.g., ImageAPI, ConfigAPI, CacheAPI, AccomplishmentAPI, RemoteAPI, DBUSAPI, etc., maybe with generally useful code going in a parent class, called API).
Then, an overarching class can be created that has aspects (attribute) which are the instantiated API classes. For example:
class SomeGoodName(
object) :
def __init__(self, ...):
self.image = ImageAPI()
self.config = CongfigAPI()
self.cache = CacheAPI()
...
etc.
Then, for the AccomplishmentS
ervice class to reference, e.g., a RemoteAPI method, it would do something along the lines of:
self.
ad.remote. verifyU1Account (...)
This will keep things more organized, easier to read, easier to maintain (folks will know where to put new functionality and keep things clean, as opposed to rapid crustification), etc.
|
https://bugs.launchpad.net/ubuntu-accomplishments-daemon/+bug/947288
|
CC-MAIN-2016-26
|
refinedweb
| 276
| 54.42
|
Using static typing
Python is both a strongly typed and a dynamically typed language.
Strong typing means that variables do have a type and that the type matters when performing operations on a variable. Dynamic typing means that the type of the variable is determined only during runtime.
Due to strong typing, types need to be compatible with respect to the operand when performing operations. For example Python allows one to add an integer and a floating point number, but adding an integer to a string produces error.
Due to dynamic typing, in Python the same variable can have a different type at different times during the execution. Dynamic typing allows for flexibility in programming, but with a price in performance.
Everything is an object
One of the key features of Python is that everything is an object, and the
type is just one attribute of an object. As an illustration, we can assign a
single integer to a variable, and use the Python built-in function
dir for
finding out the attributes of the object. If you execute the following two
lines in an interactive interpreter, it should become clear that a Python
integer is much more complex than just a number. Please feel free to
experiment also with other types!
n = 5 dir(n)
The fact that everything is an object means that there is a lot of “unboxing” and “boxing” involved when Python performs operations with variables. For example, when just adding two integers
a = 7 b = 6 c = a + b
there are several steps Python needs to do:
- Check the types of both operands
- Check whether they both support the + operation
- Extract the function that performs the + operation (due to operator overloading objects can have a custom definition for addition)
- Extract the actual values of the objects
- Perform the + operation
- Construct a new integer object for the result
Due to the fact that Python is dynamically typed, the interpreter cannot know beforehand what type of objects one is dealing with, and everytime two variables are added one needs to perform all the above steps.
Adding static type information
What if one knows that e.g. in a certain function the variables have always the same type? That’s where Cython steps in: Cython allows one to add static typing information so that boxing and unboxing are not needed, and one can operate directly with the actual values.
When Cythonizing a Python code, static type information can be added either:
- In function signatures by prefixing the formal arguments by their type
- By declaring variables with the cdef Cython keyword, followed by the the type
For example, a simple Python function adding two objects could be Cythonized as follows:
def add (int x, int y): cdef int result result = x + y return result
The function works now only with integers but with less boxing/unboxing overheads.
The types provided in Cython code are C types, and the variables with type information are pure C variables and not Python objects. When calling a Cythonized function from Python, there is an automatic conversion from the Python object of actual arguments to the C value of formal argument, and when returning a C variable it is converted to corresponding Python object. Automatic conversions are carried out also in most cases within the Cython code where both Python objects and C variables are involved.
The table below lists the most common C types and their corresponding Python types. More information can be found in the Cython documentation.
Static typing in Mandelbrot kernel
In week 1 we did a performance analysis of Mandelbrot fractal in Step 1.11. The analysis revealed that the kernel function in module mandelbrot.py was the most time critical one. Thus, let’s make mandelbrot.py into Cython module mandelbrot.pyx and introducing static typing to the function kernel.
Pure Python version was:
def
We can add type information both to the function signature and to the function body:
def kernel(double zr, double zi, double cr, double ci, double lim, int cutoff): ''' Computes the number of iterations `n` such that |z_n| > `lim`, where `z_n = z_{n-1}**2 + c`. ''' cdef int count = 0 while ((zr*zr + zi*zi) < (lim*lim)) and count < cutoff: zr, zi = zr * zr - zi * zi + cr, 2 * zr * zi + ci count += 1 return count
When comparing the performance of pure Python and Cythonized versions, we obtain the following results:
- Pure Python: 0.57 s
- Static type declarations in the kernel: 14 ms
Thus, we obtained a speed up of ~40 !
© CC-BY-NC-SA 4.0 by CSC - IT Center for Science Ltd.
|
https://www.futurelearn.com/courses/python-in-hpc/0/steps/65121
|
CC-MAIN-2020-05
|
refinedweb
| 770
| 56.18
|
The base method for inserting images into a POD result is to use the document function, described in the previous section. That being said, this method has its limits, due to the fact that it implies using a POD statement. Indeed, a statement completely replaces the portion of the ODF result being its target. For example, even if you choose to anchor the image as a character, the anchored image inserted via the document function, targeted to a paragraph, will completely replace the target paragraph. Behind the scenes, POD wraps the inserted image into a new paragraph onto which the POD template's default style will be applied. Consequently, the target paragraph's general text alignment, among other characteristics, will be lost. If you need to insert an image at a precise position, within an existing paragraph whose properties must be kept (like text alignment), anchored as a character, use the image function, and not the document function. To be brief: use the image function for centering or right-aligning an image.
Everything is in the title. The image function is one of the rare POD functions you MUST use in a POD expression, not via a POD statement.
The example below illustrates the use of this function.
It comes from a projet using the web framework part of Appy. Expression com.logo.getFilePath(com) returns the absolute path to an image file on disk. The statement conditionally injects the paragraph containing the image if this latter exists; it is a detail and it is not important for understanding the example.
What is crucial is the leading colon (:) preceding the call to the image function. If you want to undestand this, recall how a POD expression works. A POD expression is a Python expression: POD lets the Python interpreter evaluate it by calling the standard Python function eval; then, it escapes the result and injects it, replacing the field defining the expression. In our case, the image function produces a chunk of ODF code representing the image: we don't want this code to be escaped! Else, it would appear as-is, instead of being interpreted as ODF code. The colon tells Appy to avoid escaping the result of the POD expression.
When running this example, if an image is there, the result could be the following.
Don't believe I spend my time writing such ugly POD templates, surrounding images with silly sequences of childish ASCII art! My purpose was to highlight these elements:
The image function, as available in the default POD context, corresponds to method importImage defined on class Renderer. Due to the similarity with the document function, both methods share almost the same parameters, excepted those mentioned in the comments below.
def importImage(self, content=None, at=None, format=None, size=None,
sizeUnit='cm', maxWidth='page', style=None, keepRatio=True,
convertOptions=None):
'''While importDocument allows to import a document or image via a
"do ... from document" statement, method importImage allows to
import an image anchored as a char via a POD expression
":image(...)", having almost the same parameters.'''
# Compared to the "document" function, and due to the specific nature of
# the "image" function, 2 parameters are missing:
# (1) "anchor" is forced to be "as-char";
# (2) "wrapInPara" is forced to False.
|
https://appyframe.work/100/view?page=main&nav=ref.19.pages.15.18&popup=False
|
CC-MAIN-2022-27
|
refinedweb
| 545
| 52.39
|
Video Skills for Fire TV Apps Overview from the Alexa Skills Kit. However, the integration into Android-based streaming media apps for Fire TV will involve additional APIs and services, including Amazon Device Messaging (ADM), AWS Lambda, AWS IAM, Login with Amazon, Cloudwatch, Node JS, Alexa Client Library, and more. Incorporating a video skill for your Fire TV app gives customers the richest voice experience with your content, driving up the levels of engagement and discovery for your content.
- Capabilities Provided with Video Skills for Fire TV Apps
- Prerequisite: Catalog Integration
- Expectations in Handling Directives
- Supported Countries
- What You'll Need
- High-level Workflow
- Detailed Workflow
- Estimated Development Time
- Naming Conventions: "Video Skills" versus "Video Skills Kit"
- Other Implementations for Video Skills
- Glossary
- Next Steps
Capabilities Provided with Video Skills for Fire TV Apps
Integrating a video skill for your Fire TV app>".
A frequent interaction might be as follows:
Note that you need only implement the logic for capabilities that are available in your app. For example, if channels aren't available in your app, you wouldn't need to implement Channel Change behaviors with the video skill.
Overall, voice capabilities make it easier for customers to discover and play your content. Apps with movies and TV shows work especially well with video skills. Including voice interactivity with your app encourages customers to engage more frequently with your content.
Not only does incorporating a video skill into your Fire TV app increase engagement with your app, voice interactions are becoming a standard expectation for more and more devices. (For more background on the ways voice interactions increase app usage by simplifying the experience, see Getting into the Voice Mindset from the AWS Training and Certification library.)
Prerequisite: Catalog Integration
To incorporate a video skill for your Fire TV app, your app must be catalog-integrated. Catalog integration refers to the process of describing your app's media according to Amazon's Catalog Data Format (CDF), which is an XML schema, and regularly uploading your catalog into an S3 bucket following the processes described in a video skill for your Fire TV app. However, you can still incorporate some voice interactivity with your app through two related technologies:
- Voice-enabling Transport Controls with MediaSession API. Transport controls refer to commands such as "Alexa, play," "Alexa, fast-forward", "Alexa, rewind," etc. You can use MediaSession to enable this interactivity.
- In-App Voice Scrolling and Selection. Scrolling and selection refer to commands such as "Alexa, scroll left" or "Alexa, select."
Note that if you implement the video skill for your Fire TV app, the skill's capabilities will automatically include transport controls. In-app scrolling and selection, not included in the video skill, is turned on manually by Amazon and might already be activated for your app. (In short, when you implement the Alexa video skill, you don't need to worry about any other voice integration efforts. The video skill provides the deepest level of voice enablement.)
Expectations in Handling Directives
As you develop your video skill integration, you should understand what directives your Fire TV app will receive and how you're expected to react to them. A "directive" is a set of data and instructions, expressed in JSON, sent from Alexa to a video skill. For example, the directive might to search for a TV show or play a movie. The video skill sends these directives to your Lambda function, where you're expected to process them with logic in your app. You can read more details about each directive in Step 7: Interpreting and Reacting to Directives.
Supported Countries
Video skills for Fire TV apps are not supported in every country. If you live in a country where video skills aren't supported, you cannot create a video skill for your Fire TV app. Video Skills on Devices. See also AWS Regions and Video Skills in that same topic.
What You'll Need
You will need the following to create the video skill for your Fire TV app:
- AWS Account
- Amazon Developer Account
- Android Studio
- Alexa video skill
- Logo images
- AWS Lambda
- Fire TV streaming media app (Android). If you're just testing out how the video skill works, you can use the Sample Fire TV App with a Video Skill instead of your actual app.
- Echo Dot or some other Alexa-enabled device. (If you don't have an Echo, you can use the Alexa Skill Testing Tool.)
- Fire TV. You can connect any TV with HDMI ports to a Fire TV Stick.
- Node JS. In this documentation, Node JS is used to convert the Lambda function into a zip package that you upload into AWS. However, you can use other programming languages to write your Lambda code.
- Catalog-integrated media
You will also configure a variety of services within the Appstore Developer Console, the Alexa Developer Console, and AWS. These services include IAM, Lambda, Cloudwatch, Security Profile, and more.
High-level Workflow
At a high-level, to integrate a video skill for your Fire TV app, you first create a video skill in the Alexa Developer Console and associate it with a Lambda function on AWS. When users interact with your app through voice, Alexa voice services in the cloud convert the user's commands into JSON objects, called directives.
Your video skill (using the Video Skill API) receives these directives from Alexa and sends them to your Lambda function. Your Lambda function inspects the request and takes any necessary actions in your app (such as returning results or initiating playback). The Lambda function uses Amazon Device Messaging (ADM), a push notification service, to communicate with your app.
Detailed Workflow
The previous section showed how video skills work (as they're called)/commands, is a "directive." A directive is a set of data and instructions, expressed as a JSON object, that provides direction on how to respond to the user's utterances. For example, when a user says "Play Bosch," Alexa converts this into a "Play directive" that has a specific JSON structure, like this:
{ "directive": { "payload": { "entities": [ { "type": "Video", "uri": "entity:\/\/provider\/program\/amzn1.p11cat.merged-video.858df979-c070-5533-9b1f-ecae15e9f139", "value": "Bosch", "externalIds": { "avc_vending_de": "amzn1.dv.gti.e0a9f6b7-ca7e-dc0c-c80e-f5801c580da8", "ENTITY_ID": "amzn1.p11cat.merged-video.858df979-c070-5533-9b1f-ecae15e9f139", "avc_vending_us": "amzn1.dv.gti.56a9f78c-4cfe-36f0-663d-9104c6dd6595", "asin_row_na": "B01M32CYV3", "asin_row_fe": "B01MCYRKGY", "avc_vending_jp": "amzn1.dv.gti.fea9f575-39fd-7a77-622b-a400f9b511f8", "asin_us": "B00S45ZDVE", "avc_vending": "amzn1.dv.gti.8cac011f-78c3-114b-b3f8-246a48f23ec0", "asin_roe_eu": "B01MCYRQHG", "imdb": "tt3502248", "ontv": "SH018737530000", "asin_gb": "B00IGQC64I", "asin_row_eu": "B01MDRHYR2", "asin_jp": "B014QF5HMU", "avc_vending_gb": "amzn1.dv.gti.10a9f690-1c9c-8c4e-5f67-2007ea0c5ceb", "tms": "SH018737530000", "cravetv": "m32254", "asin_de": "B00ZWBWZXW", "gti": "amzn1.dv.gti.10a9f690-1c9c-8c4e-5f67-2007ea0c5ceb", "ontv_de": "SH026719310000" } }, { "type": "Video", "uri": "entity:\/\/provider\/program\/amzn1.p11cat.merged-video.a63315af-c728-56bc-90bb-0b8cbdcdad86", "value": "Bosch", "externalIds": { "ENTITY_ID": "amzn1.p11cat.merged-video.a63315af-c728-56bc-90bb-0b8cbdcdad86", "imdb": "tt2773036" } }, { "type": "Video", "uri": "entity:\/\/provider\/program\/amzn1.p11cat.merged-video.d9ceb2e4-4802-557d-9461-24e19a438aad", "value": "Bosch", "externalIds": { "gvd": "GN2EAWZBASRC1PJ", "ENTITY_ID": "amzn1.p11cat.merged-video.d9ceb2e4-4802-557d-9461-24e19a438aad" } }, { "type": "Video", "uri": "entity:\/\/provider\/program\/amzn1.p11cat.merged-video.75f0a242-6a4c-5912-97be-a06a3a0d5e05", "value": "Bosch", "externalIds": { "ENTITY_ID": "amzn1.p11cat.merged-video.75f0a242-6a4c-5912-97be-a06a3a0d5e05", "tms": "SH018739470000", "ontv_gb": "SH018739470000" } }, { "type": "Video", "uri": "entity:\/\/provider\/program\/amzn1.p11cat.merged-video.ca646a58-8e1d-55f3-acc7-30245f8ac202", "value": "Bosch", "externalIds": { "gvd": "GN794XKHCHGKGJZ", "ENTITY_ID": "amzn1.p11cat.merged-video.ca646a58-8e1d-55f3-acc7-30245f8ac202" } } ] }, "header": { "payloadVersion": "3", "messageId": "20d83e2d-6b20-4590-92ee-f252c2f607a9", "namespace": "Alexa.RemoteVideoPlayer", "name": "SearchAndPlay", "correlationToken": "cf662810-879e-4d8f-afb7-7488b778cd35" }, "endpoint": { "cookie": { }, "endpointId": "VSKTV", "scope": { "token": "452d41e7-8e4a-71ed-e8fb-dd31b126bf2e", "type": "BearerToken" } } } }
The following table lists the kinds of directives you can handle with your Lambda function:
. (This will give you a sense of your expectations of what you must handle when you integrate a video skill for your Fire TV app.)
Alexa sends these directives to your AWS Lambda function through the Video Skill API.. For example:
- send, or your app can handle it.
Estimated Development Time
It can take anywhere from several weeks to several months to fully integrate video skills for your Fire TV app. Assuming that your content is already catalog-integrated, the bulk of the development work for the video skills involves creating logic to handle the incoming directives from Lambda function.
The process for integrating a video skill for your Fire TV app is broken out into a series of steps. See Integration Steps in "Process Overview for Creating Video Skills on Fire TV".
Naming Conventions: "Video Skills" versus "Video Skills Kit"
You might regularly encounter the term "Video Skills Kit" or "VSK." Video Skills Kit (VSK) and video skills refer to the same thing. "Video Skills Kit" appeared in communications and caught on with early adoption partners. However, the Alexa Skills Kit supports many different types of skills: flash briefing skills, smart home skills, music skills, meetings skills, cooking skills, video skills, and more. (Each skill within the Alexa Skills Kit isn't its own kit.)
Video skills for Fire TV apps refers to implementing voice-interactivity through the Video Skill API with your Fire TV app. Though you will still see "Video Skills Kit" or VSK used here and there in code, sample apps, user interfaces, or other places, to reduce confusion we are phasing out this term in favor of video skills for Fire TV apps.
Other Implementations for Video Skills
In addition to creating video skills for Fire TV apps, you can also create video skills for multimodal devices such as Echo Show. Since the same developers who build Fire TV apps would also likely build integrations with multimodal devices, we've consolidated the documentation together here. Multimodal devices such as Echo Show (and Echo Show mode on third-party devices) use an "app-less" framework that leverages your same Amazon catalog integration along with your existing HTML5 Web player for playback. Multimodal devices also provide some existing templates for rendering browse/search on device. For more details, see Video Skills for Multimodal Devices Overview.
If you're a device manufacturer building set-top boxes, consoles, and smart TVs (living room entertainment. Documentation for device manufacturers implementing Alexa video skills appears within the main Alexa Skills Kit navigation. For more information, see Understand the Video Skill API.
Video Skill API versus Custom Skills with Screen Displays
The Video Skill API is intended for video providers whose catalog content is often in IMDb (or for device manufacturers making their devices voice interactive). The implementation involves handling directives from Alexa with your own Fire TV app or.
Glossary
Alexa introduces many new terms that might be unfamiliar. You can find definitions in the Glossary.
Next Steps
To get started creating a video skill for your Fire TV app, go to Process Overview for Creating Video Skills for Fire TV Apps.
|
https://developer.amazon.com/pt-br/docs/video-skills-fire-tv-apps/introduction.html
|
CC-MAIN-2019-39
|
refinedweb
| 1,811
| 53.51
|
Developing JAX-WS Web Service Clients.
Consuming the Spell Checker Web Service.
Creating the Client
In this section, you use a wizard to generate Java objects from the web service’s WSDL file.
Choose File > New Project (Ctrl-Shift-N on Windows and Linux, ⌘-Shift-N on MacOS). Under Categories, choose Java Web. Under Projects, choose Web Application. Click Next. Name the project
SpellCheckServiceand make sure that you specify an appropriate server as your target server. (Refer to the "Getting Started" section for details.) Leave all other options at default and click Finish.
In the Projects window, right-click the
SpellCheckServiceproject node and choose New > Other and select Web Service Client in the Web Services category in the New File wizard. Click Next.
Select WSDL URL and specify the following URL for the web service:.
Leave the package name blank. By default the client class package name is taken from the WSDL. In this case is
com.cdyne.ws. Click Finish.
In the Projects window, within the Web Service References node, you see the following:.
Developing the Client.
Coding the Web Page.
In the Projects window, expand the Web Pages node of the
SpellCheckServiceproject and double-click the index page (
index.htmlor
index.jsp) to open the file in the Source Editor.
Copy the following code and paste it over the
<body>tags in the index page:
.
Creating and Coding the Serv.
Right-click the
SpellCheckServiceproject node in the Projects window, choose New > Other and then choose Web > Servlet. Click Next to open the New Servlet wizard.
Name the servlet
SpellCheckServletand type
clientservletin the Package drop-down. Click Next.
In the Configure Servlet Deployment panel, note that the URL mapping for this servlet is
/SpellCheckServlet. Accept the defaults and click Finish. The servlet opens in the Source Editor.
Put your cursor inside the Source Editor, inside the
processRequestmethod body of
SpellCheckServlet.java, and add some new lines right at the top of the method.
Right-click in the space that you created in the previous step, and choose Insert Code > Call Web Service Operation. Click the
checkSoap.CheckTextBodyV2operation in the "Select Operation to Invoke" dialog box,as shown below:;*
Replace the
tryblock of the
processRequest()method with the code that follows. The in-line comments throughout the code below explain the purpose of each line.>"); }
You see a number of error bars and warning icons, indicating classes that are not found. To fix imports after pasting the code, either press Ctrl-Shift-I (⌘-Shift-I on Mac), or right-click anywhere, which opens a context menu, and select Fix Imports. (You have a choice of List classes to import. Accept the default java.util.List.) The full list of imported classes follows:.
Deploying the Client).
Right-click the project node and choose Run. After a while, the application deploys and displays the web page that you coded in the previous section.
Enter some text, making sure that some of it is incorrectly spelled:
Click Spell Check and see the result:
Asynchronous Web Service Clients.
Creating the Swing Form:
Create a new Java Application project. Name it
AsynchSpellCheckClient. Do NOT create a
Mainclass for the project.
In the Projects view, right-click the
AsynchSpellCheckClientproject node and select New > JFrame Form…
Name the form
MainFormand place it in the package
org.me.forms.
After you create the JFrame, open the project properties. In the Run category, set
MainFormas the Main class.
In the Editor, open the Design view of
MainForm.java. From the Palette, drag and drop three Scroll Panes into
MainForm. Position and size the scroll panes. They will hold the text fields for the text you type in to check, all the wrong words, and the suggestions for one wrong word.
Drag and drop five Text Fields into
MainForm. Drop three of them into the three scroll panes. Modify them as follows:
Drag and drop a Progress Bar into
MainForm. Name the variable
pbProgress.
Drag and drop two Buttons into
MainForm. Name the first button
btCheckand change its text to Check Text or Check Spelling. Name the second button
btNextWrongWord, change its text to Next Wrong Word, and disable it.
Drag and drop some Labels into
MainForm, to give a title to your application and to describe the text fields.
Arrange the appearance of the JFrame to your liking and save it. Next you add web service client functionality.
Enabling Asynchronous Clients
Add the web service references, as described in Creating the Client. Then edit the web service attributes to enable asynchronous clients.
In the Projects window, right-click the
AsynchSpellCheckClientproject node and choose New > Other. In the New File wizard choose Web Services > Web Service Client. In the Web Service Client wizard, specify the URL to the web service:. Accept all the defaults and click Finish. This is the same procedure from Step 2 onwards described in Creating the Client.
Expand the Web Service References node and right-click the
checkservice. The context menu opens.
From the context menu, select Edit Web Service Attributes. The Web Service Attributes dialog opens.
Select the WSDL Customization tab.
Expand the Port Type Operations node. Expand the first
CheckTextBodyV2node and select Enable Asynchronous Client.
Click OK. The dialog closes and a warning appears that changing the web service attributes will refresh the client node.
Click OK. The warning closes and your client node refreshes. If you expand the
checknode in Web Service References, you see that you now have Polling and Callback versions of the
CheckTextBodyoperation.
Asynchronous web service clients for the SpellCheck service are now enabled for your application.
Adding the Asynchronous Client Code
Now that you have asynchronous web service operations, add an asynchronous operation to
MainForm.java .
To add asynchronous client code:
In
MainForm, change to the Source view and add the following method just before the final closing bracket.
public void callAsyncCallback(String text){ }
In the Projects window, expand the
AsynchSpellCheckClient's Web Service References node and locate the
checkSoap.CheckTextBodyV2 [Asynch Callback]operation.
Drag the
CheckTextBodyV2 [Asynch Callback]operation into the empty
callAsyncCallbackmethod body. The IDE generates the following
tryblock. Compare this generated code to the code generated for the synchronous client..
Switch back to the Design view. Double-click the Check Spelling button. The IDE automatically adds an ActionListener to the button and switches you to the Source view, with the cursor in the empty
btCheckActionPerformedmethod.
Add the following code to the
btCheckActionPerformedmethod body. This code gets the text that you type into the
tfYourTextfield, has the progress bar display a "waiting for server" message, disables the
btCheckbutton, and calls the asynchronous callback method.);* }
At the beginning of the
MainFormclass, instantiate a private
ActionListenerfield named
nextWord. This
ActionListeneris for the Next Wrong Word button that advances one wrong word in the list of wrong words and displays the word and suggestions for correcting it. You create the private field here so you can unregister the
ActionListenerif it already has been defined. Otherwise, every time you check new text, you would add an additional listener and end up with multiple listeners calling
actionPerformed()multiple times. The application would not behave correctly.
public class MainForm extends javax.swing.JFrame { private ActionListener nextWord; ...
Replace the entire
callAsyncCallbackmethod with the following code. Note that the outermost
tryblock is removed. It is unnecessary because more specific
tryblocks are added inside the method. Other changes to the code are explained in code comments.com); } } }
Press Ctrl-Shift-I (⌘-Shift-I on Mac) and fix imports. This adds the following import statements:.
See Also.
|
https://netbeans.apache.org/kb/docs/websvc/client.html
|
CC-MAIN-2022-33
|
refinedweb
| 1,250
| 68.26
|
Difference between revisions of "User talk:Kynikos"
Revision as of 22:55, 25 December 2013
Feel free to leave here your comments on my edits or anything else you want to talk about: I'll reply as soon as I can!
Contents
- 1 Xyne-related page edits after Powerpill, Bauerbill... discontinuation
- 2 Where should translations go?
- 3 Text shift in discussion answers
- 4 VirtualBox article rewrite
- 5 Integrating Google searches into ArchWiki
- 6 Crazy idea about interlanguage links
- 7
Pages that need to be deleted
- 8
Anomaly in list of categories do I have to put <the strings that must be replaced/adapted>. I don't even know if we have to surround them with angle brackets < >.
- Wget (talk) 22:00, 30 September 2013 (UTC)
- Help:Style/Formatting and Punctuation will give you all the answers you need, in particular Help:Style/Formatting and Punctuation#Pseudo-variables in file/command line contents deals with your example.
- Sorry if I can't give you feedback for your edits now, but I'm incredibly busy, I'll get there in the next days! Meanwhile if you have more questions don't hesitate to ask :)
- -- Kynikos (talk) 14:54, 1 October 2013 (UTC) 2013 (UTC)
Integrating Google searches into ArchWiki
Re-reading the discussion on my talk page (User_talk:Jstjohn#Unused_redirects) made me think that we should try improving the search functionality of the ArchWiki. Native MediaWiki search is really awful in my experience, and I'm guessing many others feel the same way.
The easiest way to improve it would be to integrate Google search directly into ArchWiki. A brief search on Google led me to [1] and [2], which are two ways to integrate Google search into MediaWiki. Even if those two aren't ideal solutions—I haven't looked at them in-depth—there are likely to be several other ways of integrating Google search into MediaWiki. So consider this a very nascent proposal for extending/improving search quality on ArchWiki without necessarily proposing a certain implementation.
I don't think that we should completely replace native MediaWiki search (yet?); however, integrated Google search would be a very useful alternative search feature that everyone can use.
-- Jstjohn (talk) 00:15, 5 December 2013 (UTC)
- I don't have a particular preference for one search engine or the other, however extensions can only be installed by the Devs, who have access to the repo, so a bug report should be opened for these things. In particular User:Pierre is the one who takes care of the wiki, and *IIRC* he tends to be against installing new extensions. -- Kynikos (talk) 09:18, 5 December 2013 (UTC))
Pages that need to be deleted
A few days ago, I did some extensive cleanup of the HCL/Laptops section. A number of the vendor-specific pages contained no useful information, so I flagged them for deletion and removed them from the new navigation bar template I created. As such, these pages need to be deleted:
- HCL/Laptops/ECS
- HCL/Laptops/Digital
- HCL/Laptops/Higrade
- HCL/Laptops/Hitachi
- HCL/Laptops/Medion
- HCL/Laptops/Micron
- HCL/Laptops/Mitac
- HCL/Laptops/Mitsubishi
- HCL/Laptops/NEC
- HCL/Laptops/Zenith
-- Jstjohn (talk) 03:25, 23 December 2013 (UTC)
Anomaly in list of categories
Hi,
in [7] there is an anomaly in the list, which prevents Wiki Monkey to update filter preview:
1731. Invalid title with namespace "Category" and text ""
I can't think of any reasonable explanation since
[[:Category:]] does not work.
Another thing, is there a reason why deleted pages are in the list of most linked-to pages even though they are not linked or transcluded?
-- Lahwaacz (talk) 22:21, 24 December 2013 (UTC)
- Weird, Wiki Monkey expects to find a link in those list items, so it was just crashing there. From the next release it won't blindly assume there's a link anymore :)
- Maybe a category with an empty title was created with a version of MediaWiki that was still allowing it? It's unlikely that they put it there by default for a mechanism that kind of prevents its creation, because other wikis don't have it, e.g. [8].
- About the second question, I think you're talking about deleted Categories, not simple pages, as no pages with 0 backlinks appear in Special:MostLinkedPages. Assuming you're talking about Special:MostLinkedCategories then, most (if not all) of the red links that you see there are former "wanted" (not "deleted") categories, which are likely cached in a special database table for which deletion of entries has never been implemented perhaps for the danger of breaking something else? MostLinkedCategories would then query that table without filtering the results with 0 backlinks: I've got no idea why, there could even be no reason at all and it just happens to have been implemented like that, waiting for somebody to submit a patch ;)
- -- Kynikos (talk) 15:52, 25 December 2013 (UTC)
- I was talking exclusively about categories. Thanks for pointing out that Special:MostLinkedPages (and also Special:MostLinkedTemplates) are OK - this is really weird, so I've submitted a bug report.
- I also found this commit, which is probably behind the error description produced in the list.
- -- Lahwaacz (talk) 22:55, 25 December 2013 (UTC)
|
https://wiki.archlinux.org/index.php?title=User_talk:Kynikos&curid=11164&diff=290379&oldid=290359
|
CC-MAIN-2017-34
|
refinedweb
| 879
| 53.65
|
The System.console() method provides an access point for the Console object, which is used to read input from a character input device like the keyboard and prints to character display device like the screen’s display. If the JVM is started indirectly or as a background process, the method will return null. The Console object is useful when creating CLI applications.
The class provides a way to both read character input and write character output. Keep in mind that character output may be less important than input. Kotlin already provides its own print() and println() functions for writing to the standard out. The console class does make it easy to read input from the keyboad since we do not need to work about working with System.in directly.
Let’s take a look at an example where we simply echo what’s inputted to the keyboard.
import java.io.Console fun main(args : Array<String>){ val console : Console? = System.console() when (console){ null -> { println("Running from an IDE...") } else -> { while (true){ //Read a line from the keyboard val line = console.readLine("What does Bob say? ") if (line == "q"){ return } console.printf("Bob says: %s\n", line) } } } }
The program is really simple. We make a console variable, that is nullable. This step is critical because System.console() can return null. Our next operation is to check if the console object is null. When console is null, we exit the program. Otherwise, we enter a loop that continues until the user enters “q” to quit.
The console.readLine() method returns a line inputted from the keyboard. In other words, it will return everything typed until the user pressed the enter or return key. To print the output, we use printf() to print a formatted output.
We could have used Kotlin’s print() function also.
Common Console Methods
reader() : Reader
This method returns a Reader object reference that can be used for low-level read operations.
writer() : PrintWriter
Returns a PrintWriter object reference that can be used for low-level output operations.
readLine() : String
Returns a line of text inputed from the console. The overloaded version accepts a String that serves as a command prompt.
readPassword() : CharArray!
This method disablese echoing so that a user can type a password in private. The overloaded version takes a String that is used as a command prompt.
format(fmt : String, varArgs args : Any) : Console
This method writes the format string an it’s argments to the output.
printf(fmt : String, varArgs args : Any) : Console
Does same thing as format.
flush() : void
This method flushes the buffer and forces all output to be written immediately.
References
See
|
https://stonesoupprogramming.com/2017/11/19/kotlin-console-object/
|
CC-MAIN-2021-31
|
refinedweb
| 441
| 67.15
|
Sven-Thorsten Dietrich <sdietrich@mvista.com> writes:> +#if defined(CONFIG_SMP) && defined(CONFIG_PREEMPT)> +/*> + * This could be a long-held lock. If another CPU holds it for a long time,> + * and that CPU is not asked to reschedule then *this* CPU will spin on the> + * lock for a long time, even if *this* CPU is asked to reschedule.> + *> + * So what we do here, in the slow (contended) path is to spin on the lock by> + * hand while permitting preemption.> + *> + * Called inside preempt_disable().> + */> +> +/* these functions are only called from inside spin_lock> + * and old_write_lock therefore under spinlock substitution> + * they will only be passed old spinlocks or old rwlocks as parameter> + * there are no issues with modified mutex behavior here. */> +> +#endif /* defined(CONFIG_SMP) && defined(CONFIG_PREEMPT) */May I inquire as to the purpose of placing a couple of comments underan #ifdef?-- Måns Rullgårdmru@mru.ath.cx-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at
|
https://lkml.org/lkml/2004/10/9/38
|
CC-MAIN-2017-30
|
refinedweb
| 168
| 54.32
|
This is very similar to the first example, this time I wanted to check out the MH-ET LIVE MiniKit for ESP32 rather than the Lolin32
Parts List
Pinout
This is taken from
And here is the image from the same site
Code
The code is similar – just uses a different I/O from the Lolin32 – I added debug as I was having problems with an I2CScanner, not really required in this example
from machine import Pin from time import sleep led = Pin(2, Pin.OUT) while True: led.value(0) print("LED OFF") sleep(2) led.value(1) print("LED ON") sleep(2)
|
http://www.esp32learning.com/micropython/mh-et-live-minikit-for-esp32-and-micropython.php
|
CC-MAIN-2021-39
|
refinedweb
| 104
| 73.51
|
import data into quickbooks
Orçamento $30-500 USD
I need a program/script that takes supplied data and using that supplied data create an IFF file(or other suitable method) that will create a new customer, create a new invoice, and then memorize a new invoice.
The data comes from the following page:
[url removed, login to view]
and can be supplied to your program as either a HTTP post, a tab delimited file, or from a mysql database.
Here is a link to sample IFF. (optional, as needed)
3) Complete ownership and distribution copyrights to all work purchased. (GPL or open source utilities ok)
## Platform
program must run on the linux platform and preferably be written in perl, C, or C++ . Will consider windows solutions as well.
|
https://www.br.freelancer.com/projects/php-perl/import-data-into-quickbooks/
|
CC-MAIN-2017-39
|
refinedweb
| 128
| 58.82
|
go to bug id or search bugs for
Description:
------------
the newest 5.1.X version of PHP does not seem to work with day light savings time. the Expected result was recieved from PHP 5.0.4
I am adding 6 days to Oct 25th to cross over daylight savings time on Oct 30th. There should be 25 hours in Oct 30th.
Reproduce code:
---------------
$date = strtotime('25 Oct');
echo date('m/d/Y H:m:s', $date+(86400*6));
Expected result:
----------------
10/30/2005 23:10:00
Actual result:
--------------
10/31/2005 00:10:00
Add a Patch
Add a Pull Request
Obviosly "6 days" is not equal to "86400*6", exactly because of daylight savings.
Change this line:
echo date('m/d/Y H:m:s', $date+(86400*6));
to
echo date('m/d/Y H:m:s', strtotime("+6 days", $date));
Actually I realize 86400*6 should not be right as my code displays below. It should give you back one hour short, however when I do add 86400*6 onto the day in PHP 5.1.X I am getting the exact 6 days out. That would be a problem. Again PHP 5.0.4 handles this correctly.
Please run this code with 5.0.4 and tell me what you get:
<?php
$date = strtotime('25 Oct');
var_dump(date('m/d/Y H:m:s', $date+(86400*6)));
var_dump(date('m/d/Y H:m:s', strtotime("+6 days", $date)));
?>
you get the expected result:
string(19) "10/30/2005 23:10:00" string(19) "10/31/2005 00:10:00"
However in PHP 5.1.X I get:
string(19) "10/31/2005 00:10:00" string(19) "10/31/2005 00:10:00"
Which is wrong.
Please try using this CVS snapshot:
For Windows:
>you get the expected result:
No, *I* get the expected result with both versions.
I have upgraded to the newest snap as you have requested and I am still getting the same results. PHP 5.0.4 returns the correct time. PHP 5.1.X returns the wrong time. Could this be an operating system issue? I am on Windows XP with Apache 2.
This could be also a timezone issue.
What's your TZ ?
I am Central Standard Time in MN and we are on Day light Savings time.
I unpacked both 5.0.4, 5.1.0b3 and the latest code to my Win XP box, and tried the following in command line:
C:\devtool>php-5.1.0b3\php -r "echo date('r');"
Thu, 04 Aug 2005 08:05:40 +0000
C:\devtool>php-5.0.4\php -r "echo date('r');"
Thu, 04 Aug 2005 10:05:45 +0200
C:\devtool>php-latest\php -r "echo date('r');"
Thu, 04 Aug 2005 08:10:33 +0000
I think the oly problem is that php doesn't read the timezone of the Operating system.
regards,
Czimi
well the problem comes when you cross the daylight savings time day of Oct 30th. Strtotime will handle the 25 hour day just great. Remebering there are 25 hours in Oct 30th is important. That is why when you run the following code in PHP 5.0.4
echo date('r', (strtotime('oct 25')+(86400*6)));
you do get (which is right):
Sun, 30 Oct 2005 23:00:00 -0600
an hour short of Oct 31st. However when you run that code in PHP 5.1.X you find that Oct 30th does not contain 25 hours.
Mon, 31 Oct 2005 00:00:00 +0000
This difference will definitely screw up scripts that are particularly time sensitive, like my field of Travel.
Look at the formatted date:
Mon, 31 Oct 2005 00:00:00 +0000
It doesn't have a timezone offset, so it seems that "xczimi" is right. Does it help if you add:
date_default_timezone_set("America/New_York") at the top of the script?
Oh now I understand Czimi comment. If PHP 5.1.X is not looking at the time zone on my XP box then it is not going to know that Oct 30th is daylight savings time. I think Czimi is probably right, PHP 5.1.X is not looking at the time zone my my XP box.
I tried adding that line to the top of my code. I am not familar with that function nor do I find it in the documentation. I get a fatal error:
Fatal error: Call to undefined function date_default_timezone_set()
when I run this script:
date_default_timezone_set("America/New_York");
echo date('r', (strtotime('oct 25')+(86400*6)));
I would agree with you in your conclusion though that it would appear that PHP 5.1.X is not reading the timezone of the local machine.
Now, if we can find a way how PHP can guess the correct timezone from your windows box (like it can do on most unices) that would be nice - but I think it's quite impossible.
BTW, if you use error_reporting(E_ALL) you'd have gotten a warning about this...
That function is only there in the snapshots, please try that instead. (and pick latest cvs (5.1-dev) there).
okay I figured out how to set my time zone.
I ran the following code in PHP 5.0.4 and PHP 5.1.X and recieved the same result
putenv("TZ=US/Central");
echo date('r', (strtotime('oct 25')+(86400*6)));
This would mean the bug is simply that PHP5.1.X is not looking at the time zone on the local machine.
By the way I do have E_ALL turned on, on my machine. After all I don't run my windows box with PHP in production. I use my windows box for development. Our PHP production runs on OpenBSD servers.
I don't quite understand this comment of yours:
"Now, if we can find a way how PHP can guess the correct timezone from your windows box "
PHP 5.0.4 reads my TZ perfectly and gives you the expected result. Why would PHP 5.1.X not be able to?
Please try using this CVS snapshot:
For Windows:
Sorry, but I've tested on windows and it works perfectly. Are you sure you are using an up-to-date snapshot? And that means PHP 5.1.0 beta 3 is old...
hi
it seems that I have a related problem:
I am on GMT+1
for the following example the system time is 11:00
date("H:i");
=> 09:00
set system time-zone to GMT(+0)
date("H:i");
=> 09:00
set system time to 10:00
date("H:i");
=> 08:00
It seems that php don't have the correct timezone. This error occurs since 5.1.0b3.
My box runs on win2000SP4 with the latest snapshot.
to derick:
actually its not that difficult to guess the timezone on windows (with the comming winfx api will be even easier).
After some research on the web and some testing:
#include <time.h>
main () {
time_t t;
localtime ((time(&t), &t)); // fill the _tzname var
printf("TZ=%s TZDST=%s\n", _tzname[0], _tzname[1]);
}
with GMT outputs:
TZ=GMTST TZDST=GMTDT
_tzname[0] is the timezone abbr name. _tzname[1] is filled if the current timezone has DST changes.
more testing:
Pacific time:
TZ=PST TZDST=PDT
Central time:
TZ=CST TZDST=CDT
Brasilia:
TZ=ESAST TZDST=ESADT
Brisbane:
TZ=EAST TZDST=
The problem here is that our DB doesn't have these abbreviations. But with some trialing we could all tz settings that windows uses and link them to the main db.
A better program would be:
#include <time.h>
#include <stdio.h>
main () {
time_t t;
struct tm *tstruct;
tstruct = localtime ((time(&t), &t));
printf("TZ=%s TZDST=%s is_dst:%d\n", _tzname[0], _tzname[1], tstruct->tm_isdst);
}
is_dst is 0 if DST isn't in effect, or positive otherwise.
Although you cannot get the precise tz info, you can get the timezone offset with ease.
there is a nice example here: but I can't test it, because cygwin's win32 api doesn't export some required structures (and I didn't installed MSVC yet).
This is datas from your system (or the version you use). The problem with windows is that there is many different datas in each single product version.
--Pierre
No feedback was provided for this bug for over a week, so it is
being suspended automatically. If you are able to provide the
information that was originally requested, please do so and change
the status of the bug back to "Open".
|
https://bugs.php.net/bug.php?id=33871
|
CC-MAIN-2018-09
|
refinedweb
| 1,431
| 82.95
|
On Wednesday 13 May 2009, Andrew Morton wrote:> On Wed, 13 May 2009 10:39:25 +0200> "Rafael J. Wysocki" <rjw@sisk.pl>.> > > > Isn't this a somewhat large problem?Yes, it is. The thing is 8 times slower (15 s vs 2 s) without theshrink_all_memory() in at least one test case. 100% reproducible.> The main point (I thought) was to remove shrink_all_memory(). Instead,> we're retaining it and adding even more stuff?The idea is that afterwards we can drop shrink_all_memory() once theperformance problem has been resolved. Also, we now allocate memory for theimage using GFP_KERNEL instead of doing it with GFP_ATOMIC after freezingdevices. I'd think that's an improvement?> > +/**> > + *)> > I can't say I'm a great fan of the code layout here.> > static unsigned long compute_fraction(unsigned long x, unsigned long numerator, unsigned long denominator)> > or> > static unsigned long compute_fraction(unsigned long x, unsigned long numerator,> unsigned long denominator)> > would be more typical.OK> > +{> > + unsigned long ratio = (numerator << FRACTION_SHIFT) / denominator;> > > > -#define SHRINK_BITE 10000> > -static inline unsigned long __shrink_memory(long tmp)> > + x *= ratio;> > + return x >> FRACTION_SHIFT;> > +}> > Strange function. Would it not be simpler/clearer to do it with 64-bit> scalars, multiplication and do_div()?Sure, I can do it this way too. Is it fine to use u64 for this purpose?> > +static unsigned long highmem_size(> > + unsigned long size, unsigned long highmem, unsigned long count)> > +{> > + return highmem > count / 2 ?> > + compute_fraction(size, highmem, count) :> > + size - compute_fraction(size, count - highmem, count);> > +}> > This would be considerably easier to follow if we know what the three> arguments represent. Amount of memory? In what units? `count' of> what?> > The `count/2' thing there is quite mysterious.> > <does some reverse-engineering>> > OK, `count' is "the number of pageframes we can use". (I don't think I> helped myself a lot there). But what's up with that divde-by-two?> > <considers poking at callers to work out what `size' is>> > <gives up>> > Is this code as clear as we can possibly make it??HehOK, I'll do my best to clean it up.> > +#else> > +static inline unsigned long preallocate_image_highmem(unsigned long nr_pages)> > +{> > + return 0;> > +}> > +> > +static inline unsigned long highmem_size(> > + unsigned long size, unsigned long highmem, unsigned long count)> > {> > - if (tmp > SHRINK_BITE)> > - tmp = SHRINK_BITE;> > - return shrink_all_memory(tmp);> > + return 0;> > }> > +#endif /* CONFIG_HIGHMEM */> > > > +/**> > + * saveable> > + * pages in the system is below the requested image size or it is impossible to> > + * allocate more memory, whichever happens first.> > + */> > OK, that helps.Great!Thanks for the comments. :-)
|
https://lkml.org/lkml/2009/5/13/362
|
CC-MAIN-2018-09
|
refinedweb
| 406
| 58.38
|
Odoo Help
Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps:
CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc.
Can't override rml report
I created module that overrides default invoice and it should use different rml file making it easy to change without changing anything in original account module. But somehow it still used old rml file even though in settings/actions/reports, it shows that report is using my custom rml which is located in my module. When I edit my rml file, nothing changes. When I edit original rml file (that should be overriden and shouldn't affect what will be printed in invoice) it changes my printed invoice, when I edit my rml file nothing changes. Is something went wrong?
My module: print_invoice.py
import time from openerp.report import report_sxw class account_invoice(report_sxw.rml_parse): def __init__(self, cr, uid, name, context): super(account_invoice, self).__init__(cr, uid, name, context=context) self.localcontext.update({ 'time': time, }) report_sxw.report_sxw( 'report.custom.account.invoice', 'account.invoice', 'addons/report_custom_invoice/report/account_print_invoice_custom.rml', parser=account_invoice )
xml file:
<?xml version="1.0" encoding="utf-8"?> <openerp> <data> <report auto="False" id="account.account_invoices" model="account.invoice" name="custom.account.invoice" rml="report_custom_invoice/report/account_print_invoice_custom.rml" string="Invoices" attachment="(object.state in ('open','paid')) and ('INV'+(object.number or '').replace('/','')+'.pdf')" usage="default" multi="True" /> </data> </openerp>
__openerp__.py:
{ 'name': 'Custom Invoice template', 'version': '1.0', 'depends': ['base_registry_code'], 'author': 'OERP', 'description': """ Account Print Invoice ========================================== This module customizes default invoice. It adds company registry code in invoice template. """, 'website': '', 'category': 'report', 'demo': [], 'test': [], 'data': ['account_invoice_report.xml' ], 'auto_install': False, 'installable': True, }
Did you use OpenERP Version 7 ?
In V7 there are different solutions to print. (A top print button with pulldown list, B below print button eg red) Print Button A maybe disappear if multi="True". The report id is hard coded in the method called if you click on print button B.
I have overwritten the invoice_print method and changed the return value to my report. It works for me, maybe there are better solutions.
invoice.py
from osv import osv, fields from tools.translate import _ class account_invoice(osv.osv): _inherit='account.invoice' _name='account.invoice' def invoice_print(self, cr, uid, ids, context=None): res = super(account_invoice, self).invoice_print( cr, uid, ids,context) #self, cr, uid, ids, context) res["report_name"] = "custom.account.invoice" return res account_invoice()
__init__.py
import invoice
Yes I did use OpenERP 7. I used your code and it worked. Just needed a bit of modifications, because newer openerp revisions changed where osv and tools are located. Now it should be:
from openerp.osv import osv, fields
from openerp.tools.translate import _
.Thanks.
I tried your code and I have doubt that you didn't add your xml file in
__openerp__.py.
There is one more thing you need to change in xml that is you need to remove
multi="True". Else everything is ok.
multi="True" is used when you want to remove your report from Print option in form view.
Make this changes, restart server and update your module.
Inherit Custom RML Report this may be help you.
Don't understan't why it does not work. I removed
multi="True". I updated my answer with __openerp__.py file data.
Hi,
see this subject Change report in a custom module?
I looked into this this one. But it seems like its code is the same as mine (just for different report)
About This Community
Odoo Training Center
Access to our E-learning platform and experience all Odoo Apps through learning videos, exercises and Quizz.Test it now
Make sure you have import py file in
__init__.py.
I have import py file in report/__init__.py
Did you add xml file in
__openerp__.py?
|
https://www.odoo.com/forum/help-1/question/can-t-override-rml-report-20315
|
CC-MAIN-2017-30
|
refinedweb
| 638
| 52.97
|
Ads Via DevMavens
In June, Dmitry posted a very simple photo album on his blog. I immediately liked it because it's both easy to set-up (just drop the ashx file into your web site's photo directory) and to manage (no need to upload images one by one using a clumsy web upload field, just upload new photos using ftp or the file system). It's also nice to browse. Sure, there are no fancy ratings or comments features, you can't add titles or descriptions, but frankly, I didn't need all these features.
Still, I wanted to change a few things so I went ahead and added the following to Dmitry's handler:
Viewing folders
Viewing thumbnails
Viewing details
The handler is under a shared source licence, which means that you can do pretty much what you want with it. It uses the Metadata public domain library by Drew Noakes and adapted for .NET by Renaud Ferret to extract the EXIF information from the jpeg files. This library can be downloaded from. Please use the dll from the workspace below, though, as I've made a small correction. I've also sent the correction to Renaud, but he may not publish a new version immediately...
Download the code for the handler here:
Special thanks should go to Dmitry Robsman and David Ebbo.
UPDATE: the handler is now hosted on Codeplex.
Infinity: it's shared source, so feel free to implement that, but I won't in the near future, jpeg being the dominant format for photos. Sorry.
This is a great software.
But I can only run it on Windows 2000 Server. I've tried two different Windows 2003 servers. With no luck.
Does anybody know how to get this running on Windows 2003 Server?
Tom, I'm running it at home on Windows 2003 Server without a problem. What exactly is the problem you're seeing? Are you sure you have ASP.NET 2.0 installed? Is ASP.NET activated in IIS?
I dropped the files in an image directory, and I'm getting the following error: "The type or namespace name 'com' could not be found" on the com.drew.metadata namespaces.
For the moment, you also need to copy the dll to the bin folder. I'm working on a new version that removes that requirement.
Thanks for the quick response. To clarify, I moved MetaDataExtractor.dll to my site's root bin directory, and that solved the problem. Looks like a great tool.
Looks good, but the link to download isn't working. This is a long shot, but would you want to code in a user management system so only certain users could access certain folders?
Jared: I just tried the link and it's working for me. Maybe the site was down when you tried. I don't think there's a need for a specific user management system: the built-in membership system of ASP.NET should work fine with it.
Looks like the link was down when I last tried, thanks. I've been playing around with it a bit (mainly to get it to play with a different source directory, a networked drive) and noticed it has trouble with hidden/corrupted .jpg files (these are being created by Mac users somehow). Also, is there any way to add in non-jpeg files (gif, tif, png, etc.)? It seems it is limited to what the MetaDataExtractor can read.
Jared: I think you'd have to fix those jpgs before you use them with the handler. Both corrupt jpg and non-jpg file handling are features I don't plan on adding for the moment as I have little time and more important features to implement but feel free to modify the code any way you want and implement those.
Bertrand: i downloaded the albumhandler.zip (2.0 and 2.1) and extract the files into the image folder... when i run it, i got the following message:
Parser Error Message: Type 'AlbumHandler' does not inherit from 'System.Web.UI.UserControl'.
Source Error:
Line 2: <%@ Register Src="~/album.ashx" TagPrefix="photo" TagName="album" %>
Do you have any idea what causes the problem?
You probably don't have ASP.NET 2.0 installed, or it's not active on that application.
Hey it's really great!!
Is it possible to scan only a certain folder? Because right now it scans everything in my website ehhe
Mike: just put the handler in the folder you want to scan.
I am not able to use this code please help
Neeraj: you're going to have to give more details. First check that the web site you're trying to use it on has ASP.NET 2.0.
I can get the album to work great if I put it in the root of my site, but if I put it in one directory then it loads all the links, but no thumbnails....
Any ideas?
Thanks in advance!
Daniel, please file a bug on GotDotNet.
Calios: thanks for the suggestion, that's a really good point.
Calios: thanks for the fix.
Judge: I've thought the exact same thing ever since I learned about Home Server. Unfortunately, I don't own one so I can't try it. However, from what I know I don't see what could prevent it from working. If anyone wants to try, I'd love to know how it goes...
Thanks Mike! This rocks!
There shouldn't be a limit on the folder depth. Can you package a repro into a small zip file and send it to me at bleroy at microsoft dot com?
Russ: how exactly does it not work? What I meant was that if you have a photo named default.jpg, the handler will use it as the top of the stack. Other photos will be randomly selected. If you don't have a default.jpg, it takes a random photo for the top of the stack. Does that help?
Thanks for explaining it. At least now i know that is not causing the issue. See the following link for my use of the Photo Album:
The album works great, but it does not show the stacked effect of the images in the album. Not sure why this is happening.
Russ: can you look for the UpFolderStackHeight setting in the handler and check that it's not set to 1?
UpFolderStackHeight = 3
Russ: then I have no idea, sorry. Never seen that happen.
I found the problem and fixed it. Since the color of my background is not black, i had made the modification suggested by Calios:
"Calios said:
Found a little bug/annoyance - im posting it here since gotdotnet will phase out in a few days(19th of June 2k7). in CreateFolderImage you didnt fill in the BackGround - thus using any other background than black will look wierd :-O I added this to fix it: g.FillRectangle(new SolidBrush(BackGround), 0, 0, size, size); Right after the stacked Graphcis has been declared (was line 477 of the .ashx file for me - v 2.1 of the handler) :-)
# June 8, 2007 9:33 PM"
In troubleshooting deeper, i realized that i had placed this line of code in the wrong place. it all works fantastic now.
Thanks again,
Russ
Last night, I uploaded the source code and release package for version 2.0 of the photo handler . I'll
I just finished migrating my PhotoHandler workspace from GotDotNet to CodePlex. I have got to say that
Hi, when you mention downloading code from
renaud91.free.fr/MetaDataExtractor
it might be worth mentioning to download the
MetaDataExtractorAssembly222d.zip file
MetaDataExtractorAssembly230g.zip doesn't work.
Your photohandler works great in Internet Explorer.
In Firefox, however, it shows the pictures (and directories) all in one column.
Any idea how to fix this?
Thanks!
Bas
Bas: did you make any changes to the style sheet? I just checked and it displays fine in Firefox, Opera, Safari and IE.
Hi
Thanks for making this tool available.
I have a small problem though. I am able to see the different folders display as groups of thumbnails. But when I click on it. It doesnt take to the album.
I really liked this implementation.
BTW: I am using Win XP Professional
Thanks,
Sona
Sona: not sure I'm following you, it seems to work fine on your site.
Ok I dumped this into a folder with three pictures and recived the following. Do you wise ones have any suggestions for me?
Thank you in advance
John G.
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS0246: The type or namespace name 'com' could not be found (are you missing a using directive or an assembly reference?)
Line 52: using System.Web.UI.WebControls;
Line 53:
Line 54: using com.drew.metadata.exif;
Line 55: using com.drew.metadata.jpeg;
Line 56: using com.drew.metadata.iptc;
Source File: d:\hosting\jgarlie\Custom\2\album.ashx Line: 54
John: you forgot to drop the meta data extractor dll into the applicaiton's bin folder.
Ok first and foremost thank you for this awesome app!
Now I've been trying to get this to work but to no avail.?
Also, for those interested in changing the background color and aren't necessarily using a "named" color they can substitute the
Color BackGround = Color.Black
for
Color BackGround = ColorTranslator.FromHtml("#XXXXXX")
Where the X's stand for the Hex code of the color.
Any help for my issue described above would be great!!!
Axeman: you can try to see what the response was using Firebug or Fiddler for those images. I'd guess a trust level mismatch with your configuration. We can also continue this conversation offline (bleroy at microsoft dot com)
Great app!!!
Is there a way to pass a different stylesheet to the handler, or have it use a different background. I have the app within a container on my home page and I would like to have it use a differnet background. It keeps using the background image of the main page and I can't figure out how to change it.
thanks
Great work!!! I want to definitely give it a try to integrate in my new Dating website! But before i start using the source code; is it permissible to use this code without any infringement of policies?
Ok I got everything to run fine on my local machine. When I publish to my site hosted by Godaddy.com I get a problem with the following code. Apparantly they are not giving me rights to the temporary asp.net folder this is using. Thanks in advance for your assistance.
Static IMagehelper()
{
..
_imageCacheDir = Path.Combine(HttpRuntime.CodegenDir, "Album");
Directory.CreateDirectory(_imageCacheDir);
This is the error:
Request for the permission of type 'System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
Beau: the stylesheet is inside the handler. It's very easy to change.
Manoj: the license is MS-PL. See
John: there's a setting in the handler for the cache location. Disk only works if you have a high enough trust level. Memory and none works everywhere.
ok I found it and changed it to memory and all is well.
Thank you
I get this error...
Error 1 The type or namespace name 'Directory' does not exist in the namespace 'com.drew.metadata' (are you missing an assembly reference?) C:\Users\Rob\Documents\Visual Studio 2005\WebSites\PhotoAlbum\album.ashx 58 45 C:\...\PhotoAlbum\
sorry im new to all of this and am probably being really stupid. Ive put the DLL into the Bin folder and the other errors went ragarding this reference, but this one has stayed
Robert: that's weird. Are you sure you included the same version of the dll that came with the release file? Just unzipping the release in a web app should works out of the box. Does it or did you do something different from that?
D'Oh i was being an idiot...
I went to the link, clicked on the 'Source' tab and downloaded that. it only came with a samples folder etc and was wondering was was going on.
I must be needing sleep!
Thanks for the help Betrand
Just a quick question. I have 70 pictures in the share folder but only 22 show up on the web page. Am I missing something? I am using Windows Home Server RC1. My page is the above URL. I also posed this question on Andrew Grant's site.
I like how easy it is to use.
Are all 70 photos .jpg files?
Actually 18 are jpeg and the balance is bitmap. Is that where I have gone wrong? The bitmaps are 1,800 - 2000 KB and the jpegs are 130 - 200 kb.
Phil: yes, the handler only takes jpg files.
Thanks, I converted all to Jpeg and they all show up now
A little more explaintion of the fix for black background on thumbnails please tried
but did not change anything
M Anderson: thanks, but this is a known issue (and the project moved to Codeplex long ago):
Hi, I have the same problems with
"using com.drew.metadata.exif" error.
I've downloaded latest album files (AlbumHandler2_1), extracted to wwwroot.
May I have to do anything else in IIS? (winxp)
Danilm: I'll give you the same answer I gave to other users who had the same problem and which you can read above... You probably forgot to copy the dll into the bin directory.
I'm sorry but I have copied the dll into the bin directory and it doesn't work
is the right version: 2.2.2.41745?
I've downloaded AlbumHandler2_1 that contains all the files and folders
Is the bin directory directly below the IIS application folder?
Awesome App Bertrand! I love how easy it is to use just the .ashx page! Now of course I have a question...
My file structure is such:
<Root>/Family/Photos/album.ashx
<Root>/Family/Photos/default.aspx
<Root>/Family/Photos/2007/<photos>
I had to change the CacheLocation to CacheLocation.Memory because of my host.
When I run just the album.ashx it works perfectly, all the images display, only the 2007 and sub-directories show and navigation works fine.
When I try and run the default.aspx (which I modified the original to have the src="album.ashx" instead of src="~/album.ashx") I see all directories from the root (minus hidden/protected ones) and only the red X image, no images anywhere, even in the 2007 and subs, but if I click "Details" it does show the EXIF details of the photo. The navigation still works fine, and when I get to the point where the tool tip would normally read "Click to view picture at full resolution", if I click that it opens a new browser and shows the photo as expected.
Two Questions:
1. Any idea why it doesn't show any of the photos when being called from the Default.aspx but works fine in the album.ashx?
2. How do I make it so it only scans sub-directories from it's location when being called from the default.aspx file?
Thanks for the awesome utility!
Trinity: I think that may be a bug. Please file it on the CodePlex site.
The control will always limit what photos it displays to the directory where the handler is (not the page) and subdirectories.
weird error..
<!-- Web.Config Configuration File -->
<configuration>
<system.web>
<customErrors mode="Off"/>
</system.web>
</configuration>
and
<customErrors mode="RemoteOnly" defaultRedirect="mycustompage.htm"/>
Any Ideas ?
Cab: what's the error?
Hi,
I am trying to costumize the application, although I am not being able to change the backgroudn color for the upfolder and thunbnailfolder icons... I want my background to be white and for those its in black... any one can help?
Pedro: there are config entries in the handler as wel as forum posts and bugs on the CodePlex site that should get you started.
Is there a way to have handler pull images from a certain directory?
Example file structure:
Bin
App_Data
images
---->Folder 1
---->Folder 2
---->Folder 3
defualt.aspx
ablum.ashx
Mike: why don't you put the handler in the images folder?
Bertrand-
You should not have blown M Anderson off like that. He/She is reporting a different issue (October 4, 2007 7:26 PM.)
1. Calios' June 8, 2007 fix for the background of the stacked Folder Immages works just fine. So it is no longer a "known issue" but rather a fixed issue.
2. What M Anderson is reporting is a peculiarity that I do not fully understand but can discribe. If you make the change Calios describes, the thumbnails don't change until you change the folder names. The thumbnails are stored in the application's temporary folder, background and all. They do not change just becuase you say you wnat them to look different. You have to do something to cause them to re-write.
ttomm: right, and this is a known issue too. If you want to regenerate the thumbnails, for the moment, you need to physically delete them or somehow restart the appdomain (touching web.config should do the trick). The original issue is not fixed in the sense that the fix is not yet in the current release, so it's a "known fix" rather than a "fixed".
Awesome little app, however I have some issues with it, when I add the required files to the directory, it shows everything as it is supposed to, however when I click on an image, to see if in the center of the screen, it doesnt show at all, it only shows the 'Details', 'Previous Image' and 'Return to Folder View'.
I like this app very much, but I would LOVE for it to show the image in the center of the screen.
I'm running this on WHS (Home Server) and the client OS is Vista, with IE7.
Jeff, please contact me through the contact form, and I'll look into it.
Hi Bertrand,
I want to change background color of thumbnail. I changed the following code:
private static readonly Color BackGround = Color.White;
However, the color remains blank.
Please help. Thanks.
Cathy: that's this issue:
The bug is not fixed in the current release but the discussion on it contains a fix.
hello, seems to be a nice album, but it's not working on my hoster. sohosted.com
I also have this problem:?
sohosted.com is running on medium trust, changin the location of the cache to none or memory doesn't fix the problem....
somebody knows what to do?
Regards
Lou
@Lou: it seems like you're using the user control version. If that's the case, you can try to set the HandlerUrl property to point at the ashx file, and also the Path property on non-postback requests.
Thanks for writing such a nice tool. I have tried on my website and everything works fine. However there is one photo that doesn't show the details when I use the aspx page and clicked on it. If I use the Album.ashx the same photo displays the details. To experience this behavior please go to and click on photo gallery. for now I set the url to Album.ashx to display the images. If you go to that page, you will see two photos. The first image is the one that I am having issues. If you go to you will see the same photo. And if you click on it, it doesn't display the details.
I am not sure what could be wrong?
sridhar.
Sridhar: I have no idea. The image isn't even in the dom. Drop me e-mail at bleroy at microsoft com and we'll try to debug into it.
Great Work...
All is working well in my local machine. But when I publish it on my website and click on my Gallery Menu...
It is prompting me a user name and password and not allowing me to access my gallery...It has something to do with the permission with my host...but When I checked my rights I have drwx...
Is there something else that I need to changed in the codes...Can somebody please give me some suggestion that I can try to make it work....or If somebody encountered the same problem please let me know what to do. I already changed the Caching to Memory but still the same...
Thanks very much in advance.
MichaelR
@Michael: I have no idea. You should check that with your hoster. Let me know what you find.
I was wrong...Memory Caching sorted it out.
But I get some links and red croses though in some of
the pictures though...Is this a bug or Is there a work around with this.
Thanks very much
@Michael: are the broken images consistently the same images? Are they jpeg images? Is there a public url where I could have a look?
My images are in jpeg format.
(thumbnails) red crosses and link are coming out inconsistently in these series...
thummnail ok thummnail ok thumbnail ok red cross red cross red cross link link link thumbnail ok...
I say inconsistenly, I mean sometimes when you view the gallery red crosses and links come out the other time they are fine.
url:
@Michael: we should take that offline. Please write me e-mail at bleroy at microsoft. There is a server error on these images but I'm unable to diagnose it because you have cutom errors on (which you should, this is absolutely the right setting). We should be able to sort this out via e-mail. Thanks.
This is working fine on my local machine
but on the server it just shows white bg , missing images and links , I have set my server to allow the application write permission. Any thoughts
Check that you configured the directory where the handler is as a web application.
Need Help, I get the album to work when I debug but when I publish I get the following error.
Error 13 There is no build provider registered for the extension '.ashx'. You can register one in the <compilation><buildProviders> section in machine.config or web.config. Make sure is has a BuildProviderAppliesToAttribute attribute which includes the value 'Web' or 'All'. E:\Visual Studio 2005\WebSites\xxxxxx\Entertainment\Gallery.aspx 3
@Wil: check that the server has ASP.NET 2.0 or higher installed, then check the web.config file.
I am having the smae problem, able to debug, but publish.... ASP.net 2.0 is installed on my local machine, and the web config for the website had the build providers included.... Any other suggestions...
@Jeff: difficult to say without looking at the server. Drop me a mail through the contact form and I'll have a look.
Hello,
I copied album.ashx and MetaDataExtractr.dll to directory with jpgs but I get this message:
"Błąd serwera w aplikacji '/PhotoHandler-6410'.
--------------------------------------------------------------------------------
Błąd kompilacji
Opis: Wystąpił błąd w czasie kompilowania zasobu wymaganego do obsłużenia tego żądania. Przejrzyj poniższe szczegółowe informacje o błędzie i zmodyfikuj odpowiednio kod źródłowy.?)
Błąd źródła:
Wiersz 52: using System.Web.UI.WebControls;
Wiersz 53:
Wiersz 54: using com.drew.metadata.exif;
Wiersz 55: using com.drew.metadata.jpeg;
Wiersz 56: using com.drew.metadata.iptc;"
this line is red:
this:?)
means: compilator error message: CS026: Could not find type name or namespace 'com' (check whether "using" is missing.
Hope You'll help me.
Greetings
@Bartek: it's hard for me to understand the localized error message but I'm suspecting you didn't put the dll into the bin directory of the web application.
i checked it once again and MetaDataExtractr.dl is in this directory;/
@Bartek: is the bin directory in a directory that is configured in IIS as a web application?
I assured that I put MetaDataExtractr.dll into the appropriate directory.;/
@Bartek: I believe you. The question I was asking was on the *parent* directory of bin. Is the parent of bin configured in IIS to be a web application? We can take that offline. Please contact me using the contact link.
Has anyone been able to get this into a DNN Module? Can I use this in DNN?
@Ty: I never tried, but if you use it as a user control, I don't see why not.
Is there any way to display the folders in date order and not alphabetically
@Dominic: it already is in date shot order. If that's not the case for your photos, maybe they are using an exotic EXIF tag. Feel free to send me one of those at bleroy at microsoft and I'll have a look.
I'm running the photo album on my Windows Home Server but I've run into problems with a few photos. Some photos shows as thumbnails but they are not shown in full size when I click the thumbnails. It seems like they won't load at all. If the photo doesn't load, the next thumbnail will not appear. If I open the photo in an image editor and save it with a new name, it seems to work.
Mine problem is all on godaddy when the default.aspx hit this line of code it stops
<photo:album
If I remove it the style sheet loads, but obviously the ablum doesn't work.
I can only get the original Album.ASHX to work. I an out of options until my contract with gofatty is up, cause I don't know what else to do.
Directory.CreateDirectory(_imageCacheDir);
I saw mention earlier that changing the Caching == CacheLocation.Disk to Caching == CacheLocation.Memory in the ashx file will work for godaddy. But I have tried changing all the string to memory and I still get the same error. I gues I am unsure on how to change the handler.
Hi Bertrand.
Excellent work with this photo handler. Well done. I have just one question. I would like to display a subset of the EXIF meta-data. Ie.. If I wanted to view Model, Exposure and F-Number details. Is it possible?
Thanks
Dave OS
@Dave: sure, for the moment I'm just dumping all the available info but you could certainly modify the code to only display a subset.
Thanks. I've tried but to no avail. My skill set dos'nt include C# :(. Any idea where i can start?
@Dave: if you go to GeneratePreviewPage, there is a double loop in there that loops over Image.Metadata. You could modify the code in there so that it continues the loop if the data is not in your predefined list. Something like if (!["OneKeyIWant", "AndAnotherOne"].Contains(data.Key)) continue;
Thanks for that Bertrand. I played around with it for a bit and got it working. Here it is below. I removed the qoutes from each side of the commas. :)
if (!"Model, Exposure Time".Contains(data.Key)) continue;
Again.... Thanks for your help.
I am working on converting this code to a VB format, but before I continue has anyone here already done that?
Thanks in advance!!
-Jeff
@Jeff: no, nobody is working of that that I know of. How would you keep up with new releases though?
Bertrand,
You are correct, that is my dilemma. I am now looking for a option. Thanks for your response!
@Jeff: actually I'm not quite sure why you would want to do that in the first place. If you really want to do it, I'd at least wait for the next update, which will be quite major.
Can you please let me know "How do I make the code to select the Images present in a particular folder and subfloders present in that folder"?
I mean to say "If I have placed a folder with the name ALBUMS and this folder ALBUM contains so many subfloders with the related images". So in this case how would I make the code to select the folders present only in the ALBUM Folder?
@babji.sunny: I'm not following you. The photo album already works with subfolders.
its very nice to use....thanks dude....
This is a cool app. Thanks for sharing it!
Here is my question: Does this work if it's used with a Master Page? I am using a Master Page so that I have the same look on each page. It seems that the photo album is starting at the root of my web application and trying to grab images and directories from there. Have you ever tried this with a Master Page before?
@Jeremy: sure, it should work just fine with a master. You should be able to set the path property on the control to any directory you want.
how to change bgcolor of folder, I want white color..............
:((((((((((((((((((((
pls tell me how to change....pls
Thanks for this quick an nice solution.
It took me less than 2 minutes to get it up-and running.
Nice application for jpg handling.
Awsome app, Worked great right off the bat additional user privledges needed to get the app creating its folder icons but I figured it out. Thanks for putting this together. Most companies are chrging through the nose for the ability to have a nice photo album on a website!
Hi, This looks great and something I think I can really use, but unfortunately I am encountering problems trying it on brinkster. Here is the error I am receiving. Any help you can provide is greatly appreciated. Thanks much in advance.
Compilation Error
@George: you probably didn't upload the dll into the bin folder of the application.
Hi, thanks for the quick response, but yes, I have uploaded the bin file to the application. Any other ideas?
Are you sure that bin folder is at the root of the configured IIS web application? (this is the only reason why you'd see that message)
Ahh ha... thanks again for the quick responses. I had the dll in the bin folder under the webroot folder. I just copied up the file album.ashx to my webroot folder though and it works fine there. I have not been able to get it to work in just a subdirectory yet though. I will try again tomorrow. Thanks very much for your assistance!! Great utility!!
Do you have a VB.NET Version?
@Tango: no.
Hi, this is great, but I can still only get it working in my webroot directory. If I put album.ashx in a sub folder I get the error "type or namespace com could not be found". I do have the dll in the bin folder of webroot though. Do you have any ideas on how I might resolve this? I really only want to display images from the subfolder. Thanks in advance.
some additional information... the version of the dll I am using is 2.2.2.41745. Thanks - George
@George: you can use the album as a user control and set its path property.
Hi great job. Working fine on mine. Just wondering if it is possible to have image titles or description added.
Thanks
@miraz: that's failry easy if you use it as a user control (there are templates for precisely that), otherwise you can delve into the rendering code and add it.
Hi, I dont' mean to be a pain (fairly new to this), but where do I set the path and property? Do I do it in album.ashx? If so, do you know which line, or do you have an example. Thanks again very much in advance. Again, it works fine in my webroot, but I receive the error "The type or namespace name 'com' could not be found" when I try it in a sub directory.
@George: look at the sample that comes with the handler. It uses the handler as a control inside a page. You can set the path property on this control.
This is just what I needed! Thanks for sharing this wonderful app.
I have close to zero experience with IIS and ASP.NET yet I was still able to get up and running in about an hour or 2 with help from these messages and google.
I plan to create a mobile.ashx/aspx with smaller image dimensions so I can view my photos from anywhere on my phone.
Thanks again.
I am a newbie and I have this handler up and running. I need to restrict the handler to pick up a specific directory. I have tried dropping the handler(album.ashx) in the specific directory but then when I run it, I get the thumbnails with red x's. I am simply trying to get the folder \Photos with Sub Dir's \Album1, \Album2, etc. to display without pulling from the root of the website. I have treid multiple configurations and seem to run into issues. It lloks like I can set the path in the control properties but that gives me another error ~/Photos/album.ashx. Please help!
@Rick: You don't *need* to use the page and control if you're not going to add stuff around the album or modify the templates. You can use just the handler on its own, and drop it into the photo directory.
If you do want to use it as a control, the path must not point at the handler but rather at the photo path.
Got it working. Thanks! I did not realize that you could use the .ashx directly as a page. Is there a simple way to use this with an MSACCESS database BLOB for your pics?
@Rick: no, no database support, sorry, unless you add it yourself. But why would you want to do that? Is it an existing database that you have from which you want to extract pictures?
I'm looking for source code to extract metadata from jpeg file in IPTC format, please help with C# or VB.NET
vatanpour@msn.com
I have a client who is in a hurry and wants an image gallery to be working by tomorrow ..
So I came across this site.. it seems really cool..
I'm still trying to figure out a way to add a description for each photo without using data tables..
I think I am going to use one xml file for each folder..
not sure yet..
any quick suggestions?
@Rima: the metadata in the image files themselves is more than capable to do that, and the album handler already knows how to read that information. Adding an xml file seems unnecessary.
The issue I am having is that it creates the initial album perfectly, but I am pointing to a virtual folder through IIS and the script seems to set all the addresses as f/photos instead of /photos, so I cannot click on the thumbnails for the folders to look inside...any ideas?
@Nathan: I don't understand. Can you send me e-mail at bleroy at microsoft with some more details about what you're trying to do?
Roy, the issue is, I am adding a backend for the album, to allow uploading photos, the guy isn't really into using FTP to upload each photo.
So I need a way to make uploading images, editing titles, metas and directories, deleting possible.
and I added directories creating, editing, deleting..
but the issue is I want him to select an image or album from the rendered control and edit them..
Hope you got my point.
What I am trying to add now is a button inside the <ITEMTEMPLATE> that hold "command name and command argument" though dealing with a repeater in this is a real pain.
Why I can do it separately, but I actually want to use the power of thumbnail generation on disk.
any suggestions?
Is the CSS in the current version on codeplex the newest version? because the layout doesnt look the same as the one on those images, I think i have the same problem as posted by Martin Dolphin in the very first post here
@Rima: the library that I'm using currently doesn't support writing the meta-data back to the image files but that sounds like the right thing to do in principle (and I believe .NET now has read/write APIs for EXIF data). Storing that data in a database might get you there faster though.
@greg: let's follow up offline on that.
I did not add the editing.. just added file upload, directories and files names editing and deleting.
I still can't get this PATH attribute work.
keeps getting:
Value cannot be null.
Parameter name: value
on the line:
if (path != _requestDir && !path.StartsWith(_requestPathPrefix)) {
I can't use the default album.ashx, I need to edit the template.
I have the images in a directory called: Gallery
So I tried setting the path:
~/Gallery
Gallery
~/Gallery/
Gallery/
/Gallery/
And keeping the Register
<%@ Register Src="album.ashx" TagPrefix="photo" TagName="album" %>
Same here... images in a subfolder and Path property wont work. where's the documentation for this thing?? nice application isn't so nice without docs.
Try putting the handler in the same folder as the images. There is no documentation for this. This is something I'm building for myself. I'm putting the source out there in case people find it useful but that's all. Not my day job. Sorry.
how put paging in the photo thumbnails page..
Sir,
Your Development (A simple ASP.NET photo album) is Excellent.
But I need a Small thing.
I Have Three Folders in my web directory,
Folder 1: images (some JPG images are there)
Folder 2: Products (some JPG images are there)
Folder 3: Album
Album_one (subfolder of Album)
Album_two (subfolder of Album)
I want this photo album is only applicable for
Album folder and subfolders of Album_one, and Album_two.
How to Change the code.
Thank you.
Nath
@Shankar: no need to change the code, just put the handler in that Album folder.
|
http://weblogs.asp.net/bleroy/archive/2005/09/08/a-simple-asp-net-photo-album.aspx
|
crawl-002
|
refinedweb
| 6,417
| 76.22
|
This is wash. It is yet-another shell environment for the web. Wash's special trick is that it can “mount” virtual file systems using postMessage based IPC.
It is accidentaly similar to Plan 9‘s file system, in that each origin comes with it’s own virtual filesystem that can contain data and executables.
The actual IPC messages are JSON, and can be serialized over any transport.
The work consists of two parts. Objects in the
lib.wam.* namespace are part of shared library code, which all participating origins should use. This code comes from
../lib_wam.
The
wash.* namespace is a Chrome V2 app that combines the hterm terminal emulator with a bash-like read-eval-print interface that supports lots of readline commands and keybindings.
|
https://chromium.googlesource.com/apps/libapps/+/hterm-1.32/wash/README.md
|
CC-MAIN-2019-22
|
refinedweb
| 127
| 67.86
|
Subject: Re: [boost] [bcp] Bcp namespace rename causes compileerrorsonmultiple libraries (type_traits, range, spirit, foreach, regex, iostreams) in 1.43
From: John Maddock (boost.regex_at_[hidden])
Date: 2010-06-10 11:01:03
>> I will look into and try and fix all the issues you identify as soon as I
>> can,
>
> Thanks! Keep me in the discussions (if the coordination continues on the
> Boost dev mailing list, I'll follow it there).
I believe bcp on current Trunk is now doing the right thing by all the Boost
libraries.
HTH, John.
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
|
https://lists.boost.org/Archives/boost/2010/06/167878.php
|
CC-MAIN-2021-10
|
refinedweb
| 112
| 68.87
|
- NAME
- VERSION
- SYNOPSIS
- DESCRIPTION
- METHODS
- SYNTAX
- OPTIONS
- SEE ALSO
- BUGS
- AUTHOR
NAME
Syntax::Feature::Sugar::Callbacks - Add sugar for declarative method callbacks
VERSION
version 0.002
SYNOPSIS
use AnythingExportingMethodModifiers; use syntax 'sugar/callbacks' => { -callbacks => { after => {}, before => {}, around => { -before => ['$orig'] }, }, }; after foo ($n) { $self->something($n) } before bar ($n) { $self->something($n) } around baz ($n) { $self->something($self->$orig($n)) }
DESCRIPTION
You probably won't use this extension directly. That's why it doesn't even have an
import method. Its main reasoning is the ability to provide on-the-fly sugar for method declarators, most commonly
before,
after and
around. This extension will directly dispatch to the original subroutine, and requires these to be setup before-hand. Currently, all callbacks will first receive the name of the declared method, followed by the code reference.
Note that no cleanup of the original handlers will be performed. This is up to the exporting library or the user.
METHODS
install
$class->install( %arguments )
Called by syntax (or others) to install this extension into a namespace.
SYNTAX
All declarations must currently be in one of the forms
<keyword> <name> (<signature>) { <body> } <keyword> <name> { <body> }
The
keyword is the name of the declared callback. The
name can either be an identifier like you'd give to
sub, or a double-quoted string if you want the name to be dynamic:
after "$name" ($arg) { ... }
The signature, if specified, should be in one of the following forms:
($foo) ($foo, $bar) ($class:) ($class: $foo, $bar)
Variables before
: will be used as replacement for the invocant. Parameters specified via
-before and
-middle will always be included.
The statement will automatically terminate after the block. The return value will be whatever the original callback returns.
You can supply subroutine attributes right before the block.
OPTIONS
-invocant
Defaults to
$self, but you might want to change this for very specialized classes.
-callbacks
This is the set of callbacks that should be setup. It should be a hash reference using callback names as keys and hash references of options as values. Possible per-callback options are
-before
An array reference of variable names that come before the invocant. A typical example would be the original code reference in
aroundmethod modifiers.
-middle
An array reference of variable names that come after the invocants, but before the parameters specified in the signature. Use this if the code reference declared with the construct will receive a constant parameter. There is no current way to override this in the signature on a per-construct basis.
-default
An array reference of variable names that are used when no signature was provided. An empty signature will not lead to the defaults being used.
-stmt
By default, anonymous constructs will not automatically terminate the statement after the code block. If this option is set to a true value, all uses of the construct will be terminated.
-allow_anon
If set to a true value, anonymous versions of this construct can be declared. If no name was specified, only the code reference will be passed on to the callback.
-only_anon
If set to a true value, a name will not be expected after the keyword and before the signature.
SEE ALSO
BUGS
Please report any bugs or feature requests to bug-syntax-feature-sugar-callbacks@rt.cpan.org or through the web interface at:.
|
http://web-stage.metacpan.org/pod/Syntax::Feature::Sugar::Callbacks
|
CC-MAIN-2019-43
|
refinedweb
| 553
| 55.44
|
I opened an existing 1.2 app, added a store, assigned it to a combo, then generated the code. Loaded it up in Firefox and got "c is not a constructor". I eventually figured out that the namespace I had in the 1.2 project settings window is now available under the "Application" component config's "name" attribute, but it had reverted to "MyApp". After fixing that, all was well, and I'm now able to generate code for a particular form that always crashed 1.2 the moment I dared to click on it, so this is a definite improvement on that front :-)
I still dream of a Componet Config grid with larger fonts that I can read more easily, and a one-click button each for the Hide Inherited and Hide Unset Configs options. Because there is just so much to display in these grids, I'm constantly having to switch back and forth between these settings to find what I'm looking for, and I've never been one to type the first few letters into the filter box of each setting I want to modify, rinse, and repeat, for each setting as that just drives me nuts. The way I see it, there's plenty of room to the right of the "Component Config" and "Events" tabs to right-align two discrete buttons in that header row to do these two actions. Pretty please? The two-click process to activate these actions gets very annoying after a while.
It would also be awesome if Designer remembered the fact that I had it maximised last time (rather than being a window the right size but shifted down the screen so that the grey status bar was beneath my task bar), and would remember the form I am currently working on in the Project Inspector. I see that it does not expand the component tree for every form I have any more, on loading a project, which is a welcome improvement. Thanks. And seeing the exact name of the thing I've click on at the bottom of the project inspector is a great idea.
|
https://www.sencha.com/forum/showthread.php?181929-App-name-reverts-to-MyApp-opening-old-projects
|
CC-MAIN-2017-09
|
refinedweb
| 357
| 69.96
|
Discover more resources for these services: Virtual Machines
Discover more resources: Compute Data Services App Services
This tutorial describes how to use MySQL in conjunction with Django on a single Azure virtual machine. This guide assumes that you have some prior experience using Azure and Django. For an introduction to Azure and Django, see Django Hello World. The guide also assumes that you have some knowledge of MySQL. For an overview of MySQL, see the MySQL web site.
In this tutorial, you will learn how to:
You will expand upon the Django Hello World sample by utilizing a MySQL database, hosted in an Azure VM, to find an interesting replacement for World. The replacement will in turn be determined via a MySQL-backed Django counter app. As was the case for the Hello World sample, this Django application will again be hosted in an Azure virtual machine.
The project files for this tutorial will be stored in C:\django\helloworld and the completed application will look similar to:
To complete this tutorial, you need an Azure account. You can activate your MSDN subscriber benefits or sign up for a free trial.
Follow the instructions given here to create an Azure virtual machine of the Windows Server 2008 R2 distribution.
Open up a TCP port for MySQL transactions on the virtual machine:
Add another endpoint with NAME = web, PROTOCOL = TCP, PUBLIC PORT = 80, PRIVATE PORT = 80. This redirects external Internet requests to the port Django runs on, namely 80.
Use Windows Remote Desktop to remotely log into the newly created Azure virtual machine.
Open up TCP port 80 on the virtual machine:
Install the latest version of MySQL Community Server for Windows on the virtual machine:
Note: we recommend installing your DB on a different data partition than the OS.
After installing MySQL, click the Windows Start menu and run the freshly installed MySQL 5.5 Command Line Client. Issue the following commands:
CREATE DATABASE world;
USE world;
SOURCE C:\Users\Administrator\Desktop\world.sql
CREATE USER 'testazureuser'@'%' IDENTIFIED BY 'testazure';
CREATE DATABASE djangoazure;
GRANT ALL ON djangoazure.* TO 'testazureuser'@'%';
GRANT ALL ON world.* TO 'testazureuser'@'%';
SELECT name from country LIMIT 1;
You should now see a response similar to the following:
Note: you merely need to install the Django product from WebPI to get this tutorial working. You do not need Python Tools for Visual Studio or even the Azure Python SDK installed for our purposes.
Follow the instructions given in the Django Hello World tutorial to create a trivial "Hello World" web application in Django.
Open C:\django\helloworld\helloworld\settings.py in your favorite text editor. Modify the DATABASES global dictionary to read:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'djangoazure',
'USER': 'testazureuser',
'PASSWORD': 'testazure',
'HOST': '127.0.0.1',
'PORT': '3306',
},
'world': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'world',
'USER': 'testazureuser',
'PASSWORD': 'testazure',
'HOST': '127.0.0.1',
'PORT': '3306',
}
}
As you can see, we've just given Django instructions on where to find our MySQL database.
Note: you must change the HOST key to match your Azure (MySQL) VM's permanent IP address. At this point, HOST should be set to whatever the ipconfig Windows command reports it as being.
After you've modified HOST to match the MySQL VM's IP address, please save this file and close it.
Now that we've referenced our djangoazure database, let's do something useful with it! To this end, we'll create a model for a trivial counter app. To instruct Django to create this, run the following commands:
cd C:\django\helloworld
C:\Python27\python.exe manage.py startapp counter
If Django doesn't report any output from the final command above, it succeeded.
Append the following text to C:\django\helloworld\counter\models.py:
class Counter(models.Model):
count = models.IntegerField()
def __unicode__(self):
return u'%s' % (self.count)
All we've done here is defined a subclass of Django's Model class named Counter with a single integer field, count. This trivial counter model will end up recording the number of hits to our Django application.
Next we make Django aware of Counter's existence:
From a command prompt, please run:
cd C:\django\helloworld
C:\Python27\python manage.py sql counter
C:\Python27\python manage.py syncdb
These commands store the Counter model in the live Django database, and result in output similar to the following:
C:\django\helloworld> C:\Python27\python manage.py sql counter
BEGIN;
CREATE TABLE `counter_counter` (
`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
`count` integer NOT NULL
)
;
COMMIT;
C:\django\helloworld> C:\Python27\python
Creating table counter_counter
You just installed Django's auth system, which means you don't have any superusers defined.
Would you like to create one now? (yes/no): no
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)
Replace the contents of C:\django\helloworld\helloworld\views.py. The new implementation of the hello function below uses our Counter model in conjunction with a separate sample database we previously installed, world, to generate a suitable replacement for the "World" string:
from django.http import HttpResponse
import django.db
from counter.models import Counter
def getCountry(intId):
#Connect to the MySQL sample database 'world'
cur = django.db.connections['world'].cursor()
#Execute a trivial SQL query which returns the name of
#all countries contained in 'world'
cur.execute("SELECT name from country")
tmp = cur.fetchall()
#Clean-up after ourselves
cur.close()
if intId >= len(tmp):
return "countries exhausted"
return tmp[intId][0]
def hello(request):
if len(Counter.objects.all())==0:
#when the database corresponding to 'helloworld.counter' is
#initially empty...
c = Counter(count=0)
else:
c = Counter.objects.all()[0]
c.count += 1
c.save()
world = getCountry(int(c.count))
return HttpResponse("<html><body>Hello <em>" + world + "</em></body></html>")
Note: The following shows how to run Django in a test environment. To run it in production, follow the "Setting up IIS with FastCGI" section in the "Django Hello World tutorial". Using the Windows Firewall Client to open port 80 to Internet traffic on the Windows Server 2K8 R2 virtual machine is not necessary with FastCGI.
Switch back to a Windows PowerShell window, and type the following commands to deploy your Django web site publically:
PS C:\django\helloworld> $ipPort =
PS C:\django\helloworld> $ipPort = [string]$ipPort.AddressList[1]
PS C:\django\helloworld> $ipPort += ":80"
PS C:\django\helloworld> C:\Python27\python.exe .\manage.py runserver $ipPort
The runserver parameter instructs Django to run our helloworld web site on TCP port 80. The results of this command should be similar to:
PS C:\django\helloworld> C:\Python27\python.exe .\manage.py runserver $ipPort
Validating models...
0 errors found
Django version 1.4, using settings 'helloworld.settings'
Development server is running at
Quit the server with CTRL-BREAK.
From your local web browser, open (where yourVmName is whatever name you used in the virtual machine creation step). You should see "Hello ... !" displayed as shown in the screenshot below. This indicates that Django is running in the virtual machine and is working correctly.
Refresh the web browser a few times and you should see the message change from "Hello <country abc>" to "Hello <some other country>"..
|
http://azure.microsoft.com/en-us/documentation/articles/virtual-machines-python-use-mysql-django/
|
CC-MAIN-2014-15
|
refinedweb
| 1,203
| 57.67
|
I'm new to the topic shell extensions and I'm looking for resources about namespace extensions. I would like to write a namespace extension which supports SFTP with all options to browse like FTP in the explorer.
I read the examples 1, 2 of zengxi from codeproject, but they don't compile right and seems to be old. I think that there were also many changes like the folder selection in the address bar.
Can somebody provide me some resources in the right direction or some working examples?
UPDATE:
It is important that the source is free. This is a non-profit project.
At the moment I found a good source on the MSDN called Explorer Data Provider Sample. This is up to date and provides some aliases
Explorer Data Provider
Shell Data Source
shell data source
For Drag&Drop, this series of articles are a great point to start. After I understood that the files must have the flag can copy, can move, etc. I had almost the solution. The magic was to add one line in
GetAttributesOf:
*rgfInOut |= SFGAO_CANCOPY|SFGAO_CANMOVE;
Also I had to publish the
IDataObject in
GetUIObjectOf like this:
if(riid == IID_IDataObject) { PWSTR pszName; hr = _GetName(apidl[0], &pszName); hr = SHCreateDataObject(m_pidl, cidl, apidl, new CFileDataObject(pszName), riid, ppv); } else if(riid == IID_IDropTarget) { // TODO publish return E_NOINTERFACE; }
That's all.
By the way what is the best practice for allocating
CFileDataObject here?
|
https://codedump.io/share/er7eUN5ww7Qw/1/writing-namespace-extensions-with-windows-7-integration
|
CC-MAIN-2017-04
|
refinedweb
| 237
| 62.48
|
WiFi question
On the WiPy 2.0 when does the wireless interface come up?
I know I can disable both the wireless network and network server using the following code in my boot.py (before re-configuring them as required) but I was wondering if the default wireless access point and network server are active before the boot.py script is executed.
import network server = network.Server() server.deinit() wlan = network.WLAN() wlan.deinit()
Thanks,
As you need to connect using wireless to modify 'boot.py' in the first place this makes disabling the wireless interface by default an 'interesting' challenge to a new user!
Hopefully the wireless, bluetooth, etc are only started (if not already active) after 'boot.py' is executed.
@mike632t
i suppose that all features like wifi, blootooth, lora, ... should be disabled at start
maybe this can be achived by e.g. file existence on the flash.
like boot.config
if it does not exist - then all go same as is now
but if it exists then it should be parsed
but question remain open @daniel @bucknall can you point here something?
|
https://forum.pycom.io/topic/1006/wifi-question
|
CC-MAIN-2021-31
|
refinedweb
| 185
| 68.26
|
Library Interfaces and Headers
- shared memory facility
#include <sys/shm.h>
The <sys/shm.h> header defines the following symbolic constants:
attach read-only (else read-write)
round attach address to SHMLBA
The <sys/shm.h> header defines the following symbolic value:
segment low boundary address multiple
The following data types are defined through typedef:
Unsigned integer used for the number of current attaches that must be able to store values at least as large as a type unsigned short.
The shmid_ds structure>. See types.h(3HEAD).
In addition, all of the symbols from <sys/ipc.h> are defined when this header is included.
See attributes(5) for descriptions of the following attributes:
shmctl(2), shmget(2), shmop(2), ipc.h(3HEAD), types.h(3HEAD), attributes(5), standards(5)
|
http://docs.oracle.com/cd/E18752_01/html/816-5173/shm.h-3head.html
|
CC-MAIN-2015-27
|
refinedweb
| 129
| 50.94
|
Home > c#, Visual Studio 2005 > ReSharper 3.0 and Namespaces?
ReSharper 3.0 and Namespaces?
May 7, 2007
I’ve been using b423 of ReSharper 3.0 for a while now (the EAP program is great! thank you JetBrains!) and, today, noticed that in Orcas, my namespaces have issues.
Odd; it seems to be something to ignore for now; but I’m curious what framework standard or such it’s verifying my file structure against. Yes, it’s true, the code files are all in the same structure (all 5 of them)… I can ignore it, but I’d prefer to understand what it’s drawing from and why.
Advertisements
Categories: c#, Visual Studio 2005
It matches namespace to code file location, i.e. project/folder structure. If you have default project namespace as “USD259” and file in question is not in the “Authentication” subfolder, it will issue a warning. You can switch it off in the options, or make your projhect/folder/file structure match namespaces.
Ahh, okay, that makes sense, but does that relate to a specific CLS specification or just a note of good housekeeping on JetBrains’ part?
It has nothing to do with specification, but it is widely adopted practice. Also, VS creates new code files with namespace generated using the same rule. This just keeps things cleaner.
Note, that with ReSharper you can exclude some folders from namespace path by opening folder properties and changing “Namespace Provider” setting. Useful, when you have something like “source” folder, or some leaf folders which just sort things up and shoudn’t participate in namespace structure.
|
https://tiredblogger.wordpress.com/2007/05/07/resharper-30-and-namespaces/
|
CC-MAIN-2018-05
|
refinedweb
| 267
| 65.62
|
Java inherited bit manipulation from C. As a programmer you might not use it often, but still, it's quite important. Java integers are of 32 bits (4 bytes) and are signed. This means that left most bit (Most Significant Bit / MSB) works as the sign identifier. If it's 1, the number is negative (and positive if it's 0). Let's go in detail on the binary form of numbers:
Binary Representation of Numbers
Integer 1 in binary form = 00000000000000000000000000000001 or 1
Integer -1 in binary form =11111111111111111111111111111111
In Java, you can get the binary representation of any number by calling toBinaryString() method of Integer class (Integer.toBinaryString(1)). The binary representation of -1 might be confusing if you are not aware of how negative numbers gets stored. Negative numbers get stored as two's complement which can be achieved by adding 1 to the NOT of the unsigned number i.e. ~number +1
Another way to look at it is, the weight of the MSB or leftmost bit is negative. So when this bit is 1, the number becomes negative. The binary form of -1 can be represented as:
-2^31*1+ 2^30*1 + 2^29*1 + 2^28*1+ .... ......+ 2^1*1+2^0*1
Note that, the highest weighted component is negative (-2^31*1). This will result in the overall number being negative. We can cross check it by assuming a 4-bit number system.
1111 = -2^3*1 + 2^2*1 + 2^1*1 + 2^0*1
= -8 +4 + 2 +1
= -1
Using two's complement technique, -1 = ~1 +1
-1 = ~1+1
= ~0001 + 1
= 1110 + 1
= 1111
So either way, you will get the same representation of a negative number.
Bitwise Operators
We have used NOT binary operator above, now it's time to go over Java binary operators in detail.
Flips or reverses all bits. Thus, every 1 becomes 0 and every 0 becomes 1. Also known as one's complement operator. It's a urinary operator so takes only one argument.
~101 produces 010
| (OR)
Produces one in output if at least one of the bit is 1 and produces 0 if both bits are 0.
101 | 10 produces 111
& (AND)
Produces 1 in output if both input bits are 1, otherwise, it results in 0.
101 & 10 produces 000
^ (EXCLUSIVE OR / XOR)
Produces 1 in the output if either of the bit is 1 (not both), otherwise 0
101 ^ 10 produces 111
2 ^ 10 produces 8 ( equivalent to 10 ^ 1010 )
Important Note
- Difference between bitwise operators (&, |) with logical operators && and ||. Bit operators take integers and results in other integers but logical operators take booleans and return a boolean result.
- Only NOT (~) is urinary, others are binary operators.
- Binary operators (i.e. | , & and ^) can be combined with the = sign like &=, |= and ^=
Shift Operators
Now let's go to the Java's powerful shift operators.
<< (Left Shift Operator)
Used for shifting bits of a number on left side (i.e. 8 << 1 or 00001000 << 1). The value to the right of the operator indicates how many positions to shift the bits. Bits that fall off on the left side are lost and empty bits on the right side are filled up with 0.
Note, the value can change sign depending on the state of first bit.
>> (Signed Right Shift Operator)
Used for shifting bits of a number on the right side ( 8 >> 1). The value to the right of the operator indicates how many positions to shift the bits.
- When the sign is positive (leftmost bit is 0), empty bits on left side fills up with 0. So it retains the sign.
- When the sign is negative (leftmost bit is 1), it performs sign extension. Fills up the empty bits on the left side with 1s.
>>> (Unsigned Right Shift Operator)
Regardless of the sign, zeros are inserted to the left side or higher order bits.
Let's take a simple example to illustrate above operators
Let's take a simple example to illustrate above operators
public class BinaryOperators { public static void main(String[] args) { int i = 17; System.out.println(" i :" + Integer.toBinaryString(i)); System.out.println(" ~i : " + Integer.toBinaryString(~i)); System.out.println(" -1 : " + Integer.toBinaryString(-1)); System.out.println(" -1 & i : " + Integer.toBinaryString(-1 & i)); System.out.println(" -1 ^ i : " + Integer.toBinaryString(-1 & i)); System.out.println(" i >> 2 : " + Integer.toBinaryString(i >> 2)); System.out.println(" i >>> 2 : " + Integer.toBinaryString(i >>> 2)); System.out.println(" i << 2 : " + Integer.toBinaryString(i << 2)); System.out.println(" -1 >> 2 : " + Integer.toBinaryString(-1 >> 2)); System.out.println(" -1 >>> 2 : " + Integer.toBinaryString(-1 >>> 2)); System.out.println(" -i >>>= 2 : " + Integer.toBinaryString(i >>>= 2)); } }
Important Observations:
- Multiplication and Division:
int i = 5;
i <<= 2 ; //value of i becomes 20 i.e. 5*2*2
i = 10;
i >>=2; // value of i becomes 2 i.e. 10/(2*2) = 2
i = -4
i >>=2 ; // value of i becomes -1
If you & a bit with 1; you will get the same bit.
- Finding bit at a position:
i.e. 0 & 1 = 0 ; 1&1 = 1
This can be used to get the bit value in a number at the given position.
5 & 1 = 1 // 1001 & 1
5 & 10 = 0 // 1001 & 10; second last bit is 0 so the output is 0----
that's it for now...do post your feedback about this post.
|
http://geekrai.blogspot.com/2014/03/bit-manipulation-in-java.html
|
CC-MAIN-2019-04
|
refinedweb
| 897
| 58.99
|
Nevertheless colleagues to do when developing using mapped collections in Hibernate.
Below are the 5 things to consider when working with Hibernate mapped collections :
Lets consider the following classic “Library – Visit” example :
The following Library class has a collection of Visit instances:
package eg; import java.util.Set; public class Library { private long id; private Set visits; public long getId() { return id; } private void setId(long id) { this.id=id; } private Set getVisits() { return visits; } private void setVisits(Set visits) { this.visits=visits; } .... .... }
Following is the Visit class:
package eg; import java.util.Set; public class Visit { private long id; private String personName; public long getId() { return id; } private void setId(long id) { this.id=id; } private String getPersonName() { return personName; } private void setPersonName(String personName) { this.personName=personName; } .... .... }
Assuming that a library has multiple unique visits and that every visit correlates with a distinct library, a unidirectional one-to-many association like the one shown below can be used:
<hibernate-mapping> <class name="Library"> <id name="id"> <generator class="sequence"/> </id> <set name="visits"> <key column="library_id" not- <one-to-many </set> </class> <class name="Visit"> <id name="id"> <generator class="sequence"/> </id> <property name="personName"/> </class> </hibernate-mapping>
I will also provide an example of Table definitions for the schema described above :
create table library (id bigint not null primary key ) create table visit(id bigint not null primary key, personName varchar(255), library_id bigint not null) alter table visit add constraint visitfk0 (library_id) references library
So what’s wrong with this picture?
Potential performance bottlenecks will arise when you will try to add to the mapped collection. As you can see the collection is implemented as a Set. Sets guarantee uniqueness among their contained elements. So how Hibernate will know that a new item is unique so as to add it to the Set? Well do not be surprised; adding to the Set requires loading all available items from the database. Hibernate compares each and every one of them with the new one just to guarantee uniqueness. Moreover the above is standard behavior that we cannot bypass even if we know, because of business rules, that the new item is unique!
Using a List implementation for our mapped collection will not solve the performance bottleneck problem when adding items to it either. Although Lists do not guarantee uniqueness they do guarantee item order. So to maintain the correct item order in our mapped List, Hibernate has to pull the entire collection even if we are adding to the end of the list.
To my opinion, its a long way just to add one new Visit to the Library don’t you agree?
Additionally, the above example works well in development where we only have a few number of visits. In production environments where each library may have millions of visits, just imagine the performance penalty when you try to add one more!
To overcome the above performance problems we could map the collection as a Bag, which is just a regular collection with no ordering or uniqueness guarantees, but before doing so just consider my last point below.
When you remove/add an object from/to a collection, the version number of the collection owner is incremented. Thus there is a high risk of artificial optimistic locking exceptions on the Library object when simultaneous Visit creations occur. We characterize the optimistic locking exceptions as “artificial” because they happen on the collection owner object (Library) which we do not feel we are editing (but we are!) when we are adding/removing an item from the Visits collection.
Let me pinpoint that the same rules apply for a many-to-many association type.
So what’s the solution?
The solution is simple, remove the mapped collection from the owner (Library) object, and perform insertions and deletions for the Visit items “manually”. The proposed solution affects usage in the following ways :
- To add a Visit to a Library we must create a new Visit item, associate it with a Library item and persist it in the database explicitly.
- To remove a Visit from a Library we must search the “visit” table, find the exact record we need and delete it.
- With the proposed solution, no cascading is supported. To delete a Library you need to delete (disassociate) all its Visit records first.
To keep things clean and ordered you can restore a “visits” pseudo – collection back to the Library object by implementing a helper method that will query the database and return all Visit objects associated with the specific Library. Furthermore you can implement a couple of helper methods that will perform the actual insertion and deletion of visit records, at the Visit item.
Below we provide updated versions of the Library class, the Visit class and the Hibernate mapping so as to comply to our proposed solution :
First the updated Library class :
package eg; import java.util.Set; public class Library { private long id; public long getId() { return id; } private void setId(long id) { this.id=id; } public Set getVisits() { // TODO : return select * from visit where visit.library_id=this.id } .... .... }
As you can see, we have removed the mapped collection and introduced the method “getVisits()” that should be used to return all the Visit items for the specific Library instance (the TODO comment is in pseudo-code).
Following is the updated Visit class:
package eg; import java.util.Set; public class Visit { private long id; private String personName; private long library_id; public long getId() { return id; } private void setId(long id) { this.id=id; } private String getPersonName() { return personName; } private void setPersonName(String personName) { this.personName=personName; } private long getLibrary_id() { return library_id; } private void setLibrary_id(long library_id) { this. library_id =library_id; } .... .... }
As you can see we have added the “library_id” field to the Visit object so as to be able to correlate it with a Library item.
Last is the updated Hibernate mapping :
<hibernate-mapping> <class name="Library"> <id name="id"> <generator class="sequence"/> </id> </class> <class name="Visit"> <id name="id"> <generator class="sequence"/> </id> <property name="personName"/> <property name="library_id"/> </class> </hibernate-mapping>
So, never use mapped collections in Hibernate?
Well, to be honest, No. You need to examine each case so as to decide what to do. The standard approach is fine if the collections are reasonable small – both sides in the case of a many to many association scheme. Additionally the collections will contain proxies, so they are smaller than real instances until initialized.
Happy Coding! Don’t forget to share!
Justin
P.S.
After a relatively long debate about this article on TheServerSide, one or our readers Eb Bras provided a useful list of Hibernate “tips and tricks”, lets see what he has to say :
Here are a few of my Hibernate tips and tricks that I documented a long the way:
inverse=”true”
Use this as much as possible in a one-to-many parent-child association (to another entity or value-type that is used as an entity).
This property is set on the collection tag like “set” and mean that the many-to-one owns the association and is responsible for all db inserts/updates/deletes. It makes the association part of the child.
It will save an db update for the foreign key as it will occur directly when inserting the child.
Especially when using “set” as mapping type, it can gains performance as the child don’t need to be added to the parent collection which can save the loading of the complete collection. That is: due to the nature of a set-mapping, the whole collection must always be loaded when adding a new child as that’s the only way hibernate can guarantee that the new entry isn’t a duplicate which is a feature of the JRE Set interface.
In case it concerns a component collection (= collection containing only pure value types), inverse=true is ignored and makes no sense as Hibernate has full control of the objects and will choose the best way to perform his crud actions.
If it concern detached DTO objects (not containing any hibernate objects), hibernate will delete all value-type child’s and then insert them as it doesn’t know which object is new or existent because it was completely detached. Hibernate treats it as it is a new collection.
lazy Set.getChilds() is evil
Be careful using getChilds() that returns a Set and will lazy load all child’s.
Don’t use this when you want to add or remove just a child as it will first
always implement equals/hashcode
Make sure to always implement the equals/hashcode for every object that is managed by Hibernate, even if it doesn’t seem important. This counts also for Value type objects.
If the object doesn’t contain properties that are candidates for the equals/hashcode, use a surrogate key, that consists of a UUID for example.
Hibernate uses the equals/hashcode to find out if an object is already present in the db. If it concerns an existing object but Hibernate thinks that it’s a new object because the equals/hashcode isn’t implemented correctly, Hibernate will perform an insert and possible a delete of the old value.
Especially for value types in Set’s is important and must be tested as it saves db traffic.
The idea: you are giving Hibernate more knowledge such it can use it to optimize his actions.
use of version
Always use the version property with an entity or a value type that is used as an entity.
This results in less db traffic as Hibernate uses this information to discover if it concerns a new or existing object. If this property isn’t present, it will have to hit the db to find out if it concerns a new or existing object.
eager fetching
Not-lazy collections (child’s) are by default loaded through an extra select query that is just performed just after the parent is loaded from the db.
The child’s can be loaded in the same query as loading the parent by enabling eager fetching which is done by setting the attribute “fetch=join” on the collection mapping tag. If enabled, the child’s are loaded through a left outer join.
Test if this improves the performance. In case many join’s occur or if it concerns a table with many columns the performance will get worse instead of better.
use surrogate key in value type child object
Hibernate will construct the primary key in a value-type child of a parent-child relation that consists of all not-null columns. This can lead to strange primary key combinations, especially when a date column is involved. A date column shouldn’t be part of a primary key as it’s millisecond part will result to primary key’s that are almost never the same. This results in strange and probably poor performance db indexes.
To improve this we use a surrogate key in all child value-type objects, that is the only not-null property. Hibernate will then construct a primary key that consists of the foreign key and surrogate key, which is logic and performs well.
Note that the surrogate key is only used for database optimization and it’s not required to be used in the equals/hashcode which should consists of business logic if possible.
-
- Cajo, the easiest way to accomplish distributed computing in Java
Can we update a table using hibernate on the basis id if we have id of Big Integer type.
Example are given below.
SessionFactory sesfac=Utility.getSessionFactory();
Session ses=sesfac.openSession();
Transaction tx=ses.beginTransaction();
CustomerAccount c=(CustomerAccount)ses.get(CustomerAccount.class, id);
c.setAvailableBalance(customerAccount.getAvailableBalance());
c.setBrokerageAmt(customerAccount.getBrokerageAmt());
c.setCurrentValue(customerAccount.getCurrentValue());
c.setInvestmentAmt(customerAccount.getInvestmentAmt());
ses.update(c);
tx.commit();
ses.close();
One thing here for remember that id is of Big Integer type.
The standard approach is fine if the collections are reasonable small – both sides in the case of a many to many association scheme.
This is not a strict suggestion. First, how many is considered as small. Another thing is even if you think the collection is small now, but what if future? who can be sure that these data will not increase drastically?
|
https://www.javacodegeeks.com/2011/02/hibernate-mapped-collections.html
|
CC-MAIN-2018-39
|
refinedweb
| 2,052
| 50.87
|
For many software developers, Apple’s iPhone prints money. For other developers, it’s a vexing mess. As you waltz into the depths of Objective C, Cocoa, and the host of iPhone software development tools, it can be difficult to find sufficient official documentation and near impossible to find examples of many techniques and libraries.
Fortunately, a good number of hackers have created excellent open source projects to correct the shortfall. This column points out a few helpful iPhone coding aids that call Github home.
Getting Started
If you’re just getting started with iPhone development, check out the free iPhone coding class offered by the prestigious Stanford University. The class lectures are available on iTunes—search for“CS193P”—or click the iTunes link from the class’s home page at). The instruction is valuable and teaches the ins and outs of developing for the iPhone, but each class’s assignment is where the real learning takes place.
If you get stuck on any particular assignment, you can find solutions on Github. The most complete set lives at, but there are also solutions available in, and.
Paging Dr. Nic, Paging Dc. Nic
Dr. Nic Williams or &ldquoDr. Nic&rdquo, well-known in the Ruby world, has created a few useful tools for iPhone developers. The first of these, rbiphonetest, lets you write iPhone unit tests in Ruby, saving you from the horrors of STAssertTrue and its ilk.
STAssertTrue
rbiphonetest uses RubyCocoa to bridge between Ruby and Objective-C. So to test a Downloader class in the WebDownloader bundle, run rbiphonetest in the project directory, and write some code like this:
Downloader
WebDownloader
rbiphonetest
require 'WebDownloader.bundle’
OSX::ns_import :Downloader
class TestDownloader < Test::Unit::TestCase
def test_downloads_a_file
# Your test code here...
end
end
That’s much cleaner!
If you’re interested in finding out more about testing your iPhone app with Ruby, watch Dr. Nic’s video tutorial on the matter at and checkout the code from.
If you’re writing a lot of Objective-C and find yourself annoyed by some of XCode’s quirks (such as how it handles documents and windows), you can skip XCode and use a real editor, such as TextMate. Dr. Nic has also published a TextMate bundle for editing Objective-C with excellent snippets and syntax highlighting. You can grab the bundle at.
Getting Resourceful
Cocoa’s networking libraries are fantastic when compared with many of the other available options for C and C-like languages (Boost Sockets are icky!). So when someone takes those great libraries and then puts some really nice abstractions on top of them, you know you’re looking at a recipe for pleasantness.
The guys over at Y|Factorial have created a clone of Rails’ RESTful remote object framework ActiveResource for Objective-C called ObjectiveResource. This library lets you easily talk to RESTful web services.
For example, if you want your iPhone application to work with a remote resource for a blog post., you could do something like the following:
@interface BlogPost : NSObject {
NSString *title;
NSString *body;
}
@property (nonatomic , retain) NSString *title;
@property (nonatomic , retain) NSString *body;
@end
#import “ObjectiveResourceConfig.h”
[ObjectiveResourceConfig setSite:@""];
NSArray *posts = [BlogPost findAllRemote];
After the last line, the posts variable has an array of BlogPost objects populated with data fetched from your remote REST web service. That’s a bit easier than pulling those objects from the server, parsing the XML or JSON, and feeding that data into an Objective-C object by hand.
BlogPost
The ObjectiveResource developers provide an example Rails application as the back-end, but you can easily build your remote web services in any language. Check out the code at and the companion site at.
The Y|Factorial guys also offer some other interesting libraries that have been extracted from ObjectiveResource, such as ObjectiveSupport (), which provides a number of utility classes and methods (mostly for serialization), and ObjectiveSync (), an abstraction of “the various synchronization policies used when linking a remote iPhone app to a supporting backend web service.”
A Potpourri of Good Code
If you’re just searching for some little snippets or good examples of Objective-C code, there are many “potpourri” repositories around Github. Here are a few that I find useful:
SFHFActivityIndicatingCell
TableViews
UIDevice
In this post, I’ve only pointed out a very small part of the great iPhone and Objective-C resources out there on Github. I plan on covering even more of these resources in the future, so if you’ve found something useful, feel free to point it out to me via Github at jeremymcanally or on Twitter at @jm.
jeremymcanally
The following github member has assignment 3 for cs193p Iphone development. The hello polly app at URL
I have also been doing the assignments and they are available on my github page. I hope to have Presence 1 done>
|
http://www.linux-mag.com/id/7368/
|
crawl-003
|
refinedweb
| 806
| 51.99
|
This sponsored post features a product relevant to our readers while meeting our editorial guidelines for being objective and educational.
As developers, we want the applications we build to be resilient when it comes to failure, but how do you achieve this goal? If you believe the hype, micro-services and a clever communication protocol are the answer to all your problems, or maybe automatic DNS failover. While that kind of stuff has its place and makes for an interesting conference presentation, the somewhat less glamorous truth is that making a robust application begins with your code. But, even well designed and well tested applications are often lacking a vital component of resilient code - exception handling.
This content was commissioned by Engine Yard and was written and/or edited by the Tuts+ team. Our aim with sponsored content is to publish relevant and objective tutorials, case studies, and inspirational interviews that offer genuine educational value to our readers and enable us to fund the creation of more useful content.
I never fail to be amazed by just how under-used exception handling tends to be even within mature codebases. Let's look at an example.
What Can Possibly Go Wrong?
Say we have a Rails app, and one of the things we can do using this app is fetch a list of the latest tweets for a user, given their handle. Our
TweetsController might look like this:
class TweetsController < ApplicationController def show person = Person.find_or_create_by(handle: params[:handle]) if person.persisted? @tweets = person.fetch_tweets else flash[:error] = "Unable to create person with handle: #{person.handle}" end end end
And the
Person model that we used might be similar to the following:
class Person < ActiveRecord::Base def fetch_tweets client = Twitter::REST::Client.new do |config| config.consumer_key = configatron.twitter.consumer_key config.consumer_secret = configatron.twitter.consumer_secret config.access_token = configatron.twitter.access_token config.access_token_secret = configatron.twitter.access_token_secret end client.user_timeline(handle).map{|tweet| tweet.text} end end
This code seems perfectly reasonable, there are dozens of apps that have code just like this sitting in production, but let's look a little more closely.
find_or_create_byis a Rails method, it's not a 'bang' method, so it shouldn't throw exceptions, but if we look at the documentation we can see that due to the way this method works, it can raise an
ActiveRecord::RecordNotUniqueerror. This won't happen often, but if our application has a decent amount of traffic it's occurring more likely than you might expect (I've seen it happen many times).
- While we're on the subject, any library you use can throw unexpected errors due to bugs within the library itself and Rails is no exception. Depending on our level of paranoia we might expect our
find_or_create_byto throw any kind of unexpected error at any time (a healthy level of paranoia is a good thing when it comes to building robust software). If we have no global way of handling unexpected errors (we'll discuss this below), we might want to handle these individually.
- Then there is
person.fetch_tweetswhich instantiates a Twitter client and tries to fetch some tweets. This will be a network call and is prone to all sorts of failure. We may want to read the documentation to figure out what the possible errors we might expect are, but we know that errors are not only possible here, but quite likely (for example, the Twitter API might be down, a person with that handle might not exist etc.). Not putting some exception handling logic around network calls is asking for trouble.
Our tiny amount of code has some serious issues, let's try and make it better.
The Right Amount of Exception Handling
We'll wrap our
find_or_create_by and push it down into the
Person model:
class Person < ActiveRecord::Base class << self def find_or_create_by_handle(handle) begin Person.find_or_create_by(handle: handle) rescue ActiveRecord::RecordNotUnique Rails.logger.warn { "Encountered a non-fatal RecordNotUnique error for: #{handle}" } retry rescue => e Rails.logger.error { "Encountered an error when trying to find or create Person for: #{handle}, #{e.message} #{e.backtrace.join("\n")}" } nil end end end end
We've handled the
ActiveRecord::RecordNotUnique according to the documentation and now we know for a fact that we'll either get a
Person object or
nil if something goes wrong. This code is now solid, but what about fetching our tweets:
class Person < ActiveRecord::Base def fetch_tweets client.user_timeline(handle).map{|tweet| tweet.text} rescue => e Rails.logger.error { "Error while fetching tweets for: #{handle}, #{e.message} #{e.backtrace.join("\n")}" } nil end private def client @client ||= Twitter::REST::Client.new do |config| config.consumer_key = configatron.twitter.consumer_key config.consumer_secret = configatron.twitter.consumer_secret config.access_token = configatron.twitter.access_token config.access_token_secret = configatron.twitter.access_token_secret end end end
We push instantiating the Twitter client down into its own private method and since we didn't know what could go wrong when we fetch the tweets, we rescue everything.
You may have heard somewhere that you should always catch specific errors. This is a laudable goal, but people often misinterpret it as, "if I can't catch something specific, I won't catch anything". In reality, if you can't catch something specific you should catch everything! This way at least you have an opportunity to do something even if it's only to log and re-raise the error.
An Aside on OO Design
In order to make our code more robust, we were forced to refactor and now our code is arguably better than it was before. You can use your desire for more resilient code to inform your design decisions.
An Aside on Testing
Every time you add some exception handling logic to a method, it's also an extra path through that method and it needs to be tested. It's vital you test the exceptional path, perhaps more so than testing the happy path. If something goes wrong on the happy path you now have the extra insurance of the
rescue block to prevent your app from falling over. However, any logic inside the rescue block itself has no such insurance. Test your exceptional path well, so that silly things like mistyping a variable name inside the
rescue block don't cause your application to blow up (this has happened to me so many times - seriously, just test your
rescue blocks).
What to Do With the Errors We Catch
I've seen this kind of code countless times through the years:
begin widgetron.create rescue # don't need to do anything end
We rescue an exception and don't do anything with it. This is almost always a bad idea. When you're debugging a production issue six months from now, trying to figure our why your 'widgetron' isn't showing up in the database, you won't remember that innocent comment and hours of frustration will follow.
Don't swallow exceptions! At the very least you should log any exception that you catch, for example:
begin foo.bar rescue => e Rails.logger.error { "#{e.message} #{e.backtrace.join("\n")}" } end
This way we can trawl the logs and we'll have the cause and stack trace of the error to look at.
Better yet, you may use an error monitoring service, such as Rollbar which is pretty nice. There are many advantages to this:
- Your error messages aren't interspersed with other log messages
- You will get stats on how often the same error has happened (so you can figure out if it's a serious issue or not)
- You can send extra information along with the error to help you diagnose the problem
- You can get notifications (via email, pagerduty etc.) when errors occur in your app
- You can track deploys to see when particular errors were introduced or fixed
- etc.
begin foo.bar rescue => e Rails.logger.error { "#{e.message} #{e.backtrace.join("\n")}" } Rollbar.report_exception(e) end
You can, of course, both log and use a monitoring service as above.
If your
rescue block is the last thing in a method, I recommend having an explicit return:
def my_method begin foo.bar rescue => e Rails.logger.error { "#{e.message} #{e.backtrace.join("\n")}" } Rollbar.report_exception(e) nil end end
You may not always want to return
nil, sometimes you might be better off with a null object or whatever else makes sense in the context of your application. Consistently using explicit return values will save everyone a lot of confusion.
You can also re-raise the same error or raise a different one inside your
rescue block. One pattern that I often find useful is to wrap the existing exception in a new one and raise that one so as not to lose the original stack trace (I even wrote a gem for this since Ruby doesn't provide this functionality out of the box). Later on in the article when we talk about external services, I will show you why this can be useful.
Handling Errors Globally
Rails lets you specify how to handle requests for resources of a certain format (HTML, XML, JSON) by using
respond_to and
respond_with. I rarely see apps that correctly use this functionality, after all if you don't use a
respond_to block everything works fine and Rails renders your template correctly. We hit our tweets controller via
/tweets/yukihiro_matz and get an HTML page full of Matzs' latest tweets. What people often forget is that it's very easy to try and request a different format of the same resource e.g.
/tweets/yukihiro_matz.json. At this point Rails will valiantly try to return a JSON representation of Matzs' tweets, but it won't go well since the view for it doesn't exist. An
ActionView::MissingTemplate error will get raised and our app blows up in a spectacular fashion. And JSON is a legitimate format, in a high traffic application you're just as likely to get a request for
/tweets/yukihiro_matz.foobar. Tuts+ gets these kinds of requests all the time (likely from bots trying to be clever).
The lesson is this, if you're not planning to return a legitimate response for a particular format, restrict your controllers from trying to fulfill requests for those formats. In the case of our
TweetsController:
class TweetsController < ApplicationController respond_to :html def show ... respond_to do |format| format.html end end end
Now when we get requests for spurious formats we'll get a more relevant
ActionController::UnknownFormat error. Our controllers feel somewhat tighter which is a great thing when it comes to making them more robust.
Handling Errors the Rails Way
The problem we have now, is that despite our semantically pleasing error, our application is still blowing up in our users' face. This is where global exception handling comes in. Sometimes our application will produce errors that we want to respond to consistently, no matter where they come from (like our
ActionController::UnknownFormat). There are also errors that can get raised by the framework before any of our code comes into play. A perfect example of this is
ActionController::RoutingError. When someone requests a URL that doesn't exist, like
/tweets2/yukihiro_matz, there is nowhere for us to hook in to rescue this error, using traditional exception handling. This is where Rails'
exceptions_app comes in.
You can configure a Rack app in
application.rb to be called when an error that we haven't handled is produced (like our
ActionController::RoutingError or
ActionController::UnknownFormat). The way you will normally see this used is to configure your routes app as the
exceptions_app, then define the various routes for the errors you want to handle and route them to a special errors controller that you create. So our
application.rb would look like this:
... config.exceptions_app = self.routes ...
Our
routes.rb will then contain the following:
... match '/404' => 'errors#not_found', via: :all match '/406' => 'errors#not_acceptable', via: :all match '/500' => 'errors#internal_server_error', via: :all ...
In this case our
ActionController::RoutingError would be picked up by the
404 route and the
ActionController::UnknownFormat will be picked up by the
406 route. There are many possible errors that can crop up. But as long as you handle the common ones (
404,
500,
422 etc.) to start with, you can add others if and when they happen.
Within our errors controller we can now render the relevant templates for each kind of error along with our layout (if it's not a 500) to maintain the branding. We can also log the errors and send them to our monitoring service, although most monitoring services will hook in to this process automatically so you don't have to send the errors yourself. Now when our application blows up it does so gently, with the right status code depending on the error and a page where we can give the user some idea regarding what happened and what they can do (contact support) - an infinitely better experience. More importantly, our app will seem (and will actually be) much more solid.
Multiple Errors of the Same Type in a Controller
In any Rails controller we can define specific errors to be handled globally within that controller (no matter which action they get produced in) - we do this via rescue_from. The question is when to use
rescue_from? I usually find that a good pattern is to use it for errors that can occur in multiple actions (for example, the same error in more than one action). If an error will only be produced by one action, handle it via the traditional
begin...rescue...end mechanism, but if we're likely to get the same error in multiple places and we want to handle it the same way - it's a good candidate for a
rescue_from. Let's say our
TweetsController also has a
create action:
class TweetsController < ApplicationController respond_to :html def show ... respond_to do |format| format.html end end def create ... end end
Let's also say that both of these actions can encounter a
TwitterError and if they do we want to tell the user that something is wrong with Twitter. This is where
rescue_from can be really handy:
class TweetsController < ApplicationController respond_to :html rescue_from TwitterError, with: twitter_error private def twitter_error render :twitter_error end end
Now we don't need to worry about handling this in our actions and they will look much cleaner and we can/should - of course - log our error and/or notify our error monitoring service within the
twitter_error method. If you use
rescue_from correctly it can not only help you make your application more robust, but can also make your controller code cleaner. This will make it easier to maintain and test your code making your application that little bit more resilient yet again.
Using External Services in Your Application
It's difficult to write a significant application these days without using a number of external services/APIs. In the case of our
TweetsController, Twitter came into play via a Ruby gem that wraps the Twitter API. Ideally we would make all our external API calls asynchronously, but we're not covering asynchronous processing in this article and there are plenty of applications out there that make at least some API/network calls in-process.
Making network calls is an extremely error prone task and good exception handling is a must. You can get authentication errors, configuration problems, and connectivity errors. The library you use can produce any number of code errors and then there is a matter of slow connections. I am glossing over this point, but it's oh so crucial since you can't deal with slow connections via exception handling. You need to appropriately configure timeouts in your network library, or if you're using an API wrapper make sure it provides hooks to configure timeouts. There is no worse experience for a user than having to sit there waiting without your application giving any indication of what's happening. Just about everyone forgets to configure timeouts appropriately (I know I have), so take heed.
If you're using an external service in multiple places within your application (multiple models for example), you expose large parts of your application to the full landscape of errors that can be produced. This is not a good situation. What we want to do is limit our exposure and one way we can do this is putting all access to our external services behind a facade, rescuing all errors there and re-raising one semantically appropriate error (raise that
TwitterError that we talked about if any errors occur when we try to hit the Twitter API). We can then easily use techniques like
rescue_from to deal with these errors and we don't expose large parts of our application to an unknown number of errors from external sources.
An even better idea might be to make your facade an error free API. Return all successful responses as is and return nils or null objects when you rescue any sort of error (we do still need to log/notify ourselves of the errors via some of the methods we discussed above). This way we don't need to mix different types of control flow (exception control flow vs if...else) which may gain us significantly cleaner code. For example, let's wrap our Twitter API access in a
TwitterClient object:
class TwitterClient attr_reader :client def initialize @client = Twitter::REST::Client.new do |config| config.consumer_key = configatron.twitter.consumer_key config.consumer_secret = configatron.twitter.consumer_secret config.access_token = configatron.twitter.access_token config.access_token_secret = configatron.twitter.access_token_secret end end def latest_tweets(handle) client.user_timeline(handle).map{|tweet| tweet.text} rescue => e Rails.logger.error { "#{e.message} #{e.backtrace.join("\n")}" } nil end end
We can now do this:
TwitterClient.new.latest_tweets('yukihiro_matz'), anywhere in our code and we know that it will never produce an error, or rather it will never propagate the error beyond
TwitterClient. We've isolated an external system to make sure that glitches in that system won't bring down our main application.
But What if I Have Excellent Test Coverage?
If you do have well-tested code, I commend you on your diligence, it will take you a long way towards having a more robust application. But a good test suite can often provide a false sense of security. Good tests can help you refactor with confidence and protect you against regression. But, you can only write tests for things you expect to happen. Bugs are, by their very nature, unexpected. To use our tweets example, until we choose to write a test for our
fetch_tweets method where
client.user_timeline(handle) raises an error thereby forcing us to wrap a
rescue block around the code, all our tests will have been green and our code would have remained failure-prone.
Writing tests, doesn't absolve us of the responsibility of casting a critical eye over our code to figure out how this code can potentially break. On the other hand, doing this kind of evaluation can definitely help us write better, more complete test suites.
Conclusion
Resilient systems don't spring forth fully formed from a weekend hack session. Making an application robust, is an ongoing process. You discover bugs, fix them, and write tests to make sure they don't come back. When your application goes down due to an external system failure, you isolate that system to make sure the failure can't snowball again. Exception handling is your best friend when it comes to doing this. Even the most failure-prone application can be turned into a robust one if you apply good exception handling practices consistently, over time.
Of course, exception handling is not the only tool in your arsenal when it comes to making applications more resilient. In subsequent articles we will talk about asynchronous processing, how and when to apply it and what it can do in terms of making your application fault tolerant. We will also look at some deployment and infrastructure tips that can have a significant impact without breaking the bank in terms of both money and time - stay tuned.
Envato Tuts+ tutorials are translated into other languages by our community members—you can be involved too!Translate this post
|
https://code.tutsplus.com/articles/writing-robust-web-applications-the-lost-art-of-exception-handling--net-36395
|
CC-MAIN-2018-47
|
refinedweb
| 3,378
| 52.09
|
Bugzilla – Bug 63
#ident is not recognized by C frontend
Last modified: 2003-12-10 16:41:22
You need to
before you can comment on or make changes to this bug.
Gcc 2.96 has no problem with #ident directive in the file.
Haven't checked if GCC 3.4 itself has deprecated this directive though...
I'm not familiar with #ident, can you please provide a testcase? Have you tried
#pragma ident?
-Chris
Here's a testcase:
----
#ident "foo"
----
$ llvmgcc -S test.c
test.c:-77: internal compiler error: Segmentation fault
Please submit a full bug report,
with preprocessed source if appropriate.
See <URL:> for instructions.
That is pretty catastrophic. I'll look into it.
-Chris
Ok, the bug has been fixed in the mainline C front-end. Here's a patch:
$ diff -u c-lex.c-orig c-lex.c
--- c-lex.c-orig 2003-10-28 19:19:07.000000000 -0600
+++ c-lex.c 2003-10-28 19:19:23.000000000 -0600
@@ -41,6 +41,7 @@
#include "tm_p.h"
#include "splay-tree.h"
#include "debug.h"
+#include "llvm-out.h"
/* The current line map. */
static const struct line_map *map;
@@ -179,6 +180,8 @@
unsigned int line ATTRIBUTE_UNUSED,
const cpp_string *str ATTRIBUTE_UNUSED)
{
+ if (EMIT_LLVM) return;
+
#ifdef ASM_OUTPUT_IDENT
if (! flag_no_ident)
{
If you're not interested in rebuilding the C frontend, you can pass '-fno-ident'
on the llvmgcc command line to work around this problem. Thanks for the great
bug report!
-Chris
For the record, this is tested as: test/Regression/CFrontend/2003-10-28-ident.c
-Chris
*** Bug 173 has been marked as a duplicate of this bug. ***
|
http://llvm.org/bugs/show_bug.cgi%3Fid=63
|
crawl-002
|
refinedweb
| 271
| 79.97
|
How to trigger change detection in Angular?
I perform add, update and delete operations on the grid but I can’t able to refresh the grid without refreshing the page. How Can I dothis?
Answers (1)Add Answer
Using detect changes() in a component will immediately run change detection in that component and its children. This method is helpful when we refresh the gird after performing any operation on it. It will automatically refresh the grid without refreshing the page.
First import ChangeDetectorRef to component where we want to use it.
import { ChangeDetectorRef } from ‘@angular/core’;
Now inject it.
constuctor(private changeDetactor : ChangeDetectorRef )
{
}
After that use it in method where you perform manipulation operations. Use detectChanges method to do this.
this.changeDetactor.detectChanges()
|
https://www.thecodehubs.com/question/how-to-trigger-change-detection-in-angular/
|
CC-MAIN-2022-21
|
refinedweb
| 123
| 51.14
|
org.apache.commons.pipeline.Stage; 21 22 /** 23 * This class is used to store a collection of information about a particular 24 * validation failure. 25 * 26 */ 27 public class ValidationFailure { 28 /** 29 * Enumeration of possible causes of validation failure 30 */ 31 public enum Type { 32 /** 33 * Indicates that a stage appears to be unable to consume the output of the previous stage 34 */ 35 STAGE_CONNECT, 36 /** 37 * Indicates that a branch could not consume the output (type mismatch) of pipeline 38 * stages feeding the branch. 39 */ 40 BRANCH_CONNECT, 41 /** 42 * Indicates that a branch to consume the branch output of a stage could not be found. 43 */ 44 BRANCH_NOT_FOUND, 45 /** 46 * Other validation error - see detail message. 47 */ 48 OTHER 49 }; 50 51 private Type type; 52 private String message; 53 private Stage upstream; 54 private Stage downstream; 55 56 /** 57 * Creates a new instance of ValidationError 58 * @param type The type of problem encountered 59 * @param message A message with more detailed information about the problem 60 * @param upstream A reference to the upstream stage 61 * @param downstream A reference to a downstream stage 62 */ 63 public ValidationFailure(Type type, String message, Stage upstream, Stage downstream) { 64 this.type = type; 65 this.message = message; 66 this.upstream = upstream; 67 this.downstream = downstream; 68 } 69 70 /** 71 * Type identifying what sort of problem was encountered 72 * @return the type of problem encountered 73 */ 74 public Type getType() { 75 return this.type; 76 } 77 78 /** 79 * Returns the descriptive message about the error 80 * @return message describing the error 81 */ 82 public String getMessage() { 83 return this.message; 84 } 85 86 /** 87 * The stage upstream of the connection that could not be validated 88 * @return reference to the upstream Stage 89 */ 90 public Stage getUpstreamStage() { 91 return this.upstream; 92 } 93 94 /** 95 * The stage downstream of the connection that could not be validated 96 * @return reference to the downstream Stage 97 */ 98 public Stage getDownstreamStage() { 99 return this.downstream; 100 } 101 }
|
http://commons.apache.org/sandbox/pipeline/xref/org/apache/commons/pipeline/validation/ValidationFailure.html#0
|
crawl-003
|
refinedweb
| 331
| 55.07
|
Hi Everyone…
I’m following a railscast episode on how to implement an invitation
feature.
It’s going really well, but i’ve hit a minor snag that I cant get
over…
undefined method `generate_token’ for #Invitation:0x2563bf8
The invite form allows me to check for a user, and whether they
already have registered. If they have, the invitation is not sent, and
a flash message is printed.
If the email does not exist, the invite count (starts at 5) decrements
until you have none left.
When i click invite, i get the error above. It’s moaning about this
line: @invitation.sender = @user
i tied replacing @user with user, but still no use…
def create
@invitation = Invitation.new(params[:invitation])
@invitation.sender = @user
if @invitation.save
flash[:notice] = “Thanks - Invitation sent successfully.”
redirect_to hub_url
else
render :action => ‘new’
end
end
Any ideas why this wont decrement, and why this error is still
visible?
Many Thanks
|
https://www.ruby-forum.com/t/undefined-method-generate-token/183209
|
CC-MAIN-2022-40
|
refinedweb
| 156
| 56.86
|
ServerCheck: Building a Python CLI with Click
Keith Thompson
DevOps Training Architect II in Content.
ServerCheck: Building a Python CLI with Click
Introduction.
Connect to the Lab
Option 1: Connect with the Visual Studio (VS) Code Editor
- Open your terminal application, and run the following command:
ssh cloud_user@PUBLIC_IP
- Enter
yesat the prompt.
- Enter your
cloud_userpassword at the prompt.
- Run
exitto close the connection.
- Run the following command:
ssh-copy-id cloud_user@PUBLIC_IP
- Enter your password at the prompt.
- Open Visual Studio Code.
- In the search bar at the top, enter
cloud_user@PUBLIC_IP.
- Once you've connected, click the square Extensions icon in the left sidebar.
- Under Local - Installed, scroll down to Python and click Install on SSH.
- Click Reload to make the changes take effect.
Option 2: Connect with Your Local Machine
- Open your terminal application, and run the following command (remember to replace
PUBLIC_IPwith the public IP you were provided on the lab instructions page):
ssh cloud_user@PUBLIC_IP
- Type
yesat the prompt.
- Enter your
cloud_userpassword at the prompt.
Set Up a Project and Virtualenv Using Pipenv
- Make a new directory named
servercheckand an internal subdirectory named
servercheckto hold the Python package.
mkdir -p servercheck/servercheck
- Change to the
serverchecksubdirectory.
cd servercheck
- In the
serverchecksubdirectory, create a new file named
__init__.py.
touch servercheck/__init__.py
- Install Pipenv.
pip3.7 install --user -U pipenv
- Create a virtualenv, and install
click:
pipenv --python python3.7 install click
- Activate the virtualenv.
pipenv shell
Define the CLI Function
Create the command line function in a module named
cliwithin the
servercheckpackage.
import click @click.command() def cli(): pass if __name__ == "__main__": cli()
- Run the CLI.
python servercheck/cli.py --help
Add the required decorators from the Click library.
import click @click.command() @click.option("--filename", "-f", default=None) @click.option("--server", "-s", default=None, multiple=True) def cli(filename, server): if not filename and not server: raise click.UsageError("must provide a JSON file or servers") if __name__ == "__main__": cli()
- You should receive an error, which is expected since we haven't passed any arguments yet.
Create a set to hold on to all of the server/IP combinations, and add anything from the JSON file if given and also the values passed using the
--serveror
-sflags.
import click import json import sys @click.command() @click.option("--filename", "-f", default=None) @click.option("--server", "-s", default=None, multiple=True) def cli(filename, server): if not filename and not server: raise click.UsageError("must provide a JSON file or servers") # Create a set to prevent duplicate server/port combinations servers = set() # If --filename or -f option is used then attempt to read # the file and add all values to the `servers` set. if filename: try: with open(filename) as f: json_servers = json.load(f) for s in json_servers: servers.add(s) except: print("Error: Unable to open or read JSON file") sys.exit(1) # If --server or -s option are used then add those values # to the set. if server: for s in server: servers.add(s) print(servers) if __name__ == "__main__": cli()
- Create an example JSON file to parse.
touch example.json
- Open the file with your preferred editor (e.g., vim).
vim example.json
- Add the following content to the file:
[ "JSONIP:PORT", "JSONIP:PORT", "JSONIP2:PORT2" ]
- Test the function by passing it the example JSON file in combination with the
--serveroption.
python servercheck/cli.py -f example.json --server "IP1:PORT1" -s "IP2:Port1"
Create
setup.py with
console_scripts for
servercheck
- Pull down the starter
setup.py.
curl -O
Edit the file to add
clickas a dependency in the
REQUIREDlist, create the
console_script, and remove the
UploadCommand.
#!/usr/bin/env python # -*- coding: utf-8 -*- import io import os import sys from shutil import rmtree from setuptools import find_packages, setup, Command # Package meta-data.=3.7.0" VERSION = "0.1.0" # What packages are required for this module to be executed? REQUIRED = ["click"] # What packages are optional? EXTRAS = { # 'fancy feature': ['django'], } #. about = {} if not VERSION: project_slug = NAME.lower().replace("-", "_").replace(" ", "_") with open(os.path.join(here, project_slug, "__version__.py")) as f: exec(f.read(), about) else: about["__version__"] = VERSION # Where the magic happens: setup( name=NAME, version=about["__version__"], description=DESCRIPTION, long_description=long_description, long_description_content_type="text/markdown", author=AUTHOR, author_email=EMAIL, python_requires=REQUIRES_PYTHON, url=URL, packages=find_packages(exclude=["tests", "*.tests", "*.tests.*", "tests.*"]), # If your package is a single module, use this instead of 'packages': # py_modules=['mypackage'], entry_points={"console_scripts": ["servercheck=servercheck.cli:cli"]}, install_requires=REQUIRED, extras_require=EXTRAS, include_package_data=True, license="MIT", classifiers=[ # Trove classifiers # Full list: "License :: OSI Approved :: MIT License", "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", ], )
- Install the tool and make it editable.
pip install -e .
- Run the tool.
servercheck -s "SERVER:1000" -s "SERVER2:2000" -f example.json
Conclusion
Congratulations, you've successfully completed this hands-on lab!
|
https://linuxacademy.com/hands-on-lab/570c4e02-f3fb-468b-a1e6-e60938ee4b70/
|
CC-MAIN-2020-05
|
refinedweb
| 814
| 51.34
|
In this exercise, we explore the use of WIN32_product and classes provided by the Windows installer provider.
Open Notepad or your favorite script editor.
At the top of your script, declare a variable called $strComputer. Assign the WMI shortcut dot character (.) to indicate you want to connect to WMI on your local machine. This line of code is shown here:
$strComputer = "."
On the next line, declare the variable $wmiNS, which will be used to hold the WMI namespace for your query. Assign the string "Root\cimv2" to the variable. This line of code is shown here:
$wmiNS = "root\cimv2"
On the next line, you will use the variable $wmiQuery to hold your WMI query. This query will select everything from the WIN32_ ...
No credit card required
|
https://www.safaribooksonline.com/library/view/microsoft-windows-powershelltm/9780735623958/ch06s08.html
|
CC-MAIN-2018-30
|
refinedweb
| 126
| 85.39
|
Deblank
June 28, 2019
There are at least 37.19 bajillion ways to do this, probably a few more. I’ll give six:
awk '!/^[:space:]*$/'
grep -v "^[ \t]*$"
sed '/^[ \t]*$/d'
awk '!/^[ \t]*$/'
grep -vE "^\s*$"
awk '!/^\s*$/'
Those aren’t all the same, because of varying definitions of white space. At fourteen characters, I’m not sure I can write a smaller program. If this task came up in real life, I would probably think first of the sed solution, because editing text as it passes through its filter is what sed is designed to do.
You can run the program at.
Python 3:
As a pseudo-one-liner in Python, abusing list comprehension syntax:
import sys; [sys.stdout.write(line) for line in sys.stdin if line.strip()]
Rust version:
Playground:
gawk /\S/
There’s supposed to be two backslashes in front of the “S” in that gawk expression. Looks like the text-entry form here stripped one of them.
Here’s a solution with a vim command:
Intriguing problem, with a practical aspect to it! Here is my approach to it, using Julia:
function ContainsOnlyWhiteCharacters(text::AbstractString)
wc = [‘ ‘, ‘\t’, ‘\n’] # white characters
end
function process(fn::AbstractString)
f = open(fn)
lines = readlines(f)
close(f)
n = length(lines)
ind = BitArray(undef, n)
end
Cheers
An unimaginative, under-the-top Haskell version. The octal escapes in the printf produce a Unicode thin space.
#lang racket
(require 2htdp/image)
(let ((white (car (image->color-list (text " " 12 "black")))))
(for ([line (port->lines)])
(unless
(for/and ([pixel (image->color-list (text line 12 "black"))])
(equal? pixel white))
(displayln line))))
|
https://programmingpraxis.com/2019/06/28/deblank/2/
|
CC-MAIN-2021-21
|
refinedweb
| 269
| 67.35
|
Red Hat Bugzilla – Full Text Bug Listing
Created attachment 422218 [details]
Spec file for python-mock
Description of problem:
This is for info on a name space collision for Red Hat or Fedora folks. In my adventures to put together a test passing rpm build of BuildBot 0.8.0, I cherry picked a couple of commits for the MailNotifier and its unit tests from the buildbot's upstream master branch.
Those being:
5ff4d181d552f44b2c274a17a9a0b25d1915493f fix NameError by passing
properties into createEmail
e1cfc9d95d9df49e1dca449f3cf149862774f7f9 fix tests broken in 5ff4d181
The later commit pulls in an external dependency on Mock, a mocking and testing library from and available on PyPI at.
Now for the fun part, I packaged up mock for our internal package but also with the intention of getting it into Fedora or EPEL if possible. No probs here, one nicely packaged and installed python-mock rpm.
No probs until I try running BuildBot's unit tests with the installed python-mock rpm.
$ trial buildbot/test/unit/test_status_mail_MailNotifier.py
/usr/lib64/python2.6/site-packages/twisted/mail/smtp.py:10:
DeprecationWarning: the MimeWriter module is deprecated; use the email
package instead
import MimeWriter, tempfile, rfc822
buildbot.test.unit.test_status_mail_MailNotifier
TestMailNotifier
test_createEmail_message_with_patch_and_log_contains_unicode ...
[ERROR]
test_createEmail_message_without_patch_and_log_contains_unicode ...
[ERROR]
===============================================================================
[ERROR]:
buildbot.test.unit.test_status_mail_MailNotifier.TestMailNotifier.test_createEmail_message_with_patch_and_log_contains_unicode
Traceback (most recent call last):
File
"/home/gareth/WORK/git/buildbot/master/buildbot/test/unit/test_status_mail_MailNotifier.py",
line 40, in test_createEmail_message_with_patch_and_log_contains_unicode
build = self.make_build()
File
"/home/gareth/WORK/git/buildbot/master/buildbot/test/unit/test_status_mail_MailNotifier.py",
line 26, in make_build
b = mock.Mock()
exceptions.AttributeError: 'module' object has no attribute 'Mock'
===============================================================================
I even modified the test_status_mail_MailNotifier.py to use
"from mock import Mock", but still no joy.
[gareth@localhost] ~/WORK/git/test/buildbot/master
$ trial buildbot/test/unit/test_status_mail_MailNotifier.py
[ERROR]
===============================================================================
[ERROR]: buildbot/test/unit/test_status_mail_MailNotifier.py
Traceback (most recent call last):
File "/usr/lib64/python2.6/site-packages/twisted/trial/runner.py",
line 651, in loadByNames
things.append(self.findByName(name))
File "/usr/lib64/python2.6/site-packages/twisted/trial/runner.py",
line 460, in findByName
return filenameToModule(name)
File "/usr/lib64/python2.6/site-packages/twisted/trial/runner.py",
line 95, in filenameToModule
ret = reflect.namedAny(reflect.filenameToModuleName(fn))
File "/usr/lib64/python2.6/site-packages/twisted/python/reflect.py",
line 464, in namedAny
topLevelPackage = _importAndCheckStack(trialname)
File
"/home/gareth/WORK/git/test/buildbot/master/buildbot/test/unit/test_status_mail_MailNotifier.py",
line 2, in <module>
from mock import Mock
exceptions.ImportError: cannot import name Mock
-------------------------------------------------------------------------------
FAILED (errors=1)
But python-mock was installed !!!
rpm -ql python-mock
.
/usr/lib/python2.6/site-packages/mock.py
.
So to cut a long story short, the culprit is Fedora's "mock". In can also be argued that the python-mock is the culprit. Either way, we have a problem.
rpm -ql mock
.
/usr/lib/python2.6/site-packages/mock
/usr/lib/python2.6/site-packages/mock/__init__.py
.
I realized that building python-mock inside a mock chroot is not a problem but it is if both mock and python-mock are installed.
Version-Release number of selected component (if applicable):
mock-1.0.7-1.fc12.noarch
How reproducible:
Always.
Steps to Reproduce:
1. Install mock.py to python site-packages on system either manually or with python-mock rpm
2. In python interpreter, type
from mock import Mock
Actual results:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name Mock
Expected results:
Expect to be able to import the Python mocking and testing library correctly.
from mock import Mock
Additional info:
The python-mock rpm does not exist in Fedora or EPEL. Please find the spec file in attachement.
ummm
Doesn't Python permit more detailed namespace qualification, and so by a simple addition of qualification, this may be solved within buildbot, rather than mungeing with Fedora's mock ?
-- Russ herrold
import mock
doesn't accept much qualification. The problem is that the two packages are trying to install two modules with exactly the same name - similar to two packages installing, say, /usr/lib/libmock.so. One of them needs to be renamed or moved to somewhere else in the hierarchy, and then everything *using* that module will need to be patched to find it in the new location.
Since fedora-mock presumably has fewer dependents, it seems most appropriate to change that package.
(there is a slight twist here in that the packages do not actually install files with the same pathname; to the level of detail needed here, though, mock/__init__.py and mock.py mean the same thing to Python)
My initial query shows that the following packages depend on fedora-mock's python packages:
fedora-packager-0:0.4.2-1.fc13.noarch
puritan-0:0.4-5.fc12.noarch
revisor-mock-0:2.2-1.fc13.noarch
Of the 3 packages that are listed in Commment 3, only revisor-mock imports mock directly
in /usr/lib/python2.6/site-packages/revisor/modmock/__init__.py
from mock.backend import Root
fedora-packager and puritan both use the `mock` CLI.
have you talked to upstream about renaming their package? The mock application has been around for a lot longer than python-mock:;a=log
For Fedora, we'll need to rename one or the other of these packages. Since the mock application existed first, we'd normally lean towards letting that one keep the name. We like to get upstream buyin for someone to change rather than having to change something only locally in Fedora, though.
Note that if python-mock's upstream is unwilling to rename, you can try to contact the mock application upstream as well -- Some of them are CC'd on this bug already *ahem*. But others are in the recent git changelog.
Speaking as the mock upstream, I'm really not interested in renaming the Python world the important namespace is the PyPI namespace, for which my project is named "mock". As far as I can tell you're suggesting not just renaming the project but renaming the module.
The latest release (0.7.0b3 - a beta) has had over 5300 downloads since its release on 18th September (about 3 weeks) so it is pretty popular and there is a lot of downside to renaming it. I appreciate that the various Linux distros all have difficulty with naming. In Debian mock is packaged as python-mock.
re-assigning to rawhide to avoid the bugbot. Sadly I really do think we need to change the python module name for the mock package.
I'm the buildbot maintainer and just realized this issue while trying to upgrade the package. However:
(In reply to comment #5)
> For Fedora, we'll need to rename one or the other of these packages.
If I understand it correctly, we do not need to rename the "mock" project or RPM package, but just the mock module provided by it.
If true, it looks like a much easier (and less disruptive) change.
A few notes:
1. Regarding Buildbot, the mock dependency is only needed for the unit tests. So at the cost of temporarily disabling those tests, there's no great hazard in shipping newer versions of Buildbot.
2. Most of the comments above just talk about 'mock', and I'm not sure *which* mock was intended. That said, comment 3 indicates that only three projects use fedora-mock, and only one uses the 'mock' Python namespace itself. As Michael mentioned in comment 9, the fedora-mock package is committing a Python faux pas by using a top-level package name different from its distribution name -- it should be using 'fedora_mock' or something like that instead. Compare that to python-mock, which is widely used and imported in many locations by the applications that use it.
So it sounds like (a) fedora-mock is not playing nice in Python and (b) it'd be a lot easier to change the top-level Python package name that fedora-mock uses, rather than changing that of python-mock. (c) Presumably, with a name like fedora-mock, the package has no external upstream, so Fedora could make such a rename internally without affecting other distros.
I'm not sure what you're talking about with this "fedora_mock" thing.
There is a package in Fedora, named 'mock', written in python, that has all it's modules in <pythondir>/site-packages/mock and imports them via constructs like:
import mock.exceptions
This package has been around since 2005 (the initial commit from Seth Vidal).
I'm not sure I should weigh in here, but in the broader cross-platform Python development community Michael Foord's "mock" package is a well-known and useful module for writing test cases (and I highly recommend the "Testing In Python" upstream python SIG; see and ; hi Michael!)
However, within the RPM-using community, the "mock" project is a very useful tool, and well known tool, for provisioning clean environments for performing builds.
So with my "making Fedora a great Python development/deployment environment" hat on, IMHO "mock" within site-packages should go to Michael Foord's package, since that's what the broader Python community expects. It's only on the RPM-using platforms that "mock" has had a different meaning.
So can I request that the mock chroot-provisioning tool changes the module import name? (and have a look at since there are quite a few similarly-named modules, alas).
"mockbuild" perhaps?
I appreciate that this will be a pain.
"import mockbuild as mock" could be a way to ease the transition.
if the mock -> mockbuild namespace change is agreed upon, I could find some time to produce a patch
This package has changed ownership in the Fedora Package Database. Reassigning to the new owner of this component.
It would be a very satisfying resolution of this if Dave Malcolm's suggestion to rename the chroot-provisioning tool to "mockbuild" were accepted and Gianluca Sforna's offer to implement it were accepted.
That sounds like the best plan. I Jesse told me over IRC that he and Clark talked about it and it sounds reasonable. However, the work will need to be done on more than just the mock package. Some of the packages that depend mock are importing the mock module, not just calling /usr/bin/mock.
$ repoquery -q --whatrequires mock --alldeps
mock-0:1.1.9-1.fc14.noarch
fedora-packager-0:0.5.9.0-1.fc14.noarch
koji-builder-0:1.6.0-1.fc14.noarch
mock-rpmfusion-free-0:14.0-1.fc14.noarch
mock-rpmfusion-nonfree-0:14.0-1.fc14.noarch
plague-builder-0:0.4.5.7-9.20100505cvs.fc14.noarch
puritan-0:0.4-6.fc14.noarch
revisor-mock-0:2.2-2.fc14.noarch
rpmfusion-packager-0:0.4-1.fc12.noarch
Some of those may just be calling the /usr/bin/mock binary.
* fedpkg (not listed here -- the dependency needs to be added to our fedpkg package) does that.
* autoqa (not packaged for Fedora, just used by the QA SIG) does that as well.
I would suggest grepping for mock in the .py files for those packages and then checking that none of the occurrences of mock are an import.
This is also probably not a change that we'd be able to push to older Fedora (and possibly RHEL/EPEL) so we'll need to figure out how to deal with those separately. (Fedora, we can let expire on its own... RHEL will take some thought).
I'm currently working on the controlling tty issues and have a 1.1.10/1.0.17 release planned. Once that's out I'll accept patches for changing the directory of mock in site-packages to be mockbuild. Whoever does it will need to coordinate with the dependent packages listed above.
The Tahoe-LAFS project has a buildbot herd that includes a Fedora buildslave (operated by Ruben Kerkhof). That buildslave is currently red due to this issue, and will presumably go green as soon as Ruben deploys the fix to this issue onto his buildslave. So, if you want to confirm whether the fix works for Tahoe-LAFS's purposes, just watch this space:
Thanks!
I just finished checking the packages listed by repoquery:
NEEDSWORK:
* mock
* revisor-mock
OK, configuration files for mock
* mock-rpmfusion-free-0:15.0-1.fc14.noarch
* mock-rpmfusion-nonfree-0:15.0-1.fc14.noarch
OK, no apparent mock usage (maybe called through another executable?)
* rpmfusion-packager-0:0.4-1.fc12.noarch
* fedora-packager-0:0.5.9.2-1.fc14.noarch
OK, just calls the mock binary
* puritan
* plague-builder-0:0.4.5.7-9.20100505cvs.fc14.noarch
* koji-builder-0:1.6.0-1.fc14.noarch
A patch for Fedora's mock was submitted:
And here is the one for revisor:
Clark: ping?
This is a good point in the cycle to get this applied in time for Fedora 17. I can even apply the patch and push a new rpm package to rawhide if you are ready to deal with fallout of that. Another option is to prep a new upstream release now and push it into Fedora once F16 is final -- that way we'd have more releng people who can help to deal with problems that may arise.
If we do nothing, I fear that this will continue into the next release cycle... and the next.. and the[..] :-)
Pushing this with mock-1.1.13
mock-1.1.13-1.el6 has been submitted as an update for Fedora EPEL 6.
mock-1.0.20-1.el5 has been submitted as an update for Fedora EPEL 5.
mock-1.1.13-1.fc15 has been submitted as an update for Fedora 15.
mock-1.1.13-1.fc14 has been submitted as an update for Fedora 14.
Package mock-1.1.13-1.el6:
* should fix your issue,
* was pushed to the Fedora EPEL 6 testing repository,
* should be available at your local mirror within two days.
Update it with:
# su -c 'yum update --enablerepo=epel-testing mock-1.1.13-1.el6'
as soon as you are able to.
Please go to the following url:
then log in and leave karma (feedback).
Hooray! Ruben's Fedora buildslave for Tahoe-LAFS is green now!
>:~>
(In reply to comment #32)
> >:~>
Hmmm, is there a mockbuild directory in /usr/lib/python2.6/site-packages?
> Hmmm, is there a mockbuild directory in /usr/lib/python2.6/site-packages?
Nope:
localhost:~> rpm -V mock
S.5....T. c /etc/mock/site-defaults.cfg
zsh: exit 1 rpm -V mock
localhost:~> rpm -ql mock | grep site-packages
/usr/lib/python2.6/site-packages/mock
/usr/lib/python2.6/site-packages/mock/__init__.py
/usr/lib/python2.6/site-packages/mock/__init__.pyc
/usr/lib/python2.6/site-packages/mock/__init__.pyo
/usr/lib/python2.6/site-packages/mock/backend.py
/usr/lib/python2.6/site-packages/mock/backend.pyc
/usr/lib/python2.6/site-packages/mock/backend.pyo
...
I notice that this patch wasn't completely applied:
and that's where the module paths to be installed will be defined.
Created attachment 522368 [details]
patch to install into the proper location
Documentation on automake's pkgpython variable here:
I agree with gaillu's approach to this. Attaching a patch that applies his changes.
This gets the mock module installed into mockbuild correctly. I'm preparing a patch for a second problem with default plugin paths still looking in the python_sitelib/mock/ directory.
Created attachment 522369 [details]
Fix install path of mockbuild module and default path to module dir
Updated the previous patch instead -- it turns out that the old path was being substituted via the Makefile.am. Updated that section to substitute the new path instead.
Remember to run autoreconf -fi afterwards :-)
mock-1.1.14-1.fc14 has been submitted as an update for Fedora 14.
mock-1.0.21-1.el5 has been submitted as an update for Fedora EPEL 5.
mock-1.1.14-1.fc15 has been submitted as an update for Fedora 15.
mock-1.1.14-1.el6 has been submitted as an update for Fedora EPEL 6.
Package mock-1.1.14-1.el6:
* should fix your issue,
* was pushed to the Fedora EPEL 6 testing repository,
* should be available at your local mirror within two days.
Update it with:
# su -c 'yum update --enablerepo=epel-testing mock-1.1.14-1.el6'
as soon as you are able to.
Please go to the following url:
then log in and leave karma (feedback).
> mock-1.1.14-1.el6 has been submitted as an update for Fedora EPEL 6.
This one works as expected, thanks!
mock-1.1.14-1.fc15 has been pushed to the Fedora 15 stable repository. If problems still persist, please make note of it in this bug report.
mock-1.1.14-1.fc14 has been pushed to the Fedora 14 stable repository. If problems still persist, please make note of it in this bug report.
mock-1.1.15-1.fc15 has been submitted as an update for Fedora 15.
mock-1.1.15-1.el6 has been submitted as an update for Fedora EPEL 6.
mock-1.0.22-1.el5 has been submitted as an update for Fedora EPEL 5.
mock-1.1.15-1.fc14 has been submitted as an update for Fedora 14.
mock-1.1.15-1.fc15 has been pushed to the Fedora 15 stable repository. If problems still persist, please make note of it in this bug report.
mock-1.1.15-1.fc14 has been pushed to the Fedora 14 stable repository. If problems still persist, please make note of it in this bug report.
mock-1.0.22-1.el5 has been pushed to the Fedora EPEL 5 stable repository. If problems still persist, please make note of it in this bug report.
mock-1.1.15-1.el6 has been pushed to the Fedora EPEL 6 stable repository. If problems still persist, please make note of it in this bug report.
|
https://bugzilla.redhat.com/show_bug.cgi?format=multiple&id=601725
|
CC-MAIN-2017-30
|
refinedweb
| 3,020
| 56.96
|
This article is in the Product Showcase section for our sponsors at CodeProject. These articles are intended to provide you with information on products and services that we consider useful and of value to developers.
Previously we have written about profiling performance and profiling memory with ANTS Profiler. This time we’re going to present a short tip for using ANTS Profiler, explaining how ANTS Profiler lets you quickly reduce the number of objects that you are looking at.
A common problem with profiling the memory of a .NET application is that there are an awful lot of objects to look at. Searching through a large number of objects, just to find the ones that you are interested in, is both time consuming and frustrating. In ANTS Profiler you can quickly reduce the number of objects that you are looking at by a careful use of grouping, filtering and sorting.
Let us walk through the steps for one of my typical scenarios – comparing the differences between two snapshots.
Quite often I use the memory profiler to find out what new objects are created when I execute a certain action (e.g. click on a button). To do this, I take a snapshot of the memory before I perform the action, and then another snapshot after the action. The screenshot below shows "All objects" from the second snapshot.
To focus on new memory created I immediately filter using the Comparison column to only show "New" objects that have been created since the previous snapshot. This immediately reduces the number of objects displayed in the grid from thousands to hundreds.
My next step is usually to group the objects by their "Namespace". This allows me to focus on all the objects from a particular namespace. Shown below is a screenshot of the grouped results focusing on the ShapePainter namespace.
ShapePainter
I can now see immediately that the action that I performed resulted in the creation of 10 new rectangle shapes.
Expanding the System.Drawing namespace grouping reveals that I am creating a very large number of SolidBrush objects. I might want to take some more time to find out whether I really need to be creating so many new Solid Brushes!
System.Drawing
SolidBrush
Obviously you can choose to filter or group on any of the columns that are available in the "All objects" grid. It may well prove useful to filter out all the objects that do not have a source file so that you can focus on the objects created by your code, or group by allocation method to see which methods are creating the most objects.
Try it out for yourself – download a fully-functional,.
|
https://www.codeproject.com/articles/10174/ants-profiler-how-to-reduce-the-number-of-objects?fid=173352&df=90&mpp=10&noise=1&prof=true&sort=position&view=expanded&spc=none
|
CC-MAIN-2016-50
|
refinedweb
| 446
| 62.07
|
Overview
Atlassian SourceTree is a free Git and Mercurial client for Windows.
Atlassian SourceTree is a free Git and Mercurial client for Mac.
Play with Error-Monads in OCaml
PVEM actually stands for “Polymorphic Variants-based Error Monads.”
Usage
The basic idea of these modules is to manipulate:
type ('ok, 'error) result = [ | `Ok of 'ok | `Error of 'error ]
or combinations of that type (why polymorphic variants? see some implementation notes).
When you
open Pvem (or
include) in your source, you get
- the module
Resultwhich implements the interface
ERROR_MONADwith the above type,
- the functor
With_deferred:
DEFERRED→
DEFERRED_RESULTwhich builds “error-monads” out of
Lwt-like concurrency monads.
Since the monad(s) become pervasive; the
ERROR_MONAD module type defines 3 infix operators:
>>=(
ERROR_MONAD.bind): the “standard” bind operator.
>>|(
ERROR_MONAD.map): pass the value through a “pure” function.
>><(
ERROR_MONAD.destruct): “reopen” the error monad to be able to match on both the “Ok” and “Error” cases; then return inside the monad like with
bind.
Examples
Infix Operators
Here is a basic usage example for the 3 infix operators:
open Pvem open Result let fail_on_42 : int -> (int, string) Result.t = function 42 -> fail "42" | other -> return other let f_uses_bind_and_return: int -> (float, string) Result.t = fun x -> fail_on_42 x >>= fun not_42 -> return (2. *. float not_42) let f_uses_map: int -> (int * int, string) Result.t = fun x -> fail_on_42 x >>| (fun x -> (x, x)) let f_uses_destruct: int -> (float, string * string) Result.t = fun x -> fail_on_42 x >>< function | `Ok o -> return (float o) | `Error s -> fail ("did not convert to float", s)
Functor
To get an error monad on top of Lwt, simply
module Deferred_result = Pvem.With_deferred(Lwt)
With Jane Street's Async
Deferred.t:
open Core_kernel.Std open Async.Std module Deferred_result = Pvem.With_deferred(struct include Deferred let catch tri wiz = Async.Std.try_with tri >>= function | Ok o -> return o | Error e -> wiz e end)
|
https://bitbucket.org/smondet/pvem.git
|
CC-MAIN-2015-48
|
refinedweb
| 306
| 58.38
|
EuroPython 2017, part 1
(Needs editing after I get some time and sleep)
Day zero, Sunday
After a rather pleasant flight on Sunday morning, where out of 80 passengers, I sat next to the only other EuroPython visitor, I took a nicely airconditioned train from Bologna to Rimini. I really hoped that airco was everywhere, otherwise the 33C would seriously hamper my capability of even remembering what was said just five minutes ago.
My newfound acquaintance and me got some good Italian food inside us, cooled down for a few minutes at the beach, breathing in the sea air and explored Rimini centre for a bit, where the heat was slowly leaking out of the stones.
Day one, Monday
Moving on to Monday, I was thankfully doing just fine. The walk through the park (literally) to the venue was warm and lengthy but shady and beautiful, and the venue was well organised and cool, suiting my feeble brain.
Starting off with an enlightening keynote by Armin Ronacher, where we were reminded of the fact that files and other input still are not UTF-8 (even going beyond UTF-8 now we have emoticons, which are in an even higher byte space), making it hard to do string slicing and such. Also, don’t subclass dictionaries. Just don’t.
I moved on to a hands-on session with Django and Celery, as I wanted to see if there were some features I wasn’t aware of yet, or pointers to solutions to some minor issues we are having at Sanoma.
Coming away with some remarks about just using chains and groups, as things like chords can act weirdly in certain circumstances (like on RabbitMQ, which surprise surprise is what we use at home), I thought that maybe some small refactoring is in order.
Next up was a talk about how you can know that the mocks you created for a (third party) API are valid. Vuforia (an image matching service) was used as example.
requests-mock is of course a useful tool here, and the speaker made his mock into a Flask app, which translated requests-mock to something that could be used by their library.
The verifying part is done by running all the tests twice, once against the real service, and once against your mock. This checks if the responses are the same. By scheduling tests with for example Travis CI, you can then find out about (undocumented) changes to the third party service in a timely and targeted fashion (as the failing test points to the exact location), making it a lot more easy to fix your library.
Also, if you ship software, you really should ship it with a verified fake, so people can use that to test their own software; it adds a lot of value to your product.
After the lunch it was time to measure, don’t guess. A nice hands-on presentation of how to profile your code, so you can optimise where needed. Premature optimisation is the root of all evil, so knowing where to actually put your efforts is really useful.
A string of tools were introduced, apart from the excellent Jupyter notebook software to experiment with (really, if you don’t know it, or never used it,
pip install jupyter and
jupyter notebook it). Build into Python itself is timeit (
import timeit,
timeit.default_timer, don't use os_time or time_clock, as they will give different results depending on your OS platform).
snakeviz is a browser based graphical viewer of the output of Python's cProfile module, representing time spent in various parts of the code as concentric circles, making it easy to zoom into troublesome parts. It can be run standalone, or as a module:
python -m snakeviz,
python -m cProfile -o pi.stats simple_pi.py for example (example code), or just
snakeviz pi.stats. Be aware that tool measures itself too of course.
In jupyter, you can load such modules to experiment with interactively:
load profile_me.py <shift>-<enter>
%load_ext snakeviz
%snakeviz test()
Same with
timeit:
%timeit
%%timeit # multi-line version, where you can add more lines of code to test
%timeit? # to get help of course
The line profiler is another tool that gives information about what lines of code are troublesome:
pip install line_profiler
kernprof (-v)
- line-by-line profiling: -l
kernprof -v -l profile-me_use_line_profiler.py
- in jupyter:
load_ext line_profiler
For memory usage, Pympler can be used. It keeps track of changes in the size of data structures, so you can see where your code balloons, or even where memory is leaking:
from pympler import tracker
t = tracker.SummaryTracker()
t.print_diff()
big = list(range(10**6))
t.print_diff() # shows how big the datastructure we just created is (as it shows the difference with the previous measurement)
With the Python functools one can create decorators (like in ./measuring/memory_size_pympler.py: measure_memory in the example code linked above). This one creates a decorator the create a measurement of a function, storing it in a variable.
matplotlib is another great library to visualise data.
Finally, there is another memory profiler:
pip install memory_profiler,
%load_ext memory_profiler and then you can do something like:
import use_mem # an application
%mprun -f use_mem.use_mem use_mem.use_mem(numbers)
So, enough pointers to play with and explore from.
The conference seems well balanced and organised and the participants are generally really social, making for interesting chats over food.
It’s also refreshing to see the amount of female attendees. I really hope it’s a good sign for the future, as in my opinion we need more of their talent in our field of work.
Day two, Tuesday
Instead of walking, I decided to make use of the loaner bikes of the hotel, which was really an improvement.
Cooling down, the kickoff of the day was about data visualisation by Dutch visualiser Jan Willem Tulp. This was great to behold, seeing how he made big and complex datasets comprehensible and even beautiful, appealing to laymen too (his animated globe with number of trees was used in a nice demo from a news publication).
After enjoying the nice visuals and inspirational talk, I was curious how to use and write decorators to eliminate the need for some classes.
There is a nice talk about why you should stop writing classes:
Decorators are rather easy to use, not trivial to write, but also not that hard to do, and can be really helpful in making your code more clear.
Continuing with a smart use of metaclasses by using abstract base classes (ABCs). Those help with testing behaviour, not structure.
When trying to find out if some object is what you need, checking the type (isinstance() and such) is not really the intention, because some object or class can behave like a certain class, but is of course not exactly that implementation/type you are checking. A perfect solution would be something like:
if behaveslike(someobj, ListBehaviour):
Abstract base classes are categories (like labels/tags, but it’s just a promise to act in a certain way, no checks are done). Using them though, enables you to do the above comparison.
Python Collections has a lot of classes that represent interesting behaviours (go check them).
Some more notes:
- Python is based on delegation, which is good news; magic functions come into play.
- Virtual subclasses: ParentClass.register(ChildClass), with opposite relationship, where the ParentClass knows the ChildClass, but not the other way around like in regular subclassing. Useful for when you want to know all the subclasses of a certain class. Registering is a promise, no check done, so be careful.
- A metaclass can put things into the class that is linked to it.
- You can abstract base classes to build interfaces, but in the speaker’s opinion this is not the way to go. Can be useful though.
After that I attended a slightly confused talk about design patterns and why we don’t need them in Python. The idea was good, as design patterns were thought up in a time that programming languages were in a place where developers needed them to enforce certain restrictions, but then the speaker started showing where certain design patterns were still used or usable inside Python. All in all a good way to brush up on my old knowledge of them and seeing why I don’t program in Java anymore.
Some of the points and design patterns:
-.
His take-away was good though: know your tools well, get inspiration from other languages and communities, know the business domain of your project.
After lunch there was a subject that I am really curious about: “There should be one obvious way to bring python into production” by Sebastian Neubauer.
His slides are available from the talk page, which are a good set of guidelines.
It talked about the various stages inside the delivery pipeline. When a software product has to be shipped, it has to be built and packaged. Some requirements here are that it should be built once, used everywhere, the possibility to compile it for the target systems and that versions should be really unique, preferably signed. You should not have a version 1.0.2 without $fileX and one with $fileX (because you forgot to include it in the first build).
Nice to have: upload the build to an artifact repository.
A risk is that the build environment is misconfigured.
Testing should be automated, with near production-like and reproducible conditions, and minimal changes should be done for testing reasons. Nice to have are of course fast feedback and having the tests run after each commit on all branches (something that we are already doing in quite some projects in Sanoma).
A risk here is that the tests test the test env, not production (e.g., pytest pulls in $package that turns out to be missing when deploying to production).
After that, Staging/QA has to receive an automated deploy in a production-like environment, with nearly no changes for testing purposes. It has the risk of being an outdated, manually maintained setup, so be sure to take care of this stage.
Nice to haves for a staging environment are that it is a real clone of the production system and the possibility to run A/B tests on the system.
Production should have all kinds of restrictions, like no compiler, no internet, health monitoring and preferably have automated deploys, automated monitoring, self-healing and automatic rolling updates and roll-backs.
Because of the ecosystem of software, we frequently run into the dependency hell. We have multiple layers of package managers (from OS-level, to the Python world (
pip) and of course the JavaScript world).
Within the Python package management there’s still much confusion around setuptools, distutils, eggs and such. — Many outdated ‘best practices’ on StackOverflow etc — pyscaffold, versioneer (templates for packages)
Possible solution: Nix inside a container? Someone from the audience proposed using Flatpak or Snappy instead, which sound to me better candidates, seeing how mainstream Linux distro’s are already including support for them.
Energy started running low, so the interesting, but fast talk about Descriptors left me with some notes that I really should look into them a bit more.
After that, Django and GraphQL seemed like a nice break from the de-facto REST standard (not that I dislike DjangoRestFramework). This new API standard, created by Facebook, has one endpoint and uses queries instead of paths to retrieve data. This was not new for me, but I was curious to the current state of integration with Django. Turns out that using
graphene and
graphene-django gets you going quite nicely. Enable the app and then it's only adding some glue to be able to retrieve data from your models.
Authentication is handled, as is usage/viewing permission per field. Apparently there are still issues when also using DjangoRestFramework, but a pull request is in review.
Good to know that you should limit the nesting you can have, as queries can get rather deep otherwise. GitHub does something like that already.
Frontends that can be used in concert with your shiny GraphQL are Facebook’s Relay for React, and the really Open Source Apollo.
|
https://medium.com/sanoma-technology-blog/europython-2017-part-1-4067aabc5487
|
CC-MAIN-2017-47
|
refinedweb
| 2,040
| 59.43
|
Can you show me by using my code for an example?
Type: Posts; User: LooneyTunerIan
Can you show me by using my code for an example?
import java.util.Random;
import java.util.Scanner;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
...
Can you show me by using my code for an example?
I need to be sure so as I don't get all mixed up.
You can use my code to help you. :)
No, not like that.
I meant for the program to loop again after you win.
Like this:
YOU WIN!
The number was: #
It took you this many tries to get it right:
Ok, here's what I got.
import java.util.Random;
import java.util.Scanner;
/*
* To change this license header, choose License Headers in Project Properties.
Nevermind, I'm starting this over on another thread.
This is getting too confusing.
Can you show me?
Can you borrow my code?
Bold and Italicize some parts that cna be fixed?
It's GuessingGameByIanNeumann
Here:
java.lang.ExceptionInInitializerError
Caused by: java.lang.RuntimeException: Uncompilable source code - class GuessingGameByIanNeumann is public, should be declared in a file named...
Well, I'm lost.
I tried to run it and I got an error. :(
I looked at my code and... I don't know what went wrong. :(
Something went wrong with my code. :(
import java.util.Random;
import java.util.Scanner;
/*
* To change this template, choose Tools | Templates
Nah... this actually quite helped. :)
Thank you.
I will try it out.
--- Update ---
Sorry for double posting, but...
This is getting very confusing. :confused:
Please... can you show me how to do just that by using my code?
Not just show me the little parts?
Here's another helpful tip: I want to be able...
Hmm.. so what you're saying is... if I do it like this:
while (again = true)
{
int ctr, num1, num2, fib, maxTimes;
System.out.print("How many sequences do you want?:...
Yeah...
I heard of this, but...
How can I make it work for a YES/NO Loop?
If I choose yes, how will it do it again?
I'm very confused. :confused:
Thank you. :) I've already posted my first java-related thread. :) I may need some help with it thought.
I need help with my Fibonacci Sequence Code:
public class FibSeqByIanNeumann {
public static void main(String[] args) {
Scanner get = new Scanner(System.in);
Hi, guys. :)
My name is Ian.
I joined up because I may need help with some of my java programs. :(
|
http://www.javaprogrammingforums.com/search.php?s=af24fbc9d5d0a903ce1bea90a48d1365&searchid=1461423
|
CC-MAIN-2015-14
|
refinedweb
| 429
| 80.38
|
mr.bob templates for Odoo projects
Project description
bobtemplates.odoo is a set of mr.bob templates to use when developing Odoo addons.
It provides the following templates:
- addon: an addon skeletton, with optional OCA README and icon
- model: an Odoo model with accompanying form, tree, action, menu, demo data and ACL
- test: a test class
- wizard: a wizard with transient model, view and action
The following are candidates (pull requests welcome):
- controller
- widget
Install
pip install bobtemplates.odoo
Quickstart
CAUTION: it is recommanded to backup or vcs commit your current directory before running these commands, so you can easily see what has been generated and/or changed.
Create a new addon in the current directory:
mrbob bobtemplates.odoo:addon
Now go to the newly created addon directory and run this to add a new model, with associated views, demo data, and acl:
mrbob bobtemplates.odoo:model
Add a test class:
mrbob bobtemplates.odoo:test
Tip: read the mr.bob user guide. In particular it explains how to set default values to avoid retyping the same answers at each run (such as the copyright author).
Useful links
- pypi page:
- code repository:
- report issues at:
Credits
Author:
Inspired by.
Contributors:
Changes
1.3.0 (2018-11-23)
- [IMP] Some Odoo 11/12 support (default to 12)
- [IMP] Do not add utf-8 headers to python 3 files
- [IMP] Support python 3.6
1.2.1 (2018-09-18)
- [FIX] indentation in the wizard view
- [IMP] Test Template: allow to choose test class
- [FIX] prevent repeated imports in __init__.py
1.2.0 (2017-09-11)
- [CHG] The data tag in XML file is no longer required in version 9 and following
- [FIX] issue when adding imports to __init__.py
- [IMP] better button template in form views
1.1.2 (2017-04-07)
- updated pypi trove classifiers, no functional changer
1.1.1 (2017-01-14)
- [FIX] wizard: Return correct action type
- [IMP] do not add items (eg views) that already exists in manifest
1.1.0 (2016-10-28)
- [IMP] Odoo 10.0 support
1.0.1 (2016-09-09)
- [FIX] packaging error in 1.0.0 (removed icon.svg.oca)
1.0.0 (2016-09-01)
- [IMP] wizard: improve form view template
- [IMP] wizard: use ‘new’ target in wizard action
- [ADD] wizard: add action in More/Action menu
- [FIX] wizard: remove parenthesis in multi decorator that caused crash in Odoo 8.0
- [FIX] addon: for OCA addons, generate icon.png instead of icon.svg
- [IMP] wizard, model: use <odoo> instead of <openerp> for Odoo >= 9.0
1.0.0b3 (2016-06-25)
- [ADD] wizard template
- [IMP] model: auto-add view, demo data and acl in addon manifest
- [IMP] addon: put summary in description field if there is no README.rst
- [IMP] model: do not generate action view_type (which is mostly obsolete)
- [IMP] model: add domain and context in action
- [IMP] model: add example field when not inherited
- [IMP] model: add default group in form view
- [IMP] model: do not generate an empty view xml file
- [FIX] model: menu name is mandatory when creating menu with a record entry
1.0.0b2 (2016-06-17)
- [ADD] addon: add optional OCA mode (author, README.rst and icon.svg)
- [IMP] model: improve order of import in the model file
- [FIX] model: avoid to set ir.model.access data as non updatable record
1.0.0b1 (2016-06-16)
- add post render message inviting the user to add the generated xml files in __openerp__.py data section
- auto add model import to models/__init__.py
- many improvements and fixes to the model template (views, security, demo data, and more)
- addon template
- test template
- tests (with tox and travis)
1.0.0a2 (2016-06-15)
- fix broken namespace package distribution
1.0.0a1 (2016-06-15)
- first version, very rough template for an Odoo model with view
Project details
Release history Release notifications | RSS feed
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/bobtemplates.odoo/
|
CC-MAIN-2021-17
|
refinedweb
| 671
| 64.81
|
0
def my_startswith(s1, s2): if s1[0] == s2[0]: return True elif s1[0] != s2[0]: return False elif s2 == '': return True elif s1 == '' and s2 == '': return True
Iam having trouble with the third and fourth elif. Third elif: i need to say that if s1 is a string and s2 is an empty string -> true,
the fourth elif: i need to say that s1 and s2 are empty strings -> true. When I run it, it only reads the first if when i test for situations that belong to the third and fourth elif. Any help s appreciated, thank you.
|
https://www.daniweb.com/programming/software-development/threads/465682/i-am-trying-to-create-a-function-like-startswith
|
CC-MAIN-2016-50
|
refinedweb
| 101
| 85.83
|
Events are objects that are used for communication between threads. A thread waits for a signal while another thread outputs it. Basically, an event object manages an internal flag that can be set to
true with the
set() method and reset to
false with the
clear() method. The
wait() method blocks until the flag is
true.
To understand the thread synchronization through the event object, let's take a look again at the producer/consumer problem:
import time from threading import Thread, Event import random items = [] event = Event() class consumer(Thread): def __init__(self, items, event): Thread.__init__(self) self.items = items self.event = event def run(self): while True: time.sleep(2) self.event.wait() ...
No credit card required
|
https://www.oreilly.com/library/view/python-parallel-programming/9781785289583/ch02s10.html
|
CC-MAIN-2019-35
|
refinedweb
| 120
| 74.79
|
Problem compiling C++ for SCC: could not open source file "cstdio"ally Aug 10, 2011 9:00 AM
Hi
I'm trying to compile a large C++ application to run on the SCC cores.
I have sourced "crosscompile.sh", and have set my Makefile to use icpc instead of g++. When I type: which icpc, I get:
/opt/icc-8.1.038/bin/icpc
which I believe is correct.
However, compilation fails with this error:
main.cc(2): catastrophic error: could not open source file "cstdio"
#include <cstdio>
Doing "locate cstdio" gives me this:
/opt/i386-unknown-linux-gnu/include/c++/3.4.5/cstdio
/opt/icc-8.1.038/include/c++/cstdio
/usr/include/c++/4.4/cstdio
/usr/include/c++/4.4/tr1/cstdio
/usr/include/c++/4.4/tr1_impl/cstdio
My understanding is that, having source crosscompile, I should be interested in one of the first two "cstdio" options, not the other three.
Since I am running icpc, I figured the second one, /opt/icc-8.1.038/include/c++/cstdio, should be right. So I add:
-I/opt/icc-8.1.038/include/c++/cstdio
to my compile command.
My questions are:
1) is this the right thing to do?
2) why do I have to add this, when icpc was able to successfully pick up lots of other C++ headers?
1. Re: Problem compiling C++ for SCC: could not open source file "cstdio"wbrozas Aug 10, 2011 10:01 AM (in response to ally)
I saw in the documentation programs being compiled with these flags. This will probably not fix your current problem but may fix later ones.
icpc -DCOPPERRIDGE -static -mcpu=pentium -gcc-version=340
As for your current problem -I should be followed by a directory and you probably need -L as well for libraries
Try adding -I/opt/intel_cc_80/include -L/opt/intel_cc_80/lib
instead of -L you can also set your LD_LIBRARY_PATH, I don't know what the equivalent is for include but the compiler will search through the directories listed in your LD_LIBRARY_PATH, it may have found some files there. When you source that script it probably changes your LD_LIBRARY_PATH
2. Re: Problem compiling C++ for SCC: could not open source file "cstdio"tedk Aug 10, 2011 10:18 AM (in response to wbrozas)
Please don't use -DCOPPERRIDGE ... it's now -DSCC. Copperridge is a legacy name and the docs are behind rev.
Did you look at
3. Re: Problem compiling C++ for SCC: could not open source file "cstdio"ally Aug 12, 2011 8:18 AM (in response to tedk)
Thanks for the tips regarding those flags.
But in relation to the problem finding "cstdio", can anyone comment as to why this standard file isn't found by icpc, and confirm which is the correct version to direct it to?
Thanks
Ally
4. Re: Problem compiling C++ for SCC: could not open source file "cstdio"wbrozas Aug 12, 2011 11:17 AM (in response to ally)
When the binaries are created, you configure the compiler to search for include files in a specific path as well as library files. If you would like to search somewhere else (in this case you do) you can use the arguments -I and -L.
Use this command to see where gcc will search (This is how gcc was configured)
gcc -print-search-dirs
I do not know the equivalent for icpc, but I'm sure there is one
As for where icpc should be looking, it should be searching in /opt/intel_cc_80/include and /opt/intel_cc_80/lib
Those are the c and c++ header files that go with intel version 8 c and c++ compilers
The files in /usr/include are GNU c standard header files, which may or may not be compatible
#EDIT#
Sorry I did not realize my directories are different. When I said /opt/intel_cc_80 it should be /opt/icc-8.1.038
|
https://communities.intel.com/thread/24023
|
CC-MAIN-2017-30
|
refinedweb
| 654
| 68.81
|
Search Inbox Data Using Smart Tags in Word 2003
This content is no longer actively maintained. It is provided as is, for anyone who may still be using these technologies, with no warranties or claims of accuracy with regard to the most recent product version or service release.
Summary: Link your data points in Microsoft Office Word 2003 to Inbox data stored in Microsoft Exchange Server. Use smart tags in Word to create search queries executed against the Exchange message store. Search the message store programmatically to acquire results. Then, import search result data into the Word document. (17 printed pages)
John R. Durant, Microsoft Corporation
September 2004
Applies to: Microsoft Office Word 2003, Microsoft Exchange Server 2003, Microsoft Exchange Server 2000
Contents
Whether composing e-mail messages, letters, or other documents, no program can compare to the power of Microsoft Office Word 2003. You have access to powerful templates, styles, Research services, and so much more. Smart tags make the experience even better by allowing you take action based on the text you type in the Word document. For example, when you type a person's name, Word recognizes it as a person's name and allows you to quickly search for the name in your Outlook contacts and take action from there.
This works great for contacts. But, what about other types of content? Using Outlook, you can store tasks, contacts, appointments, notes, e-mails, posts, and so much more in the Exchange message store. A smart tag that marks up words in a document and connects them to these other content types in the message store is of similar value, but no such built-in smart tags exists. Fortunately, you can develop one fairly easily.
This smart tag has a recognizer that evaluates textual input in Word and determines whether a typed word matches a term in a pre-defined list of search terms. You create this term list and store the values in an XML file. The smart tag DLL reads this file when Word first loads the smart tag and caches the terms in memory. Figure 1 shows the contents of the XML file containing the term list.
When Word matches a typed word to one of the terms in the list, it assigns an attribute to the matched word, marking it up as a smart tag. You can see a recognized term in a Word document in Figure 2.
You can then activate the smart tag menu by causing the cursor to hover over the marked up word. The smart tag menu displays a custom item for searching the mailbox (Figure 3).
Clicking this item causes the smart tag to execute code that searches the Exchange message store for e-mail messages in your inbox whose subject line contains the search term. The smart tag displays the results in a Windows form with a DataGrid that lists mail items whose subject contains the search term (Figure 4).
In this case, the DataGrid shows only the fields for the e-mail subject and the sender's information. However, behind the scenes other e-mail fields (such as the body text) are retrieved though not displayed. By simply changing the properties of the grid, you can show these hidden fields. The article explains how this is accomplished later on.
The final feature of this example allows you to insert the main text of a selected e-mail message into the Word document. You do this by hovering over a row in the DataGrid and right-clicking the item. The code inserts the subject and body text of the e-mail message into the Word document just after the smart tag-enabled text (Figure 5).
Of course, you can also alter this functionality including changing the table format, which field contents the code inserts into the document, and where it puts the field contents.
The main function of recognition in smart tag code is to compare textual input with some condition and determine if the text is important. For example, you can compare against a hard-coded list (the most inflexible but speediest mechanism), a dynamic list, or a regular expression. The sample for this article uses an XML file (Figure 1) containing terms that the smart tag DLL loads at runtime. The DLL stores the loaded term list in memory and uses it to compare against textual input. Here is the code to load the XML file and store the term list in memory:
Public Sub SmartTagInitialize( _ ByVal ApplicationName As String) _ Implements SmartTags.ISmartTagRecognizer2. _ SmartTagInitialize Dim xmlDoc As New Xml.XmlTextReader("SearchTerms.xml") While xmlDoc.Read If xmlDoc.NodeType = Xml.XmlNodeType.Text Then ReDim Preserve termList(termCount) termList(termCount) = xmlDoc.Value() termCount = termCount + 1 End If End While End Sub
This code executes when the SmartTagInitialize event fires. You could also code your smart tag to load the list at other times or periodically check for updates all of which would require different but not difficult code.
Once the list loads, code in the Recognize or Recognize2 method can use it to compare against what a user has typed in the document.
The recognizer focuses mainly on determining if a given string of text is relevant. You must code the logic for this according to your needs. Below is the logic for the Recognize2 method:
Dim i As Integer Dim propbag As SmartTags.ISmartTagProperties Dim token As SmartTags.ISmartTagToken Try Dim nToken As Integer If Not TokenList Is Nothing Then For nToken = 1 To TokenList.Count token = TokenList.Item(nToken) If Not token Is Nothing Then For i = 0 To termCount - 1 If token.Text.ToLower = termList(i).ToLower Then propbag = RecognizerSite2.GetNewPropertyBag RecognizerSite2.CommitSmartTag2( _ SEARCH_NAMESPACE, _ token.Start, token.Length, propbag) End If Next i End If Next End If Catch ex As Exception ' Add exception handling code End Try
This code loops through the TokenList collection passed as an argument of the Recognize2 method. The TokenList collection contains the text you want the code to evaluate. As you loop through the collection, you compare its items to the items you have stored in memory after reading the term list XML file.
When the code finds a match, it gets a new PropertyBag object and commits a smart tag, effectively marking up the recognized text with a namespace attribute. When you hover over the text in Word, the application knows that the text is marked up in this way and presents a menu as specified in the class that handles smart tag actions.
Recognition is only half of the smart tag technology. You also need to code the actions for the smart tag. This is where things are the most interesting because the action handler has code to provide functionality for what you want to happen based on the recognized text. In this example, the action is to take the recognized term and search within the user's Exchange inbox looking for items whose subject contains the term. The code displays a Windows form with a DataGrid containing the list of search results (Figure 4). Right-clicking a search result in the grid inserts the items body text into the Word document just after the smart tag text (Figure 5).
Following is the code
Try Select Case VerbID Case 1 If ApplicationName = "Word.Application.11" Then Dim rngWord As Word.Range = DirectCast(Target, Word.Range) Dim dv As dv = UseWebDAV(rngWord.Text) If dv.Count > 0 Then ' Create a new instance of the Windows form ' with a . Add columns to the grid. End If End If End Select Catch ex As Exception ' Add exception handling code End Try
Most of this code is devoted to formatting the DataGrid (that code is shown and explained later on) whose data source is a DataView returned from a custom function, UseWebDAV. This procedure contains the code for querying Exchange.
You can access the Exchange message store in a variety of ways including ADO, ADO.NET, WebDAV, or simple HTTP. This article demonstrates retrieving items through WebDAV. WebDAV is a protocol that extends HTTP 1.1 (see RFC 2616), and you can configure Microsoft Exchange Server 2003 or Microsoft Exchange Server 2000 to allow access to its data storage by using this protocol. Using WebDAV you send requests in XML format over HTTP, and Exchange responds by returning an XML stream.
In the example for this article, the process of querying by using WebDAV is in its own function to keep things more orderly. The function accepts the search term as a parameter, and it returns a DataView instance containing the results of the search.
You need to declare some variables in the procedure. They are as follows:
' These variables are used for the WebDAV communication Dim Request As System.Net.HttpWebRequest Dim Response As System.Net.HttpWebResponse Dim RequestStream As System.IO.Stream Dim ResponseStream As System.IO.Stream Dim ResponseXmlDoc As System.Xml.XmlDocument Dim bytes() As Byte ' These variables are for handling security Dim MyCredentialCache As System.Net.CredentialCache Dim strPassword As String Dim strDomain As String Dim strUserName As String ' These variables are for working with search results Dim SubjectNodeList As System.Xml.XmlNodeList Dim SenderNodeList As System.Xml.XmlNodeList Dim BodyNodeList As System.Xml.XmlNodeList Dim URLNodeList As System.Xml.XmlNodeList Dim myDataSet As New DataSet() Dim myRow As DataRow
There are three sets of variables. The first set contains variables for handling the communication between the smart tag DLL and the Exchange server. The second set is for setting up the security authorization for the WebDAV request and response. The final set declares some XmlNodeList variables, a DataSet, and a DataRow. These are used to get the result set into a specific structure for the final Windows form DataGrid.
For authorization, you must assign valid values to the user name, password, and domain name variables. These are used when creating a CredentialCache instance that you pass along with the WebDAV request.
Next, the code sets up the query definition. The query is in SQL-style syntax, but the FROM clause does not specify a table. Instead, the FROM clause specifies the traversal of a specific folder in the Exchange data store.
Dim QUERY As" _ & "<g:sql>SELECT ""urn:schemas:httpmail:subject"", " _ & """urn:schemas:httpmail:from"", ""DAV:displayname"", " _ & """urn:schemas:httpmail:textdescription"" " _ & "FROM SCOPE('deep traversal of """ & URL & """') " _ & "WHERE ""DAV:ishidden"" = False AND ""DAV:isfolder"" = False " _ & "AND ""urn:schemas:httpmail:subject"" LIKE '%" & term & "%' " _ & "ORDER BY ""urn:schemas:httpmail:date"" DESC" _ & "</g:sql></g:searchrequest>"
This query does a deep traversal of the specific starting point in the person's inbox in Exchange. Here, the query uses a variable, URL, for this purpose. You declare the URL variable as a class-level variable like this:
The code then creates instances of HttpWebRequest and HttpWebResponse. You use these to send the request to the Exchange server and to get its response. The response will come in the format of an XML stream.
Request = CType(System.Net.WebRequest.Create(URL), _ System.Net.HttpWebRequest) Request.Credentials = New System.Net.NetworkCredential( _ strUserName, strPassword, strDomain) Request.Method = "SEARCH" Request.ContentType = "text/xml" bytes = System.Text.Encoding.UTF8.GetBytes(QUERY) Request.ContentLength = bytes.Length RequestStream = Request.GetRequestStream() RequestStream.Write(bytes, 0, bytes.Length) RequestStream.Close() Request.Headers.Add("Translate", "F") Response = Request.GetResponse() ResponseStream = Response.GetResponseStream()
Because the response comes as an XML stream, you can load it into an instance of XmlDocument. Then, you can separate out the different fields of interest. In this case, these are the subject, from, href, and textdescription fields. These come from different namespaces, so you need to use the proper namespace prefixes when calling the GetElementsByTagName method to load the elements in to XmlNodeList objects.
'")
If one of the XmlNodeList objects contains child elements you know that the search results are not empty. Then, you can add a new table to a DataSet instance and add new columns to the table.
If SubjectNodeList.Count > 0 Then myDataSet.Tables.Add(New DataTable("Emails")) myDataSet.Tables("Emails").Columns.Add("Subject", _ System.Type.GetType("System.String")) myDataSet.Tables("Emails").Columns.Add("From", _ System.Type.GetType("System.String")) myDataSet.Tables("Emails").Columns.Add("URL", _ System.Type.GetType("System.String")) myDataSet.Tables("Emails").Columns.Add("BODY", _ System.Type.GetType("System.String"))
Looping through the XmlNodeList objects, you can add the text values of their elements to corresponding field locations in the DataSet's table.
Dim i As Integer For i = 0 To SubjectNodeList.Count - 1 myRow = myDataSet.Tables("Emails").NewRow() myRow("Subject") = SubjectNodeList(i).InnerText myRow("From") = SenderNodeList(i).InnerText myRow("URL") = URLNodeList(i).InnerText myRow("BODY") = BodyNodeList(i).InnerText myDataSet.Tables("Emails").Rows.Add(myRow) Next End If
As a matter of course, you should close the objects used to communicate with the Exchange server.
Finally, you return an instance of a DataView containing the table you just created.
Earlier, you saw that the code in the InvokeVerb2 method calls the custom procedure, UseWebDAV. This procedure returns a DataView instance that the code assigns as the DataGrid's data source. The DataGrid exists on a custom Windows form. You need to create an instance of this form and display it after configuring the grid. The code maps programmatically added DataGrid columns to columns in the DataView table. The width of two columns is set to zero so that those columns are not displayed.
If dv.Count > 0 Then ' Create a new instance of the Windows form ' with a DataGrid. Add columns to the grid. Dim f As New Form1 Dim DataGridTextBoxColumn1 As _ System.Windows.Forms.DataGridTextBoxColumn = _ New System.Windows.Forms.DataGridTextBoxColumn Dim DataGridTextBoxColumn2 As _ System.Windows.Forms.DataGridTextBoxColumn = _ New System.Windows.Forms.DataGridTextBoxColumn Dim DataGridTextBoxColumn3 As _ System.Windows.Forms.DataGridTextBoxColumn = _ New System.Windows.Forms.DataGridTextBoxColumn Dim DataGridTextBoxColumn4 As _ System.Windows.Forms.DataGridTextBoxColumn = _ New System.Windows.Forms.DataGridTextBoxColumn Dim DataGridStyle As DataGridTableStyle = _ New DataGridTableStyle DataGridStyle.MappingName = "Emails" DataGridStyle.GridColumnStyles.Add(DataGridTextBoxColumn1) f.DataGrid1.TableStyles.Add(DataGridStyle) DataGridTextBoxColumn1.MappingName = "Subject" DataGridTextBoxColumn1.HeaderText = "Subject" DataGridTextBoxColumn1.Width = 255 DataGridTextBoxColumn2.MappingName = "From" DataGridTextBoxColumn2.HeaderText = "From" DataGridTextBoxColumn2.Width = 100 DataGridTextBoxColumn3.MappingName = "URL" DataGridTextBoxColumn3.HeaderText = "URL" DataGridTextBoxColumn3.Width = 0 DataGridTextBoxColumn4.MappingName = "BODY" DataGridTextBoxColumn4.HeaderText = "BODY" DataGridTextBoxColumn4.Width = 0 f.DataGrid1.DataSource = dv f.WordRangeRef = rngWord f.ShowDialog() End If
Here, the final line displays the form as a modally to reduce complexity, but you could display the data in the task pane or in another fashion. Closing the Windows form removes the form, the DataGrid, and the search results from memory, so clicking on the smart tag menu again requires an entirely new search, form instance, and reformatting of the grid. You could code things differently to cache search results or the form itself. Before displaying the form, the code gets a pointer to the Word Range object passed as an argument to the InvokeVerb2 method. It then passes this reference to the Windows form so that it can directly manipulate the text of the Word document. This allows code in the form to insert text in the Word document in response to an event.
When you hover over a selection in the DataGrid (Figure 6) and right-click, custom code executes to insert the body text for the target item into the Word document.
In order for this part of the solution to work you need code to respond to the right-click event and you need a reference to Word document so you can add text directly to it. To gain access to the Word document, the Windows form has a public property definition that you can set by code that creates an instance of the form. The property definition looks like this:
The wrdRange variable is a private, class-level variable in the Windows form class definition. The wrdRange object is only created by using the WordRangeRef property procedure which executes when calling code sets the property. You may recall that this property is set in the InvokeVerb2 method like this:
Code for the DataGrid's right-click event can access this instance of the Word Range and use it to add text to the target document. The code to respond to a user right-clicking the DataGrid is in its MouseDown event:
Private Sub DataGrid1_MouseDown( _ ByVal sender As Object, _ ByVal e As System.Windows.Forms.MouseEventArgs) _ Handles DataGrid1.MouseDown Dim dg As DataGridView = sender If e.Button = MouseButtons.Right Then Try Dim hti As DataGridView.HitTestInfo = dg.HitTest(e.X, e.Y) If hti.Type = 1 Then Dim dv As DataView dv = CType(DataGrid1.DataSource, DataView)) End If Catch ex As Exception MessageBox.Show(ex.Message, "Exception") End Try End If End Sub
Using an argument for the event, you can detect whether or not the user right-clicked the DataGrid. Then, you can determine where the user clicked using other event arguments. If the user has right-clicked a cell in the DataGrid, you want the code to continue. The first thing to do is get access to the data in DataView.
The rest of the code creates a newly formatted Word table containing the subject and body text of the selected item in the DataGrid. The code inserts this Word table into the document:)
Because this solution is written in managed code, you may want to do a little extra maintenance with respect to the COM objects and how the .NET runtime manages their memory allocation. We release these objects from memory explicitly by calling a custom procedure in a shared class:
Friend Class GlobalUtil Public Shared Sub ReleaseComObjectInstance( _ ByVal obj As Object) ' Clean up by releasing the objects Try Dim i As Integer Do i = System.Runtime.InteropServices. _ Marshal.ReleaseComObject(obj) Loop While i > 0 Catch ex As System.Exception MessageBox.Show("Exception in GlobalUtil") MessageBox.Show(ex.Message) MessageBox.Show(ex.StackTrace) Finally obj = Nothing End Try End Sub End Class
You can then call this custom procedure in your code when you are finished using a COM object instance like this:
Finally, you should add code to the click event of a button to close the Windows form when it is no longer needed.
Microsoft Office Word 2003 includes a number of built-in smart tags. Some of these let you take action with Outlook data using typed text as the point of departure. However, you can create your own smart tags to take different actions. This article shows how to create a smart tag that does programmatic searches of the Exchange message store looking for items containing terms a user has typed in a document. Ultimately, one of the goals of smart tags is to add value to the user's experience in the application. You can create your own smart tag recognizers and action handlers, and in so doing, you can bring the user's activity in documents into proximity with many other data sources and tasks. Smart tags extend the reach of user from the document to data bases, Web services, email, scheduling, messaging and so much more.
This section lists a number of resources you can use to learn more about the products and technologies mentioned or used in this article.
Sites:
MSDN Office Developer Center
SDKs:
Online Office 2003 Smart Tag SDK
Download Office 2003 Smart Tag SDK
Microsoft Exchange Server 2003 Software Development Kit
Tools & Utilities:
Smart Tag Enterprise Resource Kit
Articles:
Communicating XML Data over the Web with WebDAV
Regular Expression Support in Microsoft Office System Smart Tags
Using Smart Tags with Research Services for the Microsoft Office System
Create Smart Tags and Event-Code for AutoFilter Results
Using the Smart Tag Shim Solution to Deploy Managed Smart Tags in Office XP
Building Smart Tags in Microsoft Visual Basic .NET
Developing Smart Tag DLLs
Integrating Office XP Smart Tags with the Microsoft .NET Platform
Smart Tags Frequently Asked Questions
How to Create an Office XP Smart Tag DLL by Using Visual Basic .NET
Blogs:
|
https://msdn.microsoft.com/en-us/library/bb226685(office.11)
|
CC-MAIN-2015-11
|
refinedweb
| 3,337
| 56.86
|
Python Tutorial
PythonContents
- Why Python?
- Variables
- Types of Variables
- Strings and Characters
- Lists and Tuples
- Loops
- Decisions
- Importing Modules
- Writing Functions
- Writing Programs
- Errors and Warnings
- Input
- Exercise 1 - Adding numbers
- Exercise 2 - Adding positive numbers
- Arithmetic
- Exercise 3 - Times Table
- Exercise 4 - Times Table Function
- Exercise 5 - Die-throwing
- Exercise 6 - More Die-throwing
- Exercise 7 - Throwing 2 Dice
- Reading from files
- Exercise 8 - Code Solving
- Exercise 9 - Pi
- Exercise 10 - Monopoly ©
- New Types
- Writing to files
- Python for Engineers
- Storing your Functions
- More Features
- More exercises
- Real programs
- Useful Links
This document makes no attempt to exhaustively cover the Python computing language. It introduces just enough Python for you to write small programs and run them. The idea is to give you the confidence to learn more yourself - like learning to snowplough as the first stage when skiing, or learning not to be scared of the water when learning to swim. Once you can run little programs that you've written, you can copy example source code and experiment with it to learn how it works. Like skiing and swimming, you can only learn programming by doing it.
Towards the end it introduces aspects of Python that you could do without when writing simple code, but they make your programs shorter and easier to read. These extra techniques are useful when writing longer programs.
The Python language is a scripting language (it doesn't have to be "compiled") and it's freely available on many types of machines. Among the users of Python are YouTube and Google. Add-ons like NumPy, Scipy and Matplotlib allow Python to be used effectively in scientific computing.
The document includes some sections of extra information that you can show or hide. If you want to see all the extra sections, click on this Extras button. Use Ctrl + and Ctrl - to adjust the text size.
Start sessions on the CUED central system by clicking on the
icon at the bottom of the screen and then clicking on the All CUED Applications/all other start scripts/Start Python option. This will put some icons on the screen for you, and start a program called idle, which makes it easier to write programs in Python
If you want to work from home and use Linux or Macs you may not need to install anything extra. If you use Windows, see Southampton University's Download and install Python software page. You won't need the extra packages they mention.
Why Python? [ back to contents]
It's a good question. You're likely to use several programming languages in your career because no language will cope with all situations. Here are a few reasons why Python might be useful to you
- It's free - Mac and Linux machines have it pre-installed. It's easy to install on Windows
- It's easy to use - Engineers aren't computer scientists. They want answers, and Python has a gentle learning curve (compared to Java and C++ anyway)
- It's expandable - There are add-ons for engineering and maths topics. There are also add-ons to make it faster so that big engineering tasks can be performed. If you want to turbo-charge part of your program you can write your own add-on in Fortran or C++
- It's adaptable - It's a "glue language" to connect things up. Engineers use many different programs. From Python you can run a number-crunching program, get some information from a web page, do a few calculations then produce an Excel file - all in a few lines of code
- It's modern - Engineers have made major contributions to maths and computing. Python has all the advanced features that cutting edge programmers and mathematicians desire.
- The University likes it - There's local support from the computing service - courses in Scientific Computing, etc.
This document uses Python 3. Its print is a function rather than a statement, so if you want to use Python 2 with this document you'll need to replace print ("hello") by print "hello", etc.
Variables [ back to contents]
You can use Python like a programmable calculator - interactively from the command line. If at your prompt in idle you type
2+2
and press the Enter key you'll get 4, but you can also do
x=2 x+2
and get the answer 4. The x used here is a variable - a place to store something, and you use a = sign to put something into a variable. You can also store text in a variable - e.g.
x="apples"
but if you then try
x+2
you'll get an error message because you can't add a number to text. You can however do
x+" and pears"
because variables of the same type can usually be added together.
You can set variables to the value of other variables. For example, you can do
x=2 y=x+1
which will give y the value 3. Similarly you can do
x=2 x=x+1
The second line might look a little strange ("how can x ever be equal to x+1?") until you remember what the equals sign means in this context. x will end up with the value 3.
Python is fussy about variable names - they can't have spaces or dots in them, nor can they begin with a digit. They shouldn't clash with the name of something that already exists. Python has lots of built-in functions (max for example). Typing max=100 is legal, but it stops you easily using the max function subsequently. So don't use names that are too general
Note also that Python distinguishes between upper and lower case characters - num and Num are different variables.
In this document we use the camelCase convention for variable names. Names will begin with a lower-case letter and each new word will begin with an upper-case letter - e.g. nameOfChild
Types of Variables [ back to contents]
As we've seen earlier, variables like x can "contain" different types of things - integers, characters, etc. Doing x=999 is different from doing x="999", though if you did print x after both of these commands, you wouldn't notice a difference. But you would notice a difference if you tried print x+1. If you try to add a number to text you'll get an error message like the following
so it's important to know about a variable's type. To find out what type of thing is in a variable, use the type command - e.g.
x=999 type(x)
tells you that x is an integer. You can convert values from one type to another using commands called int, str (to convert to text), float (to convert to a floating point number), etc. For example, the following works
x="999" print(int(x) +1)
One type of variable you haven't met yet is bool. A variable of this type can be either True or False.
Strings and Characters [ back to contents]
Strings are sequences of characters. If you add 2 strings using +, the 2nd string is appended to the 1st. If you want to find the length of a string you can use a function called len(). Here's an example of appending to, then finding the length of, a string. Try to guess what it will do if you run it, then copy/paste it into the idle window (note that Python is fussy about indentation. If pasting causes spaces at the front of any of these lines you'll get a "IndentationError: unexpected indent" message. Later you'll see how use indentation advantageously)
s="hello" s=s+" world" len(s)
To find a particular character of this string (the 3rd, for example) you can do this
s[2]
Note that the numbering of the characters starts at 0. You can also pick out a range of characters. Try
s[2:5]
Note that this picks out items s[2], s[3], and s[4] but not s[5]
You can use single quotes or double quotes around strings.[show extra information]
Lists and Tuples [ back to contents]
When you have a program with lots of variables, giving each a different but useful name can be tricky - it's like having a street where the houses have names rather than numbers. Very soon you'll want to collect variables that are related into some kind of tidy group. Python has various ways of doing this. We'll start by looking at lists because these are used in nearly every Python program. Here's a shopping list of 3 items.
shopping=["apples", "bananas", "carrots"]
You can discover the list's length and pick out particular items in the same way as you did with strings. len(shopping) will tell you how many items are in the list. The 2nd item can be accessed using shopping[1] (numbering begins at 0). To find the length of that item you could use len(shopping[1])
You can replace items in a list. You can have a mix of types of things in a list too, so
shopping[1]=999
is possible. You can append and delete items too. After
shopping.append("dates") del shopping[0]
you should be left with a shopping list containing 3 items - 999, carrots and dates. You can have lists of lists, so
megashop=[7, shopping, "nine"]
is possible. This is a list of 3 items whose 2nd item is another list. To find the length of the 3rd item in the list that's the 2nd item of megashop you can do
len(megashop[1][2])
Lists of numbers are common, so there's a function called range to create them easily
range(1,5)
creates a [1, 2, 3, 4] list and
range(1,6,2)
creates [1, 3, 5] (the list runs from 1 to 5 in steps of 2).
You can create lists by duplicating existing ones. For example, if you type [1, 2]*5 you create a new list which is 5 copies of the original one. You can use this technique to create a list full of a particular number. E.g. [0]*8 creates a list of 8 zeroes.
Tuples are like lists except that you can't change them. To create them you use ( ... ) instead of [ ... ]
Loops [ back to contents]
For repetitive tasks, use loops. Here's a for loop
for number in [1, 2, 3]: print(number)
Make sure you don't forgot the ":" symbol. When you type this in you might notice a few things. You've probably already noticed that idle colour-codes your program - function names are purple, keywords are orange, etc. When you hit Return after the colon, some spaces are added on the next line. These spaces matter! The for statement is going to make some lines run several times. These lines are call the body of the loop. The indentation is a way to show how many of the subsequent lines need to be repeated. When you hit Return after the "print number" line, the cursor will be indented on the next line, giving you a chance to continue the body of the loop (the lines all have to be indented by the same amount). If you press Return again, idle will know that the loop has finished and you should get the output. number is set to 1 and print number is run. Then number is set to 2 and print number is run. Finally number is set to 3 and the print(number) line run.
The range function goes well with the for statement. Try the following
for number in range(1,5): print("Hello")
It should print "Hello" 4 times. Another type of loop is a while loop. Here's an example
number=1 while number < 5: print(number) number=number+1
It should print the integers from 1 to 4 inclusive. Each time the code goes round the loop, the value of number is checked, its value is printed out, then 1 is added to it.[show extra information]
Decisions [ back to contents]
The while line above involved a comparison whose outcome affected the course of the program. As well as using < (meaning 'less than') to compare values you can use
- <= (meaning 'is less than or equal to')
- > (meaning 'is greater than')
- >= (meaning 'is greater than or equal to')
- != (meaning 'isn't equal to')
- == (meaning 'is equal to').
There's also an if keyword. Here's an example
num=3 if num<5: print ("num is less than 5")
Train yourself to use == rather than = when making comparisons (some languages use === so count your blessings). Be careful to avoid mixed-type comparisons - if you compare a floating point number with an integer the equality tests may not work as expected.
You can use else in combination with if - e.g.
if num<5: print ("num is less than 5") else: print ("num is greater than or equal to 5")
You can combine comparisons using boolean logic. Suppose you want to run a line of code if num is between 3 and 5. You can use
if 3<num and num<5: print ("num is greater than 3 and less than 5")
As well as and, the Python language understands or and not.
Importing Modules [ back to contents]
You've already used some of Python's functions - len and range. As we'll see later, many more exist in standard Python, but some of the most useful ones are in add-ons called Modules. Each of these modules tends to deal with a particular topic. Some are very specialised and especially useful for engineers. In this section I just give you a taste of the possibilities available. You don't need to try then all out now. You can probably guess what most of these lines do. What you will need to appreciate is that
- to use a function in a module you first need to import the module
- when you call the function you need to say which module (or submodule) the function comes from using the dot syntax - see the examples below
- you'll need to read the documentation in order to use a module
import time t=time.localtime() print (time.asctime(t)) import math math.factorial(5) math.sqrt(5) math.sin(5) import cmath cmath.sqrt(-1) import random random.randint(1, 6) x=range(1,7) random.shuffle(x) print(x) import turtle t=turtle.Pen() t.forward(50) t.right(45) t.forward(50)
Writing Functions [ back to contents]
You can write your own functions. The limits on their names are much the same as the limits on variable names. Here's a function that will print its input parameter three times
def tripleprint(s): for i in range(1,4): print(s)
Once you've typed this in, then you can try it out by typing
tripleprint("hello")
or
tripleprint(5)
tripleprint needs one input argument which inside the function is called s in this example. In fact, s can only be accessed from inside the function - it's a local variable rather than a global one. If you had a variable s elsewhere the 2 variable wouldn't "clash".
Let's now write a function that prints its first input parameter as many times as we want
def multiprint(s, howmany): for i in range(1,howmany+1): print(s)
Now multiprint("hello", 7) will print "hello" 7 times.
These 2 functions don't "return" any values - i.e. they're not like sin or sqrt which supply an answer. Here's a function that returns double the number given it. It uses the return keyword to specify the value to be returned.
def doubling(s): return 2*s x=doubling(3)
The following table shows how Python represents various types of function diagrams[show extra information]
Writing programs [ back to contents]
All the examples so far have been short. Now you're going to write
complete programs and save them. From the "Python Shell" window's File menu, choose "New Window" and type the following into it
# A program to simulate rolling a die 10 times import random def rolldie(): return random.randint(1,6) for i in range(1,11): print ("On roll ",i," I threw a ",rolldie())
The first line of this is a comment - the # symbol and anything to the right of it is ignored when the program is run. The last line uses the print command to display some strings, variables and function values. Note how commas are used to separate the values being printed out. Spaces are automatically added between the values.
Save the code as die.py (Python files usually have the suffix py) then pick the "Run Module" option from the "Run" menu to run the program. You should get a list of dice throws like this.
Errors and Warnings [ back to contents]
You may not get everything right first time. Don't be worried by error messages - even the smallest spelling or punctuation error can break a program. You can get a lot of error messages from just one mistake so just look at the first error message.
The most common errors will be due to spelling mistakes, variables being read before they've been created, missing or incorrect punctuation, or incorrect indentation. When you think you've identified the trouble, correct it, save the file and run it again.
Even if your code is legal, it may do the wrong thing - perhaps because you've put a '+' instead of a '-'. One of the most effective things to do in this situation is to use print to print out the values of certain variables to help you diagnose where the problem is. Don't just passively stare at your code - make it print out clues for you.
Python has a help function but you might not find it very helpful initially. It will tell you about the thing you give it, so you can do help(len) to find out about the len function. If you do i=9 and then help(i) you'll be told more about i than you probably want to know. Perhaps most useful is a bookmark to a page like The Python Tutorial[show extra information]
Input [ back to contents]
To get input from the user, use something like
var = input("Type a number! ")
This will display "Type a number! " on the screen and put the user's reply into the variable (var in this example). This reply will be a string, so even if they type a number in, you won't be able to perform calculations with it. To convert it into an integer you can do this
var = int(var)
Exercise 1 - Adding [ back to contents]
You now know enough to write your own programs. Use the "New Window" option to create a new file. Save it as adding.py. Write a program that prints the sum of 2 numbers typed in by the user. Print an output line looking rather like this
The sum of 6 and 73 is 79
Exercise 2 - Adding positive numbers [ back to contents]
Create a new file called adding2.py. This time keep asking the user for input until they've typed in 2 positive numbers. I suggest that you start by copying adding.py then put each raw_input command inside a while loop so that you can keep on asking for input while the variable isn't a positive value.
Arithmetic [ back to contents]
Use + (add), - (subtract), * (multiply), / (divide), and % (modulus - i.e. getting the remainder in integer division). Note that the operator for exponentiation is ** (beware: in some other languages 3^2 produces 9 but in Python it produces 1)..
If you try 5/2 you'll get the answer 2 because when an integer is divided by an integer, the result is an integer. If you do 5.0/2 or 5/2.0 you'll get the answer 2.5[show extra information]
Exercise 3 - Times Table [ back to contents]
Use the "New Window" option to create a new file. Save it as timestable.py. With a loop print out the first 10 entries in the 7 times table - i.e.
(don't worry too much about putting the spaces in exactly the right places)
Exercise 4 - Times Table Function [ back to contents]
Write a function called timestable that will print the 7 times table that you had before. Write it so that you can use timestable(7) to run it. Check that timestable(9) produce the 9 times table.
Exercise 5 - Die throwing [ back to contents]
You've already been shown a function that simulates the throwing of a die. Roll the die a 1000 times to see how many 6s are thrown. Print the answer out.
You'll need a variable to store how many sixes are thrown. Initialise it to zero and add 1 to it each time a 6 is thown.
Exercise 6 - More Die-throwing [ back to contents]
This time you're going to keep a count of all the outcomes, not just the 6s. Print the results out like this
You'll need a variable to store the frequencies of each of the outcomes. Rather than name these variables ones, twos, etc (which gets messy, especially when we start using several dice) I suggest you use a list. The following code creates a list called frequency and then sets all the elements to 0 (even frequency[0], which we're not going to use).
# the next line creates a list of 7 items initialised to 0 frequency=[0]*7
If you use frequency[1] to store the number of 1s thrown, frequency[2] to store the number of 2s thrown, etc, you can use a loop to print out these values at the end.
Exercise 7 - Throwing 2 Dice [ back to contents]
Write a function that simulates the throwing of a pair of dice and returns their sum. Roll the dice a 1000 times and display the frequency of the outcomes similar to the previous exercise.
Reading from files [ back to contents]
f = open('workfile', 'r')
opens a file called workfile ready for reading.
f.readline()
reads a single line from the file; a newline character (displayed as \n) is left at the end of the string
Using these 2 commands you can do the following to get a line of text from a file (in this case a file called secretmessage) and put it into a string (in this case called message).
f=open("secretmessage","r") message=f.readline()
There are many other file-reading facilities, but that's all you'll need for now.[show extra information]
Exercise 8 - Code Solving (reading files) [ back to contents]
In your Python folder (created when you did start python) there's a file called "secretmessage" (download this file if you don't have the original). Your mission is to write a program called decode.py to decode the contents of this file (a single line of text). It's been encoded using a simple shifting algorithm where each letter has been replaced by the letter N places behind
- Using the code in the previous section, read the message in from the file into a string using readline (the message is only one line long). Create an integer N (the amount the characters have been shifted by) and set it to a value. For now, let's just guess the number 7.
- You can use the string as if it were a list of characters. Pick out the characters in the string one at a time using a loop like this
characters_processed=0 # while we're not at the end of the string, get the character while characters_processed < len(message): letter=ord(message[characters_processed]) characters_processed=characters_processed+1Each character is represented in the computer as an integer. The ord function returns that integer so that you can perform arithmetic on it (ord('A') for example returns 65).
- Inside the while loop, process each character stored in the letter variable
- If the character is not a space, set letter to be letter plus N. If the resulting character is more than 'Z' (i.e, if letter > ord('Z'):), subtract 26 from letter so that the letter cycles round.
- Convert the resulting integer back into a character using the chr function and print the resulting string out (if you add
, end=""to the print command's argument - i.e. use print(chr(letter), end="") - then all the characters will appear on the same line)
Run the program. If you're lucky you'll get a readable message. It's more likely that you'll get junk because N will need to be a different number. Rather than manually having guess after guess (changing N and running until you get the answer) try this
- Restructure the code to make it neater. This is something developers often have to do - re-engineer their work so that it does the same as before, but in a tidier way. Put the decoding code you've written into a function called decode_and_print that takes the coded message and N as its input parameters, returning nothing. Its job is to print the decoded message. Once you've written the function, all that your main code need contain is the code to read the message in, then a call to the function by doing decode_and_print(message,7). You should get the same result as before!
- Change the program so that it tries decoding with N=1, then N=2 up to N=25. printing the decoded message each time. Do this using a loop. Determine the N that works for your message.
Exercise 9 -
The pen will hit a crack (an edge of a floorboard) if the closest distance (D) from the pen's centre to a crack.
- In a file called pi.py write a function called dropthepen to simulate the dropping of the pen. Make it return True if it touches a crack in the floor and False otherwise.
There are 2 random factors to take account of - the angle of the pen (0 - pi/2 radians) and the distance of the pen's centre from a line (0 - 0.5; our floorboards will be 1 unit wide). The function will need to calculate sin(theta). The sin function expects its argument to be in radians so you can do
angleinradians=random.uniform(0,math.pi/2)Create a variable D and set it to random.uniform(0,0.5). Using D and sin(angleinradians) you can now work out whether the pen lands on a crack.
- Add some code to call your function. Use a.
- Now do 10,000 runs. You should get a more accurate answer for pi.
Exercise 10 - Monopoly © [ back to contents]
You're playing Monopoly..py to run 10,000 simulations.
Whenever you have a non-trivial program to write, think about how it can be broken down into stages, and how you can check each stage.
- You already have a function to roll 2 dice. (draw flow charts if you want), then express that strategy using Python. the function a few times and print the outcome to see if the results are reasonable.
To see whether you've landed on a hotel, you can create a list of hotel locations
hotelLocations=[ 1, 3, ....]then use
if location in hotelLocations:to see if you've been unlucky.
- Now call that function 10,000 times using something like
output=runTheGauntlet()in a loop. You don't want to print each outcome but you do want to store how many times no hotels were landed on, how many times only 1 hotel was landed on, etc. Create a list.
New Types [ back to contents]
If the range of types that Python provides is too restrictive you can invent new types. When you use a language (like English or Python) you are often attempting to represent or model the real world. The more the modelling language structurally resembles what it's modelling, the easier the modelling is likely to be. Suppose you have the following data
Name Anna Smith Ben Crab Charlie Webb Height 177 185 170 Age 20 18 15
You can create a class (a new type) designed to contain this information as follows
class Person: fullname="" height=0 age=0
The values provided here are defaults for the properties you've created. You could then create a variable to represent Anna's information by doing
anna=Person() anna.fullname="Anna Smith" anna.height=177 anna.age=20
The variable anna "has" a fullname, height, and age just as the person Anna has a name, height, and age. If you wanted to print Anna's height later on, you could do
print ("Anna's height = ", anna.height)
Here's another example. Suppose your program was dealing with 2-dimensional points. It would help to have a type of variable to represent a point. You can create such a type like this
class Point: x=0 y=0
Inside Point there are x and y coordinates, initialised to 0. If we wanted to create a function to display the coordinates of a point we could produce this
def display(thePoint): print(thePoint.x,thePoint.y)
Then the following would work
p=Point() display(p)
But it's a good idea to keep this routine and the class it depends on together because they depend on each other. In big programs especially, this approach (the Object Oriented approach) is recommended. To illustrate this, here's an alternative way of defining the Point class.
class Point: x=0 y=0 def display(self): print(self.x,self.y)
The display function now belongs to the class (it's known as a member function). self is a special argument - it means that the function uses items inside the object it's part of. The following code fragment shows how to set p's component fields to values and print them out using this member function
p=Point() p.x=5 p.y=7 p.display()[show extra information]
Writing to files [ back to contents]
To write to a file first you need to open it by doing something like
f=open('data','w')
then you can use
f.write(str)
to write the contents of a string str to the file, To write something other than a string, it needs to be converted to a string first. For example, you can do
value = ['the answer', 42] s = str(value) f.write(s)
When you've finished with a file it's a good idea to close it using
f.close()
Python for Engineers [ back to contents]
With Python you can quickly write little programs, but as engineers you'll be writing big or specialised programs before long. You might find these modules especially useful. If they're not already on your machine you can install them.
- Numpy is the defacto standard for the work with arrays (which are like lists except that all the items need to be the same type, and they're faster) and linear algebra. We don't have these installed, but we have some earlier modules. Here's an example
import numpy as np a = np.array (( (1, 5, 6), (7, 4 ,2), (0, 2, 8))) b = np.array (((4), (2), (5))) print ("a=",a," b=",b) print ("determinant=",np.linalg.det(a)) c=np.linalg.solve(a, b) print ("Solution of ax=b is ",c)
- Scipy deals with statistics, optimization, ODEs, etc.
- matplotlib creates graphics. Here's an example
import matplotlib.pyplot as plt import numpy as np a = np.zeros(1000) a[:100]=1 b = np.fft.fft(a) plt.plot(abs(b)) plt.show()
- sympy helps with symbolic integration, etc. Here's an example
from sympy import * x = symbols('x') a=integrate(x**2 * exp(x) * cos(x), x) print(a)
- EasyGui produces buttons and menus. Alternatively you can use wXwidgets (as used in 3rd year projects) or Tk.
On linux you don't need to run idle to write or run a python program. Just typing python on the command line will type an interactive version of python, and you can use any text editor to write your programs.
You can make your programs run just by clicking on them if you want
- Add
#! /usr/bin/pythonto the top of your file
- Make the file executable ("runnable") by clicking on it with the right mouse button, choosing "Properties" and clicking on the "Execute" box (see the illustration on the right).
You can then use the file almost as if it were a compiled C++ program.
Storing your Functions [ back to contents]
If you've written a useful function you might want to use it again and again. Rather than copying it into each program you need it in, you can save it in a file and import it. Here's an example
In the folder where you're working, create a file called extras.py and put the following into it
def tripleprint(s): for i in range(1,4): print(s) def multiprint(s, howmany): for i in range(1,howmany+1): print(s)
Now from the command line (or a program) you can load and run that code by doing
import extras extras.tripleprint(6) extras.multiprint("hello",4)
Note that import won't look around everywhere for modules. It looks
- In the current folder
- In PYTHONPATH - a list of folders you can customise
- In the system's default folders (do import sys; print sys.path to list them)
You'll need to set PYTHONPATH before you start Python. In Linux or MacOS you can do something like
export PYTHONPATH=/home/tim/mypythonmaths:/home/tim/mypythonpix python
In Windows you can do something like
set PYTHONPATH=c:\python20\lib; python
More Features [ back to contents]
As your programming skills and requirements grow, Python can grow with you. Here I'll just mention a few extra features
Doing without loops - Python offers several ways to avoid using for or while. There are functions to perform tasks that in some other languages require loops - try
x=range(1,10) print(x) x.reverse() print(x) x.sort() print(x) x.index(7) # find the value '7' in x
There's also the filter routine. Given a list of items and a function that returns True or False depending on whether you want to keep an item, filter will filter out the unwanted material.
def multipleOf7(num): if num%7==0: return True else: return False x=range(1,100) y=filter(multipleOf7,x) print(y)
Dictionaries - When lists aren't powerful enough you can try dictionaries. A dictionary is a collection of paired values - an English word and a French word, for example, or a name and a phone number. They're useful whenever you want to look up something. The following code creates a dictionary, uses it to look up the boiling point of water, then prints out all the information
boilingPoints={"Methane":-164, "Water":100,"Mercury":356.9} boilingPoints["Water"] for substance, temperature in boilingPoints.iteritems(): print (substance," boils at ", temperature," C")
More exercises [ back to contents]
You can practise by trying some of the exercises below. The earlier ones are easier.
-. If the user types something invalid, ask them to try again. - e.g. 1,345,197. Write a function which is given a float and prints out the number with commas. You'll need to find out how to convert numbers to strings - use the WWW!
- Create a list so that calling it as addfractions(3,4,5,6) will make it output something like 38/24, or better still 19/12, or even 1 + 7/12. You could create a class called Fraction
- Using the turtle module draw a square. Write a function that draws a square. Write a function that draws a * to the size you request.
- Python has function to sort items. We'll investigate how the time taken to sort items depends on n, the number of items. Is the time proportional to n? Here's a program that has some timing code in it
#! /usr/bin/python from datetime import datetime import random def microseconds(): dt = datetime.now() return dt.microsecond thelength=10 numbers=range(0,thelength) random.shuffle(numbers) for i in range(0,thelength): print(numbers[i]) numbers.sort() for i in range(0,thelength): print(numbers[i]) print (" Length Time Time/n Time/(n*ln(n))") print (repr(thelength).rjust(10))The microseconds function returns the number of microseconds that have elapsed since 1st Jan 1970. Don't worry about how it works. When you run this code you'll see a list of unsorted numbers, a list of sorted numbers, then part of a table. The final line prints thelength out so that it's right-justified in a column of width 10. First, comment out the lines that print the numbers (later you won't want to watch 10,000,000 numbers being printed out). Then complete the line of the table by timing the sort function (call microseconds() twice and find the difference between the 2 results). Time only the sort function - don't time the setting-up code too. Then complete the final 2 columns of the table. Your output should be something like
Length Time Time/n Time/(n*ln(n)) 10 82 8.1999999999999993 3.5612147516066646
Then using an appropriately placed loop add a completed line of data to the table for lengths of 100, 1000 ... 10,000,000. You'll need to move the line that prints the column headings so that they only appear once.
- Find out on how many lines of this Web page's source code the word Python is mentioned. Here's some code to get you started
import re # to search for a string on a line import urllib # to get the web page url="" f = urllib.urlopen(url) for line in f.readlines(): match = re.search('Python', line) if match is not None: print (line)Write a function wordInURL that given a word and a URL will display how many lines contain that word. For example wordInURL("iPad", "") might produceiPad is on 5 times
- The following code (which uses a dictionary and recursion) defines a network of points and connections, then finds a route from A to D. Write a function to find all the non-cyclic paths. Write a function to find the shortest path
graph = {'A': ['B', 'C'], 'B': ['C', 'D'], 'C': ['D'], 'D': ['C'], 'E': ['F'], 'F': ['C']} def find_path(graph, start, end, path=[]): path = path + [start] if start == end: return path if not graph.has_key(start): return None for node in graph[start]: if node not in path: newpath = find_path(graph, node, end, path) if newpath: return newpath return None find_path(graph, 'A', 'D')(answers are on the Python Patterns - Implementing Graphs page)
- For the lines below try to explain why the 2nd line of output isn't the same as the 1st, and why the 3rd line of output isn't the same as the 2nd
4.0/3.0 -1.0/3.0 -1.0 4.0/3.0 -1.0 -1.0/3.0 4/3 -1 -1/3
Real programs [ back to contents]
The difference between a beginner's program and a commercial program can be huge - even if you were allowed to see the source code of "Word" you wouldn't understand it. But some Python programs are useful and short. If you're on a Mac or a Linux machine (the CUED central system machines, for example) you'll have some Python programs on the system. You can list them from the command line by doing ls /usr/bin/*.py. Because Python is a scripting language, these files are readable text - like the programs you've been writing. Some are short enough for you to have a chance of understanding part of them.[show extra information]
Useful Links [ back to contents]
- Numerical Programming in Python (University Computing Service, Cambridge)
- Python: Introduction for Absolute Beginners (University Computing Service, Cambridge)
- Python: Introduction for Programmers (University Computing Service, Cambridge)
- The main python site has help and documentation pages
- Invent Your Own Computer Games with Python (an online book)
- An Introduction to Python For Undergraduate Engineers
- The comp.lang.python newsgroup
- Python Package Index - repository of software for the Python programming language with over 10,000 packages.
- © 2010 University of Cambridge Department of Engineering
Information provided by Tim Love (tpl) (with help from jgt25. Last updated: August 2011)
- Privacy
- Accessibility
|
http://www-h.eng.cam.ac.uk/help/languages/python/tutorial/index.php?reply=extravariables
|
CC-MAIN-2017-51
|
refinedweb
| 6,795
| 71.14
|
std::packaged_task::packaged_task
From cppreference.com
Constructs a new
std::packaged_task object.
1) Constructs a
std::packaged_taskobject with no task and no shared state.
2) Constructs a
std::packaged_taskobject with a shared state and a copy of the task, initialized with std::forward<F>(f).
3) Constructs a
std::packaged_taskobject with a shared state and a copy of the task, initialized with std::forward<F>(f). Uses the provided allocator to allocate memory necessary to store the task.
4) The copy constructor is deleted,
std::packaged_taskis move-only. Note: C++11 does not specify const here, this is the defect 2067.
5) Constructs a
std::packaged_taskwith the shared state and task formerly owned by
rhs, leaving
rhswith no shared state and a moved-from task.
Parameters
Exceptions
2-3) Any exceptions thrown by copy/move constructor of
fand possiblly std::bad_alloc if the allocation fails.
4) (none)
Example
Run this code
#include <future> #include <iostream> #include <thread> int fib(int n) { if (n < 3) return 1; else return fib(n-1) + fib(n-2); } int main() { std::packaged_task<int(int)> fib_task(&fib); std::cout << "starting task\n"; auto result = fib_task.get_future(); std::thread t(std::move(fib_task), 40); std::cout << "waiting for task to finish...\n"; std::cout << result.get() << '\n'; std::cout << "task complete\n"; t.join(); }
Output:
starting task waiting for task to finish... 102334155 task complete
|
http://en.cppreference.com/mwiki/index.php?title=cpp/thread/packaged_task/packaged_task&oldid=64858
|
CC-MAIN-2014-52
|
refinedweb
| 229
| 51.24
|
Oracle 1z0-804 1z0-804 : Java SE 7 Programmer II Exam Q: 2 Given: public class DoubleThread { public static void main(String[] args) { Thread t1 = new Thread() { public void run() { System.out.print("Greeting"); } }; Thread t2 = new Thread(t1); // Line 9 t2.run(); } } Which two are true?
A. A runtime exception is thrown on line 9. B. No output is produced. Leading the way in IT testing and certification tools,
-3-
C. Greeting is printed once. D. Greeting is printed twice. E. No new threads of execution are started within the main method. F. One new thread of execution is started within the main method. G. Two new threads of execution are started within the main method.
Answer: C, E Q: 3 Given: import java.util.*; public class AccessTest { public static void main(String[] args) { Thread t1 = new Thread(new WorkerThread()); Thread t2 = new Thread(new WorkerThread()); t1.start(); t2.start; // line1 } } class WorkPool { static ArrayList<Integer> list = new ArrayList<>(); // line2 public static void addItem() { // line3 list.add(1); // Line4 } } class WorkerThread implements Runnable { static Object bar = new Object (); public void run() { //line5 for (int i=0; i<5000;i++) WorkPool.addItem(); // line6 } } Which of the four are valid modifications to synchronize access to the valid list between threads t1 and t2?
A. Replace line 1 with: Synchronized (t2) (t1.start();) synchronized(t1) (t2.start();) Leading the way in IT testing and certification tools,
-4-
B. Replace Line 2 with: static CopyWriteArrayList<Integer> list = new CopyWriteArrayList<>(); C. Replace line 3 with: synchronized public static void addItem () { D. Replace line 4 with: synchronized (list) (list.add(1);) E. Replace line 5 with: Synchronized public void run () { F. replace line 6 with: Synchronized (this) {for (in i = 0, i<5000, i++) WorkPool.addItem(); } G. Replace line 6 with: synchronized (bar) {for (int i= 0; i<5000; i++) WorkPool.addItem(); }
Answer: F Q: 4 Leading the way in IT testing and certification tools,
-5- Q: 5 Q: 6 Leading the way in IT testing and certification tools,
-6-
D. getName(0): education subpath(0, 2): education\institute\student E. getName(0): report.txt subpath(0, 2): insritute\student
Answer: C Q: 7 Given the code fragment: public class DisplaValues { public void printNums (int [] nums){ for (int number: nums) { System.err.println(number); } } } Assume the method printNums is passed a valid array containing data. Why is this method not producing output on the console?
A. There is a compilation error. B. There is a runtime exception. C. The variable number is not initialized. D. Standard error is mapped to another destination.
Answer: D Q: 8 Which method would you supply to a class implementing the Callable interface?
A. callable ()
Leading the way in IT testing and certification tools,
-7-
B. executable () C. call () D. run () E. start ()
Answer: C Q: 9 Which two codes correctly represent a standard language locale code?
A. ES B. FR C. U8 D. Es E. fr F. u8
Answer: A, D Q: 10 Which code fragment demonstrates the proper way to handle JDBC resources?
A. Try { ResultSet rs = stmt.executableQuery (query); statement stmt = con.createStatement(); while (rs.next()) (/* . . . */) } catch (SQLException e) {} Leading the way in IT testing and certification tools,
-8-
B. Try {statement stmt = con.createStatement(); ResultSet rs = stmt.executableQuery (query); while (rs.next()) (/* . . . */) } catch (SQLException e) {} C. Try { statement stmt = con.createStatement(); ResultSet rs = stmt.executableQuery (query); while (rs.next()) (/* . . . */) } finally { rs.close(); stmt.close(); } D. Try {ResultSet rs = stmt.executableQuery (query); statement stmt = con.createStatement(); while (rs.next()) (/* . . . */) } finally { rs.close(); stmt.close(); }
Answer: C
Leading the way in IT testing and certification tools,
-9-
Published on Aug 2, 2012
Certifyhere offers Oracle 1Z0-804 questions and answers for your Java SE 7 Programmer II Exam exam preparation. Download 1Z0-804 free sample...
|
https://issuu.com/certifyhere/docs/120803094504-03cb89ffba0d43cfa8fbcc53d72448c6
|
CC-MAIN-2017-43
|
refinedweb
| 627
| 60.82
|
Smart home intents are simple messaging objects that describe what smart home Action to perform such as turn on a light or cast audio to a speaker.
All of the smart home intents are contained in the
action.devices
namespace and you must provide fulfillment for them. Whenever Google
Assistant sends an intent to fulfillment, a user's third-party OAuth 2 access
token is passed in the Authorization header.
These are the supported smart home intents:
SYNC
The
action.devices.SYNC intent is used to request the list of smart
home devices that the user has connected and are available for use.
When a user sets up their devices with the Google Home app, they also get
authenticated to your cloud infrastructure. Then, Assistant receives an OAuth2
token. At this point, Google Assistant sends a
action.devices.SYNC intent to your fulfillment to retrieve the
initial list of user devices and capabilities from your cloud infrastructure.
![ This figure shows the interaction between the Google infrastructure
and the partner infrastructure. From the Google infrastructure there is a
list of partners that is available to the Assistant client app, which then
flows to the partner infrastructure to complete OAuth authentication. The OAuth
authentication on the partner side is the partner setup webview, OAuth webview,
optional settings ands terms, and partner cloud services. The partner infrastructure,
then returns the OAuth credentials to the Assistant client app. The partner
cloud services sends available devices and capabilities to Assistant services,
which then stores the information in the Home Graph.]()
To avoid unlinking and relinking a user’s account, you can send a request sync
to Google Assistant. This sends the
action.devices.SYNC intent
to your fulfillment to sync the list of devices and capabilities. See
Implement Request Sync for more information.
During local fulfillment setup, the
Local Home platform checks the
SYNC response from your smart home Action’s
cloud fulfillment. To learn more about how to modify your
SYNC response to
support local fulfillment, see Update SYNC response in cloud fulfillment.
QUERY
The
action.devices.QUERY intent is used to query the current state
of smart home devices.
When users are querying device status, to answer a question such as Hey
Google, what lights are on in the kitchen?, Google Assistant sends a
action.devices.QUERY intent to your fulfillment.
For the best user experience, you should implement Report State to proactively report the current state of a user’s devices directly to Home Graph. For example, this lets Google Assistant know if your user turned on a smart light with a physical light switch.
EXECUTE
The
action.devices.EXECUTE intent is used to provide commands
to execute on smart home devices.
When users send commands to devices with Google Assistant, your fulfillment
receives a
action.devices.EXECUTE intent to your fulfilment that
describes the action and the devices to act upon. A user can execute an action
on a device with a command such as Hey Google, turn on my living room lights
.
DISCONNECT
The
action.devices.DISCONNECT intent is triggered to inform you
when a user has unlinked the app account from Google Assistant. After
receiving a
action.devices.DISCONNECT intent, you should not
report state for this user's devices.
|
https://developers.google.com/assistant/smarthome/concepts/intents?hl=de-DE
|
CC-MAIN-2021-21
|
refinedweb
| 541
| 57.37
|
User Tag List
Results 1 to 2 of 2
Thread: Not Railsy, But... How Do You...
Hybrid View
- Join Date
- Apr 2005
- 485
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Not Railsy, But... How Do You...
i'm workign through agile web dev with rails. i understand the scaffold and that it generates forms based off of your db definitions.
i'm curious how one would structure an app (or portion thereof) that didn't use a db? let's say i wanted an input box like so...
Enter Number: [text box here]
[Enter link here]
i would then like it to then display a different page with the number multiplied by 2. i know the math s/b stuck in the controller. i think ruby has a post method, but i don't know how to use it.
how would i display the result in the same page?
general answers with code snippets would probably be sufficient.
tia...
- Join Date
- Aug 2005
- 986
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
You create one input page with the form:
Code:
<input type="text" name="number" />
Code:
def multiply @number = params[:number].to_f * 2 end
Code:
The number * 2 = <%= @number %>
Bookmarks
|
http://www.sitepoint.com/forums/showthread.php?400470-Not-Railsy-But-How-Do-You&mode=hybrid
|
CC-MAIN-2015-35
|
refinedweb
| 202
| 84.17
|
Requirement: I have a custom desktop application and I have created an installer for it. During installation it needs to connect trough Internet to receive the key. Now I have stored these keys in a SharePoint List as given below:
The user will provide the Activation Key and Registration Number and will receive the Unlock Key to proceed with the software installation. We can use the OOB Lists.asmx web service to achieve this. The web method we are going to use is GetListItems.
I have created a Windows Application to test. Here I'll add Activation Key and Registration Number and will receive the Unlock Key.
In the application I add web reference of http://<site_url>/_vti_bin/lists.asmx with a name ListProxy.
Here is the code of my application:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
namespace TestKeyApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
private void button1_Click(object sender, EventArgs e)
ListProxy.Lists newListProxy = new ListProxy.Lists();
//change the username, password and domain with the value of a use who has permission to the list
newListProxy.Credentials = new System.Net.NetworkCredential("<username>", "<password>", "<domain>");
XmlDocument xmlDoc = new XmlDocument();
XmlNode ndQuery = xmlDoc.CreateNode(XmlNodeType.Element, "Query", "");
XmlNode ndViewFields = xmlDoc.CreateNode(XmlNodeType.Element, "ViewFields", "");
ndViewFields.InnerXml = "<FieldRef Name='Unlock_x0020_Key'/>";
ndQuery.InnerXml = "<Where><And><Eq><FieldRef Name='Activation_x0020_Key' /><Value Type='Text'>" + textBox1.Text + "</Value></Eq><Eq><FieldRef Name='Registration_x0020_Number' /><Value Type='Text'>" + textBox2.Text + "</Value></Eq></And></Where>";
try
{
XmlNode ndListItems = newListProxy.GetListItems("KeyList", null, ndQuery, ndViewFields, null, null, null);
//MessageBox.Show(ndListItems.OuterXml);
XmlNamespaceManager nsManager = new XmlNamespaceManager(ndList = ndListItems.SelectNodes("rs:data/z:row", nsManager);
foreach (XmlNode node in nodes)
{
//label4 is where I am showing the unlock key
label4.Text += node.Attributes["ows_Unlock_x0020_Key"].Value;
}
}
catch (Exception ex)
MessageBox.Show("Please Enter correct activation key and registration number, message: " + ex.Message);
}
}
PingBack from
That's a strange way to build XML. Why create some nodes as XmlNode, and other as plain text all the way? Also, when you use this kind of stuff:
"<Value Type='Text'>" + textBox1.Text + "</Value>"
what happens if user input contains reserved XML characters (such as & or <)?
There is a SharePointUtility dll used in the SharePoint SSIS Source/Destination adapters at the linked URL which will hide all of the XML and makes it pretty easy to query SharePoint lists. You can pass in the CAML query as well. It makes working with the lists easier, and if you are working on ETL transfers, the SSIS component can make things easier as well.
- Kevin I
I find your article interesting.
Currently, I am developing a SharePoint web services on Visual Studio 2008, VB.NET window form project. I successfully manage to call the GetListitem and it return xml data. The only thing I have great difficulties is <ViewFields>.
Here is my situation:
On a SharePoint site, there is a list call ABC.
ABC has ID, Package, Version and TargetLevel. On the ABC list,
ID is a counter, automaticall generate by SharePoint;
Package is a combo drop list containg all package names. The user select one package or leave it blank. Package is not mandatory;
Version is a text field;
TargetLevel is a combo drop list contaings all Target names. This is a mandatory field and user must select a TargetLevel from the combo drop list;
Lets assume that ABC has only two records which I have shown above.
On the ABC list, the there are columns all showing, ID, Package, Version and TargetLevel. The two records exists on ABC lists clearly like this:
Id Package Version TargetLevel
27809 aaa 12.12.12 target1
27808 13.13.13 target2
The package for 27808 is blank. the package for 27809 is aaa.
I use GetListItems to retrieve all records from ABC. That worked fine and the xml results will be:
Scenario #1
If I filter the query to get only 27809, the xml result will be:
Scenario #2
If I filter the query to get 27808, the xml result will be:
Id Version TargetLevel
27808 13.13.13 target2
In scenario #2. I dont know why Package column is missing. I want the xml result to return as an empty "package" column like
I use the internal name when using with ViewFields. I have retest it over and over. I am pretty sure that any records that have blank value for package will not display Package column with blank values. I dont understand why Package column disappeared when there is no data for package!
i follow the syntax at and and and
I dont know what else im missing and do you have any ideas why <ViewFields> ommit the package column?????
I would be eternity grateful if you could assist me.
Thanks.
Regards,
Mak
If you would like to receive an email when updates are made to this post, please register here
RSS
Trademarks |
Privacy Statement
|
http://blogs.msdn.com/pranab/archive/2008/11/24/sharepoint-2007-moss-wss-using-lists-asmx-getlistitems.aspx
|
crawl-002
|
refinedweb
| 838
| 60.11
|
A value class that defines the style for pen strokes. More...
#include <Wt/WPen>
A value class that defines the style for pen strokes.
A pen defines the properties of how lines (that may surround shapes) are rendered.
A pen with width 0 is a cosmetic pen, and is always rendered as 1 pixel width, regardless of transformations. Otherwized, the pen width is modified by the transformation set on the painter.
A WPen is JavaScript exposable. If a WPen is JavaScript bound, it can be accessed in your custom JavaScript code through its handle's jsRef(). At the moment, only the color() property is exposed, e.g. a pen with the color WColor(10,20,30,255) will be represented in JavaScript as:
Returns the style for rendering line ends.
Returns the pen color.
Returns the pen color gradient.
Returns the style for rendering line joins.
Returns a JavaScript representation of the value of this object.
Implements Wt::WJavaScriptExposableObject.
Comparison operator.
Returns
true if the pens are different.
Comparison operator.
Returns
true if the pens are exactly the same.
Sets the style for rendering line ends.
The cap style configures how line ends are rendered.
Sets the pen color.
Sets the pen color as a gradient.
Sets the style for rendering line joins.
The join style configures how corners are rendered between different segments of a poly-line, rectange or painter path.
Sets the pen style.
The pen style determines the pattern with which the pen is rendered.
Sets the pen width.
A pen width
must be specified using WLength::Pixel units.
Returns the pen style.
Returns the pen width.
|
https://webtoolkit.eu/wt/wt3/doc/reference/html/classWt_1_1WPen.html
|
CC-MAIN-2021-31
|
refinedweb
| 270
| 70.19
|
mini18n − translates strings
#include <mini18n.h>
const char * mini18n(const char * source);
const char * mini18n_with_conversion(const char * source, unsigned int format);
mini18n() searches for source in the currently loaded translation and returns the translated value if it’s found. In this case, the returned string points to a mini18n internal buffer and thus should not be free()’d or modified in any way. If source is not found or no translation is loaded, the source string is returned.
mini18n_with_conversion() do the same as mini18n() but also converts the returned to the specified format. Another difference is that the returned string is always converted to the format. For now the only possible value of format is MINI18N_UTF16 and is only implemented for the Windows operating system.
The translated string if successul and the source string otherwise.
|
http://man.m.sourcentral.org/ubuntu1710/3+mini18n
|
CC-MAIN-2019-47
|
refinedweb
| 135
| 54.93
|
I started thinking about a replacement, it's in org.apache.river.imp.util.
The name spaces are as follows:
net.jini.* API - must be backward compatible, or breakage minimal for if
there's a good reason.
com.sun.jini.* - implementation, subject to change.
com.artima.* - implementation, subject to change.
org.apache.river.api.* - new API under review, please feel free to look
for ways to improve before its frozen in November / December.
org.apache.river.imp.* - new implementation, subject to change,
eventually the com.* namespace will move there too.
Best bet would be to search for the classes that depend on the Task
interface, see how they use it and come up with something better.
Agreed, the Task interface is less than optimum, best to replace it.
TaskManager has been identified as a performance bottleneck.
Thanks,
Peter.
Patricia Shanahan wrote:
> Thanks. I'll ask TaskManager specific questions in this thread, and
> create a new thread for getting started questions.
>
> The main difficulty I've found so far is the runAfter method in the
> Task interface. As currently defined, it requires the runAfter caller
> to have the tasks in question as the first i elements of a List with
> efficient random access. Although get is indeed marginally faster than
> an Iterator for random access List implementations, it is
> unfortunately slow and inflexible for anything else.
>
> Is this interface something that could be changed, subject to
> corresponding changes in the callers in River, or is it an external
> interface that cannot change?
>
> In general, the design of TaskManager involves a lot of scans,
> insertions, and removals in an ArrayList. Has this caused any
> performance problems, or are the operations sufficiently infrequent
> and the number of tasks small enough for it to not be an issue?
>
> Patricia
>
> On 6/29/2010 3:50 AM, Peter Firmstone wrote:
>> Yes, river-dev is for general development discussion and questions,
>> river-commits for svn commits and jira issues which are automatically
>> posted. Developers with commit access have a private list for discussing
>> potential new committers based on merit etc, but most things are done in
>> the open.
>>
>> I believe at one stage there was tool com.sun.jini.tool.CheckCodeStyle,
>> there is a test in
>> trunk/qa/jtreg/com/sun/jini/tool/CheckCodeStyle/test.sh The test gives
>> you an idea of the code style required, however the actual tool used for
>> checking code is not present in the source.
>>
>> Fire away...
>>
>> Cheers,
>>
>> Peter.
>>
>>
>> Patricia Shanahan wrote:
>>> I've started taking a look at the code, and have questions ranging from
>>> basic building through coding conventions to details of runAfter usage.
>>>
>>> If I were joining a co-located project I would be arranging to have
>>> lunch and an informal chat with one or more of the existing developers.
>>> Is this mailing list the lunch room, or is there somewhere more
>>> appropriate?
>>>
>>> Patricia
>>>
>>
>>
>>
>
>
|
http://mail-archives.apache.org/mod_mbox/river-dev/201006.mbox/%3C4C2B200C.6050807@zeus.net.au%3E
|
CC-MAIN-2019-04
|
refinedweb
| 477
| 54.93
|
ELMAH was originally introduced with the MSDN article “Using HTTP Modules and Handlers to Create Pluggable ASP.NET Components.” The goal of the article was to demonstrate how HTTP modules and handlers can be used in ASP.NET to provide a high degree of componentization that goes just beyond the classical reuse through controls. It was not the goal of the article to discuss the implementation details of ELMAH or the background to some of its design. That is the purpose of this document in the form of technical notes and using a casual voice.
Please bear in mind that this is a “living” document that will be expanded as needed.
ELMAH provides two HTTP modules and a set of HTTP handlers that can be used as a foundation for a complete error logging, notification and display solution for web applications. You can enable ELMAH for one or more web applications or for all web applications running on a machine. All you have to do is deploy a single assembly and make changes to the configuration file. There is no need to recompile or re-deploy an application.
The primary goal of ELMAH 1.0 is to demonstrate, by way of example, how HTTP handlers and modules can be used as a very high-level form of componentization, enabling entire sets of functionalities to be developed, packaged and deployed as a single unit and independent of web applications.
Here’s how it works. There are two independent modules, called ErrorLogModule and ErrorMailModule. Both of these subscribe to the Error event of HttpApplication in order to listen for unhandled exceptions that bubble out of the main web application code. Exceptions that are handled and swallowed by anyone along the stack are never seen by these modules, including those cleared using the ClearError method on an HttpContext instance. The ErrorMailModule is the simpler of the two, so let’s talk about that one first. When it receives the Error event, it creates an e-mail message, writes out the error details in the body and sends it off to a designated address. The solution comes with a standard implementation that formats the error as an HTML document, as shown in Figure 1. You can also provide your own implementation in case you don’t like the default formatting.
This basically takes care of the notification of errors that occur in a web application. There’s a second form of notification, but I’ll talk about that a little later.
When the ErrorLogModule receives the Error event, it goes ahead and logs it to a store. The store is defined by an implementation of the abstract ErrorLog class. The solution comes with a concrete implementation for Microsoft SQL Server 2000 (see footnote 1) that resides in the SqlErrorLog class and an in-memory implementation that resides in the MemoryErrorLog class. The majority of the remaining types in the solution are a set of handlers that provide the user interface for viewing the log. Like the module, the handlers also work off an ErrorLog implementation so if you go ahead roll your own implementations over, say the file system, Microsoft Access or an Oracle database, then the handlers will work against them too. Figure 2 shows the results from one of the handlers that displays a summary of the latest errors recorded for an application.
When one of the [Detail] links is clicked, another handler is invoked that renders the details of the selected error on a separate page. Figure 3 shows one such page in action.
These days, you can’t write a web-based solution that’s considered fashionable without involving RSS in one way or another. So to be totally en vogue, one of the handlers that I’ve provided renders the last 15 errors recorded in the error log as a RSS feed. This is the second form of notification that I mentioned earlier. A sample output of the RSS feed can be seen in Figure 4.
It’s not as detailed as the mail-based counterpart, of course, but it nevertheless allows developers, administrators and operators alike to use their favorite RSS aggregator to receive most recently logged errors as news items. If your RSS aggregator also pops a toaster sort of window à la instant messengers like MSN Messenger, then the errors will really get your attention. Sometimes, e-mails can take time to make their way to your inbox as they are push through the various systems. With an RSS news aggregator, however, you are in pull mode and consequently more in control of how often a feed is polled. Either way, you’ll get a notification through a pull or push method.
So with all these modules and handlers in hand, the next question is how to use and enable them in a web application. Let’s start with a tour for enabling logging for a single application. Open the web.config for any desired web application and add the following line to the <httpHandlers> section:
" />
Copy the GotDotNet.Elmah.dll assembly to the bin folder and that’s it. At this point, you can navigate to the specified path (see footnote 2) and see a page similar to Figure 5:
Since there are no errors yet, the page is pretty much empty. If you generate an exception in your application, you still won’t see any errors here. This is because we haven’t added the logging module, so let’s do that now. Go to the <httpModules> section and add the following line:
<add name="ErrorLog" type="GotDotNet.Elmah.ErrorLogModule, GotDotNet.Elmah, Version=1.0.5527.0, Culture=neutral, PublicKeyToken=978d5e1bd64b33e5" />
If you generate an error now then the error log will display it. If you can’t think of a way to generate an exception and test the functionality then don’t worry. The solution comes with a TestException that can be generated at any time by appending /test to the path for the handlers. So in the address bar of the browser, type:
If custom errors are disabled then you should see the standard ASP.NET error page that looks like this (assuming that custom errors are off):
The difference this time is that the log also contains a record of this error so let’s check that out. Go back to error log root page (see footnote 3) and this time you should see an entry in there:
Now click on the link next to the error message to see the details of the error entry. The next page should look similar to this:
Note that in addition to the basic error information, web collections such as the server variables are also captured and displayed. Now let’s generate another exception. In this case, we’re going to make a fault in the error page handler itself. In the query string, you should see a parameter named “id” whose value is a GUID. Change it so that it no longer is a valid GUID. For example, replace the last character with an x. Not surprisingly, you should now see a FormatException:
Now let’s go back and see what’s in the log4 (see footnote 4). You should see two entries:
If you dig into the details of this new entry, you should notice something different this time:
There’s an extra link that says, “See ASP.NET error message in full view.” When you click this, you’ll see a full blown HTML page that is the exact message that ASP.NET generated at the time of the exception (see footnote 5)! This means that even if you enable custom errors in you web application (typical of when you go to production, for example), the log can capture the original message that we’ve all come to love and rely upon. Haven’t we all been there? You write a web application, deploy it to production and then you get this dreadful page:
This is the point where you wish you could see what’s going on behind. So what’s your first instinct? Go back turn off custom errors completely so you can view the message while hoping that no customer hits the web site in the same time frame in which you are troubleshooting. Now with the error log, you don’t have to worry about that anymore. If you see this page, go to the error log and get the full-blown page (see footnote 6).
So far, all the logging has been taking place in an in-memory log (see footnote 7) that does not survive application restarts or failures. In fact, if you just touch your web.config by saving it then the application will restart and you’ll notice that the log is empty again. Let’s try something more robust and reliable like using SQL Server as the store for the log. Create a new database called ELMAH and run the supplied SQL script (see footnote 8) to create the required table and related stored procedures.
These entries basically introduce new configuration elements to the runtime’s configuration system, telling it that if it sees a certain element in the configuration file, then it should use a certain IConfigurationSectionHandler implementation to process its contents. Here, <section> is adding a new section called errorLog, whose handler is in fact a factory-supplied section handler from the BCL (Base Class Library). The <sectionGroup> does exactly what its name suggests. It just introduces a grouping element. There is no handler class associated with it. If you’ve got several related sections then it’s usually a good idea to group them together. We’ll be introducing yet another section later on so that’s why the group is being defined at this time. It often helps to think of a section group as a namespace.
Now we can go ahead and configure the error log as follows:
" />
</gotdotnet.elmah>
The type attribute on errorLog specifies the class that now serves as the error log implementation (SqlErrorLog). Change the connectionString attribute as needed. With this in place, you can try to generate once more some exceptions (like the test one earlier) and see that errors are indeed logged into the database and survive the application’s lifetime.
You can also get to the RSS feed by simply appending /rss to the root of the error log’s path. Go ahead and try it against you favorite RSS news aggregator application.
Now let’s add the final piece, which is getting an e-mail upon an exception. For this, add the following module to the configuration file:
<add
name="ErrorMail"
type="GotDotNet.Elmah.ErrorMailModule, GotDotNet.Elmah, Version=1.0.5527.0, Culture=neutral, PublicKeyToken=978d5e1bd64b33e5" />
And the following section handler under the gotdotnet.elmah section group registered earlier:
<configSections>
<sectionGroup name="gotdotnet.elmah">
<section
name="errorLog"
type="System.Configuration.SingleTagSectionHandler, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<section
name="errorMail"
type="System.Configuration.SingleTagSectionHandler, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</sectionGroup>
</configSections>
The new section can now be configured as shown error:
" />
<errorMail to="john.doe@example.com" />
</gotdotnet.elmah>
The minimal setting required by the error mailing module is the recipient’s e-mail address, which is specified here using the to attribute (see footnote 9). Now if the application generates any exceptions then you should receive an e-mail in addition to it being logged in the database.
Note that all of the modules and handlers function fairly independent of each other so you can enable and disable them individually. For example, if you remove entry that registers the HTTP handler with ASP.NET then you will not be able to view the error log although logging will continue working. If you remove the entry for the logging module instead, then the log can still be viewed via the handlers but no new errors will be logged. The same is applicable for the mailing module.
Note also the error log handlers can be secured using the normal role-based security of ASP.NET. You’ll need to just use the location element on the configured path.
Up to this point, we’ve only considered a single web application. However, if you just take all the settings and drop them into the machine.config then the same facility becomes available machine-wide and to all web applications. You don’t even have to copy the assembly to the bin directory of each application since it will go in the GAC (see footnote 10). You can append elmah/default.aspx to the virtual root of any application and get its private error log (see footnote 11). The error mail facility will also be automatically available to all applications. Of course, each individual application is free to remove entries from the sections related to handlers and modules and disable the feature. In fact, a single application can even choose its own error log store by changing the connection string in its local web.config. All other settings will be just inherited from the machine configuration file. This really illustrates the awesome power of componentizing web application aspects this way and is the heart of the approach demonstrated by ELMAH. Even an Application Server Provider (ASP) could offer error logging, viewing and mailing to all hosted applications as a built-in facility without requiring any change in the hosted application code. So start thinking about how you can refactor some aspects of your web application into handlers and modules. You should aim to reach a level of componentization that allows applications to acquire some functionality by simply deploying the assembly and adding some configuration. In the next part of the article
At this stage we’re ready to dig into the implementation details, but before doing that, I’d like to make a note about the design philosophy of ELMAH as sample solution. Bear in the mind that the overall goal of ELMAH (as a sample accompanying the original article) was to demonstrate an approach to componentizing an entire aspect of a web application. It is sample code after all and such its purpose is not to provide a comprehensive solution in terms of customization. The sample tries to do a few things and do them well, even though I’ve gone to some lengths to encapsulate implementation details and provide extensibility wherever possible (see footnote 12). The accompanying code is a vastly reduced version of a full-blown solution that is being used in production applications. When trimming down the code, I had to make a lot of hard decisions about what to keep and what to cut out. In the end, the point was to provide a reference implementation of the overall idea being illustrated by the article. One size barely fits all, so you are more than welcome to take the sample as the foundation for your own version. One of the major guiding factors was that I did not want the number of classes to sprawl out of control by factoring out as many ideas into their leanest and meanest set of interfaces and protocols.
Figure 13 depicts an architectural overview of the main classes in the solution. The diagram is not based on any particular modeling system or theory. It roughly shows how the classes relate to each other and what they do using a simple, convenient and self-explanatory notation.
The Error class is a central piece of the entire error logging and mailing solution, so it’s important to understand it first. One of the problems with exceptions is that they’re good for communicating errors along the code stack and especially while the code is running, but they don’t make great candidates for logging or long-term storage purposes. Sure, they support serialization and you could just blast an exception to some storage as a binary blob, but de-serialization adds a whole number complications if you don’t have the right assemblies and types available. This makes them less portable with the containing storage. Moreover, during development, types come and go and details change, but you want the logging architecture to be rather stable and independent. You also want to be able to ship the log to another machine and view it from there. Actually, as far as the log is concerned, it should be an “informational” trace of the errors that occurred rather than trying to maintain 100% fidelity to the entire state of the exceptions.
This is where the Error class comes in. It’s a loose and abstract digest of an exception for informational purposes. Put another way, it’s the lingering “ghost” or remains of a once living and kicking exception. The Error is just a holder of properties (see footnote 13) deemed fundamental along with some state that may eventually help in diagnosing the error. An example of the latter is web collections like ServerVariables, QueryString, Form and Cookie. Some of the properties of the Error object like Source and Message correspond directly to those of an Exception. However, almost all properties are “loosely” defined (see following table). That is, the Error object does not mandate, for example, that the Type strictly reflect the type name of the Exception class (although that’s what’s done in the code). It’s really just a string that is meant to be representative of the type of error that occurred. If you want to just put the word “Script” to describe the type of the error then that’s fine. All that said, the Error object has constructors that allow you to convert an Exception into an Error. It will use the properties of the exception to most reasonably fill up the properties of the Error object. If you also provide an HttpContext instance, then it will make a copy of the web collections associated with the request for diagnostic purposes (see footnote 14).
The Error class also sports XML serialization via its ToXml and FromXml methods. Here’s an example of how it looks like (see footnote 16):
<error
application="/LM/W3SVC/1/Root/ElmahDemo"
host="ATIFA01"
type="System.IndexOutOfRangeException"
message="Index was outside the bounds of the array."
detail="..."
user="domain\johndoe"
time="2004-06-11T16:25:07.7570000+02:00"
statusCode="500"
webHostHtmlMessage="...">
<serverVariables>
<item name="ALL_HTTP">
<value string="..." />
</item>
<item name="ALL_RAW">
<value string="..." />
</item>
<item name="APPL_MD_PATH">
<value string="/LM/W3SVC/1/Root/ElmahDemo" />
</item>
<item name="APPL_PHYSICAL_PATH">
<value string="C:\Demo" />
</item>
<item name="AUTH_TYPE">
<value string="Negotiate" />
</item>
<item name="AUTH_USER">
<value string="domain\johndoe" />
</item>
<item name="AUTH_PASSWORD">
<value string="" />
</item>
<item name="LOGON_USER">
<value string="DOMAIN\johndoe" />
</item>
<item name="REMOTE_USER">
<value string="domain\johndoe" />
</item>
<item name="CONTENT_LENGTH">
<value string="0" />
</item>
<item name="CONTENT_TYPE">
<value string="" />
</item>
<!-- rest removed for brevity -->
</serverVariables>
</error>
Note that the ToXml and FromXml methods come from my own interface, namely IXmlExportable. The reason for doing this is threefold. First, IXmlSerializable is officially un-documented in .NET Framework 1.x. It becomes documented with Whidbey so this argument does not hold so strong. Second, I didn’t want to implement GetSchema. Third, I read and write the XML slightly differently. While IXmlSerializable places an extra container element around the object’s XML, I didn’t want it because it felt unnecessary. In any case, IXmlSerializable can always be implemented later in terms of IXmlExportable so this is not a big deal.
Note that when an Error object is constructed from an Exception instance, it also maintains a reference to it. This is done only for providing some fidelity at runtime. It has no consequence on logging or the XML serialization. Right now, the sample does not do any filtering based on exception types. However, if you ever wanted to add such a facility, then that’s where the Exception property would come in handy. For example, given an Error object, you could find out if it is of the class ArgumentException or not by inspecting its Exception property. You’ll notice that when the Error object is re-created from the log for displaying purposes, the Exception property is always null.
The ErrorLog class is the abstract contract for a logging store. The log is responsible for recording instances of Error and allowing them to be read back. To create a concrete implementation, one has to provide only 3 methods: Log, GetErrors and GetError. The Log method takes an Error object and is supposed to serialize it, however it whishes, to its backing store. The GetErrors method retrieves logged errors in paged result-sets. That is, you specify the page index and the count of the errors to retrieve with each call. It is supposed to read the log and return errors in their most natural order, which is defined to be from latest to earliest. Put another way, sorted on time in descending order. GetErrors is only required to retrieve a digest version of the full error that is well-suited for quick on-screen and summary listing as shown in Figure 2. The digest (light-weight) properties are defined as ApplicationName, HostName, Type, Source, Message, User, StatusCode and Time. However, a caller should be prepared to handle empty values for these properties. Finally, the GetError method retrieves an error in its entirety given its ID. Both “get” methods actually return ErrorLogEntry instances rather than the Error object directly. The purpose of the ErrorLogEntry is to bind together the log-supplied data such as the ID with the actual Error object. Note that the Id property is typed as a string but the log can internally use an integer, GUID or what have you. The only requirement is that an ErrorLog implementation can round-trip its ID through a string.
An ErrorLog implementation is expected to store and retrieve errors bound to an application name (see footnote 17) and accounts for the ApplicationName property on Error. The reasons for this will become clearer as we move along.
SqlErrorLog is an implementation of LogError for Microsoft SQL Server 2000. The implementation is fairly straight forward since most of the code has to do with calling the stored procedures in the database. No direct table access is ever done. The database has a single table called Error:
Apart from ErrorId and Sequence, an Error object is split and stored in AllXml and the remaining columns. The AlllXml column contains the full XML of Error object as it is serialized by its ToXml method. Because the Error object contains complex and hierarchical state like collections of named values, it seemed simplest to just store it as one blob item of type NTEXT. But why have the other columns? Well, remember that the Log needs to return a digest version of the error when the GetErrors method is called. It would be too expensive to de-serialize the entire object from XML only to return a piece of it. Consequently, the lightweight properties are cached away in separate columns for quicker retrieval. What’s more, having properties like Type and User readily available allows you to quickly run statistics on the table. This is not done in the solution, but you could imagine where this would be useful in a reporting extension.
The downside of this approach, of course, is that if you update values in the cached columns, then they’ll be out of sync with the corresponding values stored in the AllXml column (and vice versa). The differences will show up in the Error objects returned by the GetErrors and GetError method. Again, you are more than welcome to change the implementation details of SqlErrorLog to your liking. The rest of the solution will not be affected.
There’s actually a much more subtle reason for having this kind of approach. Notice that the Error object is not sealed. Theoretically this means that it is extensible and you can go ahead and add your own properties to be stored in the log. However, for the log implementation to be oblivious to the final type it stores and serves, it simply records the XML of the object. The FromXml and ToXml methods on the Error class are extensible for precisely this reason. My implementation of SqlErrorLog, however, does not store the type of the Error object anywhere, so if you create your own MyError class, it does not know about it. It will be able to log it with all the state, but upon retrieval, you will always get back Error instances. One of my design goals was to keep type identity information out of the logs by as much as possible. Therefore SqlErrorLog offers a protected member called NewError that serves as an overridable factory. If you subclass Error, then you also have to provide a subclass for SqlErrorLog that can serve instances of your class.
The LogError method of SqlErrorLog is the one that splits up the Error object’s properties into the cached set and the all encompassing XML column. The values are then passed as parameters to the ELMAH_LogError stored procedure that does the actual INSERT. There’s nothing else that is specially going on over here. It is worth noting that errors are never deleted in the default implementation. The exact policy of when and how to delete the errors can be enforced in the ELMAH_LogError stored procedure and right after the INSERT statement.
The GetError method of SqlErrorLog calls the related ELMAH_GetErrorXml stored procedure to get a single error identified by a GUID (see footnote 18). The stored procedure does nothing more than return the value of AllXml column from the corresponding row. On the way back, GetError simply re-creates an Error object by sending the XML to its FromXml method.
The GetError method of SqlErrorLog calls the related ELMAH_GetErrorsXml stored procedure, which returns a page of errors as XML. However, this time the XML only contains the digest properties mentioned earlier. ExecuteXmlReader is used to dig through the data and again ReadXml is used to populate Error objects that are eventually returned in a list. The use of XML in this case is just to have a lazy implementation that leverages the de-serialization infrastructure already present in the Error class. One could have easily used a data reader to read the data in a standard fashion and manually populate Error instances. Use of ExecuteXmlReader and the FOR AUTO XML in the stored procedure is really the reason for requiring SQL Server 2000, but this can be changed easily.
MemoryErrorLog is an implementation of ErrorLog that purely uses memory as its backing store. Needless to say, this log does not survive application restarts or failures, but it provides a very simple implementation that can come in handy in some hard cases where even SqlErrorLog would fail. For example, SqlErrorLog requires a complex store like a database and this assumes that an entire chain of infrastructure (network, server, database, etc.) will be fully operation in order to log exceptions in the first place. But say that even your error logging database becomes unavailable in the face of some catastrophic failure. This is where you could change your configuration file and temporarily switch to the MemoryErrorLog implementation to be able to diagnose problems albeit a volatile backing store.
The implementation of the MemoryErrorLog is fairly straightforward. It uses a static instance of a nested collection implementation to store the error entries. The static instance is, of course, bound to the application domain so it will only store and serve errors private to the application. You can initialize the log with a size parameter that specifies the maximum number of entries it will log in its store. Once the log is filled up, the older entry is dropped to make place for a new one. The default size of the log is 15, with a maximum of 500. The default should be fine for most cases, but don’t make it too big since errors will accumulate and consume memory unnecessarily. Remember, the point of this log implementation is for troubleshooting or even otherwise testing purposes.
There are only two items to mention with this implementation. First, it uses a ReaderWriterLock instance to synchronize access to the log. A writer-lock is acquired during the Log method and reader-lock during the GetError and GetErrors methods. The lock itself is a static member of the MemoryErrorLog and is initialized together with the type. The entries collection is itself initialized when the first error is logged. Until then, it has minimum footprint.
The second item to note is that the MemoryErrorLog makes defensive copies of the Error objects on the way in and out of its store (the internal collection). Since Error objects are mutable, the log clones an Error object in the Log method to maintain its own private copy and then returns yet another clone in GetError and GetErrors for the private use of the caller. I could have avoided all this extra copying by making the Error object immutable in the first place, but I decide to keep things short and simple for the article. From a more commercial-grade solution, it would be very favorable to support immutability on Error and its collections especially because it’s really not all that hard to do.
So how does the ErrorLogModule, or anyone for that matter, know which concrete implementation of the log to use? The ErrorLog class has a Default property that provides, well, the default error log implementation configured for the application. The implementation of the Default property internally calls the CreateFromConfigSection method of the SimpleServiceProviderFactory to obtain the ErrorLog instance. The job of SimpleServiceProviderFactory is to create and configure a type from the configuration at a specified configuration section. SimpleServiceProviderFactory makes three basic assumptions to succeed (see footnote 19):
The type is created using Activator.CreateInstance and via a constructor that is expected to take a single parameter typed as IDictionary. The dictionary can then be used by the type of initialize itself. For example, SqlErrorLog expects to find its connection string in there whereas the MemoryErrorLog looks for a size override.
Note that SimpleServiceProviderFactory removes the type key from the dictionary before passing it on to the type its constructing. However, it cannot do this simply on the dictionary returned by GetConfig because this is cached away by the framework and we don’t want to be modifying that version (see footnote 20). So, instead, the dictionary is cloned and then the type key is removed. This defensive copy turns out to be good idea anyhow because the SimpleServiceProviderFactory cannot assume what the type is going to do with it anyhow.
So getting back to where it all started, the Default property on ErrorLog grabs the implementation from the configuration and hangs on to it in a static member. This means that subsequent calls to return the default instance will be instantaneous. On item of interest to note here is the static member is bound to the thread and not the application domain. In other words, an independent error log instance is maintained per thread. This yields two major benefits without writing any code and yet at the expense of very little memory overhead. We don’t need to synchronize access to the static field and, even more importantly, the downstream error log implementation can be free of multi-threaded details. This is a lot like how ASP.NET also makes life easy for implementers of modules.
There's really nothing special going on in the handlers. Most of the code is basic practice for writing handlers and it's just rendering a la HtmlTextWriter. The only interesting point to mention is that, except for the RSS handler, all handlers are in fact pages. That is, they eventually inherit from the same Page class (via the ErrorPageBase) that you're used to. This provides all the benefits of a regular Web Form (ASPX page) like view state, validators and web controls so you don't necessarily have to resort to the HtmlTextWriter-style of rendering. The only thing you won't get is the dynamic compilation and the convenience of an HTML designer. I haven't employed any web controls in the solution because I didn't need anything as rich as the DataGrid or Calendar. However, inheriting from Page still makes some things just more accessible as you don't have to pass around the HttpContext object supplied to ProcessRequest.
The ErrorPageBase class serves as the base class for all the HTML content handlers. It basically provides some base convenience properties and a frame for the page layout as illustrated in Figure 14:
Note that style sheet for all pages comes from a CSS file that is as a resource in the assembly manifest.
The ErrorLogPageFactory is just a plain switch factory that is responsible for cracking the URL and returning the corresponding handler class. The factory uses the PathInfo (see footnote 21) property of HttpRequest to determine which resource is being requested.
Note how the style sheet for all pages is embedded as a resource and served using the MainfestResourceHandler class.
A lot of handlers provide no form of customization. So what do you do if you don't like how the pages are laid out? Perhaps you want to put in there some extra detail or make them more compatible for some browser. Write your own handler to view the ErrorLog. It's so easy that creating fully extensible and configurable handlers, plus the design decisions that entail them, is simply not worth the effort.
The ErrorMailModule has a very simple implementation. During the Init method, it reads the configuration section to get some basic settings like the sender address, the recipient(s) (see footnote 22), the subject line and whether to send the mail synchronously or asynchronously. Like ErrorLogModule, it subscribes to the Error event of the application.
When an unhandled error propagates to the top, the OnError handler of the module gets called by ASP.NET. There an Error object is constructed from the Exception and then either ReportErrorAsync or ReportError is called depending on the async setting from the configuration. The idea of reporting the error asynchronously is simply to prevent an operational issue from delaying the response to the user unnecessarily (see footnote 23). Asynchronous reporting is achieved by posting a worker item to the thread pool. It may have been better not to borrow a thread from the same pool used by ASP.NET to server requests but this detail can be changed by a subclass easily (see footnote 24). For the article, it illustrates the point adequately.
The workhorse of the implementation is in the ReportError method. This is where basically an e-mail is created, formatted and dispatched. A MailMessage object is created to specify the sender, recipients, format and body of the e-mail. The module is designed to focus on its job of preparing and sending a message, but the details how the body of the message is formatted with details from the Error object are isolated into a separate type, the ErrorTextFormatter.
The ErrorTextFormatter is actually an abstract base class that defines the contract that the error formatters must implement. It has a single property and method, namely MimeType and Format. The MimeType property of a mail formatter is used to set the MailFormat property of the MailMessage. ErrorMailModule only understands text/plain and text/html, both of which directly translate to MailFormat.Text and MailFormat.Html. The Format method is where the actual writing of the mail body takes place. It receives a TextWriter and an Error object as parameters. How the formatter then writes out the body is completely oblivious to the ErrorMailModule. To obtain the concrete error formatter implementation, the ErrorMailModule calls a protected virtual method named CreateErrorFormatter. In the supplied solution, there’s only the ErrorMailHtmlFormatter implementation provided and which is returned from this method. It is the one responsible for the formatting the HTML mail as shown in Figure 1.
Just before sending out the mail, the ErrorMailModule calls PreSendMail to give subclasses a last crack at the mail to be sent and the error object (see footnote 25). The default implementation checks if the Error object’s WebHostHtmlMessage has a value or not. If it does, it creates an attachment and blasts the HTML contents into it. Finally, the SendMail method gets called and whose implementation forwards the call to SmtpMail.Send from the base class library.
The main thing to note about the implementation of the ErrorMailModule class is that it uses approach of the Template Method design pattern. Rather than adding lots of configuration options, I’ve provided the workhorse of the implementation. For all customization, you can override various protected virtual members to change things that you don’t like. Here’s a summary:
|
http://code.google.com/p/elmah/wiki/TechnicalNotes
|
crawl-002
|
refinedweb
| 6,170
| 53.41
|
Having built the ICE Code Editor out into separate, reusable classes, I have learned much. Mostly I have learned that I really do not enjoy building large applications in JavaScript. I have to compile it constantly into a single downloadable file. While developing, I have to be sure to load all of the individual files in the right order. I have to be picky about the libraries that I pull in. Coding OO JavaScript is just ugly. And forget about testing. So I wonder, how easy would it be to do this in Dart?
Part of the trouble with Dart is that I really do not want to reimplement the actual editor part of ICE:
That comes from the ACE project and it way more work than I want to get into right now. But then again, there is the js-interop package—maybe that will let me interact with ACE, while still enjoying the benefits of Dart.
In the
scriptssub-directory, I create a
pubspec.yaml:
name: Testing ICE, ICE, Dart dependencies: unittest: any js: anyThen I can pub install to get:
➜ scripts git:(master) ✗ pub install Resolving dependencies... Downloading meta 0.5.0+1... Downloading browser 0.5.0+1... Downloading unittest 0.5.0+1... Downloading js 0.0.22... Dependencies installed!I start with a simple web page:
<head> <script type="application/dart" src="scripts/ice.dart"></script> <script> navigator.webkitStartDart(); </script> </head> <h1>Hello</h1>Unfortunately, even with a very simple
ice.dartscript file:
import 'dart:html'; import 'package:js/js.dart' as js; main() { var context = js.context; }I run into a slew of problems in the console of Dartium:
Uncaught ReferenceError: ReceivePortSync is not defined localhost/:54 Exception: The null object does not have a method 'callSync'. NoSuchMethodError : method not found: 'callSync' Receiver: null Arguments: [GrowableObjectArray] Stack Trace: #0 Object.noSuchMethod (dart:core-patch:1907:25) #1 _enterScope () #2 _enterScopeIfNeeded () #3 context () #4 main ()It takes me a bit to realize that I cannot use my simple
navigator.webkitStartDart(). Instead, I should rely on one of the dependencies that was installed to do this for me. So I remove that line and source
dart.jsfrom the browser package:
<head> <script src="scripts/ace/ace.js" type="text/javascript" charset="utf-8"></script> <script type="application/dart" src="scripts/ice.dart"></script> <script src="scripts/packages/browser/dart.js"></script> </head> <h1>Hello</h1>With that, I am ready to roll.
So, back in
ice.dartI tell the JavaScript context to start ACE:
import 'dart:html'; import 'package:js/js.dart' as js; main() { var context = js.context; context.ace.edit('ace'); }And it works!
Well, not entirely. The actual editor does not show up, but the ACE DOM elements are very much there. Satisfied that this seems doable, I call it a night here. I will pick back up tomorrow with actually showing the editor and maybe even doing ICE-like stuff with it.
Update figured it out. I had a typo in the
styleattribute for the ACE
<div>. This fixes the problem:
<head> <script src="scripts/ace/ace.js" type="text/javascript" charset="utf-8"></script> <script type="application/dart" src="scripts/ice.dart"></script> <script src="scripts/packages/browser/dart.js"></script> </head> <h1>Hello</h1> <div style="width:600px; height: 400px" id="ace"></div>With that, I have Dart pulling ACE into Dartium:
Day #732
|
https://japhr.blogspot.com/2013/04/using-ace-code-editor-with-dart.html
|
CC-MAIN-2018-30
|
refinedweb
| 565
| 60.82
|
I just discovered that in using pylab you can plot an array or list of number vs the list lenght by default.
Let’s say we have a list of point like [2,2,3,4,5,5,6,10, 23,45,58,42,12]
points = [2,2,3,4,5,5,6,10,23,45,58,42,12]
well to plot this you just have to
pylab.plot(points)
and this is the results:
The whole script in python
import pylab
points = [2,2,3,4,5,5,6,10,23,45,58,42,12]
pylab.plot(points)
pylab.show()
The last one is needed to show the window, which will happen automatically if you are running the script using ipython with the pylab option.
I just discovered by chance. I always thought that to plot you need x and y, but of course it’s possible to infer the x if you just one to plot only the points, cause each point in the list has a “Cartesian coordinates” embedded, i.e. [0,2];[1,2];[2,3];[3,4];… etc.
Recent Comments
|
https://blog.michelemattioni.me/tag/plotting/
|
CC-MAIN-2020-40
|
refinedweb
| 185
| 74.02
|
I work in a public place where I have to deal with NT 4.0 machines and I can't be logging in and out manually all the time so I was wondering if anyone could help me create a program that would use a username and pass to get out of the program. I am a newb to programming and on chapter 2 of Beginning C++ Game Programming.
Currently I have a makeshift program that passlocks it in fullscreen mode and doesn't display the text whilst typing the pass but you can get around it by using alt enter. Is there any way to stop that?
Heres what I have to far:
Any ideas?Any ideas?Code://Roarke Password Lock #include <iostream> #include <windows.h> #include <string> #include <stdlib.h> using namespace std; void fullscreen() {); } int main() { fullscreen(); int leave = 0; while (leave == 0) { system("CLS"); cout << "\n\tRoarkes Computer Passlock."; string user, pass; cout << "\n\nUsername: "; cin >> user; cout << "\nPassword: "; SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 0x0000); cin >> pass; SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 0x0007); if((user == "Herc" && pass == "testing") || (user == "NumBer2" && pass == "hello")) { cout << "\n\n\t\tAccepted. Thank you."<<endl; system("PAUSE"); break; } else continue; } return 0; }
Yes, I picked up the fullscreen and the hide pass from these forums.
No, it doesn't have to be portable just has to work on 95/nt4workstation/98/xp/200/me.. basically all windows. Thanks
|
https://cboard.cprogramming.com/windows-programming/74937-lockdown-program.html
|
CC-MAIN-2017-09
|
refinedweb
| 233
| 63.9
|
.pool;23 24 /**25 * PoolKeeper class allows to clean up automatically dead and26 * expired objects.27 */28 public class PoolKeeper implements Runnable {29 30 private long sleepTime; // timeout between 2 clean up31 private GenericPool pool; // the pool to clean up32 private boolean running = true;33 34 /**35 * constructor, called by GenericPool (any kind of object)36 */37 public PoolKeeper(long sleepTime, GenericPool pool) {38 this.sleepTime = sleepTime;39 this.pool = pool;40 }41 42 public void stop() {43 synchronized (this ) {44 running = false;45 }46 }47 48 /**49 * run method. allows to clean up the pool50 */51 public void run() {52 while (running && !Thread.interrupted()) {53 try {54 synchronized (this) {55 wait(this.sleepTime); // wait for timeout ms before attack56 }57 } catch (InterruptedException e) {58 break;59 }60 this.pool.cleanUp(); // clean up the Pool and reallocate objects61 }62 // release the pool.63 this.pool = null;64 }65 66 }
Java API By Example, From Geeks To Geeks. | Our Blog | Conditions of Use | About Us_ |
|
http://kickjava.com/src/org/enhydra/jdbc/pool/PoolKeeper.java.htm
|
CC-MAIN-2017-04
|
refinedweb
| 164
| 56.76
|
Introduction: Arduino Mini Spotlight
This is a mini led spotlight that I made which can be controlled by a potentiometer.
Step 1: Materials
You will need:
Arduino Uno Rev 3
Radioshack Standard Servo
Potentiometer(I used a 10k)
6v Battery Pack
Breadboard
Jumper wires
Small led Flashlight
Step 2: Attach the Potentiometer
The first step is pretty simple just attach the potentiometer as shown in the picture.
Step 3: Attaching the Servo
Attach the servo as shown in this picture.
Step 4: Attaching the Battery Pack
Attach the battery pack as shown in this picture.
Step 5: The Led Light
For this next step you can attach the led by wrapping it around the servo horn.
Step 6: CODE!!!
The code for this project is pretty simple just copy and paste this program right here and upload it into the arduino:
#include <Servo.h>
int potPin = 2;
int pos;
Servo myservo;
void setup()
{
myservo.attach(9);
}
void loop()
{
pos = analogRead(potPin);
pos = map(pos, 0, 1023, 0, 179);
myservo.write(pos);
}
Step 7: Your Done
If you made it to this step then that means your done with the project. To use this project just turn on the power, turn on the led and twist the potentiometer to move the led.
Be the First to Share
Recommendations
2 Discussions
6 years ago
Smart idea! Thanks for shearig :)
6 years ago on Introduction
Nicely done. Thanks for sharing this!
|
https://www.instructables.com/Arduino-Mini-Spotlight/
|
CC-MAIN-2020-50
|
refinedweb
| 238
| 71.75
|
For denoting windows in Architectural Work many architects use a feet and inches finished size to denote the door so a 2668 is a 2’-6" (30") by 6’-8" (78"). On drawings this is typically noted with the feet component being larger than the inches so its a big 2 small 6 big 6 small 8. Is there a way (preferably an easy way) to do this in Rhino?
Multiple font sizes in single text box
How is that done in Autocad or Revit? I can’t recall ever seeing that convention.
no idea… but I attached a screenshot of a plan i’m working with to show several examples (doors and windows) of what i’m talking about.
Feet an inches are the same size on your image, am I missing something?
If you look at any of the windows or doors you’ll see what is usually a 4 digit number - lets look at the front door just to focus on one. The front door is directly south of the stairway - you’ll see “3080 4-LITE TEMPERED” on 3 lines - the 3 is larger than the 0 and the 8 is larger than the 0 so this can be interpreted at a 3’-0" by 8’-0" doorway. All of the doors and windows have a similar nunuber 2080 for the front windows, 2680 for the coat closet, etc, etc.
Is there a particular workflow? Tagging a box of that size? or change an existing text? Block?
I’m not sure what you’re asking? As for the text, as far as I can tell you can only set the size of the font for the entire text area and can’t have different text attributes within a textbox… this has other ramifications like I wouldn’t be able to underline or italicize one word of the text within a text area… whatever text attributes I select apply to all of the text in a text block… seems like a problem to me for areas beyond my immediate need and i’m unfortunately guessing that the only option is to make a feature request but I’m hoping that its been something others have needed and there is some workaround.
This seems to be the case from what I can see.
You can set the font, bold, italic, and underline properties for individual letters and words within a text area:
I’ve achieved the different text sizes here by using different fonts - a possible work around for your original question.
-Kevin
Here’s a lighthearted solution.
Select text to create a group with the individual different size texts.
import rhinoscriptsyntax as rs import Rhino as rh import random def split(word): return [char for char in word] selText = rs.GetObject("Select Text", 512) textstr = rs.TextObjectText(selText) textH = rs.TextObjectHeight(selText) textPt = rs.TextObjectPoint(selText) sizeList = [textH, textH*.66,textH, textH*.66] charList = split(textstr) ranname = random.randint(1,1000) group = rs.AddGroup(ranname) for inx,val in enumerate(charList): vMove = rh.Geometry.Vector3d((inx*.85),0,0) tAdd = rs.AddText(val, textPt + vMove ,sizeList[inx]) groupadd = rs.AddObjectsToGroup(tAdd,group) rs.DeleteObject(selText)
Hey Kevin, do you happen to remember the 2 fonts you used for the 2nd (4086) option? That would be a suitable workaround
this is great… I haven’t started messing with scripting within python so maybe this is a good opportunity to dive in. Thanks for the code.
The larger font is “
Helvetica” and the smaller one is “
ITF Devanagari”.
I was experimenting to see how difficult it would be to modify a font to a smaller size. I made these with “
FreeSerif” and “
FeeeSans” from “
GNU FreeFonts” and copies I modified with the program “
FontForge”.
The text in this image is all in one textbox.
-Kevin
Nice tips
|
https://discourse.mcneel.com/t/multiple-font-sizes-in-single-text-box/94125
|
CC-MAIN-2020-10
|
refinedweb
| 638
| 72.36
|
You’ve got a very busy calendar today, full of important stuff to do. You worked hard to prepare and make sure all the activities don’t overlap. Now it’s morning, and you’re worried that despite all of your enthusiasm, you won’t have the energy to do all of this with full engagement.
You will have to manage your energy carefully. You start the day full of energy – E joules of energy, to be precise. You know you can’t go below zero joules, or you will drop from exhaustion. You can spend any non-negative, integer number of joules on each activity (you can spend zero, if you feel lazy), and after each activity you will regain R joules of energy. No matter how lazy you are, however, you cannot have more than E joules of energy at any time; any extra energy you would regain past that point is wasted.
Now, some things (like solving Code Jam problems) are more important than others. For the ith activity, you have a value vi that expresses how important this activity is to you. The gain you get from each activity is the value of the activity, multiplied by the amount of energy you spent on the activity (in joules). You want to manage your energy so that your total gain will be as large as possible.
Note that you cannot reorder the activities in your calendar. You just have to manage your energy as well as you can with the calendar you have.
Input
The first line of the input gives the number of test cases, T. T test cases follow. Each test case is described by two lines. The first contains three integers: E, the maximum (and initial) amount of energy, R, the amount you regain after each activity, and N, the number of activities planned for the day. The second line contains N integers vi, describing the values of the activities you have planned for today.
Output
For each test case, output one line containing “Case #x: y”, where x is the case number (starting from 1) and y is the maximum gain you can achieve by managing your energy that day.
Limits
1 ≤ T ≤ 100.
Small dataset
1 ≤ E ≤ 5.
1 ≤ R ≤ 5.
1 ≤ N ≤ 10.
1 ≤ vi ≤ 10.
Large dataset
1 ≤ E ≤ 107.
1 ≤ R ≤ 107.
1 ≤ N ≤ 104.
1 ≤ vi ≤ 107.
Sample Input
3
5 2 2
2 1
5 2 2
1 2
3 3 4
4 1 3 5
Sample Output
Case #1: 12
Case #2: 12
Case #3: 39
In the first case, we can spend all 5 joules of our energy on the first activity (for a gain of 10), regain 2 and spend them on the second activity. In the second case, we spend 2 joules on the first activity, regain them, and spend 5 on the second. In the third case, our regain rate is equal to the maximum energy, meaning we always recover all energy after each activity – so we can spend full 3 joules on each activity.
Solution
This is similar to the knapsack problem, so I tried to solve it with recursion and memoization. My solution managed to solve the small input, but it failed at the large one (the possible values of the input were too large). Anyway here’s my approach (the version below is not using memoization, as it was geared to solve the small input, so it wouldn’t be necessary):
#include <stdio.h> int ac[10]; int r, n, e; int process(int current, int pos){ int max = 0; int i; int partial; if(pos==n) return 0; if(pos>0) current+=r; if(current>e) current=e; for(i=0;i<=current;i++){ partial = i*ac[pos] + process(current-i,pos+1); if(partial>max) max = partial; } return max; } int main(){ int t,k; int i; scanf("%d",&t); for(k=0;k<t;k++){ scanf("%d %d %d",&e,&r,&n); for (i=0;i<n;i++) scanf("%d",&ac[i]); printf("Case #%d: %d",k+1,process(e,0)); if(k<t-1) printf("n"); } return 0; }
And here’s a solution from another user which solves the problem quite elegantly. It basically runs through an array of “spent energy” optimizing it according to the value to be gained on the respect tasks:
const int maxn = 10000 + 5; int N; long long E, R, v[maxn], u[maxn]; int main() { freopen("b2.in", "r", stdin); freopen("b2.out", "w", stdout); int t2; cin >> t2; for (int t1 = 1; t1 <= t2; ++t1) { printf("Case #%d: ", t1); cin >> E >> R >> N; if (R > E) R = E; for (int i = 1; i <= N; ++i) cin >> v[i]; u[1] = E; for (int i = 2; i <= N; ++i) { u[i] = R; for (int j = i - 1; j >= 1; --j) { if (v[j] >= v[i]) break; if (u[j] + u[i] <= E) { u[i] += u[j]; u[j] = 0; }else { u[j] -= E - u[i]; u[i] = E; break; } } } long long ret = 0; for (int i = 1; i <= N; ++i) ret += u[i] * v[i]; cout << ret; printf("n"); } return 0; } alright with you. Thanks!
|
https://www.programminglogic.com/google-code-jam-2013-round-1a-problem-b/
|
CC-MAIN-2020-16
|
refinedweb
| 865
| 68.1
|
First things first here's the code:
IEnumerator FadeToBlack() {
Debug.Log ("hi");
mySprite.color = GameObject.FindWithTag ("PlayerBase").GetComponent<ColourMaster> ().worldColour;
Color TempC = mySprite.color;
float speedFade = 5f;
while (mySprite.color.a > 0f) {
TempC.a -= (0.01f * speedFade);
mySprite.color = TempC;
yield return new WaitForSeconds (0.01f);
}
}
First of all, the coroutine isn't being spammed. The debug message only appears once, meaning the coroutine is only started once. After it does start, the object's sprite renderer (mySprite) has its color defined. Then some other thing are set, like a temp color variable. Then I start a while loop that runs while the alpha value is greater than 0. As TempC's alpha is lowered, mySprite.color is changed to TempC. In theory, this is supposed to lower the alpha of the sprite until it is 0. Next, the object is destroyed (a timer is elsewhere on my script and functions properly), independently of this coroutine. However, the observed effect is that the alpha value seems to pick random values every frame. Visually, this looks like the object's sprite is glitching out and flickering. Does anyone know how to fix this? Any help would be greatly appreciated.
just as a small side-node: you might want to use
mySprite.color = Mathf.Clamp01(TempC);
in line 8 to prevent the value from becoming lower than 0.
Answer by Glurth
·
Feb 03, 2018 at 11:03 PM
I suspect it has to do with something else in your project, or perhaps the way you are invoking it?
I created the following test script decrease a color's alpha, and it worked as expected. Of course, this is the ONLY script in the test project, so I know nothing ELSE is changing the color. ( I also used just a member color variable, rather than another object's sprite's color, to simplify things- so the way you select the sprite might also have something to do with your issue.) But this should be proof enough that the coroutine is being invoked, when/as expected.
public class corouttest : MonoBehaviour {
public Color aColorValue;
void Start () {
StartCoroutine(FadeToBlack());
}
IEnumerator FadeToBlack()
{
Debug.Log("hi");
// mySprite.color = GameObject.FindWithTag("PlayerBase").GetComponent<ColourMaster>().worldColour;
Color TempC = aColorValue;
float speedFade = 5f;
while (aColorValue.a > 0f)
{
TempC.a -= (0.01f * speedFade);
aColorValue = TempC;
Debug.Log("fading: " + aColorValue.a);
yield return new WaitForSeconds(0.01f);
}
}
}
Yeah you were right. I feel pretty dumb now. I have another script attached to the object in question which makes sure the objects color matches the world color. I forgot to disable it before running the coroutine. Did that and now it.
UI Text not changing color [C#]
2
Answers
Make the cube have the same color as the background every 3 seconds
0
Answers
Problem Changin Standard shader Alpha Channel
0
Answers
Change startcolor of particle system through script
1
Answer
Animation to fade alpha but retain color
2
Answers
|
https://answers.unity.com/questions/1463849/trying-to-make-sprites-alpha-decrease-to-0-in-orde.html?sort=oldest
|
CC-MAIN-2019-43
|
refinedweb
| 486
| 59.7
|
I was thrilled to see in a recent survey from zeroturnaround that Spring MVC was voted the most popular web framework for Java.
This framework is very flexible and there are dozens of ways to use it. As with all flexible frameworks that have many options, it is important to discuss common practices.
The project I have created for this blog entry uses features common in many Spring MVC applications. You will find something like this:
In controllers you will find typical Spring MVC features for mapping requests, extracting request data through annotations, data binding, file upload…
On the other hand, inside JSPs, most of the HTML is written natively (as opposed to being generated by Spring MVC tags). Moreover, the Spring MVC tag libraries do not generate any Javascript code.
We are first going to discuss how to integrate Spring MVC with jQuery and Bean Validation. We will then see how to make those JSPs less verbose.
Bean Validation?
JSR 303 Bean Validation provides a comprehensive way to declare validation rules. Here is an example:
public class DiningForm { @Pattern(regexp="\\d{16}") private String creditCardNumber; @Size(1) private String merchantNumber; @Min(0) private double monetaryAmount; @NotNull private Date date; ... }
When validation is called, an instance of DiningForm is validated against the annotations above.
From Spring 3.0, Spring MVC integrates with Bean validation for validation rules (that’s not the only way to do validation with Spring @MVC but it is obviously becoming the most common approach).
In a controller method, we can use @Valid as follows:
@RequestMapping(value="/update", method=RequestMethod.POST) public String update(@Valid DiningForm diningForm, BindingResult result) { if (result.hasErrors()) { return “rewards/edit”; } // continue on success... } }
At the JSP level, error messages can be displayed using <form:errors />:
<form:form <form:input <form:errors … </form:form>
The code above is fairly simple and works well. But it does not generate any Javascript. Consequently it does not allow partial rendering or client side validation. Let’s see how to improve that!
Adding Javascript for partial rendering
Let us consider what happens when “first name” is empty.
In the previous example, the whole page was refreshed every time the form was submitted. Here is an extract of the HTML response:
Our target is to minimize the response size. We should be able to have such response instead (using json syntax):
{"status":"FAIL","result":[{"fieldName":"firstName","message":"firstName may not be empty"}]}
Firstly, we will use a jQuery form submission to validate the form. When the form will be considered as valid, form submission will be triggered using regular HTML form submission (in that way we'll be able to redirect to a different page).
Let us first create a simple ValidationResponse class as follows:
public class ValidationResponse { private String status; private List errorMessageList; public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public List getErrorMessageList() { return this.errorMessageList; } public void setErrorMessageList(List errorMessageList) { this.errorMessageList = errorMessageList; } }
Inside the controller class, we can add an action method:
@RequestMapping(value="/user.json") public @ResponseBody ValidationResponse processForm (Model model, @Valid User user, BindingResult result ) { ValidationResponse res = new ValidationResponse(); if(!result.hasErrors()){ res.setStatus("SUCCESS"); } // … return res; }
Thanks to the @ResponseBody annotation, the returned object will be converted into JSON as explained in the diagram below:
Inside the JSP, the error message is parsed and displayed if appropriate. You can browse the Javascript code for more details.
According to progressive enhancement best practices, all Javascript code has been placed outside the HTML form. In case Javascript is disabled on a client’s browser, the form falls back into full page refresh.
Now that we have partial refresh working for validation rules, there are 2 points that still need improvement:
- This page does not look cool!
- This hello-world-style page has 100 lines already. There should be some ways to make it shorter.
Let’s make it pretty with Bootstrap
Even though this is not directly related to Spring MVC, it was hard for me to present a sample application with such a poor UI design. In case you haven’t heard of it yet, twitter Bootstrap is becoming the de facto CSS framework. Many developers love it because it allows to make an acceptable design for a website with little effort. After copying the Bootstrap CSS and images, I just need to use the Boostrap CSS classes (see the JSP source code for more details). My form now looks like this:
Using custom tags to avoid the “JSP soup” syndrome
That’s where things become really interesting: even though we have some code which is working already, it is pretty hard to read. We are mixing together HTML, Javascript, CSS and JSP Expression Language. It would be more readable if my JSP code looked something like this:
<html:form <html:inputField <html:inputField <div> <button type="submit">Save changes</button> <button type="reset">Cancel</button> </div> </html:form>
Custom tags are part of Java EE and also work great on Apache Tomcat. It is surprisingly easy to create a custom tag. Let us take a simple example with form input fields. We currently use this syntax (8 lines):
<div id="firstName"> <label>Enter your first name:</label> <div> <form:input <span> <form:errors </span> </div> </div>
Our goal is to use this instead (1 line):
<html:inputField
In the WEB-INF folder, I can create a new tag file as follows:
Its content is the following:
<%@ taglib <label>${label}</label> <div> <form:input <span><form:errors</span> </div>
Back in userForm.jsp, I just need to declare the tag folder:
<%@ taglib prefix="html" tagdir="/WEB-INF/tags/html" %>
And I can use this newly created tag as follows:
<html:inputField
Custom tags are well integrated in Eclipse/STS and I even have access to code completion:
In a similar fashion, I can also externalize the JavaScript code into a tag so I just have one line to call:
<ajax:formPartialRefresh
Conclusion
We have discussed partial rendering in form validation with Spring MVC. In just a few minutes, we have turned JSP soup into something which is much simpler and easier to understand.
You are welcome to have a look at the corresponding sample application on github.
Credits: I would like to thank my friend Nicholas Ding who worked with me on building the code samples for this blog entry.
Back
|
http://spring.io/blog/2012/08/29/integrating-spring-mvc-with-jquery-for-validation-rules
|
CC-MAIN-2013-48
|
refinedweb
| 1,064
| 51.78
|
The Kiwi project aims to automatically translate concurrent C# and F# programs into FPGA circuits for accelerated execution. I work with David Greaves at the University of Cambridge Computer Laboratory and we have a prototype system that consumes .NET bytecode and converts it into VHDL or Verilog circuit descriptions. Kiwi usually produces a sequential circuit from a multi-threaded C# program which typically implements a data-path or finite state machine. However, it would also be convenient to describe combinational circuits using C# or F# language constructs and then have an automatic way of generating the corresponding VHDL or Verilog which can then be further synthesized by vendor tools into efficient circuits. This is now possible in Kiwi.
Here’s a very simple example of a C# program that contains a method which is intended to model a combinational circuit:
using System; using Kiwi; namespace TestIf2 { static class TestIf2Class { [Hardware] [Combinational] static int TestIf2(int x, int y) { int z; if (x < y) z = 25; else z = 42; return z; } static void Main(string[] args) { int p = 17; int q = 23; int r = TestIf1(p, q); } } }
We could also have started from the F# program:
open Kiwi [<Hardware>][<Combinational>] let testif (x : int) (y : int) = if x < y then 25 else 42 let main args = let p = 17 let q = 23 let r = testif p q 0
Let’s ignore the Main method or function for now because it is not intended for hardware implementation. The custom attribute Hardware identifies a static method (or F# function) which should be converted into a circuit by Kiwi. The new Kiwi custom attribute Combinational indicates that this method should be implemented as a combinational circuit.
The Kiwi behavioural VHDL back end takes as input the compiled binary for this program and converts the IL bytecode for the TestIf2 method (or function) into a VHDL circuit model with this interface:
entity TestIf2 is port (signal x : in integer ; signal y : in integer ; signal result : out integer) ; end entity TestIf2 ;
The VHDL implementation architecture consists of a VHDL process which is sensitive to changes in x and y. This model can be simulated using a VHDL simulator like Modelsim:
The body of the process contains a transcription of the IL bytecode into VHDL behavioural descriptions. The bytecode that we start from for our synthesis flow for the C# program shown above is:
// Code size 26 (0x1a) .maxstack 2 .locals init ([0] int32 z, [1] int32 CS$1$0000, [2] bool CS$4$0001) IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: clt IL_0005: ldc.i4.0 IL_0006: ceq IL_0008: stloc.2 IL_0009: ldloc.2 IL_000a: brtrue.s IL_0011 IL_000c: ldc.i4.s 25 IL_000e: stloc.0 IL_000f: br.s IL_0014 IL_0011: ldc.i4.s 42 IL_0013: stloc.0 IL_0014: ldloc.0 IL_0015: stloc.1 IL_0016: br.s IL_0018 IL_0018: ldloc.1 IL_0019: ret
Although these statements occur in a specific order a VHDL synthesis tool can perform the appropriate dependency analysis to synthesize a circuit which is simply a comparator and multiplexor. The XST VHDL synthesizer which is a component of the Xilinx ISE tools reports the results of the synthesis as being simply a multiplexor driven by a “less” comparison:
========================================================================= HDL Synthesis Report Macro Statistics # Latches : 3 32-bit latch : 3 # Comparators : 1 32-bit comparator less : 1
The generated latches are trimmed during a later optimization phase since they contain constant values. The screenshot from the Xilinx ISE tools below shows part of the multiplexor and comparator that is synthesised from the generated VHDL.
The final implementation uses slice LUTs on a Virtex-5 FPGA:
Device Utilization Summary: Number of External IOBs 96 out of 640 15% Number of LOCed IOBs 0 out of 96 0% Number of Slice Registers 0 out of 69120 0% Number used as Flip Flops 0 Number used as Latches 0 Number used as LatchThrus 0 Number of Slice LUTS 17 out of 69120 1% Number of Slice LUT-Flip Flop pairs 17 out of 69120 1%
How does the generated circuit from the IL bytecode compare to a handwritten circuit? As an experiment we wrote a direct transcription of the original C# method (or F# function) by hand:
entity TestIf is port ( signal x : in integer ; signal y : in integer ; signal result : out integer) ; end entity TestIf ; architecture behavioural of TestIf is begin process (x, y) begin if x < y then result <= 25 ; else result <= 42 ; end if ; end process ; end architecture behavioural ;
This was then synthesized using the Xilinx ISE tools and produced an implementation with the following resource utilization:
This is exactly the same utilization (and implementation) which was obtained from the C# version.
Right now the combinational synthesis component of Kiwi still has several restrictions but I hope to continue developing it to the point where it could be used as a “macro expander” for combinational circuits expressed in C# and then elaborated into VHDL or Verilog.
the vhdl code was cleaner and easier to understand than the C# code. Seems like another useless reasearch program.
Love this project. And as for Bob comment. Lol. Seriously.
This is a great job, you can write complex C# code with OOP capabilities and let it work on FPGA hardware.Programmers with C# experience don't need to re-invent the wheel by learning VHDL.
Bravo !!!!!!!!!!!!!!!!!!!.
Please make it open source on github! Scala has one open source tool chisel.eecs.berkeley.edu for FPGA and F# has one for quantum github.com/…/Liquid.
|
https://blogs.msdn.microsoft.com/satnam_singh/2010/04/28/kiwi-synthesis-of-c-and-f-combinational-circuit-models-into-fpga-circuits/
|
CC-MAIN-2017-22
|
refinedweb
| 918
| 50.26
|
Why does InDesign create widows when you split a paragraph?NightEd-UK Mar 21, 2012 8:53 AM
Take a look at the two screen grabs. In this first one the price £48.25 fits at the end of the fourth line.
But I want to split the paragraph at that point. Look what happens when I do:
Why does it do that? As you see from the first example, the type will fit happily on the line above with the same hyphenation and justification settings. Why should splitting the paragraph make a difference?
This feature enrages every production journalist on my UK national newspaper every working day of our lives. We don't like to put minus tracking on text and the only other way I know to counteract this effect is to reduce the word space values in the justification settings for the affected paragraph (we're working in Single Line Composer, by the way – Paragraph Composer makes it even worse). Sometimes even that doesn't work without everything looking too squished. If we can't edit the text to solve the issue (and why should we if we're otherwise happy with it?) then we have to construct a fake new paragraph using fixed spaces for the indent and baseline shift to create the 1pt space we insert between pars.
The font in this example is Corporate E Bold, in case that has any bearing.
Is there any other way round this, some mystical unknown setting that turns it off? If not, was it ever fixed in later versions of InDesign? My company uses CS3 and is not likely to update it for many years.
Thanks
1. Re: Why does InDesign create widows when you split a paragraph?Eugene Tyson Mar 21, 2012 9:00 AM (in response to NightEd-UK)
Because it uses paragraph composing to adjust for the best possible spacing within a line calculated on other lines here is how it works there are two types
Adobe Single Line Composer
and
Adobe Paragraph Composer
Paragraph composer is the default - and here's the rules on how both work:
Adobe Single-Line Composer.
Some programs use single-line composition to flow text. It goes line by line through a paragraph and sets each line as well as possible using the hyphenation & justification settings. When you modify the spacing of one line then the lines above and below that are not taken into consideration. If you adjust the space within a line it can cause poor spacing on the next line, which as they say in the business - tough luck.
When you use Adobe Single-Line Composer, the following rules apply:
- Adjusting word spacing is preferred over hyphenation.
- Hyphenation is preferred over glyph spacing.
- If spacing must be adjusted, removing a space is preferred over adding a space.
Adobe Paragraph Composer
Adobe Paragraph Composer (which was called the Multi-Line Composer in previous versions) is turned on by default. It takes a broader approach to composition by taking the entire paragraph compoistion in one go. If you have a poorly spaced line it can be fixed by adjusting the spacing in the previous lines, so that the Paragraph Composer reflows the previous line.
The Paragraph Composer is has the following rules:
- The evenness of letter spacing and word spacing is the given the highest priority. The possible breakpoints is determined by how much they cause word and letter spacing to vary from the desired settings.
- Uneven spacing is preferred to hyphenation. A breakpoint that does not need a.
2. Re: Why does InDesign create widows when you split a paragraph?Eugene Tyson Mar 21, 2012 9:03 AM (in response to NightEd-UK)
As you can see in your original - the spacing is terrible in the paragraph before the split.
After you split the paragraph it realises now there is more room to move the text spacing around and does so.
You can force it back by selecting the two words at the end of the paragraph and apply a No Break
There is a GREP around somewhere to find all Widows/Runts in paragraphs and apply No Break - but I can't remember it off the top of my head.
3. Re: Why does InDesign create widows when you split a paragraph?NightEd-UK Mar 21, 2012 9:31 AM (in response to Eugene Tyson)
4. Re: Why does InDesign create widows when you split a paragraph?Peter Spier Mar 21, 2012 1:12 PM (in response to NightEd-UK)
The paragraph composer really does a much better job of calculating spacing than you can do manually, and if you start adding No Break you limit the ability of the algorithm to work properly, especially with justified text in a narrow column and no hyphens, as it seems you have.
It actually wouldn't surprise me to see a highlight in the first example for an H&J violation if you turn on the highlight inthe Compostion section of your prefs. If you want tighter text in general, you should change the justification parameters in your style.
5. Re: Why does InDesign create widows when you split a paragraph?Eugene Tyson Mar 21, 2012 3:49 PM (in response to NightEd-UK)
Yeh the No Break idea was just that, an idea. If it doesn't come back, then you can do other things, like reduce the kerning, or even worse - you could apply a horizontal scale.
All these are just ideas, and probably bad ideas. As the program calculates the space better. You could try switching to Single Line Composer (in the paragraph panel sub menu or in the Paragraph Style).
But all in all - it's adjusting for better spacing.
6. Re: Why does InDesign create widows when you split a paragraph?NightEd-UK Mar 21, 2012 4:41 PM (in response to Eugene Tyson)
Thanks very much for taking the trouble to reply, chaps, especially Eugene. Please note I did say in my original question that we're already using Single Line Composer. Hyphenation is not turned off on any of the paragraphs.
I still don't understand WHY this happens. The first four lines in my first example are fine for our purposes. Cut and paste them on top of the second example where the fifth line is a new indented paragraph and it will look perfectly OK. The price and the full point clearly fit on to the end of fourth line without changing our default justification, tracking or horizontal scale settings, which were carefully customised for our purposes after a lot of experimentation when we last changed our body font (see screen grab below). InDesign is happy with that result when the paragraph is running on below. So why don't the same four words fit any more just because a paragraph mark is applied at the end? There is no logic to it.
To give you some context, we're a tabloid paper and our stock-in-trade is editing news stories from original texts that could be 2,000 words long to maybe 120 words in the finished version. Every word and every bit of space counts and we don't have paragraphs in the paper where the last line is less then half full, let alone widows.
It seems like there's no way out of this other than to tweak the settings every time it happens, and if that's the case then some of us already know all the ways you can do this and others are so un-techy they'll never have a hope of grasping it. So if there's no simple way out, this is not so much a question as a complaint to Adobe. They are obviously not going to change anything on CS3 now, but whatever internal setting is turning these words round when you split a paragraph needs to be something you can adjust or just turn off in future versions.
There are more than 100 people in our company who curse this serious fault in the progam (and that is what it is) every single working day. It's the only significant negative we've discovered since switching from an antique version of Quark 18 months ago.
7. Re: Why does InDesign create widows when you split a paragraph?TᴀW Mar 21, 2012 4:48 PM (in response to NightEd-UK)
By the way, often applying "full justification" aka "justify all lines"
pulls a short last line back to the previous line without having to play
with any settings, such as tracking, H&J, etc.
Ariel
8. Re: Why does InDesign create widows when you split a paragraph?NightEd-UK Mar 21, 2012 6:58 PM (in response to TᴀW)
Arïel wrote:
By the way, often applying "full justification" aka "justify all lines"
pulls a short last line back to the previous line without having to play
with any settings, such as tracking, H&J, etc.
Ariel
Thank you Arïel - this appears to be the magic bullet I was looking for. Just tried it in a dozen different paragraphs and it worked every time. Only downside is that it will cause reflow problems if the text is re-edited or the geometry adjusted, but that's a small price to pay. Thank you so much.
9. Re: Why does InDesign create widows when you split a paragraph?Eugene Tyson Mar 22, 2012 2:13 AM (in response to NightEd-UK)
I still don't understand WHY this happens.
I explained it in the first post. There is logic to it - it works by calculating either line by line - or by calculating the best spacing per paragraph, depending on whether you have single line composer or paragraph composer.
In your first example the text would look awkward if the price was moved the next line - try it yourself by inserting a soft return (shift return)
In your first example, the best spacing for that line was applied.
When you entered a return, it was calculated that there would be better spacing if the number was moved to the next line.
It's always looking for the best spacing.
|
https://forums.adobe.com/thread/978152
|
CC-MAIN-2016-30
|
refinedweb
| 1,701
| 68.4
|
How to import excel data into GridView using File Upload Control?
In this article I have explained about how to read excel data and convert into dataset and bind in the Grid View. In this example I have get Excel file using file upload control. For the security reasons we are not keep the file upload client path in the server, so we need to save the excel file in to the server path then import data to dataset.
How to import excel data into GridView
Description:
I have MS excel with more than 100 records in the same time I need to import that data into SQL server. The Excel file path is choose from the Client machine using file upload control by user. After user select that file and click the submit button. Then all import data from Excel in to DataTable and then bind it in the Grid View control.
Connection strings:
In this below code I have mention two connection strings. If you have 2003 .xls format then use below code or if you have 2007.xlsx file then change connection string (I put it in comment line check in the source code)
For example I have excel file with data look like this.
I need to import that data into dataset. I use the below code for getting records.
Client side:
I placed one Grid view, File upload and Button Controls.
Server side:
using System.Data;
public partial class _Default : System.Web.UI.Page
{
DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
//Check file is available in File upload Control
if (FileUpload1.HasFile)
{
//Store file name in the string variable
string filename = FileUpload1.FileName;
//Save file upload file in to server path for temporary
FileUpload1.SaveAs(Server.MapPath(filename));
//Export excel data into Gridview using below method
ExportToGrid(Server.MapPath(filename));
}
}
void ExportToGrid(String path)
{
OleDbConnection MyConnection = null;
DataSet DtSet = null;
OleDbDataAdapter MyCommand = null;
//Connection for MS Excel 2003 .xls format
MyConnection = new OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0; Data Source='" + path + "';Extended Properties=Excel 8.0;");
//Connection for .xslx 2007 format
// MyConnection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + path + "';Extended Properties=Excel 12.0;");
//Select your Excel file
MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection);
DtSet = new System.Data.DataSet();
//Bind all excel data in to data set
MyCommand.Fill(DtSet, "[Sheet1$]");
dt = DtSet.Tables[0];
MyConnection.Close();
//Check datatable have records
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
//Delete temporary Excel file from the Server path
if(System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
}
}
Source Code Detail:
Here with I have attached source code download it and try to learn about import data from Excel To Dataset using C# and file upload control.
Front End : ASP.NET
Code Behind : C#
Output:
Conclusion:
I hope my article help to beginner for know about Import data from excel.
My gridview is not fill with that table records what I have to do now can You please tell me?
|
https://www.dotnetspider.com/resources/43010-how-import-excel-data-into-dataset-using-file.aspx
|
CC-MAIN-2019-30
|
refinedweb
| 517
| 59.6
|
A well designed application should probably support Copy and Paste. While it sounds simple, it actually entails a few features.
Copying from Your Application to Other Applications
This means that your application should offer up data formats that other applications can read. So a user should be able to copy in your application, and paste into another one. This may entail converting your internal data format into a new one that other programs will expect.
Copying from Other Applications into Your Application
This means reading other applications data formats and converting it your applications internal representation.
Copying and Pasting within Your Application or between Instances of Your Application
This entails marshaling all the data that your application needs. If a user can run multiple instances of your Application, it won't be sufficient to simply copy an instance of an object, since one instance won't have access to what is in the memory of another instances.
How Does Copy and Paste Work?
You start out by accessing the desktop's clipboard. Then, you tell that clipboard what kind of data your app can put on the clipboard, and then what kind of data your app can take off of the clipboard. Then, you right some functions to handle the following situations:
If the user selects a Copy command in your application, you tell the clipboard that data is available (but you don't actually put the data on the clipboard until the user selects paste).
If the user selects Paste in your application, you ask the clipboard for the data, and the application with the data then supplies it to the clipboard. Sometimes the application supplying the data is your application, and sometimes it is a different application.
If the user selects Paste in a different application, then the clipboard might ask your application to supply the data.
Set Up Variables
So, let's get to the code. First thing, we need to create a reference to desktop's clipboard, and also create a variable to store a reference to whatever item may be copied.
I put this in finish_initializing.I put this in finish_initializing.
self.clipboard = gtk.Clipboard()
self.clipboard_item = None
Handling the Copy Command
Then I wrote a function called "copy_menu" which is called when the user selects "Copy" fromt he menu. the first thing this function does is tells the clipboard what kinds of data is supported by passing in a list of tuples. Each tuple has a string that specifies the type, info regarding drag and drop, and a number that you can make up to specify what the type again. For Photobomb, only the strings are important. You need to use types that are commonly understood on the Linux desktop so that apps know that you can give them data they care about. I chose "UTF8_STRING" for putting strings on the clipboard, and the mime type "image/png" for images. For example, Gedit recongizes UTF8_STRING, and Gimp recognizes image/png, so Photobomb can copy data into both of those apps. Only Photobomb recognizes "PhotobombItem", of course. These strings are called "targets" in Gtk.
After specifying what data types you will support, you then tell the clipboard about those data types, along with what function to call if the user tries to paste, and what function to call when the clipboard gets cleared. Finally, the function stores a reference to the currently selected item. It's important to store this reference seperately, as the selection could change before the user pastes.
Handling Programs Pasting from PhotobombHandling Programs Pasting from Photobomb
def copy_menu(self, widget, data=None):
paste_data = [("UTF8_STRING", 0, 0),
("image/png", 0, 1),
("PhotobombItem", 0, 2)]
self.clipboard.set_with_data(paste_data, self.format_for_clipboard, clipboard_cleared)
self.clipboard_item = self.selected_item
After telling the clipboard what kind of data you can put on it, the user may try to actually Paste! If this happens, you have to figure out what kind of data they are asking for, and then put the correct kind of data onto the clipboard. To figure out what is being asked for, you check the target. This info is stored in the selectiondata argument, that gets passed in.
Putting Text on the Clipboard
When an application is asking for a string, life is really simple. Every PhotobombItem has a text property, so it's simple to simply set the text of the clipboard with this data.
Putting an Image on the ClipboardPutting an Image on the Clipboard
def format_for_clipboard(self, clipboard, selectiondata, info, data=None):
if selectiondata.get_target() == "UTF8_STRING":
self.clipboard.set_text(self.clipboard_item.text)
But what about when the app has asked to paste an image? The clipboard only supports text, so you can't paste an image, right? Actually, the contents of any binary stream or file can be converted to text, and that text can be put on the clipboard. However, you don't want to simply set the text for the clipboard, as binary data can have characters in it that will confuse a program that thinks it's a normal string. For example, when you read in a file of binary data, you can set that to a string in Python, but other programs not written in Python will probably get have errors if they try to treat it as a string type.
In fact, the clipboard will reject text that is binary data. So, if you have binary data, you need to:
- convert it into text
- set the selectiondata with the proper target
if selectiondata.get_target() == "image/png":
selectiondata.set("image/png", 8, self.image_for_item(self.clipboard_item))
Putting a PhotobombItem on the Clipboard
If an instance of Photobomb wants to paste, we need to provide enough information to create a proper PhotobombItem. A PhotobombItem knows a lot about itself, for example, it's clipping path, it's rotation, it's scale, etc... When copyng and pasting within Photobbomb or between instances of Photobomb, we don't want to lose all of that data.
So how do we paste a PhotobombItem if we can only put text on the clipboard? Python has built in support for turning objects into strings. This is called "pickling". So, in the simplest case, we could just convert the Python object to a string, put that string onto the clipboard, and then when convert it from the string back to a Python object.
So, first, import the pickle module:
import pickle
Then you can use "dumps" to dump the object to string:.
if selectiondata.get_target() == "PhotobombItem":
s = pickle.dumps(self.clipboard_item)
self.clipboard.set_text(s)
This is, unfortunately, a lot more involved. However, it works just fine:
You don't have to use pickling. For example, you could represent this dictionary in JSON instead. However, pickling is the native serialization formatting for Python, so it's easiest to use it when you can.You don't have to use pickling. For example, you could represent this dictionary in JSON instead. However, pickling is the native serialization formatting for Python, so it's easiest to use it when you can.
if selectiondata.get_target() == "PhotobombItem":
d = {"type":type(self.clipboard_item)}
d["clip"] = self.clipboard_item._clip_path
#snipped out all the other properties that need to be addeed to the dicitonary
s = pickle.dumps(d)
self.clipboard.set_text(s)
Now Photobomb can support copying and pasting into text editors, like Gedit, and image editors, such as the Gimp, as well as into Photobomb itself.
Handling Pasting in Photobomb
The essential paste function is run when the Photobomb user uses Photobomb's Paste command. This function tries to figure out if there are any interesting data types on the clipboard, and then uses them. Typically, such a function should ask for the richest and most intersting data it can handle first, and then less rich data types in order. For Photobomb, the richest data is a PhotobombItem, or course. Then an image, and then finally text. You may have noticed above that when a user pastes from a clipboard, it runs a function in some application. There is no gauruntee that these functions will be fast. For this reason, it's best to use the asyncronous "request" methods on the clipboard.
So, the paste function simply tries to figure out which is the best data type to paste, if any, and then asks the clipboard to call the correct function when the data is ready.
def paste_menu(self, widget, data=None):
targets = self.clipboard.wait_for_targets()
if "PhotobombItem" in targets:
self.clipboard.request_contents("PhotobombItem", self.paste_photobomb_item)
return
for t in targets:
if t.lower().find("image") > -1:
self.clipboard.request_image(self.paste_image)
return
for t in targets:
if t.lower().find("string") > -1 or t.lower().find("text") > -1:
self.clipboard.request_text(self.paste_text)
return
In the cases where another applications has put an image or text onto the clipboard, it's easy to use functions already built into Photobomb to paste those data types. Notice that the return functions already have all the data ready in the form of text or the pixbuf.:
def paste_text(self, clipboard, text, data=None):
self.add_new_text(text)
def paste_image(self, clipboard, pixbuf, data=None):
self.add_image_from_pixbuf(self, pixbuf)
Persisting the Clipboard ItemPersisting the Clipboard Item
def paste_photobomb_item(self, clipboard, selectiondata, data=None):
item_dict = pickle.loads(clipboard.wait_for_text())
if item_dict["type"] is PhotobombPath:
new_item = PhotobombPath(self.__goo_canvas,
item_dict["path"],
item_dict["width"], None)
#snip out all the code to handle all of the other properties
new_item.set_clip_path(item_dict["clip"])
new_item.translate(10,10)
new_item.set_property("parent", self.__root)
self.z_order.append(new_item)
self.add_undo(new_item, None)
You may have noticed that an item isn't actually put on the clipboard until the user tries to paste. This is a great optimization, because pasting complex or big things can take a lot of time, and there is no point on the user waiting for a copy command to finish if they are never going to actually paste with it. However, what if the user selects "Copy" in your app, and then quits your app? How is the item going to get pasted?
Gtk handles this by letting you "store" data on the clipboard. This can actually be used at any time in your application, but to handle this particular situation, Photobomb just includes a few lines in it's on_destroy function. This causes the desktop's clipboard to store all of the data types, so all the functions for servicing a paste command get called, and the desktop's clipboard holds onto the data as long as it needs.
def on_destroy(self, widget, data=None):
"""on_destroy - called when the PhotobombWindow is close. """
#clean up code for saving application state should be added here
paste_data = [("UTF8_STRING", 0, 0),
("image/png", 0, 1),
("PhotobombItem", 0, 2)]
self.clipboard.set_can_store(paste_data)
self.clipboard.store()
gtk.main_quit()
Could you fix up the code snippets, please? It's really, really hard to read Python code with inconsistent indenting :-(
Very great article and so informative thanks for sharing
clipping path service
You deserve a huge thanks for this wonderful post.This is really an excellent post.thanks
clipping path service provider
clipping path service
|
http://theravingrick.blogspot.com/2011/08/coding-copy-and-paste-functionality.html
|
CC-MAIN-2018-30
|
refinedweb
| 1,852
| 55.13
|
I love to organize my code, so ideally I want one class per file or, when I have non-member functions, one function per file.
The reasons are:
include
// foo.h
void foo(int n);
// bar.h
void bar(double d);
// foobar.cpp
#include <vector>
void foo(int n) { std::vector<int> v; ... }
void bar(double d) { std::vector<int> w; ... }
foobar.cpp
std::vector<int>
foo.cpp
bar.cpp
foobar.cpp
IMHO, you should combine items into logical groupings and create your files based on that.
When I'm writing functions, there are often a half a dozen or so that are tightly related to each other. I tend to put them together in a single header and implementation file.
When I write classes, I usually limit myself to one heavyweight class per header and implementation file. I might add in some convenience functions or tiny helper classes.
If I find that an implementation file is thousands of lines long, that's usually a sign that there's too much there and I need to break it up.
|
https://codedump.io/share/b4asSMwUu1mm/1/should-i-put-many-functions-into-one-file-or-more-or-less-one-function-per-file
|
CC-MAIN-2017-17
|
refinedweb
| 179
| 67.55
|
import "golang.org/x/image/font/basicfont"
Package basicfont provides fixed-size font faces.
var Face7x13 = &Face{ Advance: 7, Width: 6, Height: 13, Ascent: 11, Descent: 2, Mask: mask7x13, Ranges: []Range{ {'\u0020', '\u007f', 0}, {'\ufffd', '\ufffe', 95}, }, } }
Face is a basic font face whose glyphs all have the same metrics.
It is safe to use concurrently.
func (f *Face) Glyph(dot fixed.Point26_6, r rune) ( dr image.Rectangle, mask image.Image, maskp image.Point, advance fixed.Int26_6, ok bool)).
Package basicfont imports 3 packages (graph) and is imported by 14 packages. Updated 2017-10-13. Refresh now. Tools for package owners.
|
https://godoc.org/golang.org/x/image/font/basicfont
|
CC-MAIN-2017-43
|
refinedweb
| 101
| 71.92
|
(@bind_values);
;
$rv = $sth->rows;
$rc = $dbh->commit; $rc = $dbh->rollback;
$sql = $dbh->quote($string);
$rc = $h->err; $str = $h->errstr; $rv = $h->state;
$rc = $dbh->disconnect;
This is the DBI specification that corresponds to the DBI version 1.13 ($Date: 1999/07/13 14:58:32 $).
The DBI specification is evolving at a steady pace so it.
Extensions to the DBI and other DBI related modules use the
DBIx::*
namespace. See Naming Conventions and Name Space E.g., "dbi:Driver(RaiseError=>1,Taint=>1,AutoCommit=>0):dbname"
Added $h->{Taint}, $sth->{NAME_uc} and $sth->{NAME_lc} attributes.
The DBI is a database access module for the Perl Language. It defines a set of methods, variables and conventions that provide a consistent database interface independant of the actual database being used.
It is important to remember that the DBI is just an interface. A layer of 'glue' between an application and one or more Database Driver modules. It is the driver modules which do the real work. The DBI provides a standard interface and framework for the drivers to operate within.
|<- Scope of DBI ->| .-. .--------------. .-------------. .-------. | |---| XYZ Driver |---| XYZ Engine | | Perl | | | `--------------' `-------------' | script| |A| |D| .--------------. .-------------. | using |--|P|--|B|---|Oracle Driver |---|Oracle Engine| | DBI | |I| |I| `--------------' `-------------' | API | | |... |methods| | |... Other drivers `-------' | |... `-'
The API is the Application Perl-script (or Programming) Interface. The call interface and variables provided by DBI to perl scripts. The API is implemented by the DBI Perl extension.
The DBI 'dispatches' the method calls to the appropriate Driver for actual execution. The DBI is also responsible for the dynamic loading of Drivers, error checking/handling and other duties..
First you need to load the DBI module:
use DBI;
(also adding
use strict; is.
The DBI allows an application to `prepare' statements for later execution. A prepared statement is identified by a statement handle. We'll call the perl variable ;;
The DBI does not have a concept of a `current session'. Every session has a handle object (i.e., a $dbh) returned from the connect method and that handle object is used to invoke database related methods..
Character sets: Most databases which understand character sets have a default global charset and text stored in the database is, or should be, stored in that charset (if it's,
e.g., a single
$sth (though some drivers do support this)..
The DBI package and all packages below it DBI::* are reserved for use by the DBI. Extensions and related modules use the
DBIx::
namespace. Package names beginning with DBD:: are reserved for use by DBI database drivers. All environment variables
used by the DBI or DBD's, SQL92 etc (portable) MixedCase DBI API (portable), underscores are not used. lower_case Driver or).
Driver Specific Prefix Registry:
ora_ DBD::Oracle ing_ DBD::Ingres odbc_ DBD::ODBC syb_ DBD::Sybase db2_ DBD::DB2 ix_ DBD::Informix f_ DBD::File csv_ DBD::CSV file_ DBD::TextFile xbase_ DBD::XBase solid_ DBD::Solid proxy_ DBD::Proxy msql_ DBD::mSQL mysql_ DBD::mysql
Some drivers support Placeholders and Bind Values. These drivers allow a database statement to contain placeholders, sometimes called parameter markers, that indicate values.
Performance
Without using placeholders, the insert statement above would have to contain the literal values to be inserted and (?, ?, ?) }) || die $dbh->errstr; while (<>) { chop; my ($product_code, $qty, $price) = split /,/; $sth->execute($product_code, $qty, $price) || die $dbh->errstr; } $dbh->commit || for more details.
See bind_column for a related method used to associate perl variables with the output columns of a select statement.
Most DBI drivers require applications to use a dialect of SQL (the Structured Query Language) to interact with the database engine. These links provide useful information and further links about SQL, the first is a good tutorial with much useful information and many links:.
For an interesting diversion on the real history of RDBMS and SQL, from the people who made it happen, see
Follow the ``And the rest'' and ``Intergalactic dataspeak'' links for the SQL history.
$dbh = DBI->connect($data_source, $username, $password) || die $DBI::errstr; $dbh = DBI->connect($data_source, $username, $password, \%attr) || die $DBI::errstr;
Establishes a database connection, or:'.
The driver_name part., data_source prefix is
'dbi::') the environment variable DBI_DRIVER is used. If neither variable
is set then the connect dies.
Examples of
$data_source values:, the last example above.)
If the environment variable DBI_AUTOPROXY is defined (and the driver in
$data_source is not 'Proxy') then the connect request will
automatically be changed to:
dbi:Proxy:$ENV{DBI_AUTOPROXY};dsn=$data_source
and passed to the DBD::Proxy module. DBI_AUTOPROXY would typically be ``hostname=...;port=...''. See DBD::Proxy for more details.
If
$username or
$password are undefined (rather than just empty) then the DBI will substitute the values of the
DBI_USER and DBI_PASS environment variables respectively. The DBI will warn
if the environment variables are not defined. The use of the environment
for these values is not recommended for security reasons. The mechanism is
primarily on (see AutoCommit and PrintError for more information). However, it is strongly recommended that AutoCommit is explicitly defined as required rather than rely on the default. Future versions of the DBI may issue a warning if AutoCommit is not explicitly defined.
The \%attr parameter can be used to alter the default settings of the PrintError, RaiseError, AutoCommit and other attributes. For example:
$dbh = DBI->connect($data_source, $user, $pass, { PrintError => 0, AutoCommit => 0 });
You can also define connection attribute values within the
$data_source parameter. For example
dbi:DriverName(PrintError=>0,Taint=>1):...
Individual attributes values specified in this way take precedence over any conflicting values specified via the \%attrib parameter to connect().
Portable applications should not assume that a single driver will be able to support multiple simultaneous sessions. Though most do..
$dbh = DBI->connect_cached($data_source, $username, $password) || die $DBI::errstr; $dbh = DBI->connect_cached($data_source, $username, $password, \%attr) || die $DBI::errstr;
Like connect except that the database handle returned will be stored in a hash
associated with the given parameters. If another call is made to
connect_cached with the same parameter values then the corresponding cached
$dbh will be returned, without
contacting the data source, so long as it is still ok. If the cached database handle has been disconnected or the
ping() method fails then it will be replaced with a new
connection.
Note that the behaviour of this method differs in several respects from the behaviour of the presistent connections implemented by Apache::DBI.
This caching can be useful in some applications but it can also cause problems and should be used with care. The exact behaviour of this method is liable to change. If you intend to use it in any production applications your should discuss your needs in the dbi-users mailing list.
The cache can be accessed (and cleared) via the CachedKids attribute.
_filename)
DBI trace information can be enabled for all handles using this DBI class method. To enable trace information for a specific handle use the similar $h->trace method described elsewhere.
Trace Levels:
0 - trace disabled. 1 - trace DBI method calls returning with results. 2 - trace method entry with parameters and exit with results. 3 - as above, adding some high-level information from the driver also adds some internal information from the DBI. 4 - as above, adding more detailed information from the driver also includes DBI mutex information when using threaded perl. 5 and above - as above but with more and more obscure information. $h->trace() and $h->trace_msg() methodd and DEBUGGING for information about the DBI_TRACE environment variable.
$str = DBI::neat($value, $maxlen);
Return a string containing a neat (and tidy) representation of the supplied value.
Strings will be quoted (but internal quotes will not be escaped). Values known to be numeric will be unquoted. Undefined (NULL) values will be shown as
undef (without quotes)..
These attributes are always associated with the last handle used.'.
If in any doubt, use the corresponding method call.
Equivalent to $h->err.
Equivalent to $h->errstr.
Equivalent to $h->state.
Equivalent to $h->rows. Please refer to the rows method documentation.
$rv = $h->err;
Returns the native database engine error code from the last driver function called. The code is typically an integer but you should not assume that.
If you need to test for individual errors and have your program be portable to different database engines, then you'll need to determine what the corresponding error codes are for all those engines and test for all of them.
$str = $h->errstr;
Returns the native database engine error message from the last driver function called.
$str = $h->state;
Returns an error code in the standard SQLSTATE five character format. Note
that the specific success code
00000 is translated to
0
(false). If the driver does not support SQLSTATE, and most don't, 0 to disable the trace. DBI->trace() method and DEBUGGING for information about the DBI_TRACE environment variable.
$h->trace_msg($message_text); $h->trace_msg($message_text, $min_level);
Writes
$message_text to trace file if trace is enabled for
$h or for the DBI as a whole. Can also be
called as DBI->trace_msg($msg). See trace.
If
$min_level is defined then the message is output only if
the trace level is equal to or greater than that level.
$min_level defaults to 1.
$h->func(@func_arguments, $func_name);
The func method can be used to call private non-standard and non-portable methods implemented by the driver. Note that the function name is given as the last argument.
This method is not directly related to calling stored procedures. Calling stored procedures is currently not defined by the DBI. Some drivers, such as DBD::Oracle, support it in non-portable ways. See driver documentation for more details. is fatal, except for private driver specific attributes (which all have names starting with a lowercase letter).
Example:
$h->{AttributeName} = ...; # set/write ... = $h->{AttributeName}; # get/read
Enables useful warnings for certain bad practices. Enabled by default. Some
emulation layers, especially those for perl4 interfaces, disable warnings.
Since warnings are generated using the perl
warn() function
they can be intercepted using the perl $SIG{__WARN__} hook.
True if the handle object is 'active'. This is rarely used in applications. The exact meaning of active is somewhat vague at the moment. For a database handle it typically means that the handle is connected to a database ($dbh->disconnect should set Active off). For a statement handle it typically means that the handle is a select that may have more data to fetch ($dbh->finish or fetching all the data should set Active off).
For a driver handle, Kids is the number of currently existing database handles that were created from that driver handle. For a database handle, Kids is the number of currently existing statement handles that were created from that database handle.
Like Kids (above), but only counting those that are Active (as above).
For a database handle, returns a reference to the cache (hash) of statement handles created by the prepare_cached method. For a driver handle, it would return a reference to the cache (hash) of statement handles created by the connect_cached method.
Used by emulation layers (such as Oraperl) to enable compatible behaviour in the underlying driver (e.g., DBD::Oracle) for this handle. Not normally set by application code.
This attribute can be used to disable the database related effect of DESTROY'ing. For a database handle, this attribute does not disable an explicit call to the disconnect method, only the implicit call from DESTROY.
This (except for old-style connect usage, see connect for more details).
If desired, the warnings can be caught and processed using a $SIG{__WARN__} handler or modules like CGI::Carp and CGI::ErrorWrap.
This attribute can be used to force errors to raise exceptions rather than
simply return error codes in the normal way. It defaults to off. When set
on, any method which results in an error occuring will cause the DBI to
effectively do a
die(``$class
$method failed:
$DBI::errstr'') where
$class is the driver class and
$method is the name of the method which failed. E.g.,
DBD::Oracle::db prepare failed: ... error text here ...
If PrintError is also on then the PrintError is done before the RaiseError unless no __DIE__ handler has been defined, in which case PrintError is skipped since the die will print the message.
If you want to temporarily turn RaiseError off (inside a library function that is likely to fail for example), the recommended way is like this:
{ local $h->{RaiseError} =.
This attribute can be used to control the trimming of trailing space characters from fixed width character (CHAR) fields. No other field types are affected, even where field values have trailing spaces..
This attribute may be used to control the maximum length of 'long' ('blob', 'memo' etc.) fields which the driver will read from the database automatically when it fetches each row of data. The LongReadLen attribute only relates to fetching/reading long values it is not involved in inserting/updating them.
A value of 0 means don't automatically fetch any long data (fetch should return undef for long fields when LongReadLen is 0).
The default is typically 0 (zero) bytes but may vary between drivers. Applications fetching long fields should set this value to slightly larger than the longest long field value which will be fetched.
Some databases return some 'long' types encoded as pairs of hex digits. For these types LongReadLen relates to the underlying data and not the doubled-up length of the encoded string.
Changing the value of LongReadLen for a statement handle after it's been
prepare()'d will typically have no effect so it's usual to set LongReadLen on the
$dbh before calling
prepare.
Note that the value used here has a direct effect on the memory used by the application, so don't be too generous. It's also a good idea to use values which are just smaller than a power of 2, e.g., 2**16-2 which is 65534 bytes.
See LongTruncOk about truncation behaviour..
If this attribute it set to some true value and Perl is running in taint
mode (e.g., started with the
-T option), then a) all data fetched from the database is tainted, and.
Currently only fetched data is tainted. It is likely that the results of other DBI method calls, and the value of fetched attributes, will also be tainted in future versions. That change may well break your applications unless you take great care now. If you use DBI Taint mode, please report your experience and any suggestions for changes.
The DBI provides a way to store extra information in a DBI handle as 'private' attributes. The DBI will allow you to store and retreive any attribute which has a name starting with 'private_'. It is strongly recommended that you use just one private attribute (e.g., use a hash ref) and give it a long and unambiguous name that includes the module or application that the attribute relates to (e.g., 'private_YourFullModuleName_thingy').
. (or undef in scalar context).
references to arrays for each row of data fetched..
$sth = $dbh->prepare($statement) || die $dbh->errstr; $sth = $dbh->prepare($statement, \%attr) || die $dbh->errstr;
Prepares a single statement for later execution by the database engine and returns a reference to a statement handle object.
The returned statement handle can be used to get attributes of the statement and invoke the execute method. See Statement Handle Methods.
Note that prepare should never execute a statement, even if it is not a select statement, it only prepares it for execution. (Having said that, some drivers, notably Oracle 7, be used with the DBI.
$sth = $dbh->prepare_cached($statement) $sth = $dbh->prepare_cached($statement, \%attr) $sth = $dbh->prepare_cached($statement, \%attr, $allow_active)
Like prepare except that the statement handle returned will be stored in a hash
associated with the $dbh. If another call is made to prepare_cached with
the same parameter values then the corresponding cached
$sth will be returned without
contacting the database server.
This caching can be useful in some applications but it can also cause
problems and should be used with care. A warning will be generated if the
cached
$sth being returned is active (i.e., is a select that
may still have data to be fetched) unless
$allow_active is
true. Quote and Quote-like Operators.', it is undefined.
Generally if you want your changes to be commited or rolled back when you disconnect then you should explicitly call commit or rollback before disconnecting.. Individual drivers should implement this function in the most suitable manner for their database engine.
The default implementation currently always returns true without actually
doing anything. Actually it returns ``
0E0'' which is true but zero. That way you can tell if the return value is
genuine or just the default.
Very few applications would have any use for this method. See the specialist Apache::DBI module for one example usage.
Warning: This method is experimental and may change or disappear.
$sth = $dbh->table_info;
Returns an active statement handle that can be used to fetch information about tables and views that exist in the database.
The handle has at least the following fields in the order show below. Other fields, after these, may also be present.
TABLE_CAT: Table catalogue identifier. NULL (undef) if not applicable to data source (usually the case). Empty if not applicable to the table.
TABLE_SCHEM: The name of the schema containing the TABLE_NAME value. NULL (undef) if not applicable to data source. Empty if not applicable to the table.
TABLE_NAME: Name of the table (or view, synonym, etc)..
For more detailed information about the fields and their meanings, you can refer to:
Warning: This method is experimental and may change or disappear.
.
Warning: This method is experimental and may change or disappear.
., NUM_PREC_RADIX => 15, }, [ 'VARCHAR', SQL_VARCHAR, undef, "'","'", undef,0, 1,1,0,0,0,undef,1,255, undef ], [ 'INTEGER', SQL_INTEGER, undef, "", "", undef,0, 0,1,0,0,0,undef,0, 0, 10 ], ];
Note that more than one row may have the same value in the DATA_TYPE field if there are different ways to spell the type name and/or there are varients. The index values shown above (e.g., NULLABLE => 6) are for illustration only. Drivers may define the fields with a different order.
This method is not normally used directly. The type_info method provides a more useful interface to the data.
Warning: This method is experimental and may change or disappear.
list is ordered by DATA_TYPE first and then by how closely each type maps to the corresponding ODBC SQL data type, closest first.
The keys of the hash follow the same letter case conventions as the rest of the DBI (see Naming Conventions and Name Space). The following items should exist:
Data type name for use in CREATE TABLE statements etc.
SQL data type number.
For numeric types this is either the total number of digits (if the NUM_PREC_RADIX value is 10) or the total number of bits allowed in the column (if NUM_PREC_RADIX is 2).
For string types this is the maximum size of the string in bytes.
For date and interval types this is the maximum number of characters needed to display the value.
Characters used to prefix a literal. Typically ``''' for characters, possibly ``0x'' for binary values passed as hex. NULL (undef) is returned for data types where this is not applicable.
Characters used to suffix a literal. Typically ``''' for characters. NULL (undef) is returned for data types where this is not applicable.
Parameters for a data type definition. For example, CREATE_PARAMS for a DECIMAL would be ``precision,scale''. For a VARCHAR it would be ``max length''. NULL (undef) is returned for data types where this is not applicable.
Indicates whether the data type accepts a NULL value: 0 = no, 1 = yes, 2 = unknown.
Indicates whether the data type is case sensitive in collations and comparisons.
Indicates how the data type can be used in a WHERE clause:
0 - cannot be used in a WHERE clause 1 - only with a LIKE predicate 2 - all comparison operators except LIKE 3 - can be used in a WHERE clause with any comparison operator
Indicates whether the data type is unsigned. NULL (undef) is returned for data types where this is not applicable.
Indicates whether the data type always has the same precision and scale (such as a money type). NULL (undef) is returned for data types where this is not applicable.
Indicates whether a column of this data type is automatically set to a unique value whenever a new row is inserted. NULL (undef) is returned for data types where this is not applicable.
Localised version of the TYPE_NAME for use in dialogue with users. NULL (undef) is returned if a localised name is not available (in which case TYPE_NAME should be used).
The minimum scale of the data type. If a data type has a fixed scale then MAXIMUM_SCALE holds the same value. NULL (undef) is returned for data types where this is not applicable.
The maximum scale of the data type. If a data type has a fixed scale then MINIMUM_SCALE holds the same value. NULL (undef) is returned for data types where this is not applicable.
The radix value of the data type. For approximate numeric types this contains the value 2 and COLUMN_SIZE holds the number of bits. For exact numeric types this contains the value 10 and COLUMN_SIZE holds the number of decimal digits. NULL (undef) is returned for data types where this is not applicable.
For more detailed information about these fields and their meanings, you can refer to:
The individual data types are described here:
\n");
For most database types quote would return
'Don''t' (including the outer quotation marks).
An undefined
$value value will be returned as the string NULL
(without quotation marks) to match how NULLs are represented in SQL.
If
$data_type is supplied it is used to try to determine the
required quoting behaviour by using the information returned by type_info. As a special case, the standard numeric types are optimised to return
$value without calling type_info.
Quote will probably not be able to deal with all possible input (such as binary data or data containing newlines) and is not related in any way with escaping or quoting shell meta-characters. There is no need to quote values being used with Placeholders and Bind Values.
This section describes attributes specific to database handles.
Changes to these database handle attributes do not affect any other existing or future database handles.
Attempting to set or get the value of an unknown attribute is fatal, except for private driver specific attributes (which all have names starting with a lowercase letter).
Example:
$h->{AutoCommit} = ...; # set/write ... = $h->{AutoCommit}; # get/read called commit automatically after every successful database operation. In other words, calling commit or rollback explicitly while AutoCommit is on would be ineffective because the changes would have already been commited.
Changing AutoCommit from off to on should issue a commit in most drivers.
Changing AutoCommit from on to off should have no immediate effect..
* Database in which a transaction must be explicitly started
For these database the intention is to have them act like databases in which a transaction is always active (as described above).
To do this the DBI driver will automatically begin a transaction when AutoCommit is turned off (from the default on state) and will automatically begin another transaction after a commit or rollback.
In this way, the application does not have to treat these databases as a special case.
See disconnect for other important notes about transactions.
Holds the handle of the parent Driver. The only recommended use for this is to find the name of the driver using
$dbh->{Driver}->{Name}
Holds the 'name' of the database. Usually (and recommended to be) the same as the ``dbi:DriverName:...'' string used to connect to the database but with the leading ``dbi:DriverName:'' removed.
A hint to the driver indicating the size of local row cache the application would like the driver to use for future select statements. If a row cache is not implemented then setting RowCacheSize is ignored and getting the value returns undef.) a value with a placeholder);
Note that the
? is not enclosed in quotation marks even when the placeholder represents a
string. Some drivers also allow
:1,
:2
etc and
:name style placeholders in addition to
? but their use is not portable. Undefined bind values or
undef are be used to indicate null values.
Some drivers do not support placeholders.
With most drivers placeholders can't be used for any element of a statement that would prevent the database server validating the statement and creating a query execution plan for it. For example:
"select name, age from ?" # wrong (will probably fail) "select name, ? from people" # wrong (but may not 'fail')
Also, placeholders can only represent single scalar values, so this statement, for example, won't work as expected for more than one value:
"select name, age from people where name in (?)" # wrong this common case, the data type can be passed directly inplace of the attr hash reference. This example is equivalent to the one above:
$sth->bind_param(1, $value, SQL_INTEGER);
The TYPE value indicates the standard (non-driver-specific) type for this parameter. To specify the driver-specific type the driver may support a driver-specific attribute, e.g., { ora_type => 97 }. The data type for a placeholder.
As an alternative to specifying the data type in the bind_param call, you can let the driver pass the value as the default type (VARCHAR) then use an SQL function to convert the type within the statement. E.g.,
insert into price(code, price) values (?, convert(money,?))
The convert function used here is just an example. The actual function and syntax will vary between different databases (and so is obviously non-portable).
See also Placeholders and Bind Values for more information.
$rc = $sth->bind_param_inout($p_num, \$bind_value, $max_len) || die $sth->errstr; $rv = $sth->bind_param_inout($p_num, \$bind_value, $max_len, \%attr) || ... $rv = $sth->bind_param_inout($p.
Note that unlike bind_param, the
$bind_value variable is not
read when bind_param_inout is called. Instead, the value in the variable is
read at the time execute is called.
The additional
$max_len parameter specifies the minimum amount
of memory to allocate to
$bind_value for the new value. If the
value.
Undefined values or
undef are be used to indicate null values. See also Placeholders and Bind Values for more information.
$rv = $sth->execute || die $sth->errstr; $rv = $sth->execute(@bind_values) || then fetchrow_arrayref returns an undef. You should check $sth->err afterwards (or use the RaiseError attribute) to discover if the undef returned was due to an error. then fetchrow_array returns an empty list. You should check $sth->err afterwards (or use the RaiseError attribute) to discover if the empty list returned was due to an error.
then fetchrow_hashref returns an undef. You should check $sth->err afterwards (or use the RaiseError attribute) to discover if the undef returned was due to an error..
$tbl_ary_ref = $sth->fetchall_arrayref; $tbl_ary_ref = $sth->fetchall_arrayref( $slice_array_ref ); $tbl_ary_ref = $sth->fetchall_arrayref( $slice_hash_ref );
The fetchall_arrayref method can be used to fetch all the data to be returned from a prepared and executed statement handle. It returns a reference to an array which contains one reference per row.
If there are no rows to return,. ref. If the parameter hash is not empty then it is used as a slice to select individual columns by name. The names should be lower case regardless of the letter case in $sth->{NAME}. The values of the hash should be set to 1.
For example, to fetch just the first column of every row very specific situations in order to allow the server to free up resources currently being held (such as sort buffers).
When all the data has been fetched from a select statement the driver should automatically call finish for you. So you should not normally need to call it explicitly.,.
$rv = $sth->rows;
Returns the number of rows affected by the last row affecting command, or -1 if not known or not available..
$rc = $sth->bind_col($column_number, \$var_to_bind);.
$rc = $sth->bind_columns(@list_of_refs_to_vars_to_bind);
Calls bind_col for each column of the select statement. You do not need to bind columns but it can be useful for some applications. The bind_columns method will die if the number of references does not match the number of fields.
For maximum portability between drivers, bind_columns should be called after execute., if the first parameter is undef or a hash reference it will be ignored.
which uses neat which formats and edits the string for reading by humans, it's not recomended for data transfer applications.
This section describes attributes specific to statement handles. Most of these attributes are read-only.
Changes to these statement handle attributes do not affect any other existing or future statement handles.
Attempting to set or get the value of an unknown attribute is fatal, except for private driver specific attributes (which all have names starting with a lowercase letter).
Example:
... = $h->{NUM_OF_FIELDS}; # get/read
Note that some drivers cannot provide valid values for some or all of these attributes until after $sth->execute has been called.
See also finish for the effect it may have on some attributes.
Number of fields (columns) the prepared statement will return. Non-select statements will have NUM_OF_FIELDS == 0.
The number of parameters (placeholders) in the prepared statement. See SUBSTITUTION VARIABLES below for more details.";
Like NAME but always returns lowercase names.
Like NAME but always returns uppercase names.
Returns a reference to an array of integer values for each column. The value indicates the data type of the corresponding column. in ranges (see type_info_all).
Returns a reference to an array of integer values for each column. For nonnumeric columns the value generally refers to either the maximum length or the defined length of the column. For numeric columns the value refers to the maximum number of significant digits used by the data type (without considering a sign character or decimal point). Note that for floating point types (REAL, FLOAT, DOUBLE) the 'display size' can be up to 7 characters greater than the precision (for the sign + decimal point + the letter E + a sign + 2 or 3 digits).
Returns a reference to an array of integer values for each column. NULL (undef) values indicate columns where scale is not applicable.
Returns a reference to an array indicating the possibility of each column returning a null: 0 = no, 1 = yes, 2 = unknown.
print "First column may return NULL\n" if $sth->{NULLABLE}->[0];
Returns the name of the cursor associated with the statement handle if
available. If not available or the database driver does not support the
"where current of ..." SQL syntax then it returns undef.
Returns the statement string passed to the prepare method.
If the driver supports a local row cache for select statements then this attribute holds the number of un-fetched rows in the cache. If the driver doesn't, then it returns undef. Note that some drivers pre-fetch rows on execute, others wait till the first fetch.
See also the RowCacheSize database handle attribute.
Transactions are a fundamental part of any robust database system. They protect against errors and database corruption by ensuring that sets of related changes to the database take place in atomic (indivisible, all-or-nothing) units..
When trying to insert long or binary values, placeholders should be used since there are often limits on the maximum size of an (insert) statement and the quote method generally can't cope with binary data. See Placeholders and Bind Values.
Here's a complete example program to select and fetch some data:
my $dbh = DBI->connect("dbi:DriverName:db_name", $user, $password) || die "Can't connect to $data_source: $DBI::errstr";
my $sth = $dbh->prepare( q{ SELECT name, phone FROM mytelbook }) || die "Can't prepare statement: $DBI::errstr";
my $rc = $sth->execute ||>) { chop; my ($name, $phone) = split /,/; $sth->execute($name, $phone); } close FH;
$dbh->commit; $dbh->disconnect; Quote and Quote-like Operators for more details.
Perl versions 5.004_50 and later support threads on many platforms. The DBI should build on these platforms but currently has made no attempt to be thread safe.
The first thing to say is that signal handling in Perl is currently not safe. There is always a small risk of Perl crashing and/or core dumping when, or after, handling a signal. (The risk was reduced with 5.004_04 but is still present.)
The two most common uses of signals in relation to the DBI are for
canceling operations when the user types Ctrl-C (interrupt), and for
implementing a timeout using
alarm() and $SIG{ALRM}.
To assist in implementing these operations the DBI provides a
cancel
method for statement handles. The cancel method should abort the current
operation and is designed to be called from a signal handler.
However, it must be stressed that: a) few drivers implement this at the moment (the DBI provides a default method that just returns undef),).
In addition to the trace method you can enable the same trace information by setting the DBI_TRACE environment variable before starting perl.. If the name beings with a number followed by an
equals (
=) then they are stripped off from the name and the number is used to set
the trace level. For example:
DBI_TRACE=3=dbitrace.log perl your_test_script.pl
See also the trace method.
(This section needs more words about causes and remedies.)
The
$dbh handle you're using to call prepare is probably
undefined because the preceeding connect failed. You should always check
the return status of DBI methods, or use the RaiseError attribute.
The
$sth handle you're using to call execute is probably
undefined because the preceeding prepare failed. You should always check
the return status of DBI methods, or use the RaiseError attribute.
SQL Language Reference Manual.
Programming the Perl DBI, by Alligator Descartes and Tim Bunce. Due to be published by O'Reilly September/October 1999.:
Mailing list archives are held at:
The DBI 'Home Page' (not maintained by me):
Other DBI related links:
Other database related links:
Commercial and Data Warehouse Links.
Recommended Perl Programming Links
Please also read the DBI FAQ which is installed as a DBI::FAQ module so you
can use perldoc to read it by executing the
perldoc DBI::FAQ command.
DBI by Tim Bunce. This pod text by Tim Bunce, J. Douglas Dunlop, Jonathan Leffler and others. Perl by Larry Wall and the perl5-porters.
The DBI module is Copyright (c) 1995-1999 Tim Bunce. England. All rights reserved.
You may distribute under the terms of either the GNU General Public License or the Artistic License, as specified in the Perl README file..
A German translation of this manual and other Perl module docs (all probably slightly out of date) is available, thanks to O'Reilly, at:
Some other translations: - Spanish - Japanese
The DBI is free software. IT COMES WITHOUT WARRANTY OF ANY KIND.
Commercial support for Perl and the DBI, DBD::Oracle and Oraperl modules can be arranged via The Perl Clinic. See for more details.
References to DBI related training resources. No recommendation implied.
data types (ISO type numbers and type name conversions) error handling data dictionary methods test harness support methods portability blob_read etc
See the DBI FAQ for a more comprehensive list of FAQs. Use the
perldoc DBI::FAQ command to read it.
To measure the speed of the DBI and DBD::Oracle code I modified DBD::Oracle such that you can set an attribute which will cause the same row to be fetched from the row cache over and over again (without involving Oracle code but exercising *all* the DBI and DBD::Oracle code in the code path for a fetch).
The results (on my lightly loaded old Sparc 10) fetching 50000 rows using:
1 while $csr->fetch;
were: one field: 5300 fetches per cpu second (approx) ten fields: 4000 fetches per cpu second (approx)
Obviously results will vary between platforms (newer faster platforms can reach around 50000 fetches per second) but it does give a feel for the maximum performance: fast. By way of comparison, using the code:
1 while @row = $csr->fetchrow_array;
(fetchrow_array is roughly the same as ora_fetch) gives:
one field: 3100 fetches per cpu second (approx) ten fields: 1000 fetches per cpu second (approx)
Notice the slowdown and the more dramatic impact of extra fields. (The fields were all one char long. The impact would be even bigger for longer strings.)
Changing that slightly to represent actually _doing_ something in perl with the fetched data:
while(@row = $csr->fetchrow_array) { $hash{++$i} = [ @row ]; }
gives: ten fields: 500 fetches per cpu second (approx)
That simple addition has *halved* the performance.
I therefore conclude that DBI and DBD::Oracle overheads are small compared with Perl language overheads (and probably database overheads).
So, if you think the DBI or your driver is slow, try replacing your fetch loop with just:
1 while $csr->fetch;
and time that. If that helps then point the finger at your own code. If that doesn't help much then point the finger at the database, the platform, the network etc. But think carefully before pointing it at the DBI or your driver.
(Having said all that, if anyone can show me how to make the DBI or drivers even more efficient, I'm all ears.)
Read the information in the references below. Please do not post CGI related questions to the dbi-users mailing list (or to me).
Using Apache and mod_perl?
General problems and good ideas:
Use the CGI::ErrorWrap module. Remember that many env vars won't be set for CGI scripts
For information on the Apache httpd server and the mod_perl module see
A DBD::ODBC module is available.
No. The DBI has no knowledge or understanding of dates at all.
Individual drivers (DBD::*) may have some date handling code but are unlikely to have year 2000 related problems within their code. However, your application code which uses the DBI and DBD drivers may have year 2000 related problems if it has not been designed and written well.
See also the ``Does Perl have a year 2000 problem?'' section of the Perl FAQ:.
|
http://www.fnal.gov/docs/products/perl/pod.new/site_perl/5.005/i686-linux/DBI.html
|
crawl-002
|
refinedweb
| 6,354
| 56.45
|
tensor.fft – Fast Fourier Transforms¶
Performs Fast Fourier Transforms (FFT).
FFT gradients are implemented as the opposite Fourier transform of the output gradients.
Warning
The real and imaginary parts of the Fourier domain arrays are stored as a pair of float arrays, emulating complex. Since theano has limited support for complex number operations, care must be taken to manually implement operations such as gradients.
theano.tensor.fft.
rfft(inp, norm=None)[source]¶
Performs the fast Fourier transform of a real-valued input.
The input must be a real-valued variable of dimensions (m, ..., n). It performs FFTs of size (..., n) on m batches.
The output is a tensor of dimensions (m, ..., n//2+1, 2). The second to last dimension of the output contains the n//2+1 non-trivial elements of the real-valued FFTs. The real and imaginary parts are stored as a pair of float arrays.
theano.tensor.fft.
irfft(inp, norm=None, is_odd=False)[source]¶
Performs the inverse fast Fourier Transform with real-valued output.
The input is a variable of dimensions (m, ..., n//2+1, 2) representing the non-trivial elements of m real-valued Fourier transforms of initial size (..., n). The real and imaginary parts are stored as a pair of float arrays.
The output is a real-valued variable of dimensions (m, ..., n) giving the m inverse FFTs.
For example, the code below performs the real input FFT of a box function, which is a sinc function. The absolute value is plotted, since the phase oscillates due to the box function being shifted to the middle of the array.
import numpy as np import theano import theano.tensor as T from theano.tensor import fft x = T.matrix('x', dtype='float64') rfft = fft.rfft(x, norm='ortho') f_rfft = theano.function([x], rfft) N = 1024 box = np.zeros((1, N), dtype='float64') box[:, N//2-10: N//2+10] = 1 out = f_rfft(box) c_out = np.asarray(out[0, :, 0] + 1j*out[0, :, 1]) abs_out = abs(c_out)
|
http://deeplearning.net/software/theano/library/tensor/fft.html
|
CC-MAIN-2019-09
|
refinedweb
| 332
| 60.92
|
curl-library
https redirect problem?
Date: Sun, 10 Oct 2004 18:10:07 -0400
Hi,
I'm a novice of libcurl. Now I'm trying to utilize it to develop an https client. Basically, just to automate the procedure of login to an
https website, and then downloading a file from it. I did a small test at first and figured out there could be a hidden bug within libcurl, because
it doesn't seem to handle https redirect properly. (At first I tought it could be within curlpp wrapper, but then I figured out it shouldn't,
as curlpp is only a C++ wrapper of libcurl. The redirect stuff is handled by libcurl. Please correct me if I am wrong.)
Here is what I did.
I downloaded the curlpp package (a C++ wrapper of libcurl, version0.3.1), compiled it and installed it w/o any problem.
My box has RedHat Linux 2.4.21-4 EL installed. It's i686 machine.
Here is the code:
==={ Source Code # 1}======================
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <string.h>
#include <fstream>
#include "curl.hpp"
#include "easy.hpp"
#include "types.hpp"
#define HTTPS_URL
int main()
{
CURL *curl;
CURLcode res;
char *useragent = "";
char *cookiejar = "cookies.jar";
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, HTTPS_URL);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
curl_easy_setopt(curl, CURLOPT_UNRESTRICTED_AUTH, 1);
curl_easy_setopt(curl, CURLOPT_USERAGENT, useragent);
curl_easy_setopt(curl, CURLOPT_COOKIEJAR, cookiejar);
curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
}
return 0;
}
======{ End of Souce code #1}=====================
And here is the output I obtained.
======{ Verbose/Trace Info. #1}==========================
*=eBusiness/OU=Terms of use Server CA - Class 3/OU= Incorp.by Ref. LIABILITY LTD.(c)97 VeriSign
> GET /login/log_log_page.jsp?CTAuthMode=BASIC&ct_orig_uri=%2XXX%XXX.jsp HTTP/1.1
Authorization: Basic XXXXXXXXXXXXXXXXXXXX==
Host: my.xxxxx.net
Pragma: no-cache
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*
HTTP/1.1 200 OK
Date: Thu, 07 Oct 2004 20:04:52 GMT
Server: HP Apache-based Web Server/1.3.26 (Unix) mod_ssl/2.8.9 OpenSSL/0.9.6c
Set-Cookie: JSESSIONID=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX; path=/
Transfer-Encoding: chunked
Content-Type: text/html
.. then followed by the ascii text format of login.jsp page, but not the page I'm trying to fetch :(
======={ End of Trace Info #1 }==========================
As I have RedHat linux installed, so there is already a bundled curl (7.10.6), which is under /usr/bin.
I tried using that curl to download the file:
$curl
and it worked perfectly! (I even don't need to put -L option in the command line. I got the file I want.
Here is the version info for the command-line curl I have on my box.
========{ command-line curl version }========================
$ /usr/bin/curl -V
curl 7.10.6 (i386-redhat-linux-gnu) libcurl/7.10.6 OpenSSL/0.9.7a ipv6 zlib/1.1.4
Protocols: ftp gopher telnet dict ldap http file https ftps
Features: IPv6 SSL libz NTLM
========{ End of command-line curl version }===================
Again, here is the strace info I got for using command line curl:
========{ Strace Info #2: for command line curl }=============
*=XXXXX/OU=Terms of use a Serve
r CA - Class 3/OU= Incorp.by Ref. LIABILITY LTD.(c)97 VeriSign
> GET /XXXX/XXXXX.jsp HTTP/1.1
Authorization: Basic XXXXXXXXXXXXXXXXXXX==
User-Agent: curl/7.10.6 (i386-redhat-linux-gnu) libcurl/7.10.6 OpenSSL/0.9.7a ipv6 zlib/1.1.4
Host: my.xxxxx.net
Pragma: no-cache
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*
< HTTP/1.1 200 OK
< Date: Wed, 06 Oct 2004 00:31:43 GMT
< Server: HP Apache-based Web Server/1.3.26 (Unix) mod_ssl/2.8.9 OpenSSL/0.9.6c
< Set-Cookie: CTSESSION=XXXXXXXXXXXXXX; domain=.xxxxx.net; path=/
< Set-Cookie: BIGipServersslmbea_xxxxx_http=XXXXXXXXX.XXXXX.0000; path=/
< Set-Cookie: JSESSIONID=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX; path=/
< Cache-control: no-cache="set-cookie"
< Transfer-Encoding: chunked
< Content-Type: text/html
<!doctype html public "-//w3c//dtd html 4.0 transitional//en" "
ose.dtd">
<HTML> // <= This is the file I want!
..
========{ End of Strace Info #2: for command line curl }=============
I also tried to turn on the cookies and force to set-up user-agent while I'm sending the request, but it didn't work, either.
I'm thinking that the problem could be within libcurl, because the curl seems to be able to handle https web rediction properly...
I understand that curl and libcurl are totally different things, curl is a command-line tool. While if curl can handle https redirect w/o problem, I assume that libcurl should be able to do something similar.
I suppose if curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1) works, then after the authentication (which already happened properly), it should automatically redirect to the https webpage I intended to fetch (but it didn't). i.e. the process should look like:
o Given -- (note that
the target file is not login.jsp, which certainly has the same domain name (my.xxxxx.net/) as MyTargetFile.jsp.
o Authentication Succeeded -- I got RSA authentication approved (detail was listed in the above)
o Redirect to page MyTargetFile.jsp and download MyTargetFile (Unfortunately, this never happened while I tried using libcurl/curlpp in my code). What I got is the ascii format of login.jsp :-( That's the whole story.
Any suggestion would be greatly appreciated. Thanks in advance.
Iris
Received on 2004-10-11
|
https://curl.haxx.se/mail/lib-2004-10/0096.html
|
CC-MAIN-2017-17
|
refinedweb
| 895
| 61.12
|
This is a standard knapsack problem with a bit of a twist. After Bessie drinks water once, her fullness value will decrease, but she won't be able to drink water again. A standard knapsack algorithm won't quite work here because the maximum fullness Bessie can achieve might not be the result of a non-decreasing function.
Since Bessie can only drink water once, we can separate the problem into two cases: the case where Bessie can still drink, and the case where she has already drunk. In both cases, we can run standard knapsack. Furthermore, notice that if we first handle the case where Bessie can still drink, then this allows us to obtain all possible points at which Bessie can start eating again, right after drinking. Then, we can just run another standard knapsack algorithm on the second case, now that we have the list of possible starting locations. Taking the maximum obtainable value over both cases gives us the answer.
Here is Nick Wu's code that implements this idea. (He sets seen[0][X] to true if Bessie can attain X units of fullness without drinking water, and seen[1][X] to true if Bessie can attain X units of fullness after drinking water.)
import java.io.*; import java.util.*; public class feast { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new FileReader("feast.in")); StringTokenizer st = new StringTokenizer(br.readLine()); int t = Integer.parseInt(st.nextToken()); int x = Integer.parseInt(st.nextToken()); int y = Integer.parseInt(st.nextToken()); boolean[][] seen = new boolean[2][t+1]; seen[0][0] = true; for(int a = 0; a < seen.length; a++) { for(int i = 0; i < seen[a].length; i++) { if(!seen[a][i]) { continue; } if(i+x <= t) { seen[a][i+x] = true; } if(i+y <= t) { seen[a][i+y] = true; } if(a+1 < seen.length) { seen[a+1][i/2] = true; } } } int ret = t; while(!seen[1][ret]) { ret--; } PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("feast.out"))); pw.println(ret); pw.close(); } }
|
http://usaco.org/current/data/sol_feast_gold_dec15.html
|
CC-MAIN-2018-17
|
refinedweb
| 343
| 66.54
|
5 important programs that you should know:
1.sorting technique of array using pointers:
#include<stdio.h>
#include<stdlib.h>
void create_array(int *p,int n);
void display(int *p,int n);
void sorting(int *p,int n);
int main()
int *p,n;
printf(“enter how many element you want to insert in the array?\n”);
scanf(“%d”,&n);
p=(int *)malloc(sizeof(int)*n);
create_array(p,n);
return 0;
void create_array(int *p,int n)
printf(“enter the element in the array”);
for(int i=0;i<n;i++)
scanf(“%d “,&p[i]);
display(p,n);
sorting(p,n);
printf(“after sorting\n”);
display(p,n);
void display(int *p,int n)
printf(“enter the element in the array”);
for(int i=0;i<n;i++)
printf(“%d “,*(p+i));
void sorting(int *p,int n)
int temp,round;
for( round=0;round<n-1;round++)
for(int i=0;i<n-round;i++)
if((p[i]>=p[i+1]))
temp=p[i];
p[i]=p[i+1];
p[i+1]=temp;
2.reversing array using structure:
#include<stdio.h>
#include<stdlib.h>
struct x{
int *p,n,start,end;
struct x* input( struct x *s1);
struct x* reverse(struct x *s1);
struct x* display( struct x *s1);
int main()
struct x *s1;
s1=(struct x*)malloc(sizeof(struct x));
printf(“how many number you want to insert in array\n”);
scanf(“%d”,&s1->n);
s1->p= (int *)malloc(sizeof(int)*s1->n);
s1->start=0;
s1->end=s1->n-1;
s1=input(s1);
return 0;
struct x* reverse(struct x *s1)
{ int temp;
while(s1->start<s1->end)
temp=s1->p[s1->start];
s1->p[s1->start]=s1->p[s1->end];
s1->p[s1->end]=temp;
s1->start++;
s1->end–;
s1=display(s1);
struct x* input( struct x *s1)
printf(“enter the number\n”);
for(int i=0;i<s1->n;i++)
scanf(“%d”,&s1->p[i]);
s1=reverse(s1);
return(s1);
struct x* display( struct x *s1)
{ printf(“dsiplay the number\n”);
for(int i=0;i<s1->n;i++)
printf(“%d “,s1->p[i]);
return(s1);
3. dynamic memory allocations in c:
#include <stdio.h>
#include<conio.h>
struct temparature
int mintemp,maxtemp;
int main()
struct temparature t;
int *days,n;
printf(“enter the no of days\n”);
scanf(“%d”,&n);
days=(int *)malloc(sizeof(int)*n);
for(int i=0;i<n;i++)
scanf(“%d”,(days+i));
avgtemp(days,n,t);
return 0;
void avgtemp(int *days,int n,struct temparature t)
int s=0;
for(int i=0;i<n;i++)
s=s+days[i];
t.mintemp=s/n;
printf(“%d”,t.mintemp);
4.fibonacci using c:
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
struct fibo {
int n,t1,t2,s;
void fibonacci(struct fibo);
int main()
struct fibo n1;
printf(“enter the mumber\n”);
scanf(“%d”,&n1.n);
fibonacci(n1);
void fibonacci(struct fibo n1)
n1.t1=-1;n1.t2=1;n1.s;
for (int i = 0; i <=n1.n; i++)
n1.s=n1.t1+n1.t2;
n1.t1=n1.t2;
n1.t2=n1.s;
printf(“%d\n”,n1.s);
5. sorting programs:
#include<stdio.h>
void input( int *p, int n );
void display(int *p,int n);
void sort(int *p,int n);
int main()
int arr[20],n;
printf(“enter the number of values”);
scanf(“%d”,&n);
input(arr,n);
return 0;
void input( int *p, int n )
printf(“enter the elements”);
for(int i =0;i<n; i++)
scanf(“%d”,p+i);
display( p,n);//p=arr=&arr[0]
sort(p,n);
void display(int *p,int n)
printf(“display the elements”);
for(int i =0;i<n; i++)
printf(“%d\n”,*(p+i));
void sort(int *p,int n)
int temp;
for(int r=0;r<=n-1;r++)
{ for(int i=0;i<n-1;i++)
if(*(p+i)>=*(p+i+1))
temp=*(p+i);
*(p+i)=*(p+i+1);
*(p+i+1)=temp;
display( p,n);
array and pointers concept descriptions breifly
our facebook page link:
340 thoughts on “array and pointers uses in c that you should know in programming”
What’s up friends, nice article and pleasant
arguments commented at this place, I am actually enjoying by these.
Inspiring quest there. What happened after? Thanks!
Feel free to surf to my website … boost libido exercise
I visited various websites except the audio feature for audio songs current at this site
is truly marvelous.
Feel free to surf to my site – testosterone continues
I like this website so much, saved to bookmarks.
Here is my web-site ::
Hello, just wanted to say, I liked this post. It was helpful.
Keep on posting!
Here is my web page: what types of diets are best for our bodies
This is my first time go to see at here and i am really happy to read all at single place.
my web-site; atkins diet plan
I enjoy looking through a post that can make people think.
Also, thank you for allowing me to comment!
Here is my site prettypeople.club
I really like your writing style, great information, appreciate it for putting up :D.
my web site …
Hello, I log on to your blogs like every week. Your humoristic style is awesome, keep up the good work!
Some genuinely fantastic content on this internet
site, regards for contribution.
Here is my site – growing cannabis seeds
Greetings! I’ve been following your web site for some time now and finally got the courage to go ahead and give you a shout out from Atascocita Tx!
Just wanted to say keep up the good work!
Feel free to surf to my web site :: lower left side back
pain,
It’s really a nice and useful piece of information. I am glad that you simply shared this helpful information with us.
Please keep us up to date like this. Thanks for sharing.
My website :: Pat
I’ve learn several just right stuff here. Definitely worth bookmarking for revisiting.
I surprise how a lot attempt you put to make any such fantastic informative site.
I am continuously searching online for articles that can aid me.
Thanks!
Have a look at my web blog: illegal drugs
I’m curious to find out what blog system you happen to be using?
I’m experiencing some minor security problems with my latest blog and I’d like to find
something more risk-free. Do you have any suggestions?
Also visit my site; skin care.
Visit my homepage … eating healthy foods
Very interesting subject, thank you sex tips for couples
putting up.
Hi there, this weekend is fastidious for me, as this moment i am
reading this enormous educational post here at my home.
Also visit my blog post: low carb recipes
Thank you for sharing your info. I really appreciate your efforts and I will be waiting
for your next write ups thank you once again.
Feel free to visit my website – hemp seed contains (Felicitas)
Hi there! This post couldn’t be written any better!
Reading through this post reminds me of my good old room mate!
He always kept chatting about this. I will forward this
article to him. Fairly certain he will have a good read.
Thank you ketogenic diet for weight loss sharing! a look at my web-site – sex pills
Keep working ,impressive job!
Also visit my blog – pure hemp seed oil (
There is evidently a bundle to realize about this.
I consider you made some nice points in features also.
Here is my page: Meridith
Very informative and superb body structure of articles,
now that’s user pleasant (:.
Feel free to visit my website: cure sciatica
I constantly spent my half an hour to read this web site’s content everyday along with a cup of coffee.
Also visit my web-site … quit smoking home remedies
Hi there, I discovered your site by the use of Google whilst searching for a similar subject, your site
came up, it appears to be like great. I’ve bookmarked it in my google bookmarks.[X-N-E-W-L-I-N-S-P-I-N-X]Hi there,
just changed into aware of your weblog through Google, and located that it is really informative.
I’m going to watch out for brussels. I will be grateful for those who proceed this in future.
A lot of other people shall be benefited out of your writing.
Cheers!
Feel free to visit my website … cannabis doctor – –
I’m not that much of a online reader to be honest but your sites really nice, keep it up!
I’ll go ahead and bookmark your site to come back down the
road. All the best
Informative article, totally what I needed.
my web site eating plan
But wanna admit that this is very helpful, Thanks for taking your time to write
this.
Here is my website :: cannabis seeds exist
Very nice post. I just stumbled upon your weblog and wanted to mention that I’ve
really enjoyed surfing around your blog posts.
After all I’ll be subscribing for your rss feed and I hope you write again very soon!
my page :: drug use
Appreciate the recommendation. Let me try it out.
Also visit my web blog skin care and acne
Incredible points. Sound arguments. Keep up the amazing effort.
my web-site: Stacy
Asking questions are in fact nice thing if you are not understanding anything totally, but this paragraph offers fastidious understanding yet.
Respect to article author, some excellent entropy.
Here is my web-site – healthy eating for kids (
We’re a group of volunteers and starting a new scheme in our community.
Your web site offered us with valuable info to work on. You have done a formidable job and our whole community will
be thankful to you.
My web site: hemp benefits
Everything is very open with a very clear description of the challenges.
It was really informative. Your website is useful. Thank you for sharing!
Wonderful goods from you, man. I’ve web site.
my site … fat burning kitchen
I enjoy your writing style really enjoying this site.
my webpage: low carb
My partner and I absolutely love your blog and find many of your post’s to be exactly what
I’m looking for. Do you offer guest writers to write content for you?
I wouldn’t mind composing a post or elaborating on some
of the subjects you write concerning here.
Again, awesome site!
I’m gone to convey my little brother, that he should also visit
this weblog on regular basis to take updated from most recent reports.
Here is my web page – what types of diets are best for our bodies
Thank you for sharing your info. I truly appreciate your efforts and I will be waiting for
your next post thank you once again.
my blog post; stop smoking
Some truly excellent information, Gladiolus I detected this.
Feel free to visit my web blog … hemp benefits
Simply wanna comment that you have eating healthy on a budget very nice web site,
I love the pattern it really stands out.
Hi! This is kind of off topic but I need some help from an established blog.
Is it very hard how to make a man orgasm set up your own blog?
I’m not very techincal but I can figure things out
pretty fast. I’m thinking about creating my own but I’m not sure
where to start. Do you have any points or suggestions? Thank you
I liked up to you will receive performed right here.
The sketch is tasteful, your authored subject
matter stylish. however, you command get got an edginess over that you want
be handing over the following. ill no doubt come more previously again since precisely the same nearly eating healthy on a budget lot frequently inside
case you defend this increase.
Good day! Do you know if they make any plugins to protect against
hackers? I’m kinda paranoid about losing everything I’ve worked hard on. Any tips?
Here is my homepage :: testosterone levels
Hiya, I am really glad I’ve found this information. Nowadays bloggers publish only about gossips and
web and this is really irritating. A good blog with exciting content, that is
what I need. Thank you for keeping this web site, I’ll be visiting it.
Do you do newsletters? Cant find it.
Look at my web site cyclical ketogenic
We are a bunch of volunteers and opening a new scheme in our community.
Your site offered us with useful info to work on. You have done a formidable process and
our whole group will be thankful to you.
my web site; atkins nutritionals ( site!
Hi there, I do believe your blog could possibly be having browser compatibility problems.
When I take a look at your web site in Safari, it looks fine but when opening in I.E., it’s got some overlapping issues.
I just wanted to provide you with a quick heads up!
Other than that, fantastic website!
My site; healthy eating diets
You really make it appear so easy with your presentation but I find this matter to
be really one thing which I feel I might never understand.
It sort of feels too complex and extremely vast
for me. I am having a look ahead in your next post, I’ll attempt to get the grasp of it!
Review my page: children smoking
Hi there! Do you use Twitter? I’d like to follow you if
that would be ok. I’m definitely enjoying your blog and look
forward to new updates.
Also visit my webpage: accessing medical cannabis
Terrific work! This is the type of info that should be shared across the net.
Disgrace on Google for not positioning this post upper!
Come on over and visit my site . Thanks =)
Here is my site … lose fa [
Everything is very open with a really clear explanation of the issues.
It was really informative. Your website is useful. Many thanks for sharing!
Also visit my web page :: hemp seed oil uses
Wow! Thank you! I permanently needed to write on my blog something like that.
Can I take a fragment of your post to my site?
my web site – sex secrets
I wanted to check up and allow you to know how much I cherished
discovering your blog today. I’d consider it a real honor
to operate at my workplace and be able to use
the tips provided on your site and also be a part of visitors’
responses like this. Should a position involving guest article writer become available at your end, i highly recommend you let me know.
Thanks , I have just been looking for info approximately this topic for
ages and yours is the greatest I’ve came upon till
now. However, what concerning the conclusion? Are you positive in regards to the source?
my page – organic skin care
Wow! Thank you! I continually wanted to write on my site something like that.
Can I take a portion of your post to my blog?
Here is my blog post :: carb nite pdf (Lorna)
I constantly spent my half an hour to read this blog’s content all the time along with a mug what types of diets are best for our bodies coffee.
I’m extremely inspired together with your writing skills and also with the layout for your blog.
Is that this a paid subject or did you customize it yourself?
Either way stay up the excellent quality writing, it
is uncommon to peer a great weblog like this one
these days.
Here is my blog post:
Link exchange is nothing else except it is just placing the
other person’s web site link on your page at proper place and other person will also do same in favor of
you.
I every time emailed this website post page to all my contacts, because if like to read it then my friends will too.
It’s very simple to find out any topic on net
as compared to textbooks, as I found this post at this site.
Feel free to surf to my blog; eat non-processed foods
As a Newbie, I am constantly exploring online for articles that can be of
assistance to me. Thank you
Feel free to surf to my blog skin cleansing
Great post, I believe blog owners should larn a lot from this blog its rattling user pleasant.
So much fantastic info on here :D.
my blog post ::
That is a great tip particularly to those new to the blogosphere.
Brief but very accurate information? Appreciate your sharing this one.
A must read article!
Here is my web blog :: acne skin care (F –
I like this web site it’s a master piece! Glad I observed this on google.
Here is my web blog … how to improve lovemaking
Good way of telling, and fastidious post to get facts regarding my presentation focus, which i am going
to deliver in school.
My web page – ketosis diet
Hurrah! Finally I got a web site from where I be capable of actually take valuable information concerning my study and knowledge.
Also visit my page – various cannabis seeds
Enjoyed reading through this, very good stuff, thank you.
Feel free to surf to my site :: aging skin care
Thank you for another informative web site. Where else may
I am getting that type of info written in such an ideal method?
I have a mission that I’m just now operating on, and I have been at the look out for such
info.
Look at my blog healthy eating pyramid
I used to be able to find good information from your blog posts.
my homepage testosterone booster
I too conceive thence, perfectly pent post!
Feel free to visit my website: pubic hair removal
I was suggested this blog through my cousin. I’m no longer
certain whether or not this publish is written via him as no one else recognize such
particular approximately my trouble. You are amazing!
Thanks!
As a Newbie, I am constantly searching online for articles that can help me.
Thank you
Feel free to surf to my web-site – 163.30.42.16
Review my blog post – 23.95.102.216
Hey there, You have done a great job. I will certainly digg it
and personally suggest to my friends. I am confident they will be benefited from this site.
my blog post: prettypeople.club
Somebody necessarily lend a hand to make
critically articles I would state. This is the first time I frequented your
web page and so far? I amazed with the analysis
you made to create this particular put up extraordinary.
Magnificent task!
My web site; genital hair removal
I’m not sure where you’re getting your information, but great topic.
I needs to spend some time learning much more or understanding more.
Thanks for fantastic information I was looking for this info for my mission.
Good article. I’m dealing with some of these issues as well..
Here is my site – wight loss program
Heya i’m for the first time here. I came across
this board and I to find It truly useful & it helped me out much.
I am hoping to offer one thing back and aid others like you helped me.
My homepage ::
Hello, i think that i saw you visited my blog thus i got here to ?return the want?.I am trying to to find issues to enhance my web site!I guess its adequate
to use a few of your ideas!!
Review my web site … fat burn Chrome. Exceptional!
Here is my site:
I really like it when people get together and share opinions.
Great website, stick with it!
It’s in point of fact a nice and helpful piece of information. I am
happy that you just shared this helpful info with us. Please stay us up to date like this.
Thanks for sharing.
You can definitely see your enthusiasm within the article you write.
The arena hopes for more passionate writers such as you who are
not afraid to mention how they believe. At all times follow your heart.
Feel free to visit my web site – drug crime
It’s awesome in support what types of diets are best for our bodies me to
have a site, which is beneficial in support of my knowledge.
thanks admin undeniably be one of the most beneficial in its niche.
Wonderful blog!
That is a really good tip especially to those fresh to the blogosphere.
Short but very precise information? Thank you for sharing this one.
A must read article!
Here is my site ::
great points altogether, you just gained a new reader.
What would you suggest in regards to your submit
that you just made a few days ago? Any sure?
I was reading some of your posts on this internet site and I conceive
this site is very informative! Retain putting up.
Here is my page … facial skin
Hey there! Do you use Twitter? I’d like to follow you if that would be ok.
I’m undoubtedly enjoying your blog and look forward to new updates.
My web-site; facial skin care tips
Thank you for sharing with us, I believe this website genuinely stands out :
D.
Also visit my web blog:
Wow! Thank you! I always needed to write on my site something like that.
Can I implement a fragment of your post to my website?
My web site kids smoking
Keep functioning ,fantastic job!
Here is my web-site: omega 3 source
I really like what you guys are up too. This sort of clever work
and reporting! Keep up the excellent works guys I’ve you guys to
my personal blogroll.
Great article, just what I was looking for.
Feel free to surf to my site …
At this moment I am going to do my breakfast,
once having my breakfast coming again to read more news.
Also visit my web page drug use
Ahaa, its fastidious discussion about this
piece of writing at this place at this blog, I have read all that, so at this time me also commenting
at this place.
My webpage :: sex life tips
This paragraph is actually a good one it helps new internet users, who are wishing in favor of blogging.
Also visit my webpage: well-balanced healthy eating
Do you have any video of that? I’d want to find out more details.
Feel free to surf to my web page carb nite solution
Hey There. I discovered your weblog using msn. That is a really neatly written article.
I will be sure to bookmark it and come back to read extra of your useful info.
Thank you for the post. I’ll definitely return.
Review my webpage: quit smoking
That is a really good tip especially to those fresh to the blogosphere.
Simple but very accurate information… Thank you for sharing this one.
A must read post!
Also visit my web-site drug rehab centres
Hi my friend! I want to say that this post is amazing,
great written and include almost all significant infos. I would
like to see more posts like this .
my webpage good pre-workout supplements
Thank you for any other informative website. The place else may just I get that type of info written in such an ideal manner?
I’ve a venture that I’m simply now running on, and I’ve been at
the glance out for such info.
my web page: weight training
Its such as you learn my thoughts! You appear to understand so much approximately this, such
as you wrote the book in it or something. I feel that you simply
could do with some % to force the message home a little bit, but instead
of that, that is magnificent blog. A fantastic read.
I will certainly be back.
I got what you mean, thanks for putting up. Woh I am lucky to find this website through google.
My blog;
I gotta bookmark this internet site it seems very useful invaluable.
My homepage :: healthy eating plan
I keep listening to the reports talk about receiving
free online grant applications so I have been looking around
for the finest site to get one. Could you advise me please, where could i acquire some?
Also visit my website – oily skin
Wow that was unusual. I just wrote an really long comment
but after I clicked submit my comment didn’t appear.
Grrrr… well I’m not writing all that over again. Anyway,
just wanted to say great blog!
my web blog stop fat gain!
Feel free to visit my blog post – hair loss
I believe everything posted was actually
very logical. But, think about this, suppose you added a
little content? I am not suggesting your information isn’t good,
however what if you added a title that grabbed people’s attention?
I mean array and pointers uses in c that you should know in programming – LMT is a little
vanilla. You ought to look at Yahoo’s front page and watch how they create
news titles to grab people interested. You might add a related video or
a picture or two to get people excited about everything’ve written. Just my opinion, it
would make your website a little bit more interesting.
My web page; medical cannabis
Hey! I understand this is kind of off-topic however I needed to ask.
Does building a well-established website like yours take a large amount of work?
I am completely!
My web site
Hello, the whole thing is going well here and ofcourse every one is sharing
facts, that’s actually good, keep up writing.
Feel free to visit my page … kids smoking
It?s difficult to find well-informed people about
this subject, but you sound like you know what you?re talking about!
Thanks
Feel free to surf to my website … Raquel
Greetings I am so happy I found your blog, I really
found you by error, while I was browsing on Aol for something else,
Nonetheless.
Here is my site – skin care p
I was able to find good information from your articles.
my page forum.m2clasic.ro
Good site! I really love how it is simple on my eyes and the data are well written. I am wondering how
I might be notified when a new post has been made.
I’ve subscribed to your RSS which must do the trick! Have a great day!
my web page :: fat loss
I read this piece of writing completely concerning the
difference of latest and earlier technologies, it’s awesome article.
Right away I am going to do my breakfast, afterward having my breakfast coming yet again to read more news.
My web blog hoodia pill
Admiring the persistence.
my blog post: cannabis doctors
It’s amazing to go to see this web page and
reading the views of all colleagues regarding this piece of writing,
while I am also keen of getting know-how.
my page – dry skin care
Wow! Thank you! I continuously wanted to write
on my website something like that. Can I include a fragment of your
post to my website?
Here is my web-site
Really no matter if someone doesn’t know afterward its up to other
users that they will assist, so here it happens.
Here is my website: Marla
Nice post. I used to be checking constantly this weblog and I am impressed!
Very useful info particularly the ultimate section :
) I maintain such info a lot. I was seeking this certain information for a long time.
Thank you and best of luck.
Feel free to surf to my site: increase testosterone
Your style is very unique compared to other folks I have read stuff from.
Thank you for posting when you have the opportunity, Guess I
will just book mark this page.
my website low carb dieting tips
This web site really has all the info I wanted concerning
this subject and didn?t know who to ask.
Look at my page: treat yeast infection
Good web site you have here.. It’s difficult how to stop smoking weed find high quality
writing like yours these days. I honestly appreciate people like you!
Take care!!
Hi site … low libido cures
I got what you intend,bookmarked, very nice site.
my blog post eczema on
Visit my site; hemp seed oil capsules
I’m not sure where you are getting your information, however great topic.
I needs to spend a while finding out much more or
understanding more. Thank you for fantastic information I used to be on the lookout for this information for my mission.
My blog post: grow weed
Oh my goodness! Awesome article dude! Thank you so much, However I am encountering problems with your RSS.
I don’t know why I am unable to subscribe to it. Is there anyone else getting similar RSS
issues? Anybody who knows the solution can you kindly respond?
Thanks!!
Here is my homepage … anti aging
Hi, i think that i saw you visited my website thus i came to return the favor?.I’m attempting
to find issues to enhance my website!I suppose its good healthy eating enough to make
use of a few of your concepts!!
I’d perpetually want to be update on new articles on this website, bookmarked!
Here is my web page: great skin care
What’s up it’s me, I am also visiting this website daily, this
web site is truly good and the visitors are actually sharing nice
thoughts.
my web-site … flaxseed oil
Helpful information. Fortunate me I found your site by chance, and I’m shocked why this twist of fate didn’t happened earlier!
I bookmarked it.
Here is my homepage – dirty talk
Hi, i feel that i noticed you visited my website thus i came to go
back the want?.I’m attempting to in finding issues to improve my website!I suppose its
good enough to use some of your concepts!!
Also visit my blog; beautiful smooth skin
Hiya, I am really glad I have found this information. Today bloggers publish only about gossips and web and this
is actually irritating. A good website with exciting
content, this is what I need. Thank you home remedies for quit smoking keeping this website, I’ll
be visiting it. Do you do newsletters? Can not find it.
I really like it when people get together and share views.
Great site, continue the good work!
Review my site :: flat belly diets
Lovely just what I was looking for. Thanks to the author for taking
his time on this one.
Here is my blog post … healthy life could not refrain from commenting. Well written!
Here is my web site :: natural skin care tips for dry skin
Thank you for every other magnificent post.
Where else may just anybody get that kind of information in such an ideal manner of writing?
I have a presentation next week, and I’m on the look for such information.
my page skin care products
I cling on to listening know your skin type to optimize your skin care routine the newscast speak about
getting free online grant applications so I have been looking
around for the top site to get one. Could you tell me please, where could i get some?
Hi there, I enjoy reading all of your post. I
like to write a little comment to support you.
I love the efforts you have put in this, thanks for all the
great content.
Feel free to surf to my web blog :: weight loss
Hello there! I could have sworn I?ve visited your
blog before but after browsing through many of the articles I realized it?s new to me.
Regardless, I?m certainly delighted I stumbled
upon it and I?ll be book-marking it and checking back often!
Also visit my homepage: cycling diet
Some really wonderful info, Gladiolus I detected this.
Also visit my web page; holiday diet
It’s an awesome paragraph designed for all the online
viewers; they will take advantage from it I am sure.
Look at my site: diet and weight loss tips
Because the admin of this site is working,
no question very soon it will be famous, due to
its quality contents.
my web site; 23.95.102.216
These are genuinely enormous ideas in on the topic of blogging.
You have touched some nice points here. Any way keep up wrinting.
Also visit my web blog: best skin care
Some genuinely interesting info, well written and broadly speaking user genial.
My website … facial skin treatment
What’s up to every one, the contents existing at this web site are really
awesome for people experience, well, keep up the nice work
fellows.
Feel free to visit my website – losing weight
Super-Duper website! I am loving it!! Will be back
later to read some more. I am taking your feeds also
my web-site skin care basics
Thank you for sharing with us, I conceive this website truly stands
out :D.
Also visit my page: sleep plan.
my website :: low libido cures
If some one wants to be updated with hottest technologies after that he must be pay
a quick visit this web site and be up to date everyday.
I really like your writing style, fantastic info, appreciate it for
putting up :D.
My webpage vaginal orgasms
hello there and thank you for your info – I’ve. Make sure you update this again soon..
Feel free to visit my homepage: freshly hatched seeds
There is definately a great deal to know about this issue.
I like all the points you made.
Here is my web page … try hemp seeds
Hey, you used to write magnificent, but the last several posts have been kinda
boring… I miss your tremendous writings. Past several
posts are just a little out of track! come on!
Look at my homepage … houston getting treatment
Wow! Thank you! I continuously wanted to write on my blog something like that.
Can I implement a portion of your post to my website?
Also visit my website: flaxseed oil
Wonderful beat ! I would like to apprentice while you amend your web site,
how could i subscribe for a blog site? The account aided me a acceptable deal.
I had been a little bit acquainted of this your
broadcast provided bright clear concept
Here is my homepage :: beautiful smooth skin
Pretty! This has been an incredibly wonderful post. Thank you for supplying this
info.
Feel free to visit my site …
There is visibly a lot to realize about this. I suppose you made certain good points in features also.
Here is my site; prettypeople.club
Wow, this piece of writing is fastidious, my sister is analyzing these things, so I am going to let know her.
Have a look at my homepage – protein diet
I used to be able to find good advice from your blog posts.
Also visit my page :: care products
That is a very good tip particularly to those fresh to the blogosphere.
Short but very accurate information? Appreciate your
sharing this one. A must read article!
my blog post … fat burning kitchen
Awsome website! I am loving it!! Will be back later to read some more.
I am taking your feeds also
Here is my page –
Thanks very interesting blog!
my web site: oil pulling teeth whit homepage Jamal
Hey very nice blog!
Also visit my web-site – seed sprouts
Hello.This article was really remarkable, particularly since I was looking for thoughts on this topic last Saturday. growing inside
This is a great tip particularly to those new
to the blogosphere. Brief but very accurate info…
Thank you for sharing this one. A must read article!
My homepage :: male skin care
I really like your writing style, fantastic info, thanks
for putting up :D.
Also visit my web-site;
After checking out a handful of the blog articles on your site, I honestly
like your technique of writing a blog. I added it to my bookmark site list
and will be checking back in the near future. Please check out
my website too and let me know how you feel.
Just want to say your article is as astonishing.
The clarity in your post is simply excellent and i could assume you are an expert on this subject.
Fine with your permission allow me to grab your feed to keep
up to date with forthcoming post. Thanks a million and please keep up
the rewarding work.
Also visit my website
I am sure this piece of writing has touched all the
internet users, its really really nice piece of writing on building up new
website.
Also visit my web blog great sex tips
Oh my goodness! Amazing article dude! Many thanks, However I am experiencing
problems with your RSS. I don?t understand why I am unable
to subscribe to it. Is there anyone else having identical RSS problems?
Anybody who knows the solution will you kindly respond?
Thanx!!
Stop by my web site … fenshuajiang88.com
Hmm is anyone else encountering problems with the
pictures on this blog loading? I’m trying to figure out if its
a problem on my end or if it’s the blog. Any responses would
be greatly appreciated.
my blog post: gain muscle
Hey! I understand this is sort of off-topic but I needed to ask.
Does building a well-established blog like yours take a massive amount work?
I am completely new to writing a blog but I do write in my journal daily.
I’d like to start a blog so I can share my experience
and views online. Please let me know if you have any kind of ideas or
great sex tips for new aspiring blog owners.
Appreciate it!
Wonderful post.Ne’er knew this, thanks for letting
me know.
My web-site :: healthy nutrition
Some genuinely nice stuff on this internet site, I like it.
Look at my site – 23.95.102.216
Asking questions are actually fastidious thing if you are not understanding something totally,
but this article provides pleasant understanding yet.
Also visit my blog post stop weed smoking
Great web site you’ve got here.. It’s hard to find high quality writing like
yours these days. I truly appreciate individuals like you!
Take care!!
Also visit my web site ::
Right here is the perfect web site for everyone who wishes
to find out about this topic. You realize a
whole lot its almost tough to argue with you (not that
I personally would want to…HaHa). You certainly put a new spin on a subject which has been written about for many
years. Excellent stuff, just wonderful!
Feel free to visit my website – propane patio heaters
You have observed very interesting details! ps nice site.
Look at my webpage … tankless water heater work
You could definitely see your expertise within the work you write.
The arena hopes for even more passionate writers such as you who aren’t afraid to say how they believe.
All the time follow your heart.
I have read so many articles regarding the blogger lovers but
this paragraph is genuinely a fastidious article, keep it up.
It is truly a great and helpful piece of info. I?¦m glad that you shared this useful info with us. Please stay us up to date like this. Thanks for sharing.
azithromycin over the counter uk
buy generic cialis fast shipping
canadian pharmacy cialis 20 mg
chloroquine cost australia
retin a cream mexico pharmacy
viagra sales online
best sildenafil coupon
sildenafil online purchase india
fluoxetine10mg
atarax 25mg tab cialis rx cialis 2.5 mg tablet celexa price canada tadalafil 20 mg no rx for sale retino 0.05 gel aurogra 100mg tablets oral ivermectin cost buy allopurinol online uk hydroxychloroquine chloroquine
stromectol brand
elimite cream ebay atarax tablet amoxicillin 10mg buy orlistat australia avodart canada permethrin cream for sale strattera 25 mg prednisolone 5mg flagyl prices stromectol online pharmacy
xenical nz
buy brand name cialis online buy viagra without a prescription tadalafil canada cymbalta 30mg tab stromectol uk best price for tadalafil 20 mg where can u buy viagra purchase viagra tablets sildenafil 20 mg online cialis for sale in india
viagra europe pharmacy covid ivermectin 5mg tadalafil daily generic cialis europe how much is viagra how to cialis generic cialis for women price of tadalafil 5 mg citalopram 20mg online aralen 150
advair diskus india
tadalafil india 5mg
tamoxifen coupon
cialis daily use buy online
tadalafil prices
neurontin 200 mg
canadian price for cialis cialis online in india discount generic cialis online buy viagra over the counter in australia brand cialis price brand viagra online viagra paypal albendazole for sale online buy generic cialis 5mg cialis 20mg canada
buy viagra online australia paypal
ivermectin usa
ivermectin oral solution
10mg cialis cost
lasix water pill 20 mg buy no prescription
avodart 0.5 mg
female viagra for women indian pharmacy antabuse costs buy generic cialis online safely viagra tablet online india canadian pharmacy cialis cheap cialis canada pharmacy yasmin price south africa viagra in canada where can you get viagra pills
plaquenil cost without insurance
tadalafil for sale cheap
cialis 5mg canada
cialis pills 5 mg
online cialis from canada
buying viagra without prescription
where can i buy cialis online in canada
ivermectin cream 1
generic cialis 2018
cialis chewable tablets
suprax over the counter
mexico pharmacy viagra
cialis discount
cheap real viagra online
ivermectin 3mg pill
stromectol online
viagra rx
viagra from india pharmacy
best viagra tablets india
ivermectin 3mg price
buy cialis pills uk
generic viagra 200
stromectol canada
order cialis no prescription
canadian neighbor pharmacy
canadian cialis 60mg
over the counter tadalafil
how to purchase cialis online
legitimate canadian pharmacies
generic cialis price comparison
purchase tadalafil
ivermectin uk
how to get cialis in australia
stromectol coronavirus
cialis 20mg pills
cialis 120
over the counter cialis
where to buy cialis for daily use
viagra singapore pharmacy
cialis canada over the counter
ivermectin 3
female viagra pills price
best online tadalafil
cheap viagra uk
where can i buy 1 viagra pill
stromectol in canada
celebrex canada
biaxin 500 mg price
viagra prescription online
viagra online discount
generic viagra free shipping
metformin 101
cialis buy online india
can you buy lisinopril
stromectol for sale
otc zanaflex
permethrin cream
amitriptyline online no prescription
purchase viagra over the counter
can you buy viagra over the counter nz
sildenafil canada prescription
tadalafil 20mg no prescription
100 mg azithromycin
cheap viagra online canadian pharmacy
viagra online without a prescription
best sildenafil brand
buy cheap viagra online uk
atarax 10mg tablet
ivermectin 12
generic sildenafil from canada
buy cialis online us
order cialis online pharmacy
sildenafil drug
buy 40mg lasix online
generic tadalafil usa
robaxin 750 tablets
how to get albendazole
cost of synthroid 200 mcg
viagra mexico
buy robaxin without prescription
amoxicillin 875 mg cost
buy female viagra australia
buy cialis in singapore
ordering amitriptyline online
buy generic cialis 20mg
can you buy stromectol over the counter
anafranil 10mg tablets
azithromycin tablets
ivermectin 1%cream
losartan lisinopril
prescription prednisone cost
india cialis pharmacy
fildena online
canada cialis online
cialis pill generic
buy cialis online free shipping
tadalafil 100
cialis 80mg online
fildena 100
discount cialis canada
cialis canada fast shipping
price synthroid 50 mcg
robaxin 114
canada pharmacy vermox
motrin uk
gabapentin daily
buy clonidine online no prescription
cheap cialis 100mg
tadalafil 40 mg uk
buy viagra without presc
tadalafil cheap uk
cheap generic cialis 20mg
canada discount pharmacy
canadian pharmacy cialis 20mg
buy propecia best price
where to get atarax
|
https://lastminutetechnology.com/array-and-pointers/
|
CC-MAIN-2022-21
|
refinedweb
| 7,296
| 73.27
|
Fetching data from a Web API to our Aurelia SPA
Welcome to this third episode in the blog series about writing an Aurelia SPA with a Web API hosted on ASP.NET Core.
This post will focus on getting data from the Web API into our Aurelia SPA.
We will also start looking into Aurelia views and try out a few ways to list the initial data we receive. make our SPA retrieve data from the API that we created in the previous post. After we’ve gotten the data we will look at how we can render it in our SPA. The intent is to use the Aurelia Fetch Client, and we’ll look at how to get that up and running in an Aurelia CLI project like our SPA.
Using Fetch in an Aurelia SPA
For retrieving data we will use the Aurelia Fetch Client. I will use Chrome and Edge for testing this, and both those browsers has an implementation of the Fetch API. Do notice that if you want to run on any other browser it might not support the Fetch API. If you are using a browser that do not support Fetch you need to use a polyfill. If you are unsure, check your browser support here: Fetch on caniuse.com.
Installing the Aurelia Fetch Client
We’re going to use npm to install our packages, so open your favorite CLI and enter the following:
npm install aurelia-fetch-client --save
Now we need to add it to Aurelia.json in the dependencies section, add the following row:
"aurelia-fetch-client"
Using the Fetch Client in an Aurelia View
Add an import for the fetch client to app.ts at the top:
import {HttpClient} from 'aurelia-fetch-client';
Now, if you build the SPA from the CLI with au build, you’ll get a slew of errors. All hailing from missing definitions for the fetch client. So, we need to add some type definitions.
Add Typings for the Fetch API needed by the Aurelia TypeScript webapp
Installing type definitions is easiest done using Typings.
So if you haven’t got Typings installed already, it’s time to install it. Install Typings by running the following in a CLI:
npm install typings --global
Add typings for the Fetch API by entering the following two lines in a CLI:
typings i dt~whatwg-fetch -GS typings i dt~whatwg-streams -GS
Compiling the Aurelia SPA after this will still produce an error, it will claim it can’t find “URLSearchParams”. Now this is actually a fault in the TypeScript definition files. This error will hopefully soon go away in a future version of TypeScript. But it’s possible to solve it now by either
- Adding a dummy definition temporarily in a file created by yourself
- Importing a temporary definition file
Let’s use the second option and import a definition to this project, then we can remove that typings reference if ever this problem get’s fixed! Import this definition by entering the following:
typings install github:RomkeVdMeulen/URLSearchParams --global --save
Building the Aurelia SPA should now work and produce no errors.
Fetching data from the Web API to the Aurelia SPA
Let’s use the fetch client to get some droid data from our Web API. Modify app.ts like this:); } }
Now, there’s a few new concepts being introduced here, so let’s talk have a look at them.
Dependency Injection and Autoinject
In Aurelia we can use Dependency Injection to get access to members we need. The easy way to use this with TypeScript is:
- Import autoinject from the Aurelia framework
- Use the @autoinject decorator on top of the class declaration
- Create a private member in the constructor definition, detailing what member should be initialized
- TypeScript will now automatically define a class wide private field for the above defined members for us!
In our example above, the private member named http is accessible in the entire class. See how it’s used further down in the activate method.
Using the Fetch Client
First we configure our http client in the constructor, telling it to use the “standard configuration” and also giving it a base address.
In the Activate method we then use the fetch client to call the Web API. We tell it to convert the repsonse to json and store that json result in our droids array.
So let’s build the SPA and open a browser and test it!
As can bee seen in both Edge and Chrome, we get a CORS error when requesting data from the Web API. To fix this we need to enable CORS requests in the Web API.
Configuring CORS in the ASP.NET Core Web API
We need to modify our Web API and enable CORS requests. We do this by defining a CORS policy that can be used in our pipeline when serving requests.
Open Startup.cs in the Web API Project. Modify the ConfigureServices method like this:>(); }
Next, modify the Configure method like this:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { app.UseCors("AureliaSPA"); loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); app.UseMvc(); }
What we have done now is to setup a CORS policy, which is quite relaxed, all we do is say “allow any traffic from localhost:5000” basically. Then we tell the Web API to use this rule in the pipeline, in the Configure method.
This means we will allow all traffic coming from our Aurelia SPA, hosted on localhost:5000.
Notice! If you change the url of the Aurelia SPA, remember to change this CORS policy as well!
Testing with CORS Enabled
Running the app again after enabling our CORS policy in the WEB API, we can see that the SPA renders properly and there are no CORS errors in the console.
However, there’s no API data showing in the UI, so how do we know that it works?
Well, either we just inspect the data in the dev tools, or we write some html to render our droids!
Implementing our first Aurelia View
Time to finally actually start implementing some front end code, after all it’s what this blog series is supposed to be about 🙂
This will be among the first times we actually start using Aurelia for creating views, and we’ll notice how smooth it is to use and how clean our html will be!
Let’s implement a table and to display the Droid data fetched from the Web API.
HTML Tables in Aurelia
Create a table as per usual in HTML with a head and a body.
Then, we want to data bind our droids to each row in the table. This is where we can use Aurelia’s Repeater. We use “repeat.for” to tell the view engine to create a new table row for each element in our droids array.
Try it out, edit app.html like this:
<template> <h1>${header}</h1> <table> <thead> <tr> <th>ID</th> <th>Name</th> <th>Product Series</th> <th>Height</th> </tr> </thead> <tbody> <tr repeat. <td>${droid.id}</td> <td>${droid.name}</td> <td>${droid.productSeries}</td> <td>${droid.height}</td> </tr> </tbody> </table> </template>
This will produces the following table.
Now, the table might not be that pretty, but something else is…
Notice how clean the View (app.html) and the Model (app.ts) is! It’s just basic TypeScript and HTML practically. For the untrained eye, it’s possible to think that there might not even be any kind of framework involved at all here 🙂
Now this is a big thing as it means:
1. On-boarding of new developers in big projects will be easier.
2. If there’s ever a need to move from Aurelia to any other framework, it’s way easier as there’s less “cruft” to remove.
But I digress, back to the code.
The repeater is very versatile and can handle more data structures than Arrays. For ex it’s possible to iterate over Maps, Sets and numerical ranges.
And the repeater can be used on any element, like template elements and even custom elements. This is pretty awesome imho! 🙂
Using the Aurelia Repeater on a Regular div Element
Say we’d prefer not to use a table for our elements, but instead create another element structure to hold our information.
Let’s use the repeater on a div to hold our droid data from the Web API. Modify the app.html code like this:
<template> <h1>${header}</h1> <div repeat. <div> <span>ID: ${droid.id}</span> <span>Name: ${droid.name}</span> </div> <div> <span>Model: ${droid.productSeries}</span> <span>Height: ${droid.height}</span> </div> <br> </div> </template>
The result will look something like this:
That’s all for this episode, hope you enjoyed finally getting started with some more Aurelia specific code and actually producing some visible results.
Next Part – Creating custom elements to be used in our Aurelia SPA
In the next episode we’ll look at custom elements. How they enable composition reuse and lay a good foundation for testing of our SPA code.
Get the Code
The code for this blog series is available on my GitHub repo, you can find it here: DWx-Aurelia-dotNETCore
Until next time,
Happy Coding! 🙂
4 thoughts on “How to: Fetch data from Web API on ASP.NET Core to an Aurelia SPA”
Pingback: How to: Build a Web API on ASP.NET Core for an Aurelia SPA - mobilemancer
Pingback: How to: Build an Aurelia SPA with TypeScript on ASP.NET Core - mobilemancer
Pingback: How To: Configure and Use the Router in an Aurelia SPA - mobilemancer
Pingback: Unit Testing and E2E Testing an Aurelia SPA (CLI) - mobilemancer
|
http://mobilemancer.com/2016/11/04/aurelia-fetch-client-web-api-asp-net-core/
|
CC-MAIN-2017-22
|
refinedweb
| 1,623
| 61.67
|
Statements (C# Programming Guide)
A statement is a procedural building-block from which all C# programs are constructed. A statement can declare a local variable or constant, call a method, create an object, or assign a value to a variable, property, or field. A control statement can create a loop, such as a for loop, or make a decision and branch to a new block of code, such as an if or switch statement. Statements are usually terminated by a semicolon. For more information, see Statement Types (C# Reference).
A series of statements surrounded by curly braces form a block of code. A method body is one example of a code block. Code blocks often follow a control statement. Variables or constants declared within a code block are only available to statements within the same code block. For example, the following code shows a method block and a code block following a control statement:
Statements in C# often contain expressions. An expression in C# is a fragment of code containing a literal value, a simple name, or an operator and its operands. Most common expressions, when evaluated, yield a literal value, a variable, or an object property or object indexer access. Whenever a variable, object property or object indexer access is identified from an expression, the value of that item is used as the value of the expression. In C#, an expression can be placed anywhere that a value or object is required as long as the expression ultimately evaluates to the required type.
Some expressions evaluate to a namespace, a type, a method group, or an event access. These special-purpose expressions are only valid at certain times, usually as part of a larger expression, and will result in a compiler error when used improperly.
For more information, see the following sections in the C# Language Specification:
1.5 Statements
7 Expressions
8 Statements
|
http://msdn.microsoft.com/en-US/library/ms173143(v=vs.80).aspx
|
CC-MAIN-2013-20
|
refinedweb
| 315
| 53.92
|
hey,
I'm making a crappy little rpg text game. Anyway I set it up so that the player stats are all saved into a class. I have a function which creates the class when a new game is started. The problem is that I can only access the class functions through the function which I used to create it.
I realize this code is probably written very poorly. Anyway, the function that you should worry about is newGame();I realize this code is probably written very poorly. Anyway, the function that you should worry about is newGame();Code:#include <stdio.h> #include <iostream> #include <fstream> #include <string> #include <stdlib.h> #include <time.h> #include <string> class character{ public: int health; int strength; int armor; string name; character(int, int, int, string); ~character(); void viewStats(); string saveStats(); }; character::character(int h, int s, int a, string n){ health = h; strength = s; armor = a; name = n; } character::~character(){ } void character::viewStats(){ cout << "\n"; cout << "Name: " << name << endl; cout << "Health: " << health << endl; cout << "Strength: " << strength << endl; cout << "Armor: " << armor << endl; } string character::saveStats(){ string send; send += name + "#"; send += health + "#"; send += strength + "#"; send += armor + "#"; return send; } int GetRand(int min, int max) { static int Init = 0; int rc; if (Init == 0) { srand(time(NULL)); Init = 1; } rc = (rand() % (max - min + 1) + min); return (rc); } void newGame(){ string temp; int a, b, c; cout << "\nName:"; cin.get(); getline(cin, temp, '\n'); again: a = GetRand(10, 15); b = GetRand(10, 15); c = GetRand(50, 70); character player(c, a, b, temp); player.viewStats(); cout << "\n\nNew Stats (Y\\N)\n\n"; char choice; cin >> choice; if(choice == 'y' || choice == 'Y'){ goto again; } } void clear(){ for (int i =0; i < 25; i++){ cout << "\n"; } } void sort(string command){ int which; which = command.find("\\help", 0); if(which == 0){ cout << "Help menu!"; return; } which = command.find("\\save", 0); if(which == 0){ cout << player.saveStats(); } } int main(int argc, char *argv[]) { int choose; string command; cout << "Menu:\n\n1.New Game\n2.Load\n3.Quit\n\n"; cin >> choose; switch (choose) { case 1: newGame(); break; } clear(); cout << "Welcome to this crappy RPG game. To see the commands type \\? or \\help\n\n"; cout << "It\'s recommended that you save. You can save at any time by typing \\save\n\n"; cin.get(); getline(cin, command, '\n'); sort(command); cin >> choose; return 0; }
Any help would be apreciated thanks
|
http://cboard.cprogramming.com/cplusplus-programming/67433-problem-class.html
|
CC-MAIN-2015-18
|
refinedweb
| 400
| 80.11
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.