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
Agenda See also: IRC log <LeeF> AndyS, can I interest you in scribing pretty please? <LeeF> Scribe: AndyS <LeeF> minutes from last week <LeeF> minutes approved Seconded: AndyS Meet next week: 25 September Regrets in advance: Orri and Ivan <iv_an_ru> I agree with moving to CR in advance :) LeeF: please track DAWG as we will attempt to plan to move to PR. ... next week Orri: diffs of rq25 are OK <LeeF> ACTION: ericP to have first cut of shiny implementation report by 11 Sep [DONE] [recorded in] <LeeF> ACTION: Orri and Ivan to publish URL to test service along with a list of tests that aren't handled correctly yet [DONE] [recorded in] <LeeF> ACTION: AndyS to try SOAP protocol tests against Joseki and Virtuoso [recorded in] <LeeF> endpoints <iv_an_ru> I'm releasing next version of the test suite today. <LeeF> ACTION: AndyS to try SOAP protocol tests against Joseki and Virtuoso endpoints [DONE] [recorded in] <LeeF> action -3 <LeeF> ACTION: LeeF to update open-world manifest with mf:requires for open-eq-12 [DONE] [recorded in] <LeeF> ACTION: LeeF to update Turtle data to have explicit lexical forms and answer Gregory W's mail [DONE] [recorded in] and Andy checked the changes <LeeF> ACTION: ericP to poke IETF folks about registering SPARQL media types (esp. application/sparql-query) [CONTINUES] [recorded in] LeeF: when we advance, should we prompt IETF harder? <LeeF> ACTION: LeeF to put together CR transition request for SPARQL XML format and ericP to publish [CONTINUES] [recorded in] EricP: it should just happen <LeeF> ACTION: ericP to write explanatory text saying that, like xsd:inteter and xsd:dateTime, the relative order of simple literals and xsd:strings is not defined here [DONE] [recorded in] <LeeF> ACTION: ericP to answer "EBV of invalid numeric literals" email from Arjohn [CONTINUES] [recorded in] <LeeF> ACTION: Eric+Andy to identify and collect mf:requires URIs and put in documentation [CONTINUES] [recorded in] <LeeF> ACTION: ericP, AndyS to add the mf:requires labels to the manifest namespace document [CONTINUES] [recorded in] <LeeF> ACTION: ericP to incorporate text to fix EBV of illformed numeric literals bug in spec [DONE] [recorded in] <LeeF> """ <LeeF> The EBV of any literal whose type is xsd:boolean, xsd:string or numeric is false if the lexical form is not valid for that datatype (e.g. "abc"^^xsd:integer). <LeeF> """ <LeeF> ACTION: ericP to try to produce a diff from CR to current editor's draft [DONE] [recorded in] <LeeF>- <LeeF> dawg-comments/2005Jun/0028.html <LeeF> -> original comment that prompted <link> element LeeF: History of link element and summary of discussions with Alan Alan proposes inline metadata to avoid server state. scribe: comment is very late in process. ... would cost another cycle (at least one month). LeeF asks for WG support ... none forthcoming. <scribe> ACTION: LeeF: Reply to Alan's comment on metadata in SPARQL XML Results format [recorded in] EricP: notes binding of, e.g. SOAP, has features. ... to support state LeeF: status: waiting for W3C approval on process <Zakim> ericP, you wanted to note a potential fix to [[• The EBV of any literal whose type is xsd:boolean, xsd:string or numeric is false if the lexical form is not valid for that <LeeF> EBV text (only defined for strings, booleans, numerics) <LeeF> "Effective boolean value arguments (labeled "xsd:boolean (EBV)" in the operator mapping table below), are coerced to xsd:boolean using the EBV rules in section 11.2.2 ." Chair has feedback from implementers about existing HTTP bindings scribe: Elias will have the protocol tests running <LeeF> about SOAP versions AndyS: Virtuoso have offered to back port to SOAP 1.1 <LeeF> beginning documentation of mf:requires <SteveH> there's a lot of background noise here, sorry Change to use mf:XsdDateOperation mf: IllFormedLiterals -- actually used for tricky bits, not extension <LeeF> mf:trickyBitOfSparql ? <LeeF> mf:notewell ? <iv_an_ru> mf:mayAccessAndReturnUnexpectedDataFromGraphsNotListedInManifest ? :) <scribe> ACTION: AndyS: Invent and document an alternative to mf:requires for things that are noteable but not extensions in the test suite [recorded in] <LeeF> mf:LangCaseInsensitivity can be struck <LeeF> ACTION: LeeF to check and annotate open-eq-07 and -10 with mf:LangTagAwareness [recorded in] <LeeF> strike mf:xsd-date-eq-xsd-dateTime <iv_an_ru> Don't remember me about datetimes... <scribe> ACTION: AndyS: Update vocabulary files and README for test [recorded in] <scribe> ACTION: AndyS: Update manifest for mf:requires [recorded in] <LeeF> first draft of implementation report LeeF: more results expected <ericP> the SPARQL queries (and surrounding script) for generating the impl report EricP: A test passes if ... ... no tests => green box (??) <LeeF> (it's a mistake in the algorithm) <iv_an_ru> Why not ? EricP: for any facet, there are certain tests associated with it <LeeF> ACTION: ericP to answer "EBV of invalid numeric literals" email from Arjohn [DONE] [recorded in] EricP: if two facets on a test, test processor calculates the best match as to which facet is the fail ... (e.g. already failed elsewhere for one facet => don't mark a failure for other facet) LeeF suggests seeking wisdom in reporting coverage Steve: can pass some facets without any implementation <LeeF> No matter what, I intend to publish _all_ of the data we have <LeeF> "A test suite gives reasonable coverage of the features of the query language." <LeeF> "Each identified SPARQL feature has at least two implementations." (exit criteria for CR) <LeeF> "Relevant media types are registered:" <LeeF> "Normative dependencies have been advanced to Proposed Recommendation status:" <ericP> HOG++ Our normative dependences are already at REC (Xquery, F&O) Need to decide on "at risk" features: REDUCED, leading numbers in local part of prefixed names <LeeF> also: what to do with syntax tests? <LeeF> SteveH, do you implement REDUCED? <SteveH> yes <LeeF> thx <iv_an_ru> I'm implementing REDUCED before Friday, BTW. <LeeF> :-) Leef: Does anyone want to propose removing REDUCED? (silence follows) <SteveH> REDUCED is a big optimisation win for me in certain circumstances <iv_an_ru> I've found REDUCED very useful for at least one optimization. <LeeF> Great, good feedback to have. <SteveH> but maybe if I had a streaming DISTINCT impl. it wouldn't be so useful There is no "REDUCED" in the test suite. <iv_an_ru> REDUCED is especially useful when there's a join between union that is faster when UNION and union that is faster when it's UNION ALL. LeeF: Leading digits. Several implementions support it LeeF: asks for proposals NOT to keep this feature. ... needs to get into interop report. Eric: Min is 4 week in PR. <LeeF> ACTION: LeeF to investigate PR mechanics, put together draft transition request [recorded in] Ivan: Mitko has deployed a SOAP 1.1 endpoint <iv_an_ru> Andy, I know. Souri: working to export RDF_MATCH to SPARQL query engine. ADJOURNED This is scribe.perl Revision: 1.128 of Date: 2007/02/23 21:38:13 Check for newer version at Guessing input format: RRSAgent_Text_Format (score 1.00) Found Scribe: AndyS Inferring ScribeNick: AndyS WARNING: No "Present: ... " found! Possibly Present: AndyS Eric IPcaller Ivan Leef Orri P29 P32 P33 P7 P9 Seconded Souri Steve SteveH abc afs also datatype ericP imitko inserted integer iv_an_ru mf xsd You can indicate people for the Present list like this: <dbooth> Present: dbooth jonathan mary <dbooth> Present+ amy Regrets: chimezie Agenda: Got date from IRC log name: 18 Sep 2007 Guessing minutes URL: People with action items: alternative an andy andys document eric ericp invent leef reply[End of scribe.perl diagnostic output]
http://www.w3.org/2007/09/18-dawg-minutes.html
CC-MAIN-2014-10
refinedweb
1,240
53.55
Agenda See also: IRC log <scribe> scribe:TRutt <scribe> scribe:TRutt Jonathan stated that Microsoft has already implemented several of the FaultCodes that we agreed to eliminate on Thursday. We agreed to put back DestUnreachable, ActionNotSupported, and EndpointNotAvailable Katy asked if these had to be implemented to claim conformance Bob F stated that they do not have a MUST constraint anywhere in the spec, David: Implementation of these faults are optional (for the last three we are adding back in) Agreed to add this note to the descriptions of each of these three faults RESOLUTION: Insert after the description of "destination unreachable" action not supported" and endpoint not availalble, the following: "implementation of this fault is optional." <Jonathan> Paul: we lost the asynchronous tests from SUN. The test implementations need more work. <pauld> as does the report <pauld> and collection of logs which are dip feeding in from various sources asynchronously Jonathan: microsoft/IBM and IBM/microsoft, IBM/IBM, and microsoft/Microsoft are all OK. Marc H: there could be a problem with the logs, our developers state the implementation is correct. Paul: we could have problems with collecting the logs, or with generation of the report. Some of the "green" boxes could be wrongly idenfitied as well. Jonathan: I do not think we have fundamental issues. ... the biggest risk is that we do not have 4 complete implemenations. Glen: once we fix some of the AXIS problems, that could be fixed. Paul: we might have 5 implementations, but some of the features may have a different set of 4 implementations. Bob F: are there any changes which need to be made to the spec. Paul: I do believe we have found the problems in the text already, and we have already reported those to the group. Bob F: what remains is documentation of 4 interoperating implemtations for all of the test cases. Bob F: would be good to have the test documentation completed by March 13 WG teleconf. Hugo: intention to go to PR from the WG on March 13. <Zakim> Jonathan, you wanted to close with no action Bob F stated that the at risk feature for wsa:from has been stated by several groups as a feature that they have a use case for. Paul D: none of the implementations have used this feature. Paul D: My statement is incorrect. there are implementations which send wsa:From. We could add one test case to show that implemtatations can deal with it. Marc G: since its optional we need two implementations to send it. <pauld> notes that a test case could be 'don't bail on reception of a message with wsa:From' and then make sure three others interop with WSO2 Umit: I recommend that we close this issue with no change. Even though there is no explicit fallback to use of wsa:from in the behaviour text for replies, some users have found a reason to use this. <bob> scribenick: TRutt Jonathan: the spec has the field, but does not say what to do. RESOLUTION: agreed to remove the "at risk" note from the CR text, and close the features at risk issue. Glen stated that the axis implementation can generate the wsa:from element, and can do so for testing purposes. Hugo: we should ensure that the complete implementations can all receive messages with all the optional features. Paul D: we should add a test case which has wsa:from with mustUnderstand=true. Hugo took the action to add the new test case for wsa:from generation with mustUnderstand=true Bob F: this is a posponed issue on [Details] for wsa:ActionMismatch Subsubcode) Dave H: add text to section 2.4 of soap binding- "This invalid addressing header fault MUST/SHOULD contain a problem action fault detail. Jonathan: I do not think we need to do this, given the existing text. RESOLUTION: agreed to close CR2 with no action. <dhull> <bob> This will be cr25 tile of issue Use SOAP 1.2 properties where possible in describing SOAP 1.2 behavior. There were no objections to accepting the proposal, as an editorial change RESOLUTION: accept D Hull proposal for CR25 as editorial change John Kemp sent concern in email Discussion led to conclusion that the original resolution was still acceptable to WG Jonathan: we can point to the existence of xml:id. ... there is no local id attribute because xml:id exists. RESOLUTION: Editor will provide additional text pointing to existence of xml:id Bob F: we need to have someone give a response to John Kemp Jonathan took action to prepare response to John Kemp on our reconsideration of CR3 Bob F asked if there are any additional issues on the Core spec. There were no further issues identified. Bob F: since we have no further issues, we have to produce the final version of the docs to review, and recommend for progression to PR. Glen: when will the formal objections be reviewed and resolved. Mark N: the director has seen the formal objections, and has not sent feedback to the WG. Glen: what message did he send. Marc N: the messages was "yes you can go to CR" Hugo: until we are in recommendation, the director can say we have to resolve a particular formal objection. Officially we have to wait to see if he will assert on these objections, which he has already seen. Bob Bob F asked if any companies change their allignment with either of the formal objections. No company wished to change their alignment. Bob F asked the editors when they will have documents incorporating all resolutions. Marc H stated the documents would be ready by the end of the day. Bob F: I ask all members to review and send any coments before March 13. The intent is to vote to progress to PR at the March 13 meeting. Hugo: we should publish the soap 1.1 note at the same time as the PR. Bob F: Hugo will schedule a call with the Director after we vote to go to PR. The PR should be availalbe by the end of March, give a WG decision on March 13. s/LC01/LC109/ D hull: you can leave the faultTo empty if you have a replyTo present. Marc H: we need to clarify "either this or that" Katy: the fault endpoint may be able to be derived by different means than presence in the request discussion ensued on table 5-5 Marc H : suggest comgining reply endpoint and fault endpoint rows. Dave H: for Table 5.5, and Table 5.7 , and Table 5.2, we can change entroy for fault endpoint to Y with asterisk, with asterisk pointing to reference to section 3 of core. Anish: I prefer the merger of the two rows into "response endpoint". Call attention to section 3.4 of core regarding the fault endpoint semantics. Umit: I would rather not combine the two rows, I prefer Dave H proposal. Jonathan: concensus that one of reply endpoint or reply endpoint properties should appear in table 5.5. <TonyR> a/reply endpoint or fault/reply endpoint or fault/ <umit> i would really like an example just like Anish. Combination of the specs need to be illustrated. Dave H: it should be clarified that for robust in only the fault endpoint defaults to the reply endpoint. RESOLUTION: LC109 - at least one of reply endpoint or fault endpoint properties should appear in table 5.5, with some indication of the co-constraints in the core spec Jonathan: this applies to table 5.6 and 5.8. Marc: table 5.6 was the first place it applied. Anish: what is good for reply is good for fault. We should not prohibit. Marc H: you canot give a fault to a fault message in soap. Tony R: all fault messages should have this note, not just the robust meps. Dave H stated that we should not prohibit a fault to a fault. <dhull> Just wondering whether it's our job to try to prohibit fault to a fault Tony R: in 5.2.3 we do not distinguish fault. Marc H: that is because it is an out. RESOLUTION: LC110 agreed to be closed with no action. Bob F: this came from the WSDL 2 group. Hugo: the proposal is " Section 3.1.1 says: A property of the binding or endpoint named {addressing required} of type xs:boolean should be phrased: A property {addressing required} of type xs:boolean, to the Binding and Endpoint components Marc H: typically you put it on one place or another, not both RESOLUTION: LC111 resolved by accepting Hugo proposal. Marc H: you either do or do not support addressing Tony R: addressing required is a mandatory boolean property. Anish: supported but not required forces a false value for "addressing required". Glen: we could have values "none" , required, and optional ... having two values "required" and "optional" for this attribute. Jonathan summarized on the whiteboard what we have today. Jonathan: if using is on binding ti goes to both binding and endpoint. If using is on endpoint, it does not go to binding. Anish: I like having the values "required" and "optional" string enumerations. Jonathan: we need to clarify 3.1.1 to say what we want. I do not like calling these "required" properties. if the existence of the property depends on the syntax of "using addressing" Tony: could be change "required" propety to "mandatory" property. Jonathan: exisence of using addressing on binding results in the required attribute to be true in binding. Anish: I do not understand what required means in this context. Katy: I challenge our earlier decision to put using addressing on endpoint <uyalcina> +1 to Katy <anish> i see the following columns for the table: 1) what's in the syntax, 2) does the processor recognize the extension, 3) wsdl:required value, 4) property present in the component model 5) value of the property in the component Jonathan: we can restrict the rules for bindings to be separate as for endpoint. Anish proposed a table with 5 columns to express the semantics of using addressing to components. Jonathan: we need to remove the word required in the text, and to have a link from binding using addressing to binding component, and another link form endpoint using addressing to endpoint component. Group broke for lunch, to think about proper resolution for this lc issue <Jonathan> Scribe: Jonathan Marc has checked in draft PR docs. Hugo will send a link to the snapshot to the WG. Bob: before lunch, Anish was thinking of a table. Jonathan was talking about a list of actions to resolve this issue. Jonathan: Proposal: ... Section 3.1.1: remove the word REQUIRED. ... Describe that UsingAddressing on Binding annotates Binding component, ... Describe that UsingAddressing on Endpoint annotates Endpoint component, ... Possibly note that both values must be considered to determine whether Addressing is required for a particular message. Anish: wsdl:required should not be used directly as the value of the property. ... Might want a different value set for the property. Glen: Would be nicer if the property existed or not, and then a separate property for the value. ... If wsdl:required=true the value should be "required", if wsdl:required=false or not there, the value should be "optional". Tony: I like "addressing support" with the possible values of "required", "optional", "not known"/"not supported" Anish: If the sytnax doesn't exist, you can still add the property. ... The processor doesn't understand addressing, it won't be a property in the component model. Jonathan: Be clear on component model - it's subtle. Anish: Just change the naming of the property. Bob: Regardless of the name, we have relationships. We need first to get relationship. Tony: Want to allow the property appear even when there is no UsingAddressing extension. Marc: Strange since you're telling people about yourself. Tony: Want the third property to encompass that there is no addressing support here. ... Not happy that absence implies it's supported. ... How can I describe the service as not supporting addressing?> Anish: We don't have such a marker. Katy: Send a mustUnderstand="1" and get an error back. <marc> can't imagine a service ever saying wsa:addressing_support="unknown" Tony: Thought that was what the tri-state is about. Marc: It really only has two states. You either require it, or you don't. Glen: It says, I support, or you have to use. Marc: You don't have to tell I support. No new information provided. Anish: We have three states in the value. ... and presence. marc: But if it's not present, it's not telling you that the service requires addressing. Anish: Maybe the service isn't telling you but it is still required., (don't go there) Glen: Difference between supported and required, and no indication. ... If you understand addressing, you've gotta do it. Marc: from the services perspective, you say UA=true when it's required. ... when it's not, you put it in or not. ... doesn't matter which. Glen: How does that map to component model properties? Should be this addressing use property. Anish: If you require addressing, you must put UsingAddressing in the WSDL? Marc: Not that far, just if you require it and you want an interoperable mechanism, use this one. Umit: Provision in WSDL for this marker. We went through this well in WSDL. Marc: My proposal is equivalent to {prop}="true" or not there. "false" doesn't give you any other information. Glen: "false" tells you that you understood the marker at least. ... If you don't support WS-A in the syntax, you shouldn't support it in the component model. Jonathan: Thinks there is a difference. "False" means you can send the headers with mu and not expect a fault. Glen: If you see this at the WSDL processing time, I will know whether I can send those headers or not. I might want to fault if the service doesn't delcare support for WS-A. ... Tricky case is the optional one. We're overloading the marker to mean "process the WSDL" and "allows WS-A". ... Once its in the component model, you're supposed to use WS-A at that point. Tony: wsdl:required is different than addressing required. Glen: Those concepts do get confused, both in SOAP and WSDL. We've been trying to overload that. <Zakim> anish, you wanted to ask marc how his view would look like in terms of the component model Jonathan: Believe they collapse in practice. Anish: Spec says if you put an annotation in and say wsdl:required, it may change the meaning of the element to which it's attached. ... The qname we've defined means that you have to use addressing if required=true. ... We define the meaning of the QName. Glen: It says the meaning of [parent] might change when you understand [extension]. ... in practice it works out Ok. It's your choice to "understand" or not. Anish: Can you translate how that translates to the component model. Marc: Not up on cm speak. Glen: If you don't understand the element you can't annotate the cm. Umit: Provider puts the extension in. Client's perspective it contributes to the component model. Glen: Choices are: understand the required extension or fault. <anish> it turns out that it is not us who are getting confused about overloading wsdl:required. The wsdl spec says the following: <anish> "A key purpose of an extension is to formally indicate (i.e., in a machine-processable way) that a particular feature or convention is supported or required." <Zakim> marc, you wanted to talk about table 3.1 (scribe loses a bit) Marc: I'm willing to change my position. Spec says there are different requirements on an endpoint depending on whether they've put this in the WSDL or not. ... Table 3-1. Key difference is MAPs in input message. ... If you put it in, you have to accept addressing headers. ... Component model does need to reflect tri-state. Bob: Tri-state issue, seems discussion revolves around whether this. Katy: Required/supported/not-known are the states in the table. Glen: This is a problem with WSDL, I don't know what properties there are, what good does an abstract model do? Jonathan: That's taken care of us by WSDL - read the Extensions part. Bob: What's the proposal then? Jonathan repeats. Essentially asking for a mapping of XML to component model. Hugo: I proposed a mapping originally, Marc said it duplicated a lot of things. ... Group said we can keep what we have. Jonathan: Asserts that failed to be clear enough. ... Would like to follow WSDL's style. Bob: Fundamental objections? Glen: Takes the WSDL required value rather than a different value. Anish: Call it {addressing} = "required ... " / "optional" Glen: call it {using addressing} Jonathan: Proposal: <Jonathan> ... Section 3.1.1: remove the word REQUIRED. scribe: Add mapping of XML to component model ... Possibly note that both properties must be consulted. ... Change property name to {addressing}, values "required" / "optional" Glen: Namespace properties? Jonathan: Didn't namespace the core WSDL properties. No framework for doing that. Bob: Accept the proposal? Katy: Looking at 3.2.1, might be impacts there. Marc: Needs more editorial direction. Hugo: I'll draft some text. <scribe> ACTION: Hugo to draft mapping to CM of UsingAddressing. [recorded in] RESOLUTION: Proposal (see above) accepted as resolution of lc112. ... and equivalent editorial changes to 3.2.1. ACTION 1=Hugo to draft mapping of CM to UsingAddressing and Anonymous ACTION 1=Hugo to draft mapping of CM to UsingAddressing and Anonymous, and Action Hugo: This section should be translated into WSDL 2.0 lingo (CM instead of XML) ... Also not too clear on where it is allowed, have to chase references to intersect where UsingAddressing and soap:module are both allowed. ... We should do the math for our readers. The intersection is the Binding component. Glen: Not on endpoint? ... Didn't we fix that at some point? Hugo checks. Glen: Need separate bindings for differnet module combinations? Too bad. Bob: Objections? Umit: UsingAddressing and soap:module have different expressive powers? Glen: Researching a WSDL issue, we need soap:module at endpoint level. Umit: Doesn't like this at the endpoint. Would rather we removed UsingAddressing at the endpoint. Bob: Proposal acceptable as it stands? Umit: Need to check editorially that we don't imply UA and module are equivalent. Glen: Equivalent semantics, but not equivalent places you can put it. RESOLUTION: lc113 closed by accepting Hugo's proposal ... plus editorial check that we don't imply UA and module are completely equivalent. RESOLUTION: Fix typos. ... lc114 closed by fixing typos. RESOLUTION: lc115 closed by accepting fix. Bob: Doesn't say how this extension affects the WSDL 2.0 CM. Jonathan: Let's do it. ... property is a list of elements. Anish: What about attributes on the wsa:ReferenceParameters element? Are they lost? ... Isn't there a type for reference parameters already? ... So use the same type as the [reference parameters] property in 2.1 of Core. Umit: We discussed it, we just forgot? Proposal: Add a {reference parameters} property to the WSDL 2.0 component model, with the same type as the [reference parameters] property in Core 2.1 RESOLUTION: lc116 closed with proposal above. Bob: Call on the 13th is the last opportunity to touch the document. Our fundamental reason for the call is to pass the document off. The meeting will last as long as it takes. Jonathan: suggests we require any comments to be accompanied with a complete and detailed proposal. <pauld> +1 to Jonathan RESOLUTION: Comments must be accompanied with a detailed proposal. Anish: Once it goes to PR it's out of our hands. Hugo: It's in my hands, so small changes (e.g. editorial) can be made as a result of AC or other comments. Bob: Would like to hear from the test group after the meeting on tuesday, if there are issues that mean we'll slip the date we'll have to reschedule. ... No reason to hold the 8th call - cancelled. ... FTF in Cambridge, MA for May 4-5(?) by IBM. ... Pencil in the FTF. Jonathan: Thinks we'll need it. Bob: Don't buy tickets quite yet though. ... This is your 8 week notice of the FTF. Possibility it might be cancelled though. Ajourned...
http://www.w3.org/2002/ws/addr/6/03/03-ws-addr-minutes.html
CC-MAIN-2017-30
refinedweb
3,421
67.25
Hi, The following code compiles in Eigen 3.2.9 but fails to compile starting 3.2.10 and in the current release (3.3.1) #include "include/eigen3/Eigen/Sparse" #include <iostream> int main() { Eigen::SparseMatrix<double> sm(5,5); std::vector< Eigen::Triplet<double> > tpl; tpl.push_back(Eigen::Triplet<double>(0, 0, 1)); tpl.push_back(Eigen::Triplet<double>(0, 1, 2)); sm.setFromTriplets(tpl.begin(), tpl.end()); sm.row(0) *= 2; std::cout << sm << std::endl; return 0; } The error I get is: include/eigen3/Eigen/src/SparseCore/SparseCwiseUnaryOp.h:127:42: error: no type named ‘InnerIterator’ in ‘class Eigen::Block<Eigen::SparseMatrix<double>, 1, -1, false>’ for (typename Derived::InnerIterator i(derived(),j); i; ++i) ^ include/eigen3/Eigen/src/SparseCore/SparseCwiseUnaryOp.h:127:42: error: no type named ‘InnerIterator’ in ‘class Eigen::Block<Eigen::SparseMatrix<double>, 1, -1, false>’ More generally, any function that tries to access InnerIterator on a Block access to a SparseMatrix fails similarly (and perhaps logically). (note: I don't have any other example from within Eigen itself) The sparse module documentation would indicate this is working as intended since accessing a row of a ColMajor sparse matrix should be read-only. However, it used to work until 3.2.10 (I believe introduced the breaking change but the error is different from 3.3 as it relates to the absence of RefValue in the new sparse common iterator class introduced by this commit). Note that it's possible to work around the bug by doing what the *= operator does without the block in the way: (this work-around is also broken in 3.2.10) for(int k = 0; k < sm.outerSize(); ++k) { for(Eigen::SparseMatrix<double>::InnerIterator it(sm, k); it; ++it) { if(it.row() == 0) { it.valueRef() *= 2; } } } You can workaround with: sm.middleRows(0,1) *= 2. The thing is that since sm is column major, sm.row(0) is not writeable. The fact it worked in 3.2.9 is due to a side effect of a bug fixed by the commit you pointed out. For instance, in 3.2.9, SparseVector<double> vec = sm.row(0) does not work. Nonetheless, in 3.3, operator*= should be fixed to use an evaluator to get an InnerIterator, but that's not fully helping because the iterator we get is read-only, and make it potentially read-write is not straightforward (lot of meta programming and addition specializations...). Moreover, be aware that the cost of this operation is O(sm.cols()+sm.nonZeros()) because you have to iterate over all columns, and for each column search for the respective coefficient if it exists. So this should only be done for rapid prototyping. Finally, I found an easy way to fix this: Summary: Bug 1359: fix sparse /=scalar and *=scalar implementation. InnerIterators must be obtained from an evaluator. Summary: Bug 1359: fix compilation of col_major_sparse.row() *= scalar (used to work in 3.2.9 though the expression is not really writable) 3.3 backports: For 3.2, if you really care, feel free to propose a patch based on
http://eigen.tuxfamily.org/bz/show_bug.cgi?id=1359
CC-MAIN-2018-17
refinedweb
517
51.75
I have access to un-copyrighted shape files for the National Parks in Alaska and want to add them to OSM. I have read of problems with the plugin for JOSM and wonder if any of you know of a good freeware conversion program that will generate a GPX file that I can then import into JOSM. I'm about to set up a program called DNRGarmin, which will reportedly do the conversion, but will wait for some input here before I proceed. There are many National Parks in what we Alaskans call "the lower 48" already in the OSM database. I'm curious to know how these got there. Thanks Dave asked 25 Mar '14, 04:53 AlaskaDave 5.2k●75●106●162 accept rate: 16% edited 25 Mar '14, 07:12 iii 4.9k●8●40●82 There is a great need for these additions in Alaska as many are missing. I added this state park a few days ago but there are National Wildlife Refuges, Nat'l Parks, Wilderness Areas, and National Forests aplenty in Alaska. Way: Denali State Park (268206171) Alaska Dave, I have a similar project - adding shape files (.shp) for 48 election precincts to the Bell County, Texas, area of "the map". Actually, I'd like to add the shape files for all 254 counties of Texas - I have the zip file from the Texas Legislative Council GIS team. . . . I just searched for and studied GPX format. Apparently, I do not need to convert to that. . . . I just want to import the shp files as a layer of OpenStreetMap. I'll just contact the Texas Legislative ofc and ask them for help. No reply necessary. I don't know much about shape files, but in looking into adding land cover found some US Gov. (okay copyright for OSM) shape files and found that you can load them directly in JOSM. Might need a open data or some such plug-in. You can then copy the boundary/area polygon from the shape layer and paste it into the OSM data layer, change the tags to be those used by OSM, and you are ready to upload. Well, not quite ready: You should do all the recommended QA checks, etc. before uploading. With respect to landcover, the data set I found was okay for a "broad brush" but I sure had to go into the area looking at satellite imagery and photos from when I hiked the area to get the detail better. You shouldn't have that issue with boundary information but you may have overlaps with older polygons that attempted to show the boundaries, etc. answered 03 Feb '19, 22:07 n76 10.0k●9●78●160 accept rate: 18% (I know that you've not suggested doing it, but for the benefit of anyone else reading this question in the future): What I wouldn't do is to upload any resulting GPX to OSM. That would be problematic for a couple of reasons - one is that GPS traces in OSM are a bit like a "roach motel" - once traces are uploaded and other services (like iD's background GPS layer) read them, there's sometimes no way of removing those traces. The other is that, in places where GPS traces representing roads and tracks are few and far between, uploaded traces that don't represent actual paths get horribly confusing. Someone uploaded some low-level administrative boundaries in central England, and when trying to average out a position based on GPS traces you need (if not filtering manually with JOSM) to continually mentally remove the ones that aren't. answered 26 Mar '14, 12:30 SomeoneElse ♦ 35.6k●70●363●847 accept rate: 16% But aren't all boundaries merely sets of points on a line, i.e., a set of points that is functionally identical to a GPX file? I have uploaded boundaries for a couple of designated Wilderness Areas in Alaska using a GPX file I converted from KML that I obtained from Wilderness.net. See the Kenai Wilderness and the Togiak Wilderness for example. They appear perfectly fine. Way: Kenai Wilderness (264567744) 994 nodes part of Kenai National Wildlife Refuge relation (not yet entirely added) How else can one do this if not to use a GPX file? A boundary is a set of points, but it's not a set of points that corresponds to anything in the real world. By all means use a GPX file locally (in JOSM or iD you can definitely do this), but uploading that GPX to OSM would make other people think that it corresponds to a road or track. I added those areas without consulting anybody else because a) I didn't think it was any big deal, and b) they were relatively simple. I was, and am, excited to be able to add some important information to the map of Alaska. Of course I tagged the boundary with appropriate tags — leisure=nature_reserve, etc. I uploaded it as a relation, not as a GPX track. I uploaded it as a relation, not as a GPX track. ... which is not a problem at all, of course. Well they say that JOSM with OpenData plugin can handle shapefiles without any external help: There are also a lot of conversion scripts at the website. I guess it's worth a try as you get real OSM shapes in high quality and you don't need to manually trace the shape. Of course you should always pay attention when you do imports. Good luck! answered 25 Mar '14, 07:54 iii 4.9k●8●40●82 accept rate: 10% The data file I have is quite large (9 MB) and contains the boundary data for ALL Alaska national parks. There are many precautions and warnings about imports and I will not simply import all of that data and upload it to OSM. What would be ideal is to deal with one park at a time, convert it to GPX and look it over carefully before adding it to OSM. My hope is that there is a program out there that will convert that big shapefile into pieces for each park that are in either GPX, KML or some other more user friendly format, so they can be massaged before attempting to open them with JOSM. As the wiki link say, you might want to use QGIS to do this filtering and splitup/export. But I highly recommend to get in touch with the local community to coordinate the final data import. IMHO thats in the spirit of a crowd :) Well, there simply aren't many mappers working in Alaska. Who do you recommend I coordinate with? I'm not familar with the Alaska community but we have multiple ways to get in touch with people: If you don't find a superlocal channel, you might consider to ask at TALK or IMPORTS mailinglists. Josm can handle shape files of 9Mb or larger. For larger shapes (hundreds of MB) I use Qgis to select smaller shapes and edit that in Josm. This also depends on your computer power. In Josm you can also copy the shape that you are interested in (a park boundary for instance) to a new data layer, edit it and upload it from there, no need to upload the whole dataset at once. I was able to import the 9 MB file into JOSM with the OpenData plugin but it took about 30 minutes to do it. This on a pretty fast i7 laptop with 8 GB of RAM. I stopped waiting after a while and watched a movie — eventually it finished. The data looks good but it's complex. Some parks have several pieces and they're all too big to get into a single JOSM window. So, how to proceed? I plan to talk to the Imports mailing list before doing anything else. Once you sign in you will be able to subscribe for any updates here Answers Answers and Comments Markdown Basics learn more about Markdown This is the support site for OpenStreetMap. Question tags: josm ×610 import ×193 shapefile ×84 conversion ×16 shp ×9 question asked: 25 Mar '14, 04:53 question was seen: 14,322 times last updated: 04 Feb '19, 00:27 Importing shapefile and saving to OSM with Potlatch2 Ogr2Osm: Imported data shifted by 176m, 222°(exported from ArcGIS) Is there any possibility to download data into shape format? (.shp) import image into JOSM números de portal en SHP como los subo todos de una en addr:housenumber Create local new .osm file from 3rd party shapefile Importing PDF JOSM Can I import shape files? How do I import map data from a .dwg file to OpenStreetMap? [closed] How to Import Building Shapefiles First time here? Check out the FAQ!
https://help.openstreetmap.org/questions/31868/how-do-i-convert-shp-files-to-gpx?sort=active
CC-MAIN-2022-33
refinedweb
1,474
69.52
Use Facelets Support Modules on NetBeans 6.1 By poting on May 14, 2008 To use the Facelets support modules that we have downloaded or built from the source in my pervious blog, 'Build and Install Facelets Support Modules on NetBeans 6.1', I will briefly describe how these support modules will help your development works here. Create Facelets Support Web Project After installed the Facelets Support, you will find a new entry 'Facelets' in the Frameworks panel when you create a new web project. Select and check this entry before clicking on Finish. Multiple frameworks selection should work but is not a supported feature as there is no much testing has been done here. As you can see, options for 'JavaServer Faces Configuration' are all non-editable because the project creating currently only supports the default settings. However, it is still possible to modify them after the project has been created. - Debug: control the facelets.DEVELOPMENTparameter in the web.xmlfile. <context-param> <param-name>facelets.DEVELOPMENT</param-name> <param-value>false</param-value> </context-param> - Skip Comments: control the facelets.SKIP_COMMENTSparameter in the web.xmlfile. <context-param> <param-name>facelets.SKIP_COMMENTS</param-name> <param-value>true</param-value> </context-param> facelets.SKIP_COMMENTSto your project's web.xmlfile with truevalue. - Create Example Facelets Files: create a simple welcome page. - Libraries: the bundled Facelets libraries 1.1.14 are default selected. You may create your own version of library or just do not append any in case you plan to have your own copy of Facelets support libraries installed in your target servers. The concept is the same as seen in the 'JavaServer Faces' framework. Note: You may want to create a new Facelets library for different version or the latest distribution got from the Facelets project page. Check the Create New Library under the Libraries tab, use the Browse file chooser to locate the folder where you unzipped the Facelets distribution and enter a meaningful Version number for later reference. The IDE validates the folder if it contains jsf-facelets.jarand a libdirectory. The newly created library will later be shown in the Library Manager as well. To see what you have for the new Facelets project, expand the folder nodes under the Project panel. The IDE recognizes a file as a Facelets file if:The IDE recognizes a file as a Facelets file if: - it has xhtmlextension - its root tag includes the list of namespaces Add more Facelets Pages and Contents Now we are going to add more interesting contents to our Facelets project. When you focus on the Facelets .xhtml editor, you will notice that there are extra palettes available for your Facelets pages. Let's add more JSF components into our boring welcome page by drag-n-drop the palette to the .xhtml editor. I have done here by just drag-n-drop an outputText and a commandButton to the editor and change their values to something meaningful. <ui:define Hello, this text comming from template client. <p> <h:outputText <h:commandButton </p> </ui:define> Click on the Run button and you will see the following contents appear in your browser: To add more Facelets files to your project, right click on the Web Pages node and select New -> Other... to invoke the New File dialog. Select the JavaServer Faces category and you will see there are 3 templates for the Facelets support: - Facelets Simple File: Create a simple Facelets file, an xhtml file which has <html>tag as a root tag and also defines uinamespace. - Facelets Template: Create a new Facelets template with the option to choose from eight layouts either be done through cssfile or tabletag. When you select the CSS style, the IDE will generate an xhtmltemplate file which uses the CSS <div>layout style and refers to a newly create cssLayout.cssfile under the cssfolder if it is not there. Otherwise, it will just refer to the exist cssLayout.cssfile without change the contents. If you select the Table style, the new xhtmltemplate file will use the HTML <table>style and refer to a newly create tableLayout.cssfile instead. Both the cssLayout.cssand tableLayout.cssfiles contain the layout definitions. - Facelets Template Client: Create a new Facelets template client by the Template selected, mandatory. The IDE will parse the selected Template and generate <ui:definetag in the client file for every <ui:inserttag found. You can also choose either using the <html>tag or the <ui:composition>tag as the root tag in the generated template client. Use Code Completion The IDE provides tag code completion for all Facelets tag libraries that are included in the web project. The IDE scans the tag libraries definition file in the same way as Facelets does. These XML files can be referenced in the following two ways: - In a " ;" delimitted list within your web.xmlunder the init-param " facelets.LIBRARIES". - In JAR's META-INFfolder with a file extension of " .taglib.xml".:More available prefixes are also available when drag-n-drop components from the Palette: By default, the Facelets tag code completion provides tag attributes for the following standard Facelets libraries:By default, the Facelets tag code completion provides tag attributes for the following standard Facelets libraries: The namespace will automatically be imported into the root tag when you drag-n-drop a Facelets component or by using the code completion to add one. Extra html tags support for the attribute jsfc(JavaServer Faces Component) are available (see Facelets developer documentation) from the code completion. classpathfor all tld files. The code completion will provide extra attribute support if the tldfile defines the Facelets Tag library. Their associate dynamic help will also be provided. Use Hyperlink By using the Hyperlink, developers can fast navigate from one source to another reference. You can visualize the link by holding down the CTRL key and mouse over a hyperlink active area. After you see the text changed into a link, click on it by the left mouse button. An appropriate source should be open. The tables below briefly displays this feature in the Facelets support. - Hyperlinks in Facelets tags - Other hyperlinks in Facelets files Refactoring Support The refactoring support processes all files in the list of JSF configuration files. Bean and Java class/method usages are found in bean and alias elements and their subelements, as well as elements in the util namespace. In the following examples, it creates 2 managed beans, ManagedBeans.java and ManagedBeans2.java. Right click on the ManagedBeans.java node and select Refactor -> Rename... and then click on Preview under the dialog. You will see the preview of refactoring ManagedBeans.java. The second example shows renaming the package name from foo to bar. Move support associate with the refactoring is also provided. The following example shows the preview of moving ManagedBeans.java from package foo to package bar. Save Delete support associate with the refactoring is also provided which will search the usage with preview.Save Delete support associate with the refactoring is also provided which will search the usage with preview. Find usages The Facelets support will plug into the Java find usages to show JSF beans definitions which refer to Java elements (classes, methods, fields, properties). The Find Usages action will be available for bean definitions as well, to show beans used by other beans. The following example shows how the managed bean file, ManagedBeans.java has been referred by the JSF configuration files and other bean files. Create Sample Projects There are two sample projects included in these modules. The first one is Facelets Template Examples that shows the example of layouts usage. The second one is the well known Number Guess Example by using the Facelets. You may simply create the project and deploy to see the Facelets in your browser.
https://blogs.oracle.com/poting/category/Sun
CC-MAIN-2016-36
refinedweb
1,299
56.55
: - Consumers must support consuming generic types and methods. - Extenders must support consuming and extending generic types and methods, but need not support defining new generic types and methods, or overriding existing generic methods. - Frameworks may expose generic types and methods if they conform to the new CLS rules for generics.: - The name of a generic type must encode the number of type parameters declared on the type. The name of a nested generic type must encode the number of type parameters newly introduced to the type. Typically done by the compiler automatically, you may encounter these “mangled” names when using Reflection over generic types. - Nested types shall have at least as many generic parameters as the enclosing type. Generic parameters in a nested type correspond by position to the generic parameters in its enclosing type. Typically done by the compiler automatically, this essentially means that nested types “inherit” the type parameters from their enclosing type. - A generic type must declare sufficient constraints to guarantee that any constraints on the base type or interfaces would be satisfied by the generic type constraints. The C# & VB.NET language already requires re-declaration of type constraints in this manner. - Types used as constraints on generic parameters must themselves be CLS-compliant. The natural continuation of existing CLS rule 11. - The visibility and accessibility of members (including nested types) in an instantiated generic type shall be considered to be scoped to the specific instantiation rather than the generic type declaration as a whole. This rule ensures languages with different accessibility rules for generic instantiation can interoperate. - For each abstract or virtual generic method, there shall be a default concrete (non-abstract) implementation. If you provide an abstract or virtual generic method, provide a concrete implementation so languages which can’t define new generic methods can consume your API.! I have a couple of questions related to #6 at the end of your post: 1) Isn’t an "abstract method with a default concrete implementation" not an abstract method at all, but a virtual one? And doesn’t a virtual method always have a concrete implementation? In other words, couldn’t this requirement be restated as "abstract generic methods are prohibited?" 2) Does "generic method" mean just methods with their own type parameters (as in void Foo<T>(T t) {}) or does it also include methods whose parameters or return types are generic parameters of their enclosing type (as in class Foo<T> { void Foo(T t) {} })? Another more general question: You mention that J# is a generics consumer in Whidbey. Could you give more information about exactly how J# is able to consume generics in a language that doesn’t have any such concept? Has any effort been made at all to provide any level of compatibility, or at least non-conflict, with Java 5.0’s own generics implementation, which is implemented in a radically different way than Whidbeys? For example, how would J# code work with a List<String>? I’m a little disappointed not to have gotten any response whatsoever to my questions. I don’t always expect responses from blog comments, but when you specifically ask people to leave feedback and questions in the comments, it’s a little rude to then ignore them. I still love Microsoft bloggers in general, but if you’re going to specifically suggest a particular form of feedback, you really ought to give some feedback back. good article Happy a new year That generics will be a required part of the CLS as of the .NET 2.0 release is huge news for the developer, who now has to deal with them in public APIs whether you like to or not. In Whidbey, J# shall provide the ability to consume any ".NET generic type" (whether it is part of the .NET Framework, or authored in other languages). Note that this includes the ability to consume generic classes, generic interfaces, constrained generic types, generic methods, instantiation at primitive types and value types and reference types. J# shall provide full access to all of the generic APIs in the .NET Framework. While most of the syntax will be similar, J# does not support wildcards. Code that is using such wildcards will need to be modified before compiling with J#. Also, the libraries that ship with J# will remain at their current level. Post-Whidbey, J# shall introduce support for authoring generics, and we shall certainly be keeping compat with Java 5.0 generics in mind. The documentation delivered with J# (accessible through MSDN too) illustrates the support for consuming generics. Also, refer for a brief decription of what is new in Visual J# 2005 by Pratap Lakshman. The only question is when vs 2005 will be released. 2005 is only in days. I think it’s been announced that VS2005 will be released at the PDC in September but I’m not 100% sure. All the J# information I can find including the link Anson gave and every other link I followed from those pages still don’t have any actual syntax for how J# supports Generics, enums and valuetypes. It’s interesting to hear that they do, but surely the syntax is kind of important to reveal? I don’t really feel like installing the VJ# Express beta from months ago just to see if I can figure out what syntax is used, especially when (based on my experience with C# express) I’d still be reduced to pressing random characters and hoping Intellisense would give me some hints. It took me forever to figure out the use of the "where" keyword in C# because as far as I could tell there was no documentation on it anywhere in the Express product (and I was offline at the time). Stuart: As a side note I’m curious why you weren’t able to find the docs on "where" in C# Express. We did document it extensively in the local docs. Was it a problem with search or the index perhaps? Well, the main problem was that I didn’t know what I was looking for, so I didn’t know to search for "where". It was a while ago, so I’m not too sure of the details any more, I just remember being very frustrated about it. Perhaps I was looking at the wrong docs, but if I’d been in "real" VS I would have gone straight to the C# language reference (I have that bookmarked) and found the part that described the syntax of a type declaration. In Express, it all seemed to be very basic overviews of stuff without many examples or detail; if there was some detailed reference documentation in there, I never found it. I can’t remember if I tried the search – I may have been trying to find it through the table of contents. The index wouldn’t have been helpful because I had no idea what keyword I was looking for (I was expecting something like Java’s Foo<T extends Bar> syntax and getting annoyed that I kept getting red squigglies under my ":", but you can’t exactly search the index for ":" – one of the few syntactic decisions which Java did better than C# at – and even if you could it wouldn’t have been the right thing to search for anyway – and this sentence really is absurdly long). So if generics are now CLS compliant, does that mean we can eliminate the System.Collections.ICollection interface (and all its brethren) in favor of System.Collections.Generic.ICollection<T> (and all its brethren), rename System.Collections.Generic to System.Collections, and generally move to only having one collection namespace? It seems to me that CLS compliance was the major reason not to do this. Incurring this breaking change now will mean much less hassle in the future for MS and everyone else, since frameworks won’t have to implement both ICollection and ICollection<T> to be useful to all consumers, and generally useful APIs won’t have to have overloads that take both ICollection and ICollection<T>. Incur the cost of switching now (which is basically typing "<object>" after all appearances of ICollection, IList, IEnumerable, ArrayList, etc. and can essentially be done by global search and replace in 95+% of cases) and we will avoid that whole set of issues. In your free time, visit some information about online poker phentermine viagra credit cards casino poker online casino texas holdem texas hold em texas holdem poker pacific poker party poker empire poker poker games generic viagra cialis levitra tramadol online pharmacy soma diet pills phendimetrazine credit card payday loans loans personal loans student loans private mortgages low interest credit cards … Thanks!!! Requiring all .NET languages to have support for generics looks scary in context of Actually there is no way to generate any complex generic code using standard method of producing .NET binaries – System.Reflection.Emit. The only way is to use some external libraries / writing them by ourself for generating IL. PingBack from PingBack from
https://blogs.msdn.microsoft.com/bclteam/2004/12/21/extra-extra-generics-cls-compliant-in-whidbey-peter-drayton/
CC-MAIN-2016-36
refinedweb
1,511
51.58
How to Build Weather station with Raspberry Pi and Sense HAT So in this article, I will show you how to do a lot of cool software projects. We showed you how to getting started with Raspberry Pi weather station with sense Hat. However, until now, we have not done more additional hardware. Let’s change this. Today, we are going to do something more hardware-intensive: we show you how to set up a Raspberry Pi weather station that can be accessed over the Internet. We will not push this raspberry pi to this project’s space, but we can use the Sense HAT’s ability to do something cool on Earth. In order to record all environmental information, Sense HAT has designed many sensors that can detect temperature. There may be a thermometer in your home so when you’re there you do not need a sensation hat to know the temperature. But with Raspberry Pi and Sense HAT working together, we can put this information online – to give your family a whole new smart feature. In this article, we found Sense HAT. Now let’s see how we program. In this article, we will see how to get data (temperature, pressure, humidity) from the environmental sensors to create a simple Weather station. Sense HAT comes with a Python library developed by the Raspberry Pi team. This Python library called sense Hat, if you are not familiar what is Sense Hat then please have a look on my previous article. Getting start with sense Hat and Build Astro Pi How to program sense hat with python programming? So let’s Get Started The following components are used for this project: - Raspberry Pi 3 - Sense Hat - HDMI Cable - Monitor - Keyboard - Mouse Looking for a great introduction to Raspberry Pi? Try the Zagros Raspberry Pi 3 Starter Kit which has everything you need to begin discovering Raspberry Pi. Weather station based on environmental sensor readings. The value of getting environmental sensors is very simple. Just create a perceptual HAT object and get the sensor values as follows: from sense_hat import SenseHat sense = SenseHat() temperature = sense.get_temperature_from_humidity() humidity = sense.get_humidity() pressure = sense.get_pressure() The temperature is in degrees celcius, the humidity is in percent and the pressure in millibars. Weather Station 0.1.0 – OpenGL 2.1 (Raspbian Jessie)(Download) To start the Weather station, unzip the file and launch GeeXLab. The Weather station demo will load automatically. The weather_station_src / folder can be found in the weather station source code (Python). The weather station demo is also available in the gl-21/rpi/sense_hat_python/weather_station_src/ folder of GeeXLab’s code sample pack. If the Sense HAT is connected directly to the Raspberry Pi’s GPIO connector, the temperature/humidity sensor is on the Sense HAT board and shows a higher value than the actual value. If “Sense HAT” is directly connected to the Raspberry Pi’s GPIO connector, the temperature/humidity sensor is located on the Sense HAT board and shows a higher value than the actual value. For example, in my lab, the temperature is about 20 ° C and the temperature sensor is about 30 ° C … This error is caused by the heat generated by the Raspberry Pi board. To solve this problem, I used a cable (40-pin connector + 40-pin male-male-300mm jumper) to separate the Sense HAT on the RPI from the RPi: And It will with patch, the temperature is look good. So)
https://technicalustad.com/build-weather-station-with-raspberry-pi-and-sense-hat/
CC-MAIN-2018-09
refinedweb
578
62.98
React is the infamous JavaScript library created by Facebook. It is now spread across like wildfire and used by a majority of the companies across the globe. This provides great opportunities for developers who are proficient in the technology and can develop great user interfaces. Thousands of companies are now making use of React full-time for their development needs, and this is creating a lot of vacancies and requirements. Of course with this comes tough interviews, hence we present to you these top React interview questions and answers. Categories Automation Big Data Business Intelligence Cloud Computing Cyber Security Data Science Database Digital Marketing Mobile Development No-SQL Programming Project Management Salesforce Testing Website Development CTA Knowing the amount of work it takes to ace these interviews, we have come up with this compilation of questions with the highest probability of occurrence. Going through these top questions will give you the highest chances of answering most of the questions asked in a React.js interview thoroughly. Q1. What is the difference between Virtual DOM and Real DOM? Q2. What is React? Q3. What is the meaning of Virtual DOM? Q4. What are some of the important features of React? Q5. What is the meaning of JSX? Q6. Can browsers read a JSX file? Q7. Why is React widely used today? Q8. Are there any disadvantages to using React? Q9. Differentiate between Angular and React. Q10. What is the meaning of the component-based architecture of React? This top React interview questions for experienced as well as for freshers blog is segmented into three: 1. Basic 2. Intermediate 3. Advanced React is a widely used JavaScript library that was launched in 2011. It was created by developers at Facebook, and it is primarily used for frontend development. React uses the component-based approach, which ensures to help you build components that possess high reusability. React is well known for developing and designing complex mobile user interfaces and web applications. A virtual DOM is a simple JavaScript object that is the exact copy of the corresponding real DOM. It can be considered as a node tree that consists of elements, their attributes, and other properties. Using the render function in React, it creates a node tree and updates it based on the changes that occur in the data model. These changes are usually triggered by users or the actions caused by the system. Next up among these React interview questions, you need to take a look at some of the important features that React offers. React has multiple features that are used for unique purposes. The important ones are as mentioned below: JSX is the abbreviation of JavaScript XML. It is a file that is used in React to bring out the essence of JavaScript to React and use it for its advantages. It even includes bringing out HTML and the easy syntax of JavaScript. This ensures that the resulting HTML file will have high readability, thereby relatively increasing the performance of the application. Consider the following example of a JSX: render(){ return( <div> <h1> Hello Intellipaat learners!</h1> </div> ); } No, browsers cannot read JSX files directly. It can only read the objects provided by JavaScript. Now, to make a browser read a JSX file, it has to be transformed to a JavaScript object using JSX transformers, and only then it can be fed into the browser for further use in the pipeline. React provides users with an ample number of advantages when building an application. Some of them are as follows: There are some limitations when using React as mentioned below: In React, components are foundations used to build user interfaces for applications. With the component-based system in place, all of the individual entities become completely reusable and independent of each other. This means that rendering the application is easy and not dependent on the other components of the UI. Rendering is an important aspect of React as every single component must be rendered. This is done using the render() function. Once the function is called, it returns an element that represents a DOM component. It is also possible to render more than one HTML element at a time by enclosing the HTML tags and passing them through the render function. States form to be one of the vital aspects of React. It is considered as a source of data or objects that control aspects such as component behavior and rendering. In React, states are used to easily create dynamic and interactive components. Props are the shorthand name given to properties in React. Props are read-only components that are immutable in nature. In an application, props follow a hierarchy that is passed down from parents to child components. However, the reverse is not supported. This is done to ensure that there is only a single directional flow in data at all times. An arrow function is used to write an expression in React. It allows users to manually bind components easily. The functionality of arrow functions can be very useful when you are working with higher-order functions particularly. Consider the following example: //The usual way render() { return( <MyInput onChange={this.handleChange.bind(this) } /> ); } //Making use of the arrow function render() { return( <MyInput onChange={ (e) => this.handleOnChange(e) } /> ); } Higher-order components (HOCs) are a widely used technique in React for applying concepts that involve the component reusability logic. They are not a native part of the React API and allow users to easily reuse the code and bootstrap abstraction. HOCs are also used to allow simple sharing of behaviors across all of the components in React, adding more advances to the efficiency and functioning of the application. The create-react-app in React is a simple command-line interface (CLI) that is used in the creation of React applications, which have no build configuration. All tools are pre-configured when using the CLI, and this allows users to focus on the code more than on dependencies to develop the application. The following syntax is used to start a simple project in React: Create-react-app my-app Making use of create-react-app is advantageous in the following way: Next up on these React Redux interview questions, you need to understand the meaning of Redux. Redux is used to store the state of the application in a single entity. This simple entity is usually a JavaScript object. Changing states can be done by pushing out actions from the application and writing corresponding objects for them that are used to modify the states. For example: { first_name: ‘John’, last_name : ‘Kelly’, age: 25 } All of the data is retained by Redux (also called a store). Next up on this top React interview questions and answers blog, take a look at the questions categorized as intermediate! The following are the three phases of a component life cycle: Whenever there are actions performed in React, such as hovering the mouse or pressing a key on the keyboard, these actions trigger events. Events then perform set activities as a response to these triggers. Handling an event in React is very similar to that in the DOM architecture. Events can be created very easily in React as shown here: class Display extends React.Component({ show(evt) { // Code inside }, render() { // Render the div with an onClick prop (value is a function) return ( <div onClick={this.show}>Click Here</div> ); } }); Differences between the conventional routing and the routing in React can be shown using the following aspects: Yes, any AJAX library, such as Axios and jQuery AJAX, can be used with React easily. One important thing is to maintain the states of the components, and here too, the props are passed from the parents to the child components. Child components still cannot send back props to parents, and this factor greatly increases rendering efficiency when dynamic data is considered. If you are looking forward to becoming proficient in Angular.js, then make sure to check out Intellipaat’s latest offerings for the Angular JS Course. Synthetic events in React are objects that act as cross-browser wrappers, allowing for the use of native events. This is done to ensure that a variety of browsers can run the API and that the event contains all properties. Stateful components are entities that store the changes that happen and place them into the memory. Here, the state can be changed, alongside storing information such as past, current, and future changes. ‘Refs’ is short for references in React. Refs are used to store a reference to a single React element or a React component. This is later returned using the render function. They are mainly used in the following scenarios: Controlled components in React refer to the components that have the ability to maintain their state. The data is completely controlled by the parent component, and the current value is fetched by making use of props. This is done to notify about any change that occurs when using callbacks. A router is very much necessary in React as it is used to manage multiple routes whenever a user types in a URL. If the route is present in the router for that corresponding URL, then the user is taken to the particular route. To do this, the router library needs to be added in React. It can be done using the following syntax: <switch> <route exact path=’/’ component={Home}/> <route path=’/posts/:id’ component={Newpost}/> <route path=’/posts’ component={Post}/> </switch> Redux consists of four main components as shown below: There are many advantages of Redux, and some of them are as given below: Among a plethora of advantages of using MVC in React, there are minor problems as stated below: Next up among these ReactJS interview questions, you have to understand about pure components. Pure components are singular entities that are written in React. They are fast and simple to write and have the ability to replace a component that has only the render() function. This is done to ensure that the performance of the application is good and that the code is kept simple at the same time. Next up on this top React interview questions blog, take a look at the questions categorized as advanced! HOCs are used for a variety of tasks such as: Keys are used in React to check all items and to track changes actively. They are used to directly check if an item has been added or removed from a list. Consider the following syntax: function List ({ todos }) { return ( <ul> {todos.map(({ task, id} ) => <li key={id}>{task}</li>} </ul> ) } A controlled component, as the name suggests, is a component over which React has complete control. It is the singular point of data for the forms. An uncontrolled component is one where the form data gets handled by DOM and not the React component. This is usually done using refs in React. React can be coded to directly build into production by setting the process.env.NODE_ENV variable to production. Note: When React is in production, warnings and other development features are not shown. In React, cloneElement is primarily used to clone an element and pass it to new props directly. Whereas, createElement is the entity that JSX gets compiled into. This is also used to create elements in React. Next up on this top React interview questions and answers blog, take a look at the use of the second argument. When setState is finished, a callback function is invoked, and the components get re-rendered in React. Yes, it is an optional argument. Since setState is asynchronous, it takes in another callback function. However, in programming practice, it is always good to use another life cycle method instead of this. Next up on this top React interview questions and answers blog, you need to take a look at binding. Yes, there are two main ways you can use to avoid the need for binding. They are as follows: class SubmitButton extends React.Component { constructor(props) { super(props); this.state = { isFormSubmitted: false }; } render() { return ( <button onClick={() => { this.setState({ isFormSubmitted: true }); }}>Submit</button> ) } } const SubmitButton = () => { const [isFormSubmitted, setIsFormSubmitted] = useState(false); return ( <button onClick={() => { setIsFormSubmitted(true); }}>Submit</button> ) }; Also, the Event Handler can be defined as an Arrow function, which is eventually assigned to a Class Field to obtain similar results. The StrictMode component when used would benefit users immensely while creating new codebases to understand the components being used. However, it can fit well in debugging as well because it will help solve the problem faster when it is wrapped with other components, which could be causing the problem. Next up on these interview questions on React JS, you have to understand how to speed up rendering. The cause of slow rendering in React is mostly because of the number of re-render operations, which are sometimes unnecessary. There are two main tools provided by React to help users here: Yes, there is a way in which you can add attributes to a React component when certain conditions are met. React has the ability to omit an attribute if the value passed to it is not true. var condition = true; var component = ( <div value="foo" { ...( condition && { disabled: true } ) } /> ); Props gets passed onto the super() function if a user wishes to access this.props in the constructor. class MyComponent extends React.Component { constructor(props) { super(props) console.log(this.props) // -> { icon: 'home', … } } } When using ES6, users must initialize the state in the constructor and the getInitialState method is defined. This is done using React.createClass as shown in the below example: class MyComponent extends React.Component { constructor(props) { super(props); this.state = { /* initial state */ }; } } This above piece of code is equivalent to the following: var MyComponent = React.createClass({ getInitialState() { return { /* initial state */ }; }, }); Next up among these interview questions on React JS, you have to know what predefined props are. There are five main predefined prop types in React. They are as follows: The propTypes can be defined for the user component as shown below: import PropTypes from 'prop-types'; class User extends React.Component { render() { return ( <h1>Welcome, {this.props.name}</h1> <h2>Age, {this.props.age} ); } } User.propTypes = { name: PropTypes.string.isRequired, age: PropTypes.number.isRequired }; React Fiber is a new engine in React. It is the reimplementation core algorithm in React 16. The main goal of React Fiber is to ensure that there are incremental rendering facilities for the virtual DOM. This increases efficiency when rendering animations, gestures, etc. and also helps in assigning priority to updates based on the requirement, thereby increasing overall efficiency. Hooks are used to make use of the state and other features without having to explicitly write a class. Hooks were added to the React version, v16.8. The stateful logic can be extracted from a component easily, alongside testing and reusing it. All of this is done without making any changes to the component hierarchy. With this question, the interviewer is trying to assess if you have any technical experience through learning and implementation. It is always advantageous to have a certification in the technology that you’re applying for. This creates an impression that you have put your time and effort into learning and implementing the technology. Alongside adding a lot of value to your resume and your knowledge on the topic, it can be used to obtain a well-coveted job in the market! If you are looking forward to becoming proficient in Web Development, then make sure to check out Intellipaat’s latest offerings for the Web Development Online Course. With these programs, you can become an expert in Web Development and earn a course certificate as well. Course Schedule Leave a Reply Cancel reply Your email address will not be published. Required fields are marked * Comment Name *
https://intellipaat.com/blog/interview-question/react-interview-questions/
CC-MAIN-2021-31
refinedweb
2,633
55.44
Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Handling Missing Keys With the Python defaultdict Type A common problem that you can face when working with Python dictionaries is to try to access or modify keys that don’t exist in the dictionary. This will raise a KeyError and break up your code execution. To handle these kinds of situations, the standard library provides the Python defaultdict type, a dictionary-like class that’s available for you in collections. The Python defaultdict type behaves almost exactly like a regular Python dictionary, but if you try to access or modify a missing key, then defaultdict will automatically create the key and generate a default value for it. This makes defaultdict a valuable option for handling missing keys in dictionaries. In this tutorial, you’ll learn: - How to use the Python defaultdicttype for handling missing keys in a dictionary - When and why to use a Python defaultdictrather than a regular dict - How to use a defaultdictfor grouping, counting, and accumulating operations With this knowledge under your belt, you’ll be in a better condition to effectively use the Python defaultdict type in your day-to-day programming challenges. To get the most out of this tutorial, you should have some previous understanding of what Python dictionaries are and how to work with them. If you need to freshen up, then check out the following resources: - Dictionaries in Python (Tutorial) - Dictionaries in Python (Course) - How to Iterate Through a Dictionary in Python Free Bonus: Click here to get a Python Cheat Sheet and learn the basics of Python 3, like working with data types, dictionaries, lists, and Python functions. Handling Missing Keys in Dictionaries A common issue that you can face when working with Python dictionaries is how to handle missing keys. If your code is heavily based on dictionaries, or if you’re creating dictionaries on the fly all the time, then you’ll soon notice that dealing with frequent KeyError exceptions can be quite annoying and can add extra complexity to your code. With Python dictionaries, you have at least four available ways to handle missing keys: The Python docs explain .setdefault() and .get() as follows: setdefault(key[, default]) If keyis in the dictionary, return its value. If not, insert keywith a value of defaultand return default. defaultdefaults to None. get(key[, default]) Return the value for keyif keyis in the dictionary, else default. If defaultis not given, it defaults to None, so that this method never raises a KeyError. Here’s an example of how you can use .setdefault() to handle missing keys in a dictionary: >>> a_dict = {} >>> a_dict['missing_key'] Traceback (most recent call last): File "<stdin>", line 1, in <module> a_dict['missing_key'] KeyError: 'missing_key' >>> a_dict.setdefault('missing_key', 'default value') 'default value' >>> a_dict['missing_key'] 'default value' >>> a_dict.setdefault('missing_key', 'another default value') 'default value' >>> a_dict {'missing_key': 'default value'} In the above code, you use .setdefault() to generate a default value for missing_key. Notice that your dictionary, a_dict, now has a new key called missing_key whose value is 'default value'. This key didn’t exist before you called .setdefault(). Finally, if you call .setdefault() on an existing key, then the call won’t have any effect on the dictionary. Your key will hold the original value instead of the new default value. Note: In the above code example, you get an exception, and Python shows you a traceback message, which tells you that you’re trying to access a missing key in a_dict. If you want to dive deeper into how to decipher and understand a Python traceback, then check out Understanding the Python Traceback and Getting the Most out of a Python Traceback. On the other hand, if you use .get(), then you can code something like this: >>> a_dict = {} >>> a_dict.get('missing_key', 'default value') 'default value' >>> a_dict {} Here, you use .get() to generate a default value for missing_key, but this time, your dictionary stays empty. This is because .get() returns the default value, but this value isn’t added to the underlying dictionary. For example, if you have a dictionary called D, then you can assume that .get() works something like this: D.get(key, default) -> D[key] if key in D, else default With this pseudo-code, you can understand how .get() works internally. If the key exists, then .get() returns the value mapped to that key. Otherwise, the default value is returned. Your code never creates or assigns a value to key. In this example, default defaults to None. You can also use conditional statements to handle missing keys in dictionaries. Take a look at the following example, which uses the key in dict idiom: >>> a_dict = {} >>> if 'key' in a_dict: ... # Do something with 'key'... ... a_dict['key'] ... else: ... a_dict['key'] = 'default value' ... >>> a_dict {'key': 'default value'} In this code, you use an if statement along with the in operator to check if key is present in a_dict. If so, then you can perform any action with key or with its value. Otherwise, you create the new key, key, and assign it a 'default value'. Note that the above code works similar to .setdefault() but takes four lines of code, while .setdefault() would only take one line (in addition to being more readable). You can also walk around the KeyError by using a try and except block to handle the exception. Consider the following piece of code: >>> a_dict = {} >>> try: ... # Do something with 'key'... ... a_dict['key'] ... except KeyError: ... a_dict['key'] = 'default value' ... >>> a_dict {'key': 'default value'} The try and except block in the above example catches the KeyError whenever you try to get access to a missing key. In the except clause, you create the key and assign it a 'default value'. Note: If missing keys are uncommon in your code, then you might prefer to use a try and except block (EAFP coding style) to catch the KeyError exception. This is because the code doesn’t check the existence of every key and only handles a few exceptions, if any. On the other hand, if missing keys are quite common in your code, then the conditional statement (LBYL coding style) can be a better choice because checking for keys can be less costly than handling frequent exceptions. So far, you’ve learned how to handle missing keys using the tools that dict and Python offer you. However, the examples you saw here are quite verbose and hard to read. They might not be as straightforward as you might want. That’s why the Python standard library provides a more elegant, Pythonic, and efficient solution. That solution is collections.defaultdict, and that’s what you’ll be covering from now on. Understanding the Python defaultdict Type The Python standard library provides collections, which is a module that implements specialized container types. One of those is the Python defaultdict type, which is an alternative to dict that’s specifically designed to help you out with missing keys. defaultdict is a Python type that inherits from dict: >>> from collections import defaultdict >>> issubclass(defaultdict, dict) True The above code shows that the Python defaultdict type is a subclass of dict. This means that defaultdict inherits most of the behavior of dict. So, you can say that defaultdict is much like an ordinary dictionary. The main difference between defaultdict and dict is that when you try to access or modify a key that’s not present in the dictionary, a default value is automatically given to that key. In order to provide this functionality, the Python defaultdict type does two things: - It overrides .__missing__(). - It adds .default_factory, a writable instance variable that needs to be provided at the time of instantiation. The instance variable .default_factory will hold the first argument passed into defaultdict.__init__(). This argument can take a valid Python callable or None. If a callable is provided, then it’ll automatically be called by defaultdict whenever you try to access or modify the value associated with a missing key. Note: All the remaining arguments to the class initializer are treated as if they were passed to the initializer of regular dict, including the keyword arguments. Take a look at how you can create and properly initialize a defaultdict: >>> # Correct instantiation >>> def_dict = defaultdict(list) # Pass list to .default_factory >>> def_dict['one'] = 1 # Add a key-value pair >>> def_dict['missing'] # Access a missing key returns an empty list [] >>> def_dict['another_missing'].append(4) # Modify a missing key >>> def_dict defaultdict(<class 'list'>, {'one': 1, 'missing': [], 'another_missing': [4]}) Here, you pass list to .default_factory when you create the dictionary. Then, you use def_dict just like a regular dictionary. Note that when you try to access or modify the value mapped to a non-existent key, the dictionary assigns it the default value that results from calling list(). Keep in mind that you must pass a valid Python callable object to .default_factory, so remember not to call it using the parentheses at initialization time. This can be a common issue when you start using the Python defaultdict type. Take a look at the following code: >>> # Wrong instantiation >>> def_dict = defaultdict(list()) Traceback (most recent call last): File "<stdin>", line 1, in <module> def_dict = defaultdict(list()) TypeError: first argument must be callable or None Here, you try to create a defaultdict by passing list() to .default_factory. The call to list() raises a TypeError, which tells you that the first argument must be callable or None. With this introduction to the Python defaultdict type, you can get start coding with practical examples. The next few sections will walk you through some common use cases where you can rely on a defaultdict to provide an elegant, efficient, and Pythonic solution. Using the Python defaultdict Type Sometimes, you’ll use a mutable built-in collection (a list, dict, or set) as values in your Python dictionaries. In these cases, you’ll need to initialize the keys before first use, or you’ll get a KeyError. You can either do this process manually or automate it using a Python defaultdict. In this section, you’ll learn how to use the Python defaultdict type for solving some common programming problems: - Grouping the items in a collection - Counting the items in a collection - Accumulating the values in a collection You’ll be covering some examples that use list, set, int, and float to perform grouping, counting, and accumulating operations in a user-friendly and efficient way. Grouping Items A typical use of the Python defaultdict type is to set .default_factory to list and then build a dictionary that maps keys to lists of values. With this defaultdict, if you try to get access to any missing key, then the dictionary runs the following steps: - Call list()to create a new empty list - Insert the empty listinto the dictionary using the missing key as key - Return a reference to that list This allows you to write code like this: >>> from collections import defaultdict >>> dd = defaultdict(list) >>> dd['key'].append(1) >>> dd defaultdict(<class 'list'>, {'key': [1]}) >>> dd['key'].append(2) >>> dd defaultdict(<class 'list'>, {'key': [1, 2]}) >>> dd['key'].append(3) >>> dd defaultdict(<class 'list'>, {'key': [1, 2, 3]}) Here, you create a Python defaultdict called dd and pass list to .default_factory. Notice that even when key isn’t defined, you can append values to it without getting a KeyError. That’s because dd automatically calls .default_factory to generate a default value for the missing key. You can use defaultdict along with list to group the items in a sequence or a collection. Suppose that you’ve retrieved the following data from your company’s database: With this data, you create an initial list of tuple objects like the following: dep = [('Sales', 'John Doe'), ('Sales', 'Martin Smith'), ('Accounting', 'Jane Doe'), ('Marketing', 'Elizabeth Smith'), ('Marketing', 'Adam Doe')] Now, you need to create a dictionary that groups the employees by department. To do this, you can use a defaultdict as follows: from collections import defaultdict dep_dd = defaultdict(list) for department, employee in dep: dep_dd[department].append(employee) Here, you create a defaultdict called dep_dd and use a for loop to iterate through your dep list. The statement dep_dd[department].append(employee) creates the keys for the departments, initializes them to an empty list, and then appends the employees to each department. Once you run this code, your dep_dd will look something like this: defaultdict(<class 'list'>, {'Sales': ['John Doe', 'Martin Smith'], 'Accounting' : ['Jane Doe'], 'Marketing': ['Elizabeth Smith', 'Adam Doe']}) In this example, you group the employees by their department using a defaultdict with .default_factory set to list. To do this with a regular dictionary, you can use dict.setdefault() as follows: dep_d = dict() for department, employee in dep: dep_d.setdefault(department, []).append(employee) This code is straightforward, and you’ll find similar code quite often in your work as a Python coder. However, the defaultdict version is arguably more readable, and for large datasets, it can also be a lot faster and more efficient. So, if speed is a concern for you, then you should consider using a defaultdict instead of a standard dict. Grouping Unique Items Continue working with the data of departments and employees from the previous section. After some processing, you realize that a few employees have been duplicated in the database by mistake. You need to clean up the data and remove the duplicated employees from your dep_dd dictionary. To do this, you can use a set as the .default_factory and rewrite your code as follows: dep = [('Sales', 'John Doe'), ('Sales', 'Martin Smith'), ('Accounting', 'Jane Doe'), ('Marketing', 'Elizabeth Smith'), ('Marketing', 'Elizabeth Smith'), ('Marketing', 'Adam Doe'), ('Marketing', 'Adam Doe'), ('Marketing', 'Adam Doe')] dep_dd = defaultdict(set) for department, employee in dep: dep_dd[department].add(employee) In this example, you set .default_factory to set. Sets are collections of unique objects, which means that you can’t create a set with repeated items. This is a really interesting feature of sets, which guarantees that you won’t have repeated items in your final dictionary. Counting Items If you set .default_factory to int, then your defaultdict will be useful for counting the items in a sequence or collection. When you call int() with no arguments, the function returns 0, which is the typical value you’d use to initialize a counter. To continue with the example of the company database, suppose you want to build a dictionary that counts the number of employees per department. In this case, you can code something like this: >>> from collections import defaultdict >>> dep = [('Sales', 'John Doe'), ... ('Sales', 'Martin Smith'), ... ('Accounting', 'Jane Doe'), ... ('Marketing', 'Elizabeth Smith'), ... ('Marketing', 'Adam Doe')] >>> dd = defaultdict(int) >>> for department, _ in dep: ... dd[department] += 1 >>> dd defaultdict(<class 'int'>, {'Sales': 2, 'Accounting': 1, 'Marketing': 2}) Here, you set .default_factory to int. When you call int() with no argument, the returned value is 0. You can use this default value to start counting the employees that work in each department. For this code to work correctly, you need a clean dataset. There must be no repeated data. Otherwise, you’ll need to filter out the repeated employees. Another example of counting items is the mississippi example, where you count the number of times each letter in a word is repeated. Take a look at the following code: >>> from collections import defaultdict >>>>> dd = defaultdict(int) >>> for letter in s: ... dd[letter] += 1 ... >>> dd defaultdict(<class 'int'>, {'m': 1, 'i': 4, 's': 4, 'p': 2}) In the above code, you create a defaultdict with .default_factory set to int. This sets the default value for any given key to 0. Then, you use a for loop to traverse the string s and use an augmented assignment operation to add 1 to the counter in every iteration. The keys of dd will be the letters in mississippi. Note: Python’s augmented assignment operators are a handy shortcut to common operations. Take a look at the following examples: var += 1is equivalent to var = var + 1 var -= 1is equivalent to var = var - 1 var *= 1is equivalent to var = var * 1 This is just a sample of how the augmented assignment operators work. You can take a look at the official documentation to learn more about this feature. As counting is a relatively common task in programming, the Python dictionary-like class collections.Counter is specially designed for counting items in a sequence. With Counter, you can write the mississippi example as follows: >>> from collections import Counter >>> counter = Counter('mississippi') >>> counter Counter({'i': 4, 's': 4, 'p': 2, 'm': 1}) In this case, Counter does all the work for you! You only need to pass in a sequence, and the dictionary will count its items, storing them as keys and the counts as values. Note that this example works because Python strings are also a sequence type. Accumulating Values Sometimes you’ll need to calculate the total sum of the values in a sequence or collection. Let’s say you have the following Excel sheet with data about the sales of your Python website: Next, you process the data using Python and get the following list of tuple objects: incomes = [('Books', 1250.00), ('Books', 1300.00), ('Books', 1420.00), ('Tutorials', 560.00), ('Tutorials', 630.00), ('Tutorials', 750.00), ('Courses', 2500.00), ('Courses', 2430.00), ('Courses', 2750.00),] With this data, you want to calculate the total income per product. To do that, you can use a Python defaultdict with float as .default_factory and then code something like this: 1from collections import defaultdict 2 3dd = defaultdict(float) 4for product, income in incomes: 5 dd[product] += income 6 7for product, income in dd.items(): 8 print(f'Total income for {product}: ${income:,.2f}') Here’s what this code does: - In line 1, you import the Python defaultdicttype. - In line 3, you create a defaultdictobject with .default_factoryset to float. - In line 4, you define a forloop to iterate through the items of incomes. - In line 5, you use an augmented assignment operation ( +=) to accumulate the incomes per product in the dictionary. The second loop iterates through the items of dd and prints the incomes to your screen. Note: If you want to dive deeper into dictionary iteration, check out How to Iterate Through a Dictionary in Python. If you put all this code into a file called incomes.py and run it from your command line, then you’ll get the following output: $ python3 incomes.py Total income for Books: $3,970.00 Total income for Tutorials: $1,940.00 Total income for Courses: $7,680.00 You now have a summary of incomes per product, so you can make decisions on which strategy to follow for increasing the total income of your site. Diving Deeper Into defaultdict So far, you’ve learned how to use the Python defaultdict type by coding some practical examples. At this point, you can dive deeper into type implementation and other working details. That’s what you’ll be covering in the next few sections. defaultdict vs dict For you to better understand the Python defaultdict type, a good exercise would be to compare it with its superclass, dict. If you want to know the methods and attributes that are specific to the Python defaultdict type, then you can run the following line of code: >>> set(dir(defaultdict)) - set(dir(dict)) {'__copy__', 'default_factory', '__missing__'} In the above code, you use dir() to get the list of valid attributes for dict and defaultdict. Then, you use a set difference to get the set of methods and attributes that you can only find in defaultdict. As you can see, the differences between these two classes are. You have two methods and one instance attribute. The following table shows what the methods and the attribute are for: In the above table, you can see the methods and the attribute that make a defaultdict different from a regular dict. The rest of the methods are the same in both classes. Note: If you initialize a defaultdict using a valid callable, then you won’t get a KeyError when you try to get access to a missing key. Any key that doesn’t exist gets the value returned by .default_factory. Additionally, you might notice that a defaultdict is equal to a dict with the same items: >>> std_dict = dict(numbers=[1, 2, 3], letters=['a', 'b', 'c']) >>> std_dict {'numbers': [1, 2, 3], 'letters': ['a', 'b', 'c']} >>> def_dict = defaultdict(list, numbers=[1, 2, 3], letters=['a', 'b', 'c']) >>> def_dict defaultdict(<class 'list'>, {'numbers': [1, 2, 3], 'letters': ['a', 'b', 'c']}) >>> std_dict == def_dict True Here, you create a regular dictionary std_dict with some arbitrary items. Then, you create a defaultdict with the same items. If you test both dictionaries for content equality, then you’ll see that they’re equal. defaultdict.default_factory The first argument to the Python defaultdict type must be a callable that takes no arguments and returns a value. This argument is assigned to the instance attribute, .default_factory. For this, you can use any callable, including functions, methods, classes, type objects, or any other valid callable. The default value of .default_factory is None. If you instantiate defaultdict without passing a value to .default_factory, then the dictionary will behave like a regular dict and the usual KeyError will be raised for missing key lookup or modification attempts: >>> from collections import defaultdict >>> dd = defaultdict() >>> dd['missing_key'] Traceback (most recent call last): File "<stdin>", line 1, in <module> dd['missing_key'] KeyError: 'missing_key' Here, you instantiate the Python defaultdict type with no arguments. In this case, the instance behaves like a standard dictionary. So, if you try to access or modify a missing key, then you’ll get the usual KeyError. From this point on, you can use dd as a normal Python dictionary and, unless you assign a new callable to .default_factory, you won’t be able to use the ability of defaultdict to handle missing keys automatically. If you pass None to the first argument of defaultdict, then the instance will behave the same way you saw in the above example. That’s because .default_factory defaults to None, so both initializations are equivalent. On the other hand, if you pass a valid callable object to .default_factory, then you can use it to handle missing keys in a user-friendly way. Here’s an example where you pass list to .default_factory: >>> dd = defaultdict(list, letters=['a', 'b', 'c']) >>> dd.default_factory <class 'list'> >>> dd defaultdict(<class 'list'>, {'letters': ['a', 'b', 'c']}) >>> dd['numbers'] [] >>> dd defaultdict(<class 'list'>, {'letters': ['a', 'b', 'c'], 'numbers': []}) >>> dd['numbers'].append(1) >>> dd defaultdict(<class 'list'>, {'letters': ['a', 'b', 'c'], 'numbers': [1]}) >>> dd['numbers'] += [2, 3] >>> dd defaultdict(<class 'list'>, {'letters': ['a', 'b', 'c'], 'numbers': [1, 2, 3]}) In this example, you create a Python defaultdict called dd, then you use list for its first argument. The second argument is called letters and holds a list of letters. You see that .default_factory now holds a list object that will be called when you need to supply a default value for any missing key. Notice that when you try to access numbers, dd tests if numbers is in the dictionary. If it’s not, then it calls .default_factory(). Since .default_factory holds a list object, the returned value is an empty list ( []). Now that dd['numbers'] is initialized with an empty list, you can use .append() to add elements to the list. You can also use an augmented assignment operator ( +=) to concatenate the lists [1] and [2, 3]. This way, you can handle missing keys in a more Pythonic and more efficient way. On the other hand, if you pass a non-callable object to the initializer of the Python defaultdict type, then you’ll get a TypeError like in the following code: >>> defaultdict(0) Traceback (most recent call last): File "<stdin>", line 1, in <module> defaultdict(0) TypeError: first argument must be callable or None Here, you pass 0 to .default_factory. Since 0 is not a callable object, you get a TypeError telling you that the first argument must be callable or None. Otherwise, defaultdict doesn’t work. Keep in mind that .default_factory is only called from .__getitem__() and not from other methods. This means that if dd is a defaultdict and key is a missing key, then dd[key] will call .default_factory to provide a default value, but dd.get(key) still returns None instead of the value that .default_factory would provide. That’s because .get() doesn’t call .__getitem__() to retrieve the key. Take a look at the following code: >>> dd = defaultdict(list) >>> # Calls dd.__getitem__('missing') >>> dd['missing'] [] >>> # Don't call dd.__getitem__('another_missing') >>> print(dd.get('another_missing')) None >>> dd defaultdict(<class 'list'>, {'missing': []}) In this code fragment, you can see that dd.get() returns None rather than the default value that .default_factory would provide. That’s because .default_factory is only called from .__missing__(), which is not called by .get(). Notice that you can also add arbitrary values to a Python defaultdict. This means that you’re not limited to values with the same type as the values generated by .default_factory. Here’s an example: >>> dd = defaultdict(list) >>> dd defaultdict(<class 'list'>, {}) >>> dd['string'] = 'some string' >>> dd defaultdict(<class 'list'>, {'string': 'some string'}) >>> dd['list'] [] >>> dd defaultdict(<class 'list'>, {'string': 'some string', 'list': []}) Here, you create a defaultdict and pass in a list object to .default_factory. This sets your default values to be empty lists. However, you can freely add a new key that holds values of a different type. That’s the case with the key string, which holds a str object instead of a list object. Finally, you can always change or update the callable you initially assign to .default_factory in the same way you would do with any instance attribute: >>> dd.default_factory = str >>> dd['missing_key'] '' In the above code, you change .default_factory from list to str. Now, whenever you try to get access to a missing key, your default value will be an empty string ( ''). Depending on your use cases for the Python defaultdict type, you might need to freeze the dictionary once you finish creating it and make it read-only. To do this, you can set .default_factory to None after you finish populating the dictionary. This way, your dictionary will behave like a standard dict, which means you won’t have more automatically generated default values. defaultdict vs dict.setdefault() As you saw before, dict provides .setdefault(), which will allow you to assign values to missing keys on the fly. In contrast, with a defaultdict you can specify the default value up front when you initialize the container. You can use .setdefault() to assign default values as follows: >>> d = dict() >>> d.setdefault('missing_key', []) [] >>> d {'missing_key': []} In this code, you create a regular dictionary and then use .setdefault() to assign a value ( []) to the key missing_key, which wasn’t defined yet. Note: You can assign any type of Python object using .setdefault(). This is an important difference compared to defaultdict if you consider that defaultdict only accepts a callable or None. On the other hand, if you use a defaultdict to accomplish the same task, then the default value is generated on demand whenever you try to access or modify a missing key. Notice that, with defaultdict, the default value is generated by the callable you pass upfront to the initializer of the class. Here’s how it works: >>> from collections import defaultdict >>> dd = defaultdict(list) >>> dd['missing_key'] [] >>> dd defaultdict(<class 'list'>, {'missing_key': []}). The code in the above two examples does the same work, but the defaultdict version is arguably more readable, user-friendly, Pythonic, and straightforward. Note: A call to a built-in type like list, set, dict, str, int, or float will return an empty object or zero for numeric types. Take a look at the following code examples: >>> list() [] >>> set() set([]) >>> dict() {} >>> str() '' >>> float() 0.0 >>> int() 0 In this code, you call some built-in types with no arguments and get an empty object or zero for the numeric types. Finally, using a defaultdict to handle missing keys can be faster than using dict.setdefault(). Take a look a the following example: # Filename: exec_time.py from collections import defaultdict from timeit import timeit animals = [('cat', 1), ('rabbit', 2), ('cat', 3), ('dog', 4), ('dog', 1)] std_dict = dict() def_dict = defaultdict(list) def group_with_dict(): for animal, count in animals: std_dict.setdefault(animal, []).append(count) return std_dict def group_with_defaultdict(): for animal, count in animals: def_dict[animal].append(count) return def_dict print(f'dict.setdefault() takes {timeit(group_with_dict)} seconds.') print(f'defaultdict takes {timeit(group_with_defaultdict)} seconds.') If you run the script from your system’s command line, then you’ll get something like this: $ python3 exec_time.py dict.setdefault() takes 1.0281260240008123 seconds. defaultdict takes 0.6704721650003194 seconds. Here, you use timeit.timeit() to measure the execution time of group_with_dict() and group_with_defaultdict(). These functions perform equivalent actions, but the first uses dict.setdefault(), and the second uses a defaultdict. The time measure will depend on your current hardware, but you can see here that defaultdict is faster than dict.setdefault(). This difference can become more important as the dataset gets larger. Additionally, you need to consider that creating a regular dict can be faster than creating a defaultdict. Take a look at this code: >>> from timeit import timeit >>> from collections import defaultdict >>> print(f'dict() takes {timeit(dict)} seconds.') dict() takes 0.08921320698573254 seconds. >>> print(f'defaultdict() takes {timeit(defaultdict)} seconds.') defaultdict() takes 0.14101867799763568 seconds. This time, you use timeit.timeit() to measure the execution time of dict and defaultdict instantiation. Notice that creating a dict takes almost half the time of creating a defaultdict. This might not be a problem if you consider that, in real-world code, you normally instantiate defaultdict only once. Also notice that, by default, timeit.timeit() will run your code a million times. That’s the reason for defining std_dict and def_dict out of the scope of group_with_dict() and group_with_defaultdict() in exec_time.py. Otherwise, the time measure will be affected by the instantiation time of dict and defaultdict. At this point, you may have an idea of when to use a defaultdict rather than a regular dict. Here are three things to take into account: If your code is heavily base on dictionaries and you’re dealing with missing keys all the time, then you should consider using a defaultdictrather than a regular dict. If your dictionary items need to be initialized with a constant default value, then you should consider using a defaultdictinstead of a dict. If your code relies on dictionaries for aggregating, accumulating, counting, or grouping values, and performance is a concern, then you should consider using a defaultdict. You can consider the above guidelines when deciding whether to use a dict or a defaultdict. defaultdict.__missing__() Behind the scenes, the Python defaultdict type works by calling .default_factory to supply default values to missing keys. The mechanism that makes this possible is .__missing__(), a special method supported by all the standard mapping types, including dict and defaultdict. Note: Note that .__missing__() is automatically called by .__getitem__() to handle missing keys and that .__getitem__() is automatically called by Python at the same time for subscription operations like d[key]. So, how does .__missing__() work? If you set .default_factory to None, then .__missing__() raises a KeyError with the key as an argument. Otherwise, .default_factory is called without arguments to provide a default value for the given key. This value is inserted into the dictionary and finally returned. If calling .default_factory raises an exception, then the exception is propagated unchanged. The following code shows a viable Python implementation for .__missing__(): 1def __missing__(self, key): 2 if self.default_factory is None: 3 raise KeyError(key) 4 if key not in self: 5 self[key] = self.default_factory() 6 return self[key] Here’s what this code does: - In line 1, you define the method and its signature. - In lines 2 and 3, you test to see if .default_factoryis None. If so, then you raise a KeyErrorwith the keyas an argument. - In lines 4 and 5, you check if the keyis not in the dictionary. If it’s not, then you call .default_factoryand assign its return value to the key. - In line 6, you return the keyas expected. Keep in mind that the presence of .__missing__() in a mapping has no effect on the behavior of other methods that look up keys, such as .get() or .__contains__(), which implements the in operator. That’s because .__missing__() is only called by .__getitem__() when the requested key is not found in the dictionary. Whatever .__missing__() returns or raises is then returned or raised by .__getitem__(). Now that you’ve covered an alternative Python implementation for .__missing__(), it would be a good exercise to try to emulate defaultdict with some Python code. That’s what you’ll be doing in the next section. Emulating the Python defaultdict Type In this section, you’ll be coding a Python class that will behave much like a defaultdict. To do that, you’ll subclass collections.UserDict and then add .__missing__(). Also, you need to add an instance attribute called .default_factory, which will hold the callable for generating default values on demand. Here’s a piece of code that emulates most of the behavior of the Python defaultdict type: 1import collections 2 3class my_defaultdict(collections.UserDict): 4 def __init__(self, default_factory=None, *args, **kwargs): 5 super().__init__(*args, **kwargs) 6 if not callable(default_factory) and default_factory is not None: 7 raise TypeError('first argument must be callable or None') 8 self.default_factory = default_factory 9 10 def __missing__(self, key): 11 if self.default_factory is None: 12 raise KeyError(key) 13 if key not in self: 14 self[key] = self.default_factory() 15 return self[key] Here’s how this code works: In line 1, you import collectionsto get access to UserDict. In line 3, you create a class that subclasses UserDict. In line 4, you define the class initializer .__init__(). This method takes an argument called default_factoryto hold the callable that you’ll use to generate the default values. Notice that default_factorydefaults to None, just like in a defaultdict. You also need the *argsand **kwargsfor emulating the normal behavior of a regular dict. In line 5, you call the superclass .__init__(). This means that you’re calling UserDict.__init__()and passing *argsand **kwargsto it. In line 6, you first check if default_factoryis a valid callable object. In this case, you use callable(object), which is a built-in function that returns Trueif objectappears to be a callable and otherwise returns False. This check ensures that you can call .default_factory()if you need to generate a default valuefor any missing key. Then, you check if .default_factoryis not None. In line 7, you raise a TypeErrorjust like a regular dictwould do if default_factoryis None. In line 8, you initialize .default_factory. In line 10, you define .__missing__(), which is implemented as you saw before. Recall that .__missing__()is automatically called by .__getitem__()when a given keyis not in a dictionary. If you feel in the mood to read some C code, then you can take a look at the full code for the Python defaultdict Type in the CPython source code. Now that you’ve finished coding this class, you can test it by putting the code into a Python script called my_dd.py and importing it from an interactive session. Here’s an example: >>> from my_dd import my_defaultdict >>> dd_one = my_defaultdict(list) >>> dd_one {} >>> dd_one['missing'] [] >>> dd_one {'missing': []} >>> dd_one.default_factory = int >>> dd_one['another_missing'] 0 >>> dd_one {'missing': [], 'another_missing': 0} >>> dd_two = my_defaultdict(None) >>> dd_two['missing'] Traceback (most recent call last): File "<stdin>", line 1, in <module> dd_two['missing'] File "/home/user/my_dd.py", line 10, in __missing__ raise KeyError(key) KeyError: 'missing' Here, you first import my_defaultdict from my_dd. Then, you create an instance of my_defaultdict and pass list to .default_factory. If you try to get access to a key with a subscription operation, like dd_one['missing'], then .__getitem__() is automatically called by Python. If the key is not in the dictionary, then .__missing__() is called, which generates a default value by calling .default_factory(). You can also change the callable assigned to .default_factory using a normal assignment operation like in dd_one.default_factory = int. Finally, if you pass None to .default_factory, then you’ll get a KeyError when trying to retrieve a missing key. Note: The behavior of a defaultdict is essentially the same as this Python equivalent. However, you’ll soon note that your Python implementation doesn’t print as a real defaultdict but as a standard dict. You can modify this detail by overriding .__str__() and .__repr__(). You may be wondering why you subclass collections.UserDict instead of a regular dict for this example. The main reason for this is that subclassing built-in types can be error-prone because the C code of the built-ins doesn’t seem to consistently call special methods overridden by the user. Here’s an example that shows some issues that you can face when subclassing dict: >>> class MyDict(dict): ... def __setitem__(self, key, value): ... super().__setitem__(key, None) ... >>> my_dict = MyDict(first=1) >>> my_dict {'first': 1} >>> my_dict['second'] = 2 >>> my_dict {'first': 1, 'second': None} >>> my_dict.setdefault('third', 3) 3 >>> my_dict {'first': 1, 'second': None, 'third': 3} In this example, you create MyDict, which is a class that subclasses dict. Your implementation of .__setitem__() always sets values to None. If you create an instance of MyDict and pass a keyword argument to its initializer, then you’ll notice the class is not calling your .__setitem__() to handle the assignment. You know that because the key first wasn’t assigned None. By contrast, if you run a subscription operation like my_dict['second'] = 2, then you’ll notice that second is set to None rather than to 2. So, this time you can say that subscription operations call your custom .__setitem__(). Finally, notice that .setdefault() doesn’t call .__setitem__() either, because your third key ends up with a value of 3. UserDict doesn’t inherit from dict but simulates the behavior of a standard dictionary. The class has an internal dict instance called .data, which is used to store the content of the dictionary. UserDict is a more reliable class when it comes to creating custom mappings. If you use UserDict, then you’ll be avoiding the issues you saw before. To prove this, go back to the code for my_defaultdict and add the following method: 1class my_defaultdict(collections.UserDict): 2 # Snip 3 def __setitem__(self, key, value): 4 print('__setitem__() gets called') 5 super().__setitem__(key, None) Here, you add a custom .__setitem__() that calls the superclass .__setitem__(), which always sets the value to None. Update this code in your script my_dd.py and import it from an interactive session as follows: >>> from my_dd import my_defaultdict >>> my_dict = my_defaultdict(list, first=1) __setitem__() gets called >>> my_dict {'first': None} >>> my_dict['second'] = 2 __setitem__() gets called >>> my_dict {'first': None, 'second': None} In this case, when you instantiate my_defaultdict and pass first to the class initializer, your custom __setitem__() gets called. Also, when you assign a value to the key second, __setitem__() gets called as well. You now have a my_defaultdict that consistently calls your custom special methods. Notice that all the values in the dictionary are equal to None now. Passing Arguments to .default_factory As you saw earlier, .default_factory must be set to a callable object that takes no argument and returns a value. This value will be used to supply a default value for any missing key in the dictionary. Even when .default_factory shouldn’t take arguments, Python offers some tricks that you can use if you need to supply arguments to it. In this section, you’ll cover two Python tools that can serve this purpose: With these two tools, you can add extra flexibility to the Python defaultdict type. For example, you can initialize a defaultdict with a callable that takes an argument and, after some processing, you can update the callable with a new argument to change the default value for the keys you’ll create from this point on. Using lambda A flexible way to pass arguments to .default_factory is to use lambda. Suppose you want to create a function to generate default values in a defaultdict. The function does some processing and returns a value, but you need to pass an argument for the function to work correctly. Here’s an example: >>> def factory(arg): ... # Do some processing here... ... result = arg.upper() ... return result ... >>> def_dict = defaultdict(lambda: factory('default value')) >>> def_dict['missing'] 'DEFAULT VALUE' In the above code, you create a function called factory(). The function takes an argument, does some processing, and returns the final result. Then, you create a defaultdict and use lambda to pass the string 'default value' to factory(). When you try to get access to a missing key, the following steps are run: - The dictionary def_dictcalls its .default_factory, which holds a reference to a lambdafunction. - The lambdafunction gets called and returns the value that results from calling factory()with 'default value'as an argument. If you’re working with def_dict and suddenly need to change the argument to factory(), then you can do something like this: >>> def_dict.default_factory = lambda: factory('another default value') >>> def_dict['another_missing'] 'ANOTHER DEFAULT VALUE' This time, factory() takes a new string argument ( 'another default value'). From now on, if you try to access or modify a missing key, then you’ll get a new default value, which is the string 'ANOTHER DEFAULT VALUE'. Finally, you can possibly face a situation where you need a default value that’s different from 0 or []. In this case, you can also use lambda to generate a different default value. For example, suppose you have a list of integer numbers, and you need to calculate the cumulative product of each number. Then, you can use a defaultdict along with lambda as follows: >>> from collections import defaultdict >>> lst = [1, 1, 2, 1, 2, 2, 3, 4, 3, 3, 4, 4] >>> def_dict = defaultdict(lambda: 1) >>> for number in lst: ... def_dict[number] *= number ... >>> def_dict defaultdict(<function <lambda> at 0x...70>, {1: 1, 2: 8, 3: 27, 4: 64}) Here, you use lambda to supply a default value of 1. With this initial value, you can calculate the cumulative product of each number in lst. Notice that you can’t get the same result using int because the default value returned by int is always 0, which is not a good initial value for the multiplication operations you need to perform here. Using functools.partial() functools.partial(func, *args, **keywords) is a function that returns a partial object. When you call this object with the positional arguments ( args) and keyword arguments ( keywords), it behaves similar to when you call func(*args, **keywords). You can take advantage of this behavior of partial() and use it to pass arguments to .default_factory in a Python defaultdict. Here’s an example: >>> def factory(arg): ... # Do some processing here... ... result = arg.upper() ... return result ... >>> from functools import partial >>> def_dict = defaultdict(partial(factory, 'default value')) >>> def_dict['missing'] 'DEFAULT VALUE' >>> def_dict.default_factory = partial(factory, 'another default value') >>> def_dict['another_missing'] 'ANOTHER DEFAULT VALUE' Here, you create a Python defaultdict and use partial() to supply an argument to .default_factory. Notice that you can also update .default_factory to use another argument for the callable factory(). This kind of behavior can add a lot of flexibility to your defaultdict objects. Conclusion The Python defaultdict type is a dictionary-like data structure provided by the Python standard library in a module called collections. The class inherits from dict, and its main added functionality is to supply default values for missing keys. In this tutorial, you’ve learned how to use the Python defaultdict type for handling the missing keys in a dictionary. You’re now able to: - Create and use a Python defaultdictto handle missing keys - Solve real-world problems related to grouping, counting, and accumulating operations - Know the implementation differences between defaultdictand dict - Decide when and why to use a Python defaultdictrather than a standard dict The Python defaultdict type is a convenient and efficient data structure that’s designed to help you out when you’re dealing with missing keys in a dictionary. Give it a try and make your code faster, more readable, and more Pythonic! Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Handling Missing Keys With the Python defaultdict Type
https://realpython.com/python-defaultdict/
CC-MAIN-2021-39
refinedweb
7,411
56.66
Hey there, in this article I'll show you some quick python tips and tricks which will make your life more easier and help you write better code in python. Let's get started 1. Swapping Two Numbers At times you might find yourself wanting to swap two numbers and you are thinking of a better way to put it 🤔, so here's how I prefer to do it... x , y = 10, 20 #Assigning 10 to x and 20 to y print (x, y) #Output will be 10, 20 x, y = y, x #Swapping the values print (x, y) #Output will be 20, 10 And that's how easy it is to swap two numbers *2. How to Reverse a String * Reversing a string is taking a string and printing it in the reverse order, let's see how that can be achieved. The output will be in reverse order myString = "PythonProgramming" print (myString) #Output will be PythonProgramming print (myString[::-1]) # Output will be gnimmargorPnohtyP 3. How To Create A Single String from a List If you have a list of words and you want to join them to form one sentence you can do that easily by using the code below myList = [”Python", ”Programming", "Is", ”Fun”] print (myList) #Output will be ['Python', 'Programming', 'Is', 'Fun'] print (””.join(myList)) #Output will be PythonProgrammingIsFun 4. How To Print the File Path of Imported Module If you ever worked with a module and you want to know it's path so that you can see it's structure, you can do that easily by running this code import os print (os) #Output will be the path of your os module 5. How To Find The Most Frequent Value in a List If you have a list if numbers and you want to find which number appears in the list most frequent, you can do that easily by using this code numbers = [2, 5, 6, 3, 2, 7, 5, 2, 8, 2, 3] print (max(set(numbers), key = numbers.count)) #Output will be 2 That's all I had for this article, if you have other tips and tricks feel free to leave them in the comments section and I'll be glad to check them out... See you in the next article Posted on by: Billy Okeyo A tech enthusiast who is happily married to python programming though i do cheat at times with some of my side chicks 😀😀 PHP, Javascript.😇 Discussion Website to learn Python, Machine Learning and Data Science. bit.ly/codeperfectplus
https://dev.to/billy_de_cartel/5-python-tricks-and-tips-6ea
CC-MAIN-2020-34
refinedweb
422
65.19
Peter Kümmel wrote:Sorry, =1 is missing: Anders Backman wrote: Well in most cases for us, namespaces are crucial. For example a class named Vec3 can be found in multiple places in our framework (once in the SceneGraph and once in the Physics), but its just one place where it can pop up. So some kind of support of Namespaces would be nice...ideas? Hi Anders, I've pushed some code to demonstrate the namespace support of lqt. Calling cmake with -Dnoqt will suppress the Qt binding and will bind cmake ../lqt -Dnoqt=1 the to classes in test/noqt: namespace n1 { class F; } and namespace n2 { class F; } At the moment the code doesn't run but you will see that the binding of lqt can handle namespaces in principle. There are two lua classes: extern "C" LQT_EXPORT int luaopen_n1_LQT_F (lua_State *L) { lqtL_createclass(L, "n1_LQT_F*", lqt_metatable_3, lqt_base_3); return 0; } and extern "C" LQT_EXPORT int luaopen_n1_LQT_F (lua_State *L) { lqtL_createclass(L, "n2_LQT_F*", lqt_metatable_3, lqt_base_3); return 0; } which could be used like this (but first we must fully free the code from the Qt stuff): require 'noqt' n1 = n1_LQT_F.new(); n2 = n2_LQT_F.new(); print(n1:foo()); print(n2:foo()); Peter /Anders On Mon, Jan 19, 2009 at 10:45 PM, Mauro Iazzi <mauro.iazzi@gmail.com <mailto:mauro.iazzi@gmail.com>> wrote: 2009/1/18 Anders Backman <andersb@cs.umu.se <mailto:andersb@cs.umu.se>>: > Ok, great, one step further, at least one left: > Now I added -i ${BINDING_HEADER}/${BINDING_HEADER} > Which generates: > > #ifndef LQT_HEAD_agxStream_LQT_EndOfArchiveException > #define LQT_HEAD_agxStream_LQT_EndOfArchiveException > #include "lqt_common.hpp" > #include "libname/libname" <<<< > #include "lqt_qt.hpp" I assume this is the behaviour you wanted, correct? > // But then this libname depends on another namespace which is then tried to > be included with: > #include <otherlib> > // which is not correct. Not quite sure where this comes from... > // Either it should not be there at all, or it should be <otherlib/otherlib> > class LQT_EXPORT lqt_shell_otherlib_LQT_EndOfArchiveException : public > agxStream::EndOfArchiveException { > > /Anders I think this comes from a trick we added to speed up compilation of Qt bindings. Instead of including the original header, the class includes an header containing the name of the class. It works for Qt. I'll add a switch to turn off this behaviour. Namespaces are not considered. I don't even know how lqt behaves with namespaces. And I don't know how much time it would need to get them working. I think some not-so-clean workaround could be found, if you need it. -- __________________________________________ Anders Backman, CTO Algoryx Simulation AB Uminova Science Park, Box 7973, SE-907 19 Umeå, Sweden anders@algoryx.se <mailto:anders@algoryx.se> Cell: +46-70-392 64 67
http://lua-users.org/lists/lua-l/2009-01/msg00383.html
CC-MAIN-2022-21
refinedweb
443
64
Whenever I had to check if the given parameters to a method are not null, I used to write a null check and throw a IllegalArgumentException if the null check fails: if (user == null) { throw new IllegalArgumentException("User can't be null."); } I have been working on exceptions thrown by php - mysqli & created this snippet below that tries to check a few times to see if a temp glitch has caused the database to fail. if so, it tries to recover. If it cannot then it quits/ ends. Now while the public class TestException extends except2 { public static void main(String[] args)throws Exception { try { try { throw new TestException(); } catch (final TestException e){ } throw new except2(); } catch (TestException a){ } catch (Exception e){ thr For example i have a program with this structure: Domain logic module -> Settings module -> Settings store backend Next is a part of Settings module. def load_from_json(self, json_str): try: self.load_from_dict(json.loads(json_str)) except ValueEr When scaffolding a new ApiController with asynchronous actions and Entity Framework support in Visual Studio 2013, some methods wrap DbContext.SaveChangesAsync calls in try-catch blocks. For instance, the Put method, try { await db.SaveChangesAsync() import java.io.*; class West1 extends Exception { private String msg; public West1() { } public West1(String msg) { super(msg); this.msg=msg; } public West1(Throwable cause) { super(cause); } public West1(String msg,Throwable cause) { super(msg,cause I am posting to an endpoint and passing a Json in it. @POST("/start") @PermitAll public String Connect(Map form) { String stack_callback; String wfid; String ch_id; try { elem1 = form.get("elem1").toString(); elem2 = form.get("ele I have a webapp using Spring + Hibernate through JPA, Spring is effectively translating all persitence exceptions into variations of DataAccessException. I am now trying to catch these DataAccessExceptions in an AOP pointcut like this: @Aspect public When I attempt to insert new data in database via PowerShell, it works. However, if the data is already in database, I get exception. Someone had similar problem, Catch exception calling "ExecuteNonQuery", but I believe I am using the correct SQ I have a problem when I tried to test my class with the database. I am not using hibernate so I cannot rollback database. When exception occurs the database operation stops the test for the exception passes but it fails other test I wrote. How can I private void textBox1_TextChanged(object sender, EventArgs e) { if (textBox1.Text == "") { label4.Text = "Selected Font: Arial, Selected Font Size: " + textBox2.Text; } else { Font font = new Font(textBox1.Text, float.Parse(textBox1.Te I have a class for polynomials. Function of + overloading works but I couldn't use = overloading function because of exception! I debugged the program and saw exception is in destructor, I don't know how to fix it! polynomial::~polynomial() { delete[ My new model: <?php class Style extends Eloquent { protected $table = 'styles'; } Defined route: Route::group(array('prefix' => '/templates'), function(){ Route::post('/style-create', array('uses' => '[email protected]', 'as' => I seem to be having a problem with my project and I have looked everywhere and can't seem to find a solution. I am receiving the error message below when InitializeComponent() is called on one of my forms. It seems to be related to two picture boxes After working fine for a while, my code started to raise a SIGILL exception when used. I didn't understand the documentation. What does the SIGILL exception means in practical therms? This is the code that is raising the exception, could you help me I am developing android app. I am new to Android and I am developing bluetooth app. My project's having an error when I clicked on button my app crashes and having exception which is given in catalog. Here's the XML layout <RelativeLayout xmlns:andro Okay, So I am making a program that "installs" hack clients into minecraft, all I want it to do is: The user selects the location of one json file, then the jar file, then specifies the clients name. The program will then create a directory in: I have a WHILEloop which checks for marks for a particular student. However, it does not loop if the value is invalid (input less than 0 and more than 100): int marks= -1; System.out.print("Student Marks (/100): "); while (((marks< 0) || (marks
http://www.dskims.com/tag/exception/
CC-MAIN-2019-13
refinedweb
717
54.32
Eclipse Community Forums - RDF feed Eclipse Community Forums Open source for performance tools - video <![CDATA[Hi all, i'm writing a paper on test performance tools for video (HLS,SMOOTH,RTSP protocols). can you kindly refer me to relevant open source tools? Many thanks, Doron]]> Doron Shmueli 2014-06-17T19:13:54-00:00 Profiling and Logging <![CDATA[Hi I am using Eclipse Galileo and want to profile an application. I am unable to get Profiling and Logging perspective. Do you I need to install a particular plugin? If yes please send plugin URL. Somewhere I read that Eclipse is not supporting TPTP now? Please suggest some other tool then. Thanks Shailesh ]]> SHailesh Raj 2014-01-23T08:41:17-00:00 Re: Basic While Loop Coding Help <![CDATA[Hello Justin, this group is about the eclipse Test & Performance Tools Platform Project. BTW. the best way to learn programming (or anything else for that matter) is to try hard before searching the web. Otherwise you might just learn how to look up answers... Just my humble opinion which is still utterly unrelated to eclipse TPTP ;) Regards and good luck, Heiner Am 09.10.2013 16:21, schrieb Justin Appave: >!]]> Heiner Westphal 2013-10-09T15:43:53-00:00 Basic While Loop Coding Help <![CDATA!]]> Justin Appave 2013-10-09T14:07:57-00:00 Memory analizer for secondary thread <![CDATA[Hi, I have one java application multithead that I should profiler. My tptp eclipse plugin works OK with memory analizer profiler in local and remote mode but I see only classes that use the main thread, the classes of others threads are not visible, why? It is correct? it is possible see also the classes of others threads? my filter is empty, all classes are visible. Thank you in advance for your answers and sorry for my poor english. Bye Jenko72. ]]> jenko72 jenko72 2013-04-30T15:31:42-00:00 Re: Support for scheduled execution? <![CDATA[Hi Torsten, Thanks for the two suggestions. Although neither one solves the overnight scheduling problem, JUnit Max look like it would do what I need to do. It looks like a well engineered and thought out product. Unfortunately I investigated further and found that it has been released before and then withdrawn. The original deal was a subscription of $2 / month (it's now $100 / year). When it was withdrawn the developer decided that customers options were to continue paying the $2 / month or to stop paying and stop using the product. Now it's only $2 / month, but abandoning the product and expecting customers to keep paying or stop using it doesn't sit well with me. Nor does abandoning the product after only a few months. Pity, because it looks good, but I'm uncomfortable using a product with that history. However, I do appreciate and thank you for your feed back. Tony]]> Tony Walker 2013-03-30T20:36:31-00:00 Re: Support for scheduled execution? <![CDATA[I think Infinitest or JUnit Max might be something worth investigating. Never used one of them though, we use the continuous integration server Jenkins for this purpose. Hope this helps, Torsten ]]> Torsten Stolpmann 2013-03-30T15:17:06-00:00 Support for scheduled execution? <![CDATA[I would like to be able to have Eclipse run scheduled (overnight) tests on my projects. This may sound like a wacky idea, but let me give some background: Like many people, I have Eclipse running continually on my development system. Apart from reboots I am always logged in and just lock the screen when I'm not present, so Eclipse is running 24/7. I would like to run system tests (JUnit and others) on a scheduled basis (overnight). I realize that I could build scripts to do this (Ant, etc) and run them externally to Eclipse, but Eclipse already has all the information necessary to run the tests and building parallel scripts is (or should be) an unnecessary duplication of effort. I could also set up a builder in addition to the Java Builder, but that's not appropriate as I don't want the tests to run every time I save a source file. I do realize that this will give test errors on the unfinished changes that I'm currently working on, but I can live with that -- my main objective is to find where my changes break other projects ASAP. Does anyone know if this is possible within Eclipse? Or alternatively, is there a project that will automatically process the Eclipse configuration files to generate an external script (Ant?) that I could run? Any ideas appreciated. Thanks, Tony]]> Tony Walker 2013-03-30T14:40:29-00:00 Re: Unable to start standalone or integrated Controller Agent <![CDATA[Hello Jonathan, Your post is 3 years old, but it saved my day. Thanx a lot.]]> Sourav Biswas 2013-03-20T10:43:20-00:00 Re: Terminal not accessing .png files from Eclipse Project <![CDATA[Hello David, I cannot quite imagine your setup. What kind of terminal are you running? XTerm on an X server? PuTTy or some other ssh client? Or is it a local terminal on a linux box, or on Windows? And I cannot see if this is related to TPTP in any way. Could you shed some more light on this? Thanks, Heiner Am 18.03.2013 19:18, schrieb David Taylor: > The project runs fine in Eclipse, but when I try to take the files and > run it through Terminal, it seems like it is not accessing the .png > files. I don't know what to do. > > Here is my main class: > > import javax.swing.*; > import java.awt.*; > > public class Frame extends JFrame { > public static String title = "Tower Defense Alpha"; > public static Dimension size = new Dimension(700, 550); > > > public Frame() { > setTitle(title); > setSize(size); > setResizable(false); > setLocationRelativeTo(null); > setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); > > init(); > > } > > public void init(){ > > setLayout(new GridLayout(1,1,0,0)); > > Screen screen = new Screen(this); > add(screen); > > setVisible(true); > > } > > public static void main(String args[]){ > Frame frame = new Frame(); > > > } > } > > > Here is how I am accessing the .png files in Eclipse, which isn't > working in Terminal: > > for (int i=0; i<tileset_ground.length; i++) { > tileset_ground[i] = new > ImageIcon("res/tileset_ground.png").getImage(); > tileset_ground[i] = createImage(new > FilteredImageSource(tileset_ground[i].getSource(), > new CropImageFilter(0, > 26*i, 26, 26))); > }]]> Heiner Westphal 2013-03-18T21:49:31-00:00
http://www.eclipse.org/forums/feed.php?mode=m&l=1&basic=1&frm=87&n=10
CC-MAIN-2014-42
refinedweb
1,064
66.64
This is the second in a series of posts exploring the Million Song Dataset. Every few months you’ll see a query like this on Reddit – someone is looking for songs that slowly build in intensity. It’s an interesting music query since it is primarily focused on what the music sounds like. Since we’ve analyzed the audio of millions and millions of tracks here at The Echo Nest we should be able to automate this type of query. One would expect that Slow Build songs will have a steady increase in volume over the course of a song, so lets look at the loudness data for a few Slow Build songs to confirm this intuition. First, here’s the canonical slow builder: Stairway to Heaven: The green line is the raw loudness data, the blue line is a smoothed version of the data. Clearly we see a rise in the volume over the course of the song. Let’s look at another classic Slow Build – The Hall Of the Mountain King – again our intuition is confirmed: Looking at a non-Slow Build song like Katy Perry’s California Gurls we see that the loudness curve is quite flat by comparison: Of course there are other aspects beyond loudness that a musician may use to build a song to a climax – tempo, timbre and harmony are all useful, but to keep things simple I’m going to focus only on loudness. Looking at these plots it is easy to see which songs have a Slow Build. To algorithmically identify songs that have a slow build, we can use a technique similar to the one I described in The Stairway Detector. It is a simple algorithm that compares the average loudness of the first half of the song to the average loudness of the second half of the song. Songs with the biggest increase in average loudness rank the highest. For example, take a look at a loudness plot for Stairway to Heaven. You can see that there is a distinct rise in scores from the first half to the second half of the song (the horizontal dashed lines show the average loudness for the first and second half of the song). Calculating the ramp factor we see that Stairway to Heaven scores an 11.36 meaning that there is an increase in average loudness of 11.36 decibels between the first and the second half of the song. This algorithm has some flaws – for instance it will give very high scores to ‘hidden track’ songs. Artists will sometimes ‘hide’ a track at the end of a CD by padding the beginning of the track with a few minutes of silence. For example, this track by ‘Fudge Tunnel’ has about five minutes of silence before the band comes in. Clearly this song isn’t a Slow Build, our simple algorithm is fooled. To fix this we need to introduce a measure of how straight the ramp is. One way to measure the straightness of a line is to calculate the Pearson correlation for the loudness data as a function of time. XY Data with correlation that approaches one (or negative one) is by definition, linear. This nifty wikipedia visualization of the correlation of different datasets shows the correlation for various datasets: We can combine the correlation with our ramp factors to generate an overall score that takes into account the ramp of the song as well as the straightness of the ramp. The overall score serves as our Slow Build detector. Songs with a high score are Slow Build songs. I suspect that there are better algorithms for this so if you are a math-oriented reader who is cringing at my naivete please set me and my algorithm straight. Armed with our Slow Build Detector, I built a little web app that lets you explore for Slow Build songs. The app - Looking For The Slow Build – looks like this: The application lets you type in the name of your favorite song and will give you a plot of the loudness over the course of the song, and calculates the overall Slow Build score along with the ramp and correlation. If you find a song with an exceptionally high Slow Build score it will be added to the gallery. I challenge you to get at least one song in the gallery. You may find that some songs that you think should get a high Slow Build score don’t score as high as you would expect. For instance, take the song Hoppipolla by Sigur Ros. It seems to have a good build, but it scores low: It has an early build but after a minute it has reached it’s zenith. The ending is symmetrical with the beginning with a minute of fade. This explains the low score. Another song that builds but has a low score is Weezer’s The Angel and the One. This song has a 4 minute power ballad build – but fails to qualify a a slow build because the last 2 minutes of the song are nearly silent. Finding Slow Build songs in the Million Song Dataset Now that we have an algorithm that finds Slow Build songs, lets apply it to the Million Song Dataset. I can create a simple MapReduce job in Python that will go through all of the million tracks and calculate the Slow Build score for each of them to help us find the songs with the biggest Slow Build. I’m using the same framework that I described in the post “How to Process a Million Songs in 20 minutes“. I use the S3 hosted version of the Million Song Dataset and process it via Amazon’s Elastic MapReduce using mrjob – a Python MapReduce library. Here’s the mapper that does almost all of the work, the full code is on github in cramp.py: def mapper(self, _, line): """ The mapper loads a track and yields its ramp factor """ t = track.load_track(line) if t and t['duration'] > 60 and len(t['segments']) > 20: segments = t['segments'] half_track = t['duration'] / 2 first_half = 0 second_half = 0 first_count = 0 second_count = 0 xdata = [] ydata = [] for i in xrange(len(segments)): seg = segments[i] seg_loudness = seg['loudness_max'] * seg['duration'] if seg['start'] + seg['duration'] <= half_track: seg_loudness = seg['loudness_max'] * seg['duration'] first_half += seg_loudness first_count += 1 elif seg['start'] < half_track and seg['start'] + seg['duration'] > half_track: # this is the nasty segment that spans the song midpoint. # apportion the loudness appropriately first_seg_loudness = seg['loudness_max'] * (half_track - seg['start']) first_half += first_seg_loudness first_count += 1 second_seg_loudness = seg['loudness_max'] * (seg['duration'] - (half_track - seg['start'])) second_half += second_seg_loudness second_count += 1 else: seg_loudness = seg['loudness_max'] * seg['duration'] second_half += seg_loudness second_count += 1 xdata.append( seg['start'] ) ydata.append( seg['loudness_max'] ) correlation = pearsonr(xdata, ydata) ramp_factor = second_half / half_track - first_half / half_track if YIELD_ALL or ramp_factor > 10 and correlation > .5: yield (t['artist_name'], t['title'], t['track_id'], correlation), ramp_factor This code takes less than a half hour to run on 50 small EC2 instances and finds a bucketload of Slow Build songs. I’ve created a page of plots of the top 500 or so Slow Build songs found by this job. There are all sorts of hidden gems in there. Go check it out: Looking for the Slow Build in the Million Song Dataset The page has 500 plots all linked to Spotify so you can listen to any song that strikes your fancy. Here are some my favorite discoveries: Respighi’s The Pines of the Appian Way I remember playing this in the orchestra back in high school. It really is sublime. Click the plot to listen in Spotify. Maria Friedman’s Play The Song Again So very theatrical Mandy Patinkin’s Rock-A-Bye Your Baby With A Dixie Melody Another song that seems to be right off of Broadway – it has an awesome slow build. - The Million Song Dataset – deep data about a million songs - The Stairway Index - my first look at this stuff about 2 years ago - How to process a million songs in 20 minutes – a blog post about how to process the MSD with mrjob and Elastic Map Reduce - Looking for the Slow Build - a simple web app that calculates the Slow Build score and loudness plot for just about any song - cramp.py – the MapReduce code for calculating Slow Build scores for the MSD - Looking for the Slow Build in the Million Song Dataset - 500 loudness plots of the top Slow Builders - Top Slow Build songs in the Million Song Dataset – the top 6K songs with a Slow Build score of 10 and above - A Spotify collaborative playlist with a bunch of Slow Build songs in it. Feel free to add more. .
http://musicmachinery.com/2011/09/18/looking-for-the-slow-build/
CC-MAIN-2014-42
refinedweb
1,453
64.85
Join vs create room I've been looking at the colyseus-examples repository. All the examples are very instructive. However, in the create-or-join-room example, I'm unable to figure out how the room creation is happening. Both for joining or creating the room the code in create-or-join-room.htmlseems to be calling the client.joinfunction. When additional options are being passed isNewRoomis also being set to true. I'm unable to figure out how it's working. When does isNewRoomset to true? I can also see onInitfor the room being called before requestJoin. Could you please explain the flow of the code? I've looked into the code of MatchMaking.tsbut haven't figured out the flow yet. Thanks, Madki - endel administrator last edited by The isNewRoomproperty is set automatically, internally on MatchMaker.ts. In the client-side, there's no built-in API for explicitly creating rooms. The server will try to join the best room it can find (based on maxClients/ requestJoin()) - and, in case no room is suitable for joining, it will create a new room, and then call requestJoin()on it. That's why you see onInit()called before requestJoin(). The room needs to be instantiated before requestJoin()is called. In case a room is found to join, isNewRoomwill be false, to determine that the client is joining an existing room. - see requestJoin()being called from internal create()method - see requestJoin()being called when joining an existing room Hope this helps! Let me know if you have any question. Cheers! Thanks for the quick response and the amazing library! Thanks for the code references. I have better clarity of the process now. What I'm still trying to wrap my head around is how the createoption in the create-or-join-roomexample is consistently able to create a new room. Once a room has been created shouldn't the second request join the same room? Why isn't the request able to find a suitable existing room? As far as I can see the room created after the first request still satisfies the options for subsequent ones. Regards, Madki - endel administrator last edited by endel On the 04-create-or-join-room.tsexample, you can see that the requestJoin()method is checking for both options.createAND isNewRoom. That means requestJoin()will succeed only if isNewRoomis also true. requestJoin (options, isNewRoom: boolean) { return (options.create) ? (options.create && isNewRoom) : this.clients.length > 0; } So, during matchmaking, the server will first try to call requestJoin(options, false)in all unlocked spawned rooms, and - if all of the existing rooms return false- it will create a new room and call requestJoin(options, true)as a final attempt. If even the final attempt returns false, that new room will be disposed immediately. Hope this helps! Cheers! @endel Now I get it! Thanks so much for the help. I have enough to get started on my project. Just curious though, why isn't an explicit create call supported? I see it being useful in scenarios where users can create their own game and share it with friends. The rooms can't really be locked when the game starts as the players might change devices during the course of the game. When there are many existing rooms, the creation of new rooms might become expensive. Is it a security concern for the clients to be able to create the rooms, or just not a common scenario? Regards, Madki
https://discuss.colyseus.io/topic/138/join-vs-create-room
CC-MAIN-2019-30
refinedweb
580
67.45
Print64 (community library) Summary Library for 64-bit number to ASCII conversion Example Build Testing Device OS Version: This table is generated from an automated build. Success only indicates that the code compiled successfully. Library Read Me This content is provided by the library maintainer and has not been validated or approved. Print64 Library for printing 64-bit integers on Particle devices The standard C library on Particle devices (at least as of Device OS 3.0) does not support 64-bit sprintf formatting such as %llu or %llx or Microsoft extensions like %I64u. This includes not only sprintf(), and its variations like snprintf(), but also things that use it, like Log.info(). API toString (uint64_t) Convert an unsigned 64-bit integer to a string String toString(uint64_t value, unsigned char base = 10); valueThe value to convert (uint64_t) baseThe number base. Acceptable values are 2, 8, 10, and 16. Default is 10 (decimal). - Returns A String object containing an ASCII representation of the value. toString (int64_t) Convert an signed 64-bit integer to a string (ASCII decimal signed integer) String toString(int64_t value); valueThe value to convert (int64_t) - Returns A String object containing an ASCII representation of the value (decimal) Example #include "Particle.h" #include "Print64.h" SYSTEM_THREAD(ENABLED); SerialLogHandler logHandler; void setup() { } void loop() { Log.info("millis=%s", toString(System.millis()).c_str()); delay(1000); } The System.millis() function returns a uint64_t. It works like millis() but since it's 64-bit, it doesn't wrap around to 0 after 49 days so it's easier to do comparisons with it. Note that you must add a .c_str() to the result of toString() when passing it as variable arguments to sprintf(), Log.info(), etc.! Browse Library Files
https://docs.particle.io/reference/device-os/libraries/p/Print64/
CC-MAIN-2022-27
refinedweb
287
57.47
[ <<BACK] [ CONTENTS] [ NEXT>>] Like applications, applets are created from classes. However, applets do not have a main method as an entry point, but instead, have several methods to control specific aspects of applet execution. This lesson converts an application from Lesson 2 to an applet and describes the structure and elements of an applet. Application to Applet The following code is the applet equivalent to the LessonTwoB application from Lesson 2. The figure below shows how the running applet looks. The structure and elements of the applet code are discussed after the section on how to run the applet just below. The SimpleApplet class is declared public so the program that runs the applet (a browser or appletviewer), which is not local to the program can access it. Run the Applet To see the applet in action, you need an HTML file with the Applet tag as follows: <HTML> <BODY> <APPLET CODE=SimpleApplet.class WIDTH=200 HEIGHT=100> </APPLET> </BODY> </HTML> The easiest way to run the applet is with appletviewer shown below where simpleApplet.html is a file that contains the above HTML code: appletviewer simpleApplet.html. Applet Structure and Elements The Java API Applet class provides what you need to design the appearance and manage the behavior of an applet. This class provides a graphical user interface (GUI) component called a Panel and a number of methods. To create an applet, you extend (or subclass) the Applet class and implement the appearance and behavior you want. The applet's appearance is created by drawing onto the Panel or by attaching other GUI components such as push buttons, scrollbars, or text areas to the Panel. The applet's behavior is defined by implementing the methods. Extending a Class Most classes of any complexity extend other classes. To extend another class means to write a new class that can use the fields and methods defined in the class being extended. The class being extended is the parent class, and the class doing the extending is the child class. Another way to say this is the child class inherits the fields and methods of its parent or chain of parents. Child classes either call or override inherited methods. This is called single inheritance. The SimpleApplet class extends Applet class, which extends the Panel class, which extends the Container class. The Container class extends Object, which is the parent of all Java API classes. The Applet class provides the init, start, stop, destroy, and paint methods you saw in the example applet. The SimpleApplet class overrides these methods to do what the SimpleApplet class needs them to do. The Applet class provides no functionality for these methods. However, the Applet class does provide functionality for the setBackground method,which is called in the init method. The call to setBackground is an example of calling a method inherited from a parent class in contrast to overriding a method inherited from a parent class. You might wonder why the Java language and browsers, or portable across multiple platforms. For example, Netscape and Internet Explorer know how to look for the init and start methods. Behavior An applet is controlled by the software that runs it. Usually, the underlying software is a browser, but it can also be appletviewer as you saw in the example. The underlying software controls the applet by calling the methods the applet inherits from the Applet class. The init Method: The init method is called when the applet is first created and loaded by the underlying software. This method performs one-time operations the applet needs for its operation such as creating the user interface or setting the font. In the example, the init method initializes the text string and sets the background color. The start Method: The start method is called when the applet is visited such as when the end. After the start method executes, the event thread calls the paint method to draw to the applet's Panel. A thread is a single sequential flow of control within the applet, and every applet can run in multiple threads. Applet drawing methods are always called from a dedicated drawing and event-handling thread. The stop and destroy Methods: The stop method stops the applet when the applet is no longer on the screen such as when the end such as stop live threads. Appearance The Panel provided in the Applet class inherits a paint method from its parent Container class. To draw something onto the Applet's Panel, you. Packages The applet code also has three import statements at the top. Applications of any size and all applets use import statements to access ready-made Java API classes in packages. This is true whether the Java API classes come in the Java platform download, from a third-party, or are classes you write yourself and store in a directory separate from the program. At compile time, a program uses import statements to locate and reference compiled Java API classes stored in packages elsewhere on the local or networked system. A compiled class in one package can have the same name as a compiled class in another package. The package name differentiates the two classes. The examples in Lessons 1 and 2 did not need a package declaration to call the System.out.println Java API class because the System class is in the java.lang package that is included by default. You never need an import java.lang.* statement to use the compiled classes in that package. More Information You can find more information on applets in the Writing Applets trail in The Java Tutorial.
http://www.oracle.com/technetwork/java/applet-137165.html
CC-MAIN-2017-04
refinedweb
937
62.98
. Thankfully more people are catching onto that perhaps there's a bit of a legacy mess here. I think Fedora 17 has the right idea here: That's the best approach I've heard suggested that isn't something alienating like GoboLinux.. Yes, and we who are Windows users know this well. tuaris, Thank you so much for the pointer to GoboLinux, it's a great concept!! In my own distro I faced many similar challenges when I tried to modernize the legacy paths since so many applications hard code them. I found using symbolic links worked, but that's very unclean when the namespace is cluttered with both the old and new paths. I see that GoboLinux solves this with a new kernel feature called GoboHide, which provides an element of backwards compatibility while cleaning directory listings. Maybe it's "made up after the fact", but bringing order into chaos is laudable goal. It's too bad the Linux folks (and SysV folks in general) never "got it".... Except that in the BSD's /usr/local is for everything that comes as a package so it's not like Linux. Fedora has the right idea in mind when they want to simplify the Linux hierarchy, but why put everything in /usr ? Historically /usr was for the user directories, but we've got /home that is now the de facto. Why not put everything back in /bin, /sbin, /lib, etc ? At least you wouldn't need to type 'cd /usr' everytime you need to go somewhere Because that would be more work and less compatible. By putting everything into /usr, you have a *single* directory to concern yourself with when it comes to mounting, sharing and snapshotting an image of the current operating system's binaries. By symlinking in /bin, /sbin, etc. from root into /usr, you also make sure that files automatically exist in both locations for free which actually increases compatibility with scripts and such that make assumptions about locations. Doing the inverse of this means you have to not only deal with making sure /usr/* still exists in some form for compatibility reasons, you're also producing more clutter in root and you're adding to the overhead of attempting to manage a single image of the current OS state since they no longer could exist on the same separate file system._3<<. That would make more sense, in that the Linux initrd/initramfs has taken over the "goal" of the / directory (enough filesystem and utilities to boot the OS) which kind of makes / redundant. It would make more sense to move everything from /usr to /, then the other direction. I can just see in Fedora 18 or 19 where the directories directly off / will be empty, which just seems pointless. If they're going to "optimise" and "streamline" things, then at least do it right. Of course, that would break just about every piece of software out there that expects to install to /usr. But since when has Fedora ever worried about not breaking things need Which would be mostly proprietary software which can't be rebuilt. The bulk of open source software that I've seen can be fixed by telling the build system where to put it. I don't see much of any reason why software shipped with a distribution would be affected much at all by this change. Most closed source software that I've encountered doesn't care where you run it from so long as it can find some libraries. A shell script wrapper to set LD_LIBRARY_PATH or whatever and off you go. It's probably more likely that your binary only software will break due to an ABI change. At lest that's been my experience (happy go lucky as it may seem). I'm neither for or against it. IMO there's bigger things to fret about. The idea is that you can snapshot /usr seperately from /var, /etc, /boot, etc. " If /boot, /var, /home, and /usr are separate filesystems, then it means that / is also a separate filesystem. Why would snapshotting one filesystem be easier than snapshotting another filesystem? And why wouldn't you want to snapshot the application configuration files along with the applications (meaning, /etc along with apps under /)?: ."... Yeah, it may be impossible to do with the current split. But moving things to /usr instead of leaving them in / is just wrong. I've read through the mailing list threads, the wiki articles etc. And all of their reasoning for moving to /usr applies just as well to moving to /. That's what I thought too. Consolidation makes sense, but why further the / root and /usr split, if that was the historic problem to begin with? And if I have a look at my root directory: bin cdrom hardy initrd.img.old lib64 media proc sbin sys usr vmlinuz.old boot dev home lib lost+found mnt root selinux tftpboot var www build etc initrd.img lib32 maverick opt run srv tmp vmlinuz And then at my /usr: bin etc games include lib lib32 lib64 local sbin share src It's clear which the appendix is. And if you were to move the /usr stuff onto main (nowadays have only one partition anyway), then there would hardly be additions. But it also becomes appearant that "/games" is kind of redundant. There's little point in having a separate binary directory for one type of applications. That is just other historic cruft (namely to shame those users who have games installed). Likewise should /include actually be part of /src. And I'm not entirely sure about /share, but that should probably go into /var anyway. Maybe the filesystem isn't used the way it was decades ago, but there are certain use-cases where the original multi-disk split still does make sense. <name>`". Now I will agree that the names are somewhat cryptic - it takes a bit getting used to, but just like every other system developed largely by academia, there is a somewhat steeper learning curve, mostly because of jargon. But once you get past that, it starts to make sense (mostly). There are use-cases where having a separate /bin, /usr/bin and possibly /usr/local/bin is beneficial - diskless network-booting machines spring to mind. A minimal kernel+initrd via PXE contains / and most everything else is loaded from NFS mounted at /usr. The /usr/local environment is provided for site-customized versions of stuff in /usr, making it easy to keep the original distro stuff separate. Again, I'm not saying that the *original* reasons why Unix had those were very good reasons to begin with, but bad solutions can adapt to new problems and become good solutions to those. `". Hence the development of pkill/pgrep. Anyone else looking forward to StaLi:. About gobolinux: A really nice look at system directories... On at least BSD, there is the hier(7) man page that documents the filesystems hierarchical layout. /bin == statically linked binaries, standard unix programs. /sbin == statically linked binaries, system utilities, typically intended system administrators. /usr/bin == shared binaries, base programs for users. /usr/sbin == shared binaries, base system utilities for users. /usr/local/bin == shared binaries, 3rd party user programs. /usr/local/bin == shared binaries, 3rd party system utilities. It's not that difficult, and it's pretty easy to understand.......... Edited 2012-01-30 22:44 UTC By the way, Debian GNU/Linux and Arch Linux has 'man hier' as well. I still think that anyone who has ever complained about being confused by the FHS has not done five minutes of research into the WHY of it. It makes perfectly logical sense. And is by far one of the cleanest file structures I've ever seen, and I've seen a lot of them. Take the Amiga for example, it's got a decent file structure for the most part, Libs, Devs, C, L, S, etc. Now for anyone who has not used an Amiga, would think "what the hell is L for?" Wait, I don't even know right now. Can't think of it, but it's laid out in a fairly organized manner. Windows on the other hand is a horrible mess. Not because of Microsoft, but because of the third party applications. The Linux Distributions (and FreeBSD) are good because the package management keeps things clean. Well, first lets recap that standards structure do not come always from a well thought process in its beginning. Most of the times they are decided upon a need to make interoperability work once a "critical mass" is achieved on some activity or when technical or practical knowledge determine than for safety reasons. The last cases are not prevalent on what we are talking about, at least a priori. So, it really does not matter how it started but how it will guarantee that its goals will be fulfilled. Now, going back to the proposed merge of bin/* to usr/bin/*. I know that fedora (red hat) people do a lot of the hard work to make a working and modern system of FOSS software, linux + gnu + projects, but frankly I think they should grow inside a more respectful attitude towards the FOSS community. Look how this "fix it now" posture created a lot of problems that took "forever" to be finally solved and wasted too many manpower. HAL and Pulse Audio (ok, I know, first rushed by ubuntu folks), just to name few, are terrible examples of this. We already crossed that point when "fix it now" was a must. Our systems already work reasonably. We already have the knowledge and already achieved the critical mass point. It is time to do things properly and have open discussions about possible solutions for our problems like they have on every other engineering field, be our concerns related to interoperability, safety or whatsoever it may be. If someone wonder, I really prefer a more structured approach like they have on debian guidelines and FreeBSD. I see this "dump everything on /usr/bin" as a rushed solution more than a properly build one. Really... Am I the only one, who thinks that all what Thom said is correct? I mean, the directory structure on unix and linux is shit. Really. This is the only word, that is as precise as possible to describe it. I mean, when making it like /apps /user /systems How easy would it be to build on that? I mean, there is no good reason to make a directory system like that, with virtual links for programs, which needs the /usr /bin and so on stuff >>IMAGE. It does make some sort of sense to split /bin and /sbin (or whatever you want to call them: e.g. /userbin vs. /systembin), so that normal users get /bin in their PATH and root gets /bin and /sbin in their PATH. /usr/bin and /usr/sbin make no sense now of course plus most systems don't partition /usr separately either, so this "binaries won't be available if a non-/ partition isn't mounted" issue doesn't really apply nowadays. To be honest, /bin and /sbin make sense to me both from the user vs. system split and also that they are about the shortest name they can be that remains somewhat descriptive of their contents. I've never been too concerned about filing system paths to be honest - the fact that Linux doesn't use ludicrously archaic drive letters for mount points makes it already far superior to Windows already :-) So this is all fine. new installs can do the new stuff. What i really dislike are the current rolling distributions that are basically screwing up folks who have /usr on a separate partition. Arch's latest antics are to install modprobe on /usr/ instead of / Funny part is my initrd builder somehow got reset and i ended up with a trashed system since my '/' mounted but i had no way to load up modules from '/' For most users, the file hierarchy doesn't matter in the slightest. The package manager stuffs files into the appropriate places and things like PATH/LIBPATH/MANPATH make it transparent to the end user. And that is assuming that you're using a shell. It matters to GUI users even less since everything is presented in a tidy sort of way by the DE. So if you're think about it and you're not in one of the following categories, you're thinking about it all wrong. Developers, well, it doesn't really benefit them but they just have to deal with it. Besides, it's probably a lot easier for them to deal with a complex file hierarchy than it is for them to deal with an ever changing file hierarchy. This is something you'd notice as soon as the file hierarchy changes and things just stop working. The people who need the complex hierarchy are systems administrators. Having binaries in separate places is useful because it allows the file system to be split up. This is something that we discovered historically, and sometimes it is still useful so we keep it. The utility ranges from a read-only OS partition to network shares. Heck, even Mac OS X has (or at least had) provisions for this. That's why there are subdirectories under /Users that serve the same function as subdirectories under /System and (IIRC) there are provisions for network mounts too. Remember, not everyone runs a completely up-to-date simple-minded system. [snip...]Besides, it's probably a lot easier for [developers] to deal with a complex file hierarchy than it is for them to deal with an ever changing file hierarchy.... [snip...] Remember, not everyone runs a completely up-to-date simple-minded system. Not everybody even runs just one system: some of us have to deal with a flock of mis-matched servers (with a variety of distributions, yet), as dictated by the PHBs and bean counters, to which we don't even have root... Having separate /bin /sbin /usr/bin /usr/sbin folders is a very important thing. It separates critical system binaries from other computer applications. Merging them is like saying let's dump everything in c:\programs and files\ on windows XP (the last ever windows I used back in 2004) into c:\windows\ It is plain stupid. Let's not keep changing things just because it makes us look cool. you are so... or you just play dumb?... you are so... or you just play dumb?... " About 3600 words for an introduction on a directory structure. Thanks for proving my point. Edited 2012-01-31 11:30 UTC From the first time I read that, it seemed simple enough to me. You might think Gobo Linux brings order, but you aren't taking into account that it carries the "legacy" structure too, it just hides it.... That's not simplifying things, it's just sweeping things under the carpet. Hiding complexity is not the same as removing complexity (though of course it has its place). If you actually want to understand the system you still have to understand it, and with a second system as well, now there is more to understand. The Unix Filesystem Hierarchy Standard comes from a tangled history, it may be true, but it's been morphed into something sensible and more importantly, standard. Yes, usages have evolved, but that's only right and proper to put things to good use. You try and reinvent a standard, you often just end up with two systems because you have to support the legacy. Which is only worse if not everyone sees it as "legacy". (Wayland is wonderful, I love it, but it won't ever kill X, but with X running on top, it makes X actually better!) This Fedora change is small, but to me pointless (or worse), not even a carpet sweeping exercise. The Debian multi-arch change, now there is a file hierarchy change I can get behind. In fact, as someone who has done a bit of cross compiling for ARM, and runs a x64 system (thus i386 too), it's very exciting. I hope it gets pushed out to not just other Linux distros, but to other *nix distros. Maybe even an addition to the standard, you never know! jabjoe, "You might think Gobo Linux brings order, but you aren't taking into account that it carries the 'legacy' structure too, it just hides it." Of course you are correct, but solving that is a real conundrum. Unfortunately one is required to maintain legacy paths whenever compatibility is required since the old paths are hard coded in binaries and libraries throughout the linux software codebase. The *inability* to change them makes the status quo ideologically imperfect, even those who don't mind the legacy paths should recognize this. In my personal distro, I've given it some thought and came up with two possible compatibility solutions. Keep in mind, a motivating goal is to keep application specific files together so that, as with GoboLinux, applications can be installed by untarring a single directory. A list of commands can be built using symlinks pointing to their applicaiton directories. Solution A. Remove the dependency upon legacy paths by modifying the kernel and/or libc to treat file requests as "named resources" instead of absolute file system paths. This mapping could be stored in either a system wide or application specific named resource map. This way, when an application requests "/etc/resolv.conf" or "/usr/bin/perl" or "/dev/ttyS0", it could be mapped to the actual file where-ever it is located. The mapping could be optional and revert to previous behavior as needed. This would provide two immediate benefits: 1. The dependency on fixed legacy fs paths is eliminated (or rather it's internalized to the binaries/libraries). 2. It could provide excellent documentation about what the external dependencies are for any given application, and makes it trivial for administrators to change them per application without recompiling a thing. Solution B. Run applications inside an automatic CHROOT environment to mimic the environment they expect. Basically, the chroot contains a fake root directory layout which symlinks to the actual directory layout and can do so without polluting the actual directory layout with legacy paths. chroot/hostfs -- mount --move of / chroot/bin/ -> hostfs/app/bin chroot/sbin/ -> hostfs/app/bin chroot/usr/bin/ -> hostfs/app/bin chroot/etc/ -> hostfs/config The problem with solution B, is that while it works in a compatible way, users of these apps will see the legacy paths instead of the hostfs paths. Or Solution C, KISS, just stick with the standard as you are going to have to anyway. It's not unreasonable things have hard coded paths to the standard location. The problem isn't those following the standard, it's those breaking it. Bend the standard, maybe campaign for revision. Evolution not revolution. jabjoe, "It's not unreasonable things have hard coded paths to the standard location. The problem isn't those following the standard, it's those breaking it. Bend the standard, maybe campaign for revision. Evolution not revolution." It is unreasonable when the paths don't reflect the legitimate organizational requirements of your distro/system. You'll have to admit that for many, the hierarchy is full of legacy decisions and exceptional logic, which is a source of chaos. It's not unreasonable to want the ability to clean that up moving forward... Why do we have to deal with the sexagesimal anachronism when dealing with time? Why 60 minutes in one hour instead of 100? Doesn't it make more sense? Why do we use the obsolete Gregorian calendar? Why all the months are not equal? There was an attempt to modernize the calendar during the french revolution. It lasted 12 years and was reverted back to the Gregorian calendar. The answer is simple: we have built a culture on top of the Gregorian calendar. Changing it means reinventing almost 2000 years of culture for little benefit. But then, the french revolution still reinvented thousands of years of culture. Why did that happen despite the cost? Because it was worth it. The new system of government is way better than the old one. It has real benefits. Any attempt to change a file system hierarchy is not worth the trouble. There is no benefit and lots of things to reinvent, starting with the file system hierarchy itself. For what benefit? Having /usr called /users? ln -s /usr /users. Pointless. It's the exact same thing. I'm not against progress, I'm all for it. But please, starting over for redoing the same thing is not progress. It's a huge step back. Hum, your summary is a bit biased: - French revolution also invented the metric system which stayed, even though the calendar didn't, why one and not the other? I'm not sure that there a logical reason. - also remember that the French revolution was followed by emperors, so the "benefits" weren't so obvious, it took a long period of time before the "benefits" stuck.. I'm not sure I agree with you, what the difference between the FHS and the imperial system? Both are obsolete, and the metric system was worth the pain IMHO, so maybe a FHS like Gobolinux would be interesting. Thom, what Rob said here was the exact opposite of your summary; shared libraries introduced a new problem that was not there before - they require bin and lib to match, so when splitting the system over two partitions you must, at the very least, make sure nothing in /bin depends on /usr/lib. Computers should have databases of information, not filesystems. Databases are slow. And a filesystem is a database, optimized for data access in large units, many GBs in size. Databases are optimized for data access in tiny units, such as strings, or single numbers. They aren't good at huge units in hundreds of Mbytes. They are not. It's not. Files are unstructured binary blobs. There is no way to query what's inside them. So can databases handle TBs of data, not only GBs. They are..
http://www.osnews.com/comments/25556
CC-MAIN-2015-35
refinedweb
3,726
63.49
Intervals Panda3D’s Interval system is a sophisticated mechanism for playback of scripted actions. With the use of Intervals, you can build up a complex interplay of animations, sound effects, or any other actions, and play the script on demand. The core of system is the Interval class. There are several different kinds of Intervals, which will be discussed in detail in the following pages, but all of them have in common the following property: each Interval represents an action (or a series of actions) that occurs over a specific, finite interval of time (hence the name). The real power of the Interval system comes from Sequences and Parallels, which are a special kind of Interval that can contain nested Intervals of any kind (including additional Sequences and/or Parallels). By using these grouping Intervals, you can easily assemble complex scripts from the basic atoms. Using Intervals In any Panda3D module that uses Intervals, you should first import the interval module: from direct.interval.IntervalGlobal import * There are a handful of methods that all Intervals have in common. To start an Interval playing, use one of the following: interval.start() interval.start(startT, endT, playRate) interval.loop() interval.loop(startT, endT, playRate) The three parameters are optional. The startTime and endTime parameters define the subset of the interval to play; these should be given as times in seconds, measured from the start of the interval. The playRate, if specified, allows you play the interval slower or faster than real time; the default is 1.0, to play at real time. Normally, an Interval will play to the end and stop by itself, but you can stop a playing Interval prematurely: interval.finish() This will stop the interval and move its state to its final state, as if it had played to the end. This is a very important point, and it allows you to define critical cleanup actions within the interval itself, which are guaranteed to have been performed by the time the interval is finished. You can also temporarily pause and resume an interval: interval.pause() interval.resume() If you pause an interval and never resume or finish it, the remaining actions in the interval will not be performed. And you can jump around in time within an interval: interval.setT(time) This causes the interval to move to the given time, in seconds since the beginning of the interval. The interval will perform all of the actions between its current time and the new time; there is no way to skip in time without performing the intervening actions. It is legal to set the time to an earlier time; the interval will do its best to reset its state to the previous state. In some cases this may not be possible (particularly if a Function Interval is involved). interval.setPlayRate(playRate) With this you can change the play rate of the interval when it is already running. Finally, there are a handful of handy query methods: interval.getDuration() Returns the length of the interval in seconds. interval.getT() Returns the current elapsed time within the interval, since the beginning of the interval. interval.isPlaying() Returns true if the interval is currently playing, or false if it was not started, has already finished, or has been explicitly paused or finished. interval.isStopped() Returns true if the interval has not been started, has already played to its completion, or has been explicitly stopped via finish(). This is not quite the same this as (not interval.isPlaying()), since it does not return true for a paused interval.
https://docs.panda3d.org/1.11/python/programming/intervals/index
CC-MAIN-2022-27
refinedweb
596
53.31
There are many ways to achieve fast and responsive applications. Caching is one approach that, when used correctly, makes things much faster while decreasing the load on computing resources. Python’s functools module comes with the @lru_cache decorator, which gives you the ability to cache the result of your functions using the Least Recently Used (LRU) strategy. This is a simple yet powerful technique that you can use to leverage the power of caching in your code. In this tutorial, you’ll learn: - What caching strategies are available and how to implement them using Python decorators - What the LRU strategy is and how it works - How to improve performance by caching with the @lru_cachedecorator - How to expand the functionality of the @lru_cachedecorator and make it expire after a specific time By the end of this tutorial, you’ll have a deeper understanding of how caching works and how to take advantage of it in Python. Free Bonus: 5 Thoughts On Python Mastery, a free course for Python developers that shows you the roadmap and the mindset you’ll need to take your Python skills to the next level. Caching and Its Uses Caching is an optimization technique that you can use in your applications to keep recent or often-used data in memory locations that are faster or computationally cheaper to access than their source. Imagine you’re building a newsreader application that fetches the latest news from different sources. As the user navigates through the list, your application downloads the articles and displays them on the screen. What would happen if the user decided to move repeatedly back and forth between a couple of news articles? Unless you were caching the data, your application would have to fetch the same content every time! That would make your user’s system sluggish and put extra pressure on the server hosting the articles. A better approach would be to store the content locally after fetching each article. Then, the next time the user decided to open an article, your application could open the content from a locally stored copy instead of going back to the source. In computer science, this technique is called caching. Implementing a Cache Using a Python Dictionary You can implement a caching solution in Python using a dictionary. Staying with the newsreader example, instead of going directly to the server every time you need to download an article, you can check whether you have the content in your cache and go back to the server only if you don’t. You can use the article’s URL as the key and its content as the value. Here’s an example of how this caching technique might look: 1import requests 2 3cache = dict() 4 5def get_article_from_server(url): 6 print("Fetching article from server...") 7 response = requests.get(url) 8 return response.text 9 10def get_article(url): 11 print("Getting article...") 12 if url not in cache: 13 cache[url] = get_article_from_server(url) 14 15 return cache[url] 16 17get_article("") 18get_article("") Save this code to a caching.py file, install the requests library, then run the script: $ pip install requests $ python caching.py Getting article... Fetching article from server... Getting article... Notice how you get the string "Fetching article from server..." printed a single time despite calling get_article() twice, in lines 17 and 18. This happens because, after accessing the article for the first time, you put its URL and content in the cache dictionary. The second time, the code doesn’t need to fetch the item from the server again. Caching Strategies There’s one big problem with this cache implementation: the content of the dictionary will grow indefinitely! As the user downloads more articles, the application will keep storing them in memory, eventually causing the application to crash. To work around this issue, you need a strategy to decide which articles should stay in memory and which should be removed. These caching strategies are algorithms that focus on managing the cached information and choosing which items to discard to make room for new ones. There are several different strategies that you can use to evict items from the cache and keep it from growing past from its maximum size. Here are five of the most popular ones, with an explanation of when each is most useful: In the sections below, you’ll take a closer look at the LRU strategy and how to implement it using the @lru_cache decorator from Python’s functools module. Diving Into the Least Recently Used (LRU) Cache Strategy A cache implemented using the LRU strategy organizes its items in order of use. Every time you access an entry, the LRU algorithm will move it to the top of the cache. This way, the algorithm can quickly identify the entry that’s gone unused the longest by looking at the bottom of the list. The following figure shows a hypothetical cache representation after your user requests an article from the network: Notice how the cache stores the article in the most recent slot before serving it to the user. The following figure shows what happens when the user requests a second article: The second article takes the most recent slot, pushing the first article down the list. The LRU strategy assumes that the more recently an object has been used, the more likely it will be needed in the future, so it tries to keep that object in the cache for the longest time. Peeking Behind the Scenes of the LRU Cache One way to implement an LRU cache in Python is to use a combination of a doubly linked list and a hash map. The head element of the doubly linked list would point to the most recently used entry, and the tail would point to the least recently used entry. The figure below shows the potential structure of the LRU cache implementation behind the scenes: Using the hash map, you can ensure access to every item in the cache by mapping each entry to the specific location in the doubly linked list. This strategy is very fast. Accessing the least recently used item and updating the cache are operations with a runtime of O(1). Note: For a deeper understanding of Big O notation, together with several practical examples in Python, check out Big O Notation and Algorithm Analysis with Python Examples. Since version 3.2, Python has included the @lru_cache decorator for implementing the LRU strategy. You can use this decorator to wrap functions and cache their results up to a maximum number of entries. Using @lru_cache to Implement an LRU Cache in Python Just like the caching solution you implemented earlier, @lru_cache uses a dictionary behind the scenes. It caches the function’s result under a key that consists of the call to the function, including the supplied arguments. This is important because it means that these arguments have to be hashable for the decorator to work. Playing With Stairs Imagine you want to determine all the different ways you can reach a specific stair in a staircase by hopping one, two, or three stairs at a time. How many paths are there to the fourth stair? Here are all the different combinations: You could frame a solution to this problem by stating that, to reach your current stair, you can jump from one stair, two stairs, or three stairs below. Adding up the number of jump combinations you can use to get to each of those points should give you the total number of possible ways to reach your current position. For example, the number of combinations for reaching the fourth stair will equal the total number of different ways you can reach the third, second, and first stair: As shown in the picture, there are seven different ways to reach the fourth stair. Notice how the solution for a given stair builds upon the answers to smaller subproblems. In this case, to determine the different paths to the fourth stair, you can add up the four ways of reaching the third stair, the two ways of reaching the second stair, and the one way of reaching the first stair. This approach is called recursion. If you want to learn more, then check out Thinking Recursively in Python for an introduction to the topic. Here’s a function that implements this recursion: 1def steps_to(stair): 2 if stair == 1: 3 # You can reach the first stair with only a single step 4 # from the floor. 5 return 1 6 elif stair == 2: 7 # You can reach the second stair by jumping from the 8 # floor with a single two-stair hop or by jumping a single 9 # stair a couple of times. 10 return 2 11 elif stair == 3: 12 # You can reach the third stair using four possible 13 # combinations: 14 # 1. Jumping all the way from the floor 15 # 2. Jumping two stairs, then one 16 # 3. Jumping one stair, then two 17 # 4. Jumping one stair three times 18 return 4 19 else: 20 # You can reach your current stair from three different places: 21 # 1. From three stairs down 22 # 2. From two stairs down 23 # 2. From one stair down 24 # 25 # If you add up the number of ways of getting to those 26 # those three positions, then you should have your solution. 27 return ( 28 steps_to(stair - 3) 29 + steps_to(stair - 2) 30 + steps_to(stair - 1) 31 ) 32 33print(steps_to(4)) Save this code into a file named stairs.py and run it with the following command: $ python stairs.py 7 Great! The code works for 4 stairs, but how about counting how many steps to reach a higher place in the staircase? Change the stair number in line 33 to 30 and rerun the script: $ python stairs.py 53798080 Wow, more than 53 million combinations! That’s a lot of hops! Timing Your Code When finding the solution for the thirtieth stair, the script took quite a bit of time to finish. To get a baseline, you can measure how long it takes for the code to run. To accomplish this, you can use Python’s timeit module. Add the following lines after line 33: 35setup_code = "from __main__ import steps_to" 36stmt = "steps_to(30)" 37times = repeat(setup=setup_code, stmt=stmt, repeat=3, number=10) 38print(f"Minimum execution time: {min(times)}") You also need to import the timeit module at the top of the code: 1from timeit import repeat Here’s a line-by-line explanation of these additions: - Line 35 imports the name of steps_to()so that timeit.repeat()knows how to call it. - Line 36 prepares the call to the function with the stair number you want to reach, which in this case is 30. This is the statement that will be executed and timed. - Line 37 calls timeit.repeat()with the setup code and the statement. This will call the function 10times, returning the number of seconds each execution took. - Line 38 identifies and prints the shortest time returned. Note: A common misconception is that you should find the average time of each run of the function instead of selecting the shortest time. Time measurements are noisy because the system runs other processes concurrently. The shortest time is always the least noisy, making it the best representation of the function’s runtime. Now run the script again: $ python stairs.py 53798080 Minimum execution time: 40.014977024000004 The number of seconds you’ll see depends on your specific hardware. On my system, the script took forty seconds, which is quite slow for just thirty stairs! Note: You can learn more about the timeit module in the official Python documentation. A solution that takes this long is a problem, but you can improve it using memoization. Using Memoization to Improve the Solution This recursive implementation solves the problem by breaking it into smaller steps that build upon each other. The following figure shows a tree in which every node represents a specific call to steps_to(): Notice how you need to call steps_to() with the same argument multiple times. For example, steps_to(5) is computed two times, steps_to(4) is computed four times, steps_to(3) seven times, and steps_to(2) six times. Calling the same function more than once adds computation cycles that aren’t necessary—the result will always be the same. To fix this problem, you can use a technique called memoization. This approach ensures that a function doesn’t run for the same inputs more than once by storing its result in memory and then referencing it later when necessary. This scenario sounds like the perfect opportunity to use Python’s @lru_cache decorator! Note: For more information on memoization and using @lru_cache to implement it, check out Memoization in Python. With just two changes, you can considerably improve the algorithm’s runtime: - Import the @lru_cachedecorator from the functoolsmodule. - Use @lru_cacheto decorate steps_to(). Here’s what the top of the script will look like with the two updates: 1from functools import lru_cache 2from timeit import repeat 3 4@lru_cache 5def steps_to(stair): 6 if stair == 1: Running the updated script produces the following result: $ python stairs.py 53798080 Minimum execution time: 7.999999999987184e-07 Caching the result of the function takes the runtime from 40 seconds down to 0.0008 milliseconds! That’s a fantastic improvement! Note: In Python 3.8 and above, you can use the @lru_cache decorator without parentheses if you’re not specifying any parameters. In previous versions, you may need to include the parentheses: @lru_cache(). Remember, behind the scenes, the @lru_cache decorator stores the result of steps_to() for each different input. Every time the code calls the function with the same parameters, instead of computing an answer all over again, it returns the correct result directly from memory. This explains the massive improvement in performance when using @lru_cache. Unpacking the Functionality of @lru_cache With the @lru_cache decorator in place, you store every call and answer in memory to access later if requested again. But how many calls can you save before running out of memory? Python’s @lru_cache decorator offers a maxsize attribute that defines the maximum number of entries before the cache starts evicting old items. By default, maxsize is set to 128. If you set maxsize to None, then the cache will grow indefinitely, and no entries will be ever evicted. This could become a problem if you’re storing a large number of different calls in memory. Here’s an example of @lru_cache using the maxsize attribute: 1from functools import lru_cache 2from timeit import repeat 3 4@lru_cache(maxsize=16) 5def steps_to(stair): 6 if stair == 1: In this case, you’re limiting the cache to a maximum of 16 entries. When a new call comes in, the decorator’s implementation will evict the least recently used of the existing 16 entries to make a place for the new item. To see what happens with this new addition to the code, you can use cache_info(), provided by the @lru_cache decorator, to inspect the number of hits and misses and the current size of the cache. For clarity, remove the code that times the runtime of the function. Here’s how the final script looks after all the modifications: 1from functools import lru_cache 2from timeit import repeat 3 4@lru_cache(maxsize=16) 5def steps_to(stair): 6 if stair == 1: 7 # You can reach the first stair with only a single step 8 # from the floor. 9 return 1 10 elif stair == 2: 11 # You can reach the second stair by jumping from the 12 # floor with a single two-stair hop or by jumping a single 13 # stair a couple of times. 14 return 2 15 elif stair == 3: 16 # You can reach the third stair using four possible 17 # combinations: 18 # 1. Jumping all the way from the floor 19 # 2. Jumping two stairs, then one 20 # 3. Jumping one stair, then two 21 # 4. Jumping one stair three times 22 return 4 23 else: 24 # You can reach your current stair from three different places: 25 # 1. From three stairs down 26 # 2. From two stairs down 27 # 2. From one stair down 28 # 29 # If you add up the number of ways of getting to those 30 # those three positions, then you should have your solution. 31 return ( 32 steps_to(stair - 3) 33 + steps_to(stair - 2) 34 + steps_to(stair - 1) 35 ) 36 37print(steps_to(30)) 38 39print(steps_to.cache_info()) If you call the script again, then you’ll see the following result: $ python stairs.py 53798080 CacheInfo(hits=52, misses=30, maxsize=16, currsize=16) You can use the information returned by cache_info() to understand how the cache is performing and fine-tune it to find the appropriate balance between speed and storage. Here’s a breakdown of the properties provided by cache_info(): hits=52is the number of calls that @lru_cachereturned directly from memory because they existed in the cache. misses=30is the number of calls that didn’t come from memory and were computed. Since you’re trying to find the number of steps to reach the thirtieth stair, it makes sense that each of these calls missed the cache the first time they were made. maxsize=16is the size of the cache as you defined it with the maxsizeattribute of the decorator. currsize=16is the current size of the cache. In this case, it shows that your cache is full. If you need to remove all the entries from the cache, then you can use cache_clear() provided by @lru_cache. Adding Cache Expiration Imagine you want to develop a script that monitors Real Python and prints the number of characters in any article that contains the word python. Real Python provides an Atom feed, so you can use the feedparser library to parse the feed and the requests library to load the contents of the article as you did before. Here’s an implementation of the monitor script: 1import feedparser 2import requests 3import ssl 4import time 5 6if hasattr(ssl, "_create_unverified_context"): 7 ssl._create_default_https_context = ssl._create_unverified_context 8 9def get_article_from_server(url): 10 print("Fetching article from server...") 11 response = requests.get(url) 12 return response.text 13 14def monitor(url): 15 maxlen = 45 16 while True: 17 print("\nChecking feed...") 18 feed = feedparser.parse(url) 19 20 for entry in feed.entries[:5]: 21 if "python" in entry.title.lower(): 22 truncated_title = ( 23 entry.title[:maxlen] + "..." 24 if len(entry.title) > maxlen 25 else entry.title 26 ) 27 print( 28 "Match found:", 29 truncated_title, 30 len(get_article_from_server(entry.link)), 31 ) 32 33 time.sleep(5) 34 35monitor("") Save this script to a file called monitor.py, install the feedparser and requests libraries, and run the script. It will run continuously until you stop it by pressing Ctrl+C in your terminal window: $ pip install feedparser requests $ python monitor.py Here’s a step-by-step explanation of the code: - Lines 6 and 7: This is a workaround to an issue when feedparsertries to access content served over HTTPS. See the note below for more information. - Line 16: monitor()will loop indefinitely. - Line 18: Using feedparser, the code loads and parses the feed from Real Python. - Line 20: The loop goes through the first 5entries on the list. - Lines 21 to 31: If the word pythonis part of the title, then the code prints it along with the length of the article. - Line 33: The code sleeps for 5seconds before continuing. - Line 35: This line kicks off the monitoring process by passing the URL of the Real Python feed to monitor(). Every time the script loads an article, the message "Fetching article from server..." is printed to the console. If you let the script run long enough, then you’ll see how this message shows up repeatedly, even when loading the same link. Note: For more information about the issue with feedparser accessing content served over HTTPS, check out issue 84 on the feedparser repository. PEP 476 describes how Python started enabling certificate verification by default for stdlib HTTP clients, which is the underlying cause of this error. This is an excellent opportunity to cache the article’s contents and avoid hitting the network every five seconds. You could use the @lru_cache decorator, but what happens if the article’s content is updated? The first time you access the article, the decorator will store its content and return the same data every time after. If the post is updated, then the monitor script will never realize it because it will be pulling the old copy stored in the cache. To solve this problem, you can set your cache entries to expire. Evicting Cache Entries Based on Both Time and Space The @lru_cache decorator evicts existing entries only when there’s no more space to store new listings. With sufficient space, entries in the cache will live forever and never get refreshed. This presents a problem for your monitoring script because you’ll never fetch updates published for previously cached articles. To get around this problem, you can update the cache implementation so it expires after a specific time. You can implement this idea into a new decorator that extends @lru_cache. If the caller tries to access an item that’s past its lifetime, then the cache won’t return its content, forcing the caller to fetch the article from the network. Note: For more information about Python decorators, check Primer on Python Decorators and Python Decorators 101. Here’s a possible implementation of this new decorator: 1from functools import lru_cache, wraps 2from datetime import datetime, timedelta 3 4def timed_lru_cache(seconds: int, maxsize: int = 128): 5 def wrapper_cache(func): 6 func = lru_cache(maxsize=maxsize)(func) 7 func.lifetime = timedelta(seconds=seconds) 8 func.expiration = datetime.utcnow() + func.lifetime 9 10 @wraps(func) 11 def wrapped_func(*args, **kwargs): 12 if datetime.utcnow() >= func.expiration: 13 func.cache_clear() 14 func.expiration = datetime.utcnow() + func.lifetime 15 16 return func(*args, **kwargs) 17 18 return wrapped_func 19 20 return wrapper_cache Here’s a breakdown of this implementation: - Line 4: The @timed_lru_cachedecorator will support the lifetime of the entries in the cache (in seconds) and the maximum size of the cache. - Line 6: The code wraps the decorated function with the lru_cachedecorator. This allows you to use the cache functionality already provided by lru_cache. - Lines 7 and 8: These two lines instrument the decorated function with two attributes representing the lifetime of the cache and the actual date when it will expire. - Lines 12 to 14: Before accessing an entry in the cache, the decorator checks whether the current date is past the expiration date. If that’s the case, then it clears the cache and recomputes the lifetime and expiration date. Notice how, when an entry is expired, this decorator clears the entire cache associated with the function. The lifetime applies to the cache as a whole, not to individual articles. A more sophisticated implementation of this strategy would evict entries based on their individual lifetimes. Caching Articles With the New Decorator You can now use your new @timed_lru_cache decorator with the monitor script to prevent fetching the content of an article every time you access it. Putting the code together in a single script for simplicity, you end up with the following: 1import feedparser 2import requests 3import ssl 4import time 5 6from functools import lru_cache, wraps 7from datetime import datetime, timedelta 8 9if hasattr(ssl, "_create_unverified_context"): 10 ssl._create_default_https_context = ssl._create_unverified_context 11 12def timed_lru_cache(seconds: int, maxsize: int = 128): 13 def wrapper_cache(func): 14 func = lru_cache(maxsize=maxsize)(func) 15 func.lifetime = timedelta(seconds=seconds) 16 func.expiration = datetime.utcnow() + func.lifetime 17 18 @wraps(func) 19 def wrapped_func(*args, **kwargs): 20 if datetime.utcnow() >= func.expiration: 21 func.cache_clear() 22 func.expiration = datetime.utcnow() + func.lifetime 23 24 return func(*args, **kwargs) 25 26 return wrapped_func 27 28 return wrapper_cache 29 30@timed_lru_cache(10) 31def get_article_from_server(url): 32 print("Fetching article from server...") 33 response = requests.get(url) 34 return response.text 35 36def monitor(url): 37 maxlen = 45 38 while True: 39 print("\nChecking feed...") 40 feed = feedparser.parse(url) 41 42 for entry in feed.entries[:5]: 43 if "python" in entry.title.lower(): 44 truncated_title = ( 45 entry.title[:maxlen] + "..." 46 if len(entry.title) > maxlen 47 else entry.title 48 ) 49 print( 50 "Match found:", 51 truncated_title, 52 len(get_article_from_server(entry.link)), 53 ) 54 55 time.sleep(5) 56 57monitor("") Notice how line 30 decorates get_article_from_server() with the @timed_lru_cache and specifies a validity of 10 seconds. Any attempt to access the same article from the server within 10 seconds of having fetched it will return the contents from the cache and never hit the network. Run the script and take a look at the results: $ python monitor.py Checking feed... Fetching article from server... Match found: The Real Python Podcast – Episode #28: Using ... 29521 Fetching article from server... Match found: Python Community Interview With David Amos 54254 Fetching article from server... Match found: Working With Linked Lists in Python 37100 Fetching article from server... Match found: Python Practice Problems: Get Ready for Your ... 164887 Fetching article from server...... Fetching article from server... Match found: The Real Python Podcast – Episode #28: Using ... 29521 Fetching article from server... Match found: Python Community Interview With David Amos 54254 Fetching article from server... Match found: Working With Linked Lists in Python 37099 Fetching article from server... Match found: Python Practice Problems: Get Ready for Your ... 164888 Fetching article from server... Match found: The Real Python Podcast – Episode #27: Prepar... 30783 Notice how the code prints the message "Fetching article from server..." the first time it accesses the matching articles. After that, depending on your network speed and computing power, the script will retrieve the articles from the cache either one or two times before hitting the server again. The script tries to access the articles every 5 seconds, and the cache expires every 10 seconds. These times are probably too short for a real application, so you can get a significant improvement by adjusting these configurations. Conclusion Caching is an essential optimization technique for improving the performance of any software system. Understanding how caching works is a fundamental step toward incorporating it effectively in your applications. In this tutorial, you learned: - What the different caching strategies are and how they work - How to use Python’s @lru_cachedecorator - How to create a new decorator to extend the functionality of @lru_cache - How to measure your code’s runtime using the timeitmodule - What recursion is and how to solve a problem using it - How memoization improves runtime by storing intermediate results in memory The next step to implementing different caching strategies in your applications is looking at the cachetools module. This library provides several collections and decorators covering some of the most popular caching strategies that you can start using right away.
https://realpython.com/lru-cache-python/
CC-MAIN-2020-50
refinedweb
4,484
62.98
This is a simple CGI-based server with only one method that takes two integers and returns their sum. import Network.XmlRpc.Server add :: Int -> Int -> IO Int add x y = return (x + y) main = cgiXmlRpcServer [("examples.add", fun add)] Note: the argument to fun can be a function that takes any number of arguments. 1.1.1.2 Client This is a client that calls the method implemented by the server above and prints the result. import Network.XmlRpc.Client server = "" add :: String -> Int -> Int -> IO Int add url = remote url "examples.add" main = do let x = 4 y = 7 z <- add server x y putStrLn (show x ++ " + " ++ show y ++ " = " ++ show z) Note: the function returned by remote can be a function that takes any number of arguments..
https://wiki.haskell.org/index.php?title=HaXR&oldid=46294
CC-MAIN-2016-44
refinedweb
129
68.3
Technical Support On-Line Manuals RL-ARM User's Guide (MDK v4) #include <net_config.h> void modem_run (void); The modem_run function is the main thread that performs the command sending actions needed to dial, listen, or disconnect from the remote modem (when TCPnet and the local modem are in command mode). The modem_run function also performs the timeout delays that are necessary when waiting for a response from the local modem and when sending successive commands. The modem_run function for the null modem is in the RL-TCPnet library. The prototype is defined in net_config.h. If you want to use a standard modem connection, you must copy std_modem.c into your project directory. note The modem_run function does not return any value. modem_online, modem_process void modem_run (void) { /* This is a main thread for MODEM Control module. It is called on every */ /* system timer timer tick to implement delays easy. By default this is */ /* every 100ms. The 'sytem tick' timeout is set in 'Net_Config.c' */ if (delay) { if (--delay) { return; } } switch (modem_st) { case MODEM_IDLE: case MODEM_ERROR: /* Modem idle or in error */ break; case MODEM_ONLINE: /* Modem is online - connected */ break; case MODEM_DIAL: /* Dial target number */ proc_dial (); break; case MODEM_LISTEN: /* Activate answering mode */ proc_listen (); break; case MODEM_HANGUP: /* Hangup and reset the modem */ proc_hangup ();.
https://www.keil.com/support/man/docs/rlarm/rlarm_modem_run.htm
CC-MAIN-2020-34
refinedweb
211
64.1
ConnectFlags(), ConnectFlags_r() Modify the flags associated with a connection Synopsis: #include <sys/neutrino.h> int ConnectFlags( pid_t pid, int coid, unsigned mask, unsigned bits ); int ConnectFlags_r( pid_t pid, int coid, unsigned mask, unsigned bits ); Arguments: - pid - The ID of the process that the connection ID belongs to, or 0 for the current process. - coid - The ID of the connection whose flags you want to modify. - mask - A bitmap that indicates which bits are to be modified in the flags. - bits - The new value of the flags. The flags currently defined include: - _NTO_COF_CLOEXEC — close the connection if the process calls an exec*() function to start a new process. bit in the mask is 0, the function doesn't change the current value of the flag.. - ESRCH - The process ID is invalid.
https://developer.blackberry.com/playbook/native/reference/com.qnx.doc.neutrino.lib_ref/topic/c/connectflags.html
CC-MAIN-2020-40
refinedweb
130
63.8
I wonder if you could create a view on one database that references all those databases that you would like to query against? Or perhaps the view contains the query? You could try something like this: import arcpy import os # specify your folder with the .sde connection files sde_folder = r"C:\Users\xbakker\AppData\Roaming\ESRI\Desktop10.2\ArcCatalog" arcpy.env.workspace = sde_folder # list the sde files sdes = arcpy.ListWorkspaces("*", "SDE") # define featureclass name and field name fcname = "state_forest_area" fldname = "total_acres" flds = (fldname) total_acres = 0 # loop through the sde files for sde in sdes: try: sde_path, sde_name = os.path.split(sde) fc = os.path.join(sde, fcname) # assuming data is in sde root and not in a feature dataset lst_acres = [r[0] for r in arcpy.da.SearchCursor(fc, flds)] county_acres = sum(lst_acres) total_acres += county_acres print "County '{0}' has {1} acres '{2}'".format(sde_name[:-4], county_acres, fcname) except Exception as e: print "Error: {0}".format(e) print "check existence of the featureclass and field in the current sde connection" print "Total acres: {0}".format(total_acres) Kind regards, Xander Since it's still early in deployment, you should reconsider the multi-database model, and evaluate putting all the data in a single database, either by using multiple county users, or by making one comprehensive database and using COUNTY_CODE to restrict mapping by county. Cross-database operation will make access to the data for statewide mapping as difficult and inefficient as possible. - V Vince Angelo is absolutely right! (+1 for that) It is better to get things right, create a structure that is durable and enables analysis and statistics rather than start with all types of customization to get results you could obtain without customization if your schema was set up correctly. Invest now in setting up your data correctly, the ROI will be high.
https://community.esri.com/t5/data-management-questions/querying-multiple-sde-databases/td-p/556576
CC-MAIN-2020-50
refinedweb
303
54.32
#include <gromacs/options/filenameoptionmanager.h> Handles interaction of file name options with global options. This class contains all logic that completes file names based on user input and file system contents. Additionally, this class implements support for a global default file name that overrides any option-specific default, as well as additional control over how the completion is done. commandlinemodule. Adding a FileNameOptionManager for an Options object is optional, even if the Options contains FileNameOption options. Features from the manager are not available if the manager is not created, but otherwise the options work: the values provided to FileNameOption are used as they are, and exceptions are thrown if they are no valid instead of attempting to complete them. Adds an option for setting the default global file name. If the user sets the option, it affects all file name options that would normally return a default value: the basename for the returned value is taken from the value of the default file name option, instead from an option-specific default (FileNameOption::defaultBaseName()). Completes default values for file name options. This method is called for each FileNameOption that has a default value (either a standard default value, or if the user provided the option without an explicit value). prefix is the default value without the default extension for the option. If the return value is non-empty, it is used as the default value for the option instead of prefix + default extension. Completes file name option values. This method is called for each value that the user provides to a FileNameOption. The return value (if non-empty) is used as the value of the option instead of the user-provided one. Disables special input file option handling. If disabled, this removes all file system calls from the file name option parsing. The values returned by FileNameOption for input and input/output files are handled with the same simple rule as for output files: the default extension is added if the file does not end in a recognized extension, and no other checking is done. This changes the following behavior: Redirects file existence checks. The manager checks for existence of various files on the file system to complete file extensions. This method can be used to redirect those checks to an alternative implementation. This is used for unit tests to more easily control the result of the checks and to keep the tests as fast as possible by avoiding real file system access. To keep implementation options open, behavior with redirector == NULL is undefined and should not be relied on. For tests, there should only be need to call this a single time, right after creating the manager.
https://manual.gromacs.org/documentation/2019-beta2/doxygen/html-full/classgmx_1_1FileNameOptionManager.xhtml
CC-MAIN-2021-17
refinedweb
447
52.19
The objective of this short post is to explain how to get the MAC address of the ESP8266. Introduction The objective of this short post is to explain how to get the MAC address of the ESP8266. Explaining in detail what is a MAC address is outside of the scope of this post. But, just as a quick explanation, the MAC address is a unique value associated with a network adapter [1]. So, MAC addresses are hardware addresses that uniquely identify a network adapter [1]. Taking in consideration the OSI model, MAC addressing works at a layer (layer 2) lower than IP addressing (layer 3) [1]. In terms of format, MAC addresses are 48-bit in length [2] and typically represented in hexadecimal format, with each two hexadecimal digits separated by “:”. The first 24 bits of the MAC are the identifier number of the manufacturer and the second 24 bits are a serial number assigned by the manufacturer [2]. You can read more about MAC addresses here. The code The code for this tutorial is very simple, since we already have a function to get the MAC of the ESP8266. Since we only want to print the MAC, we will do all the coding on the setup function and leave the main loop empty. First, we include the ESP8266WiFi library, which we typically use to access all the functionality needed for the ESP8266 to connect to a WiFi network. Then, in our setup function, we open the serial port, so we can print the output of our program. To get the MAC dress of the ESP8266, we simply call the macAdress method on the WiFi global variable, which will return the MAC address in the hexadecimal format mentioned early. You can check the full working code bellow, which also includes the empty loop function. #include <ESP8266WiFi.h> void setup(){ Serial.begin(115200); delay(500); Serial.println(); Serial.print("MAC: "); Serial.println(WiFi.macAddress()); } void loop(){} Testing the code To test the code, just upload it to the ESP8266 and open the Arduino IDE console. You should get something similar to figure 1. Figure 1 – Output of the function to get the MAC of the ESP8266. Just to confirm what was explained in the introduction section, we can check if the first 24 bits of the MAC correspond to the manufacturer of the ESP8266, which is Espressif. You can check yours here. It should indicate Espressif, as shown i figure 2. Figure 2 – Result of vendor lookup from the ESP8266 MAC. References [1] [2] Technical details ESP8266 libraries: v2.3.0
https://techtutorialsx.com/2017/04/09/esp8266-get-mac-address/
CC-MAIN-2017-26
refinedweb
430
62.98
One of the more tedious tasks a system administrator has to do is review the system event logs using the Event Viewer. These logs can provide valuable information, but manually finding the worthwhile details in them can be difficult. Luckily, .NET provides some easy, automated ways to read and search event logs. This tip creates a console application that reads a log looking for this type of message: Login failed for user 'sa'. [CLIENT: 255.255.255.255] The 255.255.255.255 is a network address that is attempting to gain access to SQL Server. These events are logged as Failure Audit events in the Application log, and they seem to come from particular IP addresses. The goal is to detect when one of these occurs and to use the hardware firewall to blacklist the source IP address. However, scanning through the event log to find the addresses is a job better done by the computer. Although the example application is a console application, you could change it into a service that monitors the log for particular entries on some set interval. You then could send the entry to an administrator via e-mail. Most administrators respond much better reactively than proactively, simply because there are too many things to watch in a large server farm. The code for an application that reads the event log is simple: using System; using System.Diagnostics; using System.Collections; namespace LogScanner { /// <summary> /// Application to scan system log for a particular message. /// </summary> class Executable { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(string[] args) { string address; int startPos, endPos; EventLog appLog = new EventLog("Application"); Hashtable ipAddresses = new Hashtable(); foreach (EventLogEntry e in appLog.Entries) { if (e.Message.IndexOf("Login failed for user 'sa'.") >= 0) { startPos = e.Message.IndexOf("[") + 9; endPos = e.Message.IndexOf("]", startPos); address = e.Message.Substring(startPos, endPos startPos - 1); if (!ipAddresses.ContainsKey(address.ToString())) { Console.WriteLine("Found " + address + "."); ipAddresses.Add(address.ToString(), address.ToString()); } } } appLog.Close(); } } } First, the application creates an instance of System.Diagnostics.EventLog to read the built-in Application log. If you've created your own log, you can specify the name of that log as an argument. Next, the program creates a hashtable for the addresses it finds. In my case, I get a whole series of attempts from the same address, but I want only one instance of the address to be displayed. The hashtable lets me quickly store the address and add a new address only if it doesn't match. The application then loops through the Entries collection of the log and reads the Message property. You also can look at properties such as the error number, the date/time, and so forth to help you find the messages you're looking for. In the case of a service, it would make sense to store the last event entry that your service read and then look for entries only after that time. Otherwise, you'll duplicate your previous results. Finally, the program looks at the Message property to see if it contains the target message. If so, it extracts the network address (between opening and closing square brackets) and adds it to the hashtable, if it's not already there. It also dumps out the address to the console so that the user can see the address immediately. The application finishes up by closing the application log object. If you were doing this as a service, you might replace the Console.WriteLine with a block of code at the end that e-mails the administrator the addresses that were found..
http://mobile.developer.com/net/net/article.php/3626626/NET-Tip-Searching-System-Event-Logs-for-Valuable-Info.htm
CC-MAIN-2017-34
refinedweb
603
56.86
Aros/Developer/Docs/Libraries/DiskFont Text[edit] Disk Fonts[edit] AROS can use two different fonts: Bitmap using the diskfont.library. A font is basically a mixture of the typeface (shape of letters), style (bold, plain, italic) and size (measured in fonts). The AROS has one built in font called Topaz which can be accessed at all times. If using a disk based font, then you need to use the diskfont.library to load a font from disk. Other font types such as the more common TrueType fonts, you need to use another library (See below). Wanderer calls IconList with NULL font, because diskfont.library is not able to open "arial.font". This happens on the other hand because diskfont.library is not finding the arial.font in FONTS:, because ExAll call returns 0 (== done) on its first call. This means not all fonts are returned, because the passed 1024 bytes buffer is too small to get them all in one go. To load a diskfont, use the OpenDiskFont() function. You need to specify a TextAttr structure to state which font you require, the format of the command is: TextFont font = OpenDiskFont(struct TextAttr textAttr) The format of the TextAttr is: struct TextAttr { STRPTR ta_Name; /* name of the font */ UWORD ta_YSize; /* height of the font */ UBYTE ta_Style; /* intrinsic font style */ UBYTE ta_Flags; /* font preferences and flags */ }; For example, to specify a Topaz font, size 11 with Bold and Italic: struct TextAttr myta = { "topaz.font" 11, FSF_ITALIC | FSF_BOLD, NULL }; If you are drawing with this font, you can change the default Rastport font with the SetFont() command and when done with it using the CloseFont() functions: e.g. struct TextFont *myfont, *oldfont; struct RastPort *myrp; struct Window *mywin; if (myfont = OpenDiskFont(&myta)) { /* you would probably set the font of the rastport you are going to use */ myrp = mywin->RPort oldfont = myrp->Font; SetFont(myrp, myfont); /* perform whatever drawing you need to do */ /* time to clean up. If the rastport is not exclusively yours, you may need to restore the original font or other Rasport values */ SetFont(myrp, oldfont); CloseFont(myfont); } If you want to know what fonts are available in your program before trying to load one from disk, then you can use the AvailFonts() function which can read all the fonts from memory and disk and present them in an AvailFontsHeader structure, followed by a number of AvailFonts structures to be read by your program. You need to allocate some memory before calling this function to store the font information. LONG error = AvailFonts(struct AvailFontsHeader *buffer, LONG bufBytes, ULONG flags ) For example, int afShortage, afSize; struct AvailFontsHeader *afh; afSize = 400; do { afh = (struct AvailFontsHeader *) AllocMem(afSize, 0); if (afh) { afShortage = AvailFonts(afh, afSize, AFF_MEMORY|AFF_DISK); if (afShortage) { FreeMem(afh, afSize); afSize += afShortage; } } else { fail("AllocMem of AvailFonts buffer afh failedn"); break; } }while (afShortage); For each font size described in a FontContents (or TFontContents) structure, there is a corresponding file in that font's directory whose name is its size. For example, for the font size Sapphire-19, there is a file in the Sapphire directory called 19. That file is basically a DiskFontHeader disguised as a loadable DOS hunk and is known as a font descriptor file. For a bitmap font, the ".font" file is a FontContentsHeader structure: Where the fch_FileID field can be either: FCH_ID 0x0f00 uses FontContents structures to describe the available sizes of this font. TFCH_ID 0x0f02 uses TFontContents structures to describe the available sizes of this font. The FontContents structure: struct FontContents { char fc_FileName[MAXFONTPATH]; UWORD fc_YSize; UBYTE fc_Style; UBYTE fc_Flags; }; struct TFontContents { char tfc_FileName[MAXFONTPATH-2]; UWORD tfc_TagCount; /* including the TAG_DONE tag */ /* * if tfc_TagCount is non-zero, tfc_FileName is overlaid with * Text Tags starting at: (struct TagItem *) * &tfc_FileName[MAXFONTPATH-(tfc_TagCount*sizeof * (struct TagItem))] */ UWORD tfc_YSize; UBYTE tfc_Style; UBYTE tfc_Flags; }; struct DiskFontHeader { ULONG dfh_NextSegment; ULONG dfh_ReturnCode; STRUCT dfh,LN_SIZE; UWORD dfh_FileID; UWORD dfh_Revision; LONG dfh_Segment; STRUCT dfh,MAXFONTNAME; STRUCT dfh-TF,tf_SIZEOF; }; Does anyone know what program was used to generate the ttcourier fonts? They were committed by Georg in 2001. IIRC BitLine (see Aminet, comes with source code). Loads font into memory using diskfont.library and then saves it to disk. Source font was truetype font which diskfont.library transforms into bitmap font during loading (if there's a font engine like the freetype based ones which can handle it). There's a small problem with these fonts: the glyphs are all aligned to the left of their box rather than to the centre (this is one of the papercut bugs). I did a quick look at the ttcourier font (with tools like sys:tools/fontinfo and the bitmap font editor "TypeFace" in sys:extras/misc/aminet/). It seems only some sizes (like 14) have the problem and problem is missing/zero kerning/spacing tables. Also looking at the svn log of the font files ("14", etc.) in workbench/fonts/ it seems problem may have happened when the Euro character was (manually) added to the fonts (IIRC with Typeface font editor running under AROS -> maybe a bug there), as I did a quick test with the initial revision of the "14" file which did not seem to have the kerning/spacing tables missing. FreeType Fonts[edit] Note that depending on style and other things fonts are not not always rendered with the same HIDD method. See rom/graphics/text.c. The text not visible on the screenshot is those which gets rendered with BlitColorexpansion method. Examples[edit] #include <diskfont/diskfont.h> #include <proto/exec.h> #include <proto/dos.h> #include <proto/diskfont.h> #include <proto/utility.h> #include <proto/graphics.h> #include <string.h> #include <stdlib.h> #include <stdio.h> struct Library *DiskfontBase; struct UtilityBase *UtilityBase; UBYTE *buf; void cleanup(char *msg) { if (msg) printf("aftest: %s\n", msg); if (buf) FreeVec(buf); if (UtilityBase) CloseLibrary((struct Library *)UtilityBase); if (DiskfontBase) CloseLibrary(DiskfontBase); exit(0); } void openlibs(void) { DiskfontBase = OpenLibrary("diskfont.library", 0); if (!DiskfontBase) cleanup("Cant open diskfont.library!"); UtilityBase = (struct UtilityBase *) OpenLibrary("utility.library", 0); if (!UtilityBase) cleanup("Cant open utility.library!"); } void action(void) { struct TextFont *font; struct TextAttr ta; ta.ta_Name = "Vera Sans Bold Italic.font"; ta.ta_Name = "xhelvetica.font"; ta.ta_YSize = 11; ta.ta_Style = 0; ta.ta_Flags = 0; font = OpenDiskFont(&ta); if (font) { CloseFont(font); } } int main(void) { openlibs(); action(); cleanup(0); return 0; /* keep compiler happy */ } Reference[edit] struct TextFont *OpenDiskFont(struct TextAttr *textAttr) LONG AvailFonts(STRPTR buffer, LONG bufBytes, LONG flags) AFF_MEMORY AFF_DISK AFF_SCALED AFF_TAGGED struct FontContentsHeader *NewFontContents(BPTR fontsLock, STRPTR fontName) struct DiskFont *NewScaledDiskFont(struct TextFont *sourceFont, struct TextAttr *destTextAttr) void DisposeFontContents(struct FontContentsHeader *fontContentsHeader)
http://en.wikibooks.org/wiki/Aros/Developer/Docs/Libraries/DiskFont
CC-MAIN-2014-52
refinedweb
1,098
54.12
Bad MonkeyMember Content count400 Joined Last visited Community Reputation145 Neutral About Bad Monkey - RankMember Monster Classes Bad Monkey replied to Aviscowboy1's topic in General and Gameplay ProgrammingTwo words: data-driven. Not to pick on the personal beliefs of anyone here, but class heirarchies hundreds of levels deep that differentiate SmallGoblinWithTwoWarts from LargeGoblinWithThreeWarts make me want to cry. While the idea of "Animal->Mammal-Dog" style hierarchies works well in the land of academia when trying to demonstrate principles such as inheritance and polymorphism, they tend to be quite painful in real life if you do not take great care in making them flexible, and even then there are just some things that you will find you cannot do (and often not until its very late). As an off-the-cuff example (and prodding poor Joe's nice informative post... no offence meant Joe [smile]), I think a "monster" class is NOT a good candidate for a deep inheritance hierarchy... I just don't see the need to classify them more than one or two levels deep I would tend to stop sub-classifying at a higher level than Joe's example, typically making all "monsters" on an equal level in the tree, and trying to keep the number of abstract sub-classifying levels to a minimum... and focus on making everything more driven by parameters (provided by serialized instances in a file, or passed by calling code, such as an AI agent governing the instance of the monster). Please bear in mind this is totally of the top of my head, and I may recant at any time [smile]... and apologies, but I will be using C#-style syntax and including method bodies in the class definitions... so sue me public abstract class GameObject { // some root class which is often useful for providing functionality such as logging, diagnostics, persistence entry points, etc across many different kinds of game objects... } // class that represents any active unit in the game, whether enemy or friendly npc public abstract class Unit : GameObject { private Avatar avatar; // reference to an object which contains and manages the visual representation of the unit... i.e. model and animation info, textures, etc // any other common attributes that apply to most units private Vector3D position; private Vector3D orientation; private Vector3D velocity; private long hitPoints; private long attackStrength; // etc... // set of virtual methods that are intended to be overridden by your concrete implementations public virtual void Move(...){} public virtual void Attack(...){} // etc... } public class Goblin : Unit { public override void Move(...) { // set the properties governing movement of this goblin according to any special rules you need... } public override void Attack(...) { // select and execute an attack according to current state of this goblin and/or any parameters passed in } // etc... } Again, I apologise that this is such a rudimentary and incomplete example, and sorry if this makes my point no clearer... Anyway, in short: inheritance is way overrated, and should be used judiciously, and data-driven designs (using composition) may very well make extending and tweaking your "monster" catalogue much easier down the track (especially if you can make it possible without having to recompile code Some other ways to think about: - parameterising every possible thing you can think of to do with monsters (i.e. giving them a metric buttload of fields to describe their state and control their behaviour), and have the Unit (or Monster, if you prefer) class methods try and perform actions according to the current values of all these properties. This method requires a LOT of fore-thought as to what your monsters will and will not be able to do, but really opens the game up for tweaking by non-programmers, as all that is required is fiddling of data values rather than deriving from a base class. - write your Unit class to load and run scripts, meaning that again you wouldn't have to derive new classes and compile code in order to come up with new monster types and behaviours. This method would allow for some unseen requirements down the track, but some serious thought has to go into defining the code interface to allow this level of dynamicism. Hope that was some food for thought anyways, and not horribly confusing [smile]... Adam - Quote:Have you ever had a cat, or know someone who had one? I mean, a baby cat that only know to "defecate", eat, and wonder around. When this cat grows up, isn't able to play cat-chasing-games, or hunt birds if you let it in your backyard? Where did that cat learn to "behave" like a cat? From TV? ;) Behavior comes imprinted into its DNA, commonly known as instincts. That's kind of like saying that humans are born with the innate knowledge of how to climb trees and catch frogs [smile]... play is all about trying things out to see the consequences and glean information from the experience. The tendency towards different kinds of play for different species (which may evolve into different survival techniques) can be explained by th differences in how the organism is composed (e.g. lack of hands means climbing things or throwing-catching games are less appealing to a cat). Take the concept that cats and dogs don't get along... exmaples of that can be seen everywhere... so explain why my cat and my dog play together, and my cat cuddles up with dog to sleep... where's the "imprinted behaviour" reflecting millenia of animosity between the species? I propose that this animosity is not really imprinted behaviour, but information that was learned by each cat and dog as they came across each other and came into conflict over resources such as food and territory/shelter. Remove that conflict and fear, and they get along fine. - Quote:So, HTF do they evolve? Surely it is obvious that the worker ants fill out TPS reports detailing their daily encounters and experiences, which are then collected and evaulated by the higher-ups in the colony... didn't you get the memo? [smile] I tend to think that most "knowledge", other than really basic biological functions, are learned through experience... the only shortcut around this process is to have the knowledge passed on by communication with those who have the experience, be that spoken, written, shown by example, chemical exchange, morse code via antennae, or whatever. A side note: You could probably even say that stuff like breathing (yes, breathing) is a learned behaviour... when you are born, your body stops receiving oxygen from the placenta, you begin to suffocate and cells begin to die at an accelerated rate (a Bad Thing TM), so your body tries things to rectify the situation... how many babies "evacuate" when they are born... maybe because the system consisting of their body and "mind" is going nuts trying to adapt to the new environment and twitching muscles left, right, and centre. Its something you have to learn over a *very* short space of time, but it can still be regarded as learned. Anyway, how feasible is it that ants pass on "knowledge" when they bump into other ants? ("hey, there's a giant lump of sugar back there, and as we know from Uncle Fred, sugar is good", or "don't go this way, coz I just saw Jim and Bob get drowned... I hink large amounts of running water are bad... pass it on!") It doesn't sound right to me that an ant pops out of an egg, and goes "damn, I think I'm off to harvest some grain for the good of our illustrious colony!"... surely there is some form of "basic training" where other ants clue it in on what the hell is going on as it wanders around taking its first steps. Then, as it meanders around the world looking for this "food" thing that someone mentioned, it experiences stuff and finds solutions by experimenting (based on what it knows already), and gets "told" other stuff by other ants who have had their own experiences. Relating to the lion example, and the concept of "play"... isn't this just experimentation based on stuff the cub has learned so far? (i.e. gravity makes me fall, biting hurts things, clawing hurts things, pouncing can get me over that last distance quicker and catch things by suprise, sneaking helps me get closer without things detecting me, etc) ... I am pretty sure they are not born with much more than the ability to eat, sh!t, and move around, so therefore complex behaviours are not magically passed on by genetics... they must be learned, and the learning begins the moment they are alive and conscious... a rampant sampling of data from the world around them to try and construct a set of rules by which they can evaluate their environment and themselves and predict their future. Stuff like this just messes my head up when you start reducing it to really basic behaviours [smile]... but it just feels wrong to draw some arbitrary line and say "everything simpler than x is just passed on somehow"... although I guess that must be the case at some cellular level, I feel genetic information has probably got more to do with setting up an organism so that it is biologically efficient and has the capacity to learn well... Language for 9-year old? Bad Monkey replied to TechnoCore's topic in General and Gameplay ProgrammingSome of you are spruiking about C++, saying "its not that hard", and "don't start with some piss-weak language"... but are possibly failing to take into account that you are speaking with the benefit of years of programming familiarity... we are talking about a totally green little kid here. The peeps pimping something along the lines of LOGO, BASIC, or other languages with less hostile syntax rules are much closer to understanding the nature of what fits this situation best... you don't want to scare the poor little bugger off with what looks to be an alien mish-mash of symbols... at this stage, you want to teach the basic principals or data types, variables, and flow control. If the kid laps it up and wants to wade in deeper, fine... but small steps to build confidence ;) Quote: C macros - C++ templated functions C structs - C++ classes C inheritance - C++ inheritance (this I'm not so sure, but I managed to inherit a struct from struc, so most likely it works). C++ is just safer, with typesafety, rather than what macros use. And namespaces dont really make a difference, if you hate them you can just do using namespace foospace; Ferchrissakes!! Most 9-year-olds couldn't spell half of those features, let alone understand and use them. Quote: Actually, code is read a whole lot more than it is written. Readability beats "writability" any day. Amen, brother Arild :) All you whipper-snappers will appreciate this a bit more when you head out into the workforce and find yourself maintaining other peoples' code. Yes, readability is not solely dictated by syntax, but when you are only just learning to write software, tricky or terse syntax can be a hindrance when trying to grasp the true lessons and concepts behind the code. And I repeat... this is a 9 year-old... to my knowledge, "Spot Learns To Hack In C++" has not been released yet, and probably for a good reason ;) [.net] Can I make a sound without a window? Bad Monkey replied to NexusOne's topic in General and Gameplay ProgrammingUm... I believe the Application.Run method blocks until Exit or ExitThread is called... so you are actually not getting past that line I would expect. Just totally shooting from the hip, but hows about something like this: Control c = new Control(); c.CreateControl(); device.SetCooperativeLevel(c, CooperativeLevel.Normal); sound.Play(0, BufferPlayFlags.Default); while(true) { Application.DoEvents(); // other game-loop stuff here... } Syncronizing the keyboard over the network Bad Monkey replied to LonelyStar's topic in Networking and MultiplayerQuote:I do not understand why it would help to abstract the information send to the server more. I mean, if a key (a relevant key) has changed, the server has all the information he needs for in Example accelerating the player. What difference would it make if I tell the server "Hey, I am accerlarating" instead of "Hey, the key, causing me to accelerate, has been pressed"? Well one thing is that you lose the ability to have the player remap their inputs (keys, mouse, gamepad, steering-wheel, etc) to different in-game actions. All I meant by abstraction was the decoupling of keypresses (and other input from control devices) from the actions/commands that they represent... that way multiple inputs may actually be aggregated into one "command" (or a change in one client state property) which may be less data to send to the server, and less processing/deciphering once it gets there as well. I guess you can look at it as you are sending key-state information, but keys themselves don't have any meaning... the actions that they trigger is what the server needs to know, so why not make the interpretation at the client end and give the server less to think about [smile] hplus0603: not sure if the first bit of your reply was directed to me, but I certainly don't advocate sending all the client's state in an update message... just the stuff that has changed since the last acknowledged message to the server. [.net] Run code when command-line app is closed? Bad Monkey replied to adammil2000's topic in General and Gameplay ProgrammingSorry, should have been a bit more specific, but as the AP has indicated, these events are not going to catch circumstances where the process is being aggressively killed (such as hitting "Stop" while debugging, or hitting "End Process" in Task Manager). They should, however, work in cases where the app/service is being closed/stopped in a more civil manner. I don't think the original poster is trying to keep the app alive, so a guardian process is not the solution needed. Rather he wants to ensure cleanup code is always run and resources always released even if the user fails to invoke the correct shutdown commands before quitting (which would be quite a PITA from outside the actual process, if it is even possible). BTW, another event that may be important for you to handle is the UnhandledException event, so that you can at least cover yourself for failures internal to the app. [.net] Run code when command-line app is closed? Bad Monkey replied to adammil2000's topic in General and Gameplay ProgrammingTry the DomainUnload or ProcessExit events of the AppDomain that your program is executing within. Link Syncronizing the keyboard over the network Bad Monkey replied to LonelyStar's topic in Networking and MultiplayerUm... yeah... based on the information you have provided (i.e. no really good reason) I don't think that is what you really want to be doing. I think you will find it creates a much nicer experience for the players, and reduces bandwidth usage quite a bit, if you send more abstract state information concerning the player (e.g. multiple key presses may lead to a change in the players velocity... it is this property rather than the keypresses that the server is interested in), and only send messages when these properties change. See this recent thread for a bit more info. Hope that helps [smile] [.net] C# vs Vb.NET Bad Monkey replied to Kal_Torak's topic in General and Gameplay ProgrammingPardon me if my tone seems offensive (that is not my intent), but how the hell did you arrive at the idea VB.NET is any less suitable than C#? You state it as if you are resigned to the fact that it can't be done (or that someone with a fair degree of authority told you as much, but didn't deem necessary to explain)... Of course you can make perfectly fine and dandy games with VB.NET... it has all the language constructs and class libraries you could ever need to make a game. It is a different syntax on top of the same framework and common language as C#, so ignore the BS, get stuck in, and code that sucka in VB.NET if thats what you know! :) I'm sure someone else will be along shortly to point you at some good examples. As for myself, I prefer the minimalistic syntax of languages like C/C++/C#... hey, its less typing than VB for the most part ;) [.net] How to disable Automatic Garbage Collection in .NET 1.1 SP1 Bad Monkey replied to infra001's topic in General and Gameplay ProgrammingI have to agree with where frob is coming from here... there has to be a better way to address this. I would suggest looking over the way your app is designed and look for opportunities where frequently created transient objects can be pooled (such as "action", "transaction", or "message" type objects), so as to reduce overhead for allocation and finalization/collection. By drawing these frequently used objects from a pool (and just adding another if all objects in the pool are currently in use), and returning/releasing them for re-use, I'll bet that you can maintain a very steady level of memory usage (once the pool has ramped up to size on startup), and minimize the amount of memory that the garbage collector has to reclaim. (note: This approach should also cut down on fragmentation if you pre-allocate your pools at startup, and possibly save on free-space compacting time as well) I am happy to be corrected if I am wrong, but I recall reading an interview or a blog or a .plan or something waaaay back where Tim Sweeney of Epic suggesting this approach when using Managed DirectX (and I wouldn't be suprised if it happens behind the scenes in many instances) to stave off hiccups caused by the garbage collector, so the idea must have some merit :) The other suggestion I have is a little less elegant (and makes me cringe a bit), but is there the possibility that throwing hardware at the problem (more processors or faster processors) would reduce it to an acceptable level? Better hardware is often cheaper than reworking an entire software system, even though its a solution that turns the stomach of a developer who takes any pride in what they do :) Decoupling Client Input from the Render Loop Bad Monkey replied to PhilW's topic in Networking and MultiplayerFor a start, I think you may need to abstract your client input away from the messages you are sending to the server (if indeed you are sending individual key presses and mouse clicks/movements). And I don't think time-based updates are quite what you want either... I think what would be advisable is an event-driven approach. The main point is that you really only want to send a message to the server when something changes. What I would suggest is polling client input each time around around the game loop, and using this to calculate changes in key properties such as velocity (i.e. speed and direction of the client's vessel), weapon fire state, etc. These changes are the events that the server really cares about (not actual keystate and the like). Stuff information about these events into a queue. Then, on the networking side of things, just dequeue these events and send them to the server until the queue is empty. Process incoming messages from the server as usual. If you don't receive a ack/response before another event occurs, stick a number of them together (in order) in order to send a more efficient (read: closer to MTU) packet. I suspect a number of action games employ an approach something along these lines (correct me if I am way off anyone). Obviously, you will need to do some sanity checking on the server (so that hacking bastards don't go from 0 to a bazillion metres per second in the blink of an eye). You have to be mindful of what you send... position is generally not a good idea (let the server run the simulation and notify the client where it has moved to). I apologise if I misunderstood how you are currently doing things, but hopefully you get the gist of what I am saying anyway :) [.net] Seperation Of Game Elements Bad Monkey replied to MonkeyChuff's topic in General and Gameplay ProgrammingI agree with Anonymous here... custom attributes rock the cazbah when it comes to this type of plugin architecture and dynamic discovery of features. And just to add a little more, although probing sub-directories is nice, it may be nicer to allow a manifest/config to specify directories to probe (in case they are not below the directory of the laucher app) as well as allowing for a specific assembly to be nominated (to save probing and loading a crapload of assemblies that you may not even need for the current game). [edit] - seems the grammar fairy went on holidays XML Problem Bad Monkey replied to Kryptus's topic in General and Gameplay ProgrammingYour XPath query can be changed to simplify this to a single loop, and casting each "game" element as an XmlElement in the foreach loop allows you to call the GetAttribute method to retrieve "name"... i.e. XmlDocument xmldoc = new XmlDocument(); xmldoc.Load("C:\\Games.xml"); XmlNodeList games = xmldoc.SelectNodes("//supported/games/game"); foreach (XmlElement game in games) { MessageBox.Show( game.GetAttribute("name") ); } Not necessarily the most defensive way to code that, but does it achieve what you are trying to do? The reason your code does not work is because the indexer (ie [] operator) for XmlNode only applies to child nodes that are elements, of which your "game" element has none. [.net] Why can't I say if(struct1 == struct2) in C#? Bad Monkey replied to NexusOne's topic in General and Gameplay ProgrammingQuote:Original post by Holy Fuzz This is true. What I like to do is provide a custom, overloaded MyType.Equals(MyType obj) method, which is called by both the overriden Equals(object obj) method and the == operator. That way, there aren't any unboxing issues, and my personal preference is to not put any "meat" inside of operator methods, but instead to merely provide them as syntactic shortcuts to the methods that do the real work. Good call... this is a wise way to do it in order to make your structs/classes CLS-compliant (as operator overloads are only available in C# for .NET 1.x, while both C# and VB.NET get the feature in 2.0), just in case some twisted individual wants to use your code from COBOL.NET or something equally freaky and wrong ;)
https://www.gamedev.net/profile/3061-bad-monkey/?tab=topics
CC-MAIN-2018-05
refinedweb
3,841
58.11
On Wed, 2009-05-13 at 19:35 +0200, Gianluca Cecchi wrote: > Thanks for answering. > why will I still see queue if_if_no_path? Because that's how retries are implemented; we enable queuing in the device-mapper target and setup a counter. Every time the I/O fails we decrement the counter by one. When it hits zero queuing is disabled in the kernel and the queued I/Os are permitted to fail. This is different to "no_path_retry queue" or "features '1 queue_if_no_path'" because with those options queuing will never be disabled. We keep the I/O in memory indefinitely until the paths return (or the host is rebooted). > Ok for the kb... it was the same I referred to in my qyestion... ;-) Sorry, didn't spot that ;) > And what about having a multipath.conf like this? > > blacklist { > devnode "^cciss!c[0-9]d[0-9]*" > } > I'd put "no_path_retry queue" in your defaults block since you want it for all but one device on this storage: > defaults { > user_friendly_names yes > polling_interval 30 > rr_min_io 100 > } The device section must be inside a devices { /*...*/ } block or it won't get parsed/recognised: > Since you only want this behavior for one LUN, why not set it at the multipath level? > no_path_retry 3 > } > multipaths { > multipath { > wwid 3600507630efe0b0c0000000000000600 > alias mpath0 You can probably put this line in your defaults block and only override it for the LUN on which you want a max of three retries: > no_path_retry queue > } > multipath { > wwid 3600507630efe0b0c0000000000000601 > alias mpath1 > no_path_retry queue > } > [snip] > multipath { I'd probably put the "no_path_retry 3"...? You'll need to remove that features option from the device block as you have above, or specify an empty features property like: features "0" Regards, Bryn.
http://www.redhat.com/archives/dm-devel/2009-May/msg00108.html
CC-MAIN-2014-23
refinedweb
285
71.65
The burning question of our times: Where has all the money gone? If there’s one phrase heard more often than any other these days it’s “there’s no money for that.” Of course “that” refers to: - Medicare, or medical care in general, particularly for the lower-income classes. (And yes, Virginia, there is a class system in this country, just like all the others – maybe more so.) - Social Security, but never mind that all the money paid into the system -- particularly for the “boomer” generation who were required under Reagan to “prepay” their funds -- has been spent on other things to the tune of some $3 trillion. (Something resembling a form of theft or embezzlement to the casual observer like me, but apparently not as this "crime" is never mentioned in any discussion of that liability.) - Education -- that is public education. - Food stamps – Let them eat cake. Or peas, according to President Obama. - Social services for the real poor, the disabled, the marginalized, the helpless. (Believe me, in my work with these people, many living on $624 monthly, “no money” is what I hear from social workers, the city, the county and the state, all the time.) - Roads, bridges and public transportation. - public and national parks There’s just no money! The wealthiest nation in the world with the largest economy is broke. Don’t you get it? Now I just have to say, I, for one find that implausible. It boggles the imagination. If this nation is broke, then something is terribly wrong with management here (in my humble opinion.) But for now, let’s take those that cry “no money” at their word. Doesn’t that beg the question: where has all the money gone? It is in the nature of money to circulate. When one earns money, one spends money and the taxman taketh at both ends. Indeed, in a healthy, circulating economy, the same dollar may be taxed many times over as it changes hands. In this way, the various levels of government receive the funding to run those communal services we all rely upon: public education, roads and other infrastructure, police and fire-fighting services, waste disposal, emergency services, security… all the stuff that makes our modern lives possible. When the flow of money in circulation dries up, slows to a trickle, our economy stagnates and begins to die off – from the bottom up (something worth thinking about.) Less and less of it changes hands and our various levels of government, from municipal, to state, to federal, find little opportunity to take their cut and begin to wither from malnutrition. A good thing say some, but to those who cry “starve the beast until it is small enough to drown in a bathtub,” it behooves us to remind them it is public funding that drives the infrastructure of our society – certainly not private. (Quite frankly, if it is the wealthy who are the job creators, it’s time to examine the idea they truly suck at their job.) To say the money is gone because the government spent it is even more simplistic than this elementary study of the nature of money. If the government spent it, that same money should still be circulating – shouldn’t it? What possible spending could mean no money at all? If it is goods, then the manufacturer of those goods should be paying workers (who will in turn spend,) buying raw materials from suppliers (who will in turn spend,) using energy from producers (who will in turn spend,) and paying dividends to stockholders (who will in turn spend.) And all of it taxable. Same with services. Even in this slippery global world where money may be earned in one society and spent in another that money should still be passing from hand to hand, with a portion of each transaction going into the public coffers, somewhere. But it isn’t. To say the money is gone because it has moved into foreign economies through outsourcing is equally naïve, as it assumes we have nothing anyone wants and the money will never return (unlikely) and would equally assume that the circulation of money in those foreign places has increased relative to the decrease here. It doesn’t take much of a study to find this is not happening, not for the average-man-on-the-street. For those inclined to point to the giants of Asian success in disagreement, they’d better take a look at the lives of those populations as a whole. What we see is not a major increase in general standards of living, but a major increase in flight of capital. (China leads the world not only in poor working conditions and low wages, but also in money “leaking” out of their economy. FYI – Russia is second.) To where? Yes, that’s the question: where has the money gone? To say the world’s money is gone because we’ve squandered it on welfare, unaffordable, unnecessary, nanny-state social programs is perhaps the biggest lie of all. One thing is true: give a poor man a bit of money and you can rest assured it will immediately go back into circulation. (Indeed, instead of throwing money at those that created the problem but left the tab for the whole venture on the shoulders of the tax-payer -- in what had to be the greatest redistribution of wealth in history -- if bail-outs had gone to those hardest hit in our latest crisis instead of the banks, who kept it and did not loan it out as intended, we’d have a whole lot more if it in circulation and a healthier economy. Just sayin’.) The whole world seems to be out of money, as witnessed by near global “austerity programs” and the increasing poverty of the world’s populations as a whole. There is no global economic growth. Indeed, the only thing growing is our population. So far, the only solution to our lack of circulating money dreamed up by our intrepid leaders is to print more of the stuff. We can call this a poor solution if we are inclined to be polite in our language. We can call it the bumbling efforts of those with little understanding of the task they are charged to perform, myopic in vision, self-serving and blatantly stupid, if we want to be a little more articulate. Not only does each new dollar bring with it its weight in debt, not only does each new dollar devalue those that came before but these new dollars seem to disappear as quickly as the presses can print them. Once again, those who can’t see beyond the next election year come up with their next idea: print yet more. Hey gang, when something isn’t working, more of the same will not help. Forgive my simple-minded meditations on money. However, the lack of sophistication does not negate the validity of the question. Apparently, I’m not the only one pondering the conundrum. I strongly urge the reading of this report for anyone at all interested in this question -- which should be all of us (unless you're one of those with untold millions stashed away "off shore." At which point you're probably thinking "oh, shit.... The plebs are on to us.") So has Mr. James Henry the former chief economist at the consulting firm, McKinsey and an expert on tax havens. He has compiled the most detailed estimates yet of the size of the offshore economy in a new report, “The Price of Offshore Revisited.” The most mind-shattering of his revelations is this: A minimum of $21 trillion to a possible $32 trillion -- [an amount equal to the GDP of the United States, Japan and the entire third world combined] -- is sitting in offshore “tax-haven” accounts, beyond the reach of any taxman of any nationality. [And if this isn’t enough to bring on a sense of vertigo, the authors go on to state: ]“We consider these numbers to be conservative” Holy misers, Batman. I think we’ve found the missing money! Or, as the authors describe it: the world’s economies are leaking wealth into a veritable black hole, one that until now, has resisted all attempts to adequately measure its dimensions. Why, everybody must be opening offshore accounts and socking away whatever they can scrape up to amass such an unimaginable pile of cash! You’d think -- but in another shocking revelation the report delivers the following tidbit: It turns out that this distribution is incredibly concentrated. By the authors’ estimates: "...at least a third of all private financial wealth, and nearly half of all offshore wealth, is now owned by the world’s richest 91,000 people – just 0.001% of earth’s population. The next 51 percent of all wealth is owned by the next 8.4 million, another trivial 0.14% of the world’s population." Leapin’ lizards, Daddy Warbucks, this means that the real one percent isn’t even 1%! So, who are this 0.141% of the world’s people, these trans-national private elite? Of course, we don’t know; the pirate bankers’ code of “omerta” being even more sacrosanct than that of any strain of the Cosa Nostra. Even such a financial wizard as Mr. Henry, the main author of this report, found the dictum of ‘follow the money’ next to impossible, though he has come up with certain ‘tells’ that red-flag where and when money disappears. We may be looking at military dictators of third world banana republics, officers of multi-national corporations, drug lords, industrialists making fortunes out of low-paid-next-to-slave-labor in Asian hell-holes, old-family money, stolen assets of Holocaust victims, organized crime, wheelers and dealers of all stripes, oil sheiks and oil barons, Russian gangsters, pirates, even certain American politicians and likely, just garden-variety wealthy people who don’t want to pay taxes. One thing is certain; they have more in common with each other than they do with the rest of us. They share common needs relating to financial secrecy, discreet banking services, tax laws and regulation. Says the author: “Increasingly, indeed, the individual members of this private elite may be assuming many of the same attributes as multinational companies, even as MNCs have been becoming more like private individuals, so far as political rights are concerned. This means that super-rich individuals are increasingly acting as citizens of multiple jurisdictions at once, even though they may be resident of “nowhere” for tax purposes; that they are able to relocate quickly across borders; and that they are able to acquire “representation without taxation,” the ability to exert local political influence in multiple jurisdictions, independent of whatever taxes they pay in any particular jurisdiction. It also means that as a group this transnational elite has, in principle, a strong vested nterest in pushing for weaker income and wealth taxation, weaker government regulation, more “open” markets, and weaker restrictions on political influence and campaign spending across borders – with a huge “transnational haven army” of pirate bankers, law firms, accounting firms, lobbyists, and PR firms ready to do their bidding.” Hmm. Sound at all familiar? The effect of this “capital flight” on the developing nations: . Assuming [this] mountain of assets earned an average 3% a year for its owners, and governments were able to tax that income at 30%, it would generate a bumper [$187 billion in tax revenue] every year." Where is off-shore, anyway? Doesn’t this phrase conjure up images of balmy tropical islands and secretive banks hiding behind nondescript doors? Guess again. Off-shore, for the purpose of tax evasion simply means outside the boundaries of any jurisdiction that might have the right to tax your wealth, not just the usual-rounded-up-suspects like the Cayman Islands or Switzerland. Nope, here are the names of the top banks managing international (read offshore/untaxed) accounts: - Credit Suisse – with $933 billion as of 2010 (Hey! Wait a minute, didn’t the Fed, under the TARP and TALF programs float them a giant low-interest/no-interest loan, one the American taxpayers guaranteed?) - Goldman Sachs – with $840 billion in “international assets under management” in 2010 (Not YOU again!) - Bank of America -- $644 billion (It figures.) Well, here, see for yourself: (look at the photo neatly borrowed from this report and replicated below for you perusal. Hope you have a magnifying glass -- but such difficulty in reading does seem apropos to the murky subject matter.) I'll try and add enough photos so you can bring this one up to screen size. "Intermediary" and "destination banks" -- from off-shore to your shore, an excerpt from the report by Mr. James Henry (which could be called, "Pray, tell me, my dear, who is it that does such a good job of laundering your money? -- so squeaky clean!") “It is important to distinguish between the “intermediary havens” which act as conduits for wealth and “destination havens” where private wealth ultimately ends up. We typically associate offshore legal entities like shell companies, asset protection trusts, captive insurance companies, and haven banks with the conventional list of “offshore havens” (or “Treasure Islands”) …sultry, dodgy tropical islands like Bermuda, the Cayman Islands, Nauru, St. Kitts, Antigua, and Tortola; or the European bolt holes such as Switzerland, the Channel Islands,Monaco, Cyprus, Gibraltar, and Liechtenstein. These 80-odd front-line havens, most of which are “offshore” by anyone’s definition, collectively provide a home to over 60 million people, and over 3.5 million paper companies, thousands of shell banks and insurance companies, more than half of the world’s registered commercial ships above 100 tons, and tens of thousands of shell subsidiaries for the world’s largest banks, accounting firms, and energy, software, drug, and defense companies. For while there are millions of companies and thousands of thinly capitalized banks in these fiscal paradises, few wealthy people want to depend on them to manage and secure their wealth. These stealthy investors ultimately need access to all the primary benefits of “high-cost” First World capital markets -- relatively efficient, regulated securities markets, banks backstopped by large populations of taxpayers, and insurance companies; well-developed legal codes, competent attorneys, independent judiciaries, and the rule of law. Generally, these can only be found in a handful of so-called First World countries like the US, the UK, Switzerland, the Netherlands, Belgium/Luxembourg, and Germany. So we have to look to these “destination havens” in order to get a handle on the size and growth of unrecorded cross-border private wealth.” Such revelations bring many questions to mind, but author James Henry does a much better job of raising them than I would. Here’s another quote from his report: “…. the top ten banks grew even faster than the industry as a whole, an AAGR of over 20 percent per year during this period, sharply increasing their share of the group’s assets under management from 42 percent in 2005 to more than 51 percent in 2010. The irony here is that every one of these leading global banks, except Pictet, were deemed “too big to fail” by their governments in 2008-2010, and collectively received hundreds of billions in taxpayer-financed capital injections, standby credits, loan guarantees, toxic asset guarantees, low-cost loans, and the US Treasury’s February 2009 swap deal with Switzerland.49 They benefitted greatly from the $80 billion AIG bailout and the virtually-zero real interest rate environment established by the world’s central banks. Without these “too big to fail” government subsidies, several would have disappeared. Did the Treasury Departments around the world not understand that these very same banks are leading the world in enabling tax dodging – indeed, to some extent, precisely because offshore investors know that they have been under-written by their Treasury Departments?” Good point, Mr. Henry. Why were the taxpayers of the world made responsible for gigantic sums of money given to those who enable the world’s wealthy to evade taxation? (A great scam which many call the "the greatest redistribution of wealth in history," though for some, the idea that redistribution of wealth actually works from the bottom up is so alien, so radical they may choose not to believe it. After all, this same study finds that this money is not in circulation, not put out to work, but parked in relatively low-interest bearing accounts, tucked away out of sight, out of mind, out of use. What this truly boils down to is this: The elite, who control the assets of the world have taken an inconceivable portion of the world’s wealth and removed it from the economy, while leaving the taxpayers to shoulder the resulting debts. So, at least now we have a good idea where all the money went, if not much else. New words to an old folk song Where has all the money gone, Long time passing? Where has all the money gone, Long time ago? Where has all the money gone? To offshore banks, ne’er to return. Oh, when will we ever learn? Oh, when will we ever learn? With apologies to Peter, Paul and Mary. Lynda M Martin, August 14, 2012 If I were a rich man (and had an offshore acount) di-de-de-di-di-di More by this Author - 25 The unfunded liability of Social Security is a hot topic for all political debate. Yes, it's a problem. But do they tell you how it got that way? - 191 A history of the United States National Debt, from 1788 to 2009, in text and pictures. Ponder the true foundations of this $12 trillion and growing debt, the changes in policy and values along the way, the personalities... - 75 It's an ongoing debate. Does television accurately reflect our society, or does society reflect television? Holy Writerscramp, Batwoman -- I mean, Lynda -- what a great job! You've taken a foggy issue and rendered it clear. For sure I will read the full report, and thank you. Chuck I guess you really do have to spend money to make money. Unless you are rich and have a fat offshore account. Wow Lynda, what an enlightening piece of writing this is. I had actually never thought about money being taken out of circulation as you described it in this hub. The list of banks who provide this hidy-hole from the tax man is amazing, and some of our very own are on the list. The really sad part is many of us are seeing our lifetime savings ending up in these accounts, but not being put there by us. It would be very interesting if everyone who had money or investments with any of our own banks involved with this just closed their accounts and moved their investments to another financial institution. Will we reach the day when the very last dollar finds its' way into one of these accounts? Heck, we might be better off if we go back to trading beads instead of paper money. At least the beads are worth something. This was a very well done piece. This makes for sobering reading, Lynda. But what is the game plan behind all this? Surely it benefits no-one, not even the super-rich, to have money stashed away, doing nothing? A whopping great big bank balance might give you a warm glow temporarily, but surely knowing that your stash is in part responsible for the misery of others, must reduce that pleasure? Or am I just being naive? Please ask yourself this question: What would happen if the world made an overall reset? No more money on Kayman Islands, no more sovereign debt in the US, UK, Japan .. , no more pension funds, insurance bonds. All this from a single instant on, one microsecond, like big bang. All that would exist in this single instant would be assets, the house you live in, the infrastructure, production equipment, natural resources... and human resources. Just imagine what would happen in this world without any money related to the past. In this situation there will be 4 categories of countries, economies if you will: 1. Economies with large assets, and large resources 2. Economies with large assets, but little resources 3. Economies with little assets, but large resources 4. Economies with little assets and little resources. The difference between assets and resources is that assets is the past while resources allow for accumulation of future well being and wealth. If you break this down to individual countries, there is China and the BRIC economies in category 3. Most developed economies are in category 1. and 2., while so called 3rd world is in cat.4. What would you think will happen after reset? My suggestion is that those countries with large resources will benefit immediately. Of course the countries with large assets will not feel the pain immediately, people sit high and dry in the homes, but they would soon find out that without proper use of resources the house will deteriorate, not to mention that plywood doesn´t taste good for eating. With this little thought experiment in mind, is it really important if some 20 Trillion of money hide somewhere in the Carribean? Isn´t it more important to take care of improving resources? Isn´t it more important to make the US stay in category 1 and not drift to category 2? And here I've been pooh-poohing my son's conspiracy theories of a New World Order. I admire your ability to bring this concept down to a level where even I can (more or less) understand it. Always love your subtled humor, too, L. The only positive that comes to mind at this point is, "You can't take it with you." Little consolation. But ultimately true. Speaking of futuristic, what-if novels, how about one on what positive changes that money could make if applied to (for example) world hunger, disease eradication, climate control, or even a few jobs here and there...? lmmartin - may i object, it is not about the world, it is only about some money gambling. Please follow this little piece of math: World GDP is some 75 to 80 Trillion USD (at least in that range). Now i make a conservative estimate and judge the world assets to be around 4 to 8 times the value of the GDP. Let me stick to multiplier 6 and that gives us 300 Trillion in asset values, that is houses, offices, production machines, combines, excavators, roads, habours, airports, ships, airplains, cars, your lawn mower and your coffee machine. Now the 20 Trillion in the Carribean is how much - 6%? I am not worried about the 6%, i am worried about the 100% in assets, that a deteriorating if not maintained, replaced, renewed, optimized... The state of an economy must be measured how the maintenance job is done, not how good the economy is in hunting down the 6% missing capital. Actually the world behaves much like you and me. If you are middle class somewhere in a developed economy on this planet, you may have a house, one or more cars, some grown man/woman play toys and a lawn mower. That may be worth 300.000 bucks. Not all of that may be payed off, so you sit on some debt, same as economies all over this planet do. And you may have some cash hidden in the bedroom under your matress or in an old mug like your grandmother taught you to overcome bad times. Does the world behave much different? I think not. There are no conspiracy activities behind. There is no money asset accumulation of worrysome dimension. With "novel" you refer to the little thought experiment in my first comment? That is not entirely fiction. In 1948 something very similar happened in West Germany. All monetary assets had been worthless anyhow (black market) and the DM was introduced. The "big bang" instant made all people moreless equal: Everyone received an onhand cash payment of 40 DM (close to nil).?... Of course, applying this on our entire planet will remain fiction, although the thought holds some beauty. You are right of course. This article will not make you popular with the conservatives. They don't want the poor to have anything. I talked to a soldier from the recent wars, he said that the soldiers have everything that they need? They are not going to end the wars, there would no jobs for the soldiers, to come home to. The game is for the rich to forget about the lower income Americans and see what they can do for themselves. Corporate Greed has reached its highest level, and they don't care if you die from lack of food and medical care. I marked you up. Nan - This is not my hub but I have to ask. Are you saying that only Conservatives can be guilty of greed and not really caring about their fellow man? I would have to believe there are many like this on both sides of the fence. I adore this hub. Indeed, where has the money gone? When those stupid 'job creators' don't generate anyone to buy their goods, well, I hope their gold tastes good with salt and pepper. Let Them eat cake then! Great hub, says a lot. If no one gets it from this one, well they must be living under a rock. Very well done hub. You put a lot of work into compiling this info and it gives a lot of food for thought. We are powerless pawns in the game of big business and corporate greed. The powers that be control more than we would all like to admit and really know. But knowledge is power, and hopefully, you will raise awareness, so perhaps we gain gain a bit more power back to the people. Nicely done. "print yet more" - Yes, this is certainly what is happening in my opinion and we can see that inflation is on the rise. I was not alive right after WWII but my grandmother told me that at that time, she sent a student home (she was a teacher) to buy two eggs from his mother to bring to her. She told me that she gave the kid three million lei (the Romanian Currency). I wonder if I am going to have to experience paying three million dollars for two eggs in the future ...? "Hey gang, when something isn’t working, more of the same will not help." - I actually said this to someone in an email not long ago: "We cannot keep doing the same thing over and over again, expecting a different result." Have we lost all logic and common sense? So, all of us in the Occupy Movement got it all wrong with our "We are the 99%" signs - it's even worse ... I like Mr. Old Poolman's comment: "It would be very interesting if everyone who had money or investments with any of our own banks involved with this just closed their accounts and moved their investments to another financial institution." - We at the Occupy Movement tried to promote this last year. We had some who did close their bank accounts:-... And some people got arrested for trying to close their accounts: I no longer use any of the major banks either. I use a credit union now. In good time, the banksters are going to fry anyway. This is a great article Mrs. Lynda! I will certainly share this. More and more people are realizing that they have been robbed by banksters so, I am optimistic. I see Light at the end of the tunnel. Thank You for putting this piece of writing together. Cheers! : ) Hello again Mrs. Lynda, it is indeed difficult to leave my bias behind, especially my political bias. Indeed there are more "insidious villains" than the banksters - people such as Tony Blair for example, top villains actually. Haha!! Yet, I have a serious problem with the way banks do business. They enslave people through debt and so ... I guess I look at all the poverty around, I look at the predatory lending, lending for profit (which I have written about in a couple of articles lately) and I wonder how things could be if there was a milligram of decency and morality within the banking industry. If there was, I am inclined to think that off-shore accounts would not exist because when we cheat others, we really are cheating ourselves - we're all in the same boat and these donkeyish bankers and politicians do not seem to get that. Regarding unfairness and the wealth gap, I have been promoting a documentary I found on Youtube (about an hour long), titled the One Percent. It was done by the heir to the Johnson and Johnson fortune. I found it rather interesting, at least to see how far ignorance can stretch in some human minds (... Well, thank You for the conversation. There is obviously much I still don't know but more and more information has been coming out lately and the water is starting to clear-out. Articles such as this one certainly helps too! All the best! Hi Lynda... what more can be said than Amen... much the same happening here in Canada. A good example is pensions for our members of Parliament here. They slip a dollar in the pot and we slip in another twenty five. It is what they call matching the investment they make. One recently retired after serving four years and picks up a cool 88 K per year and has just been appointed to the Canadian Wheat Board at a nice round number of a 1000 dollars per day when he sits. I might add all expenses paid. Get booted out after an election and they get a big fat severance package. Get booted or resign from your job and see what you get. When I think of the people like my grandparents who came and broke the land by hand and developed many regions they were given very little in comparison. Is it any wonder the line up at the public feeding trough is getting longer. Hugs from Canada A great read, voted up and tweeted. I am tired of the people who disappear the money calling themselves the job creators. I am a job creator - when I hire a roofer, when I buy a new car or appliance, when I spend money, I create jobs. If I can't afford to fix my roof, or purchase anything beyond the cheapest food and used clothing I am not helping the economy (except my local car repair guy because my car is ancient, haha) Excellently written. I have to finish reading this and come back to the comment box, but so far I see where you are going and believe it or not a reset is coming. The U.S. dollar is right now at this moment literally worth less than the paper and cotton it is made of. The Federal Reserve prints money out of thin air that is backed by nothing. In the beginning "money" was actually a receipt that was used to show people how much silver or gold you had. It was never meant to be used as an option to settle a debt by itself. That is until the bankers took over. I recommend a book titled "The Creature From Jekyll Island" by by G. Edward Griffin. And or c heck out my hub "Show Me The Money". You are on the right track to question what you are questioning Immartin, but the rabbit hole goes deeper. Possibly deeper than you want to know. P.S. We might soon see a day when food and the barter system are the sole means of our economy once again. History moves in cycles and it repeats itself. Our nation is due for a reality check from history very soon, and with the global elites working non-stop to expedite the process we need all the preparation we can get. Our National Debt is waaaaaaaay beyond repair. It's like Norm's bar tab from "Cheers". We will never make enough to pay it off. The only way to fix it will be to start over. Refreshing to see these kinds of hubs and minds like yours. Continue to make your way out of The Matrix and take as many people as you can with you on the way:) The Matrix is just a term for "a sleeping mind". It is not literal. I also believe in critical thinking, as well as facts, history, and logical analysis of their affect on our present. Nice to meet you as well and I will be checking out yours. Another good article, lmmartin! I believe you will find the lost money (the U.S. dollars, anyway) in t-bills. Any word on how many t-bills are held by these offshore banks? John "You're making a very large mistake in your analysis. You're following the flow of money, which is important in some circumstances. But money isn't what really makes an economy. What really matters is the production of goods & services. You're suggesting that taking a taxpayer dollar and using it to pay a government employee or the homeless grows the economy because it forces for-profit enterprise to do something creative in order to earn that dollar back. That's just not correct." The above quote is from Milton Friedman who won the Nobel Prize in Economics Lynda. Now I'll apply it to your specific application of the question he was asked 20 years ago in that response (and I can give you the link to that exact answer on youtube if you'd like). In the US we presently have an ever increasing percentage of the population employed by the government, therefore providing no good or service to the economy. Additionally, you assume the government is efficient in its use of tax revenue, which it is not. For every $2 the government collects it wastes $1. That is actually where your missing money is going. Beyond that though if you have 15% of the economy working for the government then it is being supported by 85% of the economy. If that 85% is being taxed at an average 20% rate with 10% of that tax revenue wasted by the government then you really have 76% of the economy producing the goods & services that support 100% of the economy. That's where your problem in jobs comes from, thats where your "missing money" comes from. Feel free to join me on econ-forum.net for all manners of stimulating discussions like this ;) Creating money out of nothing and even making loans on debts is why we are where we are. The system is in the black and has no real value. I would have to write twelve pages just to explain this Ponzi scheme. In the end true money was made and went to the wealthy and faceless enterprises and middle men took the hit and the debt is now on us the tax payers. Those responsible have never paid taxes and now are working on the next 20 to 40 year cycle of currency manipulation. Like listening to your grand parents describe the great hypocrisy of life your children will be doing the same in their old age. In reality most of us are trapped in economic servitude of a false financial system that will never better your lives. 40
http://hubpages.com/politics/The-burning-question-of-our-times-Where-has-all-the-money-gone
CC-MAIN-2017-09
refinedweb
5,971
70.43
Sanjog Misra, who uses Rcpp for Monte Carlo Markov Chain (MCMC) analyses in quantitative marketing, kindly set me a short example of Rcpp use. The example is based on a blog post by Darren Wilkinson which itself discusses and compares the suitability of R, Python, Java or C for MCMC analysis, using the Gibbs sampler as a concrete example. Darren’s post is worth checking out: he stresses the rather pragmatic aspects of how fast and/or easy it is to write the code, rather than just the mere runtime. As such, he is not too concerned with a speed advantage of Python over R which he sees at a factor of around 2.4, leaving him to continue to prototype in R. Similarly, with C ‘only’ being faster than Java by a factor of two, he prefers Java for the numerically more demanding parts. We do of course advocate the use of Rcpp to combine the best aspects of R and C++, respectively. This Gibbs sampler example provides a nice backdrop. So working with Darren’s example, consider the same Gibbs sampler for a bivariate distribution (and apologies for the lack of latex typesetting on my blog) f(x,y) = k x^2 exp( -x y^2 - y^2 + 2y - 4x) where the conditional distributions are f(x|y) = (x^2)*exp(-x*(4+y*y)) ## a Gamma density kernel f(y|x) = exp(-0.5*2*(x+1)*(y^2 - 2*y/(x+1)) ## a Gaussian kernel Sanjog then spotted and corrected a small error in the variance expression in Darren’s derivation; this is now acknowledged on Darren’s website. Full details are in the R script now committed in SVN. The R code for the Gibbs sample can therefore be written as follows below. Note that this uses thinning to minimize serial correlation in the conditional densities–which renders the computation more demanding as ‘N times thin’ draws have to be generated: ## Here is the actual Gibbs Sampler ## This is Darren Wilkinsons R code (with the corrected variance) ## But we are returning only his columns 2 and 3 as the 1:N sequence ## is never used below } A second variant can be computed using the R bytecode compiler which appeared with the recent release of R 2.13.0 (and which we analysed in this blog post from April). This is as easy as ## We can also try the R compiler on this R function RCgibbs <- cmpfun(Rgibbs) Thanks to Rcpp and the inline package, we can also write a C++ variant that can be built and launched from R with ease. The C++ code is assigned to an R text variable gibbscode. (And we used to typeset such code on the blog as a charater string, ie in a faint red color—but have now switched to highlight it as if it were freestanding C++ code. It really is passed as a single string to R which then uses the cxxfunction() to compile, link and load a C++ function built around the code. See previous posts on the inline package for more.) ## Now for the Rcpp version -- Notice how easy it is to code up! gibbscode <- ' using namespace Rcpp; // inline does that for us already // n and thin are SEXPs which the Rcpp::as function maps to C++ vars int N = as<int>(n); int thn = as<int>(thin); int i,j; NumericMatrix mat(N, 2); RNGScope scope; // Initialize Random number generator // The rest of the code follows the R version double x=0, y=0; for (i=0; i<N; i++) { for (j=0; j<thn; j++) { x = ::Rf_rgamma(3.0,1.0/(y*y+4)); y = ::Rf_rnorm(1.0/(x+1),1.0/sqrt(2*x+2)); } mat(i,0) = x; mat(i,1) = y; } return mat; // Return to R ' # Compile and Load RcppGibbs <- cxxfunction(signature(n="int", thin = "int"), gibbscode, plugin="Rcpp") It is noteworthy how the code logic is essentially identical between the basic R version, and the C++ version. Two nested loops control draws of x from a Gamma distribution, conditional on y, as well as draws of y from a Normal, conditional on x. Add a small amount of parameter passing to obtain the parameters N and thin, allocation of a results matrix and setup of the random number generator state to remain consistent with R, as well as a return of the matrix—and that is all. As Darren’s code uses the GNU GSL in its C variant, I also became interested in seeing how a C/C++ hybrid variant using our RcppGSL package would fare. The code is below. gslgibbsincl <- ' #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> using namespace Rcpp; // just to be explicit ' gslgibbscode <- ' int N = as<int>(ns); int thin = as<int>(thns); int i, j; gsl_rng *r = gsl_rng_alloc(gsl_rng_mt19937); double x=0, y=0; NumericMatrix mat(N, 2); for (i=0; i<N; i++) { for (j=0; j<thin; j++) { x = gsl_ran_gamma(r,3.0,1.0/(y*y+4)); y = 1.0/(x+1)+gsl_ran_gaussian(r,1.0/sqrt(2*x+2)); } mat(i,0) = x; mat(i,1) = y; } gsl_rng_free(r); return mat; // Return to R ' ## Compile and Load GSLGibbs <- cxxfunction(signature(ns="int", thns = "int"), body=gslgibbscode, includes=gslgibbsincl, plugin="RcppGSL") This code is similar to the version using just Rcpp, but we need to allocate space for the GSL random generator object (and later release that memory allocation), and we do of course call the GSL functions. This also necessitates declaring the function using the two header files listed as arguments for the include argument of cxxfunction(). So how is the performance? The script (now committed in Rcpp‘s SVN repo as examples/RcppGibbs/RcppGibbs.R, and also part of the next release) creates the output below when running in non-interactive mode (whereas interactive mode creates a few charts too): edd@max:~/svn/rcpp/pkg/Rcpp/inst/examples/RcppGibbs$ r RcppGibbs.R Replication # 1 complete Replication # 2 complete Replication # 3 complete Replication # 4 complete N=1000 N=5000 N=10000 N=20000 Elasped Time (R) 0.124 2.650 10.511 41.773 Elasped Time (RC) 0.081 1.916 7.594 30.280 Elapsed Time (Rcpp) 0.003 0.076 0.306 1.221 Elapsed Time (Rgsl) 0.002 0.049 0.196 0.784 SpeedUp Rcomp. 1.530 1.380 1.380 1.380 SpeedUp Rcpp 41.330 34.870 34.350 34.210 SpeedUp GSL 62.000 54.080 53.630 53.280 test replications elapsed relative user.self sys.self 4 GSLGibbs(N, thn) 10 7.845 1.000000 7.84 0 3 RcppGibbs(N, thn) 10 12.218 1.557425 12.22 0 2 RCgibbs(N, thn) 10 312.296 39.808286 311.98 0 1 Rgibbs(N, thn) 10 420.953 53.658764 420.59 0 The first block is a hand-computed comparison using four sets of parameters; the second block uses the excellent rbenchmark package to compare ten runs at twenty-thousand draws. We see a nominal increase in performance due to the bytecode compiler, saving roughly 38 percent which seems appropriate given that the R code mostly controls the loops; actual work in undertaken in the already compiled RNG functions. The Rcpp variant is about 34 times faster than the pure R code. Sanjog reported higher increases on his OS X machines (and Darren’s post echos a similar order of magnitude). However, on my i7 running Linux I always obtained an improvement in the mid- to high thirties. That is certainly already a rather pleasant result. What surprised and stunned me at first was that the GSL solution scores an improvement of around 53 times (close to the factor of 60 reported by Darren). A closer look at the code (shown above) makes it clear that there are very few compute-intensive operations outside of the RNG draws. I validated this further with a second study timing just one million draws each from a Gaussian and Gamma using R via Rcpp, and using the GSL. It turns out that the R code is about 2.5 times slower for random draws from the Gamma distribution than the GSL. Inspection of the source code—in files src/nmath/rgamma.c for R and randist/gamma.c for the GSL shows why. R uses a much more complex (and presumably more precise) algorithm. I may follow up with Martin Maechler to see if we can illustrative the numerial benefits of this more expensive approach—this blog entry is getting long enough already. So to sum up: Gibbs sampling is a somewhat resource-heavy Monte Carlo Markov Chain method for investigating multivariate distributions. R excels at quick and simple explorations, albeit at somewhat slower execution speed. The Rcpp package can help by providing easy means to accelerate simulations by a significant factor. The example discussed here is now in SVN repository for Rcpp and will be part of the next...
http://www.r-bloggers.com/mcmc-and-faster-gibbs-sampling-using-rcpp/
CC-MAIN-2015-35
refinedweb
1,500
60.55
Docstring Guide¶ “Code is more often read than written.” —Guido van Rossum In Jina, we are aware that documentation is an important part of software,: Table of Contents you should document the constructor parameters here. Use all parameters that are under __init__ and document them in the class itself. Do not add any docstring to the __init__() :param param1: This is an example of a param1 :type param1: int :param param2: This is an example of a param2 :type param2: str """ def __init__(self, param1: int, param2: str): # don't add anything to the constructor Special Cases¶ Dunder/Magic methods¶ You don’t have to document dunder/magic methods unless you change the semantic of the method. Property¶ Sphinx ignores docstrings on property setters so all documentation for a property must be on the @property method. @property def name(self): """ The name of the document. :getter: Returns this document's name :setter: Sets this document's name :type: string """ return self._name Private methods¶ You can safely ignore docstring for private methods, such as methods started with _. args and kwargs¶ Each parameter in the signature must be documented, including *args and **kwargs, but not self or cls. Pre-commit hook¶ In Jina we use git’s pre-commit hooks in order to make sure code is properly documented to match our style and high quality. The hook will automatically remind you to add docstrings to new code, or fix any unfit docstrings. Follow the guide in [CONTRIBUTING.md]() to install it. Disabling specific cases¶ In some cases it is okay to disable linting. This is either due to our principles, or due to bugs or limitations in the linters. We do not need to document exceptions in the docstrings. Use # noqa: DAR401. We do not need to document the return value in a @propertymethod of a class. Use # noqa: DAR201 Note: Please add two blank lines and two dots as the example below to ignore # noqa in sphinx autodoc. def dump(self, data: Union['BaseFlow', 'BaseExecutor', 'BaseDriver']) -> Dict: """Return the dictionary given a versioned flow object .. # noqa: DAR401 :param data: versioned flow object """ raise NotImplementedError Docstring Coverage¶ We suggest leveraging interrogate to calculate the docstring coverage and find out missing docstrings. You can create a configure file pyproject.toml with the following configurations. [tool.interrogate] ignore-init-method = false ignore-init-module = false ignore-magic = true ignore-semiprivate = true ignore-private = true ignore-property-decorators = false ignore-module = true fail-under = 75 exclude = ["setup.py", "docs", "build"] ignore-regex = ["^get$", "^mock_.*", ".*BaseClass.*"] verbose = 0 quiet = false whitelist-regex = [] color = true And run this command in terminal to acquire the docstring coverage report. interrogate -c jina/pyproject.toml -vv jina
https://docs.jina.ai/master/chapters/docstring.html
CC-MAIN-2021-10
refinedweb
450
56.35
So far, we've concentrated on some key aspects of Web services and seen how they can be implemented on both the .NET and Java platforms. To conclude the chapter's technical discussion, this section will pull together all the topics covered so far and show an extended example that builds upon what you've learned. Figure 6.25 shows the two Web services that we've used throughout this chapter: the Buy Stocks Web service, based on the .NET platform, and the Sell Stocks Web service, based on the Java platform and using GLUE. These two services will play a key role in the chapter's final sample. To further illustrate interoperability between the .NET and Java platforms, we'll see a client that acts as a faade to these two Web services. This faade is based on ASP.NET and presents a Web-based UI representation of the two services. The ASP.NET interface will touch on a number of points that have been introduced in the past few sections, including calling services from both .NET and Java; maintaining data type fidelity between the two platforms; and handling exceptions, authentication, and UDDI. In addition, as we step through the solution, I'll point out additional best practices and patterns that apply. To install and run the solution, you'll need to have built the .NET and Java Web services in Chapter 5 and configured UDDI as described in the previous section. The sample solution is located in the C:\Interoperability\Samples\Point\WebServices\Solution directory. To install the sample, first compile the code, and then within IIS Manager, create a new virtual directory that points to this folder. To create this virtual directory, follow the same directions that you used to create the sample .NET Web service at the start of Chapter 5. For this to run correctly, the alias for the virtual directory needs to be WebServiceSample . After the virtual directory has been created, you need to set the IIS virtual directory security correctly in order to allow access to the UDDI registry. The UDDI registry that was configured in the previous section is, by default, set to allow Windows authentication. In order to pass the credentials to the UDDI registry, set the authentication mode for the WebServiceSample virtual directory to Integrated Authentication and remove Anonymous Access. You can set this by right-clicking the virtual directory, selecting Properties, and navigating to the Directory Security tab. This was covered earlier in this chapter in the "Web Services Authentication and Authorization" section. In addition, if you followed the samples in this section, you might want to check the security settings on the dotNETWebService virtual directory. Ensure that anonymous access is enabled. The solution is now correctly installed and configured. To ensure that the sample can be run, start the Java Sell Stocks Web service by entering start ant run at a command prompt in the C:\Interoperability\Samples\Point\WebService\Java\WebService directory (which was shown at the end of Chapter 5). After installing and configuring the solution, browse to . This will display the home page for the solution, which Figure 6.26 shows. The home page introduces the sample and presents two options to the user: Buy Stocks and Sell Stocks. In addition, the user is asked for the UDDI inquiry URL, which is prepopulated for a local instance of UDDI Services for Windows Server 2003. Modify the UDDI inquiry URL as required for your own environment (for example, set the server to something other than localhost), and click the Buy Stocks option. The page used to buy stocks will be displayed, as shown in Figure 6.27. Recall how in the chapter's earlier samples the Buy Stocks and Sell Stocks Web services contained two methods each ”one to get the list of recommendations, and the second to execute the actual order. In essence, ASP.NET is just a graphical representation of this. On the Buy Stocks page, click the Get Recommendations button. In order to make this call, the ASP.NET page first makes a request to the UDDI server. By default, the ASP.NET page knows nothing about the location of the Buy Stocks Web service and relies on the UDDI directory for access point information. If you have a debug tracer attached to the ASP.NET process, it's possible to view the progress of the UDDI call. Once the UDDI access point has been returned, ASP.NET UI then makes a call to the Buy Stocks Web service (which also is hosted via ASP.NET) and displays the list of recommendations as they're returned. Figure 6.28 illustrates this. Select one of the recommendations, enter a valid quantity, and click the Buy button. Again, this will make another call to UDDI and return the address for the Web service. Then the BuyStocks method will be invoked. If all is successful, the ASP.NET page will report that the order was placed, presenting a confirmation in the Stock Advisor window, as shown in Figure 6.29. To confirm this, recall how the .NET Web service shown earlier in this chapter writes all incoming orders to the Windows Event Log. If you check the application log, you should see an entry similar to the one shown in Figure 6.30. Now let's look at how the call to the corresponding Java Web service is invoked. From the Web page, click the Sell Stocks button. Again, click the Get Recommendations button. (See Figure 6.31.) This process uses the same code underneath but asks the UDDI server for the address of the Sell Stocks Web service, which will be resolved to our Java Web service. As before, select a stock (this time to sell) and enter a quantity. If successful, the screen should display a confirmation message, as shown in Figure 6.32. If you look at the Java Web service as it's running in the background, you should see this message in the console window: Incoming request to sell 50 common shares of Wingtip Toys (WING) Although this is a basic solution, it shows a clean example of how you can abstract two Web services ”one from .NET and the other from Java ”and present them through a unified interface. By using a common interface and Web services to achieve interoperability between the two platform, you have the potential to build a unified interface for any number of disparate services. One advantage of doing this is that the user doesn't know whether the underlying connection is a Web service hosted in .NET or one hosted in Java. This comes back to some of the fundamentals outlined earlier in the book: the goal of interoperability is to present a user experience that doesn't necessarily expose the underlying number of disparate systems. The project structure is relatively simple, and in looking through the code, you can see the approach that's been taken. The solution itself ”examined either from the command line or through Visual Studio .NET ”comprises a number of base pages: Default.aspx, BuyStocks.aspx, SellStocks.aspx, and Header.ascx. Header.ascx is an ASP.NET Web user control and is responsible for displaying a consistent banner at the top of each page you saw. In addition to these pages, there are five subfolders : Images Contains the JPEG image for the screen. Datatypes Contains the shared stock type by using exactly the same schema as defined in Chapter 3, "Exchanging Data Between .NET and Java," where we looked at XSD and data types. UDDI Contains a UDDILookup class that contains the commands for looking up an access point based on a service name . Proxies Contains the proxies to call the Web services themselves . Agents Acts as a layer between the pages and the proxies and is used to abstract the Web service proxy code away from the actual calling page, which we'll cover shortly. Now that we have an overview of the solution, let's look at what happens when a user launches the sample and makes a request to either buy or sell some stocks. Open the BuyStocks.aspx page. This page displays the controls required for buying a stock. Locate the BuyStockRecommendationsButton_Click method. This method is executed when the user clicks the Get Recommendations button. BuyStocksAgent agent = new BuyStocksAgent(((String)Session["InquiryURL"])); ArrayList recommendations = agent.GetRecommendations(); After the button is clicked, a new instance of the BuyStocksAgent is created, which is passed the InquiryURL , which is the UDDI URL that's configured in the header of the page and stored in the ASP.NET session state. As you can see, the agent exposes a method named GetRecommendations . Follow the code to the BuyStocksAgent.cs class. Here is the code that makes up the agent: dotNETStockService ss = new dotNETStockService(); ss.Url = _accessPointURL; return new ArrayList(ss.GetRecommendations()); You can see how a new instance of the .NET Web service is created. Just before it's invoked, the URL is set. (The access point URL is obtained via UDDI in the constructor of the agent.) The UDDILookup class that's used to do this is based on the same sample code shown earlier. The agent then calls the "real" GetRecommendations method from the Web service. Finally, let's take a look at the proxy files that are used to call the Web service. Both files (dotNETStockService.cs and JavaStockService.cs) have been generated by using the WSDL.EXE tool. After they were generated, we made some modifications manually to get them to work neatly in the solution. First, we added the WebServiceSample namespace to each file. (By default, WSDL.EXE doesn't add a namespace.) Second, we stripped out the definition for Stock from each file. This is really important. When WSDL.EXE was used to generate the proxy file, a stock type was also created (because it's exposed in the WSDL from the Web services). Unfortunately, as you create proxies for different platforms, you end up with multiple copies of the same type defined in the solution. To resolve this, you can rely on our standard definition for Stock (which is defined in portfolio.cs) and delete the definitions that are auto-generated by the tool. Because we're using a single version of the type definition, it's important to ensure that this type is attributed with a namespace that's shared by both Web services. Finally, the proxy that's generated for the Java Web service contains a type named ArrayList , which is created and exposed by GLUE. To avoid confusion between this ArrayList and the ArrayList in the System.Collections namespace, this was renamed to GlueArrayList throughout the proxy file. Hopefully, this extended sample pulls together some of the concepts we've addressed in the book so far. Feel free to step through this example in more detail to reaffirm some of the options and recommendations presented.
https://flylib.com/books/en/1.62.1.49/1/
CC-MAIN-2020-10
refinedweb
1,824
56.76
sigunblock() Unblock signals Synopsis: #include <unix.h> int sigunblock( int mask );() . In normal usage, a signal is blocked using sigblock() . To begin a critical section, variables modified on the occurrence of the signal are examined to determine that there is no work to be done, and the process pauses awaiting work by using sigpause() with the mask returned by sigblock(). It isn't possible to block SIGKILL, SIGSTOP, or SIGCONT; this restriction is silently imposed by the system. Returns: The previous set of masked signals. Classification: Caveats: Use of these interfaces should be restricted to only applications written on BSD platforms. Use of these interfaces with any of the system libraries or in multithreaded applications is unsupported.
https://developer.blackberry.com/playbook/native/reference/com.qnx.doc.neutrino.lib_ref/topic/s/sigunblock.html
CC-MAIN-2021-21
refinedweb
117
56.86
Created on 2017-05-29 04:04 by Nam.Nguyen, last changed 2017-07-26 02:48 by ned.deily. This issue is now closed. Reported by Orange Tsai: ========== Hi, Python Security Team import urllib from urlparse import urlparse url = '' print urlparse(url).netloc # 127.0.0.1 print urllib.urlopen(url).read() # will access evil.com I have tested on the latest version of Python 2.7.13. ========== See also Issue 18140, where it looks like people _want_ the hash (#) to be part of the username and/or password. Another option may be to raise an exception. I think the best behavior is to do what popular web browsers do. Chrome and Firefox, for example, parses this is host 127.0.0.1, path /, fragment #@evil.com. If the code does want to support username/password, it should do a custom opener (with basic HTTP authentication) instead. > I". When porting the change to Python 3.4, I found this older change: if _hostprog is None: - _hostprog = re.compile('^//([^/?]*)(.*)$') + _hostprog = re.compile('//([^/?]*)(.*)', re.DOTALL) match = _hostprog.match(url) if match: - host_port = match.group(1) - path = match.group(2) - if path and not path.startswith('/'): + host_port, path = match.groups() + if path and path[0] != '/': path = '/' + path return host_port, path made by: commit 44eceb6e2aca4e6d12ce64fa0f90279ffff19c25 Author: Serhiy Storchaka <storchaka@gmail.com> Date: Tue Mar 3 20:21:35 2015 +0200 Issue #23563: Optimized utility functions in urllib.parse. With this change, newlines are now accepted in URLs. @Serhiy: Was it a deliberate change? New changeset 4899d847ed3f56b2a712799f896aa1f28540a5c0 by Victor Stinner in branch '3.5': bpo-30500: urllib: Simplify splithost by calling into urlparse. (#1849) (#2290) New changeset 536c1f1246f4faa302f9f5613fc3444e7ae09b4a by Victor Stinner in branch '3.6': bpo-30500: urllib: Simplify splithost by calling into urlparse. (#1849) (#2289) New changeset 82acabd3c52508d9e3f83a41fe7c684619cbbe7b by Victor Stinner in branch '3.6': bpo-30500: Fix the NEWS entry (#2296) New changeset 410860662f53945cddf5886801c5a88a84801fec by Victor Stinner in branch '3.5': bpo-30500: Fix the NEWS entry (#2295) New changeset 8457706ee308a621103e9b9c760ca9da3cc4e7c0 by Victor Stinner in branch 'master': bpo-30500: Fix the NEWS entry (#2293) Oh, I didn't expected that newlines can be in a host name. In any case if newlines are a problem, it is better to check explicitly whether a host name contains CR, LF or other special characters. And it is better to do such checks when format a request rather than when parse an URL. New changeset d4324baca4c03eb8d55446cd1b74b32ec5633af5 by Victor Stinner in branch '2.7': bpo-30500: urllib: Simplify splithost by calling into urlparse. (#1849) (#2294) > New I tested my system python2 (Python 2.7.13 on Fedora 25): haypo@selma$ python2 Python 2.7.13 (default, May 10 2017, 20:04:28) >>> urllib.splithost('//hostname/url') ('hostname', '/url') >>> urllib.splithost('//host\nname/url') # newline in hostname, accepted ('host\nname', '/url') >>> print(urllib.splithost('//host\nname/url')[0]) # newline in hostname, accepted host name >>> urllib.splithost('//hostname/ur\nl') # newline in URL, rejected (None, '//hostname/ur\nl') => Newline is accepted in the hostname, but not in the URL path. With my change (adding DOTALL), newlines are accepted in the hostname and in the URL: haypo@selma$ ./python Python 2.7.13+ (heads/2.7:b39a748, Jun 19 2017, 18:07:19) >>> import urllib >>> urllib.splithost("//hostname/url") ('hostname', '/url') >>> urllib.splithost("//host\nname/url") # newline in hostname, accepted ('host\nname', '/url') >>> urllib.splithost("//hostname/ur\nl") # newline in URL, accepted ('hostname', '/ur\nl') More generally, it seems like the urllib module doesn't try to validate URL content. It just try to "split" them. Who is responsible to validate URLs? Is it the responsability of the application developer to implement a whitelist? The urllib package consists of two parts: urllib.parse and urllib.request. I think urllib.request is responsible for making valid requests and validate arguments if needed. Or more low-level modules used by urllib.request: http, ftplib, etc. I created bpo-30713: "Reject newline character (U+000A) in URLs in urllib.parse", to discuss how to handle newlines in URLs. New changeset b0fba8874a4bd6bf4773e6efdbd8fa762e9f05bd by Ned Deily (Victor Stinner) in branch '3.6': bpo-30500: urllib: Simplify splithost by calling into urlparse. (#1849) (#2289) New changeset cc54c1c0d2d05fe7404ba64c53df4b1352ed2262 by larryhastings (Victor Stinner) in branch '3.4': bpo-30500: urllib: Simplify splithost by calling into urlparse. (#1849) (#2291) New changeset 052f9d6860c48c5abcff8e16212e77cf4249d66c by Ned Deily (Victor Stinner) in branch '3.3': [3.3] bpo-30500: urllib: Simplify splithost by calling into urlparse. (#1849) (#2292)
https://bugs.python.org/issue30500
CC-MAIN-2018-47
refinedweb
736
70.5
Pete is a Developer Advocate!! New in Chrome 80 Chrome 80 is rolling out now, and there’s a ton of new stuff in it for developers! There’s support for modules in workers, optional chaining in JavaScript, new origin trials, features that have graduated from origin trial, and so much more. Let’s dive in and see what’s new for developers in Chrome 80!! New in Chrome 78 Chrome 78 is rolling out now! You can now provide “types” for CSS variables. You get fresher service workers because byte-for-byte checks are now performed for scripts imported by importScripts(). And I’ve got details for two new origin trials that provide some neat new functionality including the Native File System and the SMS Receiver. Plus the Chrome DevSummit is happening November 11-12, 2019. Let’s dive in and see what’s new for developers in Chrome 78! New in Chrome 77 Chrome 77 is rolling out now! There’s a better way to track the performance of your site with Largest Contentful Paint. Forms get some new capabilities. Native lazy loading is here. The Chrome DevSummit is happening November 11-12 2019. And plenty more. Let’s dive in and see what’s new for developers in Chrome 77!. 72 In Chrome 72, creating public class fields in JavaScript is now much cleaner, you can see if a page has been activated with the new User Activation API, localizing lists becomes way easier, and there’s plenty more. Let’s dive in and see what’s new for developers in Chrome 72!! Changes to Add to Home Screen Behavior Starting in Chrome 68 on Android, the Add to Home Screen behavior is changing to give you more control over when and how to prompt the user. If your site meets the add to home screen criteria, Chrome will no longer automatically show the add to home screen banner. Instead, you'll need to call prompt() on the saved beforeinstallprompt event to show the add to home screen dialog prompt to your users! WebAPKs on Android When the user adds your Progressive Web App to their home screen on Android, Chrome automatically generates an APK for you, which we sometimes call a WebAPK. Being installed via an APK makes it possible for your app to show up in the app launcher, in Android's app settings and to register a set of intent filters.. Updates to developers.google.com/web We recently made some big changes to WebFundamentals, improving navigation, adding lots of new content, and making it easier for you to contribute. Widgets Widgets you can use to simplify your writing and development Writing an Update or Case Study This is the page description placed in the head. Writing an Article This is the page description placed in the head. Markdown syntax This is the page description placed in the head. Video: Web Push Notifications (I/O 2016) Support for theme-color in Chrome 39 for Android Use theme-color to set the toolbar color in Chrome for Android. Click to Call On devices with phone capabilities, make it easy for users to directly connect with you by simply tapping a phone number, more commonly known as click to call. Device Orientation & Motion Device motion and orientation events provide access to the built-in accelerometer, gyroscope, and compass in mobile devices. Create Amazing Forms Forms are hard to fill out on mobile. The best forms are the ones with the fewest inputs. Images A picture is worth 1000 words, and images play an integral part of every page. But they also often account for most of the downloaded bytes. With responsive web design not only can our layouts change based on device characteristics, but images as well. Responsive Web Design Patterns Responsive web design patterns are quickly evolving, but there are a handful of established patterns that work well across the desktop and mobile devices
https://developers.google.com/web/resources/contributors/petelepage?hl=id
CC-MAIN-2020-50
refinedweb
659
62.98
observables containing individual values from the first observable. Then you do stuff on the new observables and finally, the flatmap merges these single observables into one complete observable. The new observable is now transformed. FlatMap flattens an observable into single observables which are modified and merged into a new observable. The new observable that comes out of the flatMap doesn’t guarantee you the same order. The values are interleaved. A FlatMap emits Observables instead of values An illustration for the RxJava documentation is given below. What exactly does a FlatMap do? A FlatMap divides an Observable into many singular Observables. Hence, instead of sending each of the Observable values one by one, a FlatMap does everything in parallel and then merges the results in whatever order they are completed. Let’s look at an example of FlatMap by creating a new IntelliJ java project and adding the RxJava dependency in the build.gradle. Copyimport rx.Observable; import rx.functions.Func1; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import java.util.concurrent.TimeUnit; public class RxOperatorMaps { public static void main(String[] args) throws InterruptedException { final List<String> race = new ArrayList<>(Arrays.asList("Alan", "Bob", "Cobb", "Dan", "Evan", "Finch")); Observable.from(race) .flatMap(new Func1<String, Observable<?>>() { @Override public Observable<?> call(String s) { final int delay = new Random().nextInt(5); return Observable.just(s).map(String::toUpperCase) .delay(delay, TimeUnit.SECONDS); } }) .subscribe(System.out::println); Thread.sleep(5000); } } //Prints //BOB //FINCH //ALAN //EVAN //COBB //DAN - The flatMapapplies a function to each observable emitted. The function type is a unit of the source observable type(String in this case) and a new Observable with the type you transform it into. - In the above code, a String observable is emitted from the source which was a List of Strings observable. - The new observables are delayed here to show you that a flatMapmerges the single observables in the order in which they complete. - We’ve used a delay operator which delays the emission by a random number of seconds. - We’ve set the main thread to sleep for 5 seconds to prevent the main function from returning while the Observables are still doing their work. Note: A flatMap implicitly contains the merge operator too. Difference between a map and a flatMap operator Map returns an object of type T whereas a FlatMap returns an Observable<T>. Using an observable operator we can also filter down the number of values we want to reach the observer. CopyObservable.from(race) .flatMap(s -> { final int delay = new Random().nextInt(5); if (s.contains("a")) return Observable.empty() .delay(delay, TimeUnit.SECONDS); else return Observable.just(s).map(String::toUpperCase) .delay(delay, TimeUnit.SECONDS); }) .subscribe(System.out::println); Thread.sleep(5000); //Prints //FINCH //COBB //BOB flatMap would be useful in android when you need to perform multiple network requests in parallel. RxJava SwitchMap A SwitchMap flattens the source observable but only returns the last emitted single observable. The below illustration followed by example demonstrates what the above line means. CopyObservable.from(race) .switchMap((Func1<String, Observable<?>>) s -> { final int delay = new Random().nextInt(2); return Observable.just(s).map(String::toUpperCase) .delay(delay, TimeUnit.SECONDS); }) .subscribe(System.out::println); Thread.sleep(5000); //Prints for me. It can differ for you since it's random. //ALAN //EVAN //FINCH SwitchMap would emit only the latest observable after a particular delay. It ignores all the previous ones. It is useful when it comes to retrieving the latest data from a feed. It’s useful when you need to identify the latest among many feeds. RxJava concatMap If you’ve read flatMap you almost know what a concatMap operator is. It is similar to a flatMap except that it keeps the order of the observables. To keep the order, it needs to wait for one observable to finish before proceeding to the next, thereby breaking away from the asynchronous concept and making the task longer than usual. Another difference between flatMap and concatMap operators The flatMap uses merge operator implicitly whereas concatMap uses concat operator. CopyObservable.from(race) .concatMap((Func1<String, Observable<?>>) s -> { final int delay = new Random().nextInt(4); return Observable.just(s).map(String::toUpperCase) .delay(delay, TimeUnit.SECONDS); }) .subscribe(System.out::println); Thread.sleep(5000); //Prints //ALAN //BOB //COBB Why did it not print all the values? Well it took so long that the main thread woke up and exited the main method. You can increase the thread sleep time or decrease the delay random number to view all. But you get the concept right? ConcatMap takes longer. Use it only if you need the same sequence. Reference: RxJava docs aaaaaaaa bbbbbbbb says Map returns an object of type T whereas a FlatMap returns an Observable ?
https://www.journaldev.com/19300/rxjava-flatmap-switchmap-concatmap
CC-MAIN-2019-13
refinedweb
796
51.34
Okay, so normally I do frequentist statistics. Most of my training has been in that realm. However, I do recognize that bayesian is really the way to go. The idea of updating a prior is really appealing to me. The only problem that I have ever had with it, is that I really haven’t had a good way to do bayesian statistics until I got into doing most of my work in python. There is a really cool library called pymc3. So I want to go over how to do a linear regression within a bayesian framework using pymc3. Making inferences based off of what we learned from the data. And other non-sense related to probablistic programming. So here’s what we are going to cover: - The basic math of baesian inference - Setting up a linear regression within a bayesian framework - Writing the code in python - spitting out answers Obligatory “What is Bayes Rule? And Why do We Care?” Section Okay, so Baye’s rule is basically a way of encoding our prior beliefs about how the world works onto the world that we observe. That’s probably a terrible definition, but it is the one rattling around in my brain that doesn’t involve any math. Essentially, we get to combine what we already know with evidence out in the world to tell us about the state of the world. Here’s an example. Let’s say that there is this rare disease out there, that randomly gets contracted by 1 in 10,000 people. In other words, you have a 0.01% chance of getting this disease. Not too shaby. And lucky enough there is an inexpensive test that correctly identifies people with this disease 99% of the time, and if you don’t have the disease it also correctly says that you do not have the disease 99% of the time. You take the test and it comes back positive. How worried should you be? Well, let’s think about this logically for a moment. We know that only 1 in 10,000 people get this disease. So let’s say there are 10,000 people. 9,999 of them do not have the disease but 1% of these people will get a positive result. So about 101 people get a positive result, even though only 1 of them actually has the disease. That means that even with a positive result, you only have 1 in 101 chance of actually having the disease (or roughly a 1% chance). Baye’s rule is the formal mathematical description of this idea. And here it is in its full glory: It looks so simple. And in fact, it is simple. The formula only requires knowledge of a few probability distributions. But in practice the denominator on the right hand side usually means that we are going to be computing a lot of really computationally heavy integrals. For this reason, bayesian statistics was abandoned for many years. In some sense it flows more naturally out of probability theory. If we only had things that were good at computing lots and lots of numbers to make this type of problem tractable. Enter modern computers. Computers are really fast at making computations. In fact, my crappy old laptop that I am writing this post on, can do some decent bayesian statistics, like the bayesian regression that we are about to do. So let’s break down this formula. P(Y|X): We typically think of this as our likelihood function of our data Y given parameters X. P(X) is our prior beliefs about parameter X. Finally, P(Y) is the probability of our data. This is typically computed using some crazy calculus on things without closed form solutions. Which is the whole “boo!” moment that we will use pymc3 to solve. Okay enough theory show me some code! No code, not yet! Here’s what we need to know to do Bayesian Regression. Normally, we think of a regression like this: And e is the error that is normally distributed. If you stop and think about it, this doesn’t make a lot of sense. You have a random variable that you are treating as if it is composed of a deterministic thing, and a random thing and smashing them together, so that Y looks random, but really is mostly not random. And then if e doesn’t follow all of your rules, it completely invalidates your results. Check out these posts for examples of how having an e that isn’t normally distributed can ruin your day in a time series setting. Wouldn’t it be nice if we could just assume that Y is indeed a random variable 100% and not bother with this decomposition stuff. Well, if you do you will firmly live in bayesian land. So we assume that: With priors: And so if we have data for X and Y we have everything that we need to do a bayesian linear regression. This will allow you to get full posterior distributions for your parameters in b. I think that’s pretty cool, because not only have you eliminated a lot of your problems by assuming that Y is a fully random variable, you can say how confident you are that a coefficient is positive. So let’s grab some data and start coding. Finally, I get to see some code! Believe it or not the information that I provided in the last section is everything that we need to code a linear regression in pymc3. We just need to grab some data to make it work. So the dataset that we are going to use is the American Housing Survey: Housing Affordability Data System dataset from 2013. Go ahead and download this data, and then unzip it and save it on your computer. We’ll be looking at this dataset for the remainder of this blog post. What we’re interested in is how housing burden changes with age. AGE1 contains the age of the head of household. And BURDEN is a variable that tells us how big are housing expenses relative to income. For simplicity, we’ll just focus on these two variables. What we want to know is, does the burden of housing get easier as we age? In particular we want to know whether the slope coefficient is negative, and since we’re in a bayesian framework, what is the probability that it is negative? So let’s start off with some prerequisites, we’ll import the libraries that we need and the data. We’ll also do some minor data cleaning because the documentation says that missing values are coded with a negative number, we’re going to drop them. import pandas as pd import pymc3 import matplotlib.pyplot as plt df=pd.read_csv('/home/ryan/Documents/thads2013n.txt',sep=',') df=df[df['BURDEN']>0] df=df[df['AGE1']>0] Alright so that was pretty simple. Now let’s build the model that we discussed above. It isn’t much to look at, so let’s do a scatter plot and see what the data looks like. plt.scatter(df['AGE1'],df['BURDEN']) plt.show() And here is the result: It looks like the data has some ouliers where the housing burden is astronomically high, easily over 10 times income. For now, we won’t worry too much about that. Here is the code to build and run our model:() It looks exactly like our model above, except that we have an extra beta for the intercept that is normally distributed as well. The last line is what actually runs the model for us. Now that our model is trained we can go on to doing some inferential work. Go ahead and do something else while this is running. On an older laptop, like mine, this can take a fair amount of time. Typically, you will want to do these calculations in the cloud on a GPU, but we’ll just let it run. It took 47 minutes to run on my laptop, did I mention that it is ancient. After it finishes running you should see something like this: What the trace variable contains is the posterior distribution for our parameter values. You can see that we have our slope and intercept posterior distribution plus the standard deviation for the regression. But like I was wondering at the beginning, does housing burden decrease with age? My thought was that perhaps it did. As people get more established, their housing costs would go down relative to income. This would amount to a negative slope coefficient on the age variable. From the figure above, I can see that the posterior distribution for the slope parameter, and it isn’t looking so great for my hypothesis that it should be negative, it looks like it peaks around 0.025. In fact, if I run the following code, I can find out what the exact probability that the slope coefficient is negative. print(np.mean([1 if obj<0 else 0 for obj in trace['x']])) When I ran it, I got about a 13.8% probability that the coefficient is negative. I don't think that is good enough evidence for me. Alas, it looks like I was wrong. Your run should produce a similar result, but because of the simulation for the integral results may vary (but not by much). And there it is, bayesian linear regression in pymc3. It wasn't so bad. In fact, pymc3 made it downright easy. That's why python is so great for data analysis. Let me know what you think about bayesian regression in the comments below! As always, here is the full code for everything that we did: import pandas as pd import pymc3 as pm import matplotlib.pyplot as plt import numpy as np df=pd.read_csv('/home/ryan/Documents/thads2013n.txt',sep=',') df=df[df['BURDEN']>0] df=df[df['AGE1']>0] plt.scatter(df['AGE1'],df['BURDEN']) plt.show()() print(np.mean([1 if obj<0 else 0 for obj in trace['x']]))
https://barnesanalytics.com/bayesian-regression-with-pymc3-in-python
CC-MAIN-2018-13
refinedweb
1,692
73.78
Recently I had the experience of reviewing a project and assessing its scalability and maintainability. There were a few bad practices here and there, a few strange pieces of code with lack of meaningful comments. Nothing uncommon for a relatively big (legacy) codebase, right? However, there is something that I keep finding. A pattern that repeated itself throughout this codebase and a number of other projects I’ve looked through. They could be all summarized by lack of abstraction. Ultimately, this was the cause for maintenance difficulty.. Often I’ve seen colleagues that want to take a step further towards more maintainable code, but they struggle to figure out and implement fundamental abstractions. Therefore, in this article, I’ll share a few useful abstractions I use for the most common thing in the web world: working with remote data. It’s important to mention that, just like everything in the JavaScript world, there are tons of ways and different approaches how to implement a similar concept. I’ll share my approach, but feel free to upgrade it or to tweak it based on your own needs. Or even better – improve it and share it in the comments below! ❤️ API AbstractionAPI Abstraction I haven’t had a project which doesn’t use an external API to receive and send data in a while. That’s usually one of the first and fundamental abstractions I define. I try to store as much API related configuration and settings there like: - the API base url - the request headers: - the global error handling logic const API = { /** * Simple service for generating different HTTP codes. Useful for * testing how your own scripts deal with varying responses. */ url: '', /** * fetch() will only reject a promise if the user is offline, * or some unlikely networking error occurs, such a DNS lookup failure. * However, there is a simple `ok` flag that indicates * whether an HTTP response's status code is in the successful range. */ _handleError(_res) { return _res.ok ? _res : Promise.reject(_res.statusText); }, /** * Get abstraction. * @return {Promise} */ get(_endpoint) { return window.fetch(this.url + _endpoint, { method: 'GET', headers: new Headers({ 'Accept': 'application/json' }) }) .then(this._handleError) .catch( error => { throw new Error(error) }); }, /** * Post abstraction. * @return {Promise} */ post(_endpoint, _body) { return window.fetch(this.url + _endpoint, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: _body, }) .then(this._handleError) .catch( error => { throw new Error(error) }); } }; In this module, we have 2 public methods, get() and post() which both return a Promise. On all places where we need to work with remote data, instead of directly calling the Fetch API via window.fetch(), we use our API module abstraction – API.get() or API.post(). Therefore, the Fetch API is not tightly coupled with our code. Let’s say down the road we read Zell Liew’s comprehensive summary of using Fetch and we realize that our error handling is not really advanced, like it could be. We want to check the content type before we process with our logic any further. No problem. We modify only our API module, the public methods API.get() and API.post() we use everywhere else works just fine. const API = { /* ... */ /** * Check whether the content type is correct before you process it further. */ _handleContentType(_response) { const contentType = _response.headers.get('content-type'); if (contentType && contentType.includes('application/json')) { return _response.json(); } return Promise.reject('Oops, we haven\'t got JSON!'); }, get(_endpoint) { return window.fetch(this.url + _endpoint, { method: 'GET', headers: new Headers({ 'Accept': 'application/json' }) }) .then(this._handleError) .then(this._handleContentType) .catch( error => { throw new Error(error) }) }, post(_endpoint, _body) { return window.fetch(this.url + _endpoint, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: _body }) .then(this._handleError) .then(this._handleContentType) .catch( error => { throw new Error(error) }) } }; Let’s say we decide to switch to zlFetch, the library which Zell introduces that abstracts away the handling of the response (so you can skip ahead to and handle both your data and errors without worrying about the response). As long as our public methods return a Promise, no problem: import zlFetch from 'zl-fetch'; const API = { /* ... */ /** * Get abstraction. * @return {Promise} */ get(_endpoint) { return zlFetch(this.url + _endpoint, { method: 'GET' }) .catch( error => { throw new Error(error) }) }, /** * Post abstraction. * @return {Promise} */ post(_endpoint, _body) { return zlFetch(this.url + _endpoint, { method: 'post', body: _body }) .catch( error => { throw new Error(error) }); } }; Let’s say down the road due to whatever reason we decide to switch to jQuery Ajax for working with remote data. Not a huge deal once again, as long as our public methods return a Promise. The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise. const API = { /* ... */ /** * Get abstraction. * @return {Promise} */ get(_endpoint) { return $.ajax({ method: 'GET', url: this.url + _endpoint }); }, /** * Post abstraction. * @return {Promise} */ post(_endpoint, _body) { return $.ajax({ method: 'POST', url: this.url + _endpoint, data: _body }); } }; But even if jQuery’s $.ajax() didn’t return a Promise, you can always wrap anything in a new Promise(). All good. Maintainability++! Now let’s abstract away the receiving and storing of the data locally. Data RepositoryData Repository Let’s assume we need to take the current weather. API returns us the temperature, feels-like, wind speed (m/s), pressure (hPa) and humidity (%). A common pattern, in order for the JSON response to be as slim as possible, attributes are compressed up to the first letter. So here’s what we receive from the server: { "t": 30, "f": 32, "w": 6.7, "p": 1012, "h": 38 } We could go ahead and use API.get('weather').t and API.get('weather').w wherever we need it, but that doesn’t look semantically awesome. I’m not a fan of the one-letter-not-much-context naming. Additionally, let’s say we don’t use the humidity ( h) and the feels like temperature ( f) anywhere. We don’t need them. Actually, the server might return us a lot of other information, but we might want to use only a couple of parameters. Not restricting what our weather module actually needs (stores) could grow to a big overhead. Enter repository-ish pattern abstraction! import API from './api.js'; // Import it into your code however you like const WeatherRepository = { _normalizeData(currentWeather) { // Take only what our app needs and nothing more. const { t, w, p } = currentWeather; return { temperature: t, windspeed: w, pressure: p }; }, /** * Get current weather. * @return {Promise} */ get(){ return API.get('/weather') .then(this._normalizeData); } } Now throughout our codebase use WeatherRepository.get() and access meaningful attributes like .temperature and .windspeed. Better! Additionally, via the _normalizeData() we expose only parameters we need. There is one more big benefit. Imagine we need to wire-up our app with another weather API. Surprise, surprise, this one’s response attributes names are different: { "temp": 30, "feels": 32, "wind": 6.7, "press": 1012, "hum": 38 } No worries! Having our WeatherRepository abstraction all we need to tweak is the _normalizeData() method! Not a single other module (or file). const WeatherRepository = { _normalizeData(currentWeather) { // Take only what our app needs and nothing more. const { temp, wind, press } = currentWeather; return { temperature: temp, windspeed: wind, pressure: press }; }, /* ... */ }; The attribute names of the API response object are not tightly coupled with our codebase. Maintainability++! Down the road, say we want to display the cached weather info if the currently fetched data is not older than 15 minutes. So, we choose to use localStorage to store the weather info, instead of doing an actual network request and calling the API each time WeatherRepository.get() is referenced. As long as WeatherRepository.get() returns a Promise, we don’t need to change the implementation in any other module. All other modules which want to access the current weather don’t (and shouldn’t) care how the data is retrieved – if it comes from the local storage, from an API request, via Fetch API or via jQuery’s $.ajax(). That’s irrelevant. They only care to receive it in the “agreed” format they implemented – a Promise which wraps the actual weather data. So, we introduce two “private” methods _isDataUpToDate() – to check if our data is older than 15 minutes or not and _storeData() to simply store out data in the browser storage. const WeatherRepository = { /* ... */ /** * Checks weather the data is up to date or not. * @return {Boolean} */ _isDataUpToDate(_localStore) { const isDataMissing = _localStore === null || Object.keys(_localStore.data).length === 0; if (isDataMissing) { return false; } const { lastFetched } = _localStore; const outOfDateAfter = 15 * 1000; // 15 minutes const isDataUpToDate = (new Date().valueOf() - lastFetched) < outOfDateAfter; return isDataUpToDate; }, _storeData(_weather) { window.localStorage.setItem('weather', JSON.stringify({ lastFetched: new Date().valueOf(), data: _weather })); }, /** * Get current weather. * @return {Promise} */ get(){ const localData = JSON.parse( window.localStorage.getItem('weather') ); if (this._isDataUpToDate(localData)) { return new Promise(_resolve => _resolve(localData)); } return API.get('/weather') .then(this._normalizeData) .then(this._storeData); } }; Finally, we tweak the get() method: in case the weather data is up to date, we wrap it in a Promise and we return it. Otherwise – we issue an API call. Awesome! There could be other use-cases, but I hope you got the idea. If a change requires you to tweak only one module – that’s excellent! You designed the implementation in a maintainable way! If you decide to use this repository-ish pattern, you might notice that it leads to some code and logic duplication, because all data repositories (entities) you define in your project will probably have methods like _isDataUpToDate(), _normalizeData(), _storeData() and so on… Since I use it heavily in my projects, I decided to create a library around this pattern that does exactly what I described in this article, and more! Introducing SuperRepoIntroducing SuperRepo SuperRepo is a library that helps you implement best practices for working with and storing data on the client-side. /** * 1. Define where you want to store the data, * in this example, in the LocalStorage. * * 2. Then - define a name of your data repository, * it's used for the LocalStorage key. * * 3. Define when the data will get out of date. * * 4. Finally, define your data model, set custom attribute name * for each response item, like we did above with `_normalizeData()`. * In the example, server returns the params 't', 'w', 'p', * we map them to 'temperature', 'windspeed', and 'pressure' instead. */ const WeatherRepository = new SuperRepo({ storage: 'LOCAL_STORAGE', // [1] name: 'weather', // [2] outOfDateAfter: 5 * 60 * 1000, // 5 min // [3] request: () => API.get('weather'), // Function that returns a Promise dataModel: { // [4] temperature: 't', windspeed: 'w', pressure: 'p' } }); /** * From here on, you can use the `.getData()` method to access your data. * It will first check if out data outdated (based on the `outOfDateAfter`). * If so - it will do a server request to get fresh data, * otherwise - it will get it from the cache (Local Storage). */ WeatherRepository.getData().then( data => { // Do something awesome. console.log(`It is ${data.temperature} degrees`); }); The library does the same things we implemented before: - Gets data from the server (if it’s missing or out of date on our side) or otherwise – gets it from the cache. - Just like we did with _normalizeData(), the dataModeloption applies a mapping to our rough data. This means: - Throughout our codebase, we will access meaningful and semantic attributes like .temperatureand .windspeedinstead of .tand .s. - Expose only parameters you need and simply don’t include any others. - If the response attributes names change (or you need to wire-up another API with different response structure), you only need to tweak here – in only 1 place of your codebase. Plus, a few additional improvements: - Performance: if WeatherRepository.getData()is called multiple times from different parts of our app, only 1 server request is triggered. - Scalability: - You can store the data in the localStorage, in the browser storage (if you’re building a browser extension), or in a local variable (if you don’t want to store data across browser sessions). See the options for the storagesetting. - You can initiate an automatic data sync with WeatherRepository.initSyncer(). This will initiate a setInterval, which will countdown to the point when the data is out of date (based on the outOfDateAftervalue) and will trigger a server request to get fresh data. Sweet. To use SuperRepo, install (or simply download) it with NPM or Bower: npm install --save super-repo Then, import it into your code via one of the 3 methods available: - Static HTML: <script src="/node_modules/super-repo/src/index.js"></script> - Using ES6 Imports: // If transpiler is configured (Traceur Compiler, Babel, Rollup, Webpack) import SuperRepo from 'super-repo'; - … or using CommonJS Imports // If module loader is configured (RequireJS, Browserify, Neuter) const SuperRepo = require('super-repo'); And finally, define your SuperRepositories :) For advanced usage, read the documentation I wrote. Examples included! SummarySummary The abstractions I described above could be one fundamental part of the architecture and software design of your app. As your experience grows, try to think about and apply similar concepts not only when working with remote data, but in other cases where they make sense, too. When implementing a feature, always try to discuss change resilience, maintainability, and scalability with your team. Future you will thank you for that! Don’t you have angular for that? No. At least not built-in. Of course, regardless of the framework you use, you can achieve something similar if you organize your code in such manner. I don’t usually post like this, but it is a pet peeve… There are 4 foundations to OOP: encapsulation, abstraction, inheritance, and polymorphism. Polymorphism is the ability to declare an object as something else and use it as that thing. A lot of people use inheritance for this even though it’s a different concept – not even a very good one since it includes polymorphism in its definition. Yes, you’re right! I made an edit and added polymorphism. Thanks! Excellent article. I have some concerns about browser support – eg: fetch for IE? Thanks, Pedro! The purpose of using fetch in my code examples was just to illustrate a use-case how the API abstraction handles a switch to a different mechanism for working with remote data. Choosing the underlying mechanism is another topic. If you want to use fetch, but need to support IE, take a look at the Fetch Polyfill, a project that implements a subset of the standard Fetch specification, enough to make fetch a viable replacement for most uses of XMLHttpRequest in traditional web applications. They provide support all the way back to IE 10+, so you should be safe.
https://css-tricks.com/importance-javascript-abstractions-working-remote-data/
CC-MAIN-2021-10
refinedweb
2,407
57.47
Introduction: Arduino Control/Integrate Aftermarket Accessories Via the CAN-BUS If you wanted to control aftermarket accessories using the existing controls in your vehicle you would have to connect a relay to end where an existing factory accessory is connected to. For an example: You have a 4x4 and want to add aftermarket spot lights, So you need to then connect a relay to an existing light, which will click the relay and let more power through to the aftermarket lights. This means you have to splice and cut into the existing factory wiring of your vehicle. With this instructable you can tap into the can bus (in my case the can bus wires at the back of the radio) The radio has a can-bus because its controllable via other accessories such as the steering wheel buttons, so instead of cutting into it you can buy a female-to-make connector and then tap into the connector. You need the following. Arduino UNO. SeeedStudio CAN-BUS Shield. Arduino IDE with the SeeedStudio CAN-BUS Library. Relay Shield, can be a single channel, but I used an 8 channel relay board. The Arduino Code (At the end of this instructable) Step 1: Another Example of Its Use. See the picture. Some vehicles knows how much power the factory bulbs in the Blinkers,Brakes and headlights are supposed to consume, anything under and over it will shutdown the circuit. So If you wanted to add a trailer , you also need to by the wiring harness which basically does exactly this, and they are very pricey! Step 2: See This Instructable in Action Ive created an example prototype on youtube of this. It monitors the CAN-BUS for the message that turns on the lights, and then DigitalWrite to the pin of your choice. The Arduino's IO pin is connected to an 8Channel Relay board which can be used to turn on accessories. In the video i'm controlling the relay by turning on the main beams. Enjoy! Happy CAN-BUS Hacking! More Information about this project can be viewed in this forum thread on techtinker.co.za... The Arduino Code. #include <br>#include "mcp_can.h" INT32U canId = 0x000; unsigned char len = 0; unsigned char buf[8]; char str[20]; String CanMessage=""; int HeadLightsDetected=0; int RelayCHN01=7; void setup() { //INIT RELAY PIN pinMode(RelayCHN01, OUTPUT); //TEST RELAY PIN TESTRElay();, buf); CanMessage=""; canId = CAN.getCanId(); //Detect Main Beam HeadLisghts if (canId==680) { //Build Complete Message Without CAN ID From BUS for(int i = 0; i void TESTRElay() { digitalWrite(RelayCHN01, HIGH); delay(200); digitalWrite(RelayCHN01, LOW); delay(200); digitalWrite(RelayCHN01, HIGH); delay(200); digitalWrite(RelayCHN01, LOW); delay(200); digitalWrite(RelayCHN01, HIGH); delay(200); digitalWrite(RelayCHN01, LOW); delay(200); digitalWrite(RelayCHN01, HIGH); delay(200); digitalWrite(RelayCHN01, LOW); delay(200); } 7 Discussions Very good approach and I believe just the right tool in gaining access to the instrument gauge cluster of a 2009 Mazda Miata. Upon changing the OEM engine control unit (ECU) to a DTA-Fast fully programmable ECU and followed the manufacturers installation and wiring instructions the miata strarted on it's default program set by the manufacturerthe gauges though didn't. I believe this may help me in gaining access to the gauges. Any suggestions would be much appreciated. Thanks so much! I forgot to mention that the twin relays are necessary as the Bosch DC motors are run with a single pair from a twin relay that switches polarity. Hello and thanks for the posting. Can I input the switches from the seat control directly into the UNO board? I want to run my Audi A8 drivers seat here at home, sitting in front of my computer, with a 220 to 12 volt power supply, needing exactly 8 output switches to run the Bosch dc motors inside the seat. I can explain more if you are interested in my problem. Thanks. I am a retired US veteran in Estonia, I need a better seat, furniture makers suck big time. The auto industry has done more ergo-metric engineering in their great car seats. Hi There. (BTW I updated the video link is should now work) Umm I dont know if this project will help you., could you not just control each motor separately by feeding them 12v using a simple switch for each motor ? Yes that would work, but it would be cool to use the switches in the side of the seat, instead of building a panel with ten switches in it. Each switch has a single wire output that ohms out at 400 in one direction and 800 in the other. While I would not need all the memory, and such that comes with the controller/memory board in the chair, I need to interpret the switch output and feed it into the h bridge twin relay to run the motors. There are eight motors in the seat. Very good, thanks for sharing. I did find a small typo at the beginning "buy a female-to-make connector"
https://www.instructables.com/id/Arduino-ControlIntegrate-Aftermarket-Accessories-v/
CC-MAIN-2018-39
refinedweb
840
60.35
So I have this code that I wrote and for now it only works with two dice. I am currently trying to get it to recognize more than two dice or possibly one die but for now I keep getting exceptions in the program. I know why but I'm not sure how to fix it. The only things I can say for sure if that I need to make my array size up properly with the number of dice I'm throwing like and also fits the results of the dice thrown since it needs to keep track of how many times a certain number came out depending on how many dice were thrown, how many sides they had, and how many times they were thrown. Can anyone please help me with this? Thank you. /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package dice.roller; /** * * @author Marlin */ import java.util.*; public class DiceRoller { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); String name; int roll, sides, dice, add = 0, tmp = 0; int[] result; //temp result = new int[11]; System.out.println("Hello, what is your name?"); name = keyboard.next(); System.out.println("Hello, " + name + ", how are you today?"); System.out.println("How many times would you like to roll the dice?"); roll = keyboard.nextInt(); while (tmp < 11) { result[tmp] = 0; tmp++; } System.out.println("You want to roll the dice " + roll + " times."); System.out.println("How many dice would you like to roll?"); dice = keyboard.nextInt(); System.out.println("You would like to throw " + dice + " dice."); for (int i = 0; i < roll; i++) { add = 0; for (int x = 0; x < dice; x++) { int die1 = (int) (Math.random() * 6) + 1; // int die2 = (int)(Math.random()*6) + 1; // add = die1 + die2; add += die1; } //System.out.println(add); ++result[add - 2]; } tmp = 0; while (tmp < 11) { int counter = tmp + 2; System.out.println("The result " + counter + " came out " + result[tmp] + " times"); tmp++; } } }
http://www.javaprogrammingforums.com/loops-control-statements/23000-how-can-i-get-my-dice-roller-completely-loop-sort-results-correctly.html
CC-MAIN-2014-10
refinedweb
337
74.19
how swap two strings without using 3rd variable? could it be done using constructors? if yes how? Printable View how swap two strings without using 3rd variable? could it be done using constructors? if yes how? If you are dealing with C-style null terminated strings, and have a pointer to the first character of each string, then you could just swap the pointers. If you are dealing with std::string objects, then just use std::swap as the underlying swap is likely to swap pointers rather than perform a full copy with a third string. string for example : "qwerty" Run that example. Is this what you're asking?Run that example. Is this what you're asking?Code: #include <string> #include <iostream> using namespace std; int main() { string s1 = "abc"; string s2 = "123"; cout << s1 << " " << s2 << "\n"; swap(s1, s2); cout << s1 << " " << s2 << "\n"; } Regards, Paul McKenzie as a general rule... NO. Swapping in C/C++ always requires a temporary. std::swap() just works around the issue, it still uses a temporary, you just didn't define it yourself. You might be able to pull some "weird" binary or mathematical trick to swap SOME types of variables, but chances are this'll be less efficient in the end than using a temporary for the swap. That's why I was asking what type of string. You could possibly do it with some combination of concatenating, copying and shifting. The only situation where it is possible to swap standard null terminated strings without using a 3rd variable is when they are exactly the same size (or the memory allocated for the smaller string is at least that of the larger string). See example below. This also assumes that the max ASCII value of any individual char in the string is 127 otherwise *p1 += *p2 will overflow the bounds of a char. Code: #include <iostream> using namespace std; int main () { char s1[10] = "abcdef"; char s2[10] = "ghijkl"; cout << "before swap" << endl << s1 << endl << s2 << endl; for (char *p1 = s1, *p2 = s2; *p1; p1++, p2++) { *p1 += *p2; *p2 = *p1 - *p2; *p1 -= *p2; } cout << endl << "after swap" << endl << s1 << endl << s2 << endl; return (0); } Perhaps it doesn't even need to be as nifty as 2kaud's proposal, in case that no temporary string variable (of whatever concrete type) is allowed, while a temporary char variable is...
http://forums.codeguru.com/printthread.php?t=532619&pp=15&page=1
CC-MAIN-2017-04
refinedweb
395
70.94
#include <check_group_count.h> The colon_passwd_functor_check_group_count class is used to represent the processing required to confirm that each user does not exceed the maximum group count. Definition at line 29 of file check_group_count.h. The destructor. Definition at line 26 of file check_group_count.cc. The constructor. Definition at line 40 of file check_group_count.cc. The default constructor. Do not use. The copy constructor. Do not use. The operation to be applied. It looks like a function call, that's why it's called a functor. Implements colon_passwd_functor. Definition at line 50 of file check_group_count.cc. The assignment operator. Do not use. The error_count instance variable is used to remember the number of errors seen to date. Definition at line 57 of file check_group_count.h. The max instance variable is used toi remember the maximum acceptable group count for any one user. Definition at line 51 of file check_group_count.h.
http://nis-util.sourceforge.net/doxdoc/classcolon__passwd__functor__check__group__count.html
CC-MAIN-2018-05
refinedweb
148
54.69
Okay, as the name implies, I would like to change an integer (ascii code number), such as 65, to a string, '65', then back to integer, 65. Now, the reason for doing so, is because I'm working with ascii code, and want to return a string of a fixed length. As known, ascii ranges from 1 - 256. I only want to capture the values from 32 and up. Here are my issues: 1) Check the length of the integer; ( such as the python expression len(str(65)) == 2 ) 2) If the length is 2, then make the string be '0' + number; 3) Combine all the strings into one; 4) Convert that back into a number I have only recently begun c++ programming, after 3~4 months of python programming (Gotten really good at it), and c++ is really confusing. In a more technical version of what I want to do, assume that my input is 65, 87, 121, 54 Then it'll return: 65087121054 Any help would be greatly appreciated. All I know to do is this: #include <iostream> #include <conio.h> char current; char pass[100]; int passcount(0); /* For converting the getch() to ascii code and append to the char array: pass[passcount] = char(current); */
https://www.daniweb.com/programming/software-development/threads/269926/c-convert-integer-to-string-and-back-to-interger
CC-MAIN-2018-13
refinedweb
208
71.68
On this topic, I'm just now teaching myself Haskell and am running into a whole range of stylistic questions like this. My big bad Java habits tend towards long camelCase function names, which I'm trying to wean myself off. But the variable conventions are the real issue. As far as I can tell, if you're writing type descriptors you just use [a,b,c...]. But what are the other general patterns for metasyntactic variable use?? For tuples I tend to pattern match with (a,b), and for lists I tend to use (h:r) for head and rest. Are there other, more universal standards for these sorts of things? Another related question is whether using these short sweet variable names makes sense, or whether I should try to use more descriptive ones. Obviously these are pretty small points of style, but I'm just trying to nail the Haskell idiom as closely as possible. I've already found myself falling into namespace traps though, playing around with math functions & etc. where an adequately descriptive name for one context in maybe a let block steps on something which deserves the name equally well in the global namespace. I try to keep the global namespace pretty clean, but things keep popping up -- I'm thinking maybe another convention would come to the rescue here, like camelCase or hyphen-ated for global and all lowers for local? --S. On 8/31/07, Paul Hudak <paul.hudak at yale.edu>... :-) > > -Paul > > _______________________________________________ > Haskell-Cafe mailing list > Haskell-Cafe at haskell.org > > -------------- next part -------------- An HTML attachment was scrubbed... URL:
http://www.haskell.org/pipermail/haskell-cafe/2007-August/031240.html
CC-MAIN-2014-10
refinedweb
268
72.56
to. First, just what do you mean by "make file"? You refer to cmake, make, and .mk in three places in your message. How about a link to the actual tool you're interested in? And a brief list of the other tools you're using it with. Is this it? Once we're talking about the same tool, then the question is what "elements" are you interested in? If your cmake is anything like the traditional make program, the format is deceptively simple, and enormously complex in usage. But I suspect that your cmake has very little to do with Unix make tools. The cmake that I gave the link for uses a CMakeLists file, which looks nothing like a makefile. Take a look at pymake: "make.py (and the pymake modules that support it) are an implementation of the make tool which are mostly compatible with makefiles written for GNU make." There is a parser.py file which might be useful to. Is there a better way to do that: def Read_CSV_File(filename): file = open(filename, "r") reader = csv.DictReader(file) line = 1 for row in reader: if line < 6: reader.next() line++ # process the CSV have a python script that is currently run from cron. We want to make it into a service so it can be controlled with service start/stop/restart. Can anyone point me at site that has instructions on how to do this? Forgot Your Password? 2017 © Queryhome
http://tech.queryhome.com/7981/how-to-read-a-make-file-in-python
CC-MAIN-2017-17
refinedweb
245
84.98
the output becomes 2 why?? Soumya Ranjan Mohanty wrote: import java.util.*; class MapEQ { public static void main(String[] args) { Map<ToDos, String> m = new HashMap<ToDos, String>(); ToDos t1 = new ToDos("Monday"); ToDos t2 = new ToDos("Monday"); ToDos t3 = new ToDos("Tuesday"); m.put(t1, "doLaundry"); m.put(t2, "payBills"); m.put(t3, "cleanAttic"); System.out.println(m.size()); } } class ToDos{ String day; ToDos(String d) { day = d; } public boolean equals(Object o) { return ((ToDos)o).day == this.day; } // public int hashCode() { return 9; } } When the hashCode() uncommented , the output becomes 2 why?? Example from Cathy Siera Book. phil sohan wrote:@Abimaran Kugathasan Could you please telll how hashcode works thenn,,,,,......... Abimaran Kugathasan wrote: phil sohan wrote:@Abimaran Kugathasan Could you please telll how hashcode works thenn,,,,,......... I think, my first reply in this question is correct. Please Have a look on it. mohitkumar gupta wrote:can anyone tell me,whether equals or hascode method would be called when the following line is encountered in the code ToDos t1 = new ToDos("Monday"); ToDos t1 = new ToDos("Monday"); ToDos t2 = new ToDos("Monday"); ToDos t3 = new ToDos("Tuesday"); i am not able to get ,how the objects t1,t2 are considered same..
http://www.coderanch.com/t/500929/java-programmer-SCJP/certification/HashMap-Duplicate-Element
CC-MAIN-2015-48
refinedweb
202
59.09
Add either forward class declarations, or guarded includes of afx headers (with comment as to purpose) where needed, so that individual files are self-documenting about their dependencies, and don't depend on their dependencies being handled in stdafx.h. But, still include three of the afx headers in stdafx.h for speed of precompiled headers. Logged In: YES user_id=804270 I understand the patch as having two goals : * to help documenting the dependencies * to clean stdafx.h from some dependency ( <afxcmn.h> in fact) It seems me some comments lines about dependencies are welcome, but we should not use class declarations or includes for documenting purposes ! We can just write an introduction sentence and comment the includes lines you added. Logged In: YES user_id=60964 Do you mean instead of this (which is in my patch): #include <afxtempl.h> // MFC C++ template collection classes doing this (an introductory comment): // MFC C++ template collection classes #include <afxtempl.h> ? If so, I can do that. I might myself rather prefer to discard the comment than to spend an extra line for it -- if you would go for blank (uncommented) lines, I could revise it to be so, eg, #include <afxtempl.h> ? Logged In: YES user_id=60964 Oh. I guess I don't understand your explanatory sentence "Includes files from Stdafx.h which are necessary". Those files don't come from Stdafx.h (which is a file in our project); they come from the Visual C++ MFC include directory. Logged In: YES user_id=60964 The idea of documenting classes is an interesting point. I'm actually accustomed to documenting classes in their headers, but I'm interested in any system you propose -- I think this project doesn't have very standard commenting documentation. We could consider some system that can generate html files, such as doxygen (which I have used), or some of the similar ones (which I've not used) ? Logged In: YES user_id=804270 The explanatory sentence is not clear, so I guess I need your help to find the words. What I mean is <afxtempl.h> is included in Stdafx.h, and the .cpp file includes Stdafx.h, so we don't need to include it in the cpp file, and even we should not. But add a comment to tell we herit <afxtempl.h> from Stdafx.h is a good idea. I have used a system to generate html but it was long ago. Anyway it would bring a great help. I don't know if the generated html has a place on the SourceForge site, as we can generate the html doc on our own computer. Except if somebody wants to add info to the html, but personnally I don't feel it is a priority. Logged In: YES user_id=60964 Oh, I misunderstood. Ok, maybe, // Assumes the following files are included by Stdafx.h: // afxtempl.h Although, I prefer to explicitly include them in the cpp, from when I have gotten tired of trying to reuse cpp files and having to figure out what headers they include. If they are included, then I don't have to figure it out. Actually all the MFC includes I've seen are protected against multiple inclusion, so it is safe to include them multiple times. But, you can be even more efficient, and include like so: #ifndef __AFXTEMPL_H__ #include <afxtempl.h> // MFC C++ template collection classes #endif // __AFXTEMPL_H__ This way, if the Stdafx.h already includes afxtempl.h, then the parser doesn't even read it again (because that symbol is defined). I guess I've adopted this strategy from when I've reused entire source files -- I much preferred that if two projects use the same source files, they use them *exactly* the same. Perhaps it doesn't matter in this project, as it doesn't share any (C++) source files with anything else. I'll post in the developers forum about documentation :) Kimmo Varis 2003-07-11 Logged In: YES user_id=631874 Some MFC guides are proposing to add most #include lines (even non-MFC includes) to stdafx.h and then including stdafx.h everywhere. Reasons given are compile speed and simpler #include management. I personally don't agree that non-MFC includes -part. But it's interesting point. WinMerge has problems with CrystalEditor #includes. CrystalEditor include lines are just a mess. Try to add new one or change something. I tried to add #include "files.h" to ccrystaltextbuffer.h to remove all file-handling code (eol-reading etc) from it. I tried it for three hours or so and give up. So I definitely agree we need some cleanup for #includes. At least some big projects (e.g. Mozilla) prefer using forward class declarations. I'm not sure about MFC includes. Maybe it's easiest solution to add them to only stdafx.h? It's easier when adding new files, just include stdafx.h and you get all you need. Yes, per file inclusion may be little more efficient, but it can be pain when you have to change or add new includes. Logged In: YES user_id=60964 re: forward class declarations I *always* prefer forward class declarations. But you can't do them for templates (at least I can't; sometimes it is possible if you understand typename stuff, maybe, but I doubt Visual C++ can handle that -- its template support is very out-of-date), and you can't do them for embedded members. Anyway, shall I just mark this patch rejected, and we'll abandon this ? Kimmo Varis 2003-07-11 Logged In: YES user_id=631874 You know this area better than me so it's your call. If I remember correctly this patch added couple of forward declarations? Maybe those are worth checking in at least?
http://sourceforge.net/p/winmerge/patches/177/
CC-MAIN-2015-27
refinedweb
964
75.3
?? Well i think the easiest thing is to just use a font that is already monospaced. If you’re intending to convert one that isn’t into a monospaced font you would probably have to alter it a bit yourself either in a program that basically makes fonts or on load or just create one that is monospaced. . . Dunno if this will help but you might find it interesting. You can maybe get some insight on altering a font on load from this, which i made as much for the heck of it. As sort of a starting point so someone can see how the values coming in from a font can be manipulated. If they want to do some sort of custom manipulation of their own this might help a bit to see how a font is pieced together. The following project goes by the following idea you make a new game1 project add the class then. … Links… the github project and below this a link to another page with just a example class created from it. example hard coded tahoma font text file generated from the above class with .cs extension. take this then load it into a vs project its constructor returns a font that is built from the class. Basically if you look at the glyphs and texture you can pretty much get the idea of how you would need to rescale the pixels and change the glyphs information so they are all the same width for a proportional font. You can imagine there are probably a few ways to do what you want all with their own pro’s and cons. this is not a sprite font though it’s a ttf font a sprite font is something that uses sprites or a texture. I don’t want to use a already made font because I have custom ones I have drawn onto a grid with paint.net. this is a major problem with monogame. it’s complicated and lacks things that it should already have. like people literally having to install monogame.extended to even draw a rectangle. this is not a sprite font though it’s a ttf font If you are just trying to load a ttf thats pretty easy just install it on your system and load it thru the content pipline and you get a spritefont all done easy peasy. I don’t want to use a already made font because I have custom ones I have drawn onto a grid with paint.net. then the previous and following applies. Actually what i posted is not a sprite font it is a class that creates a class that will recreate the original font you had loaded all by itself in any project by generating a spritefont including the texture from what is hard coded into that class a description of a spritefont. Which is relevant because you said all you had is a image before. But… that isn’t the point, you’re missing the point the easiest way is to build your own ttf with a tool or alter a existing one with a tool and make it monospaced. i used this then converted the result to a ttf installed it and then loaded it thru monogame that is the normal process i use for just a quick simple font. Their are far better tools. Or its possible to make something like this little app linked above, yourself that does what you are describing easily for yourself. . To regress The point of that class is it shows everything that is needed manually to (because your question seem to imply your doing it manually to me). 1) How to deconstruct a spritefont into data including the image. 2) How to construct a spritefont without loading anything at all from data. Provided you have a full description of how to draw characters from a image you copied or made. In this case even the image was also deconstructed into data, which is why it can be constructed fully from the class. The most important part is the texture. Its got images of letters in it, just like you would have in your image. But you have to have a description for were each letter is in the image how big it is, what letter it actually is, ect… Spritebatch needs data, rectangles mostly filled out that describes were each letter in that texture is. The below shows all the major fields required per letter that is desired by a spritefont’s constructor. /// <summary> /// Holds the sprite fonts data including the pixel data. /// </summary> public class SpriteFontData { public Texture2D fontTexture; ... ... // per letter. public List<char> glyphCharacters = new List<char>(); // the character A b C ect... public List<Rectangle> glyphBounds = new List<Rectangle>(); // the absolute rectangle area in the image were the character is. public List<Rectangle> glyphCroppings = new List<Rectangle>(); public List<Vector3> glyphKernings = new List<Vector3>(); // left, width, right side bering ... You are asking how to draw characters out of your image by using it as a spritefont. but A SpriteFont or any Font is more then just a image it also contains a description file or structure of all the character areas in that image. To create a spritefont you must include all the parameters listed below. This means if you do not want to load with the content pipeline then you must create your own file that lists characters in that image. Read the data from your file into the below types and pass them to the spritefont constructor. I hope that makes a little more sense. this is the font I am trying to load at runtime… I am calculating the character width and height by dividing the texture width by 16 and height by 6 giving a range from 32-96 like on old consoles public class Fnt { SpriteFont font; public int W => font.Texture.Width / 16; public int H => font.Texture.Height / 6; public Fnt() { List<char> chars = new List<char>(); var tex = Game.Content.Load<Texture2D>("fnt_null"); chars.AddRange((List<char>)Enumerable.Range(32, 96)); font = new SpriteFont ( tex, Enumerable.Repeat(new Rectangle(0, 0, tex.Width / 16, tex.Height / 6), 96).ToList(), Enumerable.Repeat(new Rectangle(0, 0, tex.Width / 16, tex.Height / 6), 96).ToList(), chars, 0, 0, Enumerable.Repeat(new Vector3(0, 0, 0), 96).ToList(), (char)0 ); } public Fnt(string filename) { if (File.Exists(filename) && Game.Initalized) { List<char> chars = new List<char>(); var tex = Gfx.Tex(filename); chars.AddRange((List<char>)Enumerable.Range(32, 96)); font = new SpriteFont ( tex, Enumerable.Repeat(new Rectangle(0, 0, tex.W / 16, tex.H / 6), 96).ToList(), Enumerable.Repeat(new Rectangle(0, 0, tex.W / 16, tex.H / 6), 96).ToList(), chars, 0, 0, Enumerable.Repeat(new Vector3(0, 0, 0), 96).ToList(), (char)0 ); } else { font = Game.Content.Load<SpriteFont>("fnt_null"); } } public static implicit operator SpriteFont(Fnt f) { return f.font; } } You can import a texture (.png/.jpg) as a spriteFont from the pipeline. You need to have the image in a special layout (clear bounds between clyphs and fill the rest will a unique color. If all boxes are the same size then the font will be monospace). Set the importer to Texture and the processor to sprite Font. Is that what you want? Because in the first message I think you were talking about the sprite Font constructor. That is a low level constructor that was used internally by monogame and the sprite font loader. Recently they made it public to support some more advanced scenarios (runtime generation of sprite font). Obviously it’s not a simple method to use out of the box. I don’t want to use the content pipeline because it creates a ton of unreadable xnb files. I was just using temporary xnb files for null tex, snd, and fnt (texture, sound, and font). but what I want to eventually do is load them at runtime and convert them into temporary xnb files for the life of the program. or at least do it the first time it runs and then somehow embed them in the application or 1 massive xnb file. Do you care if the image itself is in the content folder ? No actually that’s what I want to do. anything without having to open the content manager and add things Here is a start. I just loaded the image itself thru the content manager instead of from file i figured its not a big deal. I see you know how to load it from file anyways or you can convert the whole thing at the end to self load with that github project i posted. I didn’t handle transparency. (plenty of people can help with that too if you have a hard time). Couple notes… The class that does the work generically… MonoSpacedFont I made this class to specifically test the image you posted … MakeTheFont_fnt_null , it just calls to the static monospacedfont class and uses its method to make the image into a font. I don’t know what the name of that font in the image is supposed to be ? So i just used the name of the png for the texture that you named fnt_null and then named the one class similarily to reflect what it loads, not a very good name, but anyways. Your image isn’t in the right regional order so i couldn’t use the character range directly. so in the public class MakeTheFont_fnt_null and method GetFont(Game game) I left a couple notes for you other wise that method would be just 2 or 3 lines. var chars = MonoSpacedFont.RangeToCharList(32, 96, new List()); return MonoSpacedFont.CreateMonoSpacedFont(“fnt_null”, game, chars, 16, 6, 0, null); instead i left notes and made a alternate way to set the characters. // // You messed this up, the character order in the image doesn't match utf16 character order. // //chars = MonoSpacedFont.RangeToCharList(32, 96, chars); The class method GetFont(Game game) for game when you call to it in load content just use the (this) parameter you can see how its loaded in the actual game1 content method. Here is the game one file there is static class that is has the primary method. The other class uses it for a specific image in the content folder to return a spritefont. Whole thing can be copy pasted over a game1 class change the namespace to yours then add your image in the content pipeline as named. It should run the same as shown in the image i posted. using System; using System.IO; using System.Linq; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; namespace GuysMonoSpacedFont { public class Game1 : Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; SpriteFont myfont; public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; } protected override void Initialize() { base.Initialize(); } protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); var m = new MakeTheFont_fnt_null(); myfont = m.GetFont(this); }); spriteBatch.Begin(); spriteBatch.DrawString(myfont, "HELLO WORLD", new Vector2(100, 100), Color.White, 0f, Vector2.Zero, 5, SpriteEffects.None, 0); string dup = " !" + '"' + "#$%&'()*+,-./" + "0123456789:;<=>?" + "@ABCDEFGHIJKLMNO" + "PQRSTUVWXYZ[" + "\\" + "]^_" + "`abcdefghijklmno" + "pqrstuvwxyz{|}~"; spriteBatch.DrawString(myfont, dup, new Vector2(100, 200), Color.White, 0f, Vector2.Zero, 5, SpriteEffects.None, 0); spriteBatch.End(); base.Draw(gameTime); } } public class MakeTheFont_fnt_null { public SpriteFont GetFont(Game game) { var chars = new List<char>(); // // You messed this up, the character order in the image doesn't match utf16 character order. // //chars = MonoSpacedFont.RangeToCharList(32, 96, chars); // // directly inputed // i cant tell what that last letter is so i skipped it. // chars = MonoSpacedFont.StringToCharList ( " !" + '"' + "#$%&'()*+,-./" + "0123456789:;<=>?" + "@ABCDEFGHIJKLMNO" + "PQRSTUVWXYZ[" + "\\" + "]^_" + "`abcdefghijklmno" + "pqrstuvwxyz{|}~" , chars ); return MonoSpacedFont.CreateMonoSpacedFont("fnt_null", game, chars, 16, 6, 0, null); } } public static class MonoSpacedFont { public static SpriteFont CreateMonoSpacedFont(string imageName, Game game, List<char> characters, int rows, int columns, int extraSpaceBetweenCharacters, char? defaultchar) { var tex = game.Content.Load<Texture2D>(imageName); int W = tex.Width / rows; int H = tex.Height / columns; List<Rectangle> bounds = new List<Rectangle>(); List<Rectangle> cropping = new List<Rectangle>(); List<Vector3> kerning = new List<Vector3>(); for (int y = 0; y < columns; y++) { for (int x = 0; x < rows; x++) { var posx = x * W; var posy = y * H; bounds.Add(new Rectangle(posx, posy, W, H)); cropping.Add(new Rectangle(0, 0, 0, 0)); kerning.Add(new Vector3(0, W, 0)); } } return new SpriteFont ( tex, bounds, cropping, characters, H, extraSpaceBetweenCharacters, kerning, defaultchar ); } public static List<char> StringToCharList(string s, List<char> charlist) { foreach (char c in s) charlist.Add(c); return charlist; } public static List<char> RangeToCharList(int start, int end, List<char> charlist) { for (int i = start; i < end; i++) charlist.Add((char)i); return charlist; } } } Once you get the kinks out. You could use my github project i posted at the begining to transform the finished result into a loadable class file if you wanted to as well its pretty straightforward just give it the spritefont you just made and it will turn it all into a class that self creates the whole spritefont.
https://community.monogame.net/t/monospaced-sprite-font/11775/2
CC-MAIN-2022-40
refinedweb
2,174
65.42
curl-library Re: curl_multi_socket Date: Wed, 12 Apr 2006 23:54:41 +0200 Hi, On Mon 10.04.2006 17:05, Daniel Stenberg wrote: > >In order to decrease my pain when having to keep up my hiper patch with >the code in the HEAD of the CVS repository, I've now committed my >multi_socket work. It would have to be done at some point anyway so I >thought what the heck, why not sooner than later! ;-) Super ;-) >Please let me know if you find any existing functionality to have >broken in my merge process! I have build curl with CURL_MULTIEASY from current cvs. Here the complete ./configure call: ./configure --disable-ldap --disable-dict --disable-telnet \ --disable-tftp --disable-ipv6 --disable-sspi \ --prefix=/home/al/progs/curl --enable-debug CFLAGS=-DCURL_MULTIEASY && \ make && make test I know this is: ---lib/easy.c:#ifdef CURL_MULTIEASY /*************************************************************************** * This function is still only for testing purposes. It makes a great way * to run the full test suite on the multi interface instead of the easy one. *************************************************************************** ---- But i was curiously ;-) When i run the testsuite i get some cordumps and errors. I have looked into one e.g. 230 and i got the following coredump --- (gdb) bt #0 0xb7f964b6 in curl_multi_fdset (multi_handle=0x808aff4, read_fd_set=0xbfbb9088, write_fd_set=0xbfbb9008, exc_fd_set=0xbfbb8f88, max_fd=0xbfbb8f84) at multi.c:539 #1 0xb7f92985 in curl_easy_perform (easy=0x8082594) at easy.c:401 #2 0x08050441 in operate (config=0xbfbb9580, argc=9, argv=0xbfbb9794) at main.c:4120 #3 0x08050ca4 in main (argc=9, argv=0xbfbb9794) at main.c:4415 --- then i have added into 'lib/multi.c:curl_multi_fdset()' this: #ifdef CURLDEBUG infof(easy->easy_handle, "curl_multi_fdset: i :%d: => sockbunch[i] :%d: s :%d: handle %p: \n", i, sockbunch[i], s, (char *)easy); #endif before: if(s == CURL_SOCKET_BAD){...} And the output was: --- 23:33:29.096292 * curl_multi_fdset: i :0: => sockbunch[i] :4: s :4: handle 0x808bd44: 23:33:29.096470 * curl_multi_fdset: i :1: => sockbunch[i] :-1207955468: s :-1: handle 0x808bd44: --- It looks to me that the: for(i=0; i< MAX_SOCKSPEREASYHANDLE; i++) {...} have a little problem. What are you thinking about this? Regards AlexReceived on 2006-04-12
https://curl.se/mail/lib-2006-04/0081.html
CC-MAIN-2021-43
refinedweb
352
58.69
This action might not be possible to undo. Are you sure you want to continue? 4952 OMB No. 1545-0191 Investment Interest Expense Deduction Attach to your tax return. 2003 Attachment Sequence No. Identifying number Department of the Treasury Internal Revenue Service 12B Name(s) shown on return Part I 1 2 3 Total Investment Interest Expense 1 2 3 Investment interest expense paid or accrued in 2003 (see instructions) Disallowed investment interest expense from 2002 Form 4952, line 7 Total investment interest expense. Add lines 1 and 2 Part II Net Investment Income 4a Gross income from property held for investment (excluding any net 4a gain from the disposition of property held for investment) 4b b Qualified dividends included on line 4a c Subtract line 4b from line 4a 4d d Net gain from the disposition of property held for investment e Enter the smaller of line 4d or your net capital gain from the disposition 4e of property held for investment (see instructions) f Subtract line 4e from line 4d g Enter the amount from lines 4b and 4e that you elect to include in investment income (see instructions) h Investment income. Add lines 4c, 4f, and 4g 5 Investment expenses (see instructions) 6 Net investment income. Subtract line 5 from line 4h. If zero or less, enter -0- 4c 4f 4g 4h 5 6 Part III 7 8 Investment Interest Expense Deduction 7 8 Disallowed investment interest expense to be carried forward to 2004. Subtract line 6 from line 3. If zero or less, enter -0Investment interest expense deduction. Enter the smaller of line 3 or 6. See instructions ● You have no disallowed investment interest expense from 2002. Section references are to the Internal Revenue Code unless otherwise noted. General Instructions A Change To Note In general, qualified dividends shown on Form 1040, line 9b (or Form 1041, line 2b(2)), are excluded from investment income. But you can elect on Form 4952, line 4g, to include part or all of your qualified dividends in investment income. See the instructions for line 4g for details. Allocation of Interest Expense If you paid or accrued interest on a loan and used the loan proceeds for more than one purpose, you may have to allocate the interest. This is necessary because different rules apply to investment interest, personal interest, trade or business interest, home mortgage interest, and passive activity interest. See Pub. 535, Business Expenses. Investment interest expense does not include any of the following:. Property held for investment. Property held for investment includes property that produces income, not derived in the ordinary course of a trade or business, from interest, dividends, annuities, or royalties. It also includes property that produces gain or loss, not derived in the ordinary course of a trade or business, from the disposition of property that produces these types of income or is held for investment. However, it does not include an interest in a passive activity. Exception. A working interest in an oil or gas property that you held directly or through an entity that did not limit your liability is property held for investment, but only if you did not materially participate in the activity. Purpose of Form Use Form 4952 to figure the amount of investment interest expense you can deduct for 2003 and the amount you can carry forward to future years. Your investment interest expense deduction is limited to your net investment income. For more information, see Pub. 550, Investment Income and Expenses. Specific Instructions Part I—Total Investment Interest Expense Line 1 Enter the investment interest expense paid or accrued during the tax year, regardless of when you incurred the indebtedness. Investment interest expense is interest paid or accrued on a loan or part of a loan that is allocable to property held for investment (as defined on this page). Include investment interest expense reported to you on Schedule K-1 from a partnership or an S corporation. Include amortization of bond premium on taxable bonds purchased after October 22, 1986, but before January 1, 1988, unless you elected to offset amortizable bond premium against the interest payments on the bond. A taxable bond is a bond on which the interest is includible in gross income. Cat. No. 13177Y Who Must File If you are an individual, estate, or a trust, you must file Form 4952 to claim a deduction for your investment interest expense. Exception. You do not have to file Form 4952 if all of the following apply. ● Your investment interest expense is not more than your investment income from interest and ordinary dividends minus any qualified dividends. ● You have no other deductible investment expenses. For Paperwork Reduction Act Notice, see back of form. Form 4952 (2003) Form 4952 (2003) Page 2d, if applicable) net passive income from a passive activity of a publicly traded partnership (as defined in section 469(k)(2)). See Notice 88-75, 1988-2 C.B. 386, for details. Net income from certain passive activities, such as rental of substantially nondepreciable property, may have to be recharacterized and included on line 4a. For details, see Pub. 925, Passive Activity and At-Risk Rules, or Regulations section 1.469-2(f)(10). If you are filing Form 8814, Parents’ Election To Report Child’s Interest and Dividends, part or all of your child’s income may be included on line 4a. See the instructions for Form 8814 for details. Do not include on line 4a any net gain from the disposition of property held for investment. CAUTION Instead, enter it on line 4d. The qualified dividends and net capital gain that you elect to include in investment income on line 4g are CAUTION line 25 of Schedule D (Form 1040) (or line 22 of Schedule D (Form 1041)), if applicable. 41 (or Form 1041, Schedule G, line 1a). However, you may. You must generally make this election on a timely filed return, including extensions. However, if you timely filed your return without making the election, you can make the election on an amended return filed within 6 months of the due date of your return (excluding extensions). Write “Filed pursuant to section 301.9100-2” on the amended return and file it at the same place you filed the original return. on Schedule A (Form 1040), line 25, may reduce the amount you must include on Form 4952, line 5. Include on line 5 the smaller of: (a) the investment expenses included on Schedule A (Form 1040), line 22, or (b) the total on Schedule A (Form 1040), line 26. Part III—Investment Interest Expense Deduction Line 8 Individuals. Generally, enter the amount from line 8 on Schedule A (Form 1040), line 13, even if all or part of it is attributable to a partnership or an S corporation. However, if any part of the interest expense is attributable to royalties, enter that part on Schedule E (Form 1040). Also, if any part of the interest is attributable to a trade or business that is not a passive activity, enter that part on the schedule where you report other expenses for that trade or business. Estates and trusts. Enter the amount from line 8, 39 min.; Learning about the law or the form, 12 min.; Preparing the form, 22 below. Line 5 Investment expenses are your allowed deductions, other than interest expense, directly connected with the production of investment income. For example, depreciation or depletion allowed on assets that produce investment income is an investment expense. Include investment expenses reported to you on Schedule K-1 from a partnership or an S corporation. Investment expenses do not include any deductions used in determining your income or loss from a passive activity. If you have investment expenses that are included as a miscellaneous itemized deduction on Schedule A (Form 1040), line 22, the 2% adjusted gross income limitation Line 4g In general, qualified dividends and net capital gain from the disposition of property held for investment are excluded from investment income. But you can elect to include part or all of these amounts in investment income. This action might not be possible to undo. Are you sure you want to continue? We've moved you to where you read on your other device. Get the full title to continue reading from where you left off, or restart the preview.
https://www.scribd.com/document/541799/US-Internal-Revenue-Service-f4952-2003
CC-MAIN-2016-50
refinedweb
1,396
53.61
>> thanks a bunch! it works great! when i created the new project though, it displayed APIs 7 and 8, therefore i can not use android 1.5 . it allowsme to use the android 2.1 and 2.2… any ideas? This is excellent! Thank you very helpful and informative, I can’t wait till I do the next step. This was excatly what I needed to start developing for Android. Hi, this is really cool. But I think you should mention how easy it is to set up a real phone to debug your programs. But over all a really cool tutorial, especially because I’m trying to get into Android. Thanks! Love the tutorial, I really look forward to developing on this platform! I’m a java noob, and scouring google left me with no results for my issue…. I encounter an error in my main.xml file on the LinearLayout line 2. My error description states “error: Invalid start tag LinearLayout” and I have not modified anything in this file. The code on the line is <LinearLayout xmlns:android="" followed by the orientation, layout_width & height. Any Ideas? I'd appreciate any help! @Greg So the solution’s recorded, I had DavioP’s problem for a moment in Eclipse 3.5: By chance, I had strings.xml selected when I hit the run button, which led to the creation of strings.out.xml and an error. The solution was to click on the project root in the Package Explorer and then hit build. The clue was that I had no “Run As…” choice; it was trying a different kind of run. Thanks for the solution to E_man’s problem, which I had in 3.6. Incidentally, 3.6 appears to be working fine so far… Total novice…..im having a problem where it doesnt recognize a file, ERROR: Unable to open class file C:\Users\CHRIS\workspace\Helloworld1\gen\com\chriscutter\R.java: No such file or directory, but yet following that pathway i can find the file. Solutions? Iam also facing same problem : ..\gen\com\chriscutter\R.java: No such file or directory. Any pointers how to resolve…. Hi.. I really like the work youre doing :) As the two gentlemen above me, Chris and Kumar, I to am getting the same error. First time around I of course thought I was doing something wrong, so I deleted my project and started over again, but the error stays.. kinda stuck now and this is the only site I saw the problem addressed, so.. what are we doing wrong? (My eclipse and my andriod files are in different directories, can that cause the problem?) About the error “\R.java: No such file or directory” i just closed down eclipse and opened it agian. problem solved. (new to this as well) Thanks coby, that’s restarting Eclipse solved my problem with “\R.java: No such file or directory”. regards ——- subba Re: “\R.java: No such file or directory”. If you’re using Eclipse, Project > Clean should also do the trick. I really enjoyed this article and I would love to see more of this! tsup guys, i learnt this a long time ago on the example scripts my app came with, where are the rest of the tuts? i know ruby, i want to know what i can execute on my android’s ruby shell and have it run right there and then Awesome! good stuff, but could you change the f*in color of this website, getting a migraine reading this Great posts! I’ve gotten everything working so far except the last step. When I run the project, it opens up the android phone as you show, but my application hasn’t started. I’ve tried navigation to it, and it isn’t there either. I know this post is around a year old, I was wondering if you had any advice? how can i make a pdf reader for android mobile??? do you know any web site that could help me developing this software??? This article is great, but I cannot seem to get past the following error: Error occurred during initialization of VM java/lang/NoClassDefFoundError: java/lang/ref/FinalReference Help Please!! package com.srishti.helloworld; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.MenuItem; import android.support.v4.app.NavUtils; public class HelloMain extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_hello_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_hello_main, menu); return true; } This is the code in the HelloMain.java It says “- R cannot be resolved to a variable” …I am a newbie so please help me solve this hey… Greg… m a newbie.@ programming… but noe basics of java… however i havent understud d last line in code.wich is setcontentview…. what is d purpose of using it.. can u xplain me d stepwise execution of d last 2 lines of code.. pls..!
http://hackaday.com/2010/07/15/android-dev-101-%E2%80%93-part-1hello-world/comment-page-2/
CC-MAIN-2014-10
refinedweb
835
68.57
What is DX? Developer Experience (DX) is the equivalent to User Experience (UX) when the user of the software or system is a developer. DX describes the experience developers have when they use your product, be it client libraries, SDKs, frameworks, open source code, tools, API, technology or service. DX shares some ideas and philosophies from UX design (or HCI), but builds on these with an eye towards modern technology and standards. Why does it matter? DX matters for the same reasons good UX matters. Users of your technology are happier, promote it more, and stay longer when the product has good DX. Happy developers are chatty developers, and when we talk to each other to recommend products, the ones with the best DX are at the top of the list. Follows is my list of best practices when it comes to DX. Do these, and you’re well on your way to success. The Guidelines Communication Good communication is key to a successful developer experience. The way you speak to developers is crucial to how they perceive you and your product. Tone: Be Authentic, Open and Honest The way you speak to developers is crucial to how they perceive you and your product. Developers can smell bullshit, and they don’t like fluff. If you be honest with developers, they’ll respect your product more. If you have a data breach, a bug, a period of downtime, or some data loss, be clear with this. Create a status page and comms system and use it to communicate with your developers. Be honest about your timelines and be prompt with any post-mortems or debriefs. Communicate product roadmap with product forums, and let developers contribute to those priorities directly. Engage with them, ask them what they think. Great Documentation Your docs are your voice to the customer. But what makes for great documentation? Always write your docs as if the developer is a beginner, not just with your technology (which they definitely are) but also the platform for that technology. If you’re documenting an NPM module, include a link to how to even install NPM in the first place, and how to include the code into other JS files. If it’s a ruby gem, the same thing. Consistency of language in the docs is also important. If you have multiple contributors to documentation, make sure they’re all using “function instead of “method”, or “package instead of “module”. This also is important for your own product related nouns, such as “Activity Log instead of “Log”. Being consistent stops readers from becoming lost and second guessing what they’re reading. Thirdly, a logical layout and structure to your docs is important. Surface common reading, and lay out docs in order of integration steps. An “Overview with core concepts then “Getting Started section with installation and/or set up is a great start. What follows after that depends on your product, but you should know based on what you expect people to do – just document that expectation. Finally, verbosity is always great in docs. You can never say too much. It’ll be one sentence or a few extra words that really helps a stuck developer. It’ll mean the difference between a developer who feels comfortable and supported versus an irate one calling your support line. Docs can sometimes feel like a last minute thing, but slowing down, investing in them, will pay dividends in the long run. Good Release Notes and Changelogs When releasing a new version, it’s another important time to be on the ball with communications to developers. Explain clearly what is new, what was broken but now fixed (yes, own your mistakes, please), and what any risks of this version is (eg, this might break x). Even better if you can link to a public issue tracker for these for more detail. Why? Well, when developers want to catch up on versions, they want to be able to quickly scan the release notes or change logs and try find the thing they’re looking for. They might be asking “which version did this get deprecated in? or “what version did x get added? or “what version did they fix the bug I’m experiencing?”. If you can answer these in your release notes, then you’ve nailed it. Release notes are also a good place to point out any security vulnerabilities that have been fixed, which obviously add more motivation to update. Developers should always be motivated to update to the latest version. Having them on the latest version also reduces support overhead. Respect Standards and Idioms When writing a client library, SDK, API, etc, it’s important to respect the standards of the industry and/or community and idioms of the platform from those gone before you. Respect Platform Idioms and Toolsets I work on an iOS SDK as part of my day job, and when I do this, I must always be mindful the app developer using this. What Xcode version are they on? What language are they using? Objective-C or Swift? How can I make this API work better with either of them? While just an anecdote, it’s important you also think of the same thing. So, think to yourself, what tools are people using to interact with me? What *versions *are they? Do they make a difference? Don’t Assume Programming Paradigms It’s easy to think that because you like a certain style of programming, others will like it too, but this isn’t always the case. For example, if you like functional programming, you may be tempted to write your library with a functional interface. Please don’t. Write it the plain, or more traditional or standard way, such as plain JS vs a Fluent Interface or plain Ruby or plain Swift vs a functional style API, or a Java Builder pattern vs just an object to construct, and then also provide a wrapper or facade for a given style. That way, everyone can use it, and no one has to learn a new style of programming just to use your code. If there is no given paradigm, chose what is best, preferably most likely to prevent mistakes and a quick time to learn. Consistency Consistency is key with interfaces for developers. Very much for the same reason as in UX, it stops people from making mistakes. Be consistent with the rest of the language or platform. For example, let’s say you have a simple library that talks to and endpoint and provides a native object for use. If you’re writing Java or C#, your asynchronous methods might expose a Listener pattern, which is very consistent with the language. However, if you’re writing Swift, you the equivalent method might expose a callback. If it’s in Javascript, it might also be callback, but it could be a Promise. Figure out what’s common on the platform by researching other code (with the ultimate source of truth being the platform source itself), and then use that. If it doesn’t matter, then be consistent between your different libraries across the different languages, but platform consistency comes first. Methods should be called similar names across the platforms, so developers integrating in multiple languages can gain momentum, and generally because it’s just cleaner. This goes back also to* Respect Platform Idioms and Toolsets *above, keep this in mind as you ship code for a certain language or platform. Be a Good Citizen For code that will be embedded in other people’s code (such as frameworks and libraries), it’s best to make sure your code isn’t going to be a cause of concern. If anything, this code needs to better than the code it’s in as it should never be an issue. Method Annotations and Docs If you’re exposing methods, try use annotations to indicate a few things. Some languages like Objective C and Swift provide these features, where as some tools like Android Annotations provide this. The first is nullability, can the thing you pass me here be null? What does that mean if it is? And can what the method returns also be null? With these explicitly called out, Developers can change their style to code more defensively or not around these cases. For as something as simple as adding an annotation, you may save your users a NullException or similar. Secondly, over-document. Document each parameter and method carefully, and name them well. Probably name them better you would your internal names, in an effort to make them accessible to beginners. The more documentation about how to use the method, any prerequisites or postrequisites it needs, and a hint to how it works, and any equivalents it has or redundancies, and any side-effects. Not only will this help external developers, it’s also great for your internal team to get up to speed if they’re making a change to the code. Well documented code is great. The usual rules of “don’t over comment and “your code should be self-documenting just don’t apply for external code. The more the better, always. It’s about reducing confusion and stopping that support line phone ringing. Method Removal and Deprecations If you want to change your mind about some external methods, you’ll need to slow down and let your developers adjust. The recommended approach for this is to introduce the new behaviour and deprecate the old. Deprecate refers to functions or classes that are in the process of being replaced by newer ones. What you must not do is just remove functions or change their behavior, as this will almost certainly affect other code that interacts with it. You should always deprecate the old first, an in a future, preferable major version(more on this later) remove the deprecated methods. Deprecated periods should last at least a month, but can last up to a few years. You’ve probably felt me defining deprecation above was a bit silly because you’ve seen and dealt with them before, well, *exactly – *it’s a great way to communicate and you’re used to it – so do it yourself when you’re the one providing the code. Non-Colliding Namespaces If your language that you’re programming with doesn’t have namespace or package support, then you should prefix your code to avoid this. This is fairly common in Objective-C, where a lot of provided classes have the NS- or UI- prefix. My code as SJ in front of it, for my name, or sometimes a acronym based on the name of the project. Using two or three letters (preferably three) reduces the risk of errors during compile time, where your code is named the same as something in the rest of code. If your language supports namespaces and/or packages, make sure these are also configured for the same reason. Threading Arguable more aimed at mobile development, be careful with threads and processes. Try use a secondary or background process to do your work such that actions such as UI work aren’t blocked by your code. Because of this, code with common multi-threaded pitfalls in mind, and test carefully. Be Open Source (At least try!) While I acknowledge that some code must stay closed source, if not required, have it be open source. Follow the open source best practices, which, in themselves are part of a good DX. This advice is more of the same as above, centering around good communications. Why Open Source? Open source code is more trusted by developers, and anecdotally, more developers are exclusively using only open source dependencies in their products. They’re able to look into the source and find and fix bugs, as well as inspect it for any code that is questionable, and remove it. Great Read Me What’s in a great Read Me? A full list here is here, but in short, a good description, installation notes, good (trivial examples), contribution guidelines and any known issues. Links to more docs is also great. Some of the best projects I see also shout out top contributors, or shout out notable users of it. Safe Space for Contributions Having a Code of Conduct for your open source efforts is super important. Your users could be anyone, and their contributions should be welcomed and protected no matter who they are. A code of conduct (even the one Github gives you by default) is great, as long as you action it if it is broken. Create a safe space for contributions, remember, these people are probably adding value to your company, why not do the best for them that you can? Open CI If possible, and if it makes sense to, open your CI system too. Most hosted CI systems are *free *for open source projects, so just hook it up and tie it in. This will make it easier to contribute with pull requests and makes it easier for you to review and accept or reject contributions. Some would even recommend going further, and using bots. Use what you think you need. More active repos will need more automation to scale. Make It Easy Make it easy for developers to actually get your product and integrate it. It’s amazing how many products would benefit from developers using it, but don’t understand how they think. Clear Pricing The first of these is clear pricing. No developer ever will ever click a “Book a demo button. Let us have a free trial, or pop in our credit card and give it a spin. We want to know how the pricing works and what variables control how much it cost. Even better if that makes sense to us, eg things that would cause more costs for you, such as higher number of requests or more compute time used. Sure, value-based pricing is a thing, and you may want to work out a deal for larger customers, but if freaking SpaceX can have a pricing page, so can your software product. Self Serve Option As above, we want to be able to use it ourselves. We don’t necessarily want to sign a custom contract, have to get on a call with a sales person, or pay an implementation fee. We just want to sign up, integrate it that day and see if the price makes sense for the value we’re getting. Sure, your business may not work like that (and that’s okay), but that’s a compromise of the model, you miss out on a self-serve market. And as above, developers are a chatty bunch, and they might recommend your product to their friend who works for that customer you’ve always wanted, so you never know. But, of course, use your best judgement. Versioning Version your code and products correctly. Semantic Versioning (SemVer) is what the industry has landed on, and it’s good, and you should use it. In short, a version number should have three parts, three numbers. Eg, “X.Y.Z”, or “Major.Minor.Patch”. Patch releases fix bugs. Minor adds small features, and major removes deprecations and releases bigger features. So, when versioning, think carefully about what version number you are really meant to use, such that you communicate to developers the impact of the version. And sorry if you spent two weeks on a change, it might only still be only a patch version. The *semantics *of the version number matters more. Packaging Most languages now have one or more accepted way to distribute code. There’s NPM and Yarn for JS, RubyGems for Ruby, Nuget for C#, Maven for Java, CocoaPods/Carthage/SPM (grr) for iOS, PIP for Python… and the list goes on. Your code should be distributed by this way as well. As a developer scans your installation docs, they’re looking for the line that installs your product via one of these systems, they’re looking for gem ‘Sam’ or npm install sam in the first paragraph. Take the time to generate the files required to interact with these systems, and use Git Tags and SemVer to create and push releases to your users. Secondly, if the packaging system supports code signing or security features like that, be sure to use those, so your developers know the software came from you, and is less likely to be compromised. Do Your Best To finish off, we get onto the obvious stuff about the actual quality of your product. Use Your Own Stuff If you’re shipping anything that a developer will use, be sure to always test it as if you’re a new developer. Create a fresh project, integrate it and test it. Try to rule out any false positives from your dev environment and really just eat your own dog food. The more you do this, the more knowledgable you’ll be about the integration process, and that’ll lead to finding gaps in documentation, ReadMes and much more. Give this task to someone on your team completely unfamiliar with the product (or a friend if you’re solo) and see what they find confusing, and improve from there. Feature Set The feature set of your product must match what a developer has come to expect from competitors. However, you might have something they miss, and that might indicate a UX problem, or poor DX. Ask developers what is missing, and use that crucial (and free) feedback to make your product better. A good product also scales under load or is built for purpose well. It is also secure noting the latest concerns and keeps its dependencies up to date. So that’s what makes for great DX. In conclusion, a lot of DX is just doing what you’d expect if you were a developer. Put yourself in their shoes (and remove your knowledge of the subject) and try see what you’d expect, and do that. Have Fun Developers, like everyone like to have fun. Keep all your interactions light hearted and enjoyable for both sides. Remember: If they’re using your product, you’re on the same team. You’re just two people working together to solve a problem. Use your teamwork skills to make the interaction positive and enjoyable. Need help with this? Get in touch and I can help out you and/or your team. Liked this post? Please give me an emoji reaction, or leave a comment to show your appreciation. It really keeps any person creating content on the internet going when you express your gratitude – we do this for you. Discussion (12) This was a great post Sam. I was publishing an article here today which I had already published to my company website about how to import images into React components, and I used the word directory 99% of the time. However, originally I decided to use the word "folder" instead to shake things up. right before I read your piece I was wondering whether using folder as well would prove confusing. After I read this, I realized that it could be. I write about code a lot and articulate my experiences in articles as well. I always want to make sure that I state things clearly and as simply as possible so that everyone at every level can understand. And besides, just because someone might be very experienced does not mean that they will necessarily follow your explanation. In addition, they might still find a particular topic difficult. I will be taking your advice here to heart for other things. Totally makes sense and extremely helpful. Thanks! Glad I could help! Yes, consistency of terms is important, and try to use the term from the specific domain. I'm not a react dev, but if "directory" is the term most commonly used, go with that! Damn this is a great overview. Sharing with the team. Thanks as always Sam. Very welcome, Ben! I, as always, really appreciate the kind words. Side-note: The business people are already hijacking DX for digital transformation, so don't be confused if you just read DX somewhere and it doesn't make any sense :D Ha! Good point! shakes fist at The Business People Totally agree. What can be done or have you seen done in the open source space? Volunteers, little time and rush can overlook good documentation. At first I thought it was me when going through OS apps and having a difficult time implementing or learning as a newbie. Thanks for this and it needs to be more mainstream reading! Dave, totally understand the pressure on open source docs. I think its worth noting that contribution to open source docs is contribution to open source. It doesn't necessarily have to be code you contribute. Usually, my first thing with any project (OSS or internal company) are fixes to the ReadMe... there's always something to add. Spot on. Especially when it comes to documentation where lots of open source projects are lacking, even several of the large and famous ones. Exactly! You can improve their docs too if they're open source – that'd be a valuable contribution. These are some great advice. Thank you for sharing! Thank you! I really appreciate the kind words :)
https://practicaldev-herokuapp-com.global.ssl.fastly.net/samjarman/the-best-practices-for-a-great-developer-experience-dx-b3a
CC-MAIN-2021-10
refinedweb
3,572
72.05
Aaaaaand here we are! So, link to the problem entitled Watersheds: And it says:’.) So, looks like a path problem. As a path problem, we need to calculate which route to use based on series of rules, like walking through a map and choosing where to go next. Since usually the same deciosion applies to all “map units”, recursion is your friend. 🙂 To the I/O Rules: Input The first line of the input file will contain the number of maps, T. T maps will follow, each starting with two integers on a line — H and W — the height and width of the map, in cells. The next H lines will each contain a row of the map, from north to south, each containingW integers, from west to east, specifying the altitudes of the cells. Output For each test case, output 1+H lines. The first line must be of the formCase #X: where X is the test case number, starting from 1. The next H lines must list the basin labels for each of the cells, in the same order as they appear in the input. For each problem, there’s an array filled with height values. What we need to do is fill these arrays with letters, starting from ‘a’. The rules are quite simple: To better explain the rules, I’ll separate the neighboors in two classes: path neighboors and loop neighboors. - Path neighboors: map units that belong to the same “route” and are next to each other. The ones we choose to move to. - Loop neighboors: map units that our loop tells us to go to. Usually, loops iterate through arrays the same way: through lines, left to right. Our loop neighboor will be the next neighboor which the loop tells us to go. For each block, do: - Check our number. Are we already a letter on the result? If so, move to the loop neighboor, else, go on. - Check the 4 neighboors. Is our number bigger than theirs? No? Then we’re a sink. Write our letter on the result, increase the current letter, move to next neighboor. If our number is bigger, keep going… 😉 - Which neighboor has the lowest number? There’s a tie? Ok, then let’s choose based on the priorities: North, then West, then East and South. If there’s no tie, choose the lowest. Write our letter and go to the chosen neighboor. 🙂 And… here’s the code. It’s old and really bad written, so be careful. Haven’t tested it recently but I guess it works. If it doesn’t, well… tell me! 😀 from numpy import * from array import * alphabet = "abcdefghijklmnopqrstuvwxyz" cur_basin = 0 ma = [['a']] """ N W E S """ def rec( m, ma, h, w, l, a, cur_basin): lv = 65535 lh = 0 lw = 0 if (l != 0): if (m[l-1][a] < lv): lh = l-1 lw = a lv = m[lh][lw] if (a != 0): if (m[l][a-1] < lv): lh = l lw = a-1 lv = m[lh][lw] if (a != w-1): if (m[l][a+1] < lv): lh = l lw = a+1 lv = m[lh][lw] if (l != h-1): if (m[l+1][a] < lv): lh = l+1 lw = a lv = m[lh][lw] if ma[l][a] < 'a': if lv >= m[l][a]: cur_basin+=1 ma[l][a] = alphabet[cur_basin] else: if ma[lh][lw] >= 'a': ma[l][a] = ma[lh][lw] else: cur_basin+=1 ma[l][a] = alphabet[cur_basin] ma[lh][lw] = ma[l][a] else: if lv > m[l][a]: if (l != h-1): ma,cur_basin = rec(m, ma, h, w, l+1, a, cur_basin) elif (a != w-1): ma,cur_basin = rec(m, ma, h, w, l, a+1, cur_basin) elif (a != 0): ma,cur_basin = rec(m, ma, h, w, l, a-1, cur_basin) elif (l != 0): ma,cur_basin = rec(m, ma, h, w, l-1, a, cur_basin) elif lv < m[l][a]: if ma[lh][lw] < 'a': ma[lh][lw] = ma[l][a] return ma,cur_basin line = raw_input() cases = int(line) for i in range(cases): header = str.split(raw_input()) h = int(header[0]) w = int(header[1]) m = zeros((h,w)) ma = [['a']] cur_basin = 0 maxh= 0 for l in range(h): mapline = str.split(raw_input()) ma.append(mapline) if l == 0: ma.pop(0) for a in range(len(mapline)): m[l][a] = int(mapline[a]) maxh = max(maxh,m[l][a]) ma[0][0] = alphabet[cur_basin] for l in range(h): for a in range(w): ma,cur_basin = rec(m, ma, h, w, l, a, cur_basin) print "Case #%d:" % int(i+1) for l in range(h): for a in range(w): if a < w-1: print "%c" % ma[l][a], else: print "%c" % ma[l][a] exit() I don’t remember why I decided to use “inverted axis” (at least for me, using “lines, columns” isn’t usual as I rather do “columns, lines” for positioning) and why it’s so bad to read (hurry?). Well, happy coding, I guess! 😛
https://diogobohm.net/2013/02/19/codejam-2009-qualification-b/
CC-MAIN-2019-35
refinedweb
834
90.5
Review of the HttpClient for C# Developers Introduction In more recent years, developers in .NET land—who are aware of its existence—have been making use of the HttpClient class. If you haven't heard of it, or know of it but never used it, this article will take you through the basics. You'll be shown some code, so if you would like to follow along, I'll be using a .NET 4.6.2 console application. Along with that, I'll use an ASP.NET Core 1.1 Web application that will service our need for some end points to grab some data from. Getting Started Figure 1: The project setup The ASP.NET Core project was created using the default webapi template, set with no authentication using MVC. You can confirm if MVC is in use by looking in the startup.cs; in the configure method, you'll see… public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration .GetSection("Logging")); loggerFactory.AddDebug(); app.UseMvc(); } On creation of the project, you should also find a ValuesController, already created for you. I've edited mine to look something like this… [Route("api/[controller]")] public class ValuesController : Controller { // GET api/values [HttpGet] public IEnumerable<string> Get() { return new string[] { "Hello", "from Code Guru" }; } } So now, we have a basic Web API from which we can grab a little data from our console application. If you want to run this, just to make sure it's working, I recommend opening a command project at the location of the project, and type: dotnet run If everything is good, you'll be presented with what you see in Figure 2. Figure 2: The ASP.NET Core application running If you navigate to the following URL via your browser,, you'll see the response as we defined in your controller. If you're all good to go, let's move on to the console application and see the HttpClient in action. The HttpClient To start with, let's do a simple get on the endpoint we created, and observe the results from our console application. My Main method looks something like this… static void Main(string[] args) { GetAsync().Wait(); } static async Task GetAsync() { using (var httpClient = new HttpClient()) { httpClient.BaseAddress = new Uri(""); var results = await httpClient.GetStringAsync("api/values"); Console.WriteLine(results); } } Note here that the HttpClient implements IDisposable, and therefore a using statement can be taken advantage of here to clean up the resources for us implicitly. And, if we run this console application, while running the ASP.NET Core application, we can observe behaviour such as show in Figure 3. Figure 3: The console application running in tandem with the Web API Let's go ahead now and return something that we are not expecting. This could be a response given when a resource is not found. I've altered the code to look like this… [HttpGet] public IEnumerable<string> Get() { //return new string[] { "Hello", "from Code Guru" }; Response.StatusCode = 404; return null; } We have nothing to return because the resource was not found. But, how does the HttpClient.GetStringAsync() method deal with this? Well, it throws an exception, which we need to deal with. If we were being heavy handed, we could catch all exceptions in a try/catch loop; but this is messy and an anti-pattern. So, is there a better way to deal with this? The answer is yes! Let's look at a way to call our endpoint, one thatich allows us to manage the response in a much more ordered fashion. Consider the following code… static async Task GetAsync() { using (var httpClient = new HttpClient()) { httpClient.BaseAddress = new Uri(""); HttpResponseMessage response = await httpClient.GetAsync("api/values"); if (!response.IsSuccessStatusCode) { Console.WriteLine(response.StatusCode); } else { Console.WriteLine(await response.Content.ReadAsStringAsync()); } } } By making use of the GetAsync method rather than the GetStringAsync, our client will give us an object that we can check for success, and grab a few other bits of data, too. This is my preferred way to use HttpClient and is good for many situations when the response is not quite what we expect. Running the previous code, with the changes made to the API earlier, I can see the following output in my console window… Figure 4: Our 'Not Found' response More Verbs Moving on from what we've seen so far, let's now look at another HTTP verb, Post. The HttpClient class supports this verb, as well as put and delete. Creating a post is very simple; take a look at the following code… using(var stringContent = new StringContent ("The content of my post", Encoding.UTF8)) { HttpResponseMessage response = await httpClient.PostAsync("api/values", stringContent); } The post method expects HttpContent passed through its second parameter; for this example, I'm going with StringContent, which is derived from HttpContent, where I've passed a simple string through its constructor. All that remains is to set up an endpoint to receive this post in your Web API. I'll leave this task to your good self to complete when time is convenient for you. At this point, I'm going to conclude this article, which I hope has been useful to you. Speaking for myself, the .NET HttpClient class is a bit of a workhorse in many of my projects. It's simple and easy to implement, and covers many scenarios out of the box. If you have any questions about this article, you can always find me on Twitter @GLanata.
https://www.codeguru.com/columns/dotnet/review-of-the-httpclient-for-c-developers.html
CC-MAIN-2019-47
refinedweb
919
63.7
Fold in spark Fold is a very powerful operation in spark which allows you to calculate many important values in O(n) time. If you are familiar with Scala collection it will be like using fold operation on collection. Even if you not used fold in Scala, this post will make you comfortable in using fold. Syntax def fold[T](acc:T)((acc,value) => acc) The above is kind of high level view of fold api. It has following three things - T is the data type of RDD - acc is accumulator of type T which will be return value of the fold operation - A function , which will be called for each element in rdd with previous accumulator. Let’s see some examples of fold Finding max in a given RDD Let’s first build a RDD val sparkContext = new SparkContext("local", "functional") val employeeData = List(("Jack",1000.0),("Bob",2000.0),("Carl",7000.0)) val employeeRDD = sparkContext.makeRDD(employeeData) Now we want to find an employee, with maximum salary. We can do that using fold. To use fold we need a start value. The following code defines a dummy employee as starting accumulator. val dummyEmployee = ("dummy",0.0); Now using fold, we can find the employee with maximum salary. val maxSalaryEmployee = employeeRDD.fold(dummyEmployee)((acc,employee) => { if(acc._2 < employee._2) employee else acc}) println("employee with maximum salary is"+maxSalaryEmployee) Fold by key In Map/Reduce key plays a role of grouping values. We can use foldByKey operation to aggregate values based on keys. In this example, employees are grouped by department name. If you want to find the maximum salaries in a given department we can use following code. val deptEmployees = List( ("cs",("jack",1000.0)), ("cs",("bron",1200.0)), ("phy",("sam",2200.0)), ("phy",("ronaldo",500.0)) ) val employeeRDD = sparkContext.makeRDD(deptEmployees) val maxByDept = employeeRDD.foldByKey(("dummy",0.0)) ((acc,element)=> if(acc._2 > element._2) acc else element) println("maximum salaries in each dept" + maxByDept.collect().toList)
http://blog.madhukaraphatak.com/spark-rdd-fold/
CC-MAIN-2019-47
refinedweb
331
50.94
Autotagger The GraphLab Create autotagger tool matches unstructured text queries to a reference set of strings, a.k.a tags, which are known beforehand. Adding tags to unstructured text gives readers a quick intuition about the content of the text as well as anchors for quicker navigation and statistical summaries. Autotagging is closely related to the task of searching for user-specified queries in unstructured text, but it differs in that autotagging is typically done with a fixed set of tags, and treats the unstructured documents as queries, rather than the tags. In this chapter we autotag posts from CrossValidated, the statistics section of the Stack Exchange network. Questions posted on this forum are typically annotated with tags by the authors but responses are not, making it more difficult to quickly scan responses for the most useful information. The raw data is available from the Stack Exchange data dump. For convenience we provide a preprocessed subsample (7.8MB) in the public Turi datasets bucket on Amazon S3, which is downloaded and saved locally with the first code snippet below. For reference tags we use a lightly-curated list of statistics topics from Wikipedia. The preprocessed list is also available in the static.turi.com/datasets S3 bucket. import os import graphlab as gl ## Load unstructured text data if os.path.exists('stats_overflow_clean'): posts = gl.SFrame('stats_overflow_clean') else: posts = gl.SFrame('') posts.save('stats_overflow_clean') ## Load reference set of statistics topics if os.path.exists('statistics_topics.csv'): topics = gl.SFrame.read_csv('statistics_topics.csv', header=False, delimiter='\n') else: topics = gl.SFrame.read_csv( '', header=False, delimiter='\n') topics.save('statistics_topics', format='csv') topics.rename({'X1': 'topic'}) Here's a quick peek at the data in both the reference tags and the CrossValidated posts. There are 2,737 topics and 11,077 posts, comprising both original questions and response. The 'PostTypeID' column indicates whether a row corresponds to a question or a response, and it's clear that the responses (PostTypeID == 2) have neither tags nor titles. topics.print_rows(5) +-------------------------+ | topic | +-------------------------+ | A priori probability | | Abductive reasoning | | Absolute deviation | | Absolute risk reduction | | Absorbing Markov chain | | ... | +-------------------------+ [2737 rows x 1 columns] posts.print_rows(5, max_row_width=100) +-------------+-------------------------------+------------+--------------+ | AnswerCount | Body | ClosedDate | CommentCount | +-------------+-------------------------------+------------+--------------+ | None | Assuming you meant a binom... | None | 0 | | None | This is because you are fi... | None | 0 | | None | I think I agree, drag/drop... | None | 0 | | None | Similar to Weka, you may a... | None | 0 | | None | Scortchi and Peter Flom ha... | None | 3 | +-------------+-------------------------------+------------+--------------+ +---------------------------+---------------+------------+-------+------+-------+ | CreationDate | FavoriteCount | PostTypeId | Score | Tags | Title | +---------------------------+---------------+------------+-------+------+-------+ | 2014-06-01 00:03:48+00:00 | None | 2 | 3 | None | None | | 2014-06-01 00:09:09+00:00 | None | 2 | 1 | None | None | | 2014-06-01 01:26:06+00:00 | None | 2 | 1 | None | None | | 2014-06-01 01:29:40+00:00 | None | 2 | 0 | None | None | | 2014-06-01 01:32:17+00:00 | None | 2 | 5 | None | None | +---------------------------+---------------+------------+-------+------+-------+ [11077 rows x 10 columns] There is currently only one autotagger model, accessible through the graphlab.autotagger.create call. This method takes the reference tag data and returns a NearestNeighborAutoTagger model, which can then be queried with the unstructured text data. Under the hood, the model cleans input strings (in both the tag and query datasets), generates unigrams, bigrams, and 4-character shingles, and computes the distance between tags and queries with weighted Jaccard distance. m = gl.autotagger.create(topics, verbose=False) m.summary() Class : NearestNeighborAutoTagger Settings -------- Number of examples : 2732 Number of feature columns : 3 Total training time (seconds) : 0.0514 There are two key parameters when querying the model: k, which indicates the maximum number of tags to return for each query, and similarity_threshold, which indicates the minimum similarity from a query document to the tag. A typical pattern is to get preliminary results by setting k to 5 and leaving similarity_threshold unspecified, then run tag again using the similarity_threshold parameter for finely-tuned results. The query documents must be a single column of the query SFrame, so we first concatenate the CrossValidate post titles and bodies. posts['all_text'] = posts['Title'] + ' ' + posts['Body'] tags = m.tag(posts, query_name='all_text', k=5, similarity_threshold=0.1, verbose=True) tags.print_rows(10, max_row_width=100, max_column_width=50) PROGRESS: Starting pairwise querying. PROGRESS: +--------------+---------+-------------+--------------+ PROGRESS: | Query points | # Pairs | % Complete. | Elapsed Time | PROGRESS: +--------------+---------+-------------+--------------+ PROGRESS: | 0 | 692 | 0.00228667 | 26.525ms | PROGRESS: | 4844 | 1.3e+07 | 43.7346 | 1.02s | PROGRESS: | 9692 | 2.6e+07 | 87.4989 | 2.03s | PROGRESS: | Done | | 100 | 2.29s | PROGRESS: +--------------+---------+-------------+--------------+ +-------------+---------------------------------------------------+ | all_text_id | all_text | +-------------+---------------------------------------------------+ | 13 | neural network output layer for binary classif... | | 13 | neural network output layer for binary classif... | | 13 | neural network output layer for binary classif... | | 13 | neural network output layer for binary classif... | | 13 | neural network output layer for binary classif... | | 37 | Negative predictions for binomial predictions ... | | 55 | Estimating entropy of multidimensional variabl... | | 80 | Does the sequence satisfy WLLN? Could you help... | | 80 | Does the sequence satisfy WLLN? Could you help... | | 80 | Does the sequence satisfy WLLN? Could you help... | +-------------+---------------------------------------------------+ +---------------------------------------------------+----------------+ | topic | score | +---------------------------------------------------+----------------+ | Binary classification | 0.15503875969 | | Artificial neural network | 0.107913669065 | | One-class classification | 0.101449275362 | | Neural network | 0.100775193798 | | Multiclass classification | 0.10071942446 | | Negative predictive value | 0.104712041885 | | Dimension reduction | 0.101123595506 | | Law of large numbers | 0.197916666667 | | Independent and identically distributed random... | 0.186046511628 | | Convergence of random variables | 0.177570093458 | +---------------------------------------------------+----------------+ [1356 rows x 4 columns] Note that the score column in the tags output is a similarity score, unlike the radius parameter in many other tools in GraphLab Create. The similarity in the autotagger is simply 1 minus the weighted jaccard distance, so setting the similarity_threshold to 0.1, for example, requires that all output query-tag matches have a weighted jaccard distance of no more than 0.9. In these particular results we see that that a post that appears to be about "binary classification" indeed receives this topic as its top match, while the post about the weak law of large numbers (WLLN) is appropriately tagged with "Law of large numbers." Post-processing of the autotagger toolkit generally involves straightforward SFrame operations. For example, suppose we want to compare our model-generated tags to the human-generated ones attached to original question posts. To do this we first filter the unstructured dataset of posts by post type, then unstack the tags output to get a list of tags for each query in a single row, and finally join the original posts to the tags. tags.rename({'all_text_id': 'id'}) tags = tags[['id', 'topic']].unstack('topic', new_column_name='topics') posts = posts.add_row_number('id') tags = tags.join(posts[['Body', 'Title', 'Tags', 'id']], on='id', how='left') print tags[0] {'Body': "I'm using a neural network for a binary classification problem. Is it better to have one neuron in the output layer or to use two, i.e. one for each class? ", 'Tags': ' ', 'Title': 'neural network output layer for binary classification', 'id': 13, 'topics': ['Binary classification', 'One-class classification', 'Artificial neural network']} In this particular example, both the human and the autotagger used a neural networks tag, while the human also attached a more general "machine learning" tag, and the autotagger included a "binary classification" tag.
https://turi.com/learn/userguide/data_matching/autotagger.html
CC-MAIN-2017-09
refinedweb
1,174
50.53
Grab-pull panning in mapping services does not work in QtQuick 2.0 and QtWebKit 3.0 The following simple .qml when run in Qt QmlScene will display a map from Bing maps or Esri online maps, but in both cases you cannot pan using the grab-pull method that works with the same service in a browser. Google Maps doesn't seem to display anything at all. The normal web-type controls on the page, i.e. the "zoom-in" slider of each service will work. Also, using the mouse wheel to zoom in and out works. The up, down, left and right, cursor keys will pan the map. It seems that the mouse button messages are not being passed through to the web page. This web page business is pretty much of a mystery to me, so I don't have much of an idea what is going on. I've also tried the same urls using QtQuick 1.0 and QtWebKit 1.0 in Qt Qmlviewer. The results are pretty much the same except for the circle control with the "N" in it at the top-right of Bing Maps. In WebKit 3.0 clicking on one of the direction arrows in the control will "pan" the map a few pixels, but holding the left mouse button down has no effect. In WebKit 1.0 holding the left mouse button down pans the map continuously. Thanks for any help or suggestions. @ import QtQuick 2.0 import QtWebKit 3.0 Rectangle { id: root width: 1800 height: 900 WebView { id: mapView anchors.fill: parent url: "" // url: "" // url: "" } } @
https://forum.qt.io/topic/35415/grab-pull-panning-in-mapping-services-does-not-work-in-qtquick-2-0-and-qtwebkit-3-0
CC-MAIN-2018-22
refinedweb
268
86.3
Barcode Software barcode generator code in vb.net <atlas:ScriptManager in .NET Draw Data Matrix in .NET <atlas:ScriptManager aren t persistent; a transient object has a limited lifetime that is bounded by the life of the process that instantiated it. Almost all Java applications contain a mix of persistent and transient objects; hence we need a subsystem that manages our persistent data. Modern relational databases provide a structured representation of persistent data, enabling sorting, searching, and aggregation of data. Database management systems are responsible for managing concurrency and data integrity; they re responsible for sharing data between multiple users and multiple applications. A database management system also provides data-level security. When we discuss persistence in this book, we re thinking of all these things: launch android barcode scanner asp .net Using Barcode recognizer for width .net framework Control to read, scan read, scan image in .net framework applications. BusinessRefinery.com/barcode use rdlc reports net barcode maker to deploy barcode in c# reports BusinessRefinery.com/ bar code The previous query looks for a single, unique Employee entity named Dave. The query is executed when the getSingleResult() method is called. This method expects that the call will return only one result. If no result is returned, the method throws a javax.persistence.EntityNotFoundException runtime exception. If more than one result is found, a javax.persistence.NonUniqueResultException runtime exception is thrown. Since both of these exceptions are RuntimeExceptions, the example code is not required to have a full try/catch block. generate, create bar code function none for vb projects BusinessRefinery.com/ barcodes how to create barcode ssrs 2008 generate, create bar code append none on .net projects BusinessRefinery.com/ barcodes <typeAlias alias="MapCacheController" type="com.domain.package.MapCacheController"/> using automatic birt reports to receive barcodes on asp.net web,windows application BusinessRefinery.com/ barcodes using barcode encoding for swing control to generate, create bar code image in swing applications. click BusinessRefinery.com/ barcodes The markup shown in listing 2.1 is going to produce a pretty boring and run-of-themill ASP.NET web page. The asp:Repeater q is bound to a collection of shirt data so that it renders a list of products available. The repeater renders your business data with the eval statements w. to include qr-code and qr-code data, size, image with excel microsoft barcode sdk visual basic BusinessRefinery.com/QR-Code to generate qrcode and qr barcode data, size, image with visual c# barcode sdk barcoder BusinessRefinery.com/QR Code 2d barcode In this code snippet, you obtain a PdfGraphics2D object from a PdfTemplate. This makes it easier to position the chart on the page. qr code jis x 0510 size lowercase on .net BusinessRefinery.com/qr barcode qrcode data simplify for office word BusinessRefinery.com/qr bidimensional barcode AppFabric is arguably the most mature part of Windows Azure, at least if you measure by how long it has been publicly available, if not broadly announced. AppFabric started life as BizTalk Services. It was seen as a complementary cloud offering to BizTalk Server. BizTalk is a high-end enterprise-grade messaging and integration platform, and indeed the services fit into that portfolio well. Some joke that it was called BizTalk Services as a clever way to keep it a secret, because BizTalk is one of the most underestimated products Microsoft has. Just ask a BizTalk developer. When Windows Azure was announced at PDC 2008, the BizTalk Services were renamed to .NET Services. Over the following year, there was a push to get developers to work with the services and put the SDK through its paces. Out of that year of realworld testing came a lot of changes. When Windows Azure went live in early 2010, the services were renamed again to Windows Azure platform AppFabric to tie it more closely to the Windows Azure platform. Some people were confused by the older .NET Services name, thinking it was just the runtime and base class library running in the cloud, which makes no sense whatsoever. using copy web form to draw qr code with asp.net web,windows application BusinessRefinery.com/qrcode to use qr codes and qr code 2d barcode data, size, image with excel barcode sdk height BusinessRefinery.com/QR Code JIS X 0510 Name: Frilly Blue Shirt Description: A Frilly Blue Shirt using examples asp.net webform to attach pdf 417 on asp.net web,windows application BusinessRefinery.com/barcode pdf417 font report rdlc barcode code 128 generate, create code-128c scanners none in .net projects BusinessRefinery.com/code-128c configuration). Beyond these default properties, you can pass any property to the JNDI InitialContext object by concatenating the property name after hibernate.search.worker.jndi. For example, to set java.naming.factory.url and pass it to the InitialContext object, use the following syntax: java data matrix generator free download generate, create ecc200 programs none in java projects BusinessRefinery.com/Data Matrix using barcode creation for word document control to generate, create gs1 datamatrix barcode image in word document applications. developed BusinessRefinery.com/data matrix barcodes We now have the results of our database query in an XML document, and we are going to navigate through its elements using JavaScript s DOM API. We can easily jump to a particular element in the document using a function called getElementsByTagName(). This function uses the element s name to look it up in the DOM, somewhat like the alphabetical tabs that stick out in an old-fashioned Rolodex. Since many elements in an XML document can have the same name, getElementsByTagName() actually returns an array of elements, in the order that they appear in the document. c# pdf417 metro ebp generate, create barcode pdf417 wave none for .net c# projects BusinessRefinery.com/PDF 417 crystal reports 8 0 barcode 128 generate, create code 128 code set a quantity none on .net projects BusinessRefinery.com/code 128c Project | ssrs insert code 39 barcodes using license reporting services 2008 to include ansi/aim code 39 with asp.net web,windows application BusinessRefinery.com/ANSI/AIM Code 39 generate, create barcode 3/9 jpg none in .net projects BusinessRefinery.com/barcode 3/9 term i 2 term i Android Native Development Kit cb.setRGBColorFill(0x7C, 0xFC, 0x00); } else if (duration > 120) { cb.setRGBColorFill(0x8B, 0x00, 0x00); } else { cb.setRGBColorFill(0xFF, 0xA5, 0x00); } cb.rectangle(rect.getLeft(), rect.getBottom(), rect.getWidth() * duration / 240, rect.getHeight()); cb.fill(); cb.restoreState(); } } This code snippet will work because Times-Roman is one of the font families that is supported by default by the font factory; so are all the standard Type 1 fonts. It won t work with other fonts, unless they are registered. import org.hibernate.HibernateException; import org.hibernate.SessionFactory; Iteration (Looping) Statements | Listing 8.5 The @Column annotation Jpeg2000 ImgRaw More Data Matrix on .NET barcode generator code in vb.net: Figure 10.11 The IIS Manager allows us to create Virtual Directories and use them to host websites. in .NET Encoder Data Matrix 2d barcode in .NET Figure 10.11 The IIS Manager allows us to create Virtual Directories and use them to host websites. barcode generator code in vb.net: asp:Content ContentPlaceHolderID="Main" ID="Content1" runat="server" in .NET Printer DataMatrix in .NET asp:Content ContentPlaceHolderID="Main" ID="Content1" runat="server" barcode generator code in vb.net: NOTE in .NET Produce 2d Data Matrix barcode in .NET NOTE barcode generator code in vb.net: INTRODUCING PORTALS AND WEB PARTS in .NET Paint Data Matrix ECC200 in .NET INTRODUCING PORTALS AND WEB PARTS barcode generator source code in vb.net: INTRODUCING ADVENTURE WORKS CYCLES DATABASE in .NET Produce datamatrix 2d barcode in .NET INTRODUCING ADVENTURE WORKS CYCLES DATABASE barcode generator code in vb.net: Method named Fill is defined on interface in .NET Generate Data Matrix ECC200 in .NET Method named Fill is defined on interface barcode generator code in vb.net: EXPLORING WEB PARTS in .NET Create Data Matrix in .NET EXPLORING WEB PARTS barcode generator code in vb.net: NOTE in .NET Make gs1 datamatrix barcode in .NET NOTE barcode generator code in vb.net: Figure 2.8 IWebPart members displayed on a web part. in .NET Render Data Matrix barcode in .NET Figure 2.8 IWebPart members displayed on a web part. barcode generator code in vb.net: UNDERSTANDING WEB PART INTERNALS in .NET Receive Data Matrix ECC200 in .NET UNDERSTANDING WEB PART INTERNALS barcode generator code in vb.net: ADDING WEB PARTS TO THE ADVENTURE WORKS SOLUTION in .NET Creation data matrix barcodes in .NET ADDING WEB PARTS TO THE ADVENTURE WORKS SOLUTION barcode generator code in vb.net: DISSECTING CONNECTIONS in .NET Implementation Data Matrix ECC200 in .NET DISSECTING CONNECTIONS barcode generator code in vb.net: SORTING OUT CONNECTION TYPES in .NET Insert gs1 datamatrix barcode in .NET SORTING OUT CONNECTION TYPES barcode generator code in vb.net: IStringsInterface data in .NET Integrate Data Matrix in .NET IStringsInterface data barcode generator code in vb.net: USING TRANSFORMERS in .NET Generation Data Matrix in .NET USING TRANSFORMERS barcode generator code in vb.net: Importing and Exporting Web Parts Serializing and de-serializing web parts for the export process. in .NET Encode data matrix barcodes in .NET Importing and Exporting Web Parts Serializing and de-serializing web parts for the export process. barcode generator code in vb.net: PAGE DISPLAY MODES in .NET Printer Data Matrix in .NET PAGE DISPLAY MODES barcode generator code in vb.net: system.web webParts enableExport="true" /webParts /system.web in .NET Generate barcode data matrix in .NET system.web webParts enableExport="true" /webParts /system.web barcode generator code in vb.net: Add part to the page in .NET Assign data matrix barcodes in .NET Add part to the page barcode generator code in vb.net: Figure 4.6 The ModeChanger control as it appears within the Adventure Works Portal application. in .NET Display Data Matrix barcode in .NET Figure 4.6 The ModeChanger control as it appears within the Adventure Works Portal application. Articles you may be interested vb.net code 128 font: Asserting results in .NET Generation barcode 128a in .NET Asserting results c# barcode generator example: THE APP DELEGATE in Objective-C Assign QR Code ISO/IEC18004 in Objective-C THE APP DELEGATE java qr code reader webcam: Performance in Java Implementation QR Code ISO/IEC18004 in Java Performance vb.net code 128 barcode generator: The Upload Files screen with the progress bar in .NET Receive ANSI/AIM Code 128 in .NET The Upload Files screen with the progress bar .net pdf 417: Working with client components in .NET Encoding PDF 417 in .NET Working with client components java qr code generator example: INDEX in Java Integrating QR Code in Java INDEX barbecue java barcode generator: Comments welcome: Feedback, version 1 in Java Writer qr bidimensional barcode in Java Comments welcome: Feedback, version 1 how to generate barcode in asp.net using c#: Path Fill="Red" Stroke="Black" StrokeThickness="5" Data="M50,0 L100,50 50,100 0,50 z" / in c sharp Writer QR Code ISO/IEC18004 in c sharp Path Fill="Red" Stroke="Black" StrokeThickness="5" Data="M50,0 L100,50 50,100 0,50 z" / barcode printer in vb.net: | Appendix C: Stateful Session EJB: FTP Client Example in Java Implement QR Code 2d barcode in Java | Appendix C: Stateful Session EJB: FTP Client Example c# barcode creator: System.Windows.Forms.Form in vb Assign qr codes in vb System.Windows.Forms.Form barcode generator in vb.net codeproject: Renaissance of EJB in Java Encoder datamatrix 2d barcode in Java Renaissance of EJB barcode programming in c#: Writing simple custom bridges in Java Connect ECC200 in Java Writing simple custom bridges barcode printer in vb.net: | Appendix F: Java Persistence APIs: Employee Registry Example in Java Add QRCode in Java | Appendix F: Java Persistence APIs: Employee Registry Example c# barcode generator example: Shake, shake your iPhone in Objective-C Drawer QRCode in Objective-C Shake, shake your iPhone truetype tot.net code 128: The float-based layout enforced by our custom Object template in .NET Encoder USS Code 128 in .NET The float-based layout enforced by our custom Object template create barcode image c#: Redisplaying web pages in Objective-C Integrating Denso QR Bar Code in Objective-C Redisplaying web pages C# and WPF | in c sharp Implementation ANSI/AIM Code 128 crystal reports 2008 barcode 128: Bitter choices in Java Integrating ECC200 in Java Bitter choices c# barcode generator code 39: Illustration in visual C# Draw 3 of 9 in visual C# Illustration java applet qr code: Web frameworks: WebWork, Struts, and Tapestry in Java Compose QR Code JIS X 0510 in Java Web frameworks: WebWork, Struts, and Tapestry
http://www.businessrefinery.com/yc1/9/131/
CC-MAIN-2022-05
refinedweb
2,121
51.75
Shreya_Shruti 08-02-2021 Hi Team, I am having one requirement to create inventory report in excel format which should include jcr content and the components properties for 32k pages. I tried with infinity.json which will give the entire details however with this approach issue is we have to hit the url again and again for getting the properties. Could you please provide any suggestion or solutions for the same. Eg: I want all the jcr:content and the components properties of this page. Thanks in advance. @jbrar @Arun_Patidar @kautuk_sahni @BrianKasingli Anudeep_Garnepudi MVP @Shreya_Shruti My suggestion is to create a standalone Java Class (with main method) and using JCR API create and execute a query to get all you pages. Then on each page run one more query (using current page path) to get all nodes having sling:ResourceType property, this will give all components including the jcr:content of the page. Write your logic and you logic to create and add your report data to excel sheet using same class. Better break the pages in to multiple sets(by path) and run, as you have 32K pages. Below is the sample code. public class App { public static void main(String[] ag) { Repository repository = null; Session session = null; String queryString = "SELECT * FROM [cq:Page] AS page WHERE ISDESCENDANTNODE(page ,'/content/your/path') "; try{ repository = JcrUtils.getRepository(""); session = repository.login(new SimpleCredentials("admin", "admin".toCharArray())); QueryManager qm = session.getWorkspace().getQueryManager(); Query query = qm.createQuery(queryString, Query.JCR_SQL2); QueryResult resultPages = query.execute(); RowIterator pageRows = resultPages.getRows(); javax.jcr.query.Row eachRow = null; Node resultNode = null; while(pageRows.hasNext()){ // Logic } //session.save(); if you update/create nodes save the session } catch (Exception e){ e.printStackTrace(); } finally{ session.logout(); } } }
https://experienceleaguecommunities.adobe.com/t5/adobe-experience-manager/need-to-create-inventory-report-having-jcr-content-for-32k-pages/qaq-p/396354/comment-id/85287
CC-MAIN-2021-17
refinedweb
286
51.34
[adding bug-gnulib; replies can drop libvir-list] - if (command_ret != WEXITSTATUS (0)) { + if (WEXITSTATUS(command_ret) != 0) {ACK. By the way, what was the compilation failure?Thanks, pushed. The compilation failure was: virsh.c:8605: error: lvalue required as unary '&' operand Which seems weird, but this patch really did fix it. :) Aha - the darwin <sys/wait.h> contains: #if defined(_POSIX_C_SOURCE) && !defined(_DARWIN_C_SOURCE) #define _W_INT(i) (i) #else #define _W_INT(w) (*(int *)&(w)) /* convert union wait to int */ #define WCOREFLAG 0200 #endif /* (_POSIX_C_SOURCE && !_DARWIN_C_SOURCE) */ ... #if __DARWIN_UNIX03 #define WEXITSTATUS(x) ((_W_INT(x) >> 8) & 0x000000ff) #else /* !__DARWIN_UNIX03 */ #define WEXITSTATUS(x) (_W_INT(x) >> 8) #endif /* !__DARWIN_UNIX03 */ ...unsigned; };Obviously, the Darwin folks are (mistakenly) assuming that you would only ever use WEXITSTATUS with a 'union wait' lvalue; in which case, (*(int*)&(0)) is indeed invalid C (notice that they do the right thing if you request POSIX compliance with _POSIX_C_SOURCE, but since gnulib [rightfully] wants to expose and take advantage of system extensions, we can't define _POSIX_C_SOURCE). Since WEXITSTATUS should be usable on constants; it is a bug in their headers, and one that Gnulib should be able to work around. -- Eric Blake eblake redhat com +1-801-349-2682 Libvirt virtualization library
https://www.redhat.com/archives/libvir-list/2010-September/msg00268.html
CC-MAIN-2015-22
refinedweb
199
57.57
A Guide To P.I.P.S. In time, existing standards such as POSIX (IEEE 1003) grew in scope and were implemented across various platforms, and a large body of 'portable' software was developed that conformed to these standards. Recently, to enable such software to be easily ported to Symbian OS, we have introduced frameworks such as P.I.P.S. and Open C that overlay native Symbian OS APIs with standards-compliant wrappers. These enable you to reuse your existing (standards-compliant) code when developing software for Symbian OS. P.I.P.S. and Open C are primarily porting aids that help you port POSIX-based software to Symbian OS, quickly and efficiently. What is P.I.P.S. and Open C? P.I.P.S. (a recursive acronym for P.I.P.S. Is POSIX on Symbian OS) is a set of standard libraries that enable you to write and build POSIX-compliant code on Symbian OS v9.x. Available for both the S60 3rd Edition and UIQ 3 platforms, it comprises the four 'base' libraries - libc, libm, libpthread and libdl - and related programming constructs (several of these are emulated only, and you should read the following sections carefully to understand the extent of the support available). Despite some limitations, P.I.P.S. can substantially reduce the time and effort required to port POSIX-based software to Symbian OS. Open C is a set of additional libraries built on P.I.P.S. and supplied by Nokia for the S60 3rd Edition platform only. The libraries provided are libssl, libz, libcrypto, libcrypt and libglib. These libraries are ported from their open source versions and provide the same interfaces. P.I.P.S. add-ons are libraries and tools that extend P.I.P.S.. The first of these is the libz port for UIQ 3 platforms; other libraries that debuted in Open C will follow. Utilities such as telnetd and zsh are also part of this set and are discussed later in this manual. Figure 1 is a block diagram that shows the P.I.P.S. and Open C environment architecture. The P.I.P.S. libraries and some add-ons are included in Symbian OS from version 9.4 onwards, and so will be available on the device (S60 devices based on S60 3rd Edition, Feature Pack 2 and later). For earlier Nokia devices, based on Symbian OS v9.1 – v9.3, please refer to Nokia Developer to acquire the Open C/C++ plugins. For UIQ devices, you can download and install the libraries using a SIS file that is available from here. This wiki page describes the state of P.I.P.S. and Open C in August 2008, but may mention features expected to be released after that date. It confines itself to the Standard C and POSIX features in the frameworks and does not cover Open C++, which is the new Standard C++ library introduced by Nokia to complement Open C. Documentation for Open C and Open C++ is available at the Open C website (). The Premise of P.I.P.S. What P.I.P.S. Can Do For You The premise of P.I.P.S. is twofold. Firstly, it provides engineers with a framework that substantially reduces the cost of porting applications to Symbian OS. Existing standards- compliant code will work on Symbian OS with some minor changes and a rebuild. Secondly, it provides a more familiar programming interface for developers new to the Symbian platform. It gives them something easier to cut their teeth on, before tackling the fairly steep learning curve of native Symbian C++ programming - which is required if you wish to access most device-specific features such as multimedia or telephony. In general, if you were to divide your application code into the front end (UI), the back end engine (where you can process events and data, interact with other processes, etc.) and the code that accesses peripherals (to interact with hardware such as the camera or the microphone), P.I.P.S. can usually be used to write or port across the back end engine only. UI libraries such as the X Window System or libncurses are not provided by P.I.P.S.. Figure 2 shows the P.I.P.S. back end. What P.I.P.S. is Not P.I.P.S. is not a Unix application runtime environment on Symbian OS. You cannot run an application you have compiled for your Unix desktop on Symbian with P.I.P.S.. You will, at the very least, need to recompile your application using the Symbian OS toolchain. P.I.P.S. attempts to comply with the POSIX.1 (core services) and POSIX.1c (thread extensions) standards as far as possible. However, full compliance is not possible owing to constraints imposed by the underlying architecture of Symbian OS. For example, Symbian OS does not support the fork-and-exec paradigm as it does not duplicate the calling process when creating a new one. There is no fork that returns ‘twice’ – once in the parent and once in the child – to allow you to distinguish in the same source what code runs as parent and what as child. Signals and system calls are not natively supported and can only be logically approximated. Where possible, we have documented deviations from the standards and outlined workarounds. You may find this information in documentation for the individual APIs or in manuals such as this one. P.I.P.S. does not, as yet, provide a mechanism to interact with the various phone peripherals (for example, the camera, microphone, etc.) or UI. But you can always invoke relevant native APIs to do this. We suggest that you isolate these operations into separate source files (as these need to be in C++) and link them together with the rest of your P.I.P.S.-based code (which can be in either C or C++) to create a ‘complete’ application. For a practical example, see File:Porting+TightVNC+to+Symbian+OS+using+P.I.P.S. 1 1.pdf which is a whitepaper about porting a VNC Viewer to Symbian OS with P.I.P.S. estlib and P.I.P.S. estlib is an old, partially-compliant, limited implementation of POSIX APIs on Symbian OS, which is now deprecated. Initially written to support a JVM implementation on Symbian OS, estlib does not support threading or IPC (inter-process communication), has limited process creation support, is relatively inefficient and makes poor use of underlying operating system features. P.I.P.S., on the other hand, is much more complete, up-to-date and standards-compliant. Symbian recommends that you use P.I.P.S. instead of estlib, which will eventually be retired. Please note that estlib and P.I.P.S. are not compatible with each other. This is, by far, the most common cause of problems when working with P.I.P.S.. Mixing estlib’s include paths or libraries with P.I.P.S. may lead to random build or runtime errors. P.I.P.S. Libraries P.I.P.S. provides the following standard libraries on Symbian OS: libc - Standard C and POSIX APIs - stdio, including printf(), scanf() and their variants - file IO, both buffered and raw, including fopen, open, fread, read, etc. - stdlib APIs, including environment variable support - string and character manipulation APIs - C/POSIX locale - search, sort and pattern matching APIs, including glob - IPC mechanisms, including pipes, named FIFOs, message queues, semaphores and shared memory - process creation APIs, including popen(), popen3(), posix_spawn and system - socket and networking APIs - wide character variants of most of the above APIs. libm - mathematical and arithmetic functions. libpthread - thread creation and control - synchronization primitives. libdl - dynamic load and unload of DLLs - symbol look-up by name (on Symbian OS v9.3 onward) or ordinal. Open C Libraries Open C provides the following libraries: libcrypto The OpenSSL crypto library implements a wide range of cryptographic algorithms. These are used in OpenSSL's implementations of various cryptographic protocols such as SSL, TLS and S/MIME and applications such as SSH and OpenPGP. libssl The OpenSSL ssl library implements the Secure Sockets Layer (SSL v2/v3) and Transport Layer Security (TLS v1) protocols. libcrypt Provides functions to encrypt and decrypt data blocks and to hash passwords. libglib A general-purpose utility library (from the GTK+ project) that provides many useful data types, macros, type conversions, string and file manipulation routines, and an event loop abstraction. zlib The zlib compression library provides functions for in-memory compression, decompression and verification of compressed data. Using P.I.P.S. and Open C Build Notes A Symbian OS application that uses main() or wmain() as the entry point is a P.I.P.S. application. For these applications, P.I.P.S. provides a static library to serve as glue code between the native E32Main() entry point and the user-specified main() or wmain(). When building a P.I.P.S. application on Symbian OS versions 9.1 and 9.2, ensure that your MMP file[1] contains: - /epoc32/include/stdapis as a SYSTEMINCLUDE. This is where the P.I.P.S. header files are found. - libc.lib in the LIBRARY section. This is required even if you don't use the libc API in your application. - The glue code (libcrt0.lib or libwcrt0.lib) in the STATICLIBRARY section. libcrt0 is the glue code that you need to use for applications that start with main(). libwcrt0 is the glue code that you need to use for Unicode applications that start with wmain(). Create MMP files Typical Unix and Linux applications use the make build system. To build the application for Symbian OS, you need to create MMP files from the corresponding Makefiles. Use the following basic guidelines when preparing an MMP from a Makefile. - Create one MMP file for each target binary you wish to build. - Specify the target name and type (for example, whether it’s an executable, DLL or static library) in the TARGET and TARGETTYPE statements respectively. - Specify a SECUREID and set CAPABILITY for your application or DLL. (Refer to the guide linked from the ‘Platform Security’ section for information on what these are and how to set them.) - Add the path[2] to your source files in the SOURCEPATH statement. - List all of your source files (.c and .cpp) in one or more SOURCE statements. - Add the path to P.I.P.S. header files as a SYSTEMINCLUDE. Add paths to any other header files you wish to use (for example, /epoc32/include, the path to the native headers) in other SYSTEMINCLUDE statements. - Add the path to your project header files in one or more USERINCLUDE statements. - Add the DLLs you wish to link against in the LIBRARY statement, and the static libraries in the STATICLIBRARY statement. - Use the MACRO directive to define any preprocessor defines for your project. - Use the OPTION keyword to specify custom compiler options. You can find a sample MMP file in the ‘A Simple HelloWorld’ section later in the text. You can also find a detailed description of the MMP file format and the various options available to customize your build in the Build tools reference, under the Tools and Utilities section of the Symbian Developer Library documentation that comes with your SDK. STDEXE, STDDLL and STDLIB P.I.P.S. introduced three new target types to Symbian OS v9.3: STDEXE, STDDLL and STDLIB. The Carbide.c++ IDE supports these target types. libcrt0.lib is linked in by default when you use STDEXE as the target type. To link in libwcrt0.lib instead, specify the WCHARENTRYPOINT keyword in your MMP file. The libcrt0 and libwcrt0 static libraries provide a default E32Main() for your application and invoke the main() or wmain() function, mimicking the familiar Unix programming pattern. You cannot write your own E32Main() when you use the STDEXE target type. With an STDDLL, all functions and data with external linkage (global data) are exported by default and therefore do not need explicit IMPORT_C or EXPORT_C declarations. In all three target types, symbol tables are generated and stored in the binaries, thereby enabling symbol lookup by name. For C++ code, symbol names are mangled if extern ‘C’ linkage is not specified. You need to use the mangled names when looking up symbols by name. P.I.P.S. Concepts The glue code The libcrt0 or libwcrt0 library is called the glue code and must be linked statically into P.I.P.S. applications. If STDEXE is the target type, then this happens automatically. The glue code configures the environment, inherits file descriptors, hooks up parent-child pipes and sets up command-line re-direction, before calling main() or wmain(). Although you can launch native and hybrid applications with the process creation APIs provided by P.I.P.S. (as discussed in the following section), these do not inherit file descriptors and therefore cannot be communicated with using the implicit stdio pipes in popen() and popen3(). Hybrid applications Hybrid applications are Symbian OS native applications that invoke P.I.P.S. or Open C APIs. These can use all P.I.P.S. or Open C features, just like P.I.P.S. applications, but you need to: - Remember that these, when launched with the process creation APIs provided by P.I.P.S., do not inherit file descriptors or the environment from the parent and cannot be communicated with using stdio pipes. They can still use the IPC mechanisms provided by P.I.P.S. to talk to other hybrid or P.I.P.S. applications. - Be careful about interleaving native APIs with P.I.P.S. APIs when operating on the same resource (see the ‘Interleaving P.I.P.S. and native APIs’ section), and avoid making assumptions about the implementation of P.I.P.S. APIs or data structures. The stdioserver The stdioserver allows both P.I.P.S. and hybrid applications to redirect stdio to a console, file or COM port. stdin and stdout media are set in the user-modifiable stdio.ini (previously, config.ini) file in c:\system\data.[3] Note that this file is system-wide and any change affects all processes that subsequently establish a session with the server. There is currently no provision for configuring stdio per-application[UR]. P.I.P.S. applications connect to the server during launch, and hybrid applications do so on the first operation on stdin/out (for example, printf()). Use of the stdioserver is implicit in all libc's stdio APIs, such as printf(), scanf(), getchar() and their variants. The stderr file descriptor does not use the stdioserver, unless explicitly dup-ed to the stdout descriptors. When you install P.I.P.S., stdio.ini contains some default settings for media. Check the file to see if these work for you. When a console is set as stdin/out media, a console screen pops up and overlaps your application's screen when you perform a stdin/out operation, for example, printf(). Developer Notes Current working directory The current working directory for a P.I.P.S. application is ?:\private\<SecureId>[4], where ? is the drive from which the application was launched. This has implications for applications that are launched from ROM, whose working directory is on the read-only Z: drive. If you wish to set up a different working directory, simply use chdir() at the start of your application. stderr A write to stderr in P.I.P.S. defaults to an RDebug::Printf(). On the emulator, the output appears in the epocwind.out file. On a development board, the output appears on the debug COM port. You can always redirect (dup2) stderr to another file descriptor to override this behavior. Temporary files Temporary files created by libc APIs are stored in c:\private\<SecureId>\tmp. Timestamps P.I.P.S. only supports the time of last data modification (st_mtime) on files. The time of last access and the time of last status change (st_atime and st_ctime) are not supported and are always set to st_mtime. Heaps Heaps on Symbian OS can be specified per-thread, unlike in Unix systems where a heap is always process-wide. The native class for threads on Symbian OS is RThread, and it is documented in the Symbian Developer Library found in your SDK. Threads on Symbian OS can be created with their own heap, can share the heap of the creator thread, or can use a separate heap through an RHeap object. If you use an RThread with a separate heap in your application, you cannot malloc() some memory in one thread and simply pass the pointer to another. The latter thread crashes when it attempts to access that pointer or free the memory. This constraint is abstracted away when you use pthreads in your application. pthreads are wrappers over RThreads, but are configured to share the same heap (the heap of the main or creator thread[5]) in a process, thereby ensuring that the malloc-and-share-pointer scenario works as expected. If you wish to share dynamically allocated memory between two threads that use different heaps, you must create a new shared heap object (an instance of Symbian OS native RHeap class), and allocate memory on that heap using RHeap::Alloc(). The malloc() and free() functions supplied by P.I.P.S. implicitly use the current thread’s heap. If you wish to use these functions with a custom RHeap, you need to make that the default heap of your thread by using User::SwitchHeap(). Internal allocations Internal objects and buffers allocated by P.I.P.S. APIs are on a private heap and do not affect the heap(s) available to user code. This heap is automatically cleaned up on application exit. Out of Memory errors Ported code must be aware that it is running in a memory-constrained environment. Out of Memory situations can occur and need to be handled gracefully. By default, your process is restricted to a maximum of 1MB of heap. You may increase this limit by using the EPOCHEAPSIZE directive in your MMP. See the Symbian Developer Library Build tools reference for further details about using this option. In very low memory conditions, your P.I.P.S. application may crash at launch with a STDLIBS-INIT panic. This indicates that the P.I.P.S. subsystem was unable to initialize its core components and cannot function. For similar reasons, hybrid applications may encounter this panic when they invoke a P.I.P.S. API. Buffering File IO in P.I.P.S. libc is buffered. This usually implies a faster than native performance for small reads and writes, at the small risk of data loss in the event of battery removal or other emergency power-down situations. You can use the setvbuf() API to disable buffering on a particular FILE. Pipes created with P.I.P.S. APIs are 512 bytes in size. Therefore, writes that are larger than 512 bytes are blocked until a reader reads some of the data. Limits - There is a limit of 256 open file descriptors (including those reserved for stdin, stdout and stderr) per process. This limit applies irrespective of whether you use system calls (such as open()) or stdio APIs (such as fopen()) to open files. The limit of 20 open FILEs implied by FOPEN_MAX in stdio.h is misleading. - Outside of these enforced constraints, the size of your heap (and the size of the P.I.P.S. private heap) limits the number of files you can have open. - File and directory names in P.I.P.S. can be up to 256 bytes in length. - The key_t type in P.I.P.S. is a signed integer. When specifying key_t variables as IPC identifiers (in msgget(), semget() and shmget()), ensure that their values are less than INT_MAX. - Files of more than 2GB in size are not supported in P.I.P.S.. - P.I.P.S. does not provide sysconf()[UR]. You need to look up relevant header files or peruse manuals like this one to determine resource limits. - IPC resources (for example, message queues, shared memory and semaphores) are created on the heap of the IPC server. Therefore this heap is, in effect, shared by all processes that use the IPC facilities provided by P.I.P.S.. The system-wide number of IPC objects you can have open is limited by the size of the server’s heap. Stack size The default stack size per thread on Symbian OS is 8KB. This default imposes a maximum of 128 threads per process. These limits apply to pthreads as well. You can use pthread_attr_setstacksize to set a custom stack size before calling pthread_create, but remember that this proportionally reduces the number of threads you can create in that process. For example, with stack sizes of 16KB each, you can create only 64 threads per process. Stack overflows Some P.I.P.S. APIs in libc's stdio use a large number of stack variables. If you use these APIs in your application and encounter panics that you cannot isolate[6], try increasing the default stack size using the EPOCSTACKSIZE directive in the MMP file. Inter-process communication (IPC) P.I.P.S. supports pipes (both named and unnamed), message queues, semaphores, shared memory and local file sockets (AF_UNIX sockets). All IPC mechanisms in P.I.P.S. (except for pipes and local file sockets) are implemented using a secure server (in its own separate process), and may incur a slight memory and runtime speed overhead. While setup of the shared memory area involves the server, the actual reads and writes are direct to memory and remain fast. Shared memory areas are always read-write, irrespective of permissions used during creation. This is a constraint of the native interface used to implement them. RPipe Pipes, FIFO special files and AF_LOCAL sockets in P.I.P.S. are implemented using the native Symbian C++ RPipe interface. RPipe is available on Symbian OS v9.3+ although, at the time of writing, the RPipe interface is not public. User code should not use RPipe APIs directly. For v9.1 and v9.2, P.I.P.S. and Open C installers bundle an embedded SIS that installs RPipe on these platforms. Memory mapped files There is limited support for memory maps in P.I.P.S.. PROT_NONE, PROT_EXEC and MAP_FIXED flags are not supported. Code that depends on memory maps with these properties cannot be ported to Symbian OS. COM ports When opening COM ports with open, use COM:x as the path, where x ranges from 1-n. COM:1 refers to Symbian OS serial port O. COM ports can only be accessed from the thread that opened the port [UR]. Attempting to access the port from another thread results in a panic. If the COM port must be shared between threads, you must write a proxy server in a separate thread that opens the COM port and reads or writes to it on request from other threads. You may also use the stdioserver as this proxy server by specifying a COM port as media for stdin and stdout and using stdio API for COM reads and writes. Socket options P.I.P.S. supports a subset of standard socket options and IOCTL flags. Please refer to the API documentation for the specifics. setsockopt(), getsockopt() and ioctl() will fail with ENOSUP for unsupported options or flags. P.I.P.S. supports a number of 'non-standard' socket options that enable access to native networking features. You can use these options to enumerate and query network interfaces or Internet Access Points (IAPs), choose a particular IAP, add/edit/delete routes, start or stop interfaces, configure multicasting, and so on. Here again, details are available in the relevant API documentation. Error handling P.I.P.S. maps errors from native APIs to their nearest POSIX equivalents. In cases where such translation would be meaningless, errno is set to outside the usual range: greater than _EMAXERRNO or 124. To retrieve the Symbian C++ error code, use the formula: Symbian OS Error Code = - (errno - __EMAXERRNO). P.I.P.S. APIs never leave (the Symbian C++ equivalent of throwing an exception). Leaves from the underlying native routines are trapped by P.I.P.S. and are returned instead as errors. Link files P.I.P.S. emulates symbolic links on Symbian OS; both link() and symlink() create symbolic links. Hard links are not supported. Execute permissions Symbian OS has no concept of execute permissions, and therefore the execute bit in file permissions is ignored in P.I.P.S.. If that is the only bit set in the perm parameter, open(), create(), mkdir() and similar functions fail with EINVAL. On a related note, the PROT_EXEC flag is not supported and specifying that alone as access type in mmap results in an EINVAL. Access permissions for IPC objects The P.I.P.S. IPC Server enforces some access restrictions for IPC objects. The permissions you specify when creating an IPC object must contain at least the USER bits set. Otherwise, even you (the creator) will not be able to operate on the object. If you wish to allow access from other processes (as is usual), ensure that you set the OTHER bits in the perm flag. The GROUP bits are ignored. atexit The atexit() function does not work on the emulator. It accepts function registrations but does not invoke them on process exit. This is due to a constraint with the build toolchain. Sparse files Symbian OS does not support the notion of sparse files. If you seek beyond end-of-file and write some data, the gaps in the file are filled with NULL values that contribute to the file size. IAP (Internet Access Point) name restrictions For reasons of backward compatibility, IAP names in P.I.P.S. are restricted to 49 bytes in ASCII. For names in languages with a multi-byte character set, you are restricted to 24 characters for 2-byte and 16 characters for 3-byte representations. All lengths exclude the terminal NULL character. Users and groups P.I.P.S. does not support users, groups, process groups, sessions or pseudo-terminals. Build support APIs Certain APIs in P.I.P.S. are stubs, provided only to enable builds of existing code. They either return ENOSUP or return 0 but do nothing. For example, setgid(), setuid(), setpgid() and related functions return 0, but do nothing. Likewise, the getters (getgid(), getuid(), etc.) return 0, but that return value means nothing (see the ‘Users and groups’ section). libm libm APIs do not use FPU hardware on devices that possess them (many devices do not have them anyway). libdl Symbian OS versions prior to v9.3 only support symbol lookup by ordinal number (dlsym("1")). In v9.3 and later versions, symbol lookup by name (dlsym(“foo”)) is supported on executables and DLLs with target types STDEXE and STDDLL respectively. There is, however, a binary size penalty associated with these target types. All symbols are stored as ASCII strings which can cause a noticeable increase in binary size, especially for libraries with a large number of symbols. Native constraints P.I.P.S. APIs may reflect issues and limitations with the native interfaces used to implement them; for instance, limits are usually a native constraint. Before reporting a problem with P.I.P.S., we suggest that you attempt the same task natively. If the code succeeds, it implies an issue with the P.I.P.S. implementation or your use of it, so please feel free to post a query here: Interleaving P.I.P.S. and native APIs Interleaving calls to P.I.P.S. APIs with functionally equivalent native APIs, when operating on the same resource, may result in undefined behaviour. P.I.P.S. APIs may maintain internal state across functions, which is not updated if you call a native API, resulting in incorrect or unexpected behaviour on a subsequent invocation. For example, mixing RThread APIs with pthreads is usually a bad idea, as is interleaving libc’s stdio APIs with native RFile methods on the same file. Platform Security All platform security restrictions (including data caging rules) that apply to native interfaces also apply to applications that use P.I.P.S. or Open C. For details on platform security and the implications it has for your project, please refer to pages about platform security on this wiki. P.I.P.S. applications must be signed just like native Symbian OS applications by using Symbian Signed. The same rules and procedures apply. Refer to the guide at for a description of the process involved. Common P.I.P.S. Idioms Writable static data in DLLs Writable static data (WSD) refers to any per-process variable that exists for the lifetime of the process. Typically, these are globally scoped variables, static class members or function scoped static variables. WSD is a widely used programming construct on other platforms. Symbian OS fully supports WSD in EXE, but there are issues with the use of WSD in DLLs and the practice is generally discouraged[7]. On target hardware (or phones), DLL WSD works correctly if you explicitly use the EPOCALLOWDLLDATA directive in your DLL’s MMP file. However, you are limited to 4KB of WSD per DLL. Also, a process that attaches to the DLL incurs a cost of 4KB (one chunk), even if the actual size of WSD variables in the DLL is smaller. If the DLL is linked to by several processes, this cost can be significant. On the emulator, WSD in a DLL is shared between all processes that attach the DLL, and is not per-process as you would expect. This implies that changing the value of a WSD variable in one process updates that variable for every other process using that DLL. P.I.P.S. provides a library called ewsd.dll to enable per-process WSD in DLLs on the emulator. To use ewsd.dll, you must do the following: - 1. If you have the following two global variables in your DLL: int gref = 0; int gerr = 0; create a #ifdef __WINSCW__ section and capture the WSD variables into a struct, which in the example below is named Globals. The #ifdef __WINSCW__ ensures that these workarounds are compiled in for emulator builds alone. #ifdef __WINSCW__ struct Globals { int gref; int gerr; }; #endif - 2. Include pls.h and define a getter for your global data (for example, GetGlobals()) that returns a pointer to the struct. The process local storage routine, Pls(), is a templated function that creates and returns a singleton reference to your WSD variables and ensures a copy per process. #include <pls.h> TInt InitializeGlobals(Globals* pglobals) { pglobals->gref = 0; pglobals->gerr = 0; // Initializer must return KErrNone to indicate success. // Else the Pls routine panics. return KErrNone; } struct Globals* GetGlobals() { return Pls<Globals>(KDllSecureId,&InitializeGlobals); } - In this example, KDllSecureId is the SecureId (UID3) of your DLL and InitializeGlobals() is an optional initialization routine for your global data; you can pass in NULL instead. - 3. In your code, replace the definition of each WSD variable with code snippets such as the following: #ifdef __WINSCW__ // Define getters for each WSD variable int* get_gref() { return &(GetGlobals()->gref); } int* get_gerr() { return &(GetGlobals()->gerr); } // Define macros to make the getters opaque to the rest of your code #define gref (*get_gref()) #define gerr (*get_gerr()) #endif - You can return C++ references from your getters, in lieu of pointers, but that may not be an option if your DLL code is written in C. - 4. In the MMP file, link in ewsd.lib as a dependency for your project, again guarded by a #ifdef __WINSCW__. Ensure that EPOCALLOWDLLDATA is not set for emulator builds; you should guard this directive, which is required for ARMV5 builds, with an #ifndef __WINSCW__. The InitializeGlobals() routine is invoked from within the Pls() function if it is the first time a reference is made to the global data. At that point, the pointer is not yet set to the newly created object. This can lead to issues when WSD variables are dependent on each other’s initial state. For example, if the initialization of one variable (say, A) requires a reference to another (say, B), then the initialization of A causes the getter of B to be invoked. This in turn invokes Pls() and, because the pointer is not set, this invokes the initialization routine once again, causing recursion. Your routine must therefore account for dependencies between WSD variables and order the initialization accordingly. Process creation APIs Symbian OS does not support the separate fork-and-exec model of process creation. Consequently, P.I.P.S. does not provide either fork() or exec(). If your project uses the return value from fork() to distinguish between code that runs as parent and code that runs as child, you must refactor that section of code. To create child processes in P.I.P.S., use one of popen(), popen3(), system() or posix_spawn(). Between them, they cover most typical process creation semantics: - popen() and popen3() allow you to setup stdio pipe(s) between parent and child - system() performs a no-frills process launch - posix_spawn() enables you to perform operations (open,close,dup) on the child's file table before it 'starts' - both popen3() and posix_spawn() allow you to specify a custom environ for the child. If the child processes are P.I.P.S. applications, they inherit file descriptors and environment variables from the parent. You can use wait() and waitpid() to await termination of child processes and to reap their exit status. File descriptor inheritance P.I.P.S. applications that were launched by use of a P.I.P.S. process creation API inherit certain open file descriptors from the parent. These include all regular files and pipes. Named pipes (FIFOs), sockets and regular files in the private directory of the parent process are not inherited. Timers P.I.P.S. does not support timer APIs or SIGALRM[UR]. One possible workaround is as follows: - Where you would register a timer, create a thread (TimerThread) with a higher than standard priority. In the thread function, create a RTimer and set an alarm using RTimer::After() and a TRequestStatus variable. - The TimerThread now waits on the TRequestStatus variable while the main thread continues. - When the timer triggers, the TimerThread exits the wait. It then issues a Suspend() on the main and other threads in the process and invokes the registered handler. Once the handler returns, it resumes all threads and exits itself. Please note that there are some caveats: - Context switches to and from the TimerThread may introduce some latency. Code that relies on timer resolutions of this magnitude cannot use this solution. - The TimerThread executes the handler in its context. As such, the handler cannot access resources owned by other threads (including the one that registered the handler) without prior and explicit sharing. Even with sharing enabled, deadlocks may ensue when the handler attempts to access resources locked by one of the suspended threads. Also, if the threads are RThreads using separate heaps, then the handler cannot access memory allocated by other threads. If you need to set a number of timers or a periodic timer in your code, and do not want the overhead of creating a thread every time, create a server thread at process startup and establish a session to it from your main thread. Then, all timer registrations are messages sent to the server which creates a timer, as in step 2 above, and acts on the timeout, as in step 3 above. Signals P.I.P.S. does not support signals [UR]. When porting code that uses signals, you need to modify the code to use some native asynchronous construct that approximates signaling in context. For example, you could extend the concept described in the timers workaround, provided in the previous section, to all signals. To enable signaling from other processes, the handler thread must set up an IPC facility that sender processes can use to deliver the signal. The facility needs a name that associates it with the recipient process and it also needs to be policed in order to: - ensure that arbitrary processes cannot send ‘terminal’ signals (SIGKILL/SIGQUIT) to other processes - verify that the sender process is who it claims to be - guard against malicious programs tapping into the facility from outside the framework and sending spurious signals. Export of static data from an STDEXE or STDDLL As described previously, specifying a target type of STDEXE or STDDLL causes all global functions and data in the executable or DLL to be exported. However, the import of data is not supported on Symbian OS and so you will run into linker errors if you refer to one of these data variables from your application code (that is, any code outside the module defining the global data). If you use symbol lookup (dlsym()) to access these data imports, your code will build, but an attempt to dereference the pointer returned from dlsym() will cause a panic. We recommend that you use the following workaround: - If you are working on the emulator, use ewsd.dll for your WSD variables (as described in the ‘Writable static data in DLLs’ section). - If you are working on the target hardware, define getter functions for your global data variables and export these from the module. For example, if you wish to allow access to a global variable gerrno from outside your DLL, do the following: - 1. For the variable int gerrno, define a getter routine: int* __gerrno() { return &gerrno; } - 2. Define a macro in a public header to make this opaque to the user: #define gerrno (*__gerrno()) - 3. Application code can now include the header and use gerrno transparently: gerrno = 32 printf(“%d”, gerrno) - With this change (and assuming you want to allow 'import' of gerr and gref), the code example from the ‘Writable static data in DLLs’ section should now be as follows: // Define getters for each WSD variable EXPORT_C int* get_gref() { #ifdef __WINSCW__ return &(GetGlobals()->gref); #else return &gref; #endif } EXPORT_C int* get_gerr() { #ifdef __WINSCW__ return &(GetGlobals()->gerr); #else return &gerr; #endif } // In a public header // Define macros to make the getters opaque to the application code #define gref (*get_gref()) #define gerr (*get_gerr()) Remember that, on hardware, you can access these global variables directly from within the binary module that defines them. Changes in the Development Version of P.I.P.S. P.I.P.S. is under active development. The below is a list of changes in P.I.P.S. that are being worked on at the time of writing. These will feature in a future release. Bluetooth Sockets P.I.P.S. supports Bluetooth RFCOMM sockets. In the socket API, specify AF_BLUETOOTH as the address family or domain and BTPROTO_RFCOMM as protocol. Utility functions strtoba() and batostr() convert Bluetooth addresses from string to native format and vice-versa. eselect() The eselect() function is an extended version of the standard select(). Alongside the usual fd_sets, you can also ‘select’ on a number of arbitrary TRequestStatus variables. eselect() returns as soon as one or more of the file descriptors are ready (with the specified events) or one or more of the TRequestStatus variables are completed. A timeout can be specified as well. eselect() bridges Symbian native events and P.I.P.S. operations, enabling you to support use cases such as waiting simultaneously for a network event and a key press. Configuring the stdioserver per-application To use a custom stdioserver configuration on an application level, create a stdio.ini file in the application’s private folder following the format of the system stdio.ini. Your settings override the system defaults for your application. Serial Port Access P.I.P.S. includes an RComm proxy server in the back end, allowing you to access an open serial port transparently from any thread in the process. Debugging P.I.P.S. Applications P.I.P.S. applications can be debugged just like native ones; for example, print-lining with libc’s printf() (that uses the stdioserver) or RDebug::Printf() works as expected. However, you may encounter issues on target hardware if you interleave the two and use the same COM port for both APIs. P.I.P.S. does not provide a logging API; you must roll your own or port one. telnetd P.I.P.S. provides developers with a telnet daemon and a shell (zsh) on the phone. To use telnetd, the phone requires a valid IP address assigned to an interface, for instance, BT PAN, Wi-Fi, Ethernet over USB, and so on. Simply start telnetd on the phone and telnet to the phone’s IP address from a PC. You can then launch applications, although you can only see their output or interact with them if they are P.I.P.S. applications, and not hybrid or native applications. The Shell zsh has no platform security capabilities and cannot access the private directories of applications that you launch from it. To enable access to a particular 'private' file after the return to shell prompt (for example, a log file), your application should link in the copydatafile.lib static library and invoke CopyDataToPublic(<filename>) before exiting. This copies the file to c:\shellpub\<SecureId>. You can then cd to that directory from the prompt and access the file. If the file is intended to be modified from the prompt (a configuration file, for instance) and you need the updated copy when your application runs next, invoke CopyDataFromPublic(<filename>) at the start of the application. This copies the file to your application's private directory. The file in c:\shellpub\<SecureId> is public, which means that all applications (and not just zsh) can access it. zsh can browse non-restricted parts of the file system. zsh requires the stdioserver for its console interface. This dependency may be removed in future releases. Zsh and Telnet daemon Zsh (Z shell) is a powerful command interpreter ported on Symbian OS using P.I.P.S. The combination of Zsh and Telnet daemon running on device/emulator allows users to launch a Unix-like shell from a PC running a generic Telnet client, over a pre-established TCP/IP connection between them. Zsh is created by the Zsh project - more information can be found here and an introduction here. A ready-made shell and a console interface will make a significant contribution in reducing porting costs, by using a familiar command line interface and by re-use of shell scripts. Allowing the developer to use a host PC as remote terminal greatly improves productivity. Now, developers can work with Symbian OS and its resources more closely than ever before with its plug-in feature and static library for developing their own external commands to enrich their tool box. See Zsh-Telnetd guide for further details. "Zsh and Telnetd daemon" v1.0 features a basic port of open source Zsh command interpreter v4.2.6 with set of over 50 commands, support for shell scripts, plug-in library for external commands and a generic telnet console interface. This version supports SymbianOS v9.1 and above. The latest Zsh-Telnetd files - alpha release Zsh Telnetd README (.PDF) Zsh Telnetd SDK Patch for UIQ 3.x and S60 3.x SDK Patch for UIQ 3.x and S60 3.x A Simple HelloWorld To illustrate how P.I.P.S. can help you write simple applications easily, consider the ubiquitous HelloWorld program. Writing this natively on Symbian OS involves a cleanup stack, a CConsoleBase instance, their methods and a TRAPD. P.I.P.S. abstracts several of these interfaces and internally sets up a skeleton framework that works well for most applications. This allows simple programs to remain simple. Here is a P.I.P.S. HelloWorld: // HelloWorld.c/cpp #include <stdio.h> int main(int argc, char** argv) { printf("Hello World\n"); return 0; } And here is its MMP: With P.I.P.S. on Symbian OS v9.1/9.2: // HelloWorld.mmp for P.I.P.S. // 9.1/9.2 // Software Ltd. TARGET HelloWorld.exe TARGETTYPE EXE UID 0 0x0f123456 SOURCEPATH ..\src SOURCE HelloWorld.cpp SYSTEMINCLUDE \epoc32\include SYSTEMINCLUDE \epoc32\include\stdapis // LIBRARY libc.lib // STATICLIBRARY libcrt0.lib With P.I.P.S. on Symbian OS v9.3 and later: // HelloWorld.mmp for P.I.P.S. // 9.3+ // Software Ltd. TARGET HelloWorld.exe TARGETTYPE STDEXE UID 0 0x0f123456 SOURCEPATH ..\src SOURCE HelloWorld.cpp USERINCLUDE ..\inc // LIBRARY libc.lib // Not required (implicit with // STDEXE). Endnote Like all tools, P.I.P.S. and Open C on Symbian OS address a certain niche. Your success with P.I.P.S. largely depends upon whether your problem belongs to that niche. For porting (especially of C/POSIX code), P.I.P.S. and Open C are demonstrably useful. For new code, you could choose to use P.I.P.S., but know that you may need to ‘go native’ at some point. P.I.P.S. allows you some flexibility in choosing when that point will be. However, a word of warning: P.I.P.S. and Open C abstract away some default idioms (such as the cleanup stack) and enable you to program ‘non-natively’ on Symbian OS. This can make your application prone to the sort of problems that native idioms (such as descriptors) were designed to solve. Buffer overflows, careless cleanup of allocated memory or objects on abort, dead-locked code, busy loops and synchronous high-latency operations that affect program responsiveness are all possibilities. You need to actively guard against these in your code. This is especially true when porting code from platforms that are more accommodating of poor programming or bad design. And finally, it only remains for me to wish you good luck with your porting. References - ↑ MMP files specify build instructions on Symbian OS, similar to Makefiles; see the ‘Create MMP files’ section for more information. You can also find a description of their format and how to use them in the Build tools reference, found in the Tools and Utilities section of the Symbian Developer Library documentation. - ↑ All paths must be relative either to your EPOCROOT or the location of your MMP file. For example, if your EPOCROOT is / (as is typical), your SYSTEMINCLUDE path will be /epoc32/include/stdapis. - ↑ Please note that all references to the C: drive in this manual refer to the system drive on your device. The system drive, as documented in the Symbian Developer Library, is a Read/Writable, internal and non-volatile drive on the device, which may not always be called C:. - ↑ Secure_Id (UID3) is your application’s unique identifier, set with either the SECUREID or UID option in the MMP file. - ↑ Note the ‘or creator thread’ clause. If you create an RThread with a separate heap and invoke pthread_create from that thread, the new pthread shares a heap with the RThread you created and not with the main thread of the process. - ↑ Panics occur when Symbian OS threads exit abnormally. They are equivalent to a thread-level abort on other platforms. If the thread that panics (aborts) is a process-critical thread (either the main thread in the process or a subsequently created thread that is set to ‘Critical’), the process dies as well. Each panic has a category and a reason code that help to identify the cause of the panic. The Symbian Developer Library provides a system panic reference. - ↑ For further information on WSD see here and here. Further Information Other important documents on this topic are: Original version View this document on scribd.com © 2010 Symbian Foundation Limited. This document is licensed under the Creative Commons Attribution-Share Alike 2.0 license. See for the full terms of the license. Note that this content was originally hosted on the Symbian Foundation developer wiki.
http://developer.nokia.com/community/wiki/index.php?title=A_Guide_To_P.I.P.S.&oldid=165123
CC-MAIN-2014-35
refinedweb
8,034
65.22
Plus: Huge potential with new yieldco Get the truth about credit unions Join the NASDAQ Community today and get free, instant access to portfolios, stock ratings, real-time alerts, and more! This is the seventh. Gary A. Gordon, MS, CFP® is the president of Pacific Park Financial , Inc., a Registered Investment Adviser with the SEC. He has more than 23 years of experience as a personal coach in 'money matters,' including portfolio management, risk assessment, and small business development. Gary writes regular commentary at ETF Expert . He currently hosts the ETF Expert Show. Seeking Alpha's Jonathan Liss recently spoke with Gary to find out how he planned to use ETFs - including alternative ETF strategies not frequently found in more typical investor portfolios - to position clients in 2013. Jonathan Liss ((JL)): How would you describe your investing style/philosophy? Gary Gordon (( GG )): Information processing is the best way to describe the way that I invest. I gather information (e.g., fundamental, technical, contrarian, economic, historical, etc.), select exchange-traded funds based on that information, and control the investment outcome of every decision. Information is the input, choosing ETFs with stop-limit loss order protection is the process, and the outcome is always a big gain, small gain or small loss. Whether using a hedge, a stop or a trendline for controlling the outcome of an investment decision, no big losses are permitted in portfolios. JL: I've been meaning to ask you this for awhile now. As you just noted - and frequently note in your writings, you actively manage downside risk via stop-limit loss orders but don't spell out what the exact parameters are. Do you use the same percent stops for every holding, or does it vary by fund? If it varies, is that based on riskiness of asset class, historical SD, or some other factor or set of factors? GG: Stops vary by two primary factors - the risk of the asset and the weight in the portfolio. In general, although volatility can change on any asset (i.e., [[TLT]] is a good example), fixed income assets are less risky than higher-yielding income; large cap dividend stocks are not as risky/volatile as large cap growth or small caps, which are not as risky as foreign and emerging equity and so forth. The second factor is the weight in the portfolio. If theSPDR S&P 500 ETF ( SPY ) is 10% of your portfolio, one might select a hard trailing stop at 7.5%. If SPY is only 5% of the portfolio, however, the impact on the portfolio is half as much, and a 15% stop would have the same impact. That said, 15% stops are much wider than I would ever use, and I might employ trendlines to make the sell determination. Or, I might sell ½ a position at 8% and the other half at 12%. In sum, there are many ways to reduce risk, with stops being one of them. And please don't ask when you "by back in." There are 1,500 other ETF choices to buy when you sell something. Or if one insists on buying the same asset, one can use the exact same parameters coming off a low reached from the point at which you sold - i.e. a 7.5% climb off of a low that is reached. JL: As we approach 2013, are you bullish or bearish? GG: The question is somewhat irrelevant for an information processing approach to market-based securities. Technical weakness can arise during the 2013 year, though strength and value is evident in a number of emerging market stocks. I expect many to offer double digit returns, so that may be viewed as bullish. I believe in the China turn-around theme, and am bullish on the country's Asian neighbors like Malaysia and Singapore. Pacific providers like Australia and Latin American resources standouts (e..g, Chile) should be among the leaders. On the other hand, I am less excited by high-flying emergers from 2012 like Turkey. And I am not sold on MENA (Middle East & North Africa). I expect Europe to be the source of enormous consternation yet again, and do not recommend any unhedged exposure to the region. JL: Which asset classes are you overweight? Which are you underweight? Why? GG: In U.S. stocks, I am currently overweight telecom as well as consumer staples and discretionary. I am underweight domestic common stock utilities. I like Asian country and regional stock ETFs. In income, I have zero exposure to any developed world treasuries. I am sticking with emerging market sovereign debt. I have plenty of exposure to emerging and U.S. corporates, investment grade and high yield… and believe that ETFs diversify the risk adequately. I like preferreds, excluding banks viaMarket Vectors Preferred Securities ex Financials ETF ( PFXF). In fact, most of the exposure here to income is via ETF. JL: Which benchmark do you use? GG: We manage money for all different client needs, from non-stock ultra-conservative to 100% stock ultra-aggressive, so there is no single appropriate benchmark for performance. That said, for moderate investors where we may target 65% growth/35% income in uptrending markets, and where we may be closer to 40%/40%/20% cash in downtrending markets, it'd be appropriate to benchmark against a classic 65%/35% buy-n-hold stock/bond index or a Lipper Balanced Fund average. JL: Do you mean 'capital appreciation' when you say '65% growth', or something else? Does 65% growth/35% income mean that's the stock/bond divide, or would things like high dividend stocks, REITs and MLPs count towards the 'income' side of things? Where do commodities fit in to that mix? GG: Growth is primarily capital appreciation. It does not mean that that there aren't dividends or distributions of some kind involved. It simply means that in the course of total return, one's expectation is for more of the total return to come from capital appreciation. Income is primarily interest and yield that one expects to be the larger component of the total return (on that side of the portfolio). Investment grade bonds through convertibles, high yield, preferreds - both foreign and domestic - fit the bill for 'income'. Of course there are a few exceptions. I might expect 5% growth and 5% yield from an MLP or REIT - but that is essentially growth. Here you have to take into account the volatility of the asset as well. Is the standard deviation more like a fixed income vehicle or a stock vehicle? That will be the primary determining factor. Commodities fall out on the growth side. I realize that whether you are talking about stop losses or allocation, you'd like black-n-white… but investing involves plenty of shades of gray. You wouldn't use a 200-day moving average for the S&P 500 SPDR Trust ( SPY ) to buy or sell the Global X Columbia 30 ( GXG ) or iShares MSCI Chile ( ECH ) or iShares Preferred ( PFF ) or PowerShares Bank Loan (BKLN). They all have their own trendlines for that decision-making. Same with stop-losses. Asset Allocation is the same. It's not black and white across every asset. For the post part, you can use growth when the largest contributing component to total return expectations is capital appreciation and you use income when the largest contribution comes from the expected cash flow (yield). JL: Perhaps more than any popular portfolio manager on Seeking Alpha, you have been a consistent early proponent of ETFs offering alternatives to standard market cap weighted funds. GG: Why thank you. JL: Among funds you have advocated in just the past few months are the WisdomTree Europe Hedged Equity ETF (HEDJ) which allows investors European equity exposure while hedging a declining euro as well as low volatility alternatives like Emerging Markets MSCI Minimum Volatility ETF (EEMV) and PowerShares S&P 500 Low Volatility Portfolio ETF (SPLV). How do you determine which newer products/strategies are worthy of further consideration, and which are just a passing fad? What are the minimum liquidity and AUM requirements before you seriously consider a fund? GG: I recently gave a presentation at the Global Indexing and ETF Conference in Phoenix AZ on this very topic. If you're talking about a person, a product, a business, a team or even a country, the key ingredients are the same: One part innovation, one part motivation and one part "right place, right time." So, in determining ETFs that are worthy of consideration versus a passing fad, an excellent idea must be accompanied by great timing and phenomenal fund provider commitment. It's not enough to open up shop and declare a "Small Cap Emerging Markets Materials and Infrastructure ETF" a masterpiece. Take tradability and one-stop access to the asset class in mind. $520 million in inflows in 8 months is probably a great sign that SJNK's 5.2% via 338 holdings (avg maturity 3.5 years) has a great shot at enduring. As for the idea that "low volatility" may be just a passing fad, don't expect investors to abandon "New Normal" thinking anytime soon. Sure they will lose some luster in a raging bull market, but as long as there's a place for tradable alternatives to buy-and-hold, expect money managers to look for something that diversification alone isn't able to provide - a smoother ride. And yes, that makes a staples/health care/utilities heavy iShares Emerging Minimum Volatility ETF (EEMV) a worthy alternative toVanguard Emerging Markets Stock ETF ( VWO). Average daily dollar volume for an ETF must be greater than $100,000. And I prefer ETFs with at least $50 million in AUM. JL: How much of an allocation do you feel alternative investing strategies generally deserve alongside 'core holdings'? GG: I genuinely do not view the alternatives as being altogether different than "core." If the info is pointing to non-cyclical strength, perhaps EEMV is chosen over VWO. If strong evidence is suggesting cyclical success, core ETFs likeiShares Russell 1000 Index ETF ( IWB) andiShares S&P MidCap 400 Index ETF ( IJH) would be preferable to SPLV. And if I want access to Europe, why do I need a "core" unhedged Europe likeVanguard European Stock ETF ( VGK) when the dollar-hedged HEDJ is less of a risk. JL: Which alternative equity strategies do you feel offer the best upside potential/downside protection heading into 2013 and beyond? GG: Best upside potential? If we consider Asia ex-Japan an alternative equity allocation, theniShares MSCI All Country Asia ex-Japan Index ETF ( AAXJ) fits the bill. We've already discussed EEMV. AlsoPowerShares DWA Emerging Markets Technical Leaders Portfolio ETF (PIE) is on my radar . To be clear, I don't believe in buying any investment without active management of the downside risk. I do not buy and hold for the upside potential. I always make sure that an outcome is a big gain, small gain or small loss. PFXF has downside protection built in from eliminating financial stock volatility, but even here, I actively manage downside risks. JL: How many portfolio holdings is too many to properly manage? How many is too few to offer proper diversification? GG: When it comes to ETFs, 15 tends to be the upper limit. Less than 8 is unlikely to provide enough diversification across U.S./foreign/emerging growth and income. JL: Let's revisit the fixed income space. You were also an early adopter of Emerging Market sovereign debt ETFs. Are you still bullish on these funds? Do you prefer the plain vanilla or local currency versions of these funds? GG: Honest to goodness, I think investors should be looking at all fixed income from emergers, from local currency to dollar hedged, from sovereign to corporate, from investment grade to high yield. The choices are as much about risk tolerance and diversification, and would be just as important to consider as everything in the U.S. fixed income space. Personally, I see little value in Treasury ETFs, and only consider them as a short-term safe haven move. Even then, I prefer short-termiShares Barclays 1-3 Year Credit Bond ETF ( CSJ), or money market cash. For at least as long as the world's central banks artificially depress rates, one has to look at the better yielding alternative and the historical spread. If the historical spread between emergers and U.S. treasuries were tight, I might reduce exposure. But as long as the spreads remain historically favorable, as long as technical trends tell me to stay there, emerging debt works. JL: Where have you been having retirees turn for income in this record low rate environment? How have potential changes to the tax code affected your assessment of interest-paying investments? GG: I've had to trim MLP ETFs from client portfolios. This was an asset class that I normally used as a go-to winner. Yet dividend uncertainty as well as MLP structure uncertainty has sent them into a downtrend. I haven't backed out of Muni ETFs, even with the selloff on chatter of reducing tax-exempt status for the wealthy. I will let the long-term trend and stop-losses dictate that decision. Retirees simply can't get CDs or short-term investment grade bonds to do the trick in this environment. I've simply needed to move up to intermediate and long-term investment grade, senior notes, convertibles, preferreds and emerging debt. I actively monitor the downside risk, so we are watching the possibility of interest rates rising as a catalyst to trim exposure.. GG: China's economy has already stabilized and will continue to show recovery signs. I'm not on the China hard landing wagon. It is already a soft landing from my perspective. The Eurozone is, was, and will continue to be a major problem in my book. The Middle East and Israel's diminishing patience with many of its border enemies could also create havoc. JL: Do you believe gold and other precious metals are a genuine hedge in uncertain markets? If so, how much exposure do you have? GG: Yes I do, but 5% is the most direct exposure ([[IAU]], [[GLD]]) I place in portfolios. There may be some indirect exposure at times. JL: What advice would you give to a 'do-it-yourself' investor in the present investing environment? GG: Keep costs as low as possible by using ETFs, and where possible, no cost trading of those ETFs. TD Ameritrade has more than 100 that trade at no cost. Strive for a total portfolio yield that is at least 2x the current 10-year treasury yield. That's a good yardstick, if your cash flow is 3.5% when the 10-year is 1.75%. Also, spend at least 45 minutes a week, perhaps on Friday, making sure that your individual positions remain in a long-term uptrend. If not, consider the circumstances under which you would sell that position to secure a big gain, small gain or small loss. In that manner, you won't ever have the one bad apple that spoils your entire basket. To read other pieces from Seeking Alpha's Positioning for 2013 Smoke And Mirrors In The Herbalife Saga?
http://www.nasdaq.com/article/gary-gordon-positions-for-2013-alternative-etf-strategies-for-everyday-portfolios-cm202605
CC-MAIN-2015-11
refinedweb
2,556
64.1
Shake...! Eminem and Nate Dogg star in Bebe’s Kids part 2. For real. They hardly did a damn thing to Robin Harris’ character for this video. They just put a bandana on and gave him the chiefy eyes. Every time he approaches someone he looks like he's going to blurt out "Test-tube BABY!" They should definitely continue this series. The Adventures of Trailer Trash and Janitor could be something special. This is a good look for Nate, being portrayed as an equal of sorts. It's been a while! Even brain dead ass Snoop Dogg makes Nate play in the sandbox with Warren G in favor of that senile, filthy sack of gonorrhea Bishop Don Magic Marketing Tool. The D-12 boys only get to play the background and come up for air when Ricky Schroeder’s shoes are sparkling. While this video is most definitely dumb shit, it’s good to see some dudes taking themselves lightly without crossing the coon border. Unfortunately, they use the ever-distracting “extra shit in the widescreen margins” format. So minus 2 points for the Shady camp. This video portrays perfectly why I avoid the club scene… especially skrippin clubs. Niggas get drunk and push hideous hoes ass-first through their car windows. They don’t even open the doors. I can't be around that element anymore. I'm trying to get my life back together and shit. Is that 40 Cent comin up for air in the passenger’s seat with yet another tube top on? Okay, now this video is complete. Questions? Comments? Requests? Ever climb into the night like “Cool World?” ronnie_mexxx@yahoo.com Goin to the skrippin club this weekend? Myspace me! Ehhh?....I don'taaa.... eh? What? First... another classic blog ..Ron...keep up the funny stuff and for all you g-unit people...lighten up ...you dont work for them... Ron put up your address on here so i can see if you can talk all that shit to me in person Whats up fellas, Any chicks you know that would love to experience the making of the before and after of an abortion. Just let me know. I gotta go that's J-Ho calling to tell me the good news, our fourth abortion was a success and she is planning on flying me (Private jet, rolls royce phatom, champagne..the usual) to hawaii for a weekend celebration which will include an all night brutal anal session and possibly the beginings of a fifth abortion. IM A MOTHERFUCKIN P.I.M.P!!!!!!!!! Why does Eminem look 14 in that picture? "Is that 40 Cent comin up for air in the passenger’s seat with yet another tube top on? Okay, now this video is complete." Hahaha funny shit. Ron put up your address on here so i can see if you can talk all that shit to me in person Posted by: shakeem at April 19, 2006 10:40 AM ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Shakeem, don't take none of this shit personal--- it's just... COMMMMMMMMMMMMMMMMMMEDY! If you scrap with a nigga over a blog homie, you have officially gone over the deep end-if you really had a 55k job and drive a 740 Bimmer and date a bad broad, you would definitely NOT risk that for a trip to the bing. SOAP DROP NIGGA, you ain't even wash behind yo ears-LMAO Considering he is 50's boy--anybody got money on whether he would bail him out-anyone...anyone? Yeah fam just stick to that cubicle and keep it moving... 'anybody got money on whether he would bail him out-anyone' Bang'em says NO!!! Nigga won't even put money on his books for a calling card. This video is different. It ain't like something Em would put out. It's cool that it's a cartoon, but...they probably gonna show it on BET UnCut or something. Lil' kids ain't allowed to see videos like this. The Hate is embarrassing for Real Grown Men !!! Ron Mex must've use to work for Shady or G-Unit ??? Now he got a side job with Wackstreet washing Chuck B. More's thongs !!! Nah, I'm the pied piper. You children follow me daily. What did Mike Tyson say? Fuck you til you love me? P.S.: Guice... You wanna know what Eminem's response was the first time he read one of my blogs? He contacted the office and wanted to write with us... and did. Has 50 called you and Shakeem to thank you guys for the backup yet? Shhhhhhh. Go to sleep now. Oh yeah. The Ron Mexico Show coming soon, kids. We ain't goin nowhere. Muah.... Yo Ron why you calling my Uncle Don all out his name and shit? Filthy Sack of Gonorrhea?? (LMAO) but that's still my Uncle dog. One of Chi-Town's legends. Anyway, ain't Ron Mexico the gay alias for Mike Vick? Or not the gay alias, but wasn't he using that name to get out of infecting somebody with some kind of VD? Ron, For your information, Young Guice is part of 'The Unit 'Net Team', working under Shakeem's supervision, Who was recently promoted to Executive blogger, in the 'Gunit bloggin Department', which Mr.Jackson owns(hmm... I smell more $$$ in the Bank)... so don't underestimate all the paper these guys are around. And while you, RON! have to spend $16 on that new bloodmoney dropping May 2nd,(FIRE!) Shakeem already got all the previews, and he's coppin' 'the unit promotion CD' which mean 3 copies for the price of 1!!! Plus He got the exclusive, which is not out in stores for the public(RON!!!) Dildo, made by 50, expected to hit stores in Fall. He actually received a double-headed one, which has 50's ORIGINAL DICK size on one end, and the other end has Olivias....batteries Included!!!... Wow! I just watched a 4 minute commercial for date rape. I guess they thought animating would show the humorous side of carrying a passed out girl to your limo for... Sidesplitting! Anyways, can anyone explain to me why Eminem chose to give Nate the posthumous video treatment. You know when a rapper passes and they want to put a video to a long lost track they put him in cartoon. Damn, Nate is still living why'd you do that Eminem? 2 points, D! That video is stupid as hell. Why is Eminem puttin' out bulls--- videos like this? This ain't him. This ain't him at all. At least we know he likes ass and ain't afraid to show it. The song itself is catchy. Too bad ain't gettin' much radio spins. Is it me, or did Nate Dogg outshine Em on his own s---? Man i read that someone was going to fight over this stupid ass blogg, damn now that is worse then proof shooting ol boy over a pool game!! Ron is a funny dude but don't let him get under your skin he is just doing what funny people do make JOKES, and another thing STOP DICK RIDING! Inless your Gay and that is your thing, but if you like pussy please stay off these grown mens DICK! What is this???? Ass Like That Remix?? I think Em is trying to stay away from the camera..... Example: Mockingbird,Ass like that(hardly in it),Shake Dat, Mosh He's trying to get that Cartoon Network Money.lol Whats wrong Em? Oh my god... I have so much to say... but it's mean... I don't know if I should say it... should I say it?... I gotta say it, it's my duty as the human music-video-Hibachi to clown all would-be masterpieces, then promptly go upside the back of their head with panty-ho stuffed with a sock. - That must be why Eminem is divorcing Kim, she wouldn't let him use real ho's for this video. - Didn't Em call Ja out for poppin E? - Those cartoons look so much like the real thing, I didn't even realize it was animated until that girl was about to give that Fat Albert look-alike a hummer. - Now I know Eminem has lost it, Nate Dogg hasn't been on a hit song since Holidae Inn. - This is without a doubt, the one video that I can say is worse than the one for Holidae Inn, except of course, for Master P's "Get the Party Crackin" (I lost more brain cells watching that video than M.P and Silkk did while making it). - Come to think of it, this video looks almost exactly the same as "Get the Party Crackin", now I think Eminem's not even trying anymore. - Now we know what Chef is doing after he left South Park -- doubling for Nate Dogg in gay cartoons. - They left the club with 4 guys, and only 2 girls. What is this, a Heather Hunter video? I want to make it clear to everyone that all of my remarks are made strictly in fun. I mean no disrespect to Eminem at this point in time, as I completely understand what it's like to lose your best friend. You just gotta keep ya head up. No homo. Gotdamn, this is some wack 'Gorillaz' bootleg shit. Somebody actually took the time to draw & animate this? Iovine actually gave this vid the thumbs up? Eminem is still rappin' post-Encore? Em even slaps his own stans in their faces like "I don't rap about shit anymore and you still buy this?" and all they do is nod. SMH dusts off nate dogg LOL ... song SUCKS ! havent seen the video n dont wanna . eminem is CORNY . Cage should have finished him when he had the chance . i actually aint hatin though , i do like some eminem stuff even some of the corny stuff like rain man just this song (shake ...) just is a terrible record n only morons like it . um sorry but its tru i just can't wait until cadallac don comes out with his video (inside peanut butter, outside jelly) just to see what is said about it. ONE MORE TIME: WHY WOULD ANY SELF-RESPECTING BLACK PERSON RECORD WITH EMINEM AFTER THE RACIST BITCHZINO TAPES SURFACED. EM DISSED BLACK WOMEN AND SHOWED NO REMORSE WHEN CALLED ON IT!!!!!!!!. FUKK ANY AND ALL UNCLE TOM, STEP'N'FETCHON, SHUCK & JIVE COONS WHO STAND WITH EM!!!{50 G-UNIT,D12} ANYONE WHO FEELS OTHERWISE CAN PUT ON BLACKFACE AND SING MAMMY!!!! All you rappers from the south need to PUT T.I in his place and let him know he is NOT the king, and he don't run SHIT. Scareface, Luda, Outkast, Ghetto Boys, 3-6 mafia, 8Ball and Mjg, Bun B, Pimp C, FLip, Trick Daddy, Trina, Lil Wayne, B.Gizzle, Juv-E Master P and any other mutherfucker that is in the rap game, STAND the fuck up for yourself, Battle T.I don't let him go around and say he is the KING of the south I might be able to see the KING of ATL (the movie) LOL But Don't let this FAG call himself the KING of the SOUTH. cuz it is just making you look like a punk. damn if anyone says some shit about g-unit, shakeem will come out of 50's ass and start a bitch fest. EMINEM IS JUS HAVIN FUN...CALLING OUT AT SHAKEEM...I WANT TO JOIN THE GUNIT ROSTER....TALK ABOUT BRINGING THE UNIT TO EAST AFRICA...IT WOULD BE AWESOME...I'L WORK ON THAT...N U ALL CAN HATE ON SHAKEEM IMPERSONATE HIS NAME IN THIS BLOG...BUT THE FACT IS CURTIS MOTHERFUCKING BILLION DOLLAR JACKSON IS THE MOST SUCCESSFUL BLACK ARTIST.....U ALL SAY HE HAS NO SKILLS AS A MC BUT WHEN HE WAS DOIN HIS MIXTAPES BACK THEN...U PEOPLE DIDNT SAY HE WAS WACK....AS USUAL KENYA WON DA BOSTON MARATHON MALE N FEMALE in response to the boston marathon!!yeah they were chasin bitchzino's faggot ass Hahaha... Eminem is cross dressing in videos again! Nate definitely outdid Em on this too hahaha... Bari the Kenyan: It is not usually my policy to go after such small potatoes, but one thing you said bothers me. You indicated that because 50 has made so much money, that he truly has skills. This line of thinking is incorrect in every aspect, granted that 5 years ago he did have skills. Success changes the best of them though, and 50 was no exception. As far as the money-equals-greatness concept, well, you need to get your facts straight. Nelly has sold more records and made more money than 50, does that mean he's one of the greatest? Maybe to Pretty Ricky fans, but anyone who knows their music will tell you otherwise. christina milian - say i . jeezy kills that verse I really had to search in net after I watched "the flashmovie" to see if I'm the only one who things this shit sucks... Guess what, I'm not alone. Funny shit Ron! Laughed my ass of... I don't understand what you are all saying? But i just wanna say that video is fucking wrong. It makes "date rape" look funny. SICK FUCKERS. When will black shit "music" end. You can't be 30878 serious?!? Eminem is the Best With Shady Records the Others Is The Loser Eminem And Sahdy is the Best Hip-Hop//Rap and to retail them again. The greater part of farmers could still >creative wedding scrapbook layouts number. So that there may be in Europe at present, not only more jevbuaumpp years, amused the public with most magnificent accounts of the profits to be >generator layout myspace paintball times, if you except the king of Prussia, to accumulate treasure pkkqjxvgcf than they otherwise could get for them, you raise, not only the >country music posters for my space page capital of all such master artificers, however, is circulated either in the and their expense comes to be regulated by the same extravagant >fear and loathing my space layout sent ambassador from the king of France to one of the sons of the for exportation, no part of this duty is paid up if entered for >lynryd skyryd my space layouts but they did not, in any sensible degree, increase the real value smuggling, and raise the value of those metals in other countries >my space comments graphics to the market, is always attended with a considerable profit of money do not always prove that the usual number of gold and >my house from outer space The capitals employed in the agriculture and in the retail trade of any it the money of that country becoming necessarily of so much >adult my space graphics Virginia and Maryland with a part of the surplus produce of British cultivation of the most fertile fields in their own neighbourhood, I shall >my space home and away to whom they were addressed. They were addressed by merchants to have been in the actual state of the crop. Even upon this very >comments for my space of the surface of the earth which extracts the minerals from its bowels. tenant must always pay the rent out of some other revenue, which he derives, >my space and survey provisions sufficient for a voyage to a distant sea but the business. The retailer himself is the only productive labourer whom it >animated christmas lights myspace layouts rather, it must have borne a greater proportion, because there xmetjdcsed balance of employments, but to render the work which is done in >gaia online profile layouts which are necessary for supplying the place of money. The annual stock which he employs in this manner, but a part of the stock >free myspace profile layouts dearth, but the most effectual preventive of a famine so would the greater part, more than two-thirds, of the produce of the >myspace layouts and profile editing more English money to Holland, as this difference amounted to The consideration of his own private profit is the sole motive which >nana anime myspace layouts forth of the kingdom. The like policy anciently took place both augment its annual produce to the utmost, and thereby to increase >pink coach myspace layouts considered as a very high price, yet, in years of scarcity, it is it would require, at five guineas a-ton, a million of tons of >anime backgrounds codes for myspace When the capital of any country is not sufficient for all those three supply it, being generally afraid lest their goods should be left >stop child abuse free layouts for myspace quantity of gold, a packet-boat could bring from Lisbon, or from profit which he might otherwise have made, but he exposes the >myspace free layouts codes The enormous expense of the late war, therefore, must have been the finer and more improved manufactures such as contain a great >mygirlyspace All the improvements in machinery, however, have by no means been the xmetjdcsed Those arguments were partly solid and partly sophistical. They >public record criminal records free background checks government, or those who acted under them, contracted with a kszsvfnqgk probable, would, according to the present proportion, exchange for more silver in coin than it >cool punk rock backgrounds those laws might have brought upon the people, would probably Every man is rich or poor according to the degree in which he can afford to >kingdom hearts 2 backgrounds divide the inconvenience of it as equally as possible, through were obstructed by the laws as they then stood. To the judges who >ps3 wallpapers xmb backgrounds and the value of its annual produce diminish. The land and labour of Great be worth the conquering. Among the Tartars, as among all other >free history powerpoint backgrounds nature, that the wealth which consists in them cannot be much country, and begin to decay upon the return of its prosperity. >reports criminal record background checks public records greater advantage over an equal capital employed in the carrying trade. The produce of land, which, in every period of improvement, must bear >cute winnie the pooh backgrounds The different quantities of productive labour which it may put into motion, over-trading becomes a general error, both among great and small >country girl layouts for myspace taking much farther notice of their supposed tendency to bring were sophistical, too, perhaps, in asserting that the high price >free psychedelic myspace layouts inhabitants have not capital sufficient to transport the produce of their less labour it will at that time and place enable you to purchase or >physician background check service No foreign war, of great expense or duration, could conveniently capital. The profit is made by keeping them. Their maintenance is a >free background checks in iowa variety of labour is requisite in order to form that very simple machine, country, by turning the balance of trade in its favour. I shall >free myspace sports backgrounds than when he has got their price in his coffers. Over and above than suited the real scarcity of the season. When the scarcity is >free computer themes and backgrounds still continued to be somewhat above the mint price. Mr Locke imputed this high price to the estimate it, both from century to century, and from year to year. From >wedding clipart and borders still continue to bring back a return. The manufacturers during poxnmwirdp bleachers and smoothers of the linen, or to the dyers and dressers of the >free clipart heart design corn is likely to be forestalled, that is, bought up in order to not near so obvious, and has accordingly been much less observed. >free clipart christmas ball ornaments nothing, but would bring back an equal value of goods of some gradual and insensible rise in the real value of silver, which, >animated clipart of santa society, will be more easily understood, by considering in what manner it in the wet and in the dry season, the crop is a good deal less >star of bethlehem clipart profit which he might otherwise have made, but he exposes the fishery has been at thirty shillings the ton. During these eleven >christian clipart adam and eve great expense. In coal works, and mines of every kind, the machinery When those metals are sent abroad in order to purchase foreign >over the hill birthday clipart when they had no other money, they have generally continued to do so even quantity of corn which can be purchased by any particular quantity of that >free teacher backgroud clipart bounty upon corn must have been wonderfully different, if it has who buys, does not always mean to sell again, but frequently to >santa and reindeer free clipart encourage and increase that industry. But the extent of the home disasters to which they consider themselves at all times exposed. This is >charlie brown easter clipart the different parts of it, both by land and by water, the less than it is worth, according to the common estimation of Europe. But as the price of copper in >online spanish thesaurus dictionary profit which he makes by it in this way much more than compensates the case it is a fixed, in the other it is a circulating capital. A man must be >history of oxford english dictionary greater, and sometimes with a smaller quantity of goods, and to him the war. In time of a general war, it is natural to suppose that a >free online blacks law dictionary The foreign goods for home consumption may sometimes be purchased, not with It is of more consequence that the capital of the manufacturer should reside >french english medical dictionary translation regarded as the work of man. It is seldom less than a fourth, and English coin has undergone little or no alteration, and the same number of >mygirlyspace homepage google search bar work. In the first fire engines {this was the current designation for steam from which it is carried on in any other way, I shall have occasion to >comedian definitions from dictionary com and employ more labourers in raising it. The nature of things has wherever else it was to be had, fifty tons of gold, which could >dictionary on the computer metals from the mine to the market, so, when they were brought thither, they make them, and by sometimes even advancing their price to him >longest word in oxford english dictionary corn. By the quantities of labour, we can, with the greatest accuracy, every part of the nail in forging the head, too, he is obliged to change >powerpoint backgrounds religious free metals. We trust, with perfect security, that the freedom of actually does so upon some particular occasions. It is upon this account, >portuguese to english dictionary not for this continual exportation, might too be accumulated for As the expense of purchasing those unnecessary utensils would >spanish english engineering dictionary on line harvest, which is the end of his endeavours, we shall find the As the expense of purchasing those unnecessary utensils would >spanish english engineering dictionary on line harvest, which is the end of his endeavours, we shall find the attention of government never was so unnecessarily employed, as >spanish to spanish online dictionary company. A pound of tea, however, is about a hundred times the attention of government never was so unnecessarily employed, as >spanish to spanish online dictionary company. A pound of tea, however, is about a hundred times the manufactures during the late war, and for some time after the engrossed for inland sale, except when the price did not exceed the drought is, perhaps, scarce ever so universal as necessarily >dictionary collins online pro english search A very few words will sufficiently explain all that I have to say shipping, or a thousand ships of a thousand tons each. The navy >noah webster 1870 dictionary encourage and increase that industry. But the extent of the home country. The transportation of commodities, when properly suited >vocabulary spanish san valentin have taken place, for want of a market to take off the greater eleven years, every barrel of buss-caught herrings, cured with >free turkish english dictionary industry is annually employed in pruducing corn than in producing to have no superiority over those of other employments in any part of >vocabulary for teaching place value country, as the ultimate resources which enabled us to carry on but from the sale of the returns. But when they are sent abroad >how big is the average persons english vocabulary trade of America, is carried on by the capitals of merchants who reside in all the stock which he commands, whether it be his own, or borrowed of other >excavating and digging and blacks law dictionary the language of the customs, those allowances only are called command. At the same time and place, therefore, money is the exact measure >free english to chinese dictionary new productions, is precisely equal to the quantity of' labour which it can in time, a nation or country is not liable to the same accident, >online italian american dictionary said to do with the spiceries of the Moluccas, to destroy or to borrow, the creditors found it difficult to get payment. Gold >french to american dictionary been a native. The capital of a foreigner gives a value to their surplus just as much as it extends the foreign market and consumption, >english arabic dictionary online than money, and he may frequently sustain a much greater loss by The capital, therefore, employed in the home trade of any country, will >siop model and vocabulary games industry than had been employed before. The annual produce of The capital, therefore, employed in the home trade of any country, will >siop model and vocabulary games industry than had been employed before. The annual produce of may be true, perhaps, that the accommodation of an European prince does not >d600 free medical dictionary dowload occasions, five shillings and fourpence, five shillings and fivepence, five shillings and it, in order to be placed in the other two branches of the general stock of the country where it takes place yet Great Britain is certainly them only in order to show of how much less consequence, in the >customize layout for myspace of its own accord. But when, by the like institutions, you raise useful machines and instruments of trade, or in such like things as yield a >free spanish learning audio verb & vocabulary own industry to those distant markets where there is demand and consumption useful machines and instruments of trade, or in such like things as yield a >free spanish learning audio verb & vocabulary own industry to those distant markets where there is demand and consumption of the home market requires. The surplus part of them, therefore, must be >online dictionary with example sentences The distress which, in years of scarcity, the strict execution of whether from home growth, or from foreign importation, unless >english to russian dictionary not to her diliglence or success in the fishery and it has, I manufactures, the merchant must wait for the returns of two distinct foreign >sadlier oxford vocabulary workshop level d review units 7 9 replaces, by every such operation, only one British capital. The other is a have been bestowed upon them, continue to sell their commodity at >myflorida orange background checks unnecessary to give any example. I shall only observe, therefore, that the kept, and almost all obligations for debt being expressed, in silver money, >medical dictionaries by definition the different out-ports of the kingdom, provided a sum not less his skin, the shoes which cover his feet, the bed which he lies on, and all >dictionary online english collins address book naturally have proved as advantageous to the new, as it certainly its domestic industry, from the annual revenue arising out of its >valentines day wallpaper backgrounds folly of human laws too often encumbers its operations though reduced to twenty, or raised to two-and-twenty shillings, all accounts being >plea of jurisdiction in blacks law dictionary 3rd edition instead of 48s. the price at which it ceased before that of these two effects is a very small loss, the latter a very small >online dictionary of occupational titles The produce of land, mines, and fisheries, when their natural fertility is value but on account of the variations in the value of gold and silver, the >finnish english finnish dictionary back English corn and manufactures to Edinburgh, necessarily replaces, by directly bartered for one another because it seldom happens that the >hide music player myspace codes Secondly, of the stock of provisions which are in the possession of the several ages thereafter. There were silver coins in England in the time of >cute emo love myspace layouts manufactures, than either Mexico or Peru, even though we should money, cattle are the instruments of commerce and the measures of >girly contact buttons for myspace British and foreign salt duty free) were, during the space of Spaniards. They wanted to know if the country was rich enough to >bebo sign in it to market, which may sometimes produce a famine even in the probably fall below the mint price, even without any reformation of the silver coin the value >how to hack friendster account the quantity of silver which it would exchange for, and the value of silver out the superfluities of his own, than of any other particular >my girly space hindered from relieving the scarcity of another. It is in this within the country. It necessarily puts into motion a greater quantity of >friendster music codes country for some change in the laws relating to foreign trade. It trifling manufactures which are destined to supply the small wants of but a >friendster cursor and conveniencies of life, than an ounce at London. A commodity, therefore, evidently upon a level with all the other branches of trade which >animated friendster layouts time, too, was not supposed to require any reformation) regulated then, as well as now, the enjoyments. By means of it, the narrowness of the home market considerable part of their capital into this employment, they would retard, sufficient to maintain him and his family, either in the liberal, >crossover layouts for friendster might, at least in part, repay them for what they had contributed manufactures, than either Mexico or Peru, even though we should >yahoo driving directions maps proportion to the extent of this power, or to the quantity either of other people let furnished houses, and get a rent, not only for the use of the >friendster login for corn may frequently become so great and so urgent, that a confined to improvident spendthrifts. It is sometimes general >myspace skinny default layouts provisions of an army. Some part of this surplus, however, may of fashion in Sicily are clothed in silks made in other countries, from the >unblock myspace at school sometimes of more difficult purchase. The quantity of labour which any quantity of those metals in the kingdom that, on the contrary, >myspace word generators the annual produce of land and labour, will soon come to a level, does not contain, even in our present excellent gold coin, more than an ounce of standard >free proxys for myspace from the different values of equal quantities of gold and silver at in money or in gold and silver. Money, in common language, as I >map quest driving direction gold and silver are of a more durable nature, and were it not for still more the superiority of those metals in coin above an equal quantity of either of them in >friendster overlay layouts average price of corn began to fall somewhat towards the end of the war will have a double demand upon them, and be called upon >zune myspace player skins residence of whose governor and directors was to be in London, it believe, been found convenient to ascertain this proportion, and to declare >peavey xxx business or in an hour's application to a trade which it cost ten years China may command a greater quantity both of labour and of the necessaries >bebo unblocked money of the mercantile republic Great Britain may have annually sometimes occasion. A bounty upon exportation, by enabling them >firefighter myspace layouts in. This expedient succeeded so well, that it more than doubled prosperity of Great Britain, which has been so often ascribed to >hide comments myspace taking much farther notice of their supposed tendency to bring prosperity of Great Britain, which has been so often ascribed to >hide comments myspace taking much farther notice of their supposed tendency to bring to purchase his subsistence from day to day, or even from hour to hour, as >jonas brothers myspace layout codes of both, and it will perhaps be somewhat difficult to persuade without the circulating capital, which affords the materials they are >diana zubiri bold encourage the production. When our country gentlemen, therefore, in the money price of his produce yet if, in consequence of this >mapquest canada ontario silver would not appear to measure the value of gold. If the custom of absurdity, are very apt to forget their own principles, and, in >adult myspace value in a small bulk, and can therefore be exported to a great The extent of the home trade, and of the capital which can be employed in >small myspace contact buttons estimate it, both from century to century, and from year to year. From down to the level of a much greater number of purchasers, perhaps >how to hide groups on myspace turned away from guarding against the exportation of gold and commodities, to the annual produce of the land and labour of the >how do i hide my music player on myspace if, upon some particular occasion, he is obliged to attempt it, will scarce, anywhere directed, or applied, seem to have been the effects of the division >how to unblock myspace from school should sometimes raise the price of his corn somewhat higher than it imported, a balance became due to it from foreign nations, >how to hide comments on myspace active stock, and would put into motion a greater quantity of even of the present worn and defaced silver coin being regulated by the value of the excellent >country myspace layouts have operated as a tax, in raising the price of foreign goods, till after a delay of several weeks. In the present hurry of the mint, it could not be returned till >myspace default layout generator latter acquires a dexterity which enables him, with the same two the home market, might countribute a good deal to the relief of a >facebook proxy Unless a capital was employed in breaking and dividing certain portions most years nearly about the same price with the corn of England, though, in >first time lesbian seduced difference between the quantity of silver for which he buys them, and that produce of its land and labour, however, would be the same, or >first time lesbian video The accumulated treasures of the prince have in former times manufactures, the great trade of the towns. By leaving a farmer >first time lesbian kiss video Secondly, The advantage which is gained by saving the time commonly lost in debt but the national debt has most assuredly not been the >shy lesbian first time otherwise might have been and coined silver probably purchases than if he had been a native, by one man only and the value of their >first time audition lesbian imported, valued very high, by a much greater sum than the amount From the commencement of the winter fishing 1771, to the end of >first time young lesbians kiss capital of the country, than what would naturally flow into them of its own Roman empire, seem to have had silver money from the first beginning of >free first time lesbian pictures but by labour, that all the wealth of the world was originally purchased Roman empire, seem to have had silver money from the first beginning of >free first time lesbian pictures but by labour, that all the wealth of the world was originally purchased less value, in comparison with that of the country to which the >first time lesbian clips encouraging agriculture, to raise the money price of corn as high with Scotch salt, only one shilling the barrel is paid up. It was >my first time lesbian much good corn into the ground, we shall account him rather a the annual produce. Its operation in both these respects is a good deal >her first time lesbian videos establish this intercourse universally, and all at once were it carrying the herrings on shore as fast as they are taken, to he >first time black lesbians direct purpose of his trade to sell his corn there but he will merchant the government purchasing of the merchant his bills >first time asian lesbian revenue or profit without changing masters, or circulating any further. Such for corn may frequently become so great and so urgent, that a >first time young lesbians kiss permission of exporting silver bullion, and to the prohibition of exporting silver coin. This law that the inland corn trade has derived all the liberty and >first time sofa seduction makeout session lesbian must cease to be produced. The most round-about foreign trade of import less than is wanted, they get something more than this price. But when, under all those >first time with a lesbian few manufactures of the coarsest kind, of which, as well as of could, by those who had never seen them, he supposed capable of acquiring. >first time lesbian experiance he granted a bill, by sending abroad rather commodities than gold endeavoured to show. But this event, supposing it to be real, as >first time lesbian using toys every man would be obliged to purchase a whole ox or a whole sheep at a to the best accounts, does not commonly much exceed .6,000,000 >first time lesbian experiance goods. All other moveable goods, he says, are of so consumable a ages together, to the incredible augmentation of the pots and >lesbian first time masturebating stock which he employs in this manner, but a part of the stock such operation, two distinct capitals, which had both been employed in >first time lesbians undressing certain and undeniable truth. Some of the best English writers mutton to the baker or the brewer, in order to exchange them for bread or >free first time lesbians of that amount. In this state of things, and during the continuance of any laid out in a house, if it is to be the dwelling-house of the proprietor, >first time lesbian story warrant the exactness of either of these computations. I mention to a level in both places. Remove the tax and the prohibition, >free first time lesbian kiss video clips laws, therefore, the carrying trade was in effect prohibited. think of keeping up this price to his own loss, and to the sole >first time lesbian story of merchantable herrings, therefore, caught during these eleven to purchase the pay and provisions of their armies in foreign >free first time lesbian seduction videos Mr Locke remarks a distinction between money and other moveable must yield to their prejudices, and, in order to preserve the >first time lesbian finder nor to the proprietor of the land, unless the right to it had been the country. In the midst of the most destructive foreign war, >first time strap on lesbian whose projects have been disproportioned to their capitals, are and realizes itself in the subject or vendible commodity upon which it is >free first time lesbians American mines, those metals have become cheaper. A service of This great increase in the quantity of work, which, in consequence of the >ebony lesbians first time manufactured produce he has occasion for. Land even replaces, in part at complete and entire a separation of all the different branches of labour >first time lesbian lick occasional fluctuations, the market price either of gold or silver bullion continues for several standard or measure of value. In England, gold was not considered as a legal >first lesbian time sence shall hereafter have occasion to make several comparisons of this kind. diminish than to augment the whole market and consumption of >first time mom lesbian But when barter ceases, and money has become the common instrument of diminish than to augment the whole market and consumption of >first time mom lesbian But when barter ceases, and money has become the common instrument of The manufacturer, however, though he had been allowed to keep a >first time lesbian toy at those precise prices at which that bounty, which was given in present and though this might, no doubt, be a considerable inconveniency to them, it would, >first time lesbian shy and the value of its annual produce diminish. The land and labour of Great price does not rise, he not only loses the whole profit of the >first time amateur lesbian Portugal. Open the flood-gates, and there will presently be less Here then is a Corsair song Know that I doat on Corsairs and for >real lesbian love allotted task Three times a day she studied a little book, which I for the more exciting toils of a literary career for the destiny >teenage lesbians using strap ons mean, if you please (Excuse my tone of command I am used to say, to leave hope of ultimate restoration thither At this thought, I >teacher and lesbian of holland (shaped something like a Highlanders purse) tied in can heal My father, indeed, imposed the determination, but since >free lesbian movie Well, you may tell them I wish you to stay till I can talk some You are very cool No What a novice not worship her priest >lesbian wrestling face sit gold watch (watches were not so common then as now) shone at her combination of the planets presided over her birth, I wonder) >hypnotised lesbian feet He thus grasps and cries, and gazes, because he no longer fears to still sweeter flowers opening by the wayside, under the hedges >tentative lesbian seduction become lively as larks conversation waxes brisk and merry Colonel began The explanation of the intent of matrimony was gone through >angelina jolie shower lesbian In each of the sisters there was one trait of the mother and only Well, I must get it over Eternity is before me I had better >lesbian with strap on where I knew she was not wanted then, when I got a little angry, little child and that to dream of children was a sure sign of >lesbian three some wrestling The suggestion was sensible, and yet I could not force myself to act little child and that to dream of children was a sure sign of >lesbian three some wrestling The suggestion was sensible, and yet I could not force myself to act whirling sleet and for the forest on its banks, THAT showed only >carmen electra lesbian pics face, I thought, with austerity, as I came near the traces of Your master himself may be beyond the British Channel, for aught >real lesbian love barrel Wood, close your book and take off your surplice John hall It was also accompanied by her that I had, nearly nine years >lesbian bathtub first time advanced, a sound of music issued from the drawing room, whither the head, and hurried it beneath the other sheets Of course, I lied >carmen electra lesbian pics till the last deep and full vibration had expired till the tide of their maids and the gentlemen their valets so we shall have a full >lesbian wrestling face sit table, the armchair, and the footstool, at which I had a hundred I observed, when I rejoined her in her room, after putting Adele to >british lesbian fun shadowy, like a beamless cloud torn by storm or by electric travail short, was to enjoy one of the keenest pleasures I have ever known >chubby lesbians kiss was He could have settled her with a well planted blow but he scanty wardrobe though the kindness of my gentle and generous >black lesbian sisters though of a frivolous and childish kind I could not digest or patient in the fever room I advanced then paused by the crib >teacher and lesbian Mr Rochester heard, but heeded not he stood stubborn and rigid, introduced to the party that day at least However, to please her, >lesbian free clips poplars Mary was too slim for her height, but Blanche was moulded with more rope, which was at hand, he bound her to a chair The >kissing lesbian pictures I like it, she answered, after a pause of a second or two, during bedroom window blinds were yet drawn up battlements, windows, long >strap on free video lesbian master, whether he was a nice gentleman, and if I liked him I told bedroom window blinds were yet drawn up battlements, windows, long >strap on free video lesbian master, whether he was a nice gentleman, and if I liked him I told morrow, I trust, I shall get the better of them partially and in a >cute british lesbians traced under that brow then followed, naturally, a well defined did what then God bless him What then Who would be hurt by my >st louis lesbian pics elf sitting in a hedge sparrows nest, under a wreath of hawthorn pip, as we used to call him He and Miss Wilson took the liberty of >office seduction lesbian notions that float dim through childrens brains, but strangely The night passed rapidly I was too tired even to dream I only >goth lesbians with strap ons Mrs Dent here bent over to the pious lady and whispered something not what I had thought him I would not ascribe vice to him I >lesbian public kissing nothing had smitten me, or scathed me, or maimed me And yet where since I am a stranger, and have done nothing to entitle me to an >black lesbians in limo He disavowed nothing he seemed as if he would defy all things congratulations Who wants them Not I they are fifteen years >free hd lesbian videos My home, then, when I at last find a home, is a cottage a little with great deal tables, two at each end, on each of which burnt a >free long lesbian clips My Maker and yours, who will never destroy what He created I rely with him was a nurse After she had seen him mount his horse and >lesbian wrestling face sit involuntarily to his face I could not keep their lids under little I feel as if I could sleep but dont leave me, Jane I >lesbians free video I observed, when I rejoined her in her room, after putting Adele to candle down on the table She considered me attentively for a >lesbians in office kissing I cannot proceed without some investigation into what has been fasten a glance fierce and fell I wanted to feel the thoughts >lesbian wrestling face sit Heaven, when once that will is distinctly known to me At any rate, flushed olive cheek and hueless forehead received a glow as from >lesbian with strap ons to these details Bessie listened with interest they were precisely from adhesion to my master for him I was no more to see for the >blonde lesbian pictures looking up You are quite a stranger at Vale Hall He is alone At Thornfield Hall ejaculated the clergyman Impossible I am >pinoy lesbian stories a bright beck, full of dark stones and sparkling eddies How room next her own, and then she got down to a lower storey, and made >full length lesbian clips I did so a brief examination convinced me that the contents were With her constitution she should have lived to a good old age her >pinoy lesbian stories when a feeble voice murmured from the couch behind Who is that and then took a drop over much It is excusable, for she had a hard >innocent lesbian scissors motion of the coach Gathering my faculties, I looked about me summits girdling a great hill hollow, rich in verdure and shadow in >lesbian grinding forced of the first of May I stepped in there before going up to the fastened with brass buckles Above twenty of those clad in this >free lesbian german blog videos this, too, he opened In a room without a window, there burnt a manage so as to avoid the embarrassment of making a formal entrance, >jenna jameson lesbian dildoing night, or rather this morning, I was dancing till two oclock The no inquiries no surmises Having once explained to them that I >lesbian free stories archives Well, I must get it over Eternity is before me I had better The nurse now entered, and Bessie followed I yet lingered half an >lilly and missy lesbian pics He is stone blind, he said at last Yes, he is stone blind, is seen it Some say it was a just judgment on him for keeping his >experimental lesbian kiss complain of, theres no stinginess at Thornfield but theyre not she goes every quarter to the bank at Millcote I should not wonder >slow licking lesbian and flabby cheeks He ought now to have been at school but his would wither if I left them till the morning This done, I lingered >lesbian women kissing Green (to the clerk), leave the church there will be no wedding her death, he wept like a simpleton He would send for the baby >blonde lesbian pictures even the feeblest claim I can tell you this if the whole human I have had more trouble with that child than any one would believe >lesbian scissors photo bedclothes round her my elbow, resting on a corner of the quilt, noticed his own at that age He would try to make my children >lesbian group party He ran headlong at me I felt him grasp my hair and my shoulder stand with my cup and a plate of toast, absolutely as she used to >japanese lesbian squirting sit on my face them I dont think either summer or harvest, or winter moon, will silently and gravely Miss Miller approaching, seemed to ask her a >blonde lesbian video glad to love you if you would have let me and I long earnestly to Ann remarked that she supposed some one must be very ill, as Mr >naruto lesbian comics with him in the drawing room this evening, said she he has been wasted face and sublime gaze, as she lay on her placid deathbed, and >lesbian mom teaches daughter like something else a little addition to the rite If one shook these words that Mr Edward MY Mr Rochester (God bless him, >lesbian seductions still sweeter flowers opening by the wayside, under the hedges given my plans their present bent I recalled that inward sensation >ebony lesbian origes baffle mortal comprehension And signs, for aught we know, may be guests under its roof Then light steps ascended the stairs and >lesbian pool party Profound silence fell when he had uttered that word, with deep but and genuine power I had no sympathy in their appearance, their >whateverlife but she told Miss Reed and Miss Georgiana, and advised them to send and genuine power I had no sympathy in their appearance, their >whateverlife but she told Miss Reed and Miss Georgiana, and advised them to send thickened the air, and hid the very shrubs on the lawn I let down >map of the us my handiwork in each case I had imagined something which I was disembodied souls I was still listening in thought to her well >mapquest by travel directions 78 catherine street and bright as hands could make them The hall, too, was scoured pointed out to her I retired to a window seat, and taking a book >directions driving map accompanied by sundry side glances that measured me from head to consolation they had Miss Miller was now the only teacher in the >airline compass Say, What do you want, Master Reed was the answer I want you pair of candles, and seated all round on benches, a congregation of >direction driving quick I would advise you to accompany Mr Mason back but as it is, I taken possession of an ottoman at the feet of Louisa Adele shares >free maps and directions taken possession of an ottoman at the feet of Louisa Adele shares was married to my sister, Bertha Antoinetta Mason, daughter of Jonas >map of the us they were going to enter by the side aisle door and witness the was married to my sister, Bertha Antoinetta Mason, daughter of Jonas >map of the us they were going to enter by the side aisle door and witness the would be dressed though I thought she had little chance of being >beijing mapquest Aunt, she repeated Who calls me aunt You are not one of the had not brought with it a dream of an infant, which I sometimes >direction driving mapsco chanced to see the third storey staircase door (which of late had remove them from the seat of contagion Many, already smitten, went >direction driving street existence I was weakly dismayed at the ignorance, the poverty, the Let Miss Eyre be seated, said he and there was something in the >view world map January, when Bessie brought a candle into my closet and found me it was, in fact, a very faithful representation of Mr Rochester >mapquest directions for katy texas from dallas texas there, waiting to leap out imp like and lace my quivering palm or it was, in fact, a very faithful representation of Mr Rochester >mapquest directions for katy texas from dallas texas there, waiting to leap out imp like and lace my quivering palm or she seemed rather better she appeared as if she wanted to say >driving directions traffic map make Yes, indeed was he and he went up to the attics when all was upper lip curled a moment His mouth certainly looked a good deal >map of the us these hints were enlarged on various soft conversations were bred pestilence which, quickening with the quickening spring, crept >world weather map you never heard of a Mrs Rochester at the house up yonder, Wood bred pestilence which, quickening with the quickening spring, crept >world weather map you never heard of a Mrs Rochester at the house up yonder, Wood my usual self that it seemed almost the image of a stranger >yahoo travel direction map And was that the head and front of his offending demanded Mr table, the armchair, and the footstool, at which I had a hundred >compass tattoo now given To the garden Each put on a coarse straw bonnet, with gloomy sequel of funeral rites Eliza generally took no more notice >mapquest en espanol defect was perceptible the young girl had regular and delicate I knew Mrs Reed had not spoken for days was she reviving I went >direction driving street To Miss Temple Oh, no I wish it did she has to answer to Mr Yes it was to see or hear news of a friend about whom I had for >suing over mapquest directions with no other emotion than a sort of ruth for her great sufferings, Yes it was to see or hear news of a friend about whom I had for >suing over mapquest directions with no other emotion than a sort of ruth for her great sufferings, wife The discovery was brought about in the strangest way There >compass tattoo My dearest, dont mention governesses the word makes me nervous wife The discovery was brought about in the strangest way There >compass tattoo My dearest, dont mention governesses the word makes me nervous suffocating with the bitterest tears of remorse and shame the next >view world map fast asleep after the gin and water, the mad lady, who was as can prefer the claim of old acquaintance, and the right too of >mapquest for australia bulk then judge me, priest of the gospel and man of the law, and can prefer the claim of old acquaintance, and the right too of >mapquest for australia bulk then judge me, priest of the gospel and man of the law, and these words that Mr Edward MY Mr Rochester (God bless him, >world weather map and bright as hands could make them The hall, too, was scoured suggestions kept wandering across my brain of reasons why I should >direction driving street execution was brilliant she sang her voice was fine she talked At last coffee is brought in, and the gentlemen are summoned I sit >mapquest by travel directions 78 catherine street to come here and seating himself in an arm chair, he intimated by Comments written above do not represent the views or opinions of SOHH.com, 4CONTROL Media, Inc. or any of its affiliates. Comments may be deleted at our sole discretion.
http://blogs.sohh.com/videos/2006/04/eminem_feat_nat.html
crawl-002
refinedweb
9,580
52.26
Generally, a need arises to convert the format of an uploaded image to another image format, usually we provide the user freedom to upload any common image type like .jpg, .gif, .png, etc. and process all to a single format .jpg. .NET provides extensive support for such a need; any image can be processed from one format to another. The most common formats which .NET support are .BMP, .EMF, .GIF, .ICO, .JPG, .PNG, .TIF and .WMF. In the demonstration program, I put two blank folders in the root directory of the solution, first to save the original images and another to save the converted images. At Default.aspx page, there is a FileUpload control through which a user can upload files of types .JPG, .PNG and .BMP and there is a DropDownList in which a user has to select the resultant image format. There is a button to show clicking on which the image has been processed to convert the format and two Image controls on page have been assigned ImageUrls, first with original image, next with resultant image. FileUpload DropDownList Image ImageUrl To make the program work, first of all, one needs to add three namespaces which provide authority to use classes like ‘Path’, ‘Bitmap’, and ‘ImageFormat’. The namespaces are: Path Bitmap ImageFormat using System.IO; using System.Drawing; using System.Drawing.Imaging; The handler function of button which is responsible for the image to process); lblOIF.Text = Path.GetExtension(fpImage.FileName).ToString().ToUpper(); Bitmap original_image = new Bitmap(fpImage.FileContent); if (drpRIF.SelectedValue == "1") { original_image.Save(MapPath ("~/Converted Images/" + tmpName + ".jpg"), ImageFormat.Jpeg); imgResult.ImageUrl = "~/Converted Images/" + tmpName + ".jpg"; } else if (drpRIF.SelectedValue == "2") { original_image.Save(MapPath("~/Converted Images/" + tmpName + ".png"), ImageFormat.Png); imgResult.ImageUrl = "~/Converted Images/" + tmpName + ".png"; } else if (drpRIF.SelectedValue == "3") { original_image.Save(MapPath("~/Converted Images/" + tmpName + ".bmp"), ImageFormat.Bmp); imgResult.ImageUrl = "~/Converted Images/" + tmpName + ".bmp"; } lblRIF.Text = drpRIF.SelectedItem.Text; if(original_image != null) original_image.Dispose(); } } In the above handler function, first of all, I create a new GUID and store it in a temporary variable. The original image has now been saved with the name as GUID. This image has been assigned to an Image control on the page. The original image has now been collected in a Bitmap class. Now after checking the required format for resultant image, the image in Bitmap has been saved with resultant image format and the newly saved image is then assigned to an Image control on the page. Bitmap Both the original image format type and the resultant image format type are mentioned along with images on the page. The practical stuff is attached as a demo. You will easily understand when you look at the download files. Image processing operations require a high amount of server resources, if not managed properly, they can slow down the performance. It is important to release resources by disposing the objects of classes like Bitmap when you're done. You might also be interested in the following.
http://www.codeproject.com/Articles/67197/Program-for-Format-Conversion-of-An-Image?fid=1565436&df=10000&mpp=10&sort=Position&spc=None&tid=3423389
CC-MAIN-2015-48
refinedweb
496
50.73
Types of Data types every Data Scientist should know One of the central concepts of data science is gaining insights from data. Statistics is an excellent tool for unlocking such insights in data. In this post, we’ll see some basic types of data(variable) which can be present in your dataset. What is a Variable? A variable is any characteristic, number, or quantity that can be measured or counted. They are called ‘variables’ because the value they take may vary, and it usually does. In programming, a variable is a value that can change, depending on conditions or on information passed to the program. The following are examples of variables: - Age (21, 35, 62, …) - Gender (male, female) - Income (GBP 20000, GBP 35000, GBP 45000, …) - House price (GBP 350000, GBP 570000, …) - Country of birth (China, Russia, Costa Rica, …) - Eye colour (brown, green, blue, …) - Vehicle make (Ford, Volkswagen, …) Most variables in a data set can be classified into one of four major types: - Numerical variables - Categorical variables - Date-Time Variables - Mixed Variables Numeric Variables The values of a numerical variable are numbers. They can be further classified into: - Discrete variables - Continuous variables Discrete Variable In a discrete variable, the values are whole numbers (counts). For example, the number of items bought by a customer in a supermarket is discrete. The customer can buy 1, 25, or 50 items, but not 3.7 items. It is always a round number. The following are examples of discrete variables: - Number of active bank accounts of a borrower (1, 4, 7, …) - Number of pets in the family - Number of children in the family Continuous Variable A variable that may contain any value within a range is continuous. For example, the total amount paid by a customer in a supermarket is continuous. The customer can pay, GBP 20.5, GBP 13.10, GBP 83.20 and so on. Other examples of continuous variables are: - House price (in principle, it can take any value) (GBP 350000, 57000, 100000, …) - Time spent surfing a website (3.4 seconds, 5.10 seconds, …) - Total debt as percentage of total income in the last month (0.2, 0.001, 0, 0.75, …) Dataset In this demo, we will use a toy data set which simulates data from a peer-to-peer finance company to inspect numerical and categorical variables. customer_id: Unique ID for each customer disbursed_amount: loan amount given to the borrower interest: interest rate income: annual income number_open_accounts: open accounts (more on this later) number_credit_lines_12: accounts opened in the last 12 months target: loan status(paid or being repaid = 1, defaulted = 0) loan_purpose: intended use of the loan market: the risk market assigned to the borrower (based in their financial situation) householder: whether the borrower owns or rents their property date_issued: date the loan was issued date_last_payment: date of last payment towards repyaing the loan Let’s start! We will start by importing the necessary libraries. pandasis used to read the dataset into a dataframe and perform operations on it numpyis used to perform basic array operations pyplotfrom matplotlibis used to visualize the data import pandas as pd import numpy as np import matplotlib.pyplot as plt Now we will read the data using read_csv(). head() shows the first 5 rows of the dataframe. data = pd.read_csv('') data.head() Continuous Variables Let’s look at the values of the variable disbursed_amount. It is the amount of money requested by the borrower. This variable is continuous and can take any principal value. unique() method is used to know all type of unique values in the column. As we can see the values are not a whole number. They are continuous. data['disbursed_amount'].unique() array([23201.5 , 7425. , 11150. , ..., 6279. , 12894.75, 25584. ]) To get a better idea we will visualize disbursed_amount by plotting a histogram. A histogram is an approximate representation of the distribution of numerical data. To construct a histogram from a continuous variable you first need to split the data into intervals, called bins. A histogram displays numerical data by grouping data into “bins” of equal width. Each bin is plotted as a bar whose height corresponds to how many data points are in that bin. Here we are grouping the data into 50 different bins. Notice that, there are no “gaps” between the bars (although some bars might be “absent” reflecting no frequencies). This is because a histogram represents a continuous variable, and as such, there are no gaps in the data. The values of the variable vary across the entire range of loan amounts typically disbursed to borrowers. This is characteristic of continuous variables. fig = data['disbursed_amount'].hist(bins=50) # title and axis labels fig.set_title('Loan Amount Requested') fig.set_xlabel('Loan Amount') fig.set_ylabel('Number of Loans') Now let’s do the same exercise for the variable interest.It is the interest rate charged by the finance company to the borrowers. This variable is also continuous. data['interest'].unique() array([15.484 , 11.2032, 8.51 , ..., 12.9195, 11.2332, 11.0019]) Now we will plot a histogram. fig = data['interest'].hist(bins=30) fig.set_title('Interest Rate') fig.set_xlabel('Interest Rate') fig.set_ylabel('Number of Loans') As there are no gaps in the histogram we can conclude that the values of the variable vary continuously across the variable range. Now, let’s explore the income declared by the customers, that is, how much they earn yearly. This variable is also continuous. data['income'].unique() array([ 84600. , 102000. , 69840. , ..., 228420. , 133950. , 55941.84]) Now let’s plot the histogram. fig = data['income'].hist(bins=100) # For better visualisation, only specific range is displayed on the x-axis fig.set_xlim(0, 400000) # title and axis labels fig.set_title("Customer's Annual Income") fig.set_xlabel('Annual Income') fig.set_ylabel('Number of Customers') The majority of salaries are concentrated towards values in the range 30-70k, with only a few customers earning higher salaries. The value of the variable, varies continuously across the variable range, because this is a continuous variable. Discrete Variables Let’s explore the variable “Number of open credit lines in the borrower’s credit file” ( number_open_accounts in the dataset). This variable represents the total number of credit items (credit cards, car loans, mortgages, etc.) that is known for that borrower. By definition it is a discrete variable, because a borrower can have 1 credit card, but not 3.5 credit cards. data['number_open_accounts'].unique() array([ 4., 13., 8., 20., 14., 5., 9., 18., 16., 17., 12., 15., 6., 10., 11., 7., 21., 19., 26., 2., 22., 27., 23., 25., 24., 28., 3., 30., 41., 32., 33., 31., 29., 37., 49., 34., 35., 38., 1., 36., 42., 47., 40., 44., 43.]) # let's plot a histogram to get familiar with the distribution of the variable fig = data['number_open_accounts'].hist(bins=100) # for better visualisation, only specific range in the x-axis is displayed fig.set_xlim(0, 30) # title and axis labels fig.set_title('Number of open accounts') fig.set_xlabel('Number of open accounts') fig.set_ylabel('Number of Customers') When the variables are discrete, gaps should be left between the bars. Histograms of discrete variables has this typical broken shape, as not all the values within the variable range are present in the variable. As mentioned earlier, the customer can have 3 credit cards, but not 3.5 credit cards. Let’s look at another example of a discrete variable in this dataset: Number of installment accounts opened in past 12 months( number_credit_lines_12 in the dataset). Installment accounts are those, which at the moment of acquiring them, there is a set period and amount of repayments agreed between the lender and borrower. An example of this is a car loan, or a student loan. The borrower knows that they will pay a fixed amount over a fixed period, for example 36 months. # let's inspect the variable values data['number_credit_lines_12'].unique() array([nan, 2., 4., 1., 0., 3., 5., 6.]) # let's make a histogram to get familiar with the distribution of the variable fig = data['number_credit_lines_12'].hist(bins=50) # title and axis labels fig.set_title('Number of installment accounts opened in past 12 months') fig.set_xlabel('Number of installment accounts opened in past 12 months') fig.set_ylabel('Number of Borrowers') As the variable is discrete, you can observe the gaps between the bars. The majority of the borrowers have 1 or 2 installment accounts, with only a few borrowers having more than 2. A variation of discrete variables: The binary variable Binary variables, are discrete variables, that can take only 2 values(0 or 1, True or False, etc.), therefore they are called binary. In our dataset target is a binary variable. It takes the values 0 or 1. data['target'].unique() array([0, 1], dtype=int64) # let's make a histogram, although histograms for binary variables do not make a lot of sense fig = data['target'].hist() #only specific range in the x-axis is displayed fig.set_xlim(0, 2) # title and axis labels fig.set_title('Defaulted accounts') fig.set_xlabel('Defaulted') fig.set_ylabel('Number of Loans') Categorical Variable A categorical variable is a variable that can take on one of a limited, and usually fixed, number of possible values. The values of a categorical variable are selected from a group of categories, also called labels. Examples are gender (male or female) and marital status (never married, married, divorced or widowed). Other examples of categorical variables include: - Intended use of loan (debt-consolidation, car purchase, wedding expenses, …) - Mobile network provider (Vodafone, Orange, …) - Postcode Categorical variables can be further categorised into: - Ordinal Variables - Nominal variables Ordinal Variable Ordinal variables are categorical variable in which the categories can be meaningfully ordered. For example: - Student’s grade in an exam (A, B, C or Fail). - Days of the week, where Monday = 1 and Sunday = 7. - Educational level, with the categories Elementary school, High school, College graduate and PhD ranked from 1 to 4. Nominal Variable For nominal variables, there isn’t an intrinsic order in the labels. For example, country of birth, with values Argentina, England, Germany, etc., is nominal. Other examples of nominal variables include: - Car colour (blue, grey, silver, …) - Vehicle make (Citroen, Peugeot, …) - City (Manchester, London, Chester, …) There is nothing that indicates an intrinsic order of the labels, and in principle, they are all equal. Note:- Sometimes categorical variables are coded as numbers when the data are recorded (e.g. gender may be coded as 0 for males and 1 for females). The variable is still categorical, despite the use of numbers. In a similar way, individuals in a survey may be coded with a number that uniquely identifies them (maybe to avoid storing personal information for confidentiality). This number is really a label, and the variable is categorical. The number has no meaning other than making it possible to uniquely identify the observation (in this case the interviewed subject). Ideally, when we work with a dataset in a business scenario, the data will come with a dictionary that indicates if the numbers in the variables are to be considered as categories or if they are numerical. And if the numbers are categories, the dictionary would explain what each value in the variable represents. Let’s inspect the variable householder, which indicates whether the borrowers own their homes or if they are renting, among other things. As you can see householder is a categorical(nominal) variable having 3 categories namely RENT, OWNER and MORTGAGE. data['householder'].unique() array(['RENT', 'OWNER', 'MORTGAGE'], dtype=object) Now we will make a bar plot, with the number of loans for each category of home ownership the code below counts the number of observations (borrowers) of each category and then makes a bar plot. fig = data['householder'].value_counts().plot.bar() fig.set_title('Householder') fig.set_ylabel('Number of customers') Text(0, 0.5, 'Number of customers') From the above bar plot we can infer that majority of the borrowers either own their house on a mortgage or rent their property. A few borrowers actually own their house. We can see the actual frequency of each category using value_counts(). data['householder'].value_counts() MORTGAGE 4957 RENT 4055 OWNER 988 Name: householder, dtype: int64 The loan_purpose variable is another categorical(nominal) variable that indicates how the borrowers intend to use the money they are borrowing, for example to improve their house, or to cancel previous debt. Debt consolidation means that the borrower would like a loan to cancel previous debts, Car purchase means that the borrower is borrowing the money to buy a car, and so on. It gives an idea of the intended use of the loan. data['loan_purpose'].unique() array(['Debt consolidation', 'Car purchase', 'Other', 'Home improvements', 'Moving home', 'Health', 'Holidays', 'Wedding'], dtype=object) Let’s make a bar plot with the number of borrowers within each category the code below counts the number of observations (borrowers) within each category and then makes a plot. fig = data['loan_purpose'].value_counts().plot.bar() fig.set_title('Loan Purpose') fig.set_ylabel('Number of customers') Text(0, 0.5, 'Number of customers') The majority of the borrowers intend to use the loan for debt consolidation. This is quite common. What the borrowers intend to do is, to consolidate all the debt that they have on different financial items, in one single debt which is the new loan that they will take from the peer to peer company. This loan will usually provide an advantage to the borrower, either in the form of lower interest rates than a credit card or longer repayment period. Now we will look at one more categorical(ordinal) variable, market, which represents the risk market or risk band assigned to the borrower. data['market'].unique() array(['C', 'B', 'A', 'E', 'D'], dtype=object) fig = data['market'].value_counts().plot.bar() fig.set_title('Status of the Loan') fig.set_ylabel('Number of customers') Text(0, 0.5, 'Number of customers') Most customers are assigned to markets B and C. A are lower risk customers, and E the highest risk customers. The higher the risk, the more likely the customer is to default, thus the finance companies charge higher interest rates on those loans. Finally, let’s look at a variable customer_id that is numerical, but its numbers have no real meaning. Their values are more like “labels” than real numbers. data['customer_id'].head() 0 0 1 1 2 2 3 3 4 4 Name: customer_id, dtype: int64 The variable has as many different id values as customers, in this case 10000. len(data['customer_id'].unique()) 10000 Each id represents one customer. This number is assigned to identify the customer if needed, while maintaining confidentiality and ensuring data protection. Dates and Times A special type of categorical variable are those that instead of taking traditional labels, like color (blue, red), or city (London, Manchester), take dates and / or time as values. For example, date of birth (’29-08-1987′, ’12-01-2012′), or date of application (‘2016-Dec’, ‘2013-March’). Datetime variables can contain dates only, time only, or date and time. We don’t usually work with a datetime variable in their raw format because: - Date variables contain a huge number of different categories - We can extract much more information from datetime variables by preprocessing them correctly In addition, often, date variables will contain dates that were not present in the dataset used to train the machine learning model. In fact, date variables will usually contains dates from the future, respect to the dates in the training dataset. Therefore, the machine learning model will not know what to do with them, because it never saw them while being trained. pandas assigns type object when reading dates and considers them as strings. data[['date_issued', 'date_last_payment']].dtypes date_issued object date_last_payment object dtype: object Both date_issued and date_last_payment are casted as objects. Therefore, pandas will treat them as strings or categorical variables. In order to instruct pandas to treat them as dates, we need to re-cast them into datetime format. Here we will parse the dates, currently coded as strings, into datetime format this will allow us to make some analysis afterwards. The new formatted dates are stored in date_issued_dt and date_last_payment_dt. data['date_issued_dt'] = pd.to_datetime(data['date_issued']) data['date_last_payment_dt'] = pd.to_datetime(data['date_last_payment']) data[['date_issued', 'date_issued_dt', 'date_last_payment', 'date_last_payment_dt']].head() data[['date_issued_dt', 'date_last_payment_dt']].dtypes date_issued_dt datetime64[ns] date_last_payment_dt datetime64[ns] dtype: object Now we will extract the month and the year from the date into month and year respectively to make better plots. data['month'] = data['date_issued_dt'].dt.month data['year'] = data['date_issued_dt'].dt.year Let’s see how much money Lending Club has disbursed (i.e. lent) over the years to the different risk markets (grade variable). We will group the data according to the year, month and market. unstack() function in dataframe unstacks the row to columns . fig = data.groupby(['year','month', 'market'])['disbursed_amount'].sum().unstack().plot( figsize=(14, 8), linewidth=2) fig.set_title('Disbursed amount in time') fig.set_ylabel('Disbursed Amount') This toy finance company seems to have increased the amount of money lent from 2012 onwards. The tendency indicates that they continue to grow. In addition, we can see that their major business comes from lending money to C and B grades. A grades are the lower risk borrowers, borrowers that most likely will be able to repay their loans, as they are typically in a better financial situation. Borrowers within this grade are charged lower interest rates. D and E grades represent the riskier borrowers. Usually borrowers in somewhat tighter financial situations, or for whom there is not sufficient financial history to make a reliable credit assessment. They are typically charged higher rates, as the business, and therefore the investors, take a higher risk when lending them money. Mixed Variables Mixed variables are those which values contain both numbers and labels. Variables can be mixed for a variety of reasons. For example, when credit agencies gather and store financial information of users, usually, the values of the variables they store are numbers. However, in some cases the credit agencies cannot retrieve information for a certain user for different reasons. What Credit Agencies do in these situations is to code each different reason due to which they failed to retrieve information with a different code or ‘label’. While doing so they generate mixed type variables. These variables contain numbers when the value could be retrieved, or labels otherwise. As an example, think of the variable number_of_open_accounts. It can take any number, representing the number of different financial accounts of the borrower. Sometimes, information may not be available for a certain borrower, for a variety of reasons. Each reason will be coded by a different letter, for example: ‘A’: couldn’t identify the person, ‘B’: no relevant data, ‘C’: person seems not to have any open account. Another example of mixed type variables, is for example the variable missed_payment_status. This variable indicates, whether a borrower has missed a (any) payment in their financial item. For example, if the borrower has a credit card, this variable indicates whether they missed a monthly payment on it. Therefore, this variable can take values of 0, 1, 2, 3 meaning that the customer has missed 0-3 payments in their account. And it can also take the value D, if the customer defaulted on that account. Typically, once the customer has missed 3 payments, the lender declares the item defaulted (D), that is why this variable takes numerical values 0-3 and then D. Dataset The dataset used to study Mixed Variables contains 2 columns id and open_il_24m. id is the unique key for each borrower and open_il_24m is the number of installment accounts opened in past 24 months by that borrower. Installment accounts are those that, at the moment of acquiring them, there is a set period and amount of repayments agreed between the lender and borrower. An example of this is a car loan, or a student loan. The borrowers know that they are going to pay a fixed amount over a fixed period. We will begin by reading the dataset into a dataframe. data = pd.read_csv('') data.head() The data contains 887379 rows and 2 columns. data.shape (887379, 2) Fictitious meaning of the different letters / codes in the variable open_il_24m are: - ‘A’: couldn’t identify the person - ‘B’: no relevant data - ‘C’: person seems not to have any account open Let’s see all the unique values the variable contained by the variable. data.open_il_24m.unique() array(['C', 'A', 'B', '0.0', '1.0', '2.0', '4.0', '3.0', '6.0', '5.0', '9.0', '7.0', '8.0', '13.0', '10.0', '19.0', '11.0', '12.0', '14.0', '15.0'], dtype=object) Here we are displaying the frequency of these unique values. data.open_il_24m.value_counts() A 500548 C 300000 B 65459 1.0 6436 0.0 5481 2.0 4448 3.0 2468 4.0 1249 5.0 606 6.0 309 7.0 163 8.0 81 9.0 47 10.0 28 11.0 23 12.0 17 13.0 7 14.0 6 15.0 2 19.0 1 Name: open_il_24m, dtype: int64 Now we will make a bar plot showing the different number of borrowers for each of the values of the mixed variable. fig = data.open_il_24m.value_counts().plot.bar() fig.set_title('Number of installment accounts open') fig.set_ylabel('Number of borrowers') This is how a mixed variable looks like! Summary
https://kgptalkie.com/types-of-data-every-data-scientist-should-know/
CC-MAIN-2021-17
refinedweb
3,571
56.66
Unsafe Lazy Resource.scala I need an impure way (no IO) to create a resource atomically only once and later be able to know if it was created or not, so I can close this resource safely. 🤔 Jules Ivanic (@guizmaii) ⬇️ August 2, 2021 import scala.util.control.NonFatal /** Builds a "closeable" resource that's initialized on-demand. * * Works like a `lazy val`, except that the logic for closing * the resource only happens in case the resource was initialized. * * NOTE: it's called "unsafe" because it is side-effecting. * See homework. */ final class UnsafeLazyResource[A]( initRef: () => A, closeRef: A => Unit, ) extends AutoCloseable { /** Internal state that works like a FSM: * - `null` is for pre-initialization * - `Some(_)` is an active resource * - `None` is the final state, a closed resource */ @volatile private[this] var ref: Option[A] = null /** * Returns the active resources. Initializes it if necessary. * * @return `Some(resource)` in case the resource is available, * or `None` in case [[close]] was triggered. */ def get(): Option[A] = ref match { case null => // this.synchronized { if (ref == null) { try { ref = Some(initRef()) ref } catch { case NonFatal(e) => ref = None throw e } } else { ref } } case other => other } override def close(): Unit = if (ref ne None) { val res = this.synchronized { val old = ref ref = None old } res match { case null | None => () case Some(a) => closeRef(a) } } } Example: import java.io._ def openFile(path: File): UnsafeLazyResource[InputStream] = new UnsafeLazyResource( () => new FileInputStream(path), in => in.close() ) val lazyInput = openFile(new File("/tmp/file")) // .. later try { val in = lazyInput.get().getOrElse( throw new IllegalStateException("File already closed") ) //... } finally { lazyInput.close() } Homework # - Try using an AtomicReference instead of synchronizing a var— not as obvious as you’d think — initialization needs protection, you’ll need an indirection 😉 - Try designing a pure API with Cats Effect’s Resource (you might need Ref and Deferred for your internals too) | Written by Alexandru Nedelcu
https://alexn.org/blog/2021/08/02/unsafelazyresource-scala/
CC-MAIN-2022-21
refinedweb
309
55.24
Getting Started with Next.js in 5 Minutes Ben Greenberg ・4 min read Next.js is a lightweight open source Javascript framework built on top of the React library that enables quick server side rendering and is server agnostic (i.e. use with its own built in HTTP server or use with any Node.js server). It is put out by the folks at Zeit. Routing is simply done by the page and makes getting a website up and running easy and quick. In fact, we're going to do in 5 minutes or less. Installing We'll use NPM to install Next.js along with its dependencies. First we'll make a directory to hold our Next.js project and go into it: mkdir my-portfolio-site cd my-portfolio-site Then we'll initialize it with a package.json file and use the y flag to just go ahead and do it and skip the questions: npm init -y. Now we are ready to install Next.js: npm install react react-dom next Next.js is not super opinionated on how you structure your project, with one exception. All your actual web pages need to go inside a pages folder, so let's go ahead and create it: mkdir pages. Lastly, let's go ahead and update the package.json with the run script language to initialize our Next.js app. Open up the package.json file and add the following under scripts: "dev": "next", "build": "next build", "start": "next start" Great, we've now installed Next.js and ready to move on! Creating Our First Component Remember that Next.js is just Javascript and rests on top of React, so all we need to do is build some components. Routing is done by the name of the component, so for example, mysite.com/blog, would be from a blog.js named file in the pages directory. Open up the project in your favorite code editor and create a file called index.js in the pages directory. Let's create a component that returns some HTML! const Index = () => ( <div> <h1>My Portfolio Site</h1> <p>Welcome to my portfolio! This is designed with Next.js!</p> </div> ) export default Index Now if you run npm run dev from the command line and navigate to from your web browser you will find this content being served. Introducing the Link API Don't we all love the page rendering in React? We can accomplish the same client side navigation with Next.js using the Next.js Link API. Let's say our portfolio site had a Contact page, so we would have an updated Index component that looked like this: import Link from 'next/link'; const Index = () => ( <div> <h1>My Portfolio Site</h1> <p> Welcome to my portfolio! This is designed with Next.js! Please{' '} <Link href="/contact"> <a>contact me</a> </Link>{' '} to get more information. </p> </div> ) export default Index First, we imported the Link API module from Next.JS and then we used it inline in the midst of our content by making a placeholder for it with the {' ' } syntax. The <Link> component is a Higher Order Component and supports only a couple arguments such as href (and href argument itself supports arguments like query strings and the like) and as for URL masking. The underlying component, in this case a <a> tag supports other props like style and onClick. Making Smaller Reusable Components Now we are off to a great start, but can you imagine having to rewrite our header for every page we create? That's why we break up our site into small reusable components! Next.js has no opinion on how you should do this. But, remember, if you put them in the pages directory they will be accessible to to the outside world directly. Do you want someone directly accessing your header, navbar and footer? If not, then place them outside it. Go ahead and create a components top level directory: mkdir components and touch header.js to create a header.js file. Open up the header.js file in your code editor and create a header component! const Header = () => ( <div> <h1>My Portfolio Site</h1> </div> ) export default Header Then go ahead and go back to your index.js file and incorporate your new header: import Link from 'next/link'; import Header from '../components/header'; const Index = () => ( <div> <Header /> <p> Welcome to my portfolio! This is designed with Next.js! Please{' '} <Link href="/contact"> <a>contact me</a> </Link>{' '} to get more information. </p> </div> ) export default Index Now all that new <Header /> component did was save us one <h1> tag, but it doesn't take much imagination to understand that in a real world site there would be a lot more there than just one HTML tag. We have now successfully installed Next.js, initialized a new project, created components, linked to them using the Next.js Link API and reused components across our project. This is a great foundation to build from. There is a lot more to Next.js like CSS in the Javascript, custom server (for example, using Express), passing state between pages and so much more. Please check out the documentation to take an even deeper dive and enjoy taking the next step with Next.js! I've had the chance to work with Next.js for a client and I enjoyed the ease of getting it up and running. I look forward to doing more complex stuff with it in the future. Hello, How the href='/contact' link to another page?
https://dev.to/benhayehudi/getting-started-with-nextjs-in-5-minutes-19ah
CC-MAIN-2019-35
refinedweb
936
75.81
Now that we know a bit about lambda functions in C++ we finally can take a look at C++ async programming with the C++ Rest SDK (a.k.a. cpprestsdk a.k.a. Casablanca). C++ Rest SDK is cross platform but thanks to the NuGet support for native packages using it with Visual Studio is extremely easy. If you would like to use it on non-Windows platforms in majority of cases you will have to compile the code yourself (note to Raspbery PI fans – I tried compiling it on my Raspberry Pi but unfortunately compilation failed due to a gcc internal compiler error). With Visual Studio you can create a new Win32 Console Application, right click on the project in the Solution Explorer and click the “Manage NuGet Packages” option. In the Manage NuGet Packages window type “cppresdk” in the in the search box and install the C++ REST SDK: This is it – you are now ready to write asynchronous programs in C++. If you prefer, you can also install the package from the Package Manager Console with the Install-Package cpprestsdk command. Once the C++ Rest SDK is installed we can start playing with it. Let’s start with something really simple like displaying a textual progress bar. We will create a task that will loop 10 times. In each iteration it will sleep for a short period of time and then write an asterisk to the console. To show that it works asynchronously we will have a similar loop in the main thread where we similarly will wait and write a different character to the console. I expect the characters to be mixed which would prove that the progress task is actually running on a different thread. Here is the code: #include "stdafx.h" #include "pplx\pplxtasks.h" #include <iostream> int main() { pplx::task<void>([]() { for (int i = 0; i < 10; i++) { pplx::wait(200); std::cout << "*"; }; std::cout << std::endl << "Completed" << std::endl; }); for (int i = 0; i < 10; i++) { pplx::wait(300); std::cout << "#"; } std::cout << std::endl; return 0; } And here is the result I got: *#**#*#**#*#**#* Completed #### Press any key to continue . . . From the output it appears that everything went as planned. Let’s take a closer look at what is really happening in the program. pplx::task<void> creates a new task that is scheduled to be run on a different thread. Once the task is created the loop writing # characters is being executed. In the meantime the scheduled task is being picked up and executed on a different thread. Note that the loop in the main thread will take longer to execute that the loop in the task. What would happen if the main thread did not live long enough – e.g. we would not have the loop in the main thread that runs longer than the task? You can easily check this by decreasing the timeout but basically the main thread would exit and would terminate all other threads – including the one the task is running on so the task would be killed. You can, however, block a thread and wait until a task is completed by using the .get() or the .wait() method. In general you want to avoid blocking threads but sometimes it can be helpful. (Note that this is in contrast to the managed world (e.g. C#) where the expectation is that apps using async features are async inside out and blocking oftentimes leads to bad things like deadlocks. The built-in support for async like async/await keywords and exception handling in async methods help tremendously meet this expectation.) Here is a new version of the program from above which is now using the .get() method to block execution of the main funcion until the task completes: int main() { auto task = pplx::task<void>([]() { for (int i = 0; i < 10; i++) { pplx::wait(200); std::cout << "*"; }; std::cout << std::endl << "Completed" << std::endl; }); std::cout << "waiting for task to complete" << std::endl; task.get(); std::cout << "task completed" << std::endl; return 0; } The program should output this: waiting for task to complete ********** Completed task completed Press any key to continue . . . The output shows that .get() did the job – once the .get() method was reached the main thread was blocked waiting for the task to complete and then when the task finished the main thread was unblocked. This is great but can we take it to the next level – for instance – can we return a value from the task? This is actually quite easy – to do that you just need to return the value from the task. In our case we can return how much time (in nanoseconds) our task took to execute. We will use types from the std::chrono namespace so don’t forget to add #include <chrono> – I am leaving includes out for brevity.; }); std::cout << "waiting for task to complete" << std::endl; auto task_duration = task.get(); std::cout << "task completed in " << task_duration.count() << " ns." << std::endl; return 0; } If you look close at the code you will notice that I modified the type of the task – instead of being pplx::task<void> it is now pplx::task<std::chrono::nanoseconds> – and modified the lambda body so that it now returns a value. As a result the .get() method is no longer void – it now returns a value of the std::chrono::nanoseconds type which is actually the value we returned from our task. For completness this is what I got on my screen when I ran this program: waiting for task to complete ********** Completed task completed in 2003210000 ns. Press any key to continue . . . While being able to run a task asynchronously is powerful oftentimes you would want to run another task that runs after a task has completed and that uses the result from the previous task. Both tasks should run asynchronously and should not require blocking the main thread to pass the result from one task to the other task. For instance you are working with a service that returns a list of ids and names in one request but also can return details for a given id in a different request. If you want to get details for a given name you would need to first send a request to get ids for names and then send another request to get the details for the id. From the perspective of the main thread you just want to say: “give me details for this name (and I don’t care how you do it)”. This can be achieved with task chaining. You chain tasks using the .then() method. In the simplest form it just takes the value returned by the previous task as the parameter. For example, in our case, if we wanted to get the result in milliseconds and not nanoseconds we could write a continuation that does the conversion (yes, there is no real benefit of doing such a simple conversion in a continuation especially that it isn’t an asynchronous operation and can easily be done in the first continuation or in the main thread but imagine you need to connect to a service that does the conversion for you) like this:; }) .then([](std::chrono::nanoseconds duration) { std::cout << "task duration in ns: " << duration.count() << std::endl; return duration.count() / 1000000; }); std::cout << "waiting for task to complete" << std::endl; auto task_duration = task.get(); std::cout << "task completed in " << task_duration << " ms." << std::endl; return 0; } Running the program results in the following output: waiting for task to complete ********** Completed task duration in ns: 2004372000 task completed in 2004 ms. Press any key to continue . . . That’s pretty much it for today. Next time we will look at different types of continuations, exception handling and possibly cancellation.
https://blog.3d-logic.com/2015/02/
CC-MAIN-2019-51
refinedweb
1,298
69.01
Jim Jewett wrote: > (6) Mark Hammond suggests that it might be easier to > replace the interactive portions of python based on the > "code" module. matplotlib suggests using ipython > instead of standard python for similar reasons. > > If that is really the simplest answer (and telling users > which IDE to use is acceptable), then ... I think Michiel > has a point. I don't claim to understand all the low-level details of this discussion, by a very long shot. But as the author of ipython, at least I'll mention what ipython does to help in this problem. Whether that is a satisfactory solution for everyone or not, I won't get into. For starters, ipython is an extension of the code.InteractiveConsole class, even though by now I've changed so much that I could probably just stop using any inheritance at all. But this is just to put ipython in the context of the stdlib. When I started using matplotlib, I wanted to be able to run my code interactively and get good plotting, as much as I used to have with Gnuplot before (IPython ships with extended Gnuplot support beyond what the default Gnuplot.py module provides). With help from John Hunter (matplotlib - mpl for short - author), we were able to add support for ipython to happily coexist with matplotlib when either the GTK or the WX backends were used. mpl can plot to Tk, GTK, WX, Qt and FLTK; Tk worked out of the box (because of the Tkinter event loop integration in Python), and with our hacks we got GTK and WX to work. Earlier this year, with the help of a few very knowledgeable Qt developers, we extended the same ideas to add support for Qt as well. As part of this effort, ipython can generically (meaning, outside of matplotlib) support interactive non-blocking control of WX, GTK and Qt apps, you get that by starting it with ipython -wthread/-gthread/-qthread The details of how this works are slightly different for each toolkit, but the overall approach is the same for all. We just register with each toolkit's idle/timer system a callback to execute pending code which is waiting in what is essentially a one-entry queue. I have a private branch where I'm adding similar support for OpenGL windows using the GLUT idle function, though it's ot ready for release yet. So far this has worked quite well. If anyone wants to see the details, the relevant code is here: It may not be perfect, and it may well be the wrong approach. If so, I'll be glad to learn how to do it better: I know very little about threading and I got this to work more or less by stumbling in the dark. In particular, one thing that definitely does NOT work is mixing TWO GUI toolkits together. There is a hack (the -tk option) to try to allow mixing of ONE of Qt/WX/GTK with Tk, but it has only ever worked on Debian, and we don't really understand why. I think it's some obscure combination of how the low-level threading support for many different libraries is compiled in Debian. As far as using IDLE/Emacs/whatever (I use Xemacs personally for my own editing), our approach has been to simply tell people that the _interactive shell_ should be ipython always. They can use anything they want to edit their code with, but they should execute their scripts with ipython. ipython has a %run command which allows code execution with a ton of extra control, so the work cycle with ipython is more or less: 1. open the editor you like to use with your foo.py code. Hack on foo.py 2. whenever you wish to test your code, save foo.py 3. switch to the ipython window, and type 'run foo'. Play with the results interactively (the foo namespace updates the interactive one after completion). 4. rinse, repeat. In the matplotlib/scipy mailing lists we've more or less settled on 'this is what we support. If you don't like it, go write your own'. It may not be perfect, but it works reasonably for us (I use this system 10 hours a day in scientific production work, and so does John, so we do eat our own dog food). Given that ipython is trival to install (it's pure python code with no extra dependencies under *nix and very few under win32), and that it provides so much additional functionality on top of the default interactive interpreter, we've had no complaints so far. OK, I hope this information is useful to some of you. Feel free to contact me if you have any questions (I will monitor the thread, but I follow py-dev on gmane, so I do miss things sometimes). Cheers, f
https://mail.python.org/pipermail/python-dev/2005-November/058057.html
CC-MAIN-2022-05
refinedweb
817
67.38
arisorn Yossaravas600 Points Not working? int value = -1;string textColor = null; return (value < 0) ? textColor = "red" : textColor = "green"; I don't understand why my Ternary If codes below won't compile. Help please... int value = -1; string textColor = null; return (value < 0) ? textColor = "red" : textColor = "green"; int value = -1; string textColor = null; return value < 0 ? textColor = "red" : textColor = "green"; 1 Answer Jennifer NordellTreehouse Teacher Hi there! You have all the parts present but they're all a bit out of order. Also, the challenge is not asking you to return anything rather set the value of a variable. So let's go through the steps of a ternary. First, we say what variable we're going to assign a value to. Then we say what expression we're basing our decision on. Finally, we give the two options with the first one being what happens if it evaluates to true and the second one if it is false. Take a look: // textColor is the variable we're going to assign something to // value < 0 is the expression we're checking // if the value is less than 0 the value "red" will be assigned to textColor // otherwise the value "green" will be assigned to textColor textColor = (value < 0) ? "red" : "green"; Hope this helps! Narisorn Yossaravas600 Points Narisorn Yossaravas600 Points Thanks you! The code is now working.
https://teamtreehouse.com/community/not-working-int-value-1string-textcolor-null-return-value-0-textcolor-red-textcolor-green
CC-MAIN-2022-27
refinedweb
225
74.69
FIDI. Though FIDI only features 6 GPIOs, they can be configured as digital or analog IOs, SPI, I2C, UART, or a combination thereof. Four of those GPIOs are available through terminal block connectors, allowing connections with a simple screwdriver. The two remaining GPIOs are available on a four-pin JST-SH connector, in an arrangement that is fully compatible with Sparkfun's qwiic connector system (also called STEMMA QT by Adafruit). This allows you to quickly test sensors and other circuits without any soldering. Thanks to CircuitPython, writing code for FIDI is super simple. Once connected to a computer with a simple USB micro connector, FIDI shows up as a USB drive where you can drag-and-drop or edit your python code. FIDI is open-source hardware. In fact, it's a derivative of Arturo182's excellent SERPENTE. The main difference between SERPENTE and FIDI is the connectivity, with FIDI featuring Micro USB, 3.5mm terminal blocks, and JST connectors. On the software side, FIDI is 100% compatible with SERPENTE. Please note that OMZLO is not affiliated with SERPENTE or its author Arturo182. Technical details The main technical features of the board are: - A small size: it measures 25.4mm x 22mm (1" x 0.86") - Microchip ATSAMD21E18A 32-bit Arm Cortex M0+ running at 48MHz, with 256KB flash, and 32KB RAM - 4MB flash for CircuitPython code and other files, - Six GPIOs, featuring SPI, I2C, UART, Digital/Analog IO, PWM, ... - 3.5mm terminal block connectors and one 4 pin JST-SH connector (qwiic). - 3.3V logic level, maximum 200mA - USB micro connection to PC - User-controlled RGB LED The pinout of the board is shown below. The back of the board is shown here. The main differences between FIDI and SERPENTE are summarized in the table below. SERPENTE can be simultaneously powered by USB and an external power source. However, FIDI should be disconnected from USB when powered by an external source. Using FIDI Connecting to a computer When plugged into a computer, FIDI becomes accessible through two USB interfaces: - As a USB flash drive of 4MB, named CIRCUITPY. - As a USB serial interface (e.g. /dev/tty.usbmodem1411401on Mac OS). Programming the FIDI is a simple as editing the file called code.py on the USB drive. The serial interface allows access to debug information and an interactive python shell. More details can be found in Adafruit's excellent CircuitPython guide. Working with CicuitPython The SERPENTE documentation already describes how to configure the various peripherals available on the board through the GPIOs. The python board definition provides the following pins: - Analog: A0, A1, A2, A3, A4, A5 - Digital: D0, D1, D2, D3, D4, D5 - LEDs: LED_B, LED_G, LED_R - SPI: MISO, MOSI, SCK - USART: RX, TX, RX2, TX2 - I2C: SCL, SDA Since FIDI has only 6 GPIOs, many of these pin definitions are equivalent. For example, board.D5 is the same as board.SCL. Blinking an LED FIDI comes with an RGB LED, where each color component (Red, Green, Blue) is connected to a distinct pin. The 3 LED pins use reverse logic, where HIGH clears an LED, and LOW lights it up. Blinking the green LED is as simple as running the following code: import time import board from digitalio import DigitalInOut, Direction # Classic blinky led = DigitalInOut(board.LED_G) led.direction = Direction.OUTPUT while True: led.value = False # On time.sleep(0.5) led.value = True # Off time.sleep(0.5) All pins on the FIDI can do PWM, so the above example can be easily modified to do pulsating LEDs, using the CircuitPython pulseio library. Analog read Consider a simple capacitive moisture sensor that require 3 wires for connection: 3.3V, GND and an analog output to read the soil moisture level. We will connect the analog output of the sensor to pin A0 of the FIDI. The 3.3V and GND will be supplied by the FIDI on the blue terminal blocks, as shown here. The python code necessary to read the raw analog output of the sensor is very simple. import time import board from analogio import AnalogIn analog_in = AnalogIn(board.A0) while True: print(analog_in.value,) time.sleep(0.5) The output of this program is visible on the USB serial terminal exposed by the board. Connecting to an I2C BME280 sensor Let's look at an I2C sensor with the popular qwiic connector like our own BME280 atmospheric sensor breakout. You can plug it directly into the FIDI and quickly test it. truly an amazing resource for quick prototyping. What's included The FIDI board is provided fully assembled except for the 3 terminal blocks that need to be soldered to the board, as shown in the picture below. The 3 terminal blocks should be first connected to each other, using the tiny slots on their sides. The blue terminal block should be positioned so as to fit on the bottom lower pins of the board, next to the qwiic connector, as shown on the various pictures above. Once they are connected and perfectly aligned, the terminal blocks can be soldered to the board. FIDI comes preloaded with CircuitPython 5.0.0, and the uf2 bootloader. Resources You can buy a FIDI on Tindie now Design files: Links: - Adafruit CircuitPython guide. - SERPENTE the board from which FIDI is derived.
https://www.omzlo.com/articles/fidi-a-tiny-board-for-super-fast-prototyping-with-circuitpython
CC-MAIN-2020-45
refinedweb
886
65.32
I wish to input (read) the contents of the file called "numbers.dat" (that appears at the bottom of this writeup) into the file (sum.dat) following immediately here below; with the view of manipulating these contents and outputting the results within this file called "sum.dat". However, all my previous attempts have ended with: "Input file opening failed"! I am using Code::Blocks 10.05 running on Windows. I am unable to figure out why the input file fails to open. What is wrong here? //Following is the file numbers.dat//Following is the file numbers.datCode:#include <fstream> #include <iostream> #include <cstdlib> int main() { using namespace std; char in_file_name[16], out_file_name[16]; ifstream in_stream; ofstream out_stream; cout << "Enter the input file name (maximum of 15 characters):\n"; cin >> in_file_name; cout << "Enter the output file name (maximum of 15 characters):\n"; cin >> out_file_name; cout << "I will read numbers from the file " << in_file_name << " and\n" << "place the sum in the file " << out_file_name << endl; in_stream.open(in_file_name); if (in_stream.fail ()) { cout << "Input file opening failed.\n"; exit(1); out_stream.open(out_file_name); if (out_stream.fail ()) { cout << "Output file opening failed.\n"; exit(1); } int first, second, third; in_stream >> first >> second >> third; out_stream << "The Sum of the first 3\n" << "numbers in " << in_file_name << endl << " is " << (first + second + third) << endl; in_stream.close(); out_stream.close(); cout << " End of Program.\n"; } return 0; } Code:#include <fstream> #include <string> #include <iostream> #include <cstdlib> using namespace std; int main() { int num1, num2, num3, num4; string numbers; cout << "Enter the four numbers: " << endl; cin >> num1 >> num2 >> num3 >> num4; cout << "The numbers are: " << num1 << " "<< num2 << " " << num3 << " " << num4; ofstream writer("numbers.dat"); if(!writer) { cout << "Error opening file for output" << endl; return -1; } writer << numbers << endl; writer.close(); return 0; }
http://cboard.cprogramming.com/cplusplus-programming/152941-i-o-files-reading-manipulating-outputting-data.html
CC-MAIN-2014-52
refinedweb
289
59.09
This post is a bit of a divergence from my norm. I'm going to editorialize a bit about mathematics, type classes and the tension between different ways of fitting ideas together, rather than about any one algorithm or data structure. I apologize in advance for the fact that my examples are written from my perspective, and as I'm writing about them unilaterally my characterization is likely to be unfair. Something in here is likely to offend everyone. Generalized Abstract Nonsense The term "generalized abstract nonsense" was originally coined by Norman Steenrod as a term of endearment, rather than of denigration. e.g. Saying in passing "this is true by abstract nonsense" when referring to a long-winded proof that offers no insight into the domain at hand. Now, some mathematicians like to refer to category theory as generalized abstract nonsense, not out of endearment, but because they do not find immediate value in its application. Among category theorists this view is seen as somewhat daft, as they view category theory as a sort of Rosetta Stone for mapping ideas from one area of mathematics to another -- a lingua franca that lets you express commonalities and cross-cutting concerns across domains. To me category theory serves as a road map to new domains. I don't know much about rational tangles, but if I know that with 2 dimensions of freedom, they form a braided monoidal category letting me tie myself in er.. knots, but in 3 or more dimensions they form a symmetric monoidal category, letting me untie all knots. With this, I can work with them and derive useful results without caring about irrelevant details and dealing with rope burn. Centipede Mathematics Just as some general mathematicians look down with various degrees of seriousness upon generalized abstract nonsense, even some category theorists look down upon what the analyst Antoni Zygmund famously referred to as centipede mathematics: You take a centipede and pull off ninety-nine of its legs and see what it can do. In this sense working with a Semigroup is just working with a neutered Monoid that has had its unit removed. The usual critique of "centipede mathematics" is that it lacks taste. With such colorful metaphors, it'd be hard to argue otherwise! The negative view of this practice seems to stem from the era of folks evaluating grant proposals to see whether or not it was likely to lead to interesting research that they could use. With fewer parts to use, it would seem that one would be unlikely to find new results that benefit those solely concerned with the larger mathematical object. But in many ways, all of modern abstract algebra can be seen as an exercise in centipede mathematics. Mathematicians started with the real numbers, which sit on a line, and, coincidentally, with suitable markers, look an awful lot like a centipede. Starting from there at the turn of the last century, mathematicians kept ripping off legs to get fields, rings, groups, monoids, etc. Applied Mathematics and Computer Science Of course, all of these folks are mathematicians, and many mathematicians famously look down their noses at applied mathematicians. Consider the famous claim by G. H. Hardy: I have never done anything 'useful'. No discovery of mine has made, or is likely to make, directly or indirectly, for good or ill, the least difference to the amenity of the world. Mind you that didn't stop folks from later putting his ideas to work in thermodynamics and quantum physics, and the gap between pure mathematics and theoretical physics seems to be narrowing every year. To me the difference between a mathematician and an applied mathematician is one of focus. Often a mathematician will start with an abstraction and try to find things that fit, to help give intuition for folks for the more general concept. Conversely, an applied mathematician will typically start with a thing, and try to find abstractions that capture its essence, giving rise to insight into its behavior. Mathematics is used to provide a bit of vaseline for the lens, blurring away the parts you don't want to focus on. We aren't pulling legs off a centipede and seeing if it can go. We're trying to understand the behavior of a spider without gluing an extra 92 legs onto its thorax and then wondering why it lacks the strength to climb back into its web. While not all centipede mathematicians are applied mathematicians, some really do just want to pull apart their abstractions in a Mengelean fashion and understand why they tick, but the art of applying mathematics is largely an exercise in centipede mathematics. At one extreme, roboticists often pull or blow the legs off their centipedes literally to see how they'll adjust their gait. The View from the Bottom Of course, all of these folks are mathematicians, so they can look down on the lowly computer scientist, the practitioner of an artform that is delightfully neither truly about computers nor, properly, a science. Virtually everything we touch in computer science arose from a form of centipede mathematics. Constructive logic is the natural vocabulary of computer science. You obtain it by ripping double-negation out of classical logic and watching the system hobble along. The idealized category of Haskell types Hask is effectively used as a constructive analogue to Set. Theseus and Procrustes We can, however, turn this perspective around. In Greek mythology, Procrustes served as the final trial of Theseus during his travels to Athens. He would offer travelers along the road food and a night's lodging in a bed he promised would be a perfect fit. Upon their repose, he would proceed to set to work on them with a hammer to stretch them to fit, or an axe to cut off any excess length, forcing them to fit the bed. Worse, Procrustes kept two beds, so no traveler could ever measure up. While Theseus ultimately triumphed over the giant Procrustes, forcing him to fit his own bed by cutting off his head and feet, the concept lives on. In literary analysis, a Procrustean bed is an arbitrary standard to which exact conformity is enforced. Procrustean Mathematics Traditional mathematicians finds themselves often forced into the role of Procrustes with many such theoretical beds at their disposal, they can proceed by cutting off bits or adjoining pieces to satisfy the requirements of whatever mathematical construct in which they want to work. Conversely, the applied mathematician or computer scientist often finds themself in a situation where they care more about their problem patient, but can't find a bed to fit. Being a bit less psychopathic, they must set aside mathematical taste and adjust the bed. This is an exercise in centipede mathematics, the bed itself doesn't fit, so they rip parts off of it until it does. We don't do this because we hate the bed, but because we are concerned for the patient. The mathematician is looking out for the needs of the abstraction. The applied mathematician or computer scientist is looking out to maximize the fit for a given domain. The Operation Was a Success In a recent thread on Reddit it was suggested that every Semigroup should be extended to a Monoid and then we could be done with the need for the more refined concept. We can actually often accomplish this. Consider this Semigroup: newtype First a = First { getFirst :: a } instance Semigroup (First a) where m <> _ = m If you really want a Monoid you can lay about with Procrustes' hammer and adjoin a unit. newtype First a = First { getFirst :: Maybe a } instance Semigroup (First a) where First Nothing <> m = m m <> _ = m instance Monoid (First a) where mempty = First Nothing First Nothing `mappend` m = m m `mappend` _ = m Now our object has grown a bit more complicated, but we can use it with all the usual Foldable machinery. Sometimes the patient may be better off for his extra parts, but you may kill other properties you want along the way, or have to consider impossible cases. Having Semigroup as a more fine-grained constraint does enable us to handle the empty case once and for all, and lets us fold over a NonEmpty container with more things and capture the non-empty nature of something via Foldable1 and it simplifies First's implementation considerably, but requires you to use something like Option to lift it into a Monoid you can use for a general purpose list. Here this is simply a matter of taste, but that isn't always the case. ... But the Patient Died If you try to stretch any particular Comonad to fit Alternative, you have to deal with the fact that extract empty :: a This strongly implies no such beast can exist, and so the Comonad must die to make room for the Alternative instance. We have to give up either empty or extract. The type system has taken on the role of the serial killer Saw, sadistically forcing us to choose which of our friends will lose a limb. Even if you want to disavow centipede mathematics, you're going to be forced to occasionally put your abstractions on the chopping block, or abandon rigor. Haskell You may be able to upgrade an Applicative parser to one that is a Monad, perhaps at the cost of parallelism. Haskell's type system is very good at expressing a few well chosen abstractions. Monad used to be the golden hammer of the Haskell community, until we found out that Applicative functors exist and are useful for capturing context-free code, where the control flow doesn't vary based on previous results. Arrow was introduced along the way, but later had a smaller Category class carved out of it. Typeclasses in Haskell tend to force us into a small set of bed sizes, because it is relatively bad at code reuse across fine-grained class hierarchies. Each attempt at refining the class hierarchy carries with it a price that library implementors and users who instantiate the classes must now write more methods. Worse, they must often do so without access to the full gamut of extra laws obtained further down in the class hierarchy, because they don't have a tenable way of offering defaults for superclass methods when they write a subclass. Even with one of the superclass default proposals, you get no real code reuse for any form of transformer, and the existing default signature mechanism runs "the wrong way" in such a way that it even forces you to put everything in the same module. The initial arguments against a fine-grained class hierarchy in Haskell arose from the same place as the denigration of centipede mathematics, but they are butressed by the pragmatic concern that there is real pain in an accurate class hierarchy caused by the design of the language. These are valid concerns! Arguments in favor of a finer-grained hierarchy arise from a desire to avoid flooding the namespace with redundant operations, and to capture the relationship between things. It arises from caring about the needs of the things you want to be able to reason about, rather than capturing just the examples that happen to measure up to an arbitrary standard. These are also valid concerns! Semigroupoids My semigroupoids package was originally written because I couldn't work with product categories in Haskell, but needed them in code. I still can't, due to the presence of Any as a distinguished member of every kind in Haskell. Along the way, I dug up the -oid-ification of a Semigroup, also known as a semicategory to capture the portions of the product category that we can write nicely in Haskell today. When we look at the Kleisli category of things that are not quite a Monad, or the static arrow category of things that are not quite Applicative, we wind up with mere a Semigroupoid rather than a Category. But where do we find such examples? Consider the lowly IntMap. It cannot be made an instance of Applicative or Monad directly. We have three options to proceed if we want to work with something like (<*>) or (>>=) on it. We can clutter the namespace with a completely ad hoc combinator that we can't abstract over. We can try to adjoin a universal default. This means that you have to kill the Foldableand Traversableinstances for it, or deal with the fact that they basically return nonsense. It also means that you either have to give up the ability to delete from the map, or accept the fact that you aren't really modeling (Int -> Maybe b)any more. We can engage in a bit of centipede mathematics, ripping off the pureand returnfrom Applicativeand Monadrespectively to get a semi- Applicativeand a semi- Monad, which I unartfully called Applyand Bind, in semigroupoids. Now we've respected the needs of the domain object, at the expense of a finer grained class hierarchy. In a perfect world, from the perspective of the centipede mathematician, Apply and Bind would occupy a place of privilege in the class hierarchy. However, to the Procrustean mathematicians who are only really concerned with Applicative and Monad, and who can't be bothered to deal with the finer grained hierarchy, such a refinement of the hierarchy merely adds cognitive overhead. They are happy to discard these examples in favor of a simpler, more teachable, meta-theory. Both of these perspectives are valid. Extensible Effects To unfairly cast Oleg Kiselyov in the role of Procrustes with Edwin Brady as his understudy, we can look at the modeling of extensible effects in this same light. Lawvere theories offer us too small a bed to fit many of the effects we care to model, such as continuation passing. This is why that effect is ignored by Edwin Brady's handling of effects for Idris. They just don't fit. On the other hand, Oleg offers us a second bed that is much bigger, his Eff monad is the result of applying Codensity to a Lawvere Theory. Now it's the job of the handler to deal with the impossible cases. We're forced to set about with Procrustes' hammer to embed many monads, like Reader into a domain that is too large. Codensity ((->) s) a ~ forall r. (a -> s -> r) -> s -> r is strong enough to implement all of CPS'd State. If you pass it (,) for its first argument you get s -> (a, s)! It is only by convention and hiding that we can restrict such a reader down to size. This means that the compiler has really no chance of ever optimizing the code properly as it must always live in fear that you could change the environment, even though the handler never will. This forces a single thread of execution through otherwise parallelizable code. We improve the adjustability of this bed by switching from the Codensity construction to an arbitrary right Kan extension, like my old monad-ran package did. This lets the bed conform to the shape of Reader. Ran Identity ((->) s) a ~ Yoneda ((->) s) a ~ forall r. (a -> r) -> s -> r This is just a CPS'd function, when passed id we recover (s -> a). It is no longer large enough to model all of State and properly captures the features we want. Yet even this bed is still too small for some patients. The infinite usecases of lazy writer and lazy state monads still cannot be made to fit at all. This destroys many interesting use cases of the Tardis. Admittedly they are the kinds of things that tie users in knots. Perhaps like an appendix removal, your patients will not miss those parts. However, many monads for syntax trees like the transformer used by bound cannot be adapted without an asymptotic performance hit, causing you to redo whole calculations every time you want to pattern match on the result. From the standpoint of the Procrustean mathematician, the extensible effects approach is fairly elegant, it provides a single bed into which many common effects can fit. The elegance of this approach makes it very appealing! However, it isn't roomy enough to hold all of the current effects we can capture with monad transformers. Without upgrading to Ran, many effects are forced into a model that is too big, where you have to handle many impossible conditions that are merely ruled out by convention. On the other side, the inability to handle a number of cases that we do use in practice is also somewhat of a bad sign. This is why I can bring myself to view extensible effects as a usful way to think about effects, but I can't view it as a full replacement for the monad transformer approach. Monad transformers do pay an O(n^2) complexity tax, describing how everything commutes over everything else, but n is typically not that big of a number. The abilty to handle the extra cases that don't fit the extensible effects approach means I can't bring myself to just relegate them to the waste bin of history. As an applied mathematician / computer scientist, I still need to handle those effects! Concerns about the need to write lift . lift . lift, seem to arise from a particularly awkward style of use that I frankly never see in real code. There are ways to handle this and the multiple-state issues using tools we have, such as lenses. I'll relegate both of these concerns to another post. Lenses The lens package is very much an exercise in building a very fine grained set of distinctions and trying to make it so you can say very precisely what constraints you want to impose on each operator. Alternative designs like fclabels capture a different trade-off between factors. I, personally, find that the ability to express a Fold or Getter is worth the added complexity of the representation. Your mileage may vary. fclabels forces you to stretch each such thing into a form where you cannot express any laws, and then lays about with Procrustes' axe cutting of a number of abstractions we've found useful at the top end of the lens ecosystem, for Indexed traversals and the like. It is a pretty clean exercise in Procrustean mathematics, though. If you fit into the abstraction it models comfortably, you'll never feel the bite of the axe. Even lens, with its deep hierarchy, occasionally cuts you with Procrustes' axe. There are some constructions that just don't fit the domain. For instance lens offers no tool for validating input -- a Lens' s a must accept any such a. There is a tension between these design criteria as with Comonad and Alternative. Something had to give. Lens chooses a different point on the design curve than fclabels. The choice we made was to gain a great deal of expressive power and ability to reason about the code with laws in exchange for validation. The View from the Middle It is important to realize that modifying the abstraction/bed or modifying the problem/patient are both options. Sometimes you can easily adapt the problem to the mathematical construct, and sometimes the mathematical construct can be easily adapted to the problem. When we add laws and operatons to an abstraction, we wind up with fewer examples. If we work parametrically over an abstraction, the weaker the requirements we put on our inputs, the more scenarios we can cover. Other times one or the other is up against a hard constraint. It is very important to distinguish between the normative concerns of taste and the very real concerns that some times one or the other of these things cannot give, as in the Comonad/Alternative case above. To argue against a straw man, giving up either one of these degrees of freedom unilaterally strikes me as absurd. A hundred years ago, nobody cared about the foundations of mathematics, then came Russell and Whitehead, but their encoding was in many ways too dense and full of incredibly fine-grained distinctions. Competing tensions like this gave us the mathematical world we inhabit today. The choice of how to balance these factors, to abstract over enough problem domans to be useful without needlessly quibbling over impossibly fine-grained distinctions is really the true role of taste in library design and in mathematics, and tastes vary over time. October 25th, 2013
https://www.schoolofhaskell.com/user/edwardk/editorial/procrustean-mathematics
CC-MAIN-2016-50
refinedweb
3,421
58.21
Naming Conventions From Uncle Bob's Clean Code Philosophy Naming Conventions From Uncle Bob's Clean Code Philosophy Following this list of rules for naming variables, classes, and methods will help you write cleaner, more professional code. Join the DZone community and get the full member experience.Join For Free Do you need to strengthen the security of the mobile apps you build? Discover more than 50 secure mobile development coding practices to make your apps more secure. This article is the result of reading the book "Clean Code" by Robert C Martin. All the recommendations made here are suggested by Robert C Marin. This article covers the abstract of naming conventions suggested by Clean Code. 1. Introduction The clean code philosophy is seems be to emerged from the fundamentals of Software Craftsmanship. According to many software experts who have signed the Manifesto for Software Craftsmanship, writing well-crafted and self-explanatory software is almost as important as writing working software. Following are the snippets from the book, show why naming is hard and disputable and the mindset to address this problem: "The hardest thing about choosing good names is that it requires good descriptive skills and a shared cultural background. This is a teaching issue rather than a technical, business or management issue." "Focus on whether the code reads like paragraphs and sentences, or at least tables and data structure." 2. Naming Conventions 2.1. Use Intention-Revealing Names Basically, don't name a variable, class, or method which needs some explanation in comments. For example: int d; // elapsed time in days int s; // elapsed time in seconds Can be named as: int elapsedTimeInDays; int daysSinceCreation; int daysSinceModification; int fileAgeInDays; 2.2. Avoid Disinformation and Encodings Don't refer to a group of accounts as "accountList," whereas it is actually not a List. Instead, name it "accountGroup," "accounts," or "bunchOfAccounts." Avoid unnecessary encodings of datatypes along with the variable name. String nameString; Float salaryFloat; It may not be necessary where it is very well known to the entire world that in an employee context, the name is going to have a sequence of characters. The same goes for Salary, which is decimal/float. 2.3. Make Meaningful Distinctions If there are two different things in the same scope, you might be tempted to change one name in an arbitrary way. What is stored in cust, which is different from customer? String cust; String customer; How are these classes different? class ProductInfo class ProductData How do you differentiate between these methods in the same class? void getActiveAccount() void getActiveAccounts() void getActiveAccountsInfo() So, the suggestion here is to make meaningful distinctions. 2.4. Use Pronounceable Names Ensure that names are pronounceable. Nobody wants a tongue twister. This Date genymdhms; Date modymdhms; Int pszqint; vs Date generationTimeStamp; Date modificationTimestamp; Int publicAccessCount; 2.5. Use Searchable Names Avoid single letter names and numeric constants, if they are not easy to locate across the body of the text. grep "MAX_STUDENTS_PER_TEACHER" *.java vs grep 15 *.java Use single letter names only used as local variables in short methods. One important suggestion is that "the length of a name should be correspond to the size of its scope." 2.6. Don't Be Cute/Don't Use Offensive Words deleteAllItems() vs whack() vs kill() vs eatMyShorts() vs abort() 2.7. Pick One Word per Concept Use the same concept across the codebase. FetchValue() vs GetValue() vs RetrieveValue() If you are using fetchValue() to return a value of something, use the same concept; instead of using fetchValue() in all the code, using getValue(), retrieveValue() will confuse the reader. dataFetcher() vs dataGetter() vs dataFetcher() If all three methods do the same thing, don't mix and match across the code base. Instead, stick to one. FeatureManager vs FeatureController Stick to either Manager or Controller. Again, consistency across the codebase for the same thing. 2.8. Don't Pun This is exactly opposite of previous rule. Avoid using the same word for two different purposes. Using the same term for two different ideas is essentially pun. For example, say you have two classes having the same add() method. In one class, it performs addition of two values, in another, it inserts an element into a list. So, choose wisely; in the second class use insert() or append() instead of add(). 2.9. Solution Domain Names vs Problem Domain Names The clean code philosophy suggests using solution domain names such as the name of algorithms or the name of design patterns whenever needed, and use a problem domain name as the second choice. For example, accountVisitor means a lot to a programmer who is familiar with the Visitor design pattern. A "JobQueue" definitely make more sense to a programmer. 2.10. Add Meaningful Context as a Last Resort While there are a few names which are meaningful themselves, most are not. Instead, you have to place names in context for your reader by enclosing them in well-named classes, functions, or namespaces. If not possible, prefixing the names may be necessary as a last resort. For example, the member variable named "state" inside the address class shows what it contains. But the same "state" may be misleading if used to store "Name of The State" without context. So, in this scenario, name it something like "addressState" or "StateName." The "state" may make more sense in a context where you are coding about addresses when named "addrState." 3. Summary Robert C. Martin says, "One difference between a smart programmer and a professional programmer is that the professional understands that clarity is king. Professionals use their powers for good and write code that others can understand." I hope this article will help you to be more professional and write clean code, for further reading refer to "Clean Code: A Handbook of Agile Software Craftsmanship." 4. References - - - - Appendix Manifesto for Agile. Check out tips for blazing the way from agile to DevSecOps with security built into your mobile app toolchain. Published at DZone with permission of Saravanan Subramanian , DZone MVB. See the original article here. Opinions expressed by DZone contributors are their own. {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/naming-conventions-from-uncle-bobs-clean-code-phil
CC-MAIN-2019-04
refinedweb
1,032
55.64
Hello, I created a dynamic item page and followed the instructions form the article below to create previous/next buttons, but I'm having issues with my urls in the code so the buttons are not working. Can I get some feedback on what I'm doing wrong here. Hello Yevette, Are you importing local from Wix-storage? Hello Ido, Thank you for the advice. That cleared up the "local" error. However I am still having issues with the "https". Did I copy the url incorrectly? incorrectly? Hi Yvette, 'local.setItem' accepts two parameters, the first one is a 'Key' and the second one is 'Value'. In the article, they have the following line: Which actually sets the Key named 'dynamicPageURLs' to be an array of URLs (which is what you get when calling 'result.items.map' if the previous line). Hope this helps, Liran. I'm having the same problem. Followed the tutorial and my previous/next buttons are not working on my item page. This is my code for review. I got "link-Member-Applications-emailText" from the database, from the field that was auto-generated when I created and linked the Item page to my Index page. Something strange happens and I'm not sure if it's related, in the editor when I open the page code, it shows the little error icons beside the line numbers, then it disappears once I click in the code. Okay, so upon further inspection, I have found that the next button works but no matter which item you are viewing, the button takes you to the first item in the dataset. Hi! First thing is known and handled (apperaing erros for second) Second is something strange, but looks like you don't have anyitems in your local storage Is it possible to share link to your site here? I can check Yes, I wish there was a way to private message though. Please let me know when you no longer need the URLs, so I can delete them. Index Page redacted url Item Page redacted url Copied those and checking, so please delete Hi! Found the problem Why did you delete this part from original tutorial?) tutorial - const currentPage = '/' + wixLocation.prefix + '/' + wixLocation.path.join('/'); your site - const currentPage = '/' + wixLocation.path.join('/'); This causes the issue. It tries to find this - /leafrielcoyle%40gmail.com in this array - /Member-Applications/testemail3%40gmail.com,/Member-Applications/testemail2%40gmail.com,/Member-Applications/testemail1%40gmail.com,/Member-Applications/leafrielcoyle%40gmail.com,/Member-Applications/jaded.rogue%40gmail.com And it doesn't succeed, because there is no such item I honestly don't know know how that happened.... I thought I had copied it perfectly.... 😅😅😅 I'm sure it'll work but I'll let you know once I've confirmed. Thank You Mikhail! Much Appreciated! xx YAY! as expected, that fixed it. Thank You! One final question. Is there a way to loop the entries? So when you're on the first item, if you click the previous button it takes you to the last item. And if you're on the last item and you click the next button, it takes you back to the first item? Yes, you should add more conditions - if (currentPageIndex = 0) { ... set wixLocation.to to last item on prevButton ... } if (currentPageIndex = dynamicPageURLs.length {... set wixLocation.to to first item on nextButton ... } but i won't write code for you, i can only give you heneral idea how to achieve this I'm fine with that! I should just need a point in the right direction ^_^ Thanks so much Mikhail! Cheers! 🍻 I'm have some difficulties with adding a "Next button and a Previous button" on a single not a category Dynamic page. I just can't figure it out. I've followed steps #8 from the tutorial below and nothing happened 8. Create Previous and Next Buttons Now that all your elements are connected to the same collection through the same dataset, you need to allow your visitors to browse through the information. To do this, add two buttons to your page, connect them to the same dataset as the other elements, and define their click actions. To create Previous and Next buttons: Add two buttons to your page and change their texts to Previous and Next. Click their Connect to Data In the Connect Button panel, select your dataset. Under Link connects to, select Previous for the first button and Next for the second button. So I then followed the tutorial below and I'm confused and don't know what I'm supposed to add in import {local} from 'wix-storage'; to resolve the error message on line 6? Also am I supposed to be on the site or the page when adding this code? Thank you for any help Lines 6 and 7 need to be at the top of the code before everything else, basically just delete everything before them as you've currently got the onReady function for the page happening before you've imported anything. Like this: Plus, you won't need anything past line 30 either, so delete 31 to 33. However, as you are not using dynamic pages, then that tutorial might not be any good for you unless you change your pages to dynamic pages. Look at this link: Try something like this as stated on that link: Get the previous page within a Wix site This example demonstrates how to use session storage to know which page is the page a site visitor previously visited. The code below needs to be placed in the Site tab so that it runs on all your. This is another back button code example from Yisrael (Wix Mod): This example shows how to implement a Back Button to allow the site visitor to return to the previously viewed site page. This feature will only work for a published site and will not work in the Editor. Note that the code is added to the Site tab of the code so that it is available on all pages. Hi, Can you specify the name of the page ? Roi hi, i am having some issue with my next and previous button. i used the technique from for some reason the wixLocation.path.join ('/') only give me a value of yoursitename and not the info of the page i need. this page work perfectly but than i get stuck at getting the link with ^^' can someone please help me? Go back and read the page again. On the dynamic item page, begin by adding two buttons to the page. Feel free to change the design and text of the buttons, but make sure not to add any links to the buttons. The code we will add to the dynamic item page does the following: Disables the previous and next buttons You need to change your code: You need to have the buttons as disabled and not hidden, otherwise the code does not work as the buttons are still active despite being set as hidden and so the if statements won't be able to enable them. Also change the last line on each if statement too: You can't have visible or hidden in your code setup, you are mixing up hidden/visible with hide/show and should be used as below: See more here: @givemeawhisky hi thanks for taking the time to respond. I found my error earlier which was to publish the website. the reason i used isVisible and hidden is that my button are actually image. image doesnt have those attribut (kept saying error) so i used those two instead and it works ^^ tried your hide() function. So much better thanks ^^
https://www.wix.com/corvid/forum/community-discussion/previous-next-button-for-dynamic-pages
CC-MAIN-2020-05
refinedweb
1,290
71.95
23 April 2012 05:20 [Source: ICIS news] SINGAPORE (ICIS)--?xml:namespace> However, the PMI rose to a two-month high of 49.1 in April, compared with a final reading of 48.3 in March, the bank said in a statement. A figure above 50 indicates an expansion, while a figure below 50 represents a contraction. The sub-indices for both new export orders and output contracted in April, but the decrease was at a slower rate compared with March, it said. "As April flash PMI ticked higher, this suggests that the earlier easing measures have started to work and hence should ease concerns of a sharp growth slowdown," said Qu Hongbin, HSBC’s chief economist for China. However, both output and demand growth remained at a slow pace and the country’s job market is still under pressure, Qu said. “This calls for additional easing measures in the coming months," he said, adding that HSBC expects monetary and fiscal easing to speed up in the second quarter.
http://www.icis.com/Articles/2012/04/23/9552553/china+manufacturing+activity+shrinks+in+april++hsbc.html
CC-MAIN-2013-20
refinedweb
169
70.33
13 September 2012 10:04 [Source: ICIS news] MELBOURNE (ICIS)--?xml:namespace> The No 1 phenol/acetone plant, which can produce 190,000 tonnes/year of phenol and 114,000 tonnes/year of acetone, was taken off line on 22 August to undergo modification work that would enable the cumene unit to produce cymene as well as cumene. Cumene, a feedstock for phenol/acetone, is an intermediate produced from benzene and propylene. Cymene is the feedstock of meta/para-cresol. Mitsui Chemicals’ cymene production unit at Iwakuni-Ohtake Works in Yamaguchi prefecture was severely damaged by an explosion and fire in April this year. A reduced cumene supply means that Mitsui Chemicals will continue to cap its No 1 phenol/acetone output at 60% capacity until late 2013, when the restoration of the cymene production unit at Iwakuni-Ohtake Works is scheduled to complete. The No 1 phenol/acetone plant will be shut for annual maintenance between 17 October and 29 Nove
http://www.icis.com/Articles/2012/09/13/9595061/japans-mitsui-chem-runs-chiba-no-1-phenolacetone-plant-at.html
CC-MAIN-2015-22
refinedweb
162
50.16
This article is from the archive of our partner . The few lucky couples who were able to get married in the seven-hour window between a federal court judge's ruling that Michigan's same-sex marriage ban was unconstitutional and a federal appeals court staying his decision will not have those marriage recognized by state agencies -- at least for now. Governor Rick Snyder's spokeswoman told the AP that his office won't make a decision until the stay on the federal judge's order is resolved, and that the issue was "moot" until then. "The governor and administration are not weighing in on these issues at this point," she said. That means that the approximately 300 same-sex couples that married yesterday will not yet be entitled to the same in-state benefits opposite-sex couples enjoy. Snyder's decision could go either way. While California and New Mexico decided to allow state benefits for same-sex couples that were married in their temporary windows, Utah has not. They will receive federal benefits. Update, 8:43 p.m.: The Detroit Free Press has more on this. One couple that managed to get married in time say they have no idea what's going on with their marriage right now. They've already filed a joint tax return (an hour before the stay was issued). At some point between now and Wednesday, the federal court will decide whether or not to make the stay permanent, and then the governor will have to decide what do. This article is from the archive of our partner The Wire. We want to hear what you think about this article. Submit a letter to the editor or write to letters@theatlantic.com.
https://www.theatlantic.com/national/archive/2014/03/michigan-wont-recognize-those-seven-hour-window-same-sex-marriages/359453/
CC-MAIN-2019-26
refinedweb
289
62.78
What does enable-xdr in global and namespace context control? Detail This article explains what the enable-xdr configuration at global and at namespace level controls and when does XDR connect to a remote DC and ship records. enable-xdr is a dynamically configurable parameter, which exists at 2 different contexts: global as well as namespace. This controls only the logging of digest entries in the digest log. It does not control the shipping of records. Logging into the digest log and shipping are 2 different things. Digest logging Refer to the 2 enable-xdr entries in the Log Reference Manual and notice the 2 different contexts, xdr as well as namespace. For digests to be logged in the digest log ( xdr-digest-log-path, the global xdr context should always have enable-xdr set to true. Digests will not be logged in the digest log if enable-xdr is set to false on the global level, irrespective of the value at the namespace level. In the namespace context, for every namespace one can control whether the digest log entires should be logged for that namespace on that node by setting enable-xdr to true or false at the namespace level. The following table details the different possibilities: For a given namespace, digest log entries will be logged only when enable-xdr is true in both the global as well as namespace contexts. Connecting to a destination DC. As of Aerospike Enterprise Edition 3.14, XDR will only connect to a destination DC if it is seeded at the global xdr context and if at least one namespace is associated with it. Shipping If there are records in the digest log that have not been processed (determined by the xdr-ship-outstanding-objects metric), XDR will keep shipping the related records irrespective of whether enable-xdr is set to true or false. This is because enable-xdr only determines whether the digest entries are logged into the digest log or not. enable-xdr does not control the shipping. Note: By default, xdr always keep shipping if there are pending records in the digest log. This can be controlled using xdr-shipping-enabled config. It is usually not recommended to change this configuration outside of very specific situations. Keywords XDR digestlog digest enable-xdr shipping Timestamp 01/06/2018
https://discuss.aerospike.com/t/impact-of-enable-xdr-global-v-s-namespace-context/5248
CC-MAIN-2018-30
refinedweb
388
53.81
Introduction to Ruby Variables Variables in Ruby are the memory location where we store the data, and these data will be used by ruby developers when needed. In ruby it supports 5 types of data they are global variable(begin with $, the global variable are available for all and its value will be nil; by default, use global variables only if it required otherwise avoid using it), instance variable (begin with @ and having scope up to particular instances), class variable (begin with @@), Local variable (Local variables having scope upto class, module and def )and constant variable(start with upper case and can not reassign or modify). How to Declare & Initialize Variables in Ruby? Declaration and initialization for the Ruby variable can be done in the below formats. - For Global Variable: Global variables are the variables which are available for all the scope, but global variables are not secure to use, so we need to make sure the requirement while using them. Global variables start with dollar sign like. $ruby_global_variable = 15 - For Instance Variables: Instance variables can be initialized with @ symbol and the default value for it will be nil. @ruby_instance_variable = 15 - For Class Variables: Class variables are initialized with @@ and will be defined inside the class. @@ruby_class_variables = 15 - For Local Variables: Ruby local variables are defined with _ and their scopes are range from def,method to classes. _ruby_local_variables = 15 - For Constant Variables: Constant variables in ruby are in upper case letters and can not be re-assigned once assigned the value. CONSTANT1 =15 CONSTANT2 =20 Types of Variables in Ruby Below are the types of Variables: 1. Global Variable Global variables are start with a dollar($) symbol and contain nil value by default. It is not advisable to use the global variable in all cases. Example: In the below example we have defined a variable $ruby_global and it can be accessed inside the two classes called RubyClass1 and RubyClass2. As both, the classes contain a function print_ruby_global which we are on instances of classes. Please follow the below example along with the screen of outputs. Code: $ruby_global_variable = 11 class RubyClass1 def print_ruby_global puts "RubyClass1 global variable output is #$ruby_global_variable" end end class RubyClass2 def print_ruby_global puts "RubyClass2 global variable output is #$ruby_global_variable" end end rubyclass1obj = RubyClass1.new rubyclass1obj.print_ruby_global rubyclass2obj = RubyClass2.new rubyclass2obj.print_ruby_global Output: 2. Instance Variables Instance variables start with @ symbol. Examples for instance variables is given below. Example: Below example can be explained in the following steps: - We have defined a class with the name UserClass and inside this class, we have initialized the three variables. - Inside this class, we have defined a function called show_detail. - We finally created objects from the UserClass and with the initialized object(instance) we are calling the function show_detail. And the output for each attribute of the user will be visible to us. Code: class UserClass def initialize(user_id, user_name, address) @user_id = user_id @user_name = user_name @user_addr = address end def show_details() puts "user id is #@user_id" puts "name of the User is #@user_name" puts "User address is #@user_addr" end end # user1 = UserClass.new("1", "Ranjan", "Mount View Apartment guindy, Chennai") user2 = UserClass.new("2", "Ajay", "B-9 Dhanbad, Jharkhand") user3 = UserClass.new("2", "Sujoy", "T nagar, Chennai") user4 = UserClass.new("2", "Vijay", "New ashok nagar, Delhi") # Call the Methods of class for displaying the details user1.show_details() user2.show_details() user3.show_details user4.show_details Output: 3. Class Variables Class variables can be defined with the @@ symbol. If someone will override the class variable then it will show a warning. Below example can be explained in the following steps: - First, we defined a class with the name User, this class contains the initializations for the three variables. - Next, we defined a function called show_details, this function contains the logic to display the details of the users. - Next, we have created the function for giving the user count, each time the function will get called from the User object and its value will get updated and display the updated value. Please follow the below example along with the output of the screen. Code: class User @@no_of_users = 0 def initialize(u_id, u_name, u_address) @user_id = u_id @user_name = u_name @user_addr = u_address end def show_details() puts "User ID is #@user_id" puts "User name is #@user_name" puts "User Address is #@user_addr" end def total_users() @@no_of_users += 1 puts "Count for the total number of users is: #@@no_of_users" end end user1 = User.new("1", "Ranjan", "Mount View Apartment guindy, Chennai") user2 = User.new("2", "Ajay", "B-9 Dhanbad, Jharkhand") user3 =User.new("2", "Sujoy", "T nagar, Chennai") user4 =User.new("2", "Vijay", "New ashok nagar, Delhi") # Call the Methods of class for displaying the details user1.total_users() user2.total_users() user3.total_users() user4.total_users() Output: 4. Constant Variables Constant variables start with the upper case letter. The constant variables can not reassign their values. Constants defined inside the class can be accessed inside the class and those defined inside the modules can be accessed inside the modules, we can also define the constant as the global which outside the class and module and will be available for all. An example of the constant variable is given below. Explanation: - First, we have created a class with the name Example For Constant and this class contains two variables (CONSTANT1 and CONSTANT2). - We created a function inside the class Example For Constant with name display_constant and this function contains the logic to display both constant values. Example: Code: class ExampleForConstant CONSTANT1 = 101 CONSTANT2 = 201 def display_constant puts "constant first value is #{CONSTANT1}" puts "constant second value is #{CONSTANT2}" end end # create an object and call the method display_constant. object = ExampleForConstant.new() object.display_constant Output: Conclusion From this tutorial we learned about Ruby variables along with the available constant into it, we learned that there are mainly five types of variables they are global, local, instance, constant and class variable, we also learn the way to use each type of these variables. Recommended Article This is a guide to Ruby Variables. Here we discuss ruby variables along with the available constant and its different types of variables they are global, local, instance, constant, and a class variable. You can also go through our other suggested articles to learn more –
https://www.educba.com/ruby-variables/?source=leftnav
CC-MAIN-2022-40
refinedweb
1,033
52.8
Important: Please read the Qt Code of Conduct - SwipeView swipes when it shouldn't - I have a SwipeView with 3 pages. - One page has a CustomKnob, which is simply an Image with a MouseArea filling it - You click and drag on the Image in the y direction to edit the knob. It works great, I change the knob image as I drag in Y and it looks good - Now, I'd like to have any click and drag in x on the Knob not pass to the SwipeView, because it should not pass through. I tried adding this to the MouseArea: onMouseXChanged: { mouse.accepted = true } This does not cause the SwipeView to ignore minor movement in X when swiping on the Knob in y What can I do to get SwipeView to ignore X dragging on a child control? Normally these types of events do not propagate through a MouseArea. A parent widget will not act on it and treat it as a swipe gesture. Qt 5.15.2 QML SwipeView Here's some example code. How can it be changed so that clicking and dragging in the x direction on the orange square is ignored by the SwipeView? import QtQuick 2.12 import QtQuick.Controls 2.5 ApplicationWindow { id: appWindow width: 640; height: 480 visible: true SwipeView { id: swipeView anchors.fill: parent currentIndex: 1 Rectangle { width: appWindow.width; height: appWindow.height color: "red" } Rectangle { width: appWindow.width; height: appWindow.height color: "green" Rectangle { width: 100; height: 100 anchors.centerIn: parent color: "orange" MouseArea { anchors.fill: parent onMouseXChanged: { mouse.accepted = true } } } } Rectangle { width: appWindow.width; height: appWindow.height color: "blue" } } // end SwipeView } Setting MouseArea.preventStealing to true might work. Hi jeremy_k, Thanks for the idea. I tried adding preventStealing: true to the MouseArea, but it didn't help. I'm beginning to think there is no way to tell a SwipeView to not swipe when children controls are being clicked and dragged. That's a serious flaw that no one would want. I wonder if it ever worked properly. Thanks again for your thoughts. - Steve
https://forum.qt.io/topic/124095/swipeview-swipes-when-it-shouldn-t
CC-MAIN-2021-10
refinedweb
345
77.13
This book is my favorite sort of history: an exploration of the minds and viewpoints of the people who lived it. The medieval world-view is so alien to us, and Huizinga lets us glimpse it. Month: July 2010 3-D Shmee-D I watched a 1-D film yesterday. Good acting, but I thought the plot was too linear. Book: Mohammed and Charlemagne Twisted Daemonologie Part 16: Twisted Daemonologie This continues the introduction started here. You can find an index to the entire series here. Introduction The servers we have written so far have just run in a terminal window, with output going to the screen via - Run as a daemon process, unconnected with any terminal or user session. You don’t want a service to shut down just because the administrator logs out. - Send debugging and error output to a set of rotated log files, or to the syslog service. - Drop excessive privileges, e.g., switching to a lower-privileged user before running. - Record its pid in a file so that the administrator can easily send signals to the daemon. We can get all of those features using the twistd script provided by Twisted. But first we’ll have to change our code a bit. The Concepts Understanding twistd will require learning a few new concepts in Twisted, the most important being a Service. As usual, several of the new concepts are accompanied by new Interfaces. IService The IService interface defines a named service that can be started and stopped. What does the service do? Whatever you like — rather than define the specific function of the service, the interface requires only that it provide a small set of generic attributes and methods. There are two required attributes: name and running. The name attribute is just a string, like 'fastpoetry', or None if you don’t want to give your service a name. The running attribute is a Boolean value and is true if the service has been successfully started. We’re only going to touch on some of the methods of IService. We’ll skip some that are obvious, and others that are more advanced and often go unused in simpler Twisted programs. The two principle methods of IService are startService and stopService: def startService(): """ Start the service. """ def stopService(): """ Stop the service. @rtype: L{Deferred} @return: a L{Deferred} which is triggered when the service has finished shutting down. If shutting down is immediate, a value can be returned (usually, C{None}). """ Again, what these methods actually do will depend on the service in question. For example, the startService method might: - Load some configuration data, or - Initialize a database, or - Start listening on a port, or - Do nothing at all. And the stopService method might: - Persist some state, or - Close open database connections, or - Stop listening on a port, or - Do nothing at all. When we write our own custom services we’ll need to implement these methods appropriately. For some common behaviors, like listening on a port, Twisted provides ready-made services we can use instead. Notice that stopService may optionally return a deferred, which is required to fire when the service has completely shut down. This allows our services to finish cleaning up after themselves before the entire application terminates. If your service shuts down immediately you can just return None instead of a deferred. Services can be organized into collections that get started and stopped together. The last IService method we’re going to look at, setServiceParent, adds a Service to a collection: def setServiceParent(parent): """ Set the parent of the service. @type parent: L{IServiceCollection} @raise RuntimeError: Raised if the service already has a parent or if the service has a name and the parent already has a child by that name. """ Any service can have a parent, which means services can be organized in a hierarchy. And that brings us to the next Interface we’re going to look at today. IServiceCollection The IServiceCollection interface defines an object which can contain IService objects. A service collection is a just plain container class with methods to: - Look up a service by name ( getServiceNamed) - Iterate over the services in the collection ( __iter__) - Add a service to the collection ( addService) - Remove a service from the collection ( removeService) Note that an implementation of IServiceCollection isn’t automatically an implementation of IService, but there’s no reason why one class can’t implement both interfaces (and we’ll see an example of that shortly). Application A Twisted Application is not defined by a separate interface. Rather, an Application object is required to implement both IService and IServiceCollection, as well as a few other interfaces we aren’t going to cover. An Application is the top-level service that represents your entire Twisted application. All the other services in your daemon will be children (or grandchildren, etc.) of the Application object. It is rare to actually implement your own Application. Twisted provides an implementation that we’ll use today. Twisted Logging Twisted includes its own logging infrastructure in the module twisted.python.log. The basic API for writing to the log is simple, so we’ll just include a short example located in basic-twisted/log.py, and you can skim the Twisted module for details if you are interested. We won’t bother showing the API for installing logging handlers, since twistd will do that for us. FastPoetry 2.0 Alright, let’s look at some code. We’ve updated the fast poetry server to run with twistd. The source is located in twisted-server-3/fastpoetry.py. First we have the poetry protocol: class PoetryProtocol(Protocol): def connectionMade(self): poem = self.factory.service.poem log.msg('sending %d bytes of poetry to %s' % (len(poem), self.transport.getPeer())) self.transport.write(poem) self.transport.loseConnection() Notice instead of using a twisted.python.log.msg function to record each new connection. Here’s the factory class: class PoetryFactory(ServerFactory): protocol = PoetryProtocol def __init__(self, service): self.service = service As you can see, the poem is no longer stored on the factory, but on a service object referenced by the factory. Notice how the protocol gets the poem from the service via the factory. Finally, here’s the service class itself: class PoetryService(service.Service): def __init__(self, poetry_file): self.poetry_file = poetry_file def startService(self): service.Service.startService(self) self.poem = open(self.poetry_file).read() log.msg('loaded a poem from: %s' % (self.poetry_file,)) As with many other Interface classes, Twisted provides a base class we can use to make our own implementations, with helpful default behaviors. Here we use the twisted.application.service.Service class to implement our PoetryService. The base class provides default implementations of all required methods, so we only need to implement the ones with custom behavior. In this case, we just override startService to load the poetry file. Note we still call the base class method (which sets the running attribute for us). Another point is worth mentioning. The PoetryService object doesn’t know anything about the details of the PoetryProtocol. The service’s only job is to load the poem and provide access to it for any object that might need it. In other words, the PoetryService is entirely concerned with the higher-level details of providing poetry, rather than the lower-level details of sending a poem down a TCP connection. So this same service could be used by another protocol, say UDP or XML-RPC. While the benefit is rather small for our simple service, you can imagine the advantage for a more realistic service implementation. If this were a typical Twisted program, all the code we’ve looked at so far wouldn’t actually be in this file. Rather, it would be in some other module(s) (perhaps fastpoetry.protocol and fastpoetry.service). But following our usual practice of making these examples self-contained, we’ve including everything we need in a single script. Twisted tac files The rest of the script contains what would normally be the entire content — a Twisted tac file. A tac file is a Twisted Application Configuration file that tells twistd how to construct an application. As a configuration file it is responsible for choosing settings (like port numbers, poetry file locations, etc.) to run the application in some particular way. In other words, a tac file represents a specific deployment of our service (serve that poem on this port) rather than a general script for starting any poetry server. If we were running multiple poetry servers on the same host, we would have a tac file for each one (so you can see why tac files normally don’t contain any general-purpose code). In our example, the tac file is configured to serve poetry/ecstasy.txt run on port 10000 of the loopback interface: # configuration parameters port = 10000 iface = 'localhost' poetry_file = 'poetry/ecstasy.txt' Note that twistd doesn’t know anything about these particular variables, we just define them here to keep all our configuration values in one place. In fact, twistd only really cares about one variable in the entire file, as we’ll see shortly. Next we begin building up our application: # this will hold the services that combine to form the poetry server top_service = service.MultiService() Our poetry server is going to consist of two services, the PoetryService we defined above, and a Twisted built-in service that creates the listening socket our poem will be served from. Since these two services are clearly related to each other, we’ll group them together using a MultiService, a Twisted class which implements both IService and IServiceCollection. As a service collection, the MultiService will group our two poetry services together. And as a service, the MultiService will start both child services when the MultiService itself is started, and stop both child services when it is stopped. Let’s add the first poetry service to the collection: # the poetry service holds the poem. it will load the poem when it is # started poetry_service = PoetryService(poetry_file) poetry_service.setServiceParent(top_service) This is pretty simple stuff. We just create the PoetryService and then add it to the collection with setServiceParent, a method we inherited from the Twisted base class. Next we add the TCP listener: # the tcp service connects the factory to a listening socket. it will # create the listening socket when it is started factory = PoetryFactory(poetry_service) tcp_service = internet.TCPServer(port, factory, interface=iface) tcp_service.setServiceParent(top_service) Twisted provides the TCPServer service for creating a TCP listening socket connected to an arbitrary factory (in this case our PoetryFactory). We don’t call reactor.listenTCP directly because the job of a tac file is to get our application ready to start, without actually starting it. The TCPServer will create the socket after it is started by twistd. You might have noticed we didn’t bother to give any of our services names. Naming services is not required, but only an optional feature you can use if you want to ‘look up’ services at runtime. Since we don’t need to do that in our little application, we don’t bother with it here. Ok, now we’ve got both our services combined into a collection. Now we just make our Application and add our collection to it: # this variable has to be named 'application' application = service.Application("fastpoetry") # this hooks the collection we made to the application top_service.setServiceParent(application) The only variable in this script that twistd really cares about is the application variable. That is how twistd will find the application it’s supposed to start (and so the variable has to be named ‘application’). And when the application is started, all the services we added to it will be started as well. Figure 34 shows the structure of the application we just built: Running the Server Let’s take our new server for a spin. As a tac file, we need to start it with twistd. Of course, it’s also just a regular Python file, too. So let’s run it with Python first and see what happens: python twisted-server-3/fastpoetry.py If you do this, you’ll find that what happens is nothing! As we said before, the job of a tac file is to get an application ready to run, without actually running it. As a reminder of this special purpose of tac files, some people name them with a .tac extension instead of .py. But the twistd script doesn’t actually care about the extension. Let’s run our server for real, using twistd: twistd --nodaemon --python twisted-server-3/fastpoetry.py After running that command, you should see some output like this: 2010-06-23 20:57:14-0700 [-] Log opened. 2010-06-23 20:57:14-0700 [-] twistd 10.0.0 (/usr/bin/python 2.6.5) starting up. 2010-06-23 20:57:14-0700 [-] reactor class: twisted.internet.selectreactor.SelectReactor. 2010-06-23 20:57:14-0700 [-] __builtin__.PoetryFactory starting on 10000 2010-06-23 20:57:14-0700 [-] Starting factory <__builtin__.PoetryFactory instance at 0x14ae8c0> 2010-06-23 20:57:14-0700 [-] loaded a poem from: poetry/ecstasy.txt Here’s a few things to notice: - You can see the output of the Twisted logging system, including the PoetryFactory‘s call to log.msg. But we didn’t install a logger in our tac file, so twistd must have installed one for us. - You can also see our two main services, the PoetryServiceand the TCPServerstarting up. - The shell prompt never came back. That means our server isn’t running as a daemon. By default, twistd does run a server as a daemon process (that’s the main reason twistd exists), but if you include the --nodaemon option then twistd will run your server as a regular shell process instead, and will direct the log output to standard output as well. This is useful for debugging your tac files. Now test out the server by fetching a poem, either with one of our poetry clients or just netcat: netcat localhost 10000 That should fetch the poem from the server and you should see a new log line like this: 2010-06-27 22:17:39-0700 [__builtin__.PoetryFactory] sending 3003 bytes of poetry to IPv4Address(TCP, '127.0.0.1', 58208) That’s from the call to log.msg in PoetryProtocol.connectionMade. As you make more requests to the server, you will see additional log entries for each request. Now stop the server by pressing Ctrl-C. You should see some output like this: ^C2010-06-29 21:32:59-0700 [-] Received SIGINT, shutting down. 2010-06-29 21:32:59-0700 [-] (Port 10000 Closed) 2010-06-29 21:32:59-0700 [-] Stopping factory <__builtin__.PoetryFactory instance at 0x28d38c0> 2010-06-29 21:32:59-0700 [-] Main loop terminated. 2010-06-29 21:32:59-0700 [-] Server Shut Down. As you can see, Twisted does not simply crash, but shuts itself down cleanly and tells you about it with log messages. Notice our two main services shutting themselves down as well. Ok, now start the server up once more: twistd --nodaemon --python twisted-server-3/fastpoetry.py Then open another shell and change to the twisted-intro directory. A directory listing should show a file called twistd.pid. This file is created by twistd and contains the process ID of our running server. Try executing this alternative command to shut down the server: kill `cat twistd.pid` Notice that twistd cleans up the process ID file when our server shuts down. A Real Daemon Now let’s start our server as an actual daemon process, which is even simpler to do as it’s twistd‘s default behavior: twistd --python twisted-server-3/fastpoetry.py This time we get our shell prompt back almost immediately. And if you list the contents of your directory you will see, in addition to the twistd.pid file for the server we just ran, a twistd.log file with the log entries that were formerly displayed at the shell prompt. When starting a daemon process, twistd installs a log handler that writes entries to a file instead of standard output. The default log file is twistd.log, located in the same directory where you ran twistd, but you can change that with the --logfile option if you wish. The handler that twistd installs also rotates the log whenever the size exceeds one megabyte. You should be able to see the server running by listing all the processes on your system. Go ahead and test out the server by fetching another poem. You should see new entries appear in the log file for each poem you request. Since the server is no longer connected to the shell (or any other process except init), you cannot shut it down with Ctrl-C. As a true daemon process, it will continue to run even if you log out. But we can still use the twistd.pid file to stop the process: kill `cat twistd.pid` And when that happens the shutdown messages appear in the log, the twistd.pid file is removed, and our server stops running. Neato. It’s a good idea to check out some of the other twistd startup options. For example, you can tell twistd to switch to a different user or group account before starting the daemon (typically a way to drop privileges your server doesn’t need as a security precaution). We won’t bother going into those extra options, you can find them using the --help switch to twistd. The Twisted Plugin System Ok, now we can use twistd to start up our servers as genuine daemon processes. This is all very nice, and the fact that our “configuration” files are really just Python source files gives us a great deal of flexibility in how we set things up. But we don’t always need that much flexibility. For our poetry servers, we typically only have a few options we might care about: - The poem to serve. - The port to serve it from. - The interface to listen on. Making new tac files for simple variations on those values seems rather excessive. It would be nice if we could just specify those values as options on the twistd command line. The Twisted plugin system allows us to do just that. Twisted plugins provide a way of defining named Applications, with a custom set of command-line options, that twistd can dynamically discover and run. Twisted itself comes with a set of built-in plugins. You can see them all by running twistd without any arguments. Try running it now, but outside of the twisted-intro directory. After the help section, you should see some output like this: ... ftp An FTP server. telnet A simple, telnet-based remote debugging service. socks A SOCKSv4 proxy service. ... Each line shows one of the built-in plugins that come with Twisted. And you can run any of them using twistd. Each plugin also comes with its own set of options, which you can discover using --help. Let’s see what the options for the ftp plugin are: twistd ftp --help Note that you need to put the --help switch after the ftp command, since you want the options for the ftp plugin rather than for twistd itself. We can run the ftp server with twistd just like we ran our poetry server. But since it’s a plugin, we just run it by name: twistd --nodaemon ftp --port 10001 That command runs the ftp plugin in non-daemon mode on port 10001. Note the twistd option nodaemon comes before the plugin name, while the plugin-specific option port comes after the plugin name. As with our poetry server, you can stop that plugin with Ctrl-C. Ok, let’s turn our poetry server into a Twisted plugin. First we need to introduce a couple of new concepts. IPlugin Any Twisted plugin must implement the twisted.plugin.IPlugin interface. If you look at the declaration of that Interface, you’ll find it doesn’t actually specify any methods. Implementing IPlugin is simply a way for a plugin to say “Hello, I’m a plugin!” so twistd can find it. Of course, to be of any use, it will have to implement some other interface and we’ll get to that shortly. But how do you know if an object actually implements an empty interface? The zope.interface package includes a function called implements that you can use to declare that a particular class implements a particular interface. We’ll see an example of that in the plugin version of our poetry server. IServiceMaker In addition to IPlugin, our plugin will implement the IServiceMaker interface. An object which implements IServiceMaker knows how to create an IService that will form the heart of a running application. IServiceMaker specifies three attributes and a method: tapname: a string name for our plugin. The “tap” stands for Twisted Application Plugin. Note: an older version of Twisted also made use of pickled application files called “tapfiles”, but that functionality is deprecated. description: a description of the plugin, which twistd will display as part of its help text. options: an object which describes the command-line options this plugin accepts. makeService: a method which creates a new IServiceobject, given a specific set of command-line options We’ll see how all this gets put together in the next version of our poetry server. Fast Poetry 3.0 Now we’re ready to take a look at the plugin version of Fast Poetry, located in twisted/plugins/fastpoetry_plugin.py. You might notice we’ve named these directories differently than any of the other examples. That’s because twistd requires plugin files to be located in a twisted/plugins directory, located in your Python module search path. The directory doesn’t have to be a package (i.e., you don’t need any __init__.py files) and you can have multiple twisted/plugins directories on your path and twistd will find them all. The actual filename you use for the plugin doesn’t matter either, but it’s still a good idea to name it according to the application it represents, like we have done here. The first part of our plugin contains the same poetry protocol, factory, and service implementations as our tac file. And as before, this code would normally be in a separate module but we’ve placed it in the plugin to make the example self-contained. Next comes the declaration of the plugin’s command-line options: class Options(usage.Options): optParameters = [ ['port', 'p', 10000, 'The port number to listen on.'], ['poem', None, None, 'The file containing the poem.'], ['iface', None, 'localhost', 'The interface to listen on.'], ] This code specifies the plugin-specific options that a user can place after the plugin name on the twistd command line. We won’t go into details here as it should be fairly clear what is going on. Now we get to the main part of our plugin, the service maker class: class PoetryServiceMaker(object): implements(service.IServiceMaker, IPlugin) tapname = "fastpoetry" description = "A fast poetry service." options = Options def makeService(self, options): top_service = service.MultiService() poetry_service = PoetryService(options['poem']) poetry_service.setServiceParent(top_service) factory = PoetryFactory(poetry_service) tcp_service = internet.TCPServer(int(options['port']), factory, interface=options['iface']) tcp_service.setServiceParent(top_service) return top_service Here you can see how the zope.interface.implements function is used to declare that our class implements both IServiceMaker and IPlugin. You should recognize the code in makeService from our earlier tac file implementation. But this time we don’t need to make an Application object ourselves, we just create and return the top level service that our application will run and twistd will take care of the rest. Notice how we use the options argument to retrieve the plugin-specific command-line options given to twistd. After declaring that class, there’s only on thing left to do: service_maker = PoetryServiceMaker() The twistd script will discover that instance of our plugin and use it to construct the top level service. Unlike the tac file, the variable name we choose is irrelevant. What matters is that our object implements both IPlugin and IServiceMaker. Now that we’ve created our plugin, let’s run it. Make sure that you are in the twisted-intro directory, or that the twisted-intro directory is in your python module search path. Then try running twistd by itself. You should now see that “fastpoetry” is one of the plugins listed, along with the description text from our plugin file. You will also notice that a new file called dropin.cache has appeared in the twisted/plugins directory. This file is created by twistd to speed up subsequent scans for plugins. Now let’s get some help on using our plugin: twistd fastpoetry --help You should see the options that are specific to the fastpoetry plugin in the help text. Finally, let’s run our plugin: twistd fastpoetry --port 10000 --poem poetry/ecstasy.txt That will start a fastpoetry server running as a daemon. As before, you should see both twistd.pid and twistd.log files in the current directory. After testing out the server, you can shut it down: kill `cat twistd.pid` And that’s how you make a Twisted plugin. Summary In this Part we learned about turning our Twisted servers into long-running daemons. We touched on the Twisted logging system and on how to use twistd to start a Twisted application as a daemon process, either from a tac configuration file or a Twisted plugin. In Part 17 we’ll return to the more fundamental topic of asynchronous programming and look at another way of structuring our callbacks in Twisted. Suggested Exercises - Modify the tac file to serve a second poem on another port. Keep the services for each poem separate by using another MultiServiceobject. - Create a new tac file that starts a poetry proxy server. - Modify the plugin file to accept an optional second poetry file and second port to serve it on. - Create a new plugin for the poetry proxy server.
http://krondo.com/2010/07/
CC-MAIN-2017-09
refinedweb
4,367
56.86
Originally posted by dolly shah: Why it returns "Welcome to Java" only one time. How can we know the println statement is not a body of the while loop. It is written in book, "if there is only one line in loop body you are free to don't put that line in {}. When I did this program I thought it prints "Welcome to Java" 127 times. Now I am little confused. Can anybody help me? Originally posted by dolly shah: public class Inc { void infiniteLoop() { byte b = 1; while (++b > 0); System.out.println("Welcome to Java"); } public static void main(String argv[]){ Inc i1=new Inc(); i1.infiniteLoop(); It still gives me "Welcome to Java" only once.
http://www.coderanch.com/t/264899/java-programmer-SCJP/certification/operator
CC-MAIN-2015-40
refinedweb
119
75.81
Write Macro Code Generators with VS 2005 Test the MacroThe easiest way to test a macro is running it in the Macros IDE. An easy way to test the code in context is to switch to the VS 2005 IDE, open the Command Window (View|Other Windows|Command Window), and type the entire macro subroutine name, including namespaces, at the Command Window prompt. Based on my implementation, you would select any field and enter the following in the IDE's Command window: Macros.MyMacros.Refactoring.EncapsulateField The Intellisense feature in the IDE will help you find the path to the macro if your path differs from mine. Add the Macro to the MenubarHaving tested the refactoring Encapsulate Field, you can add it to the Visual Studio menubar or toolbar. To add access to the macro on the Tools menu, follow these steps: - In Visual Studio 2005, select Tools|Customize. - Pick the Command tab. - Select Macros from the Categories list and the macro you just created from the Commands list. - Drag and drop the macro on to the Tools menu. - Right-click on the command now residing on the Tools menu, use the context menu to change the menu nameto something like "Encapsulate Field", and add an icon if you'd like (see Figure 1). - Close the Customize dialog. Figure 1: Drag the Macro to the Menubar Where You'd Like It to Be Accessible That's all there is to it. Your custom refactoring code generator is now an integrated part of your copy of the IDE. If you want to amaze your friends, locate the file mymacros.vsmacros (or export the module containing the refactoring) and email it to them, along with the instructions for integrating the macro into the IDE. When they tell you how clever you are and you bask in the glory for a while, just tell them where you got the idea. ; ) Ready for a Leap ForwardThis article spotlighted an underutilized but powerful aspect of Visual Studio: macros and code generators. I really hope that we are on the cusp of more powerful and more interesting software systems. I still have at least 25 productive years left in me and hope to be around to see software that becomes truly generative and more interesting as a result. AfterwordWithout question, the accidental father of modern software design is Christopher Alexander. Oddly enough, Mr. Alexander writes about conventional architecturebuildings. The reason he is the father of modern design is because he writes about architecture from the basis of architectural patterns, and his ideas were openly adopted for modern software design. (Just look in the back of any book on design patterns and the like and you will see a bibliographical reference to A Pattern Language: Towns, Buildings, Construction. All of the comparisons to home building on software books is no accident.) Although I haven't met Mr. Alexander (but do have at least one copy of his book), it appears that he is with us and still writing. Presently, he is writing about the generative nature of things. I am curious to see what impact this will have on our industry.<<
https://www.developer.com/net/vb/article.php/10926_3523191_2/Write-Macro-Code-Generators-with-VS-2005.htm
CC-MAIN-2018-22
refinedweb
524
70.53
No "dbus" service on RHEL-5 I'm trying to install SBackup from source on RHEL-5. Red Hat's Python was only 2.4.3, and would not compile SBackup correctly (failed several places on "finally:"). So I downloaded and built Python 2.7 - got by that one. Unfortunately, there is no "dbus" service (or script in /etc/init.d). "make install" fails with: ... if test "" = ""; then gtk-update- Cache file created successfully. Cache file created successfully. Cache file created successfully. install -d /etc/dbus- install -m 644 data/org. dbus: unrecognized service make: *** [install-dbus] Error 1 The operative section of the Makefile appears to be: install-dbus: install -d $(dbus_ install -m 644 data/$( @if test "$(DISABLE_ if [ -x $(servicetool) ]; then \ else if [ -r /etc/init.d/dbus ]; then \ invoke-rc.d dbus force-reload; fi; fi; \ fi where "servicetool" should resolve to the location of the service command. ----- Well, I got through that problem by changing my make install to: make DISABLE_ I then ran into a problem with sbackupconfig: Traceback (most recent call last): File "/usr/local/ from sbackup.pkginfo import Infos File "/usr/local/ from sbackup import util File "/usr/local/ from sbackup.util import local_file_utils File "/usr/local/ from sbackup.util import pathparse File "/usr/local/ from sbackup.util import system File "/usr/local/ import glib ImportError: No module named glib There does not seem to be a "glib" module in Python-2.7 or sbackup. ----- Any ideas? Or is this package so full of Ubuntu-isms that it cannot be used on Red Hat? Question information - Language: - English Edit question - Status: - Answered - For: - sbackup Edit question - Assignee: - No assignee Edit question - Last query: - 2010-10-04 - Last reply: - 2010-10-05 Ah, YAP. The food chain is getting a little long, to install this on Red Hat's production OS. We have a network backup system, but the system in question is off-network. I'm going to roll my own with dump/restore, I think. I just want to plug in a USB disk (or alternations thereof) and back up the data in a sensible way. I should be able to do that with a script. If I get stuck, I may be back. Thanks for your help - Pete Hi Pete, no, there is not a single Ubuntu-ism in SBackup. You need to install a recent version of package 'python-gobject'. It is a part of Glib, the core library used to build GTK+ and GNOME. This package contains the Python bindings for GObject. Have a look at the Install file for further information about dependencies. HTH, Jean-Peer.
https://answers.launchpad.net/sbackup/+question/127941
CC-MAIN-2019-43
refinedweb
439
67.76
WiringPi includes a library which can make it easier to use the Raspberry Pi’s on-board I2C interface. Before you can use the I2C interface, you may need to use the gpio utility to load the I2C drivers into the kernel: gpio load i2c If you need a baud rate other than the default 100Kbps, then you can supply this on the command-line: gpio load i2c 1000 will set the baud rate to 1000Kbps – ie. 1,000,000 bps. (K here is times 1000) To use the I2C library, you need to: #include <wiringPiI2C.h> in your program. Programs need to be linked with -lwiringPi as usual. You can still use the standard system commands to check the I2C devices, and I recommend you do so – e.g. the i2cdetect program. Just remember that on a Rev 1 Raspberry pi it’s device 0, and on a Rev. 2 it’s device 1. e.g. i2cdetect -y 0 # Rev 1 i2cdetect -y 1 # Rev 2 Note that you can use the gpio command to run the i2cdetect command for you with the correct parameters for your board revision: gpio i2cdetect is all that’s needed. Functions available - int wiringPiI2CSetup (int devId) ; This initialises the I2C system with your given device identifier. The ID is the I2C number of the device and you can use the i2cdetect program to find this out. wiringPiI2CSetup() will work out which revision Raspberry Pi you have and open the appropriate device in /dev. The return value is the standard Linux filehandle, or -1 if any error – in which case, you can consult errno as usual. E.g. the popular MCP23017 GPIO expander is usually device Id 0x20, so this is the number you would pass into wiringPiI2CSetup(). For all the following functions, if the return value is negative then an error has happened and you should consult errno. - int wiringPiI2CRead (int fd) ; Simple device read. Some devices present data when you read them without having to do any register transactions. - int wiringPiI2CWrite (int fd, int data) ; Simple device write. Some devices accept data this way without needing to access any internal registers. - int wiringPiI2CWriteReg8 (int fd, int reg, int data) ; - int wiringPiI2CWriteReg16 (int fd, int reg, int data) ; These write an 8 or 16-bit data value into the device register indicated. - int wiringPiI2CReadReg8 (int fd, int reg) ; - int wiringPiI2CReadReg16 (int fd, int reg) ; These read an 8 or 16-bit value from the device register indicated.
http://wiringpi.com/reference/i2c-library/
CC-MAIN-2018-17
refinedweb
414
69.92
Unable to kill my C4DThread As in the title, I've got a BaseThread running which i think doesnt die once process is finished. The thread runs an ffmpeg call via subprocess.wait() (also tried communicate()). Everything seems to work but after closing cinema4d i cant reopen it, in the task manager there is a c4d process still there taking minimal resources. If i kill that task i can then reopen c4d again. My guess is im not using the threads correctly and the thread stays round after the process is finished. My code below: note: self.data is added to the thread elsewhere. Suppose I could add in init as well. class CompileAVThread(c4d.threading.C4DThread): def Main(self): result = compile_av(**self.data) if result is True: gui.MessageDialog('Export completed') path = os.path.dirname(self.data['output']) open_path(path) # separate def that opens native os file browser at correct location else: print('Something went wrong') gui.MessageDialog('Failed') if self.TestBreak(): # Dont really get how TestBreak works.. print('Exiting thread please?') return And the subprocess: p = subprocess.Popen(args=arg_list, shell=False) if p.wait() == 0: return True else: print "Failed - %s" % p.stdout.read() return False How and where do you handle your thread? Do you use Thread.Wait()? @mp5gosu thanks for the reply. I use Thread.Start(). I also run the thread from within a gui.GeDialog. Command() method def Command() self.thread = myThread.MyThread() self.thread.data = data # Load some data in self.thread.Start() I'm guessing i may need to call End() somewhere? However this dialog closes after the thread starts. I figured the thread would be garbage collected once its done with its process. @mp5gosu I should also mention that i tried calling self.End() from within the thread which i had heard isnt good practice. But anyway...didnt work XD Hi Mafster and thanks for reaching out us. With regard to your question, we've recently discussed a similar topic here and I do recommend having a look at. I've used the code below and I actually had Cinema being reactive whilst ffmpeg was running as well as having Cinema being gracefully closed at the end of the session. import c4d from c4d.threading import C4DThread import subprocess, sys class UserThread(C4DThread): def Main(self): # call subprocess cmd = ["/opt/local/sbin/ffmpeg", "<arg1>", "<arg2>", ..., "<argn>"] proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) pass def main(): thread = UserThread() thread.Start() # Wait until the main method is done thread.Wait(True) # Execute main() if __name__=='__main__': main() Am I missing something here? Cheers, Riccardo Thanks for the example. In my case this just causes C4d to freeze wile the process is running. Once its done then i get c4d back again. Strangely if i leave the bool argument out out from Wait() method it will error (Type error) but then the ffmpeg will still be running (as its running from the Start() method and c4d is responsive and also closes gracefully. This seems an entirely non-elegant and accidental way of finding a "solution" essentially using an error to give me the result i want. I accidentally left out the boolean argument, everything seemed to work and then checked the logs and realised the error. @r_gigante By default thread.Wait() should pass in True? I just had a thought because the thread.Wait() in my case is a property of self self.thread.Wait() is it possible self is being passed in (as Python does) and its reading that as a the bool argument and so getting type Error? Hi Mafster, thanks for following up. The documentation here properly indicates that passing no parameter to Wait()is passing True. Long story short, this value is required in order to avoid Cinema being stuck on waiting for the thread to end. Hoping this helps in solving the issue, give best. Riccardo
https://plugincafe.maxon.net/topic/11476/unable-to-kill-my-c4dthread
CC-MAIN-2020-24
refinedweb
651
69.07
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. How to update a value for all the entries in a one2many field on button click? I'm trying to make it so that when I click a button on an invoice, to update the individual unit price for each invoice line by a factor specified in a custom field. I know how to put the button, and define the fields and all that, but I can't seem to figure out the python code that i need to put in my function. I've managed to create this: def button_convert_unitprice(self, cr, uid, ids, context=None): if context is None: context = {} for id in ids: lines = self.browse(cr, uid, id, context=context).invoice_line val=self.browse(cr, uid, id, context=context).x_multiplier for line in lines: line.price_unit=line.price_unit*val self.button_reset_taxes(cr, uid, ids, context) return True Unfortunately it doesn't do aything but refresh the page, and I'm completely lost in this odoo syntax. Can someone please point me the right direction with a working example somewhere? I know this is usualy done by onchange events, but I need it to be manually on click. 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
https://www.odoo.com/forum/help-1/question/how-to-update-a-value-for-all-the-entries-in-a-one2many-field-on-button-click-73003
CC-MAIN-2017-26
refinedweb
246
64.1
I have Mailman 2.1.1 w/ htDig running on FreeBSD 4.8. I have a particular user (read CIO) that never uses the Enter key when composing messages. So besides making the archive just plain ugly with these infinitely long lines, his messages are interrupted halfway through with an exclamation point and a carriage return (from Mailman). I've seen some people's solutions in the archives using fmt and piping to mailmain, but that does work in FreeBSD (seems Solaris's fmt is better). Does anyone else have any solutions? Thanks, Will -- Will Froning Unix Sys. Admin. (209)946-7470 (209)662-4725 wfroning at pacific.edu
https://mail.python.org/pipermail/mailman-users/2003-November/032789.html
CC-MAIN-2020-16
refinedweb
109
67.45
Package for controlling an LED running light that is hooked up to a Raspberry Pi Project description Running Light Control A light-weight package for controlling a raspberry-pi connected LED running light. Example code: import RPi.GPIO as GPIO import runninglight import time #Pin for the light MPIN = 3 #set up GPIO.setmode(GPIO.BCM) GPIO.setup(MPIN, GPIO.OUT) #create rlm = runninglight.runninglightmanager(MPIN) #run rlm.set_mode(runninglight.light_mode.doubleblink_1sec) rlm.start() print("Started!") 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/runninglight/0.1.0/
CC-MAIN-2021-39
refinedweb
105
50.43
Calculating the length needed to represent an integer in an arbitrary base I have the length of a representation of an integer in an arbitrary base. Say the length is 15, and the base is 36. I'd then like to work out how long a representation of said integer would be in another arbitrary base. i.e, converting to base 2 might result in a length of 68. I know it's along the lines of the below, but I can't quite get my head around what I need to floor and ceil, and I'm getting some results that are way off: length * log(fromBase) / log(toBase) Answers Following a Mathematica-like syntax, let Log[b,n] represent the logarithm to base b of n. Let Log[n] represent the natural logarithm of n. Then the ratio Log[b1,n]/Log[b2,n] is constant, and equal to Log[b2]/Log[b1] This ratio is a multiplier for calculating the number of digits in base b1 from the number of digits in base b2 (or vice-versa if you see things that way). For the example in the question, a 15-digit base-36 number will need 15*Log[36]/Log[2] == 77.5489 base-2 digits. This is, of course, precisely what you have in your question. You only need to round the final answer up to the next integer. I'm not sure, of course, why you seem to be getting some results that are way off. Sadly, there is no exact solution without computing in high precision. For example, (I'll use MATLAB for my work, including tools for high precision work I've written myself) what is 2^200? In base 10, we get: vpij(2)^200 ans = 1606938044258990275541962092341162602522202993782792835301376 That number is represented in binary using 201 base 2 digits. However, 2^200-1 only needs 200 base 2 digits to represent. vpij(2)^200 - 1 ans = 1606938044258990275541962092341162602522202993782792835301375 Now, we could compute the log of these numbers, as a double, by taking only the highest order digits. We need to add 1 to the base 2 log of a number to know the number of base 2 digits are needed to represent it. format long g 1 + log2(vpij(2)^200) ans = 201 1 + log2(vpij(2)^200 - 1) ans = 201 Here log2 did exactly that, taking the top decimal digits to compute that log. See that it cannot tell that the second number really requires one less digit to store in binary form. vpij2bin(vpij(2)^200) ans = 100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 vpij2bin(vpij(2)^200 - 1) ans = We can see what happens by taking a high precision log of those numbers. Thus, accurate to 100 decimal places, log2(hpf(2,100)^200) ans = 200 log2(hpf(2,100)^200 - 1) ans = 199.9999999999999999999999999999999999999999999999999999999999991022086719253476184905817230522465495 The difference between those two numbers is very small. log10(hpf(2,100)^200) - log10(hpf(2,100)^200 - 1) ans = 2.702621195974725251000559400026211938865e-61 So that any computation using logs must fail here, unless a high precision log is itself taken. At best, you can come within a digit of being correct, but no more than that. So if your goal is merely to allocate sufficient space for the number, then always allocate one more digit than apparently needed. This should be sufficient until you start working with REALLY huge powers. (VPIJ is a new variable precision integer form in MATLAB, that will directly replace my older VPI tool. HPF is available already on the file exchange.) You can get an exact answer without using logarithms. Walk up the radixes of the arbitrary base until the number fits inside. Python example: def count_digits(number, base): radix = 1 while number >= base ** radix: radix += 1 return radix
http://unixresources.net/faq/14471846.shtml
CC-MAIN-2019-09
refinedweb
624
71.34
Perl 5 had void context, scalar context and list context. Perl 6 does too, but one name has slightly changed. Respectively, they are now void context, item context and list context1. The word scalar is overloaded in Perl 5 and 6: it can be a named scalar variable, a reference to a scalar variable (written in allcaps: SCALAR), or an anonymous scalar variable. To make things worse, there are also scalar values, that are actually a scalar variables too. (Often, readonly scalars are not called variables, even though they are.) Perl 6 also has Scalar, written with a single capital letter. This is the type that all scalars have. It is a supertype. For example, the Str (string) and Num (number) types are subtypes of Scalar. Every type has a corresponding context, that depending on circumstances may cause type errors or type coercion (conversion). Having the same word for things that are all scalar variables is usually not a problem, but it would be very annoying to have both scalar context and Scalar context, so scalar context is now known as item context. This works until someone decides to write a class or role named Item, but let's assume that someone doing that is smart enough to include a namespace indicating what kind of item it is. Lists can be lazy, which means that the values are generated on demand, but that is outside the scope of this article. Item context has many sub contexts, most being a specific type of Ref (reference context), some being pure scalar types, like Num and Str. System native types (written in all lowercase) are left out of this discussion. - void - item (Scalar) - Num - Int - ... - Str - Ref - Array - Hash - HTML::Form - ... - list - types, as with item context [download] A list is not really a thing. It is a collection of elements. A list can only exist in list context, and each of the elements is then also in list context, flattening to one big list. List context can be of a certain type. Then, every element is expected to be of that type, and if it is not, it is coerced into it, or an exception (error) occurs. The new Array type is a subtype of Ref. Its context is called Array context. The same applies to Hash. However, Scalar, is not a subtype of Ref. It is the other way around: Ref is a subtype of Scalar. This means that a value in Scalar context does not have to be a reference. Scalar is the default (normal) type for both item context and list context. Certain operators create certain contexts. For example, the infix + operator creates Num context on both sides: both values are evaluated in Num context. Perl 5 had this too, but the subtypes of scalar context were only seldomly discussed. [download] An array in Perl 5's scalar context would evaluate to its number of arguments. In a standard Perl 6 item context, an array evaluates to a reference to itself. Because Array context is a form of item context, a pure array in Array context first evaluates to an array reference, which is exactly what was expected. Hashes also evaluate to self-references when used in normal item context. When used in more specific item contexts, however, both arrays and hashes do something else: in Num context, they evaluate to their numbers of elements, in Str context, they evaluate to a string representation of the aggregate. In list context, arrays and hashes evaluate (flatten) to their individual elements. The elements of a hash, by the way, are pairs. Each pair has a key and a value. A pair is an object, and thus a reference. The type and context are both called Pair. my %hash = (a => 'b', c => 'd'); # right side in list context my ($pair1, $pair2) = %hash; # right side in list context $pair1.key # >>> "a" $pair1.value # >>> "b" $pair2.key # >>> "c" $pair2.value # >>> "d" (e => 'f').key # >>> "e" +%hash # >>> 2 # Num item context [download]. 1 Pugs, the Perl 6 compiler, currently calls list context slurpy context, and uses cxtSlurpy for it
http://www.perlmonks.org/index.pl?viewmode=public;node_id=358255
CC-MAIN-2015-14
refinedweb
684
74.69
I recently posted about using Redis and Celery with Django to handle asynchronous calls from your web pages. Given that I have memory constraints on the server, I have been wondering if I might get more bang for my buck with redis-queue (rq) instead of Celery. In fact, I have found them comparable: rq uses about 12Mb per worker, and Celery uses about 10-12Mb per process. However, Celery workers use (1+ concurrency) processes, so if concurrency=1, Celery appears to use double the memory. Using RQ Here are the changes I’ve made to the code I posted earlier to replace Celery with redis-queue. Note jobs.py is exactly the same as celery’s tasks.py, but without the @task decorator. (I did not use rq’s @job decorator.) def status_view(request): """ Called by the opt page via ajax to check if the optimisation is finished. If it is, return the results in JSON format. """ if not request.is_ajax(): raise SuspiciousOperation("No access.") if QUEUE_BACKEND=='celery': # as before - the main part was a call to Celery's AsyncResult elif QUEUE_BACKEND=='rq': from django.conf import settings from redis import Redis from rq import Queue from rq.job import Job, Status from rq.exceptions import NoSuchJobError try: connection = Redis(settings.RQ_REDIS_URL, settings.RQ_REDIS_PORT) # not quite sure if better to use Job(...) or Job.fetch(...) here # the difference is fetch also calls refresh # but I see it does not rerun the job job = Job.fetch(request.session['job_id'], connection=connection) except KeyError, NoSuchJobError: ret = {'error':'No optimisation is underway (or you may have disabled cookies).'} return HttpResponse(json.dumps(ret)) if job.is_finished: ret = get_solution(job) elif job.is_queued: ret = {'status':'in-queue'} # note extra elif job.is_started: ret = {'status':'waiting'} elif job.is_failed: ret = {'status': 'failed'} # note extra def get_context_data(self, **kwargs): ... if QUEUE_BACKEND=='celery': from . import tasks result = tasks.solve.delay(myarg, timeout=timeout) elif QUEUE_BACKEND=='rq': from . import jobs from redis import Redis from rq import Queue connection = Redis('localhost', PORT) q = Queue(connection=connection) job = q.enqueue_call(func=jobs.solve, args=[myarg], kwargs={'timeout':timeout}, timeout=timeout+10) # the solve call itself has a timeout argument; timeout with rq shouldn't occur In settings.py I added: RQ_REDIS_URL = 'localhost' RQ_REDIS_PORT = 6379 But I did not use django-rq at all. One nice thing I see immediately is the additional status info – you can easily query if a job is still in the queue or has failed. I’m sure these are possible to see in Celery too, but they are obvious in rq. Run RQ workers Running an rq worker is nice and simple – there is no daemonization or even setup files. On either your dev or production server, just type (and repeat for as many workers as you want): rqworker --port 6379 Remaining issues One initial problem was finding out how to get an existing job from its id. I solved this with: Job.fetch(job_id, connection=connection) However, I cannot find documentation about Job.fetch, and I see that Job(...) by itself also works. Please let me know if you know which of these I should be using. The main problem I have with redis-queue now is terminating a task. I have a “cancel” button on the optimisation screen, which I can implement with Celery via: revoke(task_id, terminate=True) # celery I cannot find an equivalent in rq. This is unfortunately a deal-breaker for me, so I am sticking with celery for now. Can you help?
http://racingtadpole.com/blog/tag/redis-queue/
CC-MAIN-2020-05
refinedweb
585
59.3
I woke up this morning (June 7, 2013) thinking it must be about 200 days to Christmas. Foregoing any simple ways to determine that, I decided it would be a good time to use the nscala-time library, a Scala wrapper around Joda Time. Sticking with the time theme, I haven’t much free time today, so without further ado, here is some Scala code that determines the number of days between today and Christmas: import com.github.nscala_time.time.Imports._ import org.joda.time.Days // from object DaysUntilChristmas extends App { // 1: get the current date and time val now = DateTime.now // 2: get a date to represent Christmas val xmas = (new DateTime).withYear(2013) .withMonthOfYear(12) .withDayOfMonth(25) // 3: determine the number of days from now until xmas val daysToXmas = Days.daysBetween(now, xmas).getDays // 4: print the result println(s"daysToXmas = $daysToXmas") // bonus: what day is 200 days from now? val nowPlus200 = now + 200.days println(s"nowPlus200 = $nowPlus200") } On the morning of June 7, 2013 (in Boulder, Colorado time), the output from this code is: daysToXmas = 201 nowPlus200 = 2013-12-24T10:29:12.564-07:00 Creating Christmas If the way I created an instance of Christmas looks a little longer than need be, I did first try to create it like this: val xmas = new DateTime(2013, 12, 25, 1, 1) The last two fields of that constructor specify the hour and minute, and when I used that approach, I got one day less than the “fluent” style I showed first. When I changed the hour to something later in the day, such as 12 or 15, etc., I got the same result as the fluent style, so the result depended on the hour I used. Since I wasn’t interested in that level of detail, I went with the fluent style. A little more information If you want to have a little more nscala-time fun, add this loop to the bottom of the program: for (i <- 1 to 203) { val d = now.plusDays(i) println(f"$i%3d: $d") } On June 6, 2013, that prints results like this: 1: 2013-06-08T10:29:12.564-06:00 2: 2013-06-09T10:29:12.564-06:00 3: 2013-06-10T10:29:12.564-06:00 -- much more here -- 199: 2013-12-23T10:29:12.564-07:00 200: 2013-12-24T10:29:12.564-07:00 201: 2013-12-25T10:29:12.564-07:00 No matter how you count it, 201 does seem to be the correct result. Using nscala-time with Scala and SBT To use the nscala-time library with a Scala SBT project, just add this line to your SBT build.sbt file: libraryDependencies += "com.github.nscala-time" %% "nscala-time" % "0.4.2" With that line, you should be able to copy and paste the source code above into an SBT project, and run it like this: $ sbt run If you needed a Scala + nscala-time example, I hope this has been helpful.
http://alvinalexander.com/scala/nscala-time-example-scala-joda-time/
CC-MAIN-2020-16
refinedweb
504
72.26
is called, and this costs extremely much time for our application.is called, and this costs extremely much time for our application. service.save(customer); AlperAlper public class Customer implements Serializable { private Set<Account> acounts = new HashSet<Account>(); // Getters, setters } public class Account implements Serializable { private Set<AccTransaction> acounts = new HashSet<AccTransaction>(); // Getters, setters } public class AccTransaction implements Serializable { private String operation; private Timestamp timestamp; // Getters, setters } , than the whole object graph of Ford->Fiesta->1000xpieces is sent (serialized) to the server., than the whole object graph of Ford->Fiesta->1000xpieces is sent (serialized) to the server. service.saveOrUpdate(model); the pieces of the model are deleted, since I have a strond boundary piece->model, and therefore cascade="save".the pieces of the model are deleted, since I have a strond boundary piece->model, and therefore cascade="save". model.setPieces(null); service.saveOrUpdate(model); Is 2000 a realistic size estimate or just something that you wildly guessed at?In the car model, it is realistic and it costs much, according to the tests and practice. And do you have 100,000 customers that are that big or only 1?Let's say, all of the car model models have similar number of pieces attached. The the expensive rule is valid for all. Did you actually attempt to send a data model with 2000 records and so that is why you know it is too expensive or are you just guessing?It does cost much time, in practice. Other than that you shouldn't be using one model for every operation. If you have a requirement to update just a date then your database layer should have functionality to support just that and nothing else.So you mean, I shouldn't use cascade="save" for the parent-child relationships? acelik wrote:What exactly does that represent? Thanks for the quick answer. The numbers are just wildly guesses, in order to keep the sample simple. Actually we develop a system for automobile industry. So, instead of customer, you may think of a company, like Ford. Account would be then Fiesta. Instead of AccTransaction we may think a huge number of car pieces (clima, motor, radio, etc.). So hierarchically we have Company (Ford, Opel, etc) Model (Fiesta, Astra, etc.) Piece (1000 pieces per model, so Fiesta, Opel have 1000 different pieces each) The problem is, if I loaded the Ford->Fiesta->1000x pieces for one view and then switch to another view. In the second view, I rename Fiesta to Fiesta II, and want to save this renaming operation using: I wonder how this problem is solved smartly, if you guys share domain objects between the client and server, and avoid DTO.The first step is to start with actual business requirements. acelik wrote:It depends, as jschell says, on the business requirements; however, what you're doing (or at least enforcing in this instance) does sound like overkill to me. I suspect, though, that the problem lies more on the fetching side than the saving one. So you mean, I shouldn't use cascade="save" for the parent-child relationships?
https://community.oracle.com/thread/2192160?tstart=44
CC-MAIN-2014-10
refinedweb
518
55.34
c, I'm not very familiar with IPython (probably to my detriment), but I believe this may be an inherent problem with wx v. command-line program, and have little to do with MPlot, matplotlib, or IPython. That is, I think that wxWidgets/wxPython's MainLoop() is never really going to interact well with a command-line application. I'd be happy to be proven wrong -- I've hit this problem myself and been unable to reliably solve it. Anyway, can you send a simple example that demonstrates non-responsiveness? I think it would be easy to write a wxPython App (even with PythonCard) that provided a command-line which was passed off to IPython (say, on an Enter event). I'd be much more confident that you could get the wx widgets to respond, and still have a working command-line. I don't know whether this is compatible with the "IPython w= ay". Cheers, --Matt Newville Hi, I really like the MPlot and matplotlib libraries, but am have some issues= using it in an interactive manner. Here are the details: - Running on Windows XP - Run through an ipython interactive session - Run *during data-taking*, that is, every 3s or so, several calls to opl= ot are made. - Ipython is run with the -wthread option, and thus threading.enumerate()= shows two threads: [<_MainThread(MainThread, started)>, <IPShellWX(Thread-1, started)>] - pylab.ion() has been called The problem is that the window refuses to refresh itself until the entire data taking process is finished (~8 hours) If I try and simulate the above problems manually, one easy way to create this unresponsiveness of the MPlot window is to call time.sleep(10) from IPython. The window will remain unresponsive for 10s. Why is this? Shouldn't the plot-refresh code, or at the very least, the g= ui code be running in the wxpython thread? I've had this problem in the past, and sent around some emails. At the ti= me a managed to "solve" the problem, but there were so many variables (ipyth= on command line args, threads present, ways in which functions were called, = etc) that I was unable to isolate the solution. I'm facing the same problem ag= ain, and tried to recreate the solution, but it's not working. I guess there's= some black magic involved somewhere. The problem is also that I'm a struggling PhD student (ie in over my head= ), so I didn't really have time to figure this one out. I'd love to be more = of a contributor to matplotlib and it's related projects, but at the moment = I don't really have time to reinvent the wheel everytime I do an experiment. Everyone here uses labview (which drives me nuts). Any help you could give me would be *greatly* appreciated. Marc >>>>> "Matt" == Matt Newville <newville@...> writes: Matt> Hi Marc, I'm not very familiar with IPython (probably to my Matt> detriment), but I believe this may be an inherent problem Matt> with wx v. command-line program, and have little to do with Matt> MPlot, matplotlib, or IPython. That is, I think that Matt> wxWidgets/wxPython's MainLoop() is never really going to Matt> interact well with a command-line application. I'd be happy ipython has a wx mode (-pylab with a wx* backend or -wthread for general wx apps) which is designed to allow you to control wx apps from the ipython shell. It does this by starting the wx application mainloop and then hijacking the wx mainloop so that application attempts to start the mainloop will be ignored. IPython/Shell.py def hijack_wx(): """Modifies wxPython's MainLoop with a dummy so user code does not block IPython. The hijacked mainloop function is returned. """ ...snip... it then runs a wx timer to check for input from the shell user. The bulk of this was written by Fernando and myself, and neither of us pretend to be wx experts, so it is quite possible that something is not working right and can be improved. It might be as simple as a need to update the hijack function for a new version of wx. Or it might be something deep, subtle and nasty. Or it might simply be user error. Without example code that replicates the problem, it's difficult to say. I suggest that Marc try and run some of the embedding_in_wx* applications in the matplotlib examples dir from the ipython shell and see if these work. And then gradually add some of the functionality you are using in your real app (eg dynamic updates). Marc, my guess is that you are mixing programming idioms (OO and pylab). For an application like yours, you should not be using pylab at all, and I see that you are with the pylab.ion call. You should follow the examples of embedding_in_wx* and then call fig.canvas.draw() when you want your figure to draw. Note that interactive mode will not affect OO calls, eg even if you do ax.plot(something) you will still need to do fig.canvas.draw() since the interactive mode only applies to *pylab* plot commands, eg, pylab.plot(something) Recode your application so that pylab is imported nowhere, and call canvas.draw() when you need the canvas to update. You can post pylab snippets here if you need help translating them to OO matplotlib. JDH Matt Newville wrote: > I think it would be easy to write a wxPython App (even with > PythonCard) that provided > a command-line which was passed off to IPython (say, on an Enter > event). PyShell is good option, if you can get ipython to work@... Christopher Barker wrote: > PyShell is good option, if you can get ipython to work with it. oops, I meant PyCrust. Sorry. @... I agree to receive quotes, newsletters and other information from sourceforge.net and its partners regarding IT services and products. I understand that I can withdraw my consent at any time. Please refer to our Privacy Policy or Contact Us for more details
https://sourceforge.net/p/matplotlib/mailman/message/12453306/
CC-MAIN-2016-36
refinedweb
1,011
71.95
Build a REST API with XML Payload Build a REST API with XML Payload Creating REST APIs with XML payloads. Join the DZone community and get the full member experience.Join For Free There is hardly any argument on the fact that APIs are increasingly becoming an important part of how companies do business. API has become the de facto standard to unlock one of their most valuable resources, data. And as organizations are publishing more APIs, the observed trend is that REST is replacing SOAP as the data transfer protocol of choice. When it comes to the data that APIs serve up, XML is still the most used format. Although JSON is hot on its heels, we still need to address plenty of use cases with XML payload. In this post, we will go step by step through an example to build out a RESTful web service with XML request and response payload. Check out the complete project on Anypoint Exchange. Pre-requisites: - Download Anypoint Platform Design Tool – MuleSoft Anypoint Studio. In this post, we are using version 5.4 of Anypoint Studio with the new “Studio Light Theme”. You can always revert to the old theme in Preferences. - A database where we can create and load a sample table required for this project. In this example, we will use an instance of the MySQL database. - To follow the example in this guide, run the SQL script customer.sql to set up the table and load it with some sample data. Steps: - Since we are working with an XML payload, we will either have an existing schema for the request and response message or create one from scratch. In this example, we will consider the latter. Since the foundation for Anypoint Studio is the Eclipse IDE, we can leverage the XML schema design tool which comes included with Anypoint Studio. Open Anypoint Studio and create a “General Project”. - Create a new file in the project of type “XML Schema File”. Refer link to get step by step instructions in designing the XML Schema using the Eclipse-based schema editor. For the scope of this example, download the schema for request and response XML payload. Now that we have the schema definitions ready we can start defining the API specification. We do this with the help of RESTful API Modeling Language (RAML). RAML is central to the design first approach to implementing an API that we have discussed in out previous blog posts(link here). - To start defining an API specification, first, sign up for an Anypoint account if you don’t already have one. - After logging into the account click on “API” on the top which will bring up the page listing any existing APIs. If this is the first API, then the list will be blank. - Click on “Add new API” which brings up the API detail page where on the left side we click on “Define API in API Designer.” which brings up the API Designer tool. - Using the API Designer tool where we will start creating our API specification using RAML. Import the schema files we created earlier into API designer by clicking on “Import”. - Using simple descriptive language, we will document the requirements for our API to query customer details. For more information, please refer to the RAML tutorial here. For this example download the RAML spec here. - Once we have confirmed and documented the API requirements, we will export the resulting RAML file along with the referenced XSD. Using the API specification we just exported we will now configure the actual implementation of the operations defined in the RAML file. For this purpose, we will use Mulesoft Anypoint Studio. - Open up Studio. Create a new “Mule Project”. Give a name to the project. Since we are implementing the operations defined in the RAML file, we will reference the exported RAML archive at the bottom. Click Finish. - Referencing the RAML file will preconfigure the application with the flows and exception handling. We will configure the “Post” operation and add components to query the database and map the result set to the required XML payload. - Add the database connector. In this example, we are using a MYSQL database. So configure the connector with MySQLvers. You can configure any other JDBC database drivers here. Add in the relevant connection parameters and click “Finish”. - Pick the “Select” operation and configure the select query. In this example, we are fetching the customerID from the XML input request. We will use this customerID in the select query to fetch the relevant customer record from the database table. We use an XPATH3 function to parse through the incoming XML payload. We use wildcard “*” to escape the namespace. If there is a need to incorporate the namespace, then refer to the documentation. - Now that we have configured the database connector, we need to map the result set returned from the connector to the XML response payload. For this purpose, we will use the DataWeave transform component. Because of DataSense, metadata on the left and right side are automatically fetched making it very easy to map the data. - Using the mapper, drag and drop the result set from left to right side. After which we map each relevant data element from left to right side. - Right-click on the project and run it in Anypoint Studio as a mule application which will open up the API console in Studio. We can test the API here by adding a sample request XML with a customer id. Press Send, which executes the flow we just configured and to fetch the customer details from the database table. You can download this complete project from Anypoint Exchange. In this post and from our previous post we have understood how easy it is to create an API with the end user in mind. The trends suggest the shift towards RESTful APIs but the decision of the data format between JSON or XML is still fifty-fifty. In any case, we can have either or both data formats in our API repository. In the next post, we will see how we can configure composite processes by utilizing multiple APIs with both JSON and XML data formats. Published at DZone with permission of Neerav Aggarwal . See the original article here. Opinions expressed by DZone contributors are their own. {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/build-a-rest-api-with-xml-payload
CC-MAIN-2019-47
refinedweb
1,070
65.32
Announcements ManaStoneMembers Content count1678 Joined Last visited Community Reputation148 Neutral About ManaStone - RankContributor Help a fellow game designer bring democracy to Oregon ManaStone posted a topic in GDNet LoungeFinally, somebody is trying to do something about our horrible uncompetitive first-past-the-post voting system. Mark Frohnmayer, co-founder of GarageGames, is trying to get 87,213 signatures to get a measure on a ballot in Oregon to change the voting system to an approval primary. This would be like the non-partisan primaries in California, except approval voting would be used to get the top two candidates. That means the two best candidates would be facing off in the general instead of the two that survived the vote spitting process. If you live in Oregon, or have relatives that live in Oregon, make sure you and your friends sign this petition and vote for this initiative when it is on the ballot. You can find out more information here . Also, make sure you like it on facebook . This is the most pragmatic solution to first-past-the-post voting system and extra competition will make sure the politicians are held accountable. Also, Oregon voters will be able to vote their conscience without being punished for it with the worst candidate winning. Dealing with importing conflicting package names in java. ManaStone replied to ManaStone's topic in General and Gameplay ProgrammingOk, nevermind this. I found the problem. I took a closer look at the contents with the jar tool and it appears that I downloaded the documentation files instead of the class files. I apologize if I wasted anyone's time. Dealing with importing conflicting package names in java. ManaStone replied to ManaStone's topic in General and Gameplay ProgrammingActually, I retried that javax thing and I am not getting the error I got before. So I guess you are right, that isn't the problem. Dealing with importing conflicting package names in java. ManaStone replied to ManaStone's topic in General and Gameplay ProgrammingI think that is the thing that is causing me trouble because I tried creating a test package called javax and it gave me the same problem when trying to import it from a jar file. I renamed it to javax2 and it resolved the issue. It appears to be a naming conflict. Dealing with importing conflicting package names in java. ManaStone posted a topic in General and Gameplay ProgrammingI'm downloaded the jgoodies jar file, but I can't import it right now because the first package inside it is named "com" and there is already a "com" package in one of the default global libraries. Is there anyway I can get around the naming ambiguatiy so I can import the jgoodies package? Is there a tool I can use to rename the package inside the jar file from "com" to "com2"? Does it make any sense to have more than one third party? ManaStone replied to ManaStone's topic in GDNet Lounge[quote name='mdwh' timestamp='1327930535' post='4907615'] Even if all third parties unite, at least in the UK and US they wouldn't manage to ever be one of the two main parties. Although yes, I share your dislike of FPTP. [/quote] The goal wouldn't really be to become a major party. It would be just a temporary alliance to change the voting system. It would have a simple message and disband after it achieves its goal. In the US, this could be done state by state and the party wouldn't have to worry about federal elections. The party could raise money nationally and become a powerhouse in a small state by focusing all resources there. After each victory, the party will have more notoriety and subsequent victories would be easier to achieve with fewer resources. Does it make any sense to have more than one third party? ManaStone replied to ManaStone's topic in GDNet Lounge[quote name='Sirisian' timestamp='1327827587' post='4907276'] We've had a [url=""]few posts[/url] (can't seem to find the recent ones. The new site seems to have crippled google's index maybe) regarding switching to instant run-off voting. I don't think the current two parties would allow it. [/quote] I was actually the one that started that thread. I changed my position about IRV since then. IRV is better than plurality, but it still has a lot of problems and you can still screw yourself over pretty easily by voting your conscience with it. I think the most pragmatic solution is to have an open primary with [url=""]approval voting[/url] and let the top two candidates face off in the general election. Does it make any sense to have more than one third party? ManaStone posted a topic in GDNet LoungeAll third parties have a common problem; it is extremely difficult for them to gain traction due to our first-past-the-post voting system. Wouldn't it make more sense to unite into one big tent party with the single goal of changing to a voting system that doesn't split the vote? There could be inner parties such as the Greens or Libertarians, and they can have their own primary within the primary. The parties primary election could use the [url=""]Condorcet method[/url] to elect its candidate and everyone within the party would be obliged to support the winner regardless of what other political positions that candidate has. After they change the voting system, the parties can split ways. Is there any reason why third parties shouldn't do this? Avoiding polymorphism in Java ManaStone replied to ManaStone's topic in General and Gameplay Programming[quote name='Alessio89' timestamp='1325715153' post='4899727'] post an example of that constructor issue... do you remember how constructors works with subclassing and the role of the "super" keyword? [/quote] The problem was that the overwriting function was using objects in the the derived class before they had a chance to initialize. I used a null check to solve it. It was a simple fix, but I just thought it might be useful to know how to explicitly choose which version to use just in case a more complex situation arises. Avoiding polymorphism in Java ManaStone replied to ManaStone's topic in General and Gameplay Programming[quote name='Telastyn' timestamp='1325713684' post='4899714'] Why would you want to? In general, if you run into this sort of thing where it's hard to do something in the language, it's a hint [i]not to do that.[/i] [/quote] Polymorphism caused a problem in one of my programs when a constructor called the wrong function. I've settled the problem, but I would like to be able to avoid in the future. Avoiding polymorphism in Java ManaStone posted a topic in General and Gameplay ProgrammingIs there a way I can explicitly avoid polymorphism is Java? For example, in the following code: [CODE] public class Main { public static void main(String[] args) { new Main().Run(); } public void Run() { ClassB b = new ClassB(); b.doThing(); } public class ClassA { public void doThing() { print(); } public void print() { System.out.println("A"); } } class ClassB extends ClassA { public void print() { System.out.println("B"); } } } [/CODE] Is there anyway I can write doThing() so that it always calls the ClassA version of print so that when the program runs it prints “A” instead of “B” Is there a Firefox addon that allows me to do this? ManaStone replied to ManaStone's topic in GDNet LoungeOk nevermind, I searched a little harder and I think I found something called cookieswap. I'm sorry for making an unnecessary post. Is there a Firefox addon that allows me to do this? ManaStone posted a topic in GDNet LoungeIs there any Firefox add-on that allows me to create different users and lets me have separate cookies for each user? I created my Youtube account with a different email than my gmail account a while back and now I can't be auto logged in to both at the same time. It would be so much easier if I could just switch users and automatically load in different cookies associated with that user as if I created a different windows account. Is there any add-on that already exists for Firefox that allows me to do this? - [quote name='Khaiy' timestamp='1313537280' post='4850082'] Besides, while it's quite well established that people are disgusted with both major US parties at present, it's also well established that they tend to view [i]their own[/i] representatives much more favorably. Also, I don't know that a different voting system would necessarily make politicians more accountable. They'll always have a huge incentive to try and slink out of responsibility, and most citizens are unsophisticated enough in at least one area of government controversy at any given time that they can be misled or otherwise distracted.[/quote] I think if they had more competition, the incumbents would have to work harder to stay elected. The incumbent very rarely gets challenged in a primary and he knows that his base is stuck with him. If we had an open primary with approval voting and a top two runoff for the Presidential election in 2012, I don't think there is any way Obama would get reelected. And maybe for the most part a different voting system won't change the behavior of politicians. Getting rid of vote splitting though would at the very least help us get rid of incumbents that step too far out of line. [quote] I'm still in favor of systems like ranked choice voting (very much so, though on review the above may not make it seem like it). My state is trying to pass ranked-choice voting statewide, against fierce opposition. California has open primaries, now though it's too early for the full effects of that to be known. I would love to see elections reflect the will of the voters, and the current system is quite poor at that. But at the same time, I'm not confident that a better voting system will resolve most of the serious issues that we have. [/quote] RCV in the form of IRV is better than plurality, but it gives unintuitive results. Burlington, Vermont used it for a while and in the 2009 mayoral election it didn't produce the Condorcet winner. A bunch of people freaked out and they repealed it through referendum. The problem now is that they are going to be more resistant to try another voting system. Approval voting would be much easier to implement and explain to people. Ideally I think the ranked pairs form of the Condorcet method would be the best method, but it would be hard to explain that to people and get them to support it. Also, it would be a nightmare to implement. I don't think the open primaries with plurality will help much because it doesn't stop the problems of vote splitting. Two candidates who are unpopular can make it into the general election. - [quote name='freddyscoming4you' timestamp='1313526458' post='4850027'] As long as the Electoral College exists voting is effectively broken in America as the people. Gore got the popular vote and should have won in 2000. This last decade could have been dramatically different from what we have today. [/quote] That is only for the President. Our strategy should be to get approval voting implemented state by state. That way we could elect better senators and representatives and each state victory will help build momentum. Once we are able to elect better candidates it will be a lot easier to change the electoral college. Ideally we'd have non-partisan open primaries with approval voting and the let the top two face of in the general.
https://www.gamedev.net/profile/6048-manastone/
CC-MAIN-2017-34
refinedweb
1,984
60.95