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
So you're there, working for five or six hours and then, for some reason, you need a list of the files you modified. So you log them: git whatchanged --since="6 hours ago" But imagine you've worked around thousand files. So how do you list only the file names? First, let's compact our output: git whatchanged --since="6 hours ago" --format=oneline Now, we need to get only the lines that have filenames on it, so we'll use grep for that: git whatchanged --since="6 hours ago" --format=oneline | grep "^:" Now let's remove all that trash and get just the filenames. For that, we'll use sed: git whatchanged --since="6 hours ago" --format=oneline | grep "^:" | sed 's:.*[DAM][ \\''t]*\([^ \\''t]*\):\1:g' And there you have it. The regex makes sure that only the file name is return (with a few spaces on the begginig of the line. that never bothered me but can easily be removed with another sed) and you can copy that to wherever you need it.
https://coderwall.com/p/8syvsa/list-the-modified-files-on-your-repository
CC-MAIN-2016-40
refinedweb
176
85.02
Writing code is tricky enough. You shouldn’t have to spend hours improving its readability or worry about unnecessary typos causing build errors. Ranorex 6.0 now makes a ton new code editor enhancements available, which will help you quickly write clean and easily maintainable test scripts. Here’re 7 of the most fantastic time-saving features: 1. Code templates We all love the custom code templates in Ranorex Studio. Using the tab key, you can now access multiple predefined templates, such as the for/for each loop. Icing on the cake for all us coders! 2. Context specific actions Improve your code structure with these amazing new context specific actions. Simply move newly created classes into specific files, or right click on the edit pencil to check for null or undefined variables. These are just a few examples – give it a try! 3. Refactoring Wouldn’t it be great if you could replace complex code fragments with small, easily readable methods? The extract method enables you to group your fragments to methods. You can further give them a clear name that explains their purpose. 4. CamelCase search functionality Find what you’re looking for faster with the CamelCase search functionality! CamelCase identifies the segments of compound words and uses the capital letters to list potential search results. 5. Auto insertion of using Start saving time when using namespaces! Type in a class using the auto-complete functionality. Ranorex will then automatically add the specific using directive of the needed namespace. 6. Introduction of new methods And yet another feature that will save you time: When calling an unknown method in code, you can now easily implement it with the context specific action ‘introduce method…’. 7. Switch on enum This little feature comes in quite handy and enables you to write code faster. When typing a “switch” statement where the condition is an enum the cases are automatically prefilled. These and many more fantastic features are available with Ranorex 6.0. Update your Ranorex Studio now (yes, it’s free!) and start coding!
https://www.ranorex.com/blog/code-editor-features/
CC-MAIN-2019-35
refinedweb
343
65.83
Pod, others on a Kubernetes Node, and others can run anywhere you have kubectl and credentials for the cluster. To make it clear what is expected, this document will use the following conventions. If the command “COMMAND” is expected to run in a Pod and produce “OUTPUT”: u@pod$ COMMAND OUTPUT If the command “COMMAND” is expected to run on a Node and produce “OUTPUT”: u@node$ COMMAND OUTPUT If the command is “kubectl ARGS”: $ kubectl ARGS OUTPUT For many steps here you will want to see what a Pod running in the cluster sees.: apps/v1 kind: Deployment metadata: name: hostnames spec: selector: matchLabels: app: hostnames replicas: 3 template: metadata: labels: app: hostnames spec: containers: - name: hostnames image: k8s.gcr.io/serve_hostname ports: - containerPort: 9376 protocol: TCP The astute reader will have noticed that we did not actually create a Service yet - that is intentional. This is a step that sometimes gets forgotten, and is the first thing to check. So what would happen if I tried to access a non-existent Service? Assuming you have another Pod that consumes this Service by name you would get something like: u@pod$ wget -qO- hostnames wget: bad address 'hostname' So the first thing to check is whether that Service actually exists: $ kubectl get svc hostnames Error from server (NotFound): services "hostnames" not found So we have a culprit, let’s create the Service. As before, this is for the walk-through - you can use your own Service’s details here. $ kubectl expose deployment hostnames --port=80 --target-port=9376 service "hostnames" exposed And read it back, just to be sure: $ kubectl get svc hostnames NAME CLUSTER-IP EXTERNAL-IP PORT(S) AGE hostnames 10.0.1.175 <none> 80/TCP 5s As before, this is the same as if you had started the Service with YAML: apiVersion: v1 kind: Service metadata: name: hostnames spec: selector: app: hostnames ports: - name: default protocol: TCP port: 80 targetPort: 9376 Now you can confirm that the Service exists. From a Pod in the same Namespace: u@pod$:: u@pod$): u@node$ is correct. u@pod$ cat /etc/resolv.conf. If the above still fails - DNS lookups are not working for your Service - we can take a step back and see what else is not working. The Kubernetes master Service should always work:, you might need to go to the kube-proxy section of this doc, or even go back to the top of this document and start over, but instead of debugging your own Service, debug DNS. Assuming we can confirm that DNS works, the next thing to test is whether your Service works at all. From a node in your cluster, access the Service’s IP (from kubectl get above). u@node$ curl 10.0.1.175:80 hostnames-0uton u@node$ curl 10.0.1.175:80 hostnames-yp2kp u@node$ curl 10.0.1.175:80 hostnames-bvc05 If your Service is working, you should get correct responses. If not, there are a number of things that could be going wrong. Read on.", "selfLink": "/api/v1/namespaces/default/services/hostnames", port you are trying to access in spec.ports[]? Is the targetPort correct for your Pods (many Pods choose to use a different port than the Service)? If you meant it to be a numeric port, is it a number (9376) or a string “9376”? If you meant it to be a named port, do your Pods expose a port with the same name? Is the port’s protocol the same as the Pod’s? If you got this far, we assume that you have confirmed that your Service exists and is resolved by DNS. Now let’s check that the Pods you ran are actually being selected by the Service. Earlier we saw that the Pods were running. We can re-check that: $ kubectl get pods -l app=hostnames NAME READY STATUS RESTARTS AGE hostnames-0uton 1/1 Running 0 1h hostnames-bvc05 1/1 Running 0 1h hostnames-yp2kp 1/1 Running 0 1h The “AGE” column says that these Pods are about an hour old, which implies that they are running fine and not crashing. The -l app=hostnames argument is a label selector - just like our Service has. Inside the Kubernetes system is a control loop which evaluates the selector of every Service and saves the results into that these commands use the Pod port (9376), rather than the Service port (80). u@pod$ wget -qO- 10.244.0.5:9376 hostnames-0uton pod $ wget -qO- 10.244.0.6:9376 hostnames-bvc05 u@pod$ wget -qO- 10.244.0.7:9376 hostnames-yp2kp We expect each Pod in the Endpoints list to return its own hostname. If this is not what happens (or whatever the correct behavior is for your own Pods), you should investigate what’s happening there. You might find kubectl logs to be useful or kubectl exec directly to your Pods and check service from there. Another thing to check is that your Pods are not crashing or being restarted. Frequent restarts could lead to intermittent connectivity If the restart count is high, read more about how to debug pods. If you get here, your Service is running, has Endpoints, and your Pods are actually serving. At this point, the whole Service proxy mechanism is suspect. Let’s confirm it, piece by piece. Confirm that kube-proxy is running on your Nodes. You should get something like the below: u@node$:https":https". One of the” mode. You should see one of the following cases. u on your Service (just one in this example) - a “KUBE-PORTALS-CONTAINER” and a “KUBE-PORTALS-HOST”. If you do not see these, try restarting kube-proxy with the -V flag set to 4, and then look at the logs again. Almost nobody should be using the “userspace” mode any more, so we won’t spend more time on it here. There should be 1 rule in KUBE-SERVICES, 1 or 2 rules per endpoint in KUBE-SVC-(hash) (depending on SessionAffinity), one KUBE-SEP-(hash) chain per endpoint, and a few rules in each KUBE-SEP-(hash) chain. The exact rules will vary based on your exact config (including node-ports and load-balancers). Assuming you do see the above rules, try again to access your Service by IP: u@node$ curl 10.0.1.175:80 hostnames-0uton: u@node$ curl localhost:48577 hostnames-yp2kp: hairpin-modeis set to hairpin-vethor promiscuous-bridge. You should see something like the below. hairpin-modeis set to promiscuous-bridgein the following example. u@node$" hairpin-veth, ensure the Kubelethas the permission to operate in /syson node. If everything works properly, you should see something like: u@node$ for intf in /sys/devices/virtual/net/cbr0/brif/*; do cat $intf/hairpin_mode; done 1 1 1 1 promiscuous-bridge, ensure Kubelethas the permission to manipulate linux bridge on node. If cbr0` bridge is used and configured properly, you should see: u@node$ ifconfig cbr0 |grep PROMISC UP BROADCAST RUNNING PROMISC MULTICAST MTU:1460 Metric:1 If you get this far, something very strange is happening. Your Service is running, has Endpoints, and your Pods are actually serving. You have DNS working, iptables rules installed, and kube-proxy does not seem to be misbehaving. And yet your Service is not working. You should probably let us know, so we can help investigate! Visit troubleshooting document for more information.Create an Issue Edit this Page
https://kubernetes.io/docs/tasks/debug-application-cluster/debug-service/
CC-MAIN-2018-17
refinedweb
1,253
71.14
This is a class that I made to test my if-else statement for calculating withholding tax for gross pay. The error I get is this: error: variable tax might not have been initialized System.out.println("Withholding Tax = " + tax); I initialized the variable tax and covered all of the possible values for gross in the if-else statements. So what am I doing wrong? Code : import java.util.Scanner; class apples { public static void main(String args[]) { Scanner input = new Scanner(System.in); double gross = input.nextDouble(); double tax; if (0 <= gross && gross <= 300.00) { tax = 0.10; } else if (300.01 <= gross && gross <= 400.00) { tax = 0.12; } else if (400.01 <= gross && gross <= 500.00) { tax = 0.15; } else if (gross >= 500.01) { tax = 0.20; } else { System.out.println("ERROR! Gross pay is less than zero"); } System.out.println("Withholding Tax = " + tax); } }
http://www.javaprogrammingforums.com/%20whats-wrong-my-code/14752-variable-not-initialized-printingthethread.html
CC-MAIN-2017-30
refinedweb
146
73.85
Agenda <fixup> Date: 23 Sep 2008 <fixup> Scribe: DanC SKW: agenda changes? AM: how about metadata? SKW: under URNsAndRegistries-50? JAR (and AM): probably won't fit there. SKW: ok... will try to fit it somewhere AM: or maybe discuss it over lunch. "proposal for a TAG F2F meeting Weds-Fri 10-12 December 2008 in Cambridge Mass, USA." -- SKW: there was a question as to why end of week [Wed-Fri as opposed to Tue-Thu] ... I think it was due to an XML conference HT: that XML conference has no technical track; I don't plan to go TBL: how about 9-11 Dec? several: that would be better for me PROPOSED: To hold a TAG meeting Tue-Thu 9-11 Dec 2008 in Cambridge, MA, USA, TBL/W3C to host. ... 3 full days TBL: or noon to noon? PROPOSED: to hold a TAG meeting Tue-Thu 9-11 Dec 2008 in Cambridge, MA, USA, TBL/W3C to host, ending at 3:30p Thu RESOLUTION: to hold a TAG meeting Tue-Thu 9-11 Dec 2008 in Cambridge, MA, USA, TBL/W3C to host, ending at 3:30p Thu TVR abstaining <DaveO> probable regrets for in person attendance at dec f2f SKW: I asked chairs whether there was interest to meet with TAG members during the TPAC... ... I won't be there. ... I've seen 2 responses: ... WebApps WG on the topic of URI Schemes for Widgets ... WAI-PF invitation to observe NM: I'm likely to be availble to meet with WebApps ... there will be a room for a TAG meeting? SKW: yes, there's meeting space reserved for TAG ... ok... so it looks like there's interest from TAG members to meet with WebApps re URI schemes SKW: The OASIS XRI TC is asking whether their present direction is something the TAG thinks is promising. discussion of communications between TAG chair and XRI TC chairs... SKW: examples [of base URIs]: or or or NM: an important point is: these =xyz things... they aren't expected to be recognized out of context, but treated as a relative URI, and the XRI-related policy stuff would be communicated in the usual top-down ways TBL: do they still expect to use this [?] in OpenID? HT: I expect so, as that's a major use case. ... yes, this looks promising, but the devil will be in the details... <noah> Right. What I said was: I would find it unacceptable if anyone proposed that the =xxx syntax was supposed to be recognized as an XRI in an arbitrary URI [context]; what I think is being proposed, and what's OK with me, is that URI is recognized as an XRI if and only if example.com says that they have used their URI space in this way. HT: the XML base rules are specified in some detail by specs from the XML Core WG, and unless this proposal plays by those rules exactly, we'll have to discuss it in detail SKW: any discussion against? no? ok... I'll take the ball... <scribe> ACTION: Stuart encourage discussion of proposal around or or or in www-tag <trackbot> Created ACTION-174 - Encourage discussion of proposal around or or or in www-tag [on Stuart Williams - due 2008-09-30]. SKW: the XRI TC is concerned that tracking this under URNsAndRegistries-50 is misleading ... and suggests some tweaks to our issue tracking... HT: it's administratively inconvenient to change the issue name, since our discussion is indexed under UrnsAndRegistries TBL: how about... ... his issue covers a) URIs for namespace names b) URNs and other proposed schemes for location ... independent names c) XML registries, and perhaps centralized vs. ... decentralized vocabulary tracking. NM: does that capture the indirection enough? there's something to the "registries" bit SKW: sounds like there's willingess to revise the issue description <scribe> ACTION: Stuart to collect input from TimBL and others and revise issue description <trackbot> Created ACTION-175 - Collect input from TimBL and others and revise issue description [on Stuart Williams - due 2008-09-30]. SKW: and we have another bit of writing... "Dirk and Nadia design a naming scheme" draft 16 Sep HT: after 2 years of [writer's block], I think I'm on to something... ... earlier drafts would neither (a) convert a skeptic, nor (b) serve as an introduction to a someone new to the issue. It only spoke to those who already agreed. ... this approach is perhaps not effective enough to convert those who take an extreme view, but I think it's not as off-putting as earlier drafts ... is this a promising direction? DC: I had a "I don't see point X covered yet" feeling, though I can't recall what the X was AM: [oops; missed the question] HT: I'm particularly happy with the list under "So, here are the requirements in detail" ... it doesn't yet incorporate a uri-in-uri requirement... I haven't gotten my head around that TBL: perhaps in a break I can help with that HT: there's a bit of "apples and oranges" between 'delegation' and the sorts of stability... HT goes to the whiteboard... headings: Owner / Resource / Representation under each, 0 = centralized, 1 = decentralized HT: all 8 possibilities... ... the 0 / 0 / 0 extreme... e.g. W3C... naming and resources are centralized. TBL: er... ok... I'll stipulate for now... HT: the 1 / 1 / 1 extreme is, e.g. "the web". ownership is distributed, etc. ... the hypothesis is "we can do all 8 rows with http". That's what I'm working through. TBL: a weakness in this table is that it assumes ownership, but naming schemes like using sha-1 don't really have ownership DC: yes, I think we need an appendix to say "we're not treating the things that don't involve ownership" ... I've seen "the TAG thinks all new URI schemes are harmful" but I want to be clear that we're not going that far... only "no new schemes when there's an administrative hierarchy in place" ... counterexamples include freenode/p2p, sha-1, etc. NM: I'm not sure the W3C example is a good one for the 0/0/0 case ... the W3C has delegation internally poll shows support for this direction [I presume there's a drafting action on HT that continues] <ht> (hmm... a copy of that should go to www-archive or something.) action-93? <trackbot> ACTION-93 -- Henry S. Thompson to review EXI WDs since 20 Dec -- due 2008-09-23 -- OPEN <trackbot> HT: the EXI WG has published 5 drafts: * Best Practices * Primer * Evaluation * WD * Impacts HT: I think "Best Practices" is most relevant for us... it's 10 now months old ... "Primer" seems to be orthogonal to / irrelevant for TAG considerations <timbl> I completely agree with your comment on section 4.2 HT: several years ago, the approach for exi was as a character encoding... ... then more recently, a new story emerged... "an EXI document is not a well-formed XML document..." [?more] HT: 2 questions: ... 1. EXI documents should not be well-formed XML ... 2. 2 bits (leading 1 0) is enough to distinguish EXI from XML ... i.e. does the TAG agree with 1 and 2? NM: I gather this is a new content encoding... [?] <Zakim> noah, you wanted to ask whether Content Type:application/___+xml; Content-Encoding: x-exi is the right way to go SKW: how about the Evaluation document? HT: I haven't worked on that lately SKW: we asked them to give a more succinct argument in the evaluation document TBL: a concern with the content-encoding approach it suggests exi applies to any byte sequence [?] ... [and a similar concern about the charset approach; scribe couldn't distinguish] HT: yes, all approaches have their down sides... [missed the gist of it] NM: one requirement is to round-trip XML documents, preserving single vs double quotes. This doesn't seem to meet that. HT: right. NM: ah. so it's acknowledged that this requirement isn't met. HT: another design choice is to duplicate the XML mime hierarchy; i.e. application/exi to to with application/xml, application/svg+exi to go with applicaiton/svg+xml and so on [incoherent chorus of down-sides to that approach] TBL draws a table: + / - for charset, content-encoding a + for the charset approach is that it applies to all XML files a - for charset is "not connegable". [DanC isn't sure about that. There's Accept-Charset, no?] a + for content-encoding work for all content types [disputed by Noah] a - for content-encoding is: software architecture on client needs a kludge HT: a downside of the charset is the 32 bytes <?xml version="1.0" encoding="exi"?> [incoherent debate about whether that really requires 32 bytes] SKW: we're requested to participate in their last call review 19 Sep to 7 Nov <noah> Evaluation document: DanC: yes; we should double-check that their new drafts address the comments they said they'd address ... in reply to <timbl> Do they have machine-readable data behind those graphs? NM: re efficiency, the gist of our comments, I see [something like] "this will be done in CR" DO: as I recall, we also asked for some less exotic use cases... I don't see that. <timbl> It would be nice if there were a web form based thing to test your own data, so that David could for example try ot with acouple of bits of XML from his daily life NM: I see convincing results re compactness but not yet wrt efficiency; so now I'd like to know if that's good enough for an interesting set of usecases <scribe> ACTION: Noah work with Dave to draft comments on exi w.r.t. evaluation and efficiency <trackbot> Created ACTION-176 - Work with Dave to draft comments on exi w.r.t. evaluation and efficiency [on Noah Mendelsohn - due 2008-09-30]. <scribe> ACTION: Stuart to schedule more discussion of exi architecture charset/encoding etc. <trackbot> Created ACTION-177 - Schedule more discussion of exi architecture charset/encoding etc. [on Stuart Williams - due 2008-09-30]. SKW: I'm bi-modal about this topic. I understand that it is a high priority for the TAG and why. However, there are now communities with such established momentum in [many] directions that I wonder what impact the TAG could expect to have. In addition, my day-job focus is not on hypertext which means that finding time to commit to doing a proper review of a 450+ page spec. is a real challenge - it's not my style to skim read. In 3-5 years time, what advice does the W3C expect to be giving hypertext content creators - what recommendation will it be making? I think that the W3C presenting multiple options does not help content creators and amounts to "...let the market figure it out...". DO: the way the HTML 5 spec is being produced... I have concerns about the process... but process issues are awkward for the TAG to address... ... meanwhile, it interferes with technical input, e.g. w.r.t. distributed extensibility NM: perhaps nothing novel to add, but... ... we should give what technical input we think will help, and if our input isn't taken up, such is life ... if HTML and XHTML co-exist, the TAG should help W3C tell people when to use one and when to use the other and such ... that advice might include recommending practical approaches despite conflict with architectural principles ... one view is "there's clean XHTML and messy tag soup". Then I've ready comments on the HTML 5 spec about the way it mixes a spec for browsers with a language spec... ... perhaps you could write a clean language spec for HTML 5 and separate that from the browser-patch-up stuff. I don't hear much about that approach HT: again, perhaps not novel... I'd like to help get the good stuff in HTML 5 more visible ... perhaps using traditional formal techniques and separate it from error recovery and such ... I see some support for this approach ... To the extent the TAG can do that, I'm interest. ... meanwhile, as a researcher, I'm interested in being more formal about the error recovery stuff. DC: well, I was hugely frustrated with making no progress toward my goals for HTML 5 in the first year of the HTML WG, but a few months later, perhaps one year is not that much in the HTML timeframe. So I'm open to looking at lots of approaches AM: I'm new to this area... the WHATWG is new on my radar. Looking at the landscape, I wonder if the chances of having impact are so low that... well... should we use our time for other things? JAR: it looks somewhat daunting to have impact; most of my work is disjoint with this technical area TVR: there's a potential crisis for the W3C if we say "HTML 5 is so difficult to deal with that we'll ignore it" then much of the work in W3C becomes irrelevant to deployment on the Web <jar> scribe: jar Around the table regarding html5 <timbl> Concern over - Losses of engineering quality, and architectural principles, which have serious consequences; - Changes of philosophy about improving the web as opposed to letting it fester while describing it; - Socially, lack of review by other groups who can't read the huge spec; - Socially and engineering .. making willful departure from other specs without negotiation with the other community. timbl: people have accused of partisanship stuart: Putting our analysis on record is a good idea. ... Let's document TAG opinion even if it risks having no effect. noah: Important for TAG to approach sympathetically needs of the different communities. Core intuition - we need to document what the browsers do - is beneficial ... But to mix this with a language spec is not a service to the community ... Better if the document could be relayered. Separate permissive behavior from 'clean' behavior ... having a clean spec is good for content creators ht: It would be good for goals of html5wg AND for w3c if a traditional language spec were separated out from monolithic ... and if it were described formally (with a grammar) ... (2) two bits of bridge-building to pursue: look at media type namespace defaulting proposal; and ... we need to find mechanisms, perhaps the w3c validator, perhaps via changes to specs, that help to people see that there are incremental improvements possible in the quality of their html documents <noah> Actually, where I'm scribed as saying "separate permissive behavior from clean behavior" isn't quite the nuance I had in mind. I think a language specification indicates which documents are legal, and what they mean. That's one spec. I think HTML 5 as drafted also includes a specification for pieces of code we might call browsers, which by the way attempt to provide useful output for content that would not be "legal" in the language spec, e.g. improperly nested elements. I think having both specifications is very important, but I would prefer that the browser specification, including fixup of bad content, was separate from the specification of the clean language and its correct interpretation. The former spec. would be for authors and for those who might in future be able to deploy less permissive UAs; the latter would be to achieve interoperability among browsers as we know them. raman: From TAG perspective, we must ask: How does the rest of W3C's work fit in with HTML5? <Zakim> raman, you wanted to add treat html5+js as the assembly language of the Web, compile better languages to the assembly language for delivery. That is what everyone is doing right noah: Consider possibility of encouraging people who can contribute to this discussion to run for an elected TAG spot? noah: Different axes along which to modularize ashok: There's a fairly large section on microformats - that should go in an appendix danc: Does parsing html5 require parsing numbers? ... So what about document.write ? ht: XML spec defines (BNF) which simultaneously defines language including entity refs AND language after entity ref expansion ... so to define two grammars is not completely unprecedented noah: would be nice to define a correspondence between nicely formed input and the DOM <DanC> (I think the spec for how markup relates to the DOM is currently specified as serialization rather than parsing in the current HTML5 draft) <DanC> ( 8.4 Serializing HTML fragments ) noah: defining the DOM should be straightforward... then the script runs. Suppose new text is not nicely formed. Maybe the specification for the clean language can just not specify what happens in the intermediate states while new text is being written, until the document character string is once again properly formed. ? ... try to make it as declarative as possible raman: Let's define clean version separately from conversion from not-clean to clean. ... Effect of executing document.write: apply same rules that would apply to get you from not-clean to clean ... html 5 spec is not clear on this. complicated state table ... browsers can load script synchronously or asynchronously (example of two .js files executing asynchronously) ... this twist is an accident. people noticed that the first script blocks the second script, workaround is document.createElement of a script tag stuart: Remember Douglas Crockford article against document.write ? ht: If you want a walled community, here's what the walls look like raman: google ajax has no document.write. no namespace pollution ... you do your library as a javascript library. publish a 2nd file that's a load hook. defines one new name. there is no document.write or createElement. read the ajax documentation timbl: About document.write: the createElement alternative is a pain ... <bubbles> Dan, see and <bubbles> show source on the first one, and note the call to google.load() timbl: but there's an ecmascript extension that makes it more concise ht: it makes xml a first-class syntactic object in javascript ... The languages that permit xml elements embedded, have never taken off. raman: Once you say declarative, all the imperative people come out and say you can't do everything declaratively ... but in Lisp, no one ever said "declarative". Instead they just made special forms that abstracted out the imperative part timbl: Is there a clean, concise alternative to document.write? <DanC> Fixing HTML Douglas Crockford 2007-11-28 raman: If you have eval, you don't need document.write timbl: Are there languages where SQL is integrated well into another language? [looking for precedent] noah: (about xaml) raman: document.write is a challenge to modularization. can we do: [core], error recovery, document.write ? ... document.write is what connects all the other clumps together noah: Language spec says what tags, attributes means. A spec for a processor talks about what can be done incrementally, what is accepted. Error recovery is about not-legal input, here's how to process it. ... Language to DOM could be specified declaratively. It's not a processing problem ... Wants one module that says: This is the clean spec, here's what you should author to ... then error recovery would go in another module danc: HTML 5 is not coordinating with other w3c activities. How should this be addressed. [looking at agenda - css, other web languages, ...] break. reconvening danc: Why should I be worried about this? raman: HTML5 spec has no business talking about how URLs are parsed ... should not be talking about how these particular strings should be interpreted. Rationale for doing so was error recovery... ... but this doesn't warrant defining the parsing rules for URLs. Danc: Doesn't see where HTML5 respecifies anything ... Is quite surgical. noah: It says it's not using "URI" as defined in rfc3986. Maybe a better way to write it would be to give a new name for the syntactic change/extension to URI? raman: Goes back to what group owns which specs ht: XML Core has names for things like this. System Identifier is a nonescaped URI, vintage 1998. What you put into an XML doc that gets turned into a URI by a specified process ... 5 specs have this same problem - what to call things that get turned into URIs. They all cut & paste text that was written for Xlink 1.0 ... When IRI came along, this became untenable. Current revision of IRI spec will include a section on 'legacy extended IRIs' ... Not clear when new RFC is coming out. hostage to IDN ... A part of HTML 5's problem has been solved by LEIRIs ... The problem is error recovery - what to do when the string isn't a URI ... First bullet (2.5.2 of [what document??]) is addressed by the WG note [on LEIRIs] <ht> noah: First issue is stripping leading and trailing space ... no one is saying the spaces are part of the URI ht: Principle of least surprise says we'd be better if across the board users had a single expectation on how to write URIs in the documents ... Ergo, (1) we need the RFC specifying URIs; and (2) we need to say how to write them in documents stuart: Jena handles IRIs - has 6 modes of operation ht: XML Core is trying to reduce this to 1 raman: URL situation is an example of the social problem. I don't expect to solve this, or if we do, for our solution to make any difference ... Rather, how do we bring about solution to social problem, of who owns what specs? Danc: Maybe take URI related parts of HTML 5 and send to IETF for review ... ? noah: Space trimming is a funny use of "error recovery". I think "error recovery" has to do with processing... danc: agreed. jar: Is this an example of clean/not-clean distinction? noah: No, it's a detail timbl: The problem is that the HTML 5 spec doesn't distinguish clean from not-clean ... [thinks that space stripping is not-clean but recoverable] <DanC> for reference, Assess whether "URLs" section/definition conflicts with Web architecture <timbl> I think it is important that the cases which don't meet the IRI spec are referred to as errors, even if the errors are ignored in HTML5 browser handling jar: compare to C programming language 1970's vs. 1980's raman: No problem with having the browser accept everything ... Problem is that the spec is writing in: Go ahead and write these things, it's OK jar: Balance of power is different. In C the language had no power relative to the "browsers" (CPUs), so new CPUs could dictate language changes ht: Is the third bullet (about %s) telling us that % should, or shouldn't be %-encoded? still on 2.5.2 of HTML 5 draft danc: issue of string + document encoding pairing ... <DanC> uri encoding test cases <DanC> SKW: "It is possible for xml:base attributes to be present even in HTML fragments, as such attributes can be added dynamically using script. (Such scripts would not be conforming, however, as xml:base attributes are not allowed in HTML documents.)" <DanC> see also 3.3.3.4. The xml:base attribute (XML only) danc: (unknown elements go in the dom. unknown attributes don't) noah: rationale? danc: unknown ... XQuery has test cases for handling of URIs in attribute values, right? ht: There are XML test cases for 'system identifiers' danc: IETF is concerned about scope of HTML 5 including a protocol (web sockets) raman: What about interaction between metadata (e.g. xml:lang=) in document vs. in HTTP headers? ... Does xml:lang or lang override HTTP headers? This should technically be decided by HTTP WG stuart: 'authoritative metadata' tag finding ... Is html LANG well specified anywhere? danc: see HTML 4 <DanC> long thread around lang vs xml:lang vs http content-language <Stuart> danc: (Wondering about how to liaise regarding URI spec(s)) <DanC> for reference: URIs in HTML5 and issues arising Ian Hickson (Sunday, 29 June) stuart: The original idea of http-equiv was that the server would pull it out and supply as http header? danc: Yes, since some people had no [other] way to influence the server stuart: and then the clients started interpreting http-equiv as well <ht> adjourned.
http://www.w3.org/2001/tag/2008/09/23-minutes
crawl-002
refinedweb
4,068
64.1
Definition of Python Object to JSON Python Object to JSON is a method of serialization of a python class object into JSON (JavaScript Object Notation) string object. This method helps us to convert a python class object into JSON, which is a more compact format than a python object. In this method, we use the “JSON” package which is a part of the python programming language itself (built-in), and use the JSON.dumps() method to convert a python class object into a flat JSON string object. The JSON is a light-weight data format due to which we save space by converting a python class object into a JSON string object (python class objects consume more space than the JSON object). In this article, we will cover how to convert a python class object to a JSON string object with hands-on example codes with output as well. Install the package Before you can start converting a python object into a json object, the first thing that you have to do is install a package that allows you to do so. We have a “json” package in python to deal with this conversion and which can be installed with the code syntax mentioned below: #installing json package This package has “json.dumps()” and “json. dump()” functions which allow us to convert the python object into a JSON object. However, these two procedures have a basic difference as mentioned below: - dumps() function converts(serializes) a python object into a string that is JSON formatted. - dump() function on the other hand does an additional job than converting the object; it allows you to write that formatted change into a file. You can convert different types of python objects into JSON string such as int, string, list, tuple, dict, float, bol, etc. The functions discussed above will help you in the conversion of a Python object to an equivalent JSON object based on the table below: Python to JSON Conversion Table Examples Let us see a basic example that covers the conversion of all these datatypes above into a JSON string in python. Example #1 Code: import json #Converting different python objects into an equivalent JSON string name = "Dell Vostro" #Str print(json.dumps(name)) ram_in_gb = 4 #Int print(json.dumps(ram_in_gb)) price = 37500.98 #Float print(json.dumps(price)) touch = False #Bool print(json.dumps(touch)) wifi = True #Bool print(json.dumps(wifi)) Graphic = None #None print(json.dumps(Graphic)) list1 = ["Dell Vostro", 4, 37500.98] #List print(json.dumps(list1)) touple1 = ("Dell Vostro", 4, 37500.98) #Touple print(json.dumps(touple1)) dict1 = {"name" : "Dell Vostro", "price" : 37500.98, "wifi" : True} #Dict print(json.dumps(dict1)) Here, we have enclosed the object of each data type into json.dumps() function in order to convert it into a JSON string. See below is the output of this code once run. Here, in this example, all details associated with my laptop are considered as different data types usually deal with. The equivalent JSON objects can be seen in the output screenshot above. Interestingly, we can create a python object with all these data types together and then convert it into a json string as well. Note that, the final output will be a dictionary of a JSON string. See the code associated with it as shown below: Example #2 Code: import json #Converting a python object into a JSON string together = json.dumps( { "name" : "Dell Vostro", "ram_in_gb" : 4, "price" : 37500.98, "touch" : False, "wifi" : True, "Graphic" : None, "list1" : ["Dell Vostro", 4], "touple1" : ("Dell Vostro", 37500.98) }) print(together) Here, we have created a python dictionary with multiple data types (string, int, bool, etc.) and all these details are provided as input to json.dumps() function. It is stored into a variable named together so that we can print it later. Finally, the json.dumps() function is used to convert this python object (a dictionary) to JSON (output will be a dictionary with JSON string data types). See the output as shown below: If you see the output, keywords are retained as keywords in JSON string dictionary and values for those keywords are converted into equivalent JSON data types. A point to note here is, siblings and languages are both converted into an array in resultant JSON (previously were a list and a tuple respectively). We can customize the JSON output with few customization Arguments in the code above. See it as below: #Customizing the code with additional arguments together = json.dumps( { "name" : "Dell Vostro", "ram_in_gb" : 4, "price" : 37500.98, "touch" : False, "wifi" : True, "Graphic" : None, "list1" : ["Dell Vostro", 4], "touple1" : ("Dell Vostro", 37500.98) }, sort_keys=True, indent = 4) print(together) Here, in this code, the two additional arguments (apart from the object argument) we have used under the json.dumps() function. The first argument, “sort_keys = True” allows the system to generate output in a manner that keys are sorted in alphabetical order. The second argument “indent = 4” specifies how many indentations should be used while generating the output. Example #3 Let us use the json.dump() function to create a JSON file in the python. Code: import json #creating a file with name user.json in working directory with open('user.json','w') as file: json.dump({ "name" : "Lalit", "age" : 28, "active" : True, "married" : False, "pets" : None, "amount": 450.98, "siblings": ["Mona", "Shyam", "Pooja"], "languages" : ("English", "German", "Spanish") }, file, sort_keys= True, indent=4) Here in this code, we have used the json.dump() function in combination with open() to create a JSON file named user.json in the working directory. The json.dump() function itself is used when we want to create a file of JSON objects that are converted from the original python objects. Let us see the file in the working directory: After running the code above, a JSON file gets created in the working directory If we try to open this file in any text editor, we will have the same dictionary of JSON string as in the above example. Please find below is the screenshot for your reference: This article ends here. However, before closing it off, let’s make a note of few conclusion points. Conclusion - The python to Object to JSON is a method of converting python objects into a JSON string formatted object. - We have the “json” package that allows us to convert python objects into JSON. - The json.dumps() function converts/serialize a python object into equivalent JSON string object and return the output in console. - The json.dump() function instead of returning the output in console, allows you to create a JSON file on the working directory. Recommended Articles This is a guide to Python Object to JSON. Here we discuss the Definition and install the package and Python to JSON Conversion Table with examples. You may also have a look at the following articles to learn more –
https://www.educba.com/python-object-to-json/?source=leftnav
CC-MAIN-2021-39
refinedweb
1,144
64.51
I have a String[] with values like so: public static final String[] VALUES = new String[] {"AB","BC","CD","AE"}; Given String s, is there a good way of testing whether VALUES contains s? 7 Arrays.asList(yourArray).contains(yourValue) Warning: this doesn’t work for arrays of primitives (see the comments). Since java-8 you can now use Streams. String[] values = {"AB","BC","CD","AE"}; boolean contains = Arrays.stream(values).anyMatch("s"::equals); To check whether an array of int, double or long contains a value use IntStream, DoubleStream or LongStream respectively. Example int[] a = {1,2,3,4}; boolean contains = IntStream.of(a).anyMatch(x -> x == 4); 33 - 106 I am somewhat curious as to the performance of this versus the searching functions in the Arrays class versus iterating over an array and using an equals() function or == for primitives. Jul 15, 2009 at 0:06 - 195 You don’t lose much, as asList() returns an ArrayList which has an array at its heart. The constructor will just change a reference so that’s not much work to be done there. And contains()/indexOf() will iterate and use equals(). For primitives you should be better off coding it yourself, though. For Strings or other classes, the difference will not be noticeable. Jul 15, 2009 at 0:09 - 19 - 65 Nyerguds: indeed, this does not work for primitives. In java primitive types can’t be generic. asList is declared as <T> List<T> asList(T…). When you pass an int[] into it, the compiler infers T=int[] because it can’t infer T=int, because primitives can’t be generic. Jun 14, 2011 at 16:51 - 29 @Joey just a side note, it’s an ArrayList, but not java.util.ArrayListas you expect, the real class returned is: java.util.Arrays.ArrayList<E>defined as: public class java.util.Arrays {private static class ArrayList<E> ... {}}. Oct 17, 2012 at 9:16 Concise update for Java SE 9 Reference arrays are bad. For this case we are after a set. Since Java SE 9 we have Set.of. private static final Set<String> VALUES = Set.of( "AB","BC","CD","AE" ); “Given String s, is there a good way of testing whether VALUES contains s?” VALUES.contains(s) O(1). The right type, immutable, O(1) and concise. Beautiful.* Original answer details Just to clear the code up to start with. We have (corrected): public static final String[] VALUES = new String[] {"AB","BC","CD","AE"}; This is a mutable static which FindBugs will tell you is very naughty. Do not modify statics and do not allow other code to do so also. At an absolute minimum, the field should be private: private static final String[] VALUES = new String[] {"AB","BC","CD","AE"}; (Note, you can actually drop the new String[]; bit.) Reference arrays are still bad and we want a set: private static final Set<String> VALUES = new HashSet<String>(Arrays.asList( new String[] {"AB","BC","CD","AE"} )); (Paranoid people, such as myself, may feel more at ease if this was wrapped in Collections.unmodifiableSet – it could then even be made public.) (*To be a little more on brand, the collections API is predictably still missing immutable collection types and the syntax is still far too verbose, for my tastes.) 13 - 197 Except it’s O(N) to create the collection in the first place 🙂 Apr 25, 2011 at 6:54 - 67 - 2 @TomHawtin-tackline Why do you say “in particular here we want a set”? What is the advantage of a Set (HashSet) in this case? Why is a “reference array” bad (by “reference array” do you mean an ArrayList backed by an array as generated by a call to Arrays.asList)? Aug 29, 2014 at 5:04 - 7 @nmr A TreeSetwould be O(log n). HashSets are scaled such that the mean number of elements in a bucket is roughly constant. At least for arrays up to 2^30. There may be affects from, say, hardware caches which the big-O analysis ignores. Also assumes the hash function is working effectively. Sep 9, 2014 at 23:51 - 3 You can use ArrayUtils.contains from Apache Commons Lang public static boolean contains(Object[] array, Object objectToFind) Note that this method returns false if the passed array is null. There are also methods available for primitive arrays of all kinds. Example: String[] fieldsToInclude = { "id", "name", "location" }; if ( ArrayUtils.contains( fieldsToInclude, "id" ) ) { // Do some stuff. } 8 - 4 - 2 package: org.apache.commons.lang.ArrayUtils Jan 31, 2014 at 2:39 - 45 - 1 - 11 @max4ever Most android apps are minimalized by Proguard, putting only the classes and functions you need into your app. That makes it equal to roll your own, or copy the source of the apache thing. And whoever doesn’t use that minimalization doesn’t need to complain about 700kb or 78kb 🙂 Aug 12, 2016 at 13:11 Long way around it, but you can use a for loop: “for (String s : VALUES) if (s.equals(“MYVALUE”)) return true; Jul 15, 2009 at 0:51 @camickr–I have a nearly identical situation with this one: stackoverflow.com/a/223929/12943 It just keeps getting votes yet was just a copy/paste from sun’s documentation. I guess score is based on how much help you provided and not how much effort you put into it–and mostly how fast you post it! Maybe we’ve stumbled onto John Skeet’s secret! Well good answer, +1 for you. Apr 29, 2013 at 6:50 If you’re using Apache Commons, then org.apache.commons.lang.ArrayUtils.contains() does this for you. Nov 12, 2013 at 21:05 @camickr because people, like me, google a question, click on the SO result, see your answer, test it, it works, upvote the answer and then leave. Jul 20, 2015 at 2:41 I really miss a simple indexOfand containsin java.util.Arrays– which would both contain straightforward loops. Yes, you can write those in 1 minute; but I still went over to StackOverflow expecting to find them somewhere in the JDK. May 1, 2020 at 10:38 | Show 2 more comments
https://coded3.com/how-do-i-determine-whether-an-array-contains-a-particular-value-in-java/
CC-MAIN-2022-40
refinedweb
1,026
65.32
import Data using Excel 2003 on 64 Bit SQL Server - Tuesday, August 03, 2010 4:04 PMI wonder if you happen to run into following issue with 64 bit SQL Server when we try to import from Excel 2003: Do you know if there any driver available to do what we need. We have a lot of functionality relying on following statement: select * into TableName FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0','Excel 8.0;HDR=YES;IMEX=1;Database=fullfilename',Sheet1$)" which works nicely from 32 bit SQL Server 2005 to import Excel 2003. Now we need to do the same from 64 bit SQL2008, this driver doesn't work and new "ACE" drivers also seem to fail. I appreciate any feedaback you may have. All Replies - Wednesday, August 04, 2010 5:26 AM Hi, Could you please elaborate a bit? There is no 64-bit version of the Jet Drivers available. We can use the 64-bit version of the ACE Driver/Provider to retrieve data from an Excel spreadsheet on a 64-bit box. Please see: How to get a x64 version of Jet? What do you mean by “new ACE drivers also seem to fail”? Did you receive any error messages? As it’s a 64-bit SQL Server, we need to download and install the64-bit “Microsoft.ACE.OLEDB.12.0” from the following link: Microsoft Access Database Engine 2010 Redistributable After that, we can use the following statement to retrieve data from the Excel 2003 spreadsheet: SELECT * FROM OPENROWSET( 'Microsoft.ACE.OLEDB.12.0', 'Excel 12.0 Xml;Database=D:\Book1.xls;HDR=YES', 'SELECT * FROM [Categories$]') Please remember to mark the replies as answers if they help and unmark them if they provide no help. Welcome to the All-In-One Code Framework! If you have any feedback, please tell us. - Marked As Answer by vinod kushwaha Thursday, August 05, 2010 7:02 PM - - Monday, August 16, 2010 10:17 AM Hi Guys I've been playing with this driver for a while and I'm not yet satifisied this is a stable driver, myself and according to quite a lot of other internet forums like this, have experienced serious problems with this driver. You may find it works fine for a while, but randomly it will stop working and if you are using this to insert data say from an Excel file or CSV file then you will end up will a process on your SQL server that cannot be killed (it will be left in a permanent state of KILLED/ROLLBACK for weeks if you leave it). This is not a permissions issue, trust me, it would appear most likely to be an issue with the driver - aside from the fact that it screws the process and leaves it in a state of perpetual KILLED/ROLLBACK if you try and kill it. I thought this might be the answer to 64 bit woes of Microsoft Office file connectivity via SQL 2005. Which might I say has made 64 bit SQL and the lack of 64 bit Windows drivers to access CSV or Microsofts own Access/Excel files via 64 bit SQL server a joke until this driver! I for one seriously lost faith in SQL server 64 bit because of this, I know its a fault with Windows Server 2003 64 bit and it not the JET driver but come on Microsoft do you want to have SQL server taken seriously over its competitors? So SSIS an Excel files on a 64 bit server? Say hello to running it from a command line in via WOW... For anyone interested, here is the command line you can use to execute your 32bit package... unless your lucky enough to have SQL 2008 where you've got a tick box to run in 32bit mode. C:\Windows\SYSWOW64\CMD.EXE /C ""C:\Program Files (x86)\Microsoft SQL Server\90\DTS\Binn\DTEXEC.EXE" /FILE "C:\somepackage.dtsx" /MAXCONCURRENT " -1 " /CHECKPOINTING OFF /REPORTING E" Don't forget all those quotes, that stung me the first time!!! So unless you can work around this problem and are free to restart your server - I invite anyone else to come up with another solution - then steer clear of this driver or use with caution!! If anyone has figured any way round this, please let me know! I will eternally be your friend!! :-) - Wednesday, January 05, 2011 4:03 PMHi Padigan I'm just writing to confirm what you said. For simple excel file around couple of thousands of row the process run fine but when we get closed to 100 of thousands of row, the process run for ever. The funny thing is it works sometimes and other times it just gets stocked. I just choose to enable the 32bit mode in IIS 7.5 and stick with the 32 bit version of ACE.
http://social.msdn.microsoft.com/Forums/en-US/sqldataaccess/thread/2cb05610-55ee-4f7d-8f94-0236c515927a/
CC-MAIN-2013-20
refinedweb
816
68.4
A QtAV is a multimedia playback library based on Qt and FFmpeg. It can help you to write a player with less effort than ever before. QtAV has been added to FFmpeg projects page QtAV is free software licensed under the term of LGPL v2.1. The player example is licensed under GPL v3. If you use QtAV or its constituent libraries, you must adhere to the terms of the license in question. QtAV can meet your most demands Some components in QtAV are designed to be extensible. For example, you can write your decoder, audio output for particular platform. Here is a very good example to add cedar hardware accelerated decoder for A13-OLinuXino The required development files to build QtAV can be found in sourceforge page: depends See the wiki Build QtAV and QtAV Build Configurations Write a media player using QtAV is quite easy. GLWidgetRenderer2 renderer; renderer.show(); AVPlayer player; player.setRenderer(&renderer); player.play("test.avi"); For more detail to using QtAV, see the wiki Use QtAV In Your Project or examples. QtAV can also be used in Qml import QtQuick 2.0 import QtAV 1.6 Item { Video { id: video source: "test.mp4" } MouseArea { anchors.fill: parent onClicked: video.play() } } Run player -h Use QtAV in QML with OpenGL shaders(example is from qtmultimedia. But qtmultimedia is replaced by QtAV) 2013-01-21
https://xscode.com/wang-bin/QtAV
CC-MAIN-2021-17
refinedweb
228
67.96
Beautiful APIs in Node This post is on how to build beautiful APIs in Node.js. Great, and what is an API? The definition says Application Programming Interface, but what does it mean? It could mean on of the few things depending on the context: - Endpoints of a service service-oriented architecture (SOA) - Function signature - Class attribute and methods The main idea is that an API is a form of a contract between two or more entities (objects, classes, concerns, etc.). Your main goal as a Node engineer is to build beautiful API so that developers who consume your module/class/service won’t be cursing and sending you hate IM and mail. The rest of your code can be ugly but the parts which are public (mean for usage by other programs, and developers) need to be conventional, extendable, simple to use and understand, and consistent. Let’s see how to build beautiful APIs for which you can make sure other developer Beautiful Endpoints in Node: Taming the REST Beast Most likely, you are not using core Node http module directly, but a framework like Express or Hapi. If not, then strongly consider using a framework. It will come with freebies like parsing and route organization. I’ll be using Express for my examples. Here’s our API server with CRUD for the /accounts resource listed with an HTTP method and the URL pattern (`{} means it’s a variable): - GET /accounts: Get a list of accounts - GET /accounts/{ID}: Get one account by ID - PUT /accounts/{ID}: Partial update one account by ID - DELETE /accounts/{ID}: Remove one account by ID You can notice immediately that we need to send the resource (account) ID in the URL for the last three endpoints. By doing so we achieve the goals of having a clear distinction between resource collection and individual resource. This in turn helps to prevent mistakes from the client side. For example, it’s easier to mistake DELETE /accounts with ID in the body of the request for the removal of all accounts which can easily get you fired if this bug ever makes it into production and actually causes the deleting of all accounts. Additional benefits can be derived from caching by URL. If you use or plan to use Varnish, it caches responses and by having /accounts/{ID} you will achieve better caching results. Still not convinced? The let me tell you that Express will just ignore payload (request body) for requests like DELETE so the only way to get that ID is via a URL. Express is very elegant in defining the endpoints. For the ID which is called a URL parameter, there’s a req.params object which will be populated with the properties and values as long as you define the URL parameter (or several) in the URL pattern, e.g., with :id. app.get('/accounts', (req, res, next) => { // Query DB for accounts res.send(accounts) }) app.put('/accounts/:id', (req, res, next) => { const accountId = req.params.id // Query DB to update the account by ID res.send('ok') }) Now, a few words about PUT. It’s misused a lot because according to the specification PUT is for complete update, i.e., replacement of the whole entity, not the partial update. However, a lot of API even of big and reputable companies use PUT as a partial update. Did I confuse you already? It’s just the beginning of the post! Okay, let me illustrate the difference between partial and complete. If you update with{a: 1} an object {b: 2}, the result is {a: 1, b: 2} when the update is partial and {a: 1} when it’s a complete replacement. Back to the endpoints and HTTP methods. A more proper way is to use PATCH for partial updates not PUT. However, PATCH specs is lacking in implementation. Maybe that’s the reason why a lot of developers pick PUT as a partial update instead of PATCH. Okay, so we are using PUT because it became the new PATCH. So how do we get the actual JSON? There’s body-parser which can give us a Node/JavaScript object out of a string. const bodyParser = require('body-parser') // ... app.use(bodyParser.json()) app.post('/accounts', (req, res, next) => { const data = req.body // Validate data // Query DB to create an account res.send(account._id) }) app.put('/accounts/:id', (req, res, next) => { const accountId = req.params.id const data = req.body // Validate data // Query DB to update the account by ID res.send('ok') }) Always, alway, always validate the incoming (and also outgoing) data. There are modules like joi and express-validator to help you sanitize the data elegantly. In the snippet above, you might have noticed that I’m sending back the ID of a newly created account. This is the best practice because clients will need to know how to reference the new resource. Another best practice is to send proper HTTP status codes such as 200, 401, 500, etc. They go into categories: - 20x: All is good - 30x: Redirects - 40x: Client errors - 50x: Server errors By providing a valid error message you can help developers on the client side dramatically, because they can know if the request failure is their fault (40x) or server fault (500). In the 40x category, you should distinguish at the very least between authorization, poor payload, and not found. In Express, status codes are chained before the send(). For example, for POST /accounts/ we are sending 201 created along with the ID: res.status(201).send(account._id) The response for PUT and DELETE doesn’t have to contain the ID because we know that client knows the ID. They used in the URL after all. It’s still a good idea to send back some okay message saying that it all when as requested. The response might be as simple as {“msg”: “ok”} or as advanced as { "status": "success", "affectedCount": 3, "affectedIDs": [ 1, 2, 3 ] } What about query strings? They can be used for additional information such as a search query, filters, API keys, options, etc. I recommend using query string data for GET when you need to pass additional information. For example, this is how you can implement pagination (we don’t want to fetch all 1000000 accounts for the page that shows only 10 of them). The variable page is the page number and the variable limit is how many item is needed for a page. app.get('/accounts', (req, res, next) => { const {query, page, limit} = req.query // Query DB for accounts res.status(200).send(accounts) }) Enough about endpoints, let’s see how to work on a lower level with functions. Beautiful Functions: Embracing the Functional Nature of Node Node and JavaScript are very (but not completely) functional meaning we can achieve a lot with functions. We can create objects with functions. A general rule is that by keeping functions pure you can avoid future problems. What is a pure function? It’s a function which does NOT have side effects. Don’t you love smart asses who define one obscure term with another even more obscure one? A side effect is when a function “touches” something outside, typically a state (like a variable or an object). The proper definition is more complex, but if you remember to have function which only modify their argument, you’ll better off than majority (with majority only being 51% — and it’s my humble guesstimate anyway). This is a beautiful pure function: let randomNumber = null const generateRandomNumber = (limit) => { let number = null number = Math.round(Math.random()*limit) return number } randomNumber = generateRandomNumber(7) console.log(randomNumber) This is a very impure function because it’s changing randomNumber outside of its scope. Accessing limit out of scope is an issue too because this introduce additional interdependency (tight coupling): let randomNumber = null let limit = 7 const generateRandomNumber = () => { randomNumber = Math.floor(Math.random()*limit) } generateRandomNumber() console.log(randomNumber) The second snippet will work alright but only up to a point in the future as long as you can remember about the side effects limit and randomNumber. There are a few things specific to Node and function only. They exist because Node is asynchronous and we didn’t have the hipster promises or async/await back in 201x when the core of Node was forming and growing rapidly. In short, for async code we need a way to schedule some future code execution. We need to be able to pass a callback. The best approach is to pass it as the last argument. If you have a variable number of argument (let’s say a second argument is optional), then still keep the callback as last. You can use arity (arguments) to implement it. For example, we can re-write our previous function from synchronous execution to asynchronous by using callback as the last argument pattern. I intentionally left randomNumber = but it will be undefined since now the value will be in the callback at some point later. let randomNumber = null const generateRandomNumber = (limit, callback) => { let number = null // Now we are using super slow but super random process, hence it's async slowButGoodRandomGenerator(limit, (number) => { callback(number) }) // number is null but will be defined later in callback } randomNumber = generateRandomNumber(7, (number)=>{ console.log(number) }) // Guess what, randomNumber is undefined, but number in the callback will be defined later The next pattern which is closely related to async code is error handling. Each time we set up a callback, it will be handled by event loop at some future moment. When the callback code is executed we don’t have a reference to the original code anymore, only to variable in the scope. Thus, we cannot use try/catch and we cannot throw errors like I know some of you love to do in Java and other synchronous languages. For this reason, to propagate an error from a nested code (function, module, call, etc.), we can just pass it as an argument… to the callback along with the data (number). You can check for your custom rules along the way. Use return to terminate the further execution of the code once an error is found. While using null as an error value when no errors are present (inherited or custom). const generateRandomNumber = (limit, callback) => { if (!limit) return callback(new Error('Limit not provided')) slowButGoodRandomGenerator(limit, (error, number) => { if (number > limit) { callback(new Error('Oooops, something went wrong. Number is higher than the limit. Check slow function.'), null) } else { if (error) return callback(error, number) return callback(null, number) } }) } generateRandomNumber(7, (error, number) => { if (error) { console.error(error) } else { console.log(number) } }) Once you have your async pure function with error handling, move it to a module. You have three options: - File: The easiest way is to create a file and import it with require() - Module: You can create a folder with index.js and move it to node_modules. This way you don’t have to worry about pesky __dirname and path.sep). Set private: true to avoid publishing. - npm Module: Take your module a step further by publishing it on npm registry In either case, you would use CommonJS/Node syntax for modules since the ES6 import is nowhere near TC39 or Node Foundation roadmap (as of Dec 2016 and a talk from the main contributor I’ve heard at Node Interactive 2016). The rule of thumb when creating a module is what you export is what you import. In our case, it’s function so: module.exports = (limit, callback) => { //... } And in the main file, you import with require. Just don’t use capital case or underscores for file names. Really, don’t use them: const generateRandomNumber = require('./generate-random-number.js') generateRandomNumber(7, (error, number) => { if (error) { console.error(error) } else { console.log(number) } }) Aren’t you happy that generateRandomNumber is pure? :-) I bet it would have taken you longer to modularize an impure function, due to the tight coupling. To sum up, for beautiful function, you would typically make the asynchronous, have data as the first argument, options as the second and callback as the last. Also, make the options an optional argument and thus callback can be second or third argument. Lastly, the callback will pass error as first argument event if it’s just null (no errors) and data as the last (second) argument. Beautiful Classes in Node: Diving into OOP with Classes I’m not a huge fan of ES6/ES2015 classes. I use function factories (a.k.a. functional inheritance pattern) as much as I can. However, I expect more people would start coding in Node who came from front-end or Java background. For them, let’s take a look at the OOP way to inherit in Node: class Auto { constructor({make, year, speed}) { this.make = make || 'Tesla' this.year = year || 2015 this.speed = 0 } start(speed) { this.speed = speed } } let auto = new Auto({}) auto.start(10) console.log(auto.speed) The way class is initialized (new Auto({})) is similar to a function call in the previous section, but here we pass an object instead of three argument. Passing an object (you can call it options) is a better more beautiful pattern since it’s more versatile. Interestingly enough, as with functions, we can create named functions (example above) as well as anonymous classes by storing them in variables (code below): const Auto = class { ... } The methods like the one called start in the snippet with Auto are called prototype or instance method. As with other OOP languages, we can create static method. They are useful when methods don’t need access to an instance. Let’s say you are a starving programmer at a startup. You saved $15,000 from your meager earning by eating ramen noodles. You can check if that enough to calling a static method Auto.canBuy and there’s no car yet (no instance). class Auto { static canBuy(moneySaved) { return (this.price<moneySaved) } } Auto.price = 68000 Auto.canBuy(15000) Of course, it all would have been too easy if TC39 included the standard for static class attributes such as Auto.price so we can define them right in the body of class instead of outside, but no. They didn’t include class attribute in ES6/ES2015. Maybe we’ll get it next year. To extend a class, let’s say our automobile is a Model S Tesla, there’s extends operand. We must call super() if we overwrite constructor(). In other words, if you extend a class and define your own constructor/initializer, then please invoke super to get all the things from the parent (Auto in this case). class Auto { } class TeslaS extends Auto { constructor(options) { super(options) } } To make this beautiful, define an interface, i.e., public methods and attributes/properties of a class. This way the rest of the code can stay ugly and/or change more often without causing any frustration or anger to developers who used the private API (sleep and coffee deprived developers tend to be the angriest — have a snack handy in your backpack for them in case of an attack). Since, Node/JavaScript is loosely typed. You should put extra effort in documentation than you would normally do when creating classes in other language with strong typing. Good naming is part of documentation. For example, we can use _ to mark a private method: class Auto { constructor({speed}) { this.speed = this._getSpeedKm(0) } _getSpeedKm(miles) { return miles*1.60934 } start(speed) { this.speed = this._getSpeedKm(speed) } } let auto = new Auto({}) auto.start(10) console.log(auto.speed) All the things related to modularizing described in the section on functions apply to classes. The more granular and loosely coupled the code, the better. Okay. This is enough for now. If your mind craves more of this ES6/ES2015 stuff, check out my cheatsheet and blog post. You might wonder, when to use a function and when a class. It’s more of an art than a science. It’s also depends on your background. If you spent 15 years as a Java architect, it’ll be more natural for you to create classes. You can use Flow or TypeScript to add typing. If you are more of a functional Lisp/Clojure/Elixir programmer, then you’ll lean towards functions. Wrap-up That’s was a hell of a long essay but the topic is not trivial at all. Your well being might depend on it, i.e., how much maintenance the code will require. Assume that all the code is written to be changed. Separate things which change more often (private) from other things. Expose only interfaces (public) and make them robust to changes as much as possible. Lastly, have unit tests. They will serve as documentation and also make your code more robust. You will be able to change the code with more confidence once you have a good test coverage (preferably automated as GitHub+CI, e.g. CircleCI or Travis). And keep on Nodding! — Azat Mardan To contact Azat, the main author of this blog, submit the contact form. Also, make sure to enroll in amazing online courses for FREE at Node University (). Simple. Easy. No commitment.
https://medium.com/software-engineering/beautiful-node-apis-eaf0b636cbe
CC-MAIN-2017-34
refinedweb
2,877
65.22
React as a Static Site Generator Two years ago I converted my website from WordPress to a static build process. It has served me well but the final process was rather messy. Hacks and plumbing to get Metalsmith plugins working my way didn’t helped. Time for a new project! Abstract: rebuild my website using React as the template engine for a bespoke static site generator. Learn more Node and ES6 along the way. Rationale: because I can. Result: If you’re reading this I have succeeded. Why React? In January I wrapped up a long contract to build a React/Redux web app. I found React to be an intuitive solution to manage UI. React fits nicely with the modular thinking I apply when coding HTML & CSS. I’m aware of existing static site generators that use React. I decided to roll my own for the fun of it. Writing the React Components I got off to a false start. Last year’s redesign project was a bit rushed in development and I wanted to fix some issues. It was a mistake to attempt to refactor HTML & CSS whilst translating everything into JSX. I got lost in a refactoring tunnel. Restart. Step one: write components with existing markup. Step two: improve modularity once my site is rendering (still to do as of writing this). All my React components are functional/stateless. There is no logic to them because I’m don’t plan to render client-side. I don’t need to worry about an API serving data to the browser. My build script parse data and pass it along to React properties once to render HTML. Some components — e.g. the Bio[graphy] — load default props from a JSON file. Lazier components have data hardcoded in the HTML (Newletter for example). When I get time I’ll do a proper job abstracting these. It’s not an urgent task because I doubt I’ll ever need more than one instance. The Blog component is an interesting one. It displays recent posts and appears on all pages. It too loads JSON. I have a task to update this file before rendering (rather than passing new props from the parent). The reason for that is incidental, but it does allow pages to render with up-to-date content without parsing all of the blog data again. I’m storing page content like blog articles as Markdown with YML front matter. A result of exporting WordPress to a format Metalsmith liked. This has proven good enough and I see no reason to change. An improvement I’ve made is to render syntax highlighting rather than doing it in the browser. I’m using Marked and Prism for that. Components receive HTML content as a property and use the aptly named dangerouslySetInnerHTML. marked.setOptions({ smartypants: true, langPrefix: 'language-', highlight: (code, lang) => Prism.highlight(code, Prism.languages[lang]) }); /** * Reduced example from a React component. The `html` prop has been * passed through Marked with Prism. */ render() { const html = () => { return {__html: props.html}; }; return ( <div className="post" dangerouslySetInnerHTML={html()}/> ); } This seems like an acceptable solution. I see no reason to convert the inner content to React elements only to render back to HTML immediately. I render everything inside the body tag with React. I’m using Handlebars to glue together the final page. This allows me to inline CSS with header/footer partials. It’s simpler and less fussy about formatting. For the same reason I’m also using Handlebars to build my RSS and Sitemap XML files. This avoid any workarounds for namespaced attributes. Hello GitHub Pages I’ve been hosting personal websites on a VPS for a long time. The VPS was useful, if not a bit overkill, for WordPress hosting. I first bought it to experiment with Node services, NGINX, and Varnish caching. More recently — in fact for almost two years now — it was doing nothing but hosting static files. Time to be frugal. Why pay VPS prices when GitHub Pages is free? For convenience my website exists within two repositories. The source code and the static build. I have the latter repo cloned as a directory within the former (but ignored by Git). This way when I run my build task the static build repo is the destination. In regards to performance, GitHub Pages does a decent job. There’s some caching and CDN stuff I need to sort out at some point. Up Next Now that I’ve rebuilt my website from stratch and it’s indistinguishable from itself prior to doing this work, I plan to: - Refactor modularity and trim down CSS - Consider going isomorphic/universal (unlikely) - Return to my regular blogging schedule By the way, if you’re reviewing my build scripts and thinking “what in the world…” — you’re not alone! I’ve had some fun for the sake learning new JavaScript features (async/await in particular). Just know that this is not code I’d deliver to a client! More from me… Read more on my blog and follow @dbushell. If you like what I do:
https://dbushell.com/2017/02/13/react-as-a-static-site-generator/
CC-MAIN-2020-05
refinedweb
850
67.86
Issue Using OpenCV 4 Windows Build, VS 2017 - Unhandled Exception with imshow() Hello everyone, I'm running into a big problem just trying to setup OpenCV again in my IDE with the latest version for Windows. I've done this before in earlier versions successfully, but I'm stumped this time around. I extracted the files from the downloaded .exe, added the paths to my environmental variables and setup my properties sheet properly for debug x64. However, when I implement this simple test script to see if everything is connected correctly: #include "opencv2/opencv.hpp" using namespace std; using namespace cv; int main() { Mat A; A = Mat::zeros(100, 100, CV_32F); imshow("x", A); //waitKey(0); return 0; } program halts on the imshow() line and my Call Stack reports: The ellipses are because I don't think I need to write out all the functions parameters.The ellipses are because I don't think I need to write out all the functions parameters. KernelBase.dll!... vcruntime140d.dll!... opencv_world400d.dll!cv::Error(... opencv_world400d.dll!cvShowImage(... opencv_world400d.dll!cvimshow(... And I have tried unpacking the libraries again. Thank you! Followup Info: I just built my own version from the source using CMake, and I am still getting the same issue, where KernelBase.dll is the farthest I get on the Call Stack before everything falls apart.
https://answers.opencv.org/question/204449/issue-using-opencv-4-windows-build-vs-2017-unhandled-exception-with-imshow/
CC-MAIN-2019-35
refinedweb
224
59.43
This notebook was put together by [Jake Vanderplas]() for PyCon 2015. Source and license info is on [GitHub](). Here we'll explore Gaussian Mixture Models, which is an unsupervised clustering & density estimation technique. We'll start with our standard set of initial imports %matplotlib inline import numpy as np import matplotlib.pyplot as plt from scipy import stats # use seaborn plotting defaults import seaborn as sns; sns.set() We previously saw an example of K-Means, which is a clustering algorithm which is most often fit using an expectation-maximization approach. Here we'll consider an extension to this which is suitable for both clustering and density estimation. For example, imagine we have some one-dimensional data in a particular distribution: np.random.seed(2) x = np.concatenate([np.random.normal(0, 2, 2000), np.random.normal(5, 5, 2000), np.random.normal(3, 0.5, 600)]) plt.hist(x, 80, normed=True) plt.xlim(-10, 20); Gaussian mixture models will allow us to approximate this density: from sklearn.mixture import GMM clf = GMM(4, n_iter=500, random_state=3).fit(x) xpdf = np.linspace(-10, 20, 1000) density = np.exp(clf.score(xpdf)) plt.hist(x, 80, normed=True, alpha=0.5) plt.plot(xpdf, density, '-r') plt.xlim(-10, 20); Note that this density is fit using a mixture of Gaussians, which we can examine by looking at the means_, covars_, and weights_ attributes: clf.means_ array([[ 4.5601338 ], [ 0.0861325 ], [ 3.01890623], [ 6.87627234]]) clf.covars_ array([[ 30.34748627], [ 4.30521863], [ 0.19750802], [ 14.78230876]]) clf.weights_ array([ 0.27613209, 0.48308463, 0.11612442, 0.12465886]) plt.hist(x, 80, normed=True, alpha=0.3) plt.plot(xpdf, density, '-r') for i in range(clf.n_components): pdf = clf.weights_[i] * stats.norm(clf.means_[i, 0], np.sqrt(clf.covars_[i, 0])).pdf(xpdf) plt.fill(xpdf, pdf, facecolor='gray', edgecolor='none', alpha=0.3) plt.xlim(-10, 20); These individual Gaussian distributions are fit using an expectation-maximization method, much as in K means, except that rather than explicit cluster assignment, the posterior probability is used to compute the weighted mean and covariance. Somewhat surprisingly, this algorithm provably converges to the optimum (though the optimum is not necessarily global). print(clf.bic(x)) print(clf.aic(x)) 25696.4735953 25625.7016679 Let's take a look at these as a function of the number of gaussians: n_estimators = np.arange(1, 10) clfs = [GMM(n, n_iter=1000).fit(x) for n in n_estimators] bics = [clf.bic(x) for clf in clfs] aics = [clf.aic(x) for clf in clfs] plt.plot(n_estimators, bics, label='BIC') plt.plot(n_estimators, aics, label='AIC') plt.legend(); It appears that for both the AIC and BIC, 4 components is preferred. GMM is what's known as a Generative Model: it's a probabilistic model from which a dataset can be generated. One thing that generative models can be useful for is outlier detection: we can simply evaluate the likelihood of each point under the generative model; the points with a suitably low likelihood (where "suitable" is up to your own bias/variance preference) can be labeld outliers. Let's take a look at this by defining a new dataset with some outliers: np.random.seed(0) # Add 20 outliers true_outliers = np.sort(np.random.randint(0, len(x), 20)) y = x.copy() y[true_outliers] += 50 * np.random.randn(20) clf = GMM(4, n_iter=500, random_state=0).fit(y) xpdf = np.linspace(-10, 20, 1000) density_noise = np.exp(clf.score(xpdf)) plt.hist(y, 80, normed=True, alpha=0.5) plt.plot(xpdf, density_noise, '-r') #plt.xlim(-10, 20); Now let's evaluate the log-likelihood of each point under the model, and plot these as a function of y: log_likelihood = clf.score_samples(y)[0] plt.plot(y, log_likelihood, '.k'); detected_outliers = np.where(log_likelihood < -9)[0] print("true outliers:") print(true_outliers) print("\ndetected outliers:") print(detected_outliers) true outliers: [ 99 537 705 1033 1653 1701 1871 2046 2135 2163 2222 2496 2599 2607 2732 2893 2897 3264 3468 4373] detected outliers: [ 537 705 1653 2046 2135 2163 2496 2732 2893 2897 3067 3468 4373] The algorithm misses a few of these points, which is to be expected (some of the "outliers" actually land in the middle of the distribution!) Here are the outliers that were missed: set(true_outliers) - set(detected_outliers) {99, 1033, 1701, 1871, 2222, 2599, 2607, 3264} And here are the non-outliers which were spuriously labeled outliers: set(detected_outliers) - set(true_outliers) {3067} Finally, we should note that although all of the above is done in one dimension, GMM does generalize to multiple dimensions, as we'll see in the breakout session. The other main density estimator that you might find useful is Kernel Density Estimation, which is available via sklearn.neighbors.KernelDensity. In some ways, this can be thought of as a generalization of GMM where there is a gaussian placed at the location of every training point! from sklearn.neighbors import KernelDensity kde = KernelDensity(0.15).fit(x[:, None]) density_kde = np.exp(kde.score_samples(xpdf[:, None])) plt.hist(x, 80, normed=True, alpha=0.5) plt.plot(xpdf, density, '-b', label='GMM') plt.plot(xpdf, density_kde, '-r', label='KDE') plt.xlim(-10, 20) plt.legend(); All of these density estimators can be viewed as Generative models of the data: that is, that is, the model tells us how more data can be created which fits the model.
https://nbviewer.ipython.org/github/jakevdp/sklearn_pycon2015/blob/master/notebooks/04.3-Density-GMM.ipynb
CC-MAIN-2022-33
refinedweb
906
51.65
Incrementing numeric indices happens maybe 1_000 or even 1_000_000 times more often than incrementing strings. So for integers this operator has to be short. But the effort to learn and maintain string_increment with a core operator like ++ is far less economic. For that reason I agree that strinc() (or whatever notation suits the most) would pollute the namespace like in PHP, so it should be outsourced to a pragma or module. The inverse approach would be the 'no feature qwinc' I proposed, forcing ++ to croak on strings and allowing full backwards compatibility. Furthermore allowing optimizations within Perl and less headaches and far more performance when translating to other VMs. Cheers Rolf In reply to Re^4: getting rid of special features by LanX in thread getting rid of costly special features by LanX Perl Cookbook How to Cook Everything The Anarchist Cookbook Creative Accounting Exposed To Serve Man Cooking for Geeks Star Trek Cooking Manual Manifold Destiny Other Results (146 votes), past polls
http://www.perlmonks.org/?parent=1019202;node_id=3333
CC-MAIN-2014-41
refinedweb
163
56.49
error Accessing Database using EJB Accessing Database using EJB This is a simple EJB Application that access the database. Just go through the EJB example given below to find out the steps involved in accessing Jaa - JSP-Servlet Jaa How to access data from the database using JSP program Hi Friend, Please visit the following links: code delete data from database using jsp jsp jsp how to write hindi in jsp and store in database as unicode JSP language , it is a simple language for accessing data, it makes it possible to easily access application data stored in JavaBeans components. The jsp expression...). Before JSP 2.0, we could use only a scriptlet, JSP expression, or a custom! program - JSP-Servlet for more information. hi friends... i hv faced a problem of jsp code.my problem... to concated with a textbox that is selected from database. my database is postgresql.i jst connec to database - JSP-Servlet connec to database Need code to connect the application to database. I have developed the application JSP and Servlet JSP JSP i need coding for auto text and auto complete of my database for my JSP with out using plugin if any one know answer if any one know's coding for it give me some suggestion database database how to search data from database using jsp & how... the following links: entered name and password is valid HII Im developing a login page using jsp and eclipse,there are two fields username and password,I want... check that from database,plz help me..... Plz send me the codes. Im new database links: Connect JSP with database Mysql Connect Java with database Mysql...database tell me use about database and give me a small program. It is secure and can easily be accessed, managed, and updated. Moreover connection with database - JSP-Servlet and the connection with the database using jsp code, I get exceptions that I have... with java code. Is there any other way to establish a connection with database in jsp... with the database by writing the program in java. Following is the code: import Jsp Code to store date in database - JSP-Servlet Jsp Code to store date in database Hi, Can u give me jsp code to store current date in to database. Thanks Prakash: JSP Database Example This example shows you how to develop JSP that connects to the database and retrieves the data from database. The retrieved data is displayed on the browser. Read Example JSP Database Example Thanks jsp ;" import = "java.io.*" errorPage = "" %> <jsp:useBean id = "formHandler... = "java.io.*" errorPage = "" %> <jsp:useBean id = "formHandler" class... the database field names here String effectivedate = request.getParameter jsp with database.. - Development process jsp with database.. Hello i need code for..... I have a car... of that brand should be retrieved from database.i have created a table in database... Thanks For the above code, create database table named JSP in listview or in gridview within JSP? Hi Friend, Try...;Pagination of JSP page</h3> <body> <form> <input type="hidden...(); } %> In the above code,we have taken the database table student(rollNo,name line chart from database in jsp line chart from database in jsp how can i create line chart from database in jsp code JSP and Database access JSP and Database access Hi, Please help me with the following program. I am not able to update all the pa column values in my database. csea.jsp: <html> <body> <%@page import="java.sql.*"%> <form jsp jsp retrieve the values from the database which you have entered through the form and display 1)form.jsp: <html> <form method...+"')"); out.println("Data is successfully inserted into database jsp jsp ques: how to insert data into database using mysql //index.jsp <%-- Document : index Created on : May 20, 2013, 1:20:04 PM Author : ignite178 --%> <%@page contentType="text/html Accessing Database using EJB .style1 { color: #000000; } Accessing Database...; This is a simple EJB Application that access the database. Just go through the EJB example given below to find out the steps involved in accessing Database. Creating To insert attachment file in database in JSP. To insert attachment file in database in JSP. I am doing project in JSP. How to insert attachment file in mysql database? Please suggest some solution. Your inputs is valuable to me. Hi Friend, Visit Here Thanks Java JSP - JDBC Java JSP JDBC connectivity in JSP? Hi Friend, Please visit the following link: Hope that it will be helpful for you. Thanks posted to a JSP file from HTML file | Accessing database from JSP | Implement... in JSP Code | Connect JSP with mysql | Create a Table in Mysql database... mysql database through jsp | How To Page Refresh Using JavaScript  Problem in Jsp and database - Development process Problem in Jsp and database Hi, How can I reterive values from database and display them in teextboxes so that when the user select the UPDATE... to the database itself . Thanks in advance. Hi Friend, You can use JSP to Excel - JSP-Servlet JSP to Excel Need an example of JSP and Excel database connection. Thanks How to show database values into graph using jsp? How to show database values into graph using jsp? How to show database values into graph using jsp Draw graph using jsp without database connection Draw graph using jsp without database connection Draw graph using jsp code without database connection search functionality using jsp from database search functionality using jsp from database search functionality using jsp from database code for insert the value from jsp to access database code for insert the value from jsp to access database code for insert the value from jsp to access database Static database class - JSP-Servlet Static database class I want to create a static database class and i want to use that class in all servlets ? How can i achive how to display data from database in jsp how to display data from database in jsp how to display data from database in jsp connecting JSP Getting Started, Getting Started With JSP related tutorials: JSP Architecture JSP Actions Accessing database from...Getting Started with JSP This page is all about getting started with JSP language. Java Server Pages or JSP for short is Sun specification for developing To insert attachment file in database in JSP. To insert attachment file in database in JSP. I am doing project in JSP. How to insert attachment file in mysql database? Please suggest some solution. Your inputs is valuable to me. Hi Friend, Try the following edit database using jsp and servlet edit database using jsp and servlet I am creating a website using jsp and servlets that is used to view houses from a database. I want to be able... information from the database in the textboxes. Please help me to display JSP-Mysql - JSP-Servlet JSP-Mysql Hello friends, Anyone send me the way how to store image in mysql database from a jsp page. Hi friend, Code to insert image in mysql Using Jsp : For more information on JSP
http://roseindia.net/tutorialhelp/comment/91082
CC-MAIN-2014-41
refinedweb
1,176
65.01
Archived GeneralDiscussion. Zwiki 0.30 released --Simon Michael, Mon, 03 May 2004 23:08:00 -0700 reply Summary: Page rating, fix epoz support, bugfixes, code cleanups, i18n work, a french translation Best, -Simon editing menu -- Wed, 05 May 2004 12:17:04 -0700 reply Does anybody know, where I can change the menu titles or names like "wiki changes", "wiki contents" or "serch this wiki". Are the hardcoded or defined in any external file? editing menu --SimonMichael, Wed, 05 May 2004 14:07:16 -0700 reply They are in the wikipage_macros and possibly wikipage page templates. The skin customizing docs should help. How does one lock a page ? -- Sat, 01 May 2004 14:57:26 -0700 reply Allowing anyone to comment (say at the end of each paragraph or bottom of the page) but no content editing by anonymous users. note Comment moved from LinkingNotes? How does one lock a page ? --DeanGoodmanson, Thu, 06 May 2004 15:03:42 -0700 reply See ZWiki:QuickReference#5 site downtime --simon, Fri, 07 May 2004 20:06:47 -0700 reply None of these strange site hangs for a week. Touch wood.. you could not make this stuff up :) --simon, Fri, 07 May 2004 22:15:32 -0700 reply Happy weekend you could not make this stuff up :) --simon, Fri, 07 May 2004 22:38:53 -0700 reply braaaaaains! editing menu -- Mon, 10 May 2004 04:20:29 -0700 reply Thanks for your answer, but I still couldn't find them. editing menu -- Mon, 10 May 2004 04:26:53 -0700 reply To explain my problem I have some code here: <h5 class="hiddenStructure">Aktionen</h5> <ul class="actionItems"> <li id="contentaction-contents"> <a class="" href="" accesskey="accesskeys-Wiki contents"> Wiki contents </a> </li> My question is: Where comes this "Wiki contents" from? happy weekend --simon, Fri, 14 May 2004 13:09:28 -0700 reply Today's quote is worth a read ! Re: Stopping users from editing same page and overwriting each others changes --Bob McElrath?, Wed, 19 May 2004 19:21:24 -0700 reply Andy Hird [andyh@ekit-inc.com]? wrote: Hi there, Apologies if this is a FAQ but I didn't see it in the howtos or FAQ documentation. =20 I'm hosting severally frequently used pages (website changelogs) with a Zwiki page and have hit the situation where there may be several users editing the same page at the same time and then the later one who clicks save overwrites overwrites the earlier saved information. =20 i.e. they both click on edit for the same revision of some page and then one clicks save, their changes are saved, and then at some later time another user hits save, and overwrites the previous saved changes. =20 Is there some way of stopping this from happening? Ideally some zwiki option I guess which stops the later user from saving their changes until they've merged previous saved changes (or more simply edited their changes into the later saved page). =20 If not, I'm quite happy to implement it as some sort of option - would there be interest in merging the change.=20 I've noticed this too. I think it occurs when a save comes in while ZWiki is pre-rendering. Andy: this should not happen already...it is a bug. Re: Stopping users from editing same page and overwriting each others changes --simon, Thu, 20 May 2004 07:22:10 -0700 reply This should not be possible, unless you have a strange customized editform template. Let me know if you can reproduce it. Re: Stopping users from editing same page and overwriting each others changes --DeanG, Thu, 20 May 2004 07:25:00 -0700 reply I learned something about IP's yesterday that may support this scenario. Everyone from my company is seen as from the same IP (through the firewall), so if two of use are editing the same (external) wiki page, a conflict might not be triggered, as (last I knew) the conflict checker checks for different IP's. Re: Stopping users from editing same page and overwriting each others changes --Simon Michael, Thu, 20 May 2004 13:38:56 -0700 reply Oh good point. Check out this docstring: def checkEditConflict(self, timeStamp, REQUEST): """ Warn if this edit would be in conflict with another. Edit conflict checking based on timestamps - things to consider: what if - we are behind a proxy so all ip's are the same ? - several people use the same cookie-based username ? - people use the same cookie-name as an existing member name ? - no-one is using usernames ? strategies: 0. no conflict checking 1. strict - require a matching timestamp. Safest but obstructs a user trying to backtrack & re-edit. This was the behaviour of early zwiki versions. 2. semi-careful - record username & ip address with the timestamp, require a matching timestamp or matching non-anonymous username and ip. There will be no conflict checking amongst users with the same username (authenticated or cookie) connecting via proxy. Anonymous users will experience strict checking until they configure a username. 3. relaxed - require a matching timestamp or a matching, possibly anonymous, username and ip. There will be no conflict checking amongst anonymous users connecting via proxy. This is the current behaviour. Re: Stopping users from editing same page and overwriting each others changes --Nate Johnson, Fri, 21 May 2004 08:53:09 -0700 reply I mentioned this issue a while ago. Sorry I did not have the time to investigate it further at the time. I tested it with three different users on the telephone, several times (all on the same intranet) and there did not appear to be any conflict resolution or warnings at all. -Nate PS I also want to request a feature: I would love to have an automated to-do list. For instance, when editing a Zwiki page, I want to enclose a note to myself as an HTML anchor named "to-do-Finish Explaining This Point-to-do" and have the system insert that note on a "to-do" page with a link to that exact spot on the page I was editing. Then I (or others that want to help) can later work through the to-do list, reading the anchor's text and linking directly to that spot, ideally pulling up the page in the editform and putting the cursor right at the anchor. If the editor then removes the anchor, the to-do list should show the item as completed, but still keep record of it (the page, who did it and when). This should help a lot with page maintenance. Is there any limit to the length of the the name of an anchor? This functionality could also make it possible to keep track of a single users contributions, inserting links to all their edits on a "user edits" page, kind of like whynot.net does for each user, see my page at for example. what do you think? nate nate@betterdifferent.com StudlyCaps? -- Tue, 25 May 2004 13:21:11 -0700 reply How do I turn off zwiki from rendering StudlyCaps? as links in a plone install? This is my biggest gripes with zwiki at the moment. There is little control for the admin to select what gets rendered as links. StudlyCaps? are seems rather silly as a means to render links. For example, if my name is McElroy?, zwiki immidiately thinks it is supposed to be a page. What would be really cool is to have zwiki use the plone ControlPanel? to let admins select how the zwiki operates, select WikiWiki markup, StructuredText, reStructuredText, HMTL, StudlyCaps?, or any combination thereof. Hope this doesn't sound to negative, zwiki is otherwise an awesome product and I'm really glad I found it. //\//\ P.S. Would there be any way to use workflows with zwik? This would be a really cool feature as I could run a script to check spellings, mail me a notice upon new entry etc. Anyhow just a tought and not critical. Adding images -- Tue, 25 May 2004 13:32:12 -0700 reply I couldn't find any documentation in the how-tos. But is there a way to add an image in the wiki? Thank You, Laura StudlyCaps? --Simon Michael, Tue, 25 May 2004 13:46:23 -0700 reply Gripe, gripe, gripe. :) Check out the use_*_links properties at . One reason these are not in Plone setup is that they are a per-wiki option. I encourage someone to start work on a control panel for them. Adding images --Simon Michael, Tue, 25 May 2004 13:50:30 -0700 reply I couldn't find any documentation in the how-tos. But is there a way to add an image in the wiki? If you have file upload permission (see QuickReference) you will see a file/image upload field in the editform. There's also? Perhaps you could add something under . release candidate coming --simon, Tue, 25 May 2004 16:00:17 -0700 reply It's on the way.. sorry all, I am little sluggish after a couple of late hack-a-thons. Re: Subclassing/extending ZWikiPage --Bob McElrath?, Tue, 25 May 2004 16:41:15 -0700 reply Edoardo ''Dado'' Marcora [marcora@caltech.edu]? wrote: Has anybody been successfull in extending ZWikiPage by subclassing it? What are you trying to do? LatexWiki subclasses the PageType?'s to accomplish stuff. I'm not sure why you would want to subclass ZWikiPage. Re: Subclassing/extending ZWikiPage --Bob McElrath?, Tue, 25 May 2004 17:31:45 -0700 reply Edoardo ''Dado'' Marcora [marcora@caltech.edu]? wrote: I would like to have my ZWikiPage have additional properties and methods.==2E. for example, I would like to have an object w/ ZWikiPage behavior/integration into ZWiki that would represent a Journal Article, w=ith fields like Authors, Journal, Date of Publication, etc. + methods to retrieve the bibliographic information from online databases (e.g., PubMe?=d). =20 I already such an object has a plain Zope Product, but I would like it to=be integrated into ZWiki and behave like a ZWiki page. This does sound like a PageType? subclass rather than ZWikiPage. Take a look at LatexWiki for an example of an external product that does exactly this. I also want to integrate methods to deal with proper journal references. (for me, mostly arxiv.org and spires) Would you be willing to share your code? It would be much better to create some kind of generic "bibliography" module that will extend the ZWiki citation mechanism, rather than create several for different subject specialties. See my TODO, search for "Auto-referencifier". Also see the citations at the bottom of that page for an idea of how those should look. Adding images --Nate Johnson, Tue, 25 May 2004 18:34:34 -0700 reply The best way to set this up for your users is to use an all-HTML wiki, and install Epoz so that you can use Epoz's Insert Image tool(icon). However, the Insert Image Tool asks for the URL of the image and does not allow uploading from the user's computer. The user still needs to upload the file and know how the link to it (the URL). It would be awesome if between Epoz and Zwiki we could make the "post a photo" process more straight forward for all-HTML Epoz Zwiki's. What I want is an improved Insert Image Tool so that you can browse the local file system, the Zwiki filesystem (starting in the folder that contains the page you are editing), OR type in the URL... All in the same box that pops up when a user clicks the "insert image" tool. While I am on the wish list, I would like to incorporate smart file resizing, so Joe Dumb User who just got his digital camera doesn't accidentally but a 3 meg photo on my page. It would be nice as the moderator to set some standard sizes for thumbnails and a maximum size (eg 1024x768) and file-size (eg 400K) per upload. Then when the user selects "insert image" they have to pick a thumbnail size. Then the server automatically makes and displays the thumbnail (e.g. imagefilename-thumbnail) and links it directly to the full size photo just uploaded. A small text link below says (eg) "click for full size." Now if I can just find some money I can help out with the development. Nate ps the site I am building with Zwiki / Epoz : --- Simon Michael <zwiki-wiki@zwiki.org> wrote: couldn't find any documentation in thehow-tos. But is there a way to add an image in the wiki? If you have file upload permission (see QuickReference) you will see a file/image upload field in the editform. There's also Perhaps you could add something under . -- forwarded from ===== - solving the world's problems (and your's) through innovative application of communications technology 0.31rc1 released --simon, Tue, 25 May 2004 21:10:14 -0700 reply Bah, depressingly short change list considering the work involved..! Please hammer on it :) subpage(s) -- Wed, 26 May 2004 07:51:03 -0700 reply Hi, for my wiki I need to have a page with the same title e.g. "Introduction", but different content, several times. Currently I made subdirectories in Zope and link to them, but "show_navlinks" does not work with this solution. Any other solution possible ? Thanks Sigbert 0.31rc2 released --simon, Wed, 26 May 2004 13:05:26 -0700 reply After some moaning, I merged the latest (great) i18n patches and tackled a number of issues brought to light, Among other things, this should work better when PTS is not installed. - updated zh-TW.po and new zh-CN.po (T.C. Chou) - updated, utf-8 fr.po (Foenyx) - more standard skin i18n (Foenyx) - python i18n (Foenyx) - prevent dtml-translate tag errors when PTS is not installed - work around i18n unit test issues subpage(s) --SimonMichael, Thu, 27 May 2004 08:35:37 -0700 reply Hi.. it sounds like a job for two wikis here. Really by definition, one wiki page has one name - that's part of what makes it work. Re: DTML page to ZWiki Input? --Simon Michael, Thu, 27 May 2004 09:54:51 -0700 reply Hi Scott.. first a note on mail issues: I'm citing your entire post (and cc'ing you) since I'm not sure if you're subscribed to the list or wiki. I think that's why it didn't show up on the wiki, or perhaps it's because of the unquoted DTML you included generating an error. List and wiki posting in general is a bit confusing right now and needs some attention. I dig your old-school DTML tags! :) To post something directly to a wiki page, look at the comment or edit methods in Editing.py or here: Something like: <dtml-call "StaffPage.comment( text='Name:%s\nEmail:%s\n etc..' % (username,useremail), subject_heading='registration', REQUEST=REQUEST)"> should do it. Any subscribers to StaffPage? will receive mail, etc. Passing REQUEST is generally a good idea, it passes on the current user's authentication. In this case you may not want users to have permission to comment on StaffPage?, then you'll need to (eg) move this call into a separate python script or dtml method which you can grant a proxy role. S.D. wrote: A long time ago, I asked about piping the output from a DTML registration page into ZWiki. The sequence of events is as follows: - A user visits our site to download (free) software. 2. The site sends the user to a registration page. 3. The user enters their registration information and clicks OK. 4a. The user is transported to the download page from which he or she gleefully grabs software. 4b. The user's registration information is sent to a ZWiki page (in Plone) where we use it for customer relations purposes. In Plone 1, I set up two DTML pages: One displays the registration form and the other is the post-registration page that contains the download links. The second page also emails the registration info to our feedback address, where it can be managed in the email client. Here's the email-sending DTML from the second page:: ----- < dtml-var standard_html_header> < h2>< dtml-var title_or_id>< /h2> < !--#sendmail mailhost="MailHost"--> To: Feedback Recipient < me@some.edu> From: Zope Feedback Form < me@some.edu> Subject: [Download]? Registration Information Institution Name: < !--#var institutionname--> Name: < !--#var username--> Country: < !--#var country--> Type(s): < !--#var type--> < p>Thank you for your input, < !--#var username-->!< /p> < dtml-var standard_html_footer> ----- Since all of this activity is contained inside a single Plone instance, I don't need to use email. All I want to do is set up a direct connection between my DTML page and ZWiki. What is the best way to pipe this kind of info into ZWiki 0.30 inside Zope 2.7 and Plone 2.0.3? All suggestions will be very welcome! Thanks! Scott Re: DTML page to ZWiki Input? --simon, Thu, 27 May 2004 09:58:48 -0700 reply Or, you could just give the first wiki page (a read-only registration form, if I understand correctly) the proxy role. zwiki.org templates updated --simon, Thu, 27 May 2004 12:34:12 -0700 reply We did not have the latest i18n templates here (I keep copies in the zodb for customization). Now you can see the latest i18n work, french is currently the most complete. Er, and some glitches. RecentChanges? ? --DeanG, Thu, 27 May 2004 12:39:29 -0700 reply RecentChanges? is prompting me for login. RecentChanges? ? --SimonMichael, Thu, 27 May 2004 18:07:29 -0700 reply Thanks! Some bad permissions that were never initialized in the past. There may be more of these lurking. Re: DTML page to ZWiki Input? --Simon Michael, Thu, 27 May 2004 18:30:08 -0700 reply S.D. wrote: Simon says:Or, you could just give the first wiki page (a read-only registration form, if I understand correctly) the proxy role. That would be the slickest solution: The Registration/Download area would simply be a ZWiki whose default page snagged the pertinent visitor info (name, email address, institution name, comments) and sent that info on, as a comment, to another wiki page that only administrators could see. Well, not quite that simply because clicking OK on the initial registration page would, from the visitor's perspective, then move on to the (static) download page that contained the links to our software. As far as proxies go, I don't quite understand the proxy Help page you get in the ZMI. ----- "Proxy roles explicitly list the roles that a DTML Document or Method will execute with. This allows you to carefully control access. Proxy roles can either increase or decrease access." ----- Since we're talking about allowing anonymous users to see the registration page, I assume that means the page should be assigned the "Anonymous" proxy role. Or is that the opposite of what should be done? Will assigning the "Anonymous" role to a publicly viewable page give anonymous visitors Manager-level permissions? Just now, I tried your first suggestion, sticking the following in a DTML Document page inside a "Registration" Plone folder. ----- <? I apologize for the dumb questions, but I am still trying to get a handle on various objects find one another inside Zope. Thanks! Scott 0.31rc3 released --simon, Fri, 28 May 2004 10:52:09 -0700 reply Zwiki 0.31rc3 ReleaseNotes: - update pot and po files - minor additional i18n, pluralize number of subscribers correctly (foenyx@online.fr) - FrenchGrammarAndVocabularyFix1? (foenyx@online.fr) - fix a UI regression (simpler replying indicator) - fix some permissions preventing anonymous recent changes access - fix stx asterisks in add issue form (IssueNo0826?) - drop the page name from the subscribe to page button to simplify i18n - Important fixes to italian subscription messages (Lele Gaifax) - don't show a .svn subdirectory in add wiki form (Lele Gaifax) - undo page management form layout tweaks (IssueNo0827?) - fr.po: fix number of subscribers translation - chinese translations update (T.C. Chou) - Italian messages update (Lele Gaifax) - fix rating button spacing - remove CMF dependency (IssueNo0824?) Re: DTML page to ZWiki Input? --Simon Michael, Fri, 28 May 2004 15:46:42 -0700 reply S.D. wrote: Simon suggested:(snip) I'm sorry for being so dense, but what is the best way to send this to a ZWiki? I've been looking at DTML, ZPT, and Archetypes examples all day today and I am rather lost on what to use and how to use it. Documentation is rather hit and miss for this stuff. Is there an example of an input page that you know of? It would be neat (I think) if I could use Archetypes to set up the input form. Is there a good Archetypes starting point you could suggest? Or is Archetypes overkill for my simple scenario? Hi Scott.. I was just about to read your last. Tip: your messages keep getting rejected by the wiki because of the dtml examples. Every page on zwiki.org including GeneralDiscussion is a live dtml page. Your example snippets don't run so the whole mail-in gets rejected. You need to quote dtml examples like this: <dtml-var > indented after a double : or like this: < dtml-var> with a space after each left angle bracket. Re: DTML page to ZWiki Input? --Simon Michael, Fri, 28 May 2004 16:04:39 -0700 reply Scott, Well, not quite that simply because clicking OK on the initial registration page would, from the visitor's perspective, then move on to the (static) download page that contained the links to our software. That's up to you. Use the form tag's action field to say where it should go next. A pattern I often use is to put the form and the form handler (in dtml) on the same page. is an old example. If it were me, and I was already using wiki pages, that's what I'd do here. You don't need more than two pages. RegistrationForm? - executes some dtml, looking for submitted form data. If there is none, displays the form (which posts to itself). If there is data, use the dtml-call I posted to add it to the StaffPage?, and display a thank you message. This page is public, viewable by anonymous but read-only. It has the manager proxy role (eg), which means that when it runs dtml it will have manager privileges. This is so it can add data to the private StaffPage?. StaffPage? - this page is private, perhaps in another folder. It can be viewed by managers and receives data from RegistrationForm?. <? (note the space neutralising the dtml above) Is Wikipage01 in the same folder or in a parent folder ? If yes, this should work (using acquisition). Otherwise you'd need to give the folder path. is Archetypes overkill for my simple scenario? Yes, I think so. Like perl, in zope there's many ways to do this. If you're comfortable with dtml wiki pages that is the simplest IMHO. server upgrade, downtime --simon, Sat, 29 May 2004 07:31:51 -0700 reply The server was rebooted and zope/apache failed to come up automatically. This has been fixed. 0.31rc4 released --simon, Sat, 29 May 2004 13:38:11 -0700 reply Zwiki 0.31.0rc4 ReleaseNotes: - always update backlinks by default when renaming (page management form was not) - show current page in contents by default again This is much more convenient for a human user. The drawback is more hits to contents (one for each page) from robots which treat #ref as a separate url. - defaultPage (and navigation links) were ignoring the default_page folder property - issue tracker: show recent issues by default again - standard wikipage.pt: add a left/right layout table around ratingform - issuepropertiesform: replace stx markup with html - FrenchGrammarAndVocabularyFix2? (foenyx@online.fr) - add dtml messages to pot & po files - plone editform: don't attempt to translate page names, showing duplicates instead (IssueNo0823?)
https://zwiki.org/FrontPage/UserDiscussion200405
CC-MAIN-2021-25
refinedweb
4,019
73.37
React basic 4 — Class Based Component and Lifecycle Methods In contrast to the functional component from the previous post (React basic 3 — Reusable Functional Components), if your component should manage states properly, class component may be the way to go. Class component comes with a built-in lifecycle that allows you to manipulate your component at different phases. This post explains how to create a class-based component by going over the most fundamental, constructor() and render() lifecycle methods first. Create the first class-based component Step 1. Declare class and extend React.Component The structure of class-based component is similar to the functional component. Instead of declaring with const for functional components, we extend React.Component subclass to declare a class. Below is an example of how a simple functional component could be refactored into a class-based component. Functional Component const App = () => { return( <h1>Hello!</h1> );}; Class-based Component class App extends React.Component { render() { return ( <h1>Hello!</h1> ); }}; Step 2. Constructor() and render() lifecycle methods As shown in the example above, we need to call a render() method to display an UI. The render() is one of lifecycle methods, which will be called multiple times when the class's state would change. In contrast, you may use a constructor() method to initialize the class. For example, when you access an external data, you only need to call it once as your class gets initialized, so those callbacks should happen in the constructor(). class App extends React.Component { constructor(props) { super(props); // you need this with props! // Call a function that only needs first } render() { return (<h1>Hello!</h1>); }}; Step 3. State and update state After requesting data from constructor(), it may take some time before the data is available, or the data may get updated while your user is still looking at your page. When the data is available after some time, or gets updated, you may want to reflect those changes to your page. To manage these phases, we use state in React class. State is an object that records users' local states. 1) You can declare a state in constructor() by saying this.state={key:value}, 2) access the state with this.state.key, and 3) update the state with this.setState={key:newValue}. Below example is from the Udemy course, which checks for a user's location in constructor(), but the callback takes time since the user has to permit their browser option. Until the data is available, the page shows the loading state. When the user allows the location access or denies, the React state gets updated with .setState, and render() method runs once again. class App extends React.Component { constructor(props) { super(props); this.state = { lat: null }; window.navigator.geolocation.getCurrentPosition( position => { this.setState ({ lat: position.coords.latitude }); }, err => { this.setState ({ errorMessage: err.message }); } ); } render() { return ( <div> { this.renderContent() } </div> ) } renderContent() { if(this.state.errorMessage && !this.state.lat){ return ( <div> Error: { this.state.errorMessage } </div> ) } if(!this.state.errorMessage && this.state.lat){ return ( <div> Latitude: {this.state.lat} </div> ) } return( <div> Loading … </div> ); } } Lifecycle methods - constructor() - Initializer for declaring variables or states. - componentDidMount() - Called after the component is rendered. The initial request for data may be called in this method instead of constructor(). - render() - REQUIRED method that outputs HTML to the DOM. - componentDidUpdate() - Called after the component is updated in the DOM. componentWillUnmount() — Called when the component is about to be removed from the DOM. Lifecycle of Components | W3School
https://takuma-kakehi.medium.com/react-basic-4-class-based-component-and-lifecycle-methods-1677c44038f4
CC-MAIN-2021-25
refinedweb
578
52.56
Contracts are used when creating drivers to ensure they conform to Masonite requirements. They are a form of interface in other languages where the child class is required to have the minimum number of methods needed for that driver to work. It is a promise to the class that it has the exact methods required. Contracts are designed to follow the "code to an interface and not an implementation" rule. While this rule is followed, all drivers of the same type are swappable. Drivers are designed to easily switch the functionality of a specific feature such as switching from file system storage to Amazon S3 storage without changing any code. Because each driver someone creates can technically have whatever methods they want, this creates a technical challenge of having to change any code that uses a driver that doesn't support a specific method. For example a driver that does not have a store method while other drivers do will throw errors when a developer switches drivers. Contracts ensure that all drivers of a similar type such as upload, queue and mail drivers all contain the same methods. While drivers that inherit from a contract can have more methods than required, they should not. If your driver needs additional methods that can be used that are now inside a contract then your documentation should have that caveat listed in a somewhat obvious manner. This means that by the developer using that new method, they will not be able to switch to other drivers freely without hitting exceptions or having to manually use the methods used by the driver. Therefore it is advisable to not code additional methods on your drivers and just keep to the methods provided by the base class and contract. Contracts are currently used to create drivers and are located in the masonite.contracts namespace. Creating a driver and using a contract looks like: from masonite.contracts import UploadContractclass UploadGoogleDriver(UploadContract):pass Now this class will constantly throw exceptions until it overrides all the required methods in the class. It is useful if you want to "code to an interface and not an implementation." This type of programming paradigm allows your code to be very maintainable because you can simply swap out classes in the container that have the same contract. For example, Masonite has specific manager contracts depending on the type of driver you are trying to resolve. If we are trying to get the manager for the upload drivers, we can resolve that manager via the corresponding upload manager: from masonite.contracts import UploadManagerContractdef show(self, upload: UploadManagerContract):upload.store(..)upload.driver('s3').store(..) Notice this simply returns the specific upload manager used for uploading. Now the upload manager is not a "concrete" implementation but is very swappable. You can load any instance of the the UploadManagerContract in the container and Masonite will fetch it for you. There are several contracts that are required when creating a driver. If you feel like you need to have a new type of driver for a new feature then you should create a contract first and code to a contract instead of an implementation. Below are the types of contracts available. All contracts correspond to their drivers. So an UploadContract is required to create an upload driver.
https://docs.masoniteproject.com/managers-and-drivers/contracts
CC-MAIN-2020-34
refinedweb
549
52.7
Hi, Is there already some code/custom activity to write/append a variable to a (windows)file? Regards, Mark Hey Mark, are you wanting to just append a line to a file on the local machine? If so, you can use a Script activity like below to append a line to a file. You can also create a Custom Script activity with this code if you need to use it in multiple places. import java.io.File;import java.io.FileWriter;File file = new File("c:\\temp\\file.txt");if (!file.exists()) file.createNewFile();FileWriter writer = new FileWriter(file, true);writer.write("new line in file\n");writer.close(); The highlighted items can be replaced with your requirements and/or variables. Regards That works on the local disks, but I have also to write to another server like \\server\share\path\file.ext How can I use apply usercredentials (usr+psw) on such an activity? To do this you'll need to use activities that allow impersonation like ExecuteCommand and ExecuteScript. For instance you could use ExecuteScript with the Batch script type along with an administrator impersonation to pipe text to a file: echo xpath:{...} >> \\server\share\path\file.ext Also you maybe can execute the Script on the remote server directly and not have to pipe it across a share echo xpath:{...} >> c:\path_to_share\path\file.ext
http://sso.forum.commvault.com/forums/thread/53258.aspx
CC-MAIN-2019-22
refinedweb
228
56.76
See also: IRC log zakim list agenda JALLAN: Overall opinions of HTMl5 draft. Simon: I had read it before, followed lots of discussion. JAN: Haven't had a chance to review yet. Jim: bringing up Simon's comments. Simon: I think what we are saying and what others are saying with respect to access keys might be a bit difficult. <scribe> Scribe: KFord Simon's mail on concerns is at Mark: Looking at WAI ARIA. Within the user agent we can identify widgets. <AllanJ> KF: ARIA role mapping to Accessibility API exits <AllanJ> ...if authro doesnot define all behaviors in the script, there is nothing the UA can do. <AllanJ> MH: how does UA repair, or preempt mapping <AllanJ> KF: Keyboard behaviors are a problem with ARIA and developers Henny: Saw some comments on lists that the intent is there to do some ARIA in HTML5 but not much action yet. <AllanJ> HS: discussion on lists for ARIA in HTML5, intent is to include it Jim: Restating Mark's idea of user agent mapping keys to ARIA roles. Kim: How viable is that? Mark: Brings up various technical issues like whgat happens when elements of item are not defined. s/wghat/what <AllanJ> KF: Question: intrigued by Mark's suggestion. Could HTML 5 require that a specific control have x semantics Kim: Are there ways to handle things if a developer leaves something out? Simon: Browsers do handle certain errors today for missing sections of tags and such. Kim: We try to get people to do things with speech in ways that don't use the mouse if possible. ... What works better with speech is not having to find the mouse but rather being able to say I want to put the mouse in location x. <AllanJ> Discussion of Drag-and-drop and accessibility Kim: If you had an absolute pointing tablet this is easier. kford: Gave example of iPhone and touch being absolute. Jim: I was reading in HTML 5 on the drag stuff. ... They kind of talk about user agents without pointing devices and saying the user would need to be able to say what they want to drag. Kim: Talked about Dragon Naturally Speaking approach where you need to indicate drop target first. Jim: One thing we can take to WAI is concerns about keyboard, script, AJAX and such. Isn't necessarily specific to HTML5 but problem continues to grow. Simon: Expressed concern over HTML5 hidden data. <AllanJ> KF: DOM should get updated when mutation event fires <AllanJ> SH: Decision to fire is at UA discretion. Concern is how does UA decide appropriate firing of event, might be different for different device users or AT users Jim: A couple of items I noticed that said they were violations. <AllanJ> These requirements are a willful violation of the XPath 1.0 specification, motivated by desire to have implementations be compatible with legacy content while still supporting the changes that this specification introduces to HTML regarding which namespace is used for HTML elements. [XPATH10] Jim: Talked about xpath. ... I looked at user agent behaviors. ... Whole thing is about how things should interact with the DOM. Most seemed pretty reasonable. ... A couple of issues. ... HTML5 definition of plugin is different from ours. They don't define a method of interacting. This is supposed to be to the user agent or platform. HTML5 definition for plugin. 2.1.4 Plugins The term plugin is used to mean any content handler for Web content types that are either not supported by the user agent natively or that do not expose a DOM, which supports rendering the content as part of the user agent's interface. Jim: Also looked at iframe element and attribute called sandbox. ... Sandbox sets behavior such as allowing the iframe to behave like a full browser. Sandbox definition:-or Kim: User needs to be in control, they get confused when they set things and then they don't work. <AllanJ> ACTION: JAllan to write SC for user override sandbox attribute in Iframe [recorded in] <trackbot> Created ACTION-220 - Write SC for user override sandbox attribute in Iframe [on Jim Allan - due 2009-08-13]. Jim: My other concern is how many other attributes like this are there floating around? How do we generalize this? Kim: If you had a way to alert the user about things that the site wants to override this could help. <AllanJ> KF: UA override, how to define list. <AllanJ> ...lots of things could be included. <AllanJ> ...pop-ups as an example. Authors want them, users block them. if user initiated then ok. <AllanJ> ...User needs an intelligent way to set overrides, what it does, what can I effect, what will be the results. Jim: HTML 5 has concept of fallback content. Gives example from canvas. ... I think we have that covered from our cascade of alternatives. ... Have concerns around datagrid and labels, images and such. ... Need to form these thoughts further. zakim close item 2 Looking at mail from Simon. Now talking about <AllanJ> SH: is there an API or bridge between javascript and platform Accessibility API <AllanJ> KF: ARIA helps some (with roles) <AllanJ> SH: is there a validity checker or something for accessible Javascript? <AllanJ> KF: ARIA attempts to put semantics and mapping to accessibility API <AllanJ> ...for javascript widgets <AllanJ> JR: Java bridge, is a small set of java widgets that are passed to the platform AAPI. <AllanJ> ...somebody declared a 'winner' for what the specific Java widget set would be. <mth> <sharper> Marcos Cáceres, Opera Software ASA This is scribe.perl Revision: 1.135 of Date: 2009/03/02 03:52:20 Check for newer version at Guessing input format: RRSAgent_Text_Format (score 1.00) FAILED: s/wghat/what/ Found Scribe: KFord Inferring ScribeNick: KFord Default Present: kford, AllanJ, Jan, Henny, sharper, Kim Present: Jan Jim Simon Henny Kford Mark Kim WARNING: Replacing previous Regrets list. (Old list: Greg, Jeanne) Use 'Regrets+ ... ' if you meant to add people without replacing the list, such as: <dbooth> Regrets+ +Greg Regrets: +Greg WARNING: No meeting title found! You should specify the meeting title like this: <dbooth> Meeting: Weekly Baking Club Meeting Got date from IRC log name: 06 Aug 2009 Guessing minutes URL: People with action items: jallan WARNING: Input appears to use implicit continuation lines. You may need the "-implicitContinuations" option.[End of scribe.perl diagnostic output]
http://www.w3.org/2009/08/06-ua-minutes.html
CC-MAIN-2016-36
refinedweb
1,064
65.62
# Imports from __future__ import division import numpy as np import matplotlib import matplotlib.pyplot as plt import seaborn as sb import scipy.optimize as opt from mpl_toolkits.mplot3d import Axes3D, proj3d from matplotlib.colors import LogNorm # Magics %matplotlib inline One of the most used optimization algorithms of today is the Nelder-Mead algorithm. It has become a core muscle in many programming languages' minimization techniques, including being the default for both Matlab and Scipy's fmin function. One of its key benefits is that it requires no information about first or second derivatives. The Nelder-Mead algorithm searches for the minimum value of an objective function map $f : \mathbb{R}^{n} \rightarrow \mathbb{R}$ by applying simple operations to a simplex of $n+1$ points in $\mathbb{R}^n$. The algorithm is simple and a basic understanding of it can provide valuable intuition for when it is (and more importantly when it isn't) an appropriate minimization technique. The algorithm relies on 4 main operations on a simplex of points. Before presenting the main algorithm, we will discuss these operations to simplify the process later. The four operations are: We will discuss these operations in the context of a concrete example. Consider the following simplex of points in 2-D. Let $\Delta$ be a simplex that consists of the points $x_1 = (0, 0); x_2 = (2, 3); x_3 = (4, 0)$. We can then compute the center of mass $\bar{x} = \frac{1}{3} \sum_{i=1}^3 x_i = (2, 1)$. We graph the points of our simplex and their center of mass below. alpha, beta, gamma, delta = 1., 2., .5, .75 x1, x2, x3 = np.array([0., 0.]), np.array([2., 3.]), np.array([4., 0.]) xbar = np.array([2, 1]) Delta = np.vstack([x1, x2, x3]) offsets = [(-15, 10), (5, 5), (5, 5)] # init_simplex = Polygon(Delta, closed=True) fig, ax = plt.subplots(1, figsize=(10, 8)) ax.set_xlim((-2, 7)) ax.set_ylim((-5, 5)) for ind, point in enumerate(Delta): curr_x = r"$x_{}$" curr_offset = offsets[ind] ax.scatter(point[0], point[1], color="k") ax.annotate(curr_x.format(ind+1), xy=point, xytext=curr_offset, textcoords='offset points', size=18) ax.scatter(xbar[0], xbar[1], color="k") ax.annotate(r"$\bar{x}$", xy=xbar, xytext=xbar, textcoords='offset points', size=16) plt.show(fig) To facilitate a simple description of these operations, we sweep several formalities under the rug. First, the point that has these operations applied to it is chosen within the algorithm, but we simply perform all of our operations on $x_2$. Second, and perhaps more importantly, the center of mass used within the algorithm is not the center of mass of all $n+1$ points (it is the center of mass of $n$ points where we exclude the point for which the function ahieves the highest value). Also for aesthetic purposes, we use some nonstandard parameter values in the graphing of these operations ($\alpha = 1$, $\beta = 2$, $\gamma=.5$, and $\delta=.75$). The reflection operation creates a new point defined by reflecting a point across the center of mass of the simplex by $x_r := \bar{x} + \alpha (\bar{x} - x_i)$, where $x_i$ is the point we are reflecting. Thus in our example, $x_r = \bar{x} + \alpha (\bar{x} - x_2) = (2, 1) + \alpha \left( (2, 1) - (2, 3) \right) = (2, -1)$. We add the reflected point below. xr = xbar + alpha*(xbar - x2) ax.scatter(xr[0], xr[1], color="b") ax.annotate(r"$x_r$", xy=xr, xytext=xr, textcoords='offset points', size=16) fig The expansion operation creates a new point by expanding the reflected point further away from $\bar{x}$. It is created by $x_e := \bar{x} + \beta (x_r - \bar{x})$. We can see in our example that $x_e = \bar{x} + \beta (x_r - \bar{x}) = (2, 1) + \beta \left( (2, -1) - (2, 1) \right) = (2, -3)$. We add the expanded point below. xe = xbar + beta*(xr - xbar) ax.scatter(xe[0], xe[1], color="g") ax.annotate(r"$x_e$", xy=xe, xytext=xe, textcoords='offset points', size=16) fig There are two types of contractions: outside and inside. The operation of contraction is the opposite of the operation expanding in the sense that instead of expanded the reflected point out further, it draws it closer towards the center of mass. The outside contraction creates a new point by contracting towards the center of mass from the reflected point and is defined by $x_{oc} = \bar{x} + \gamma (x_r - \bar{x})$. The inside contaction creates a new point by contracting towards the center of mass from the point $x_i$ that we reflected on and is defined by $x_{ic} = \bar{x} + \gamma (x_r - \bar{x})$. xoc = xbar + gamma*(xr - xbar) xic = xbar - gamma*(xr - xbar) ax.scatter(xoc[0], xoc[1], color="r") ax.scatter(xic[0], xic[1], color="r") ax.annotate(r"$x_{oc}$", xy=xoc, xytext=xoc, textcoords='offset points', size=16) ax.annotate(r"$x_{ic}$", xy=xic, xytext=xic, textcoords='offset points', size=16) fig The shrink operation takes all but one of the points and draws them closer to that one point. In the algorithm, we won't be shrinking the points towards the point that we perform the reflection/expansion/contraction on, so we will use $x_1$ as the point towards which the points "shrink." For every point except $x_1$, we create a new point $x_i^s = x_1 + \delta (x_i - x_1)$. xs2 = x1 + delta*(x2 - x1) xs3 = x1 + delta*(x3 - x1) ax.scatter(xs2[0], xs2[1], color="DarkOrange") ax.scatter(xs3[0], xs3[1], color="DarkOrange") ax.annotate(r"$x_{2}^s$", xy=xs2, xytext=xs2, textcoords='offset points', size=16) ax.annotate(r"$x_{3}^s$", xy=xs3, xytext=xs3, textcoords='offset points', size=16) fig Now that we understand what each of the 4 operations within the Nelder-Mead algorithm do, we can discuss the actual algorithm. As you read through the algorithm take note that the main idea is very simple: Order the points, Create some new points, Replace the point with the largest function value, Repeat. There are two ways to obtain the initial simplex. The first way is to simply pass in a simplex $\Delta$ as the guess. The second is to pass in a single point, $x_0$, and create the simplex based around that point (we do this by using $x_0$ as one point of the simplex and by using $x_i := x_0 + e_i \varepsilon$ for the $n$ other points). Once we have the simplex, we evaluate the function at each of the points in the simplex and sort the points such that $x_1 \leq x_2 \leq \dots \leq x_{n+1}$ and find $\bar{x} := \frac{1}{n} \sum_{i=1}^n x_i$ (Notice as we mentioned earlier, we are only taking the center point of the $n$ points with smallest function evaluations). If $|f(\bar{x}) - f(x_1)|$(or another convergence metric of your choosing) then return $x_1$ as the minimum value, otherwise proceed. Create a reflected point $x_r$. 4.1 If $f(x_1) \leq f(x_r) < f(x_n)$ then replace $x_{n+1}$ with $x_r$ 4.2 Return to step 2. Else if $f(x_r) < f(x_1)$ then create the expanded point $x_e$. 5.1 If $f(x_e) < f(x_r)$ then replace $x_{n+1}$ with $x_e$ 5.2 Else if $f(x_r) < f(x_e)$ then replace $x_{n+1}$ with $x_r$. 5.3 Return to step 2. Else if $f(x_n) < f(x_r) < f(x_{n+1})$ then create the outside contraction point $x_{oc}$. 6.1 If $f(x_{oc}) < f(x_r)$ then replace $x_{n+1}$ with $x_{oc}$ 6.2 Else, shrink the points towards $x_1$ 6.3 Return to step 2 Else if $f(x_{n+1}) < f(x_r)$ then create the inside contraction point $x_{ic}$. 7.1 If $f(x_{ic}) < f(x_r)$ then replace $x_{n+1}$ with $x_{ic}$ 7.2 Else, shrink the points towards $x_1$ 7.3 Return to step 2 That is the entire algorithm. As previously stated, you can see that it simply applies our main operations repeatedly until we converge. I have written a simple implementation of the algorithm below. """ Author: Chase Coleman Date: August 13, 2014 This is a simple implementation of the Nelder-Mead algorithm """ def nelder_mead(f, x0, method="ANMS", tol=1e-8, maxit=1e4, iter_returns=None): """ This is a naive python implementation of the nelder-mead algorithm. Parameters ---------- f : callable Function to minimize x0 : scalar(float) or array_like(float, ndim=1) The initial guess for minimizing method : string or tuple(floats) If a string, should specify ANMS or NMS then will use specific parameter values, but also can pass in a tuple of parameters in order (alpha, beta, gamma, delta), which are the reflection, expansion, contraction, and contraction parameters tol : scalar(float) The tolerance level to achieve convergence maxit : scalar(int) The maximimum number of iterations allowed References : Nelder, J. A. and R. Mead, "A Simplex Method for Function Minimization." 1965. Vol 7(4). Computer Journal F. Gao, L. Han, "Implementing the Nelder-Mead simplex algorithm with adaptive parameters", Comput. Optim. Appl., TODO: * Check to see whether we can use an array instead of a list of tuples * Write some tests """ #-----------------------------------------------------------------# # Set some parameter values #-----------------------------------------------------------------# init_guess = x0 fx0 = f(x0) dist = 10. curr_it = 0 # Get the number of dimensions we are optimizing n = np.size(x0) # Will use the Adaptive Nelder-Mead Simplex paramters by default if method is "ANMS": alpha = 1. beta = 1. + (2./n) gamma = .75 - 1./(2.*n) delta = 1. - (1./n) # Otherwise can use standard parameters elif method is "NMS": alpha = 1. beta = 2. gamma = .5 delta = .5 elif type(method) is tuple: alpha, beta, gamma, delta = method #-----------------------------------------------------------------# # Create the simplex points and do the initial sort #-----------------------------------------------------------------# simplex_points = np.empty((n+1, n)) pt_fval = [(x0, fx0)] simplex_points[0, :] = x0 for ind, elem in enumerate(x0): if np.abs(elem) < 1e-14: curr_tau = 0.00025 else: curr_tau = 0.05 curr_point = np.squeeze(np.eye(1, M=n, k=ind)*curr_tau + x0) simplex_points[ind, :] = curr_point pt_fval.append((curr_point, f(curr_point))) if iter_returns is not None: ret_points = [] else: ret_points = None #-----------------------------------------------------------------# # The Core of The Nelder-Mead Algorithm #-----------------------------------------------------------------# while dist>tol and curr_it<maxit: # 1: Sort and find new center point (excluding worst point) pt_fval = sorted(pt_fval, key=lambda v: v[1]) xbar = x0*0 for i in range(n): xbar = xbar + (pt_fval[i][0])/(n) if iter_returns is not None and curr_it in iter_returns: ret_points.append(pt_fval) # Define useful variables x1, f1 = pt_fval[0] xn, fn = pt_fval[n-1] xnp1, fnp1 = pt_fval[n] # 2: Reflect xr = xbar + alpha*(xbar - pt_fval[-1][0]) fr = f(xr) if f1 <= fr < fn: # Replace the n+1 point xnp1, fnp1 = (xr, fr) pt_fval[n] = (xnp1, fnp1) elif fr < f1: # 3: expand xe = xbar + beta*(xr - xbar) fe = f(xe) if fe < fr: xnp1, fnp1 = (xe, fe) pt_fval[n] = (xnp1, fnp1) else: xnp1, fnp1 = (xr, fr) pt_fval[n] = (xnp1, fnp1) elif fn <= fr <= fnp1: # 4: outside contraction xoc = xbar + gamma*(xr - xbar) foc = f(xoc) if foc <= fr: xnp1, fnp1 = (xoc, foc) elif fr >= fnp1: # 5: inside contraction xic = xbar - gamma*(xr - xbar) fic = f(xic) if fic <= fr: xnp1, fnp1 = (xic, fic) # Compute the distance and increase iteration counter dist = abs(fn - f1) curr_it = curr_it + 1 if curr_it == maxit: raise ValueError("Max iterations; Convergence failed.") if ret_points: return x1, f1, curr_it, ret_points else: return x1, f1, curr_it One of the key tests for an optimization algorithm is Rosenbrock's "banana function" which is $f(x, y) := (a - x)^2 + b(y - x^2)^2$ which has a minimum at $(a, a^2)$. It is a tricky function because of nonconvexities and there are many points that are close to being a minimium. I graph the function below: # Define Rosenbrock Function def rosenbrock(x, a=1, b=100): """ The minimum value of rosenbrock function is (a, a**2) """ y = x[1] x = x[0] return (a - x)**2 + b*(y - x**2)**2 x = np.linspace(-2.5, 2.5, 500) y = np.linspace(-2.5, 2.5, 500) X, Y = np.meshgrid(x, y) Z = rosenbrock([X, Y]) fig = plt.figure(figsize=(14, 8)) ax1 = fig.add_subplot(121) ax2 = fig.add_subplot(122, projection="3d") fig.suptitle("Rosenbrock Function", size=24) # Color mesh ax1.set_axis_bgcolor("white") ax1.pcolormesh(X, Y, Z, cmap=matplotlib.cm.viridis, norm=LogNorm()) ax1.scatter(1, 1, color="k") ax1.annotate('Global Min', xy=(1, 1), xytext=(-0.5, 1.25), arrowprops=dict(facecolor='black', shrink=0.05)) # Surface plot ax2.set_axis_bgcolor("white") ax2.plot_surface(X, Y, Z, norm = LogNorm(), cmap=matplotlib.cm.viridis, linewidth=0) ax2.view_init(azim=65, elev=25) ax2.scatter(1., 1., 0., color="k") xa, ya, _ = proj3d.proj_transform(1,1,0, ax2.get_proj()) ax2.annotate("Global Min", xy = (xa, ya), xytext = (-20, 30), textcoords = 'offset points', ha = 'right', va = 'bottom', arrowprops=dict(facecolor='black', shrink=0.05)) plt.tight_layout() plt.show() Now that we have seen the objective function, I will try and use our algorithm to find the minimum of this function. To show the progress, I will plot some of the steps below --In particular, I will plot iterations 0, 1, 2, 3, 4, 5, 10, 20, 50, 75, 90, and 95 as set by iterstosee. iterstosee = [0, 1, 2, 3, 4, 5, 10, 15, 30, 45, 75, 90] x, fx, its, ret_tris = nelder_mead(rosenbrock, x0=np.array([-1.5, -1.]), tol=1e-12, iter_returns=iterstosee) fig, axs = plt.subplots(nrows=6, ncols=2, figsize=(16, 24)) axs = axs.flatten() # Color mesh for i, curr_ax in enumerate(axs): curr_simplex = np.vstack([ret_tris[i][0][0], ret_tris[i][1][0], ret_tris[i][2][0]]) curr_ax.pcolormesh(X, Y, Z, cmap=matplotlib.cm.viridis, norm=LogNorm()) curr_ax.set_title("This is simplex for iteration %i" %iterstosee[i]) curr_ax.scatter(curr_simplex[:, 0], curr_simplex[:, 1]) plt.tight_layout() plt.show()
http://nbviewer.jupyter.org/github/QuantEcon/QuantEcon.notebooks/blob/master/chase_nelder_mead.ipynb
CC-MAIN-2017-04
refinedweb
2,308
57.06
One Angry Coder At Microsoft, we really do care about our customers (you). Last week we got a visit from the Application Compatibility team from the .NET framework. These guys are serious about making sure that any app that you wrote for the .NET framework 1.1, will be forward compatible with 2.0. It seems that on there travels, they ran into a few of you having problems running the January 2005 release of Enterprise Library because some of the things we did (that we fixed in the June 2005 release) are not forward compatible. What does this mean? Well in short, if you have built your application with the January 2005 release of Enterprise Library and move it forward to run in a .NET 2.0 AppDomain it will fail (I will tell you why later). We realized this and we put out the June 2005 release (now stay with me, this could get a little confusing). The June 2005 served two purposes : 1) to make sure that when you ran your app that was built for the .NET framework 1.1 and moved it (without recompiling etc) to the .NET 2.0 framework, it would run; 2) You could recompile Enterprise Library June 2005 for Whidbey Beta 2 and build a bridge for your apps until you could convert them to Enterprise Library 2.0. Now you may be asking yourself, “Wait a minute, what do you really mean by ‘build a bridge’?”. Glad you asked. Enterprise Library will not be backwards compatible. Now before everyone gets really mad, read the post made by edjez and it will hopefully make some since. As edjez so eloquently puts it, we want to give you the best guidance on the platform that we release upon. And like I have said before we are aligning with the .NET 2.0 platform in this release, so we have to do a little bit of movement to do that. Why does Enterprise Library January 2005 fail?In .NET 2.0, they have added new attributes to some of the sections in machine.config and new namespaces for web.config. The logic that we did to parse the config files need to be changed. We made this change and others to help get things to run on .NET 2.0. We have spent most of last week and this weekend verifying that everything works on RTM builds (no it is not done, but they have build layouts for RTM). Here is what we learned from this exercise: What is the moral of this story? Get the June 2005 release. This will upgrade you to the newest bits and make sure your migration to Whidbey will be easy. Now playing: Collective Soul - No More, No Less PingBack from
http://blogs.msdn.com/scottdensmore/archive/2005/08/07/448761.aspx
crawl-002
refinedweb
464
82.04
$ENV{test} = "TRUE"; $command = `setenv test TRUE`; system "setenv test TRUE"; [download] The traditional approach to pass environment variables upwards is to output a shell script and source that shell script from the calling shell: eval "$(myvalues.pl)" [download] If you want to see and capture which shell variables a shell script sets up, a good approach is to run that shell script in a subshell and then output the resulting values. See for example Get default login environment and the comments to it, and also Shell::GetEnv. The environment is always copied from parent to child process and not shared. A changed environment in your Perl script is only visible inside this script and children processes of that script. Cheers Rolf (addicted to the Perl Programming Language :) Wikisyntax for the Monastery FootballPerl is like chess, only without the dice If your problem is in the other direction, try export with variables meant to be available to a child process lanx@ubuntu:~$ export TEST=TRUE lanx@ubuntu:~$ perl -E 'say $ENV{TEST}' TRUE [download] lanx@ubuntu:~$ perl -E '$ENV{TEST}=TRUE; say `echo \$TEST` ' TRUE [download] Again, you can only effect the child process. ( update: please note you have three different processes in this example: ~$ Bash > Perl -E '...' > `Bash` ) If you want to effect the parent process, you need to return text information which is either eval'ed or source'd (when put into a file). lanx@ubuntu:~$ eval `perl -E 'say q{export TEST=TRUE}'` lanx@ubuntu:~$ echo $TEST TRUE [download] In other words the parent process always keeps full control of the environment. When you use system or backticks or qx{}, the command is executed in a newly spawned shell, so setting an environment variable using one of these methods will not reflect to the calling process. Consider it to be equivalent to (I used $$ to show that it is the prompt of the sub-shell) $ export A=1 $ echo $A 1 $ bash $$ echo $A 1 $$ export A=2 $$ echo $A 2 $$ exit $ echo $A 1 [download] So, those three are out. The case of %ENV is way more interesting, as it involves scope and timing. Lets start with simple examples: $ echo $A;perl -wE'say $ENV{A};$ENV{A}=2;say$ENV{A}';echo $A 1 1 2 1 $ perl -wE'say $ENV{A};qx{echo \$A};$ENV{A}="B";say $ENV{A };qx{echo \$A};' 1 B [download] You can observe that the proces spawned with the first qx uses the original value stored in $A, and the second invocation uses the changed value, as you expect (if I read your question correctly), so no surprises there. What will complicate matters is if those %ENV values are used in the startup phase of a module that you use. This implies that the value is used before you change its value. In that case, you should do something like BEGIN { $ENV{test} = "B"; } use My::Module; # Which initializes with $ENV{test} [download] Now the environment is set before it is seen by the module. HTH It's not clear from the post what you are trying to achieve. Do you want to set variable test in the shell that is calling your perl script? Or do you want to set test in further processes created by your program via system? In the scary old times of DOS, it was possible to patch the environment of the parent process. But then again, you could even patch away DOS and replace it with something completely DOS is single user, single task, without any memory protection. Unix is multi-user, multi-task, and usually has memory protection. And it is a good thing that you can not patch the environment of your parent process. It would be a security hole. Imagine this: On a system that allows patching the environment of the parent process, root would have lost control over the system. /some/where/dangerous has changed $ENV{'PATH'} of the login shell so that a directory containing malicious software under common names (ls, rm, vi, touch, ...) is searched first. That software runs with root privileges, i.e. no limits. On a system as we know it, /some/where/dangerous can't do that. Of course, working as root is a bad idea to start with, and relying on $ENV{'PATH'} as root is even worse. But such things happen. It does not have to be that bad, the same problem would happen even without sudo and for any user if software messes with the parent's environment. Alexander Prepare to be enlightened: #!/usr/bin/perl # setenv from within perl to effect parent shell # actually parent should be more appropriately # called "adopted" or "step-parent", re execl # there is one little requirement: # you should run this program via shell's exec: # % exec <scriptname> # # author: bliako # date: 09/07/2018 use Inline C => DATA; # ... # this should be the last statement in your script # because nothing else will be executed after that # not even the 'or die ...' mysetenv("test", "TURE") or die "mysetenv() failed"; __END__ __C__ #include <stdio.h> #include <unistd.h> #include <stdlib.h> int mysetenv(const char *K, const char *V){ if( K==NULL || V==NULL ){ return 0; } char *shell = getenv("SHELL"); if( setenv(K, V, 1) ){ fprintf(stderr, "mysetenv() : call to setenv() has fai +led.\n"); return 1; } // replace caller shell with a new shell which now has // set this new env var //printf("shell to exec is %s\n", shell); execl(shell, NULL, NULL); perror("execl failed, "); return 1; } [download] % echo $test % exec env.pl % echo $test TURE The above script sets the specified environment variable and at the same time replaces current program (the perl script) with a new shell which inherits the env. If this script is executed via shell's exec, e.g. % exec env.pl the current shell will be replaced by the new shell created in the perl script and having the set environment. For more flexibility, the mysetenv() function should be split into 2 parts. The setenv part and the execl part. The execl part should be executed last. After execl call the perl script process stops to exist! bw, bliako (and excuse my boasting) Corion observed that this can be done using only pure Perl. Which is right but somehow escaped me. So here it is in pure Perl. You still need to execute the script via exec env2.pl. #!/usr/bin/perl # setenv from within perl to effect parent shell # actually parent should be more appropriately # called "adopted" or "step-parent", re execl # there is one little requirement: # you should run this program via shell's exec: # % exec <scriptname> # # this is pure-Perl implementation after Corion's # comment. # set env $ENV{test} = 'TURE'; # ... # this should be the last statement in your script # because nothing else will be executed after that # not even the 'or die ...' die "no shell!" unless defined($ENV{SHELL}); exec($ENV{SHELL}); __END__ [download] Your trick only works interactively because you need to exec a NEW follow up shell, waiting for human input. This means this illusion won't work in a non interactive script. All code after the exec will be ignored. On a more serious node, the exec() is a safe (Edit: not safe as in safety and security) way to achieve what the question asked as my use-case demonstrated. It is true that unless one executes the "trick" from an interactive shell any command past that exec will not run as KurtZ whines rightly points out. For example as a cron job. I don't see it as a "trick" because this is what exec() was intended to do in the first place. It is not exploiting any of its features=bugs, it is not using it in a heads-down-feet-up kind of way. And definetely the result is not an illusion because it's there. You get your environment modified albeit within a brand new shell which inherits from the parent shell. It inherits env variables and even opened file descriptors. For example: exec 3> /tmp/out echo 'before exec' >&3 exec env2.pl echo 'after exec' >&3 exec 3>&- cat /tmp/out before exec after exec [download] So, not a trick, not an illusion but limited (and what isn't) to interactive shells. For non-interactive use, e.g. a cron-job one can go with Corion's Re: setenv in perl. And if only 1 env-variable needs to be set up, then the eval can be avoided by using: export test=`perl -e 'print 'TURE'` [download] Lastly, if the scenario is to run a shell command which reads data from the environment and having a perl script to calculate this data and export it to the environment then why not let perl calculate AND spawn the command because any system() call inherits perl's environment vars, like so: #!/usr/bin/env perl $ENV{test} = 'TURE'; # calculate my @cmd = ('command-exec', 'args'); system(@cmd); # spawn # simple demo: system('echo $test'); # prints what [download] bw, bliako Nope! Not in a Quantum Computer running UNIX. There, in a parallel universe my "trick"'s "illusion" will warp into reality. Clever. Here's what happens. When you run Perl with exec, it replaces the shell in the same process. This is the key; just running Perl as it is usually done will not have this effect, which is why you got so many "It can't be done" responses. Because environment variables live in a process, the Perl script sees the same environment the shell did. When you then exec the shell after modifying the environment, the new copy of the shell, still running in the same process, sees those modifications. I do have a couple observations to add. This approach only works if you have control over how your Perl script is run. Unless the Perl script is in the PATH, I found I needed to explicitly specify the directory: ./env.pl If you do it this way, you do not need to use Inline::C. Simply modifying %ENV will work: #!/usr/bin/env perl use 5.008; use strict; use warnings; $ENV{test} = 'TURE'; exec $ENV{SHELL} or die "Failed to exec shell '$ENV{SHELL}'\n"; [download] works just as well: $ echo "PID=$$; test='$test'" PID=87533; test='' $ exec ./exec.pl $ echo "PID=$$; test='$test'" PID=87533; test='TURE' [download] I was trying to follow your post as I think triangulating this question with C makes complete sense. Have I missed a step? $ touch 1.bliako.pl $ chmod +x 1.bliako.pl $ gedit 1.bliako.pl & [download] I paste in your code and set it to execute. First I need Inline.pm: try installing Inline:.
https://www.perlmonks.org/?node_id=1218130
CC-MAIN-2019-09
refinedweb
1,785
70.43
I was just looking at Rails' functional testing. Here's their first example: require File.dirname(__FILE__) + '/../test_helper' # grab our HomeController because we're going to test it require 'home_controller' # Raise errors beyond the default web-based presentation class HomeController; def rescue_action(e) raise e end; end class HomeControllerTest < Test::Unit::TestCase def setup @controller = HomeController.new @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new end # let's test our main index page def test_index get :index assert_response :success end end Here's how you'd do it in Paste: from paste.tests.fixture import * def test_index(): res = app.get('/') (Note: 100% framework neutral!) Why is it so much shorter? Well, first it uses py.test instead of an XUnit-based system, which gets rid of the stupid cruft of XUnit. This isn't a criticism of Rails or Ruby, per se -- we have the same module in Python and it's no better. py.test is much better, though. Second, setup is done in paste.tests.fixture.setup_module, which is a special function that py.test calls (and you imported with import *). This finds your configuration file and creates your WSGI application. This part (finding a configuration file and using that to construct an application) is Paste-specific, but everything else sticks to WSGI. This also puts app (an object intended for testing) in the module's namespace. Lastly, this object assumes when you say app.get('/') that you expect everything to work. That means a 200 OK response (as well as a couple other checks -- redirects are also okay). You have to specifically indicate that you expect another response; since this is an object intended for testing, why not build test-friendly assumptions into it? Looking through the Rails docs on this, there's some other useful features I'd like to add. Because this only uses opaque WSGI applications, you can't look at the variables used to render the document; the only communication you get is the actual textual response. Here's what I frequently do: def test_index(): res = app.get('/') for item in db.TodoItem.select(): res.mustcontain(item.title) I'm not actually that interested in how the view got the items, so looking at the communication between view and controller isn't that interesting. But I can imagine adding some convention so that frameworks (when run in testing mode) could stuff objects into the WSGI environment for later inspection. One of the things I like about Paste's tests compared to tests that are more opaque (e.g., actually speak to the app over HTTP) is that I have access to the backend objects (like db.TodoItem), and exceptions propogate (which gives me py.test's fancy tracebacks). As a result I've become less excited about the functional testing provided by Twill and others. The whole thing is fairly young, but I think it is pleasantly simple and yet quite useful. If you are interested look at the docs. I'd be nice to see examples of the test failures. As you say, the fancy tracebacks. These are often one of the hidden beauties of testing frameworks. Where does app come from? From looking at the test I can't tell where app comes from. I suppose it could be a good thing to write generic tests for multiple applications. Perhaps explicitly tell it where the config file is? However what is in this config file? If I was writing this test from scratch I'd need to know the config file format, and what needs to go in it. Importing your app module directly might be the go to make it more explicit?from paste.tests.fixture import * import yourapp app = yourapp.app def test_index(): res = app.get('/') The configuration is a Paste configuration file, which describes an application. The configuration file is found in server.conf, and the fixture searches parent directories for such a file until it finds one. The app object is actually paste.tests.fixture.TestApp(paste_app). Generally this should work easily if you have your application set up to run in Paste. But not so easy otherwise. Hrm... and I don't think I really have good documentation for the configuration file at this time :(
http://www.ianbicking.org/functional-testing-in-paste.html
CC-MAIN-2014-52
refinedweb
709
68.06
What Does XML Smell Like? February 28, 2007 This article introduces a set of heuristic rules for sniffing the content of a file in order to determine whether it is an XML document or an HTML document. An implementation is provided using the xmlReader interface of libxml2. This implementation is used in Prince, a formatter for creating PDF files from web documents. Problem Say. Heuristics.) On the other hand, a DOCTYPE declaration with a public identifier containing "HTML," such as -//W3C//DTD HTML 4.01 Transitional//EN, means that it must be an HTML document, not XML.or xml:base, mean that the document must be XML. .htmlextension,. Examples From the last heuristic, it is clear that this document smells like HTML: <html> <head> <title>What am I?</title> ... This seems reasonable, as there is nothing to indicate that this document is XML. It is possible that later in the document there might be some XML content with namespaces that will fail to impress the HTML parser, but this falls under the topic of parsing XML islands in HTML documents; the jury is still out on the legality of this. We can indicate that this document is actually XHTML by adding an XML declaration, or an XHTML DOCTYPE declaration, or by adding an xmlns attribute to the root element. These are all sensible things to do if the document is really intended to be XHTML, and they make it obvious to human readers as well as to programs. Note that strictly conforming XHTML1 documents should be easy for our heuristics to recognize, as they must have a DOCTYPE declaration with a public identifier that references one of the three XHTML1 DTDs and an xmlns attribute on the root element. Document authors are also encouraged to add an XML declaration. However, a user agent also needs to handle XHTML documents that reference other DTDs, such as the XHTML + MathML DTD, and may lack an explicit xmlns attribute or specify an incorrect namespace URI. The heuristics above can correctly handle these documents. Implementation In Prince, these document sniffing heuristic rules are implemented as a C function that uses the xmlReader interface from libxml2 to parse the document up until the first start tag or one of the heuristics matches. A copiously commented version of the code, as well as some sample documents to test it on, is available for download in the "Code" section below; it compiles to a small program that sniffs files and classifies them as being XML or HTML. One caveat with this implementation is that, while we only explicitly parse up to the first start tag in the document, behind the scenes the libxml2 xmlReader appears to be parsing further ahead for efficiency, as it assumes we ultimately intend to parse the entire document. This means that it is possible for the xmlReader interface to reach a syntax error that occurs shortly after the first start tag, in which case our heuristic will conclude that the document must be HTML and stop. This is not really a problem, but in some cases can result in slightly more confusing error messages for XML documents that contain syntax errors near the top of the file. You could also implement the heuristics using the xmlReader interface from .NET (on which the libxml2 interface is based) or any of the XML pull-parser libraries available for Java. Another option is to implement the heuristics using a SAX parser instead, ensuring that it doesn't try to be clever and eagerly parse ahead of where it should be. Just make sure that you remember to stop the SAX parser when a heuristic matches or when you reach the first start tag in the document. Code Here's the source code for sniffxml, a program that sniffs files to determine if they are XML or HTML. Notes On the web, content sniffing is considered harmful. When user agents ignore the metadata in the HTTP response and try to guess the type of the document, it can lead to confusing behavior, lack of interoperability, and even security problems. The heuristics described in this article should only be applied to local files where no other type information is available. When a document is retrieved over HTTP, the user agent should always respect the Content-Type header. It is considered to be poor practice to determine the semantics of XML or SGML documents based on their DOCTYPE declarations. The DOCTYPE is a purely syntactical construct that does not specify the meaning of the document, so a user agent should not choose how to handle a document by looking at the public identifier specified in the DOCTYPE. (The split between quirks mode and standards mode in browsers is one processing model that breaks this rule, and it exists purely to compensate for a lack of interoperability and standards compliance in older browsers.) The heuristics described in this article do examine the DOCTYPE declaration. However, they only do this in order to determine whether a document is most likely to be XML or HTML. Once this has been determined, the document can be parsed as normal and the DOCTYPE will not affect the semantics of the document. For an in-depth look at the issues affecting XML and HTML on the Web, see Sending XHTML as text/html Considered Harmful, by Ian Hickson. It would be interesting to know if the question of what XML smells like triggers any illuminating associations in the minds of people who have been working with XML for years. Please leave a comment if you think XML smells like apple pie or the first breath of spring. Or more realistically, if the question evokes a response of "worse than week-old prawns on a hot summer day," well, that's good too.
https://www.xml.com/pub/a/2007/02/28/what-does-xml-smell-like.html
CC-MAIN-2017-34
refinedweb
968
55.78
It's not the same without you Join the community to find out what other Atlassian users are discussing, debating and creating. How can I get html content of page when I heve page ID? I am writing plugin for confluence (java api) and I need content of page in html (source of page). You need to use the PageManager API to retrieve the content of the page, and then use the WikiStyleRenderer API to convert the wiki markup into the HTML markup for the page. Here's a code snippet: public class MyExampleClass { private final PageManager pageManager; private final WikiStyleRenderer wikiStyleRenderer; public MyExampleClass(PageManager pageManager, WikiStyleRenderer wikiStyleRenderer) { this.pageManager = pageManager; this.wikiStyleRenderer = wikiStyleRenderer; } public String getHtmlForPage(long pageId) { Page page = pageManager.getPage(pageId); PageContext pageContext = page.toPageContext(); String contentToRender = page.getContent(); return wikiStyleRenderer.convertWikiToXHtml(pageContext, contentToRender); } } Marcin, I hope I have understood your question correctly. Confluence has the ability to allow you to export a space or a page in HTML (usually so it can be used for a website), this will allow you to view a page in HTML. Directions are as follows: Go to a page in the space, open the 'Browse' menu and select 'Advanced'. More detailed information can be viewed at: Confluence 3.5 Documentation - Export to HTML Hope that answers your issue! Thanks for your answer! I am writing confluence plugin and I want to take page as html code and process this string. I can use getContent() method (from Page class) but I get wiki markup. What class or method can I use in order to get html code page? Hey Marcin, I've been doing a lot of research on your question, and I've been struggling to find an inbuilt method to display HTML code for the page. What I have found is the following: Wiki Markup Converters The best one on there appears to be Wiky. It is written in Javascript and is bi-directional. It can convert your wiki markup to HTML, then convert the generated HTML back to wiki markup (should you need the function) Hope this helps.
https://community.atlassian.com/t5/Confluence-questions/Confluence-3-5-13-Content-Page-in-html/qaq-p/391041
CC-MAIN-2019-09
refinedweb
350
56.76
{-# LANGUAGE ViewPatterns #-} import Control.Concurrent.MVar import Control.Monad import Data.Char import Data.Sequence (Seq, viewl, ViewL(..), (><)) import qualified Data.Sequence as Seq import Data.List import Data.Map.Strict (Map, (!)) import qualified Data.Map.Strict as M import qualified Data.Set as S import Text.ParserCombinators.Parsec Core War In a round of Core War, two programs attempt to halt each other by overwriting instructions that are about to be executed. Watch a battle between two famous warriors, CHANG1 (left, blue) versus MICE (right, red): The programs are written in a language called Redcode. For details, read the original Scientific American articles introducing the game, as well as a guide to the 1994 revision of Redcode, which is nicer than the official document. See also complete listings of many programs. Some potential points of confusion: In the original Redcode, MOV with an immediate A field writes a DAT instruction to the target address. In later versions, it overwrites the B field only by default. The instruction encoding scheme given in the original article is irrelevant. For example, the only way to change an instruction is to use MOV to copy another instruction, The '94 specification defines CMP to be an alias of SEQ, but the Gemini program featured in the original article, it clearly means SNE. In general, documentation felt buggy. For example, I happened to browse the source of theMystery 1.5, which claims "spl 1; mov -1, 0; mov -1, 0" makes 7 processes. It seems it results in 5 processes. To get 7, we could write "spl 1; spl 1; mov -1, 0". The Journey to MARS The above Memory Array Redcode Simulator was written in Haskell and compiled to JavaScript with Haste. $ haste-cabal install parsec $ wget $ hastec redcode.lhs $ sed 's/^\\.*{code}$/-----/' redcode.lhs | asciidoc -o - - > redcode.html We start with imports for our Redcode emulator: Then append some Haste-specific imports: import Haste import Haste.DOM import Haste.Events import Haste.Graphics.Canvas Arrays are cumbersome in Haskell because of purity, so we use Data.Map to represent the memory array of 8000 cells, initialized to DAT 0 instructions. The game state consists of the memory array, along with a tuple holding a program ID along with the program counters of its threads. For the latter, we use Data.Sequence instead of a list to obtain fast and strict queue operations. type Arg = (Char, Int) data Op = Op String Arg Arg deriving (Show, Eq) type Core = Map Int Op data Game = Game Core [(Int, Seq Int)] deriving Show sz = 8000 initCore = M.fromList $ zip [0..sz - 1] $ repeat $ Op "DAT" ('#', 0) ('#', 0) Simulating a single instruction at a given location results in a list of changes to be made to memory, and a list of the next locations to execute. Focusing on the changes makes it easy to update our visualization of memory. If we instead returned a new map, we might have to redraw the entire screen to show the next state. I began with the three original memory addressing modes: inskvs = foldl' (\c (k, v) -> M.insert k v c) load ops a c = inskvs c $ zip [a..] ops exeRedcode c ip = f op ma mb where Op op (ma, a) (mb, b) = c!ip f "DAT" _ _ = ([], []) f "NOP" _ _ = ([], adv) f "MOV" '#' _ = ([(rb, putB aa ib)], adv) f "MOV" _ '#' = ([(rb, putB ba ib)], adv) f "MOV" _ _ = ([(rb, c!ra)], adv) f "SEQ" '#' _ = skipIf $ aa == bb f "SEQ" _ '#' = skipIf $ ba == bb f "SEQ" _ _ = skipIf $ ia == ib f "SNE" '#' _ = skipIf $ aa /= bb f "SNE" _ '#' = skipIf $ ba /= bb f "SNE" _ _ = skipIf $ ia /= ib f "ADD" '#' _ = ([(rb, putB (add a bb) ib)], adv) f "ADD" _ '#' = ([(rb, putB (add ba bb) ib)], adv) f "ADD" _ _ = ([(rb, putA (add aa ab) $ putB (add ba bb) ib)], adv) f "SPL" _ _ = ([], adv ++ [ra]) f "JMP" _ _ = jumpIf True ra f "JMN" _ _ = jumpIf (bb /= 0) ra f "JMZ" _ _ = jumpIf (bb == 0) ra f "DJN" _ _ = effect [(rb, putB (sub bb 1) ib)] $ jumpIf (bb /= 1) ra f "DJZ" _ _ = effect [(rb, putB (sub bb 1) ib)] $ jumpIf (bb == 1) ra f op _ _ = error $ "huh " ++ op jumpIf True a = ([], [a]) jumpIf False _ = ([], adv) skipIf True = ([], add 1 <$> adv) skipIf False = ([], adv) effect es (ds, a) = (ds ++ es, a) ra = resolve c ip (ma, a) rb = resolve c ip (mb, b) ia = c!ra ib = c!rb aa = getA ia ba = getB ia ab = getA ib bb = getB ib adv = [add ip 1] getA (Op _ (_, a) _) = a getB (Op _ _ (_, b)) = b putA a (Op op (m, _) mb) = Op op (m, a) mb putB b (Op op ma (m, _)) = Op op ma (m, b) add x y = (x + y) `mod` sz sub x y = (x + sz - y) `mod` sz resolve c ip ('#', i) = ip resolve c ip ('$', i) = add ip i resolve c ip ('@', i) = let j = add ip i in add j $ getB $ c!j Later I learned of newer addressing modes that predecrement or postincrement. I hastily added a wrapper function to handle the case needed for the MICE program: resolve c ip ('<', i) = resolve c ip ('@', i) exe c ip = (preb ++ prea ++ deltas, ip1) where Op _ (ma, a) (mb, b) = c!ip preb | mb == '<' = [(rb, putB (sub (getB $ c!rb) 1) $ c!rb)] | otherwise = [] cb = inskvs c preb rb = resolve c ip ('$', b) prea | ma == '<' = [(ra, putB (sub (getB $ cb!ra) 1) $ cb!ra)] | otherwise = [] ca = inskvs cb prea ra = resolve cb ip ('$', a) (deltas, ip1) = exeRedcode ca ip I had no motivation to add the other addressing modes. Let’s move on to the assembler. We use the Parsec parser combinator library: num :: Parser Int num = do s <- option id $ const negate <$> char '-' s . read <$> many1 digit arg = do spaces m <- option '$' $ oneOf "@#$<" n <- num return (m, standardize n) standardize n | m < 0 = sz - m | otherwise = m where m = mod n sz jumps = words "JMP JMZ JMN DJZ DJN SPL" known = flip S.member $ S.fromList $ words "MOV ADD SUB SEQ SNE DAT " ++ jumps isJump = flip S.member $ S.fromList jumps unalias "CMP" = "SNE" unalias "JMG" = "JMN" unalias s = s asm :: Parser Op asm = do spaces op <- unalias . map toUpper <$> many1 letter if not $ known op then fail $ "unknown: " ++ op else do a <- arg m <- optionMaybe $ optional (try $ spaces >> char ',') >> arg spaces eof case m of Just b -> return $ Op op a b Nothing | isJump op -> return $ Op op a ('#', 0) | op == "DAT" -> return $ Op op ('#', 0) a | otherwise -> fail $ "needs 2 args: " ++ op Lastly, we add a GUI. We have a timer that fires every 16 milliseconds, which causes our program to advance the game held in an MVar by 64 steps. Each of the two warriors is limited to 32 processes. I tried using a once-only timer that would set up the next once-only timer, which would then be canceled if the simulation were halted, but I couldn’t get stopTimer to work. We use an MVar to store the game state between ticks. An IORef would work too, since JavaScript is single-threaded. I spent little effort on this part. The code here is tightly coupled to Haste and HTML: rewriting it for, say, SDL or GHCJS would require big changes anyway. passive = [RGB 63 63 191, RGB 191 63 63] active = [RGB 127 127 255, RGB 255 127 127] main = withElems ["canvas", "player1", "player2", "con", "goB", "stopB"] $ \[canvasE, player1E, player2E, conE, goB, stopB] -> do Just canvas <- fromElem canvasE gv <- newMVar Nothing let mark c a = renderOnTop canvas $ color c $ box x y where (y, x) = divMod a 100 box x y = fill $ rect (xf, yf) (xf + 3, yf + 3) where xf = fromIntegral x * 3 yf = fromIntegral y * 3 tryStep = do jg <- takeMVar gv case jg of Just g -> step g Nothing -> putMVar gv Nothing con s = do v0 <- getProp conE "value" setProp conE "value" $ v0 ++ s ++ "\n" step g@(Game c []) = putMVar gv Nothing >> con "all programs halted" step g@(Game c ((id, viewl -> ip :< rest):players)) = do let (deltas, next) = exe c ip truncNext = take (32 - Seq.length rest) next ipq = rest >< Seq.fromList truncNext c1 = inskvs c deltas mapM_ (mark (passive!!id) . fst) deltas mark (passive!!id) ip mapM_ (mark (active!!id)) truncNext case viewl ipq of EmptyL -> do con $ "program " ++ show id ++ " halted" putMVar gv $ Just $ Game c1 players _ -> putMVar gv $ Just $ Game c1 $ players ++ [(id, ipq)] newMatch = do render canvas $ color (RGB 0 0 0) $ fill $ rect (0, 0) (300, 240) setProp conE "value" "new match: 0 vs 1\n" s <- getProp player1E "value" case mapM (parse asm "") $ lines s of Left err -> do swapMVar gv Nothing con $ show err Right p1 -> do s <- getProp player2E "value" case mapM (parse asm "") $ lines s of Left err -> do swapMVar gv Nothing con $ show err Right p2 -> gameOn p1 p2 gameOn p1 p2 = do mapM_ (mark $ passive!!0) [0..length p1 - 1] mark (active!!0) 0 mapM_ (mark $ passive!!1) [4000..4000 + length p2 - 1] mark (active!!1) 4000 void $ swapMVar gv $ Just $ Game (load p2 4000 $ load p1 0 initCore) [(0, Seq.singleton 0), (1, Seq.singleton 4000)] con "running programs" void $ goB `onEvent` Click $ const newMatch void $ stopB `onEvent` Click $ \_ -> do jg <- takeMVar gv case jg of Just _ -> con "match halted" Nothing -> pure () putMVar gv Nothing newMatch void $ setTimer (Repeat 16) $ replicateM_ 64 tryStep
https://crypto.stanford.edu/~blynn/play/redcode.html
CC-MAIN-2019-22
refinedweb
1,590
77.47
- transparent transaction support - dog-pile prevention mechanism - a couple of hacks to make django faster Requirements Python 3.5+, Django 2.1+ and Redis 4.0+. Installation Using pip: $ pip install django-cacheops # Or from github directly $ pip install git+ Setup Add cacheops to your INSTALLED_APPS., # connection timeout in seconds, optional 'password': '...', # optional 'unix_socket_path': '' # replaces host and port } # Alternatively the redis connection can be defined using a URL: CACHEOPS_REDIS = "redis://localhost:6379/1" # or CACHEOPS_REDIS = "unix://path/to/socket?db=1" # or with password (note a colon) CACHEOPS_REDIS = "redis://:password@localhost:6379/1" # If you want to use sentinel, specify this variable CACHEOPS_SENTINEL = { 'locations': [('localhost', 26379)], # sentinel locations, required 'service_name': 'mymaster', # sentinel service name, required 'socket_timeout': 0.1, # connection timeout in seconds, optional 'db': 0 # redis database, default: 0 ... # everything else is passed to Sentinel() } # To use your own redis client class, # should be compatible or subclass cacheops.redis.CacheopsRedis CACHEOPS_CLIENT_CLASS = 'your.redis.ClientClass' CACHEOPS = { # Automatically cache any User.objects.get() calls for 15 minutes # This also includes .first() and .last() calls, # as well as all queries to Permission # 'all' is an alias for {'get', 'fetch', 'count', 'aggregate', }, # NOTE: binding signals has its overhead, like preventing fast mass deletes, # you might want to only register whatever you cache and dependencies. # Finally you can explicitely forbid even manual caching with: 'some_app.*': None, } You can configure default profile setting with CACHEOPS_DEFAULTS. This way you can rewrite the config above: CACHEOPS_DEFAULTS = { 'timeout': 60*60 } CACHEOPS = { 'auth.user': {'ops': 'get', 'timeout': 60*15}, 'auth.*': {'ops': ('fetch', 'get')}, 'auth.permission': {'ops': 'all'}, '*.*': {}, } Using '*.*' with non-empty ops is not recommended since it will easily cache something you don’t intent to or even know about like migrations tables. The better approach will be restricting by app with 'app_name.*'.' -: from django.test import override_settings @override_settings(CACHEOPS_ENABLED=False) def test_something(): # ... assert cond Usage It’s automatic you just need to set it up. You can force any queryset to use cache by calling its .cache() method: Article.objects.filter(tag=2).cache() Here you can specify which ops should be cached for the queryset, for example, this code: qs = Article.objects.filter(tag=2).cache(ops=['count']) paginator = Paginator(objects, ipp) articles = list(pager.page(page_num)) # hits database will cache count call in Paginator but not later articles fetch. There are five possible actions - get, fetch, count, aggregate and exists. You can pass any subset of this ops to .cache() method even empty - to turn off caching. There is, however, a shortcut for the latter:=...). You can cache and invalidate result of a function the same way as a queryset. Cached results of the next function will be invalidated on any Article change, addition or deletion: from cacheops import cached_as @cached_as(Article, timeout=120) def article_stats(): return { 'tags': list(Article.objects.values('tag').annotate(Count('id'))) 'categories': list(Article.objects.values('category').annotate): qs = Article.objects.filter(category=category) @cached_as(qs, extra=count) def _articles_block(): articles = list(qs.filter(photo=True)[:count]) if len(articles) < count: articles += list(qs.filter(photo=False)[(). Class based views can also be cached: class NewsIndex(ListView): model = News news_index = cached_view_as(News)(NewsIndex.as_view()). There is also speed up batch jobs. Normally qs.update(…) doesn’t emit any events and thus doesn’t trigger invalidation. And there is no transparent and efficient way to do that: trying to act on conditions will invalidate too much if update conditions are orthogonal to many queries conditions, and to act on specific objects we will need to fetch all of them, which QuerySet.update() users generally try to avoid. In the case you actually want to perform the latter cacheops provides a shortcut: qs.invalidated_update(...) Note that all the updated objects are fetched twice, prior and post the update.’s safe against concurrent writes. Second, it’s invalidation is done as separate task, you’ll need to call this from crontab for that to work: /path/manage.py cleanfilecache /path/manage.py cleanfilecache /path/to/non-default/cache/dir None for timeout in @cached_as to use it’s default value for model. %}. Transactions Cacheops transparently supports transactions. This is implemented by following simple rules: - Once transaction is dirty (has changes) caching turns off. The reason is that the state of database at this point is only visible to current transaction and should not affect other users and vice versa. - Any invalidating calls are scheduled to run on the outer commit of transaction. - Savepoints and rollbacks are also handled appropriately. Mind that simple and file cache don’t turn itself off in transactions but work as usual. Dog-pile effect prevention There is optional locking mechanism to prevent several threads or processes simultaneously performing same heavy task. It works with @cached_as() and querysets: @cached_as(qs, lock=True) def heavy_func(...): # ... for item in qs.cache(lock=True): # ... It is also possible to specify lock: True in CACHEOPS setting but that would probably be a waste. Locking has no overhead on cache hit though. Multiple database support By default cacheops considers query result is same for same query, not depending on database queried. That could be changed with db_agnostic cache profile option: CACHEOPS = { 'some.model': {'ops': 'get', 'db_agnostic': False, 'timeout': ...} }. Keeping stats Cacheops provides cache_read and cache_invalidated signals for you to keep track. Cache read signal is emitted immediately after each cache lookup. Passed arguments are: sender - model class if queryset cache is fetched, func - decorated function and hit - fetch success as boolean value. Here is a simple stats implementation: from cacheops.signals import cache_read from statsd.defaults.django import statsd def stats_collector(sender, func, hit, **kwargs): event = 'hit' if hit else 'miss' statsd.incr('cacheops.%s' % event) cache_read.connect(stats_collector) Cache invalidation signal is emitted after object, model or global invalidation passing sender and obj_dict args. Note that during normal operation cacheops only uses object invalidation, calling it once for each model create/delete and twice for update: passing old and new object dictionary.. Use .prefetch_related() instead. - Mass updates don’t trigger invalidation by default. But see .invalidated_update(). - Sliced queries are invalidated as non-sliced ones. - Doesn’t work with .raw() and other sql queries. - Conditions on subqueries don’t affect invalidation. - Doesn’t work right with multi-table inheritance. Here 1, 2, 3, 5 are part of, see, however, .invalidated_update(). 8 is postponed until it will gain more interest or a champion willing to implement it emerges. All unsupported things could still be used easily enough with the help of @cached_as(). only desirable in the hottest places, not everywhere. requirements-test.txt. - Ensure you can run tests with ./run_tests.py. - Copy relevant models code to tests/models.py. - Go to tests/tests.py and paste code causing exception to IssueTests.test_{issue_number}. - Execute ./run_tests.py {issue_number} and see it failing. - Cut down model and test code until error disappears and make a step back. - Commit changes and make a pull request. TODO - faster .get() handling for simple cases such as get by pk/id, with simple key calculation - integrate previous one with prefetch_related() - shard cache between multiple red | 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/django-cacheops/
CC-MAIN-2020-40
refinedweb
1,195
51.24
Glyn Curt Milburn (born February 19, 1971) was an American football player. He is currently the General Manager and the Director of Player Personnel for the Austin Wranglers in the Arena Football League. He holds the National Football League record for Most All Purpose Yards Gained in a single Game with 404 on December 10, 1995. High School Milburn starred at California football powerhouse Santa Monica High School, where his coach [Tebb Kusserow] was quoted as saying that Milburn played little on offense as a junior. What Milburn learned from [Mark Jackson] is a tribute to Kusserow's seniors-first philosophy. Of Jackson, Milburn said: "He would tell me, `Next year will be your year. You're going to have to do it because they're going to be inexperienced and you have to show them. If you want to win, you have to do it yourself.' As an All-Ocean League cornerback and part-time running back as a junior, has rushed for 1,770 yards and scored 29 touchdowns in leading Santa Monica to a 7-0 record, the No. 2 spot in the Southern Conference poll and No. 6 in The Times' Southern Section rankings. Milburn was a prep all-America selection in football by SuperPrep and USA Today (second team)...Earned California 'Offensive Player of the Year' honors from the Los Angeles Times and 'Best of the West' recognition from the Long Beach Press Telegram...Set state prep records for rushing yards (2,718) and rushing touchdowns (38) as senior...Earned three letters in football (as a RB and CB) and track, plus one in basketball. Opposing coaches eventually placed him in the same class as Crespi's Russell White, considered by many to be the best running back in the state in 1988. Milburn averaged 202.5 yards per game rushing, White 169. His game-by-game yardage totals are 241, 157, 282, 383-which broke a 19-year-old school record-256, 242 and 209. That's an average of 252.9 a game. The 1,770-yard total was 264 better than the No. 2 rusher in the Southern Section, Sean Cheatham of Garden Grove Rancho Alamitos, who has played eight games. Also, Milburn averaged 8.6 yards a carry, has scored five touchdowns three times and has not scored fewer than three in his games. Milburn shredding the CIF rushing records by setting a Southern Section record with 2,718 yards rushing in a season, surpassing the 2,620 by Ryan Knight of Riverside Rubidoux in 1983. As a senior he led the "Samohi" (Santa Monica High School) Vikings to an 8-0 mark until the last game of the regular season when Hawthorne, led by junior quarterback and future USC wide receiver Curtis Conway an Ocean League rival of Santa Monica's, became one of the few teams to slow down Milburn and the only one to beat Santa Monica who fell to season record of 9-1. Milburn's final high school contest was against Santa Ana High in the CIF Southern Section Conference Quarterfinals losing 42-26 as Milburn hit Santa Ana for 251 yards in 30 carries, his ninth straight 200-yard game, and rushing touchdown No. 38, fourth best ever in the nation. Recruiting Process Glyn Milburn would have liked to get and education from Stanford and play football for Oklahoma. But in an effort to initially please his family the star running back from Santa Monica High School chose Oklahoma. While Glyn Milburn was at Oklahoma, he worried about the attention given to football players. He said that's one reason he transferred to Stanford, where football is not king. "I like blending into the student body, not sticking out as a football player," Milburn told Bay Area reporters. "People here aren't concerned with what you do. They're more interested in you as a person." Milburn said football players were, "put on a pedestal and made to believe you're something that you're really not" at Oklahoma. Milburn transferred to Stanford as the academic lure of the school was too good to pass up. College career Three-year starter and letterman (1990-92) for Stanford after beginning collegiate career at Oklahoma (1988). He totaled 25 touchdowns and 6,363 yards — 2,387 rushing, 1,512 receiving, 1,161 on punt returns and 1,303 on kickoff returns — between the two schools, including 6,049 at Stanford. He sat out redshirt season in 1989 following transfer. As a senior, ran for career-high 851 yards and eight touchdowns while averaging 4.8 yards per carry, caught 37 passes for 405 yards and two TDs, returned 15 kickoffs for 316 yards and averaged 17.3 yards on punt returns (34 for 589 yards). He garnered first-team All-America recognition from Associated Press as an "all-purpose player. In 1992, became first player in Stanford history to return three punts for TDs in one season, just one shy of NCAA record, and left with school's career record for punt return touchdowns (four). He was second-team all-conference choice in 1991 after averaging 137.6 all-purpose yards per game...Set school mark with 2,222 all-purpose yards in 1990. Milburn received honorable mention on all-America teams of AP, United Press International and Football News. Also a member of track team in first two years at Stanford and earned B.A. degree in public policy. NFL career 2000: Posted a season-high of 175 kickoff return yards on seven returns at Min (9/3), including a long of 34...Gave Bears great field position vs NO (10/8) by returning six kickoffs for 169 yards with a season-long of 38 yards and three punts for 33 yards with a season-long of 25...Recorded 80 return yards on three kickoffs with a long of 36 in win vs TB (11/19)...Totaled 135 return yards at NYJ (11/26) with 90 yards coming on three kickoff returns...Produced 100 return yards on four kickoffs in win vs NE (12/10)...Passed Dennis Gentry on Bears career kick-return yardage list with two returns for 42 yards at SF (12/17) giving him 4,357 over his Chicago career...Returned four kickoffs for 87 yards in season-finale at Det (12/24). Games played-started: 16-0. 1999: Garnered second career Pro Bowl bid, the first Bear to be honored since 1994...Named first-team all-Pro as a kick returner by Associated Press and Football Digest...Earned second-team honors from College & Pro Football Newsweekly...Selected to the Pro Football Weekly and Football News all-NFC Team and The Sporting News all-Pro Team as punt returner...Led Bears with 1,426 yards on 61 kickoff returns and 346 yards on 30 punt returns...Rated 2nd in NFC with 11.5 yard punt return average and 8th in NFC with 23.4 yard KOR average...Also ranked fourth on team with 102 rushing yards on 16 attempts and sixth with 20 receptions for 151 yards...Totaled 2,025 all-purpose yards, the second-highest total in the League...Joined Walter Payton and Gale Sayers as only Bears in team history to eclipse 2,000 all-purpose yards in a season...Recorded season-high 54-yard punt return vs Sea (9/19)...Compiled season-best 157 KOR yards (39.3 avg.) at Oak (9/26), including season-long 93-yard return...Equaled career-high with seven kickoff returns (130 yards) at Was (10/31) while catching six passes for 59 yards...Broke free for 49-yard touchdown run on draw play at GB (11/7), the longest rushing TD of career...Earned sole start of season in five-receiver set vs Min (11/14)...Returned five kickoffs for 144 yards (28.8 avg.) vs GB (12/5). 1998: Set four single-game career-highs including most punt return yards (106), long punt return (93), most kickoff return yards (202) and longest kickoff return (94)...Only kick returner in NFL to finish among Conference top five in both punt and kickoff returns...Ranked 4th in NFC (8th in NFL) in punt returns with 11.6 yard average...Finished 5th in NFC (10th in NFL) in kickoff returns with 25.0 yard average...Returned two kickoffs and a punt for touchdowns, career firsts for each...First Bear to return a kickoff and punt for a TD in the same season since Ike Hill (1973)...Voted Pro Bowl alternate as kick returner...Returned kickoff 88 yards for first career touchdown return in Season Opener vs Jax (9/6); finished afternoon with 197 yards on five kick returns...Returned two punts for 106 yards including 93-yarder for a touchdown, the first of his career, at TB (9/20)...Set up game-winning drive with 47-yard kickoff return in fourth quarter at Ten (10/25)...Returned six kickoffs for 202 yards including career-long 94-yard touchdown return at GB (12/13)...Season-high two rushes for three yards and two catches for 19 yards vs Balt (12/20)...Signed three-year contract extension during middle of season (11/2). 1997: Played in all 16 regular-season games with one start for Detroit...Began year as club's third receiver, but became solely a return man later in season...Named an alternate to NFC Pro Bowl squad as kick returner...Finished season with five receptions for 77 yards (15.4 avg.)...Ranked sixth in NFC in KOR, averaging 23.9 yards on 55 runbacks, while finishing 10th in the conference in punt returns (47 for 433 yards)...Caught season-long 43-yard pass in opener vs Atl (8/31)...Season-high two receptions vs TB (9/7)...Lone start of season came at NO (9/21) as Lions opened game with three receivers...Season-long 40-yard punt return at TB (10/12)...Season-high 189 KOR yards (on five attempts) vs Chi (11/27)...Returned five kickoffs for 140 yards (28.0 avg.) in Wild Card playoff loss at TB (12/28). 1996: Served primarily as kick returner while playing in all 16 games in first season with Detroit after being acquired in off-season trade...Set club single-season record for most kickoff return yards (1,627) and most kickoff returns (64)...Finished fourth in NFC (fifth in NFL) with 25.4-yard kickoff return average...Had longest punt return of season (33 yards) vs Atl (10/6), setting up Lions' first TD...Season-long 65-yard KOR vs NYG (10/27); also averaged season-high 35.8 yards per return in game...Compiled season-high 148 kickoff return yards on five runbacks (29.6 avg.) at SD (11/11)...Joined Lions in April 12 trade with Denver. 1995: Named to AFC Pro Bowl squad as kick return specialist in final season with Broncos...Saw action in all 16 games as a return man, wide receiver and tailback...Led NFL with 27-yard kickoff return average, returning 47 for 1,269 yards...Also averaged 11.4 yards on 31 punt returns, third in AFC and fifth in NFL...Along with the Redskins' Brian Mitchell, one of only two players to rank among top five in the NFL in both kickoff and punt return average...Named first-team all-Pro as kick returner by The Sporting News...Second-team all-Pro honors from Associated Press and College & Pro Football Newsweekly...All-AFC pick of Pro Football Weekly and Football News...Earned AFC 'Special Teams Player of the Week' honors for performance against SD (11/19), when he totaled 177 yards on four kickoff returns (44.3 avg.)...Opened game against Chargers with 86-yard kickoff return...Recorded 178 KOR yards (seven returns) at Hou (11/26)...Set NFL record with 404 total yards vs Sea (12/10) as he rushed career-high 18 times for career-best 131 yards (7.3 avg.), his only 100-yard rushing performance as a pro...Also caught five passes for 45 yards, returned five punts for season-high 95 yards and brought back five kicks for 133 yards (26.6 avg)...Accounted for 193 total yards at Phi (11/12), when he had five kickoff returns for 140 yards (28.0 avg.), caught four passes for 23 yards and rushed twice for 30 yards...Made only start of season at tailback at KC (12/17), replacing injured Terrell Davis, and totaled 114 all-purpose yards. 1994: Played in all 16 games with three starts...Compiled 1,818 all-purpose yards, including 201 rushing on 58 attempts, 549 receiving on career-high 77 receptions, 793 yards on 37 kickoff returns and 379 yards on 41 punt returns...77 catches were most by an NFL running back in '94 and most ever in one season by a Broncos RB...Finished sixth in AFC with 9.2-yard punt return average...Set career-highs for receptions (nine) and receiving yards (85) vs LA Rai (9/18)...Posted 202 total yards and scored on 20-yard reception at LA Rams (11/6)...Scored first rushing TD of pro career at SF (12/17). 1993: Played in all 16 games, starting two...Put together solid rookie season, gaining 1,125 total yards...Rushed for 231 yards on 52 attempts, caught 38 passes for 300 yards and three TDs, averaged 10.6 yards on 40 punt returns (fifth in AFC and eighth in NFL) and returned 12 kickoffs for 188 yards...Accounted for 148 all-purpose yards in first NFL game at NYJ (9/5), including career-long 50-yard reception, a 36-yard punt return and a 25-yard touchdown catch...Caught season-high eight passes at KC (9/20)...Gained season-high 173 total yards vs Min (11/14) and 129 all-purpose yards in postseason vs LA Rai (1/9/94)...Originally drafted in the second round (43rd overall) by Denver. Signed by the Chargers as a free agent on Nov. 15, 2001, Glyn Milburn is one of the most prolific kick returners in NFL history and a veteran of nine NFL seasons, including three in Denver (1993-95), two in Detroit (1996-97) and the last four in Chicago (1998–2001). He returned six kickoffs for 152 yards (25.3 avg.) and four punts for 33 yards (8.3 avg.). He also caught three passes for nine yards while adding three carries for three yards. Since starting his NFL career in Denver as a second round draft pick (43rd overall) in 1993, Milburn has played in all 16 regular season games in every season up until this year. Including the 2001 season before he signed with the Chargers, his career totals included nine starts in 132 games played, 407 kickoff returns for 9,788 yards (24.0 avg.) and two touchdowns, and 287 punt returns for 2,845 yards (9.9 avg.) and one touchdown. When he signed with the Chargers, Milburn ranked third on the NFL's all-time kickoff return yardage list with 9,788 yards behind Brian Mitchell (11,304 as of Nov. 15, 2001) and Mel Gray (10,250). Prior to joining the Chargers, Milburn had caught 170 passes for 1,322 yards and six touchdowns, while adding 183 carries for 817 yards and two touchdowns. In all, Milburn had amassed 14,772 combined yards on kickoff returns, punt returns, rushing and receiving before signing with San Diego. Milburn played in four games with the Bears in 2001 before being released on Oct. 17, 2001. Personal life He is a second cousin to Rod Milburn, the 1972 Olympic Games 100-meter hurdles champion. Participated in the Presidential Inauguration Committee in 1996, his efforts included on-site work the day that President Clinton was sworn in for second term...Community oriented, among the groups he has been involved with are Special Olympics, the American Diabetes Foundation, United Way, Kiwanis Club, Optimists Club, Athletes in Action Kappa Alpha Psi and Champions for Christ. This entry is from Wikipedia, the leading user-contributed encyclopedia. It may not have been reviewed by professional editors (see full disclaimer)
http://www.answers.com/topic/glyn-milburn
crawl-002
refinedweb
2,697
74.08
Please avoid using namespace spirv as we can pull in symbols of the same name (like ModuleOp, etc.). (We are using it in the codebase but it should be fixed actually.) s/nextConflictID/nextFreeID/ or something like that? nextConflictID reads to me that it's an ID that triggers confliction. :) No need to use the const: in mlir ir constructs normally don't require const modifier. See Have a limit over nextFreeID to avoid infinite loop? It's a bit arbitrary; but I'd assume 2^20 might be a good number for now. Nit: by ++nextFreeID, it's actually lastUsedID here. ;-P So I'd expect nextFreeID++ here. (You can set the intial value of nextFreeID as 1 if wanting to be 1 based.) Indeed. I renamed to lastUsedID (laziest solution that works 😁 ) This appends the number to the symbol again (like _123456)? I'd assume we want to mutate the number suffix? can directly return possible? I feel better having a single exit point here 😁 . Please let me know if you have a strong opinion against this. s/globalVarOp/op/ (given this is not for global variable specifically) if (!...) return WalkResult::advance(); MLIR typically prefers early exit if possible. return op.emitError(...) here. Also should we let the function to report an error properly? Silently ignoring the issue seems not good. module.emitError. combinedModule is still something under construction. What about going through all the symbols in the cloned module and renaming them in one pass? I think you can do something like for (auto op: module.getBlock().without_terminator()) { if (auto symbolOp = dyn_cast<SymbolOpInterface>(op)) ... } This way we avoids multiple iterations. s/dyn_cast/isa/ You can use moduleClone.getBlock().without_terminator() to avoid checking the module end op. This can also be guarded by && symRenameListener? Didn't do this to make sure the management of symNameToModuleMap is properly handled. I can also guard all code that manages the map with the same check but this is cleaner. but _thought_ this _would be_ cleaner. No worries! I changed it before landing, plus a few other tweaks. :) But I don't have full visibility into what your planned next batch of code so I may very well misunderstand things. If that's the case, please just feel free to change it back. :)
https://reviews.llvm.org/differential/changeset/?ref=2234079
CC-MAIN-2021-17
refinedweb
381
68.97
My intuitive answer is yes, and the implementation could also be used by a "printf". And it might be easy to overload for user-defined types. Has anyone ever attempted this before? I believe you can't - the main problem would be how would you get the result out of the function. When you return a string, you can actually return (1) a new-ed buffer (or malloced which is just as bad), (2) a static buffer or (3) fill some other buffer. (1) is quite clearly disallowed (2) is against the contract of sprintf (ie. a non- constexpr sprintf mustn't do that either) (3) assignment is not possible in constexpr. If you just want "something like sprintf", regardless of possibly inconvenient usage, something eg. with interface like this would work: my_sprintf<my_string<'%', 'd', '%', 'c'>, my_data<int, 42>, my_data<char, 'l'> >::string_value On second thought, you could avoid actually computing the string and just store the parameters of the sprintf invocation for later. The user would then call a non- constexpr method of that intermediate result if he wanted to get a char*, but a single character could be obtained by a constexpr function. That would be an unorthodox version of sprintf, I'm not sure if it would count at all.
https://codedump.io/share/a1k2abQSYPur/1/is-constexpr-quotvnsprintfquot-possible
CC-MAIN-2017-04
refinedweb
213
61.06
- ASP.NET: - Overview - ASP.NET Samples Most people are used to relational databases, and they tend to overlook other data storage options when they're designing a cloud app. The result can be suboptimal performance, high expenses, or worse, because NoSQL (non-relational) databases can handle some tasks more efficiently than relational databases. When customers ask us for help resolving a critical data storage problem, it’s often because they have a relational database where one of the NoSQL options would have worked better. In those situations the customer would have been better off if they had implemented the NoSQL solution before deploying the app to production. On the other hand, it would also be a mistake to assume that a NoSQL database can do everything well or well enough. There is no single best data management choice for all data storage tasks; different data management solutions are optimized for different tasks. Most real-world cloud apps have a variety of data storage requirements and are often served best by a combination of multiple data storage solutions. The purpose of this chapter is to give you a broader sense of the data storage options available to a cloud app, and some basic guidance on how to choose the ones that fit your scenario. It's best to be aware of the options available to you and think about their strengths and weaknesses before you develop an application. Changing data storage options in a production app can be extremely difficult, like having to change a jet engine while the plane is in flight. Data storage options on Azure The cloud makes it relatively easy to use a variety of relational and NoSQL data stores. Here are some of the data storage platforms that you can use in Azure. The table shows four types of NoSQL databases: Key/value databases store a single serialized object for each key value. They’re good for storing large volumes of data where you want to get one item for a given key value and you don’t have to query based on other properties of the item. Azure Blob storage is a key/value database that functions like file storage in the cloud, with key values that correspond to folder and file names. You retrieve a file by its folder and file name, not by searching for values in the file contents. Azure Table storage is also a key/value database. Each value is called an entity (similar to a row, identified by a partition key and row key) and contains multiple properties (similar to columns, but not all entities in a table have to share the same columns). Querying on columns other than the key is extremely inefficient and should be avoided. For example, you can store user profile data, with one partition storing information about a single user. You could store data such as user name, password hash, birth date, and so forth, in separate properties of one entity or in separate entities in the same partition. But you wouldn't want to query for all users with a given range of birth dates, and you can't execute a join query between your profile table and another table. Table storage is more scalable and less expensive than a relational database, but it doesn't enable complex queries or joins. Document databases are key/value databases in which the values are documents. "Document" here isn't used in the sense of a Word or Excel document but means a collection of named fields and values, any of which could be a child document. For example, in an order history table an order document might have order number, order date, and customer fields; and the customer field might have name and address fields. The database encodes field data in a format such as XML, YAML, JSON, or BSON; or it can use plain text. One feature that sets document databases apart from key/value databases is the ability to query on non-key fields and define secondary indexes to make querying more efficient. This ability makes a document database more suitable for applications that need to retrieve data based on criteria more complex than the value of the document key. For example, in a sales order history document database you could query on various fields such as product ID, customer ID, customer name, and so forth. MongoDB is a popular document database. Column-family databases are key/value data stores that enable you to structure data storage into collections of related columns called column families. For example, a census database might have one group of columns for a person's name (first, middle, last), one group for the person's address, and one group for the person's profile information (DOB, gender, etc.). The database can then store each column family in a separate partition while keeping all of the data for one person related to the same key. You can then read all profile information without having to read through all of the name and address information as well. Cassandra is a popular column-family database. Graph databases store information as a collection of objects and relationships. The purpose of a graph database is to enable an application to efficiently perform queries that traverse the network of objects and the relationships between them. For example, the objects might be employees in a human resources database, and you might want to facilitate queries such as "find all employees who directly or indirectly work for Scott." Neo4j is a popular graph database. Compared to relational databases, the NoSQL options offer far greater scalability and cost-effectiveness for storage and analysis of unstructured data. The tradeoff is that they don't provide the rich queryability and robust data integrity capabilities of relational databases. NoSQL would work well for IIS log data, which involves high volume with no need for join queries. NoSQL would not work so well for banking transactions, which requires absolute data integrity and involves many relationships to other account-related data. There is also a newer category of database platform called NewSQL that combines the scalability of a NoSQL database with the queryability and transactional integrity of a relational database. NewSQL databases are designed for distributed storage and query processing, which is often hard to implement in "OldSQL" databases. NuoDB is an example of a NewSQL database that can be used on Azure. Hadoop and MapReduce The high volumes of data that you can store in NoSQL databases may be difficult to analyze efficiently in a timely manner. To do that you can use a framework like Hadoop which implements MapReduce functionality. Essentially what a MapReduce process does is the following: - Limit the size of the data that needs to be processed by selecting out of the data store only the data you actually need to analyze. For example, you want to know the makeup of your user base by birth year, so you select only birth years out of your user profile data store. - Break down the data into parts and send them to different computers for processing. Computer A calculates the number of people with 1950-1959 dates, computer B does 1960-1969, etc. This group of computers is called a Hadoop cluster. - Put the results of each part back together after the processing on the parts is done. You now have a relatively short list of how many people for each birth year and the task of calculating percentages in this overall list is manageable. On Azure, HDInsight enables you to process, analyze, and gain new insights from big data using the power of Hadoop. For example, you could use it to analyze web server logs: - Enable web server logging to your storage account. This sets up Azure to write logs to the Blob Service for every HTTP request to your application. The Blob Service is basically cloud file storage, and it integrates nicely with HDInsight. - As the app gets traffic, web server IIS logs are written to Blob storage. - In the portal, click New - Data Services - HDInsight - Quick Create, and specify an HDInsight cluster name, cluster size (number of HDInsight cluster data nodes), and a user name and password for the HDInsight cluster. You can now set up MapReduce jobs to analyze your logs and get answers to questions such as: - What times of day does my app get the most or least traffic? - What countries is my traffic coming from? - What is the average neighborhood income of the areas my traffic comes from. (There's a public dataset that gives you neighborhood income by IP address, and you can match that against IP address in the web server logs.) - How does neighborhood income correlate to specific pages or products in the site? You could then use the answers to questions like these to target ads based on the likelihood a customer would be interested in or likely to buy a particular product. As explained in the Automate Everything chapter, most functions that you can do in the portal can be automated, and that includes setting up and executing HDInsight analysis jobs. A typical HDInsight script might contain the following steps: - Provision an HDInsight cluster and link it to your storage account for Blob storage input. - Upload the MapReduce job executables (.jar or .exe files) to the HDInsight cluster. - Submit a MapReduce that stores the output data to Blob storage. - Wait for the job to complete. - Delete the HDInsight cluster. - Access the output from Blob storage. By running a script that does all this, you minimize the amount of time that the HDInsight cluster is provisioned, which minimizes your costs. Platform as a Service (PaaS) versus Infrastructure as a Service (IaaS) The data storage options listed earlier include both Platform-as-a-Service (PaaS) and Infrastructure-as-a-Service (IaaS) solutions. PaaS means that we manage the hardware and software infrastructure and you just use the service. SQL Database is a PaaS feature of Azure. You ask for databases, and behind the scenes Azure sets up and configures the VMs and sets up the databases on them. You don’t have direct access to the VMs and don’t have to manage them. IaaS means that you set up, configure, and manage VMs that run in our data center infrastructure, and you put whatever you want on them. We provide a gallery of pre-configured VM images for common VM configurations. For example, you can install pre-configured VM images for Windows Server 2008, Windows Server 2012, BizTalk Server, Oracle WebLogic Server, Oracle Database, etc. PaaS data solutions that Azure offers include: - Azure SQL Database (formerly known as SQL Azure). A cloud relational database based on SQL Server. - Azure Table storage. A key/value NoSQL database. - Azure Blob storage. File storage in the cloud. For IaaS, you can run anything you can load onto a VM, for example: - Relational databases such as SQL Server, Oracle, MySQL, SQL Compact, SQLite, or Postgres. - Key/value data stores such as Memcached, Redis, Cassandra, and Riak. - Column data stores such as HBase. - Document databases such as MongoDB, RavenDB, and CouchDB. - Graph databases such as Neo4j. The IaaS option gives you almost unlimited data storage options, and many of them are especially easy to use because you can create VMs using preconfigured images. For example, in the management portal go to Virtual Machines, click the Images tab, and click Browse VM Depot. You then see a list of hundreds of preconfigured VM images, and you can create a VM from an image that has a database management system preinstalled, such as MongoDB, Neo4J, Redis, Cassandra, or CouchDB: Azure makes IaaS data storage options as easy to use as possible, but the PaaS offerings have many advantages that make them more cost-effective and practical for many scenarios: - You don’t have to create VMs, you just use the portal or a script to set up a data store. If you want a 200 terabyte data store, you can just click a button or run a command, and in seconds it’s ready for you to use. - You don’t have to manage or patch the VMs used by the service; Microsoft does that for you automatically. - You don’t have to worry about setting up infrastructure for scaling or high availability; Microsoft handles all that for you. - You don’t have to buy licenses; license fees are included in the service fees. - You only pay for what you use. PaaS data storage options in Azure include offerings by third-party providers. For example, you can choose the MongoLab Add-On from the Azure Store to provision a MongoDB database as a service. Choosing a data storage option No one approach is right for all scenarios. If anyone says that this technology is the answer, the first thing to ask is "What is the question?", because different solutions are optimized for different things. There are definite advantages to the relational model; that’s why it’s been around for so long. But there are also down-sides to SQL that can be addressed with a NoSQL solution. Often what we see work best is a compositional approach, where you use SQL and NoSQL in a single solution. Even when people say they’re embracing NoSQL, if you drill into what they’re doing you often find that they’re using several different NoSQL frameworks: they’re using CouchDB, and Redis, and Riak for different things. Even Facebook, which uses NoSQL extensively, uses different NoSQL frameworks for different parts of the service. The flexibility to mix and match data storage approaches is one of the things that’s nice about the cloud, because it’s easy to use multiple data solutions and integrate them in a single app. Here are some questions to think about when you’re choosing an approach: What we generally recommend is know the answer to the questions in each of these categories before you choose your data storage solutions. In addition, your workload might have specific requirements that some platforms can support better than others. For example: - Does your application require audit capabilities? - What are your data longevity requirements -- do you require automated archival or purging capabilities? - Do you have specialized security needs? For example, the data includes PII (personally identifiable information) but you have to be able to make sure that PII is excluded from query results. - If you have some data that can't be stored in the cloud for regulatory or technological reasons, you might need a cloud data storage platform that facilitates integrating with your on-premises storage. Demo – using SQL Database in Azure The Fix It app uses a relational database to store tasks. The environment creation Windows PowerShell script shown in the Automate Everything chapter creates two SQL Database instances. You can see these in the portal by clicking the SQL Databases tab. It's also easy to create databases by using the portal. Click New -- Data Services -- SQL Database -- Quick Create, enter a database name, choose a server you already have in your account or create a new one, and click Create SQL Database. Wait several seconds, and you have a database in Azure ready for you to use. So Azure does in a few seconds what it may take you a day or a week or longer to accomplish in the on-premises environment. And since you can just as easily create databases automatically in a script or by using a management API, you can dynamically scale out by spreading your data across multiple databases, so long as your application has been programmed for that. databases, so long as your application has been programmed for that. This is an example of our Platform-as-a-Service model. You don’t have to manage the servers, we do it. You don’t have to worry about backups, we do it. It’s running in high availability – the data in the database is replicated across three servers automatically. If a machine dies, we automatically fail over and you lose no data. The server is patched regularly, you don't need to worry about that. Click a button and you get the exact connection string you need and can immediately start using the new database. The Dashboard shows you connection history and amount of storage used. You can manage databases in the portal or by using SQL Server tools you're already familiar with, including SQL Server Management Studio (SSMS) and the Visual Studio tools SQL Server Object Explorer (SSOX) and Server Explorer. Another nice thing is the pricing model. You can start development with a free 20 MB database, and a production database starts at about $5 per month. You pay only for the amount of data you actually store in the database, not the maximum capacity. You don’t have to buy a license. SQL Database is easy to scale. For the Fix It app, the database we create in our automation script is capped at 1 gig. If you want to scale it up to 150 gig, you can just go into the portal and change that setting, or execute a REST API command, and in seconds you have a 150 gig database that you can deploy data into. That’s the power of the cloud to stand up infrastructure quickly and easily and start using it immediately. The Fix It app uses two SQL databases, one for membership (authentication and authorization) and one for data, and this is all you have to do to provision it and scale it. You saw earlier how to provision the databases through Windows PowerShell scripts, and now you’ve also seen how easy it is to do in the portal. Entity Framework versus direct database access using ADO.NET The Fix It app accesses these databases by using the Entity Framework, Microsoft's recommended ORM (object-relational mapper) for .NET applications. An ORM is a great tool that facilitates developer productivity, but productivity comes at the expense of degraded performance in some scenarios. In a real-world cloud app you won't be making a choice between using EF or using ADO.NET directly -- you'll use both. Most of the time when you're writing code that works with the database, getting maximum performance is not critical and you can take advantage of the simplified coding and testing that you get with the Entity Framework. In situations where the EF overhead would cause unacceptable performance, you can write and execute your own queries using ADO.NET, ideally by calling stored procedures. Whatever method you use to access the database, you want to minimize "chattiness" as much as possible. In other words, if you can get all the data you need in one larger query result set rather than dozens or hundreds of smaller ones, that's usually preferable. For example, if you need to list students and the courses they're enrolled in, it's usually better to get all of the data in one join query rather than getting the students in one query and executing separate queries for each student's courses. SQL databases and the Entity Framework in the Fix It app In the Fix It app the FixItContext class, which derives from the Entity Framework DbContext class, identifies the database and specifies the tables in the database. The context specifies an entity set (table) for tasks, and the code passes in to the context the connection string name. That name refers to a connection string that is defined in the Web.config file. public class MyFixItContext : DbContext { public MyFixItContext() : base("name=appdb") { } public DbSet<MyFixIt.Persistence.FixItTask> FixItTasks { get; set; } } The connection string in the Web.config file is named appdb (here pointing to the local development database): <connectionStrings> <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-MyFixIt-20130604091232_4;Integrated Security=True" providerName="System.Data.SqlClient" /> <add name="appdb" connectionString="Data Source=(localdb)\v11.0; Initial Catalog=MyFixItContext-20130604091609_11;Integrated Security=True; MultipleActiveResultSets=True" providerName="System.Data.SqlClient" /> </connectionStrings> The Entity Framework creates a FixItTasks table based on the properties included in the FixItTask entity class. This is a simple POCO (Plain Old CLR Object) class, which means it doesn’t inherit from or have any dependencies on the Entity Framework. But Entity Framework knows how to create a table based on it and execute CRUD (create-read-update-delete) operations with it. public class FixItTask { public int FixItTaskId { get; set; } public string CreatedBy { get; set; } [Required] public string Owner { get; set; } [Required] public string Title { get; set; } public string Notes { get; set; } public string PhotoUrl { get; set; } public bool IsDone { get; set; } } The Fix It app includes a repository interface that it uses for CRUD operations working with the data store. public interface IFixItTaskRepository { Task<List<FixItTask>> FindOpenTasksByOwnerAsync(string userName); Task<List<FixItTask>> FindTasksByCreatorAsync(string userName); Task<MyFixIt.Persistence.FixItTask> FindTaskByIdAsync(int id); Task CreateAsync(FixItTask taskToAdd); Task UpdateAsync(FixItTask taskToSave); Task DeleteAsync(int id); } Notice that the repository methods are all async, so all data access can be done in a completely asynchronous way. The repository implementation calls Entity Framework async methods to work with the data, including LINQ queries as well as for insert, update, and delete operations. Here's an example of the code for looking up a Fix It task. public async Task<FixItTask> FindTaskByIdAsync(int id) { FixItTask fixItTask = null; Stopwatch timespan = Stopwatch.StartNew(); try { fixItTask = await db.FixItTasks.FindAsync(id); timespan.Stop(); log.TraceApi("SQL Database", "FixItTaskRepository.FindTaskByIdAsync", timespan.Elapsed, "id={0}", id); } catch(Exception e) { log.Error(e, "Error in FixItTaskRepository.FindTaskByIdAsynx(id={0})", id); } return fixItTask; } You’ll notice there’s also some timing and error logging code here, we’ll look at that later in the Monitoring and Telemetry chapter. Choosing SQL Database (PaaS) versus SQL Server in a VM (IaaS) in Azure A nice thing about SQL Server and Azure SQL Database is that the core programming model for both of them is identical. You can use most of the same skills in both environments. You can even use a SQL Server database in development and a SQL Database instance in the cloud, which is how the Fix It app is set up. As an alternative, you can run the same SQL Server in the cloud that you run on-premises by installing it on IaaS VMs. For some legacy applications, running SQL Server in a VM might be a better solution. Because a SQL Server database runs on a dedicated VM, it has more resources available to it than a SQL Database database that runs on a shared server. That means a SQL Server database can be larger and still perform well. In general, the smaller the database size and table size, the better the use case works for SQL Database (PaaS). Here are some guidelines on how to choose between the two models. If you want to use SQL Server in a VM, you can use your own SQL Server license, or you can pay for one by the hour. For example, in the portal or via the REST API you can create a new VM using a SQL Server image. When you create a VM with a SQL Server image, we pro-rate the SQL Server license cost by the hour based on your usage of the VM. If you have a project that’s only going to run for a couple of months, it’s cheaper to pay by the hour. If you think your project is going to last for years, it’s cheaper to buy the license the way you normally do. Summary Cloud computing makes it practical to mix and match data storage approaches to best fit the needs of your application. If you’re building a new application, think carefully about the questions listed here in order to pick approaches that will continue to work well when your application grows. The next chapter will explain some partitioning strategies that you can use to combine multiple data storage approaches. Resources For more information, see the following resources. Choosing a database platform: - Data Access for Highly-Scalable Solutions: Using SQL, NoSQL, and Polyglot Persistence. E-book by Microsoft Patterns and Practices that goes in depth into the different kinds of data stores available for cloud applications. - Microsoft Patterns and Practices - Azure Guidance. See Data Consistency Primer, Data Replication and Synchronization Guidance, Index Table pattern, Materialized View pattern. - BASE: An Acid Alternative. Article about tradeoffs between data consistency and scalability. - Seven Databases in Seven Weeks: A Guide to Modern Databases and the NoSQL Movement. Book by Eric Redmond and Jim R. Wilson. Highly recommended for introducing yourself to the range of data storage platforms available today. Choosing between SQL Server and SQL Database: - Premium Preview for SQL Database Guidance. An introduction to SQL Database Premium, and guidance on when to choose it over the SQL Database Web and Business editions. - Guidelines and Limitations (Azure SQL Database). Portal page that links to documentation about limitations of SQL Database, including one that focuses on SQL Server features that SQL Database doesn't support. - SQL Server in Azure Virtual Machines. Portal page that links to documentation about running SQL Server in Azure. - Scott Guthrie explains SQL Databases in Azure. 6-minute video introduction to SQL Database by Scott Guthrie. - Application Patterns and Development Strategies for SQL Server in Azure Virtual Machines. Using Entity Framework and SQL Database in an ASP.NET Web app - Getting Started with EF 6 using MVC 5. Nine-part tutorial series that walks you through building an MVC app that uses EF and deploys the database to Azure and SQL Database. - ASP.NET Web Deployment using Visual Studio. Twelve-part tutorial series that goes into more depth about how to deploy a database by using EF Code First. - Deploy a Secure ASP.NET MVC 5 app with Membership, OAuth, and SQL Database to an Azure Web Site. Step-by-step tutorial that walks you through creating a web app that uses authentication, stores application tables in the membership database, modifies the database schema, and deploys the app to Azure. - ASP.NET Data Access Content Map. Links to resources for working with EF and SQL Database. Using MongoDB on Azure: - MongoLab - MongoDB on Azure. Portal page for documentation about running MongoDB on Azure. - Create an Azure web site that connects to MongoDB running on a virtual machine in Azure. Step-by-step tutorial that shows how to use a MongoDB database in an ASP.NET web application. HDInsight (Hadoop on Azure): - HDInsight. Portal to HDInsight documentation on the Azure website. - Hadoop and HDInsight: Big Data in Azure. MSDN Magazine article by Bruno Terkaly and Ricardo Villalobos, introducing Hadoop on Azure. - Microsoft Patterns and Practices - Azure Guidance. See MapReduce pattern. This article was originally created on June 12, 2014
http://www.asp.net/aspnet/overview/developing-apps-with-windows-azure/building-real-world-cloud-apps-with-windows-azure/data-storage-options
CC-MAIN-2015-48
refinedweb
4,486
53.51
Aggregate Statistics by Auto Scaling Group You can aggregate statistics for the EC2 instances in an Auto Scaling group. Amazon CloudWatch cannot aggregate data across regions. Metrics are completely separate between regions. This example shows you how to get. Choose the EC2 namespace and then choose By Auto Scaling Group. Select the row for the DiskWriteBytes metric and the specific Auto Scaling group, which displays a graph for the metric for the instances in the Auto Scaling group. To change the name of the graph, choose the pencil icon. To change the time range, select one of the predefined values or choose custom. To change the statistic, choose the Graphed metrics tab. Choose the column heading or an individual value, and then choose one of the statistics or predefined percentiles, or specify a custom percentile (for example, p95.45). To change the period, choose the Graphed metrics tab. Choose the column heading or an individual value, and then choose a different value. To get DiskWriteBytes for the instances in an Auto Scaling group using the AWS CLI Use the get-metric-statistics command as follows: Copy aws cloudwatch get-metric-statistics --namespace AWS/EC2 --metric-name DiskWriteBytes --dimensions Name=AutoScalingGroupName,Value= my-asg--statistics "Sum" "SampleCount" \ --start-time 2016-10-16T23:18:00--end-time 2016-10-18T23:18:00--period 360 The following is example output: Copy { "Datapoints": [ { "SampleCount": 18.0, "Timestamp": "2016-10-19T21:36:00Z", "Sum": 0.0, "Unit": "Bytes" }, { "SampleCount": 5.0, "Timestamp": "2016-10-19T21:42:00Z", "Sum": 0.0, "Unit": "Bytes" } ], "Label": "DiskWriteBytes" }
http://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/GetMetricAutoScalingGroup.html
CC-MAIN-2017-34
refinedweb
259
58.08
List is a collection class in C# and .NET. Code examples in this article show how to work with List<T> class in C#. Also code examples on C# Lists and C# Collections. Introduction A List is one of the generic collection classes in the "System.Collection.Generic" namespace. There are several generic collection classes in the System.Collection.Generic namespace that includes the following: A List class can be used to create a collection of any type. For example, we can create a list of Integers, strings and even any complex types. Why to use a List I am taking an example to store data in an array and see what the problem is in storing the data in the array. Example 2 - Using List NoteYou can also use for or while loop to access all the items. Different Properties of a "List" Different Methods of a "List" Example View All
https://www.c-sharpcorner.com/UploadFile/75a48f/list-collection-class-in-C-Sharp/
CC-MAIN-2019-26
refinedweb
152
65.01
How to detect retina display Hello, Working on the project I found that I need to detect what type of the screen have device that running my code. And made this simple detector. Probaby it is not something big, but for me this is first bites of code that uses objcbindings. Hope you will find it useful Grab the gist isretina.pyor code from objc_util import * us = ObjCClass('UIScreen') if us.mainScreen().scale() == 2.0: print('Retina') elif us.mainScreen().scale() == 3.0: print('iPhone Plus') else: print('Non retina') You could also use scene.get_screen_scale()for this (which is basically just a wrapper around [[UIScreen mainScreen] scale) – nothing wrong with your code, just wanted to point out that it's not necessary to delve into ObjC for this. from objc_util import ObjCClass scale = ObjCClass('UIScreen').mainScreen().scale() print({2: 'Retina', 3: 'iPhone Plus'}.get(scale, 'Non retina'))
https://forum.omz-software.com/topic/3251/how-to-detect-retina-display
CC-MAIN-2020-40
refinedweb
148
59.7
Opened 10 years ago Closed 10 years ago #3593 closed bug (fixed) strtod doesn't support "INF" input Description #include <stdio.h> #include <stdlib.h> int main() { char * endptr; double d = strtod("inf", &endptr); fprintf(stderr, "%f '%s'\n", d, endptr); return 0; }:[[br]] The expected form of the subject sequence is an optional plus or minus sign, then one of the following: [...] * One of INF or INFINITY, ignoring case * One of NAN or NAN(n-char-sequenceopt), ignoring case in the NAN part, where:[...] Change History (3) comment:1 by , 10 years ago comment:2 by , 10 years ago Additionaly, strtod failed with this testcase #include <stdio.h> #include <stdlib.h> int main() { double d = strtod("+8E153", NULL); printf("%.10e\n", d); return 0; } Linux result: 8.0000000000e+153 Haiku result: 7.9999999873e+153 The testcase is inspired by the results of running "python test_float.py" for the floating point test. Both python 2.6 on Haiku-gcc4 and python 2.7 on Haiku-gcc2 we print the following message - [...] self.assertEqual(v, eval(repr(v))) AssertionError: 7.9999999872500254e+153 != 7.9999999745000492e+153 The test which errors out in python is equivalent to x = "+8E153" v = eval(x) assert v == eval(repr(v)) So it looks like #3308 's test_float.py issue is caused by problems with strtod(). Our implementation comes from FreeBSD. The following is the last revision of their stdtod.c file; in later revisions, FreeBSD uses gdtoa ( link to NetBSD gdtoa as I couldn't find an online viewable FreeBSD link ): However, importing rev 112256 of FreeBSD's strtod.c into the Haiku tree and doing a full rebuild doesn't help. The link is
https://dev.haiku-os.org/ticket/3593
CC-MAIN-2019-39
refinedweb
279
68.97
An alternative Python wrapper for OpenBR which uses the Command Line Tool. import pyopenbr result = pyopenbr.run(algorithm="FaceRecognition", compare="image1.jpg model.gal") print(result) The parameters and the algorithms are exactly the same as the OpenBR Command-Line tool. The official documentation can be found at:") You can configure two things in the module: You need to have OpenBR installed on your system. For installation instructions please visit: The module is compatible with Windows, Mac OS X and *nix Systems. It has been tested under Mac OS X El Capitan. Both Python 2.7 and Python 3 are supported.. I did a quick experiment to see the time difference between the official Python wrapper and this module. The test was about recognizing a face of the same image, against a trained model: So, there is a huge difference between the speed performance of the two wrappers. Probably this is the trade-off between speed and stability. This is a rather simple wrapper which uses basic ways to communicate with the OpenBR executable. However, it is stable and easy to use, which is the reason why I publish it as open-source. You can contact me via e-mail at: antonis.katzourakis{AT}gmail{DOT}com Twitter: @ant0nisktz Copyright 2016 Antonios KatzourakisLicensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License atUnless.
https://pypi.org/project/pyopenbr/
CC-MAIN-2017-13
refinedweb
243
58.08
Who Is Looking: Building a Custom ASP.NET Control that uses Javascript, Cascading Style… In trying to bite off new things, I decided it would be fun to create a new screensaver. Visual Studio Express comes with an RSS screensaver starter kit, but I never looked at it too closely. It turns out that screensavers are pretty easy to make, though you'll need to do some work with graphics. If you're not afraid to think in terms of bitmaps and drawing operations, you can do some fun things! Use the download links at the top of the article to grab the C# or VB source, then if you haven't already, download the appropriate version of Visual Studio 2005 Express Edition. The sample will run on either XP or Vista. It will take advantage of Windows Desktop Search if available. On XP this is a stand-alone download. I've always like the Picasa Photo Pile effect: Image 1 - The Picasa Photo Pile effect (not a screensaver) This is pretty cool looking, but the Picasa screensaver uses a different effect, removing the "Polaroid"-style photo frame: Image 2 - The Picasa screensaver collage effect Instead of just settling for what they offer, I decided to try my hand at recreating the Photo Pile myself. It can work from a folder of images, optionally searching subfolders as well. Instead of working from a single color background, I thought that it would be cute to layer the pile over the actual desktop background. Of course, this might not be ideal if you have sensitive data on your screen, but if you walk away letting the screensaver kick in, you probably aren't as concerned about that anyway! Image 3 - Coding 4 Fun screensaver overlaid on my desktop My first step was to crack open the starter kit. It's nice and easy-to-follow. The biggest thing to notice is that a screensaver is just an application. There is no API. You should do some kind of visual thing, but there's nothing requiring you to. If the application is launched with the "/c" parameter, you should allow configuration. The "/p" parameter is invoked along with the a window handle to allow you to create a preview (as seen in the Display Settings dialog). I don't actually implement preview, but it's not all that difficult to do. The final parameter is "/s". This is the "show time!" flag telling you to display the screensaver itself. At this point, you can do anything that you want. What you should do is create a bitmap the same size as the screen. It should be a top-most, borderless form. The entire client area is the actual screensaver imagery. With no extra work, you'd have a nice "screen blank" screensaver. You'll probably you'll want to take it farther though! You could simply draw images to cover the surface. Perhaps a simple first stab would be to use the PictureBox control filling the entire form (Dock = Fill). For that matter, you could do something without graphics at all. It's just a form, so you have a lot of freedom at this point. For most screensavers, you will want to turn on double-buffering, set the form dimensions to the screen dimensions, and enable/disable several other properties/settings. To make this easy, I created a base class for the screensaver form: BaseScreenSaverForm (pretty original name, huh!). Any screensaver can just extend from this form. There is also an abstract class for the screensaver logic itself, ScreenSaverBase. This is called to initialize it (in our case, reading a list of files), then it will raise an event whenever there is a new bitmap available at which point the form can redraw itself appropriately. It makes it all pretty painless really. Once the basic framework is setup, you need to do some work to actually create an image in the derived screensaver object. I actually created a very simple example, CircleScreenSaver that demonstrates this. It just randomly draws circles on the screen every few seconds. It's got much less going on, so it might be a good place to start to see how it all works. If you want to switch screensavers, you'll have to make a small code modification in the ShowScreenSaver() method of Program.cs/vb. Image 4 - The simple "Circles" screensaver (two for the money!) Drawing in .NET using GDI+ take place using Graphics objects. Graphics instances are created using a factory method attached to the Image class. Think of the Bitmap/Image object as representing a snapshot of the pixels in a compact form, while the Graphics object provides methods to manipulate those pixels. The DrawEllipse() method creates a circle when height and width are equals. You can also DrawRectangle(), DrawString(), and much more. All drawing requires pens or brushes, and you can set color (32-bit), width, and an alpha blend amount (0-255) as seen in Image 4. In order to randomly draw circles around the screen, you start by obtaining a Graphics object. The _workingImage object is a Bitmap of the actual desktop. This is taken using the GrabPrimaryScreen() method of the ScreenSaverBase class. Visual Basic Public Function GrabPrimaryScreen() As Bitmap Dim rc As Rectangle = Screen.PrimaryScreen.Bounds Dim screenBitmap As New Bitmap(rc.Width, rc.Height, PixelFormat.Format32bppArgb) Using g As Graphics = Graphics.FromImage(screenBitmap) ' Copy the contents of the screen g.CopyFromScreen(rc.X, rc.Y, 0, 0, rc.Size, CopyPixelOperation.SourceCopy) End Using Return screenBitmap End Function Visual C# public Bitmap GrabPrimaryScreen() { Rectangle rc = rc = Screen.PrimaryScreen.Bounds; Bitmap screenBitmap = new Bitmap(rc.Width, rc.Height, PixelFormat.Format32bppArgb); using (Graphics g = Graphics.FromImage(screenBitmap)) { // Copy the contents of the screen g.CopyFromScreen(rc.X, rc.Y, 0, 0, rc.Size, CopyPixelOperation.SourceCopy); } return screenBitmap; } Next you generate lots of random numbers for the size of the circle, the location, and the color. The Color.FromArgb() method takes RGB (red, green, blue) values from 0-255 to create a 32-bit color. You can also optionally specify an alpha value (also from 0-255) -- in this case 128. That affects how the color is blended with any existing color in the bitmap. 128 equates to a 50% transparency. This is performed in the UpdateWorkingImageBubbles() method of the CircleScreenSaver class. Building up an image from primitives such as rectangles, lines, and ellipses can be tedious, but isn't very difficult. Visual Basic Using g As Graphics = Graphics.FromImage(_workingImage) Dim s As Integer = rnd.Next(200) Dim x As Integer = rnd.Next(_workingImage.Width - s) Dim y As Integer = rnd.Next(_workingImage.Height - s) Dim c As Color = Color.FromArgb(128, rnd.Next(255), rnd.Next(255), rnd.Next(255)) Using b As Brush = New SolidBrush(c) g.FillEllipse(b, x, y, s, s) End Using End Using Visual C# using (Graphics g = Graphics.FromImage(_workingImage)) { int s = rnd.Next(200); int x = rnd.Next(_workingImage.Width - s); int y = rnd.Next(_workingImage.Height - s); Color c = Color.FromArgb(128, rnd.Next(255), rnd.Next(255), rnd.Next(255)); using (Brush b = new SolidBrush(c)) { g.FillEllipse(b, x, y, s, s); } } Beyond the primitive drawing operations, you also have control over settings such as scaling, transformation, and rendering quality. This is important since you want the image to be drawn smaller than the original in most cases (scaling). You can choose trade-off's between fast and high quality. There's also the compositing of the images -- how various graphic elements are drawn atop each other. There are different quality levels for that as well. Finally, transformation allows you to setup a matrix to affect how an image is warped as it is drawn. This can allow for some interesting effects, though we just use it for performing the random rotation that you see in the final image. The logic for rendering the photos is found in the PhotoScreenSaver class. By factoring out the screensaver's custom rendering (using the ScreenSaverBase class) separate form the underlying form (BaseScreenSaverForm class), you can concentrate on just drawing. The fact that it's a screensaver doesn't affect how to render to the background image. The steps taken to draw the image are as follows (CreateSnapshotImage() method): Drawing the caption alone is actually a lot of steps. Use can invoke the DrawString() method of the Graphics class, but you don't get a whole lot of control. I ended up using the GraphicsPath class instead of using its AddString method to create the paths for the caption string. It allows me to define a rectangle and to left/center/right justify horizontally and/or vertically, and even to add automatic ellipses as necessary. All without need to measure the width of the string first. For better efficiency, the StringFormat object should just be reused between calls. For bonus points, see what else you can reuse between calls! Visual Basic ' Extract and draw caption Dim f As Font = My.Settings.CaptionFont Dim rect As New Rectangle(2, CInt(imageHeight + (imageBuffer * 2)), trueImageWidth - 4, CInt(imageBuffer * 2.5)) Dim path As New GraphicsPath() Dim format As New StringFormat() format.Alignment = StringAlignment.Center format.LineAlignment = StringAlignment.Center format.Trimming = StringTrimming.EllipsisCharacter path.AddString(originalPhoto.Caption, f.FontFamily, CInt(f.Style), f.Height, rect, format) g.FillPath(Brushes.Black, path) Visual C# // Extract and draw caption Font f = Properties.Settings.Default.CaptionFont; Rectangle rect = new Rectangle( 2, (int)(imageHeight + (imageBuffer * 2)), trueImageWidth - 4, (int)(imageBuffer * 2.5)); GraphicsPath path = new GraphicsPath(); StringFormat format = new StringFormat(); format.Alignment = StringAlignment.Center; format.LineAlignment = StringAlignment.Center; format.Trimming = StringTrimming.EllipsisCharacter; path.AddString(originalPhoto.Caption, f.FontFamily, (int)f.Style, f.Height, rect, format); g.FillPath(Brushes.Black, path); The complete process is as follows: After every twenty seconds, the working image is reverted back to that cached screen image. With the images cached, memory usage goes up a bit, but performance improves. Doing the heavy rendering work on a background thread means that the screensaver can still exit immediately when a keypress or mouse action is detected (remember that the screensaver is responsible for exiting gracefully when user activity is detected). Otherwise, a very large image might take a few seconds, and it would be unresponsive in the meantime. If you've read some of my past articles (Searching the Desktop, Creating an Enhanced File Search Dialog), you're already familiar with the power of Windows Desktop Search. Adding the ability to search for screensaver images from the WDS index was trivial. It makes sense too. The alternative is to add multiple folders and filename matching keywords. Searching the index is fast and it just works. Adding the caption was more difficult than I expected. It seems like an obvious need to show the caption, but I just couldn't find it. The Image class exposes lists of embedded metadata properties, but it's very tedious to work with. Worse still, modern OS's like XP and Vista don't really use EXIF anymore for metadata. The new hotness if XML-formatted XMP data. This is stored within the file as plain-text XML. It's fairly easy-to-read, but I was frustrated that data isn't completely consistent since different vendors can extend it how they want (after all, it's just XML). Feel free to uncomment code in the PhotoInfo class in the GetPhotoCaption() method if you want to get EXIF properties, but you may or may not get any use out of it. If the list of images comes from WDS, it's moot anyway -- the System.Title property brings back the image's title/caption with no extra work at all, regardless of how it's stored! One place that I do use the EXIF property is to detect image rotation (orientation). It's only any good if your camera supports the "Orientation" flag (0x0112), or if your photo software does (Picasa doesn't update that flag as far as I can tell). It's simple to rotate based on this flag. If it's not updated, you may end up with some sideways images. Notice the call to ExifSupport.GetExifShort(). I threw together the ExifSupport class based on some articles that I found. The property values are all stored as byte arrays and they're really a pain. In .NET 3.0, you can use the System.Windows.Media.Imaging namespace to get much better access to properties. I wanted this project completely 2.0, so I had to do it the lower-level way. Visual Basic Dim rotation As Short = ExifSupport.GetExifShort(originalPhoto.SourceBitmap, 274, 1) If rotation = 3 Then resizedPhoto.RotateFlip(RotateFlipType.Rotate180FlipNone) ElseIf rotation = 6 Then resizedPhoto.RotateFlip(RotateFlipType.Rotate90FlipNone) ElseIf rotation = 8 Then resizedPhoto.RotateFlip(RotateFlipType.Rotate270FlipNone) End If Visual C# short rotation = ExifSupport.GetExifShort(originalPhoto.SourceBitmap, 0x0112, 1); if (rotation == 3) resizedPhoto.RotateFlip(RotateFlipType.Rotate180FlipNone); else if (rotation == 6) resizedPhoto.RotateFlip(RotateFlipType.Rotate90FlipNone); else if (rotation == 8) resizedPhoto.RotateFlip(RotateFlipType.Rotate270FlipNone); One thing to remember for a screensaver, is that you must rename the final EXE to the SCR extension. You can do this automatically in a Post-Build event. I actually make a copy of the file with the new name. In C#, use the Build Events tab of the project properties, while in Visual Basic, look for the Build Events button in the Compile tab of My Project. There you can define actions to take before or after building. To perform this copy/rename, enter this command: copy $(TargetFileName) $(TargetName).scr The syntax is pretty self-explanatory. You can do lots of cool things with build events. You could even automate the deployment to the C:\Windows\System32 folder, but I chose not to make it quite that easy. If I add a bug to the code, I don't want it in the system32 folder to kick in when I go to get my coffee! A final note: To test the preview mode from Visual Studio, you'll need to set the command line argument to "/p". You do this in the Debug tab in your project properties. Just enter it in Command line arguments. This is much easier than launching it from a command prompt, and also keeps everything within Visual Studio. Originally, I wasn't going to add search to the application, but it was so painless that I decided that it was worth the little extra effort. Another feature that seemed like a logical extension was working with RSS feeds with image enclosures (Flickr, Zooomr). This is actually really easy too, but I chose to leave well enough alone for now! Use the Feeds Manager classes included with Internet Explorer 7 to simplify the retrieval and caching of the feed items. Adding the ability to dynamically change the dimensions of the photo frame would make it possible to avoid cropping images arbitrarily, though it would lose that "Polaroid" appearance. It's certainly not a difficult change, I just didn't like the look personally. Another big thing is supporting multi-monitor displays and preview (in the Screen Saver properties window). The extra work of creating multiple bitmaps and rendering to the preview pane is left as an exercise to the reader! The screensaver does mostly work in Vista, but I noticed that sometimes it doesn't seem to do anything. I've found that pictures in the Public Pictures folder return the wrong path. The path works fine in Windows Explorer, but it isn't the real path (there is no real "Public Pictures" folder). If I find a fix, I'll update this. If it hits such an image, no error will occur (unless you are debugging it -- I added some code to show errors then), it just doesn't show it. If all images are in such as location, nothing will appear to happen. Now that I know, I'll probably do more with screensavers in the future (on my blog or in an article). Working with graphics was fun, though it's definitely not my best skill. I'm just not that visual kind of guy! Have fun with the code and as usual, contact me through my blog for comments, complaints, or questions. The Rnd.Next(int) is not working in Visual Studo 2008 (VB.NET).... What might be the problem here? @Leigh: That is since we don't do full source posting in our articles to reduce their length. the Random object was declared in a global view. If you download the full source, you'll see this. In your application, you'll need to do something like Random rnd = new Random(DateTime.Now.Ticks); The ticks will seed the random number generator to be random. I like this code very much, but I'm curious how I would go about having it work on both (dual) monitors? I just don't think I'm familiar enough with the code itself to see where/what I need to change. I want the screen saver to spread across both of them... @Nick: Check out for a similar project (with source) that supports multiple monitors. Why does nobody implement the /p preview functionality?! If you actually *try* - there are some issues that you run into. Namely - windows keeps re-running the screensaver (with the /p flag) each time you enter and exit the preview. Your app needs to be smart enough to kill the previous one (or update it) and make sure that only one is running at any given time. @Brock: Sorry, we provide base code examples that are aimed at people beefing them out. Ping Arian, he may have a fully finished application. Thanks for the example. I compiled it with VS2008 and it runs fine. One thing I noticed is a small problem with the memory usage. It is growing continuously while the screensaver runs. The problem seems to be in the ImageUpdater function and the ConstrainSize function. An example: int sourceHeight = sourcePhoto.SourceBitmap.Height; does create an bitmap through the get method, which is never released. It can be solved by creating a local bitmap object to which you assign sourcePhoto.SourceBitmap. At the end of the ConstraintSize function you can use the Dispose() method to release the memory of the local bitmap object. I hope this helps someone. The adjusted PhotoshowScreenSaver.cs file can be downloaded from my site. Yeah, Joe is right, and there are plenty of places to manually handle the clean up in memory to keep the app lean. I watched task manager before and after making a few changes to both methods Joe mentioned. It kept the memory usage down.
https://channel9.msdn.com/coding4fun/articles/Photo-Screensaver
CC-MAIN-2017-30
refinedweb
3,119
57.67
ERR_set_mark, ERR_pop_to_mark - set marks and pop errors until mark #include <openssl/err.h> int ERR_set_mark(void); int ERR_pop_to_mark(void); ERR_set_mark() sets a mark on the current topmost error record if there is one. ERR_set_mark() ERR_pop_to_mark() will pop the top of the error stack until a mark is found. The mark is then removed. If there is no mark, the whole stack is removed. ERR_pop_to_mark() ERR_set_mark() returns 0 if the error stack is empty, otherwise 1. ERR_pop_to_mark() returns 0 if there was no mark in the error stack, which implies that the stack became empty, otherwise 1. err(3) ERR_set_mark() and ERR_pop_to_mark() were added in OpenSSL 0.9.8.
http://www.openssl.org/docs/crypto/ERR_set_mark.html
CC-MAIN-2014-10
refinedweb
108
67.15
Someone. <br> <br> <br>[1] - <br> <br>I found an article by Microsoft entitled "How to write an application that supports the Fast User Switching feature by using Visual Basic .NET in Windows XP" which also addresses the multiple instances problem. It explains how you can switch to the running application if you attempt to run another instance. But sadly it also suggests using GetProcessesByName to do the detection. <br> <br>I wanted to create a single-instance of my application, but also be able to pass messages from any new instances before terminating them. Remoting solves the message-passing problem, but I needed some way to prevent a race condition if a second instance was created before the server object was set up in the first. <br> <br>This solves all my problems :) If I run the second snippet of code, I still am only able to get one instance of the application. I even tried adding GC.WaitForPendingFinalizers(); and had the same results. This was in C# and VB.NET using the .NET Framework v1.1. string mutexName = "Local\\" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Name; using (Mutex mutex = new Mutex(false, mutexName)) { if(!mutex.WaitOne(0, false)) { MessageBox.Show("Instance of application already running!", "Law Billing"); return; } GC.Collect(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); GC.KeepAlive(mutex); } Steve: Good point. The reason for my claim is that the purpose of the Using statement is to forcibly dispose of an object being used when code execution reaches the end of the block. The author is probably saying that the end of the "Using" block is the perfect time to keep it alive (GC.KeepAlive(mutex)) because it will be promptly disposed at End Using. Regarding a Visual Basic Implementation of this article's technique, I have found that my version of the .NET framework does not support "Using", for some reason. So I have come up with this: ' --------------------------- ' Instance Control ' --------------------------- ' create an id so the machine can recognize this app Dim mutexID As String = "eb6dc9ad-cdd1-426e-8417-a37a7fc40558-My-App.." ' create mutex Dim mutex As New System.Threading.Mutex(False, mutexID) ' test for another instance If Not mutex.WaitOne(0, False) Then ' notify user, then quit MsgBox("An instance is already running and this one will close.") ' quit End End If ' keep the mutex alive before it goes out of scope.. GC.KeepAlive(mutex) using System.Threading; using System.Diagnostics; class Mutt { static void Work() { System.Console.WriteLine("PID: {0}", Process.GetCurrentProcess().Id); for(int i = 0; i < 10; i++) { Thread.Sleep(1000); System.Console.Write("."); } System.Console.Write("\n"); } public static void Main(string[] args) { bool live; Mutex m = new Mutex(true, "symon", out live); if(live) { Work(); m.ReleaseMutex(); } while(true) { m.WaitOne(); Work(); m.ReleaseMutex(); } } } I believe that if I run two instances of this program, then they would call the Work() method alternately. i.e each instance gets a shot at Work() and then waits till another instance also calls Work(). So...if only one instance were running then it would call Work() only once and wait infinitely. Am I right? But...the program does not work as expected. using System.Reflection; using System.IO; using System.Threading; static Mutex mutex;(); if (!bCreatedNew) { MessageBox.Show("App Running!", "App Already Running", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); }
http://odetocode.com/blogs/scott/archive/2004/08/20/the-misunderstood-mutex.aspx
CC-MAIN-2013-20
refinedweb
554
52.46
Every board port has its own board config file, and largely all customizable settings live there. You can usually find it at include/configs/<board>.h. Compiler related settings are placed in the board-specific config.mk which can usually be found at board/<board>/config.mk. If you make changes to these files, you should probably run make clean to make sure all changes take effect. Largely every option can be found in the top level README file in the U-Boot source tree. Some options might also be found in the wiki -- simply use the search option in the upper right of the website. Every Blackfin board port should have this at the top of its board config header: #include <asm/config-pre.h>- initial helper defines for all Blackfin boards All Analog Devices boards have common settings stored in include/configs/bfin_adi_common.h. This way they do not need to copy and paste the same thing over and over. This file too is setup so you can largely override things in the board-specific config header.
https://docs.blackfin.uclinux.org/doku.php?id=bootloaders:u-boot:customizing
CC-MAIN-2017-13
refinedweb
179
73.37
Location finding error - JSP-Servlet Location finding error Location needs from drive name: My file uploading program has an error. It requires the location should be given from... the error as file not found. Below is the coding.The problem line is marked Data (Retrieved from a XML Document) to a File that helps you in storing the data to a specified file in different format. After... Storing Data (Retrieved from a XML Document) to a File... to store data (retrieved from the XML document) to a specified file (with  storing data in xml - XML storing data in xml Can u plz help me how to store data in xml using...(); File file = new File("c:/employee.xml"); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file,true Apache HSSF Jar file location Apache HSSF Jar file location where can i get jar files for apache hssf namespace in struts.xml file - Struts in struts.xml file Struts Problem Report Struts has detected an unhandled... / and action name Logout. - [unknown location.../struts.properties file. this error i got when i run program please help me  struts ;!-- This file contains the default Struts Validator pluggable validator... messages associated with each validator defined in this file. They should... in this file. # Struts Validator Error Messages errors.required={0 Storing records of a file inside database table in java Storing records of a file inside database table in java Here is my requirement, I have a file which contains some number of records like... in student.csv file).Please help me in resolving this problem. Thanks & Struts Configuration file - struts.xml that the struts.xml file should have. Here is the Struts 2.0 DTD... Struts Configuration file - struts.xml  .... The struts.xml File The Struts 2 Framework uses a configuration file (struts.xml JavaScript method location JavaScript method location... using location property of the window object. One of them is location.href which redirects the user straightforward to the specified URL. In the given example extracting phone number n storing in excel extracting phone number n storing in excel i need a program to open a doc file n extract phone numbers from it and store it in a excel sheet?? plz do reply and help me out with the problem. in that i want user should enter data in the format specified(for eg--abcde_)how in Struts. File Upload in Struts. How to do File Upload in Struts struts struts why doc type is not manditory in struts configuration file Struts File Upload and Save Struts File Upload and Save  ... regarding "Struts file upload example". It does not contain any... in uploading a file in a Struts application. This interface Understanding Struts Action Class Understanding Struts Action Class In this lesson I will show you how to use Struts Action Class and forward a jsp file through it. What is Action Class? An Action Struts Struts Struts 2 File Upload Struts 2 File Upload In this section you will learn how to write program in Struts 2 to upload the file... be used to upload the multipart file in your Struts 2 application. In this section you) Difference between Action form and DynaActionForm? 2) How the Client request was mapped to the Action file? Write the code and explain to make a google map point to user defined location ) and points the location in google map.so how do i do it? wen i press the submit button, the form should be submitted and then the google map should display the desired location of the user Struts Validator Framework in the ApplicationResources.properties file that should be returned if a validation... in this file use the logical names of Form Beans from the struts-config.xml file along... defined in the struts-config.xml file Create File in Java a file. This example takes the file name and text data for storing to the file.... If the mentioned file for the specified directory is already exist...; a specified file. import java.io.*; public  Struts upload file - Framework Struts upload file Hi, I have upload a file from struts... and send to file upload struts..how to get the sheets and data in that sheets Thanks. Hi friend, For upload a file in struts visit to : http configuration - Struts class,ActionForm,Model in struts framework. What we will write in each... of the persistent state of the application should reside in the model objects... in the model.The JSP file reads information from the ActionForm bean using JSP tags Uploading Single File by Using JSP Uploading Single File by Using JSP  ... to understand how you can upload a file by using the Jsp. As Jsp is mainly used for the presentation logic, we should avoid to write a code in the jsp page How to make directory in java Description: This example demonstrate how to create a directory at specified path. Code: import java.io.File; public ...;new File("c:\\newDir"); file1.mkdirs();  ... javascript tree link to struts action class page java - Struts java What is Java as a programming language? and why should i learn... should handle the response. If the Action does not return null, the RequestProcessor forwards or redirects to the specified resource (by utilizing MIT Open Source MIT Open Source Open Source at MIT The goal of this project is to provide a central location for storing, maintaining and tracking Open Source... this and then all you have to do is follow the directions to upload the Tutorials - Jakarta Struts Tutorial in tiles-defs.xml file. Advance Struts...; - Struts File Upload In this lesson we will create Struts File Upload program. - Struts Struts - Struts Struts Hi, I m getting Error when runing struts application. i... /WEB-INF/struts-config.xml 1... resolve this. Hi friend, Create the web.xml file like Struts - Struts Struts Hello I have 2 java pages and 2 jsp pages in struts... for getting registration successfully Now I want that Success.jsp should display Hello + USERNAME and it should also display if name is administrator Struts 2 Redirect Action ; <include file="struts...Struts 2 Redirect Action In this section, you will get familiar with struts 2 Redirect action Struts - Struts Struts Hello I like to make a registration form in struts inwhich... course then page is redirected to that course's subjects. Also all subject should.... Struts1/Struts2 For more information on struts visit to : API - Struts Framework API online the location of the api files. The easiest way is to read the Struts...Struts API - Struts Framework API online... are looking for the Struts API, you can either download the struts framework Ask Questions? If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for. Ask your questions, our development team will try to give answers to your questions.
http://roseindia.net/tutorialhelp/comment/34667
CC-MAIN-2013-20
refinedweb
1,148
67.04
size_t strlen ( const char * str ); <cstring> Get string length Returns the length of str.The length of a C string is determined by the terminating null-character: A C string is as long as the amount of characters between the beginning of the string and the terminating null character.This should not be confused with the size of the array that holds the string. For example:char mystr[100]="test string";defines an array of characters with a size of 100 chars, but the C string with which mystr has been initialized has a length of only 11 characters. Therefore, while sizeof(mystr) evaluates to 100, strlen(mystr) returns 11. /* strlen example */ #include <stdio.h> #include <string.h> int main () { char szInput[256]; printf ("Enter a sentence: "); gets (szInput); printf ("The sentence entered is %u characters long.\n",strlen(szInput)); return 0; } Enter sentence: just testingThe sentence entered is 12 characters long.
http://www.cplusplus.com/reference/clibrary/cstring/strlen/
crawl-002
refinedweb
152
64.51
I *know* this already exists, but I can't remember where: def pivot(func, seq): # I know, a good implementation shouldn't call func() twice per item return ( (x for x in seq if func(x)), (x for x in seq if not func(x)) ) I feel like I read a thread in which this was argued to death, and I can't find that either. The scenario: I have a sequence of lines from a file. I want to split it into those lines that contain a substring, and those that don't. I want it to be more efficient and prettier than with = [x for x in lines if substring in x] without = [x for x in lines if substring not in x] Does this exist? TIA, Michael
https://mail.python.org/pipermail/python-list/2010-March/571005.html
CC-MAIN-2016-44
refinedweb
130
74.05
I version is 2.7.3. I want to know is how can I edit the existing code to be able to use the client and server on different networks. My server code: #!/usr/bin/python # This is server.py file import socket # Import socket module s = socket.socket() # Create a socket object host = '0.0.0.0' # Get local machine name port = 12345 # Reserve a port for your service. print 'Server started!' print 'Waiting for clients...' s.bind((host, port)) # Bind to the port s.listen(5) # Now wait for client connection. c, addr = s.accept() # Establish connection with client. print 'Got connection from', addr while True: msg = c.recv(1024) print addr, ' >> ', msg msg = raw_input('SERVER >> ') c.send(msg); #c.close() # Close the connection My client code : #!/usr/bin/python # This is client.py file host = socket.gethostname() # Get local machine name print 'Connecting to ', host, port s.connect((host, port)) msg = raw_input('CLIENT >> ') s.send(msg) msg = s.recv(1024) print 'SERVER >> ', msg #s.close # Close the socket when done 1) You need to first change directory to root drive C:\, and type the following command into an admin cmd prompt window, C:\mongodb\bin\mongod.exe --config c:\mongodb\mongod.cfg –install 2) After that type net start MongoDB after which you must see the following message: "The Mongo DB service was started successfully" 3) Then go to the your control panel and go to Start>Administrative Tools>Services, scroll down up to MongoDB in the list of services and please make sure you change the start up type to automatic. Press OK. 4) Finally you need to type C:\mongodb\bin\mongo.exe and you will be connected to the Mongo test DB. And your issue will be resolved.
https://kodlogs.com/34083/winerror-10061-no-connection-could-be-made-because-the-target-machine-actively-refused-it
CC-MAIN-2020-34
refinedweb
294
70.9
MAY 2013 | | 1 {cvu} ISSN 1354-3164 ACCU is an organisation of programmers who care about professionalism in programming. That is, we care about writing good code, and about writing it in a good way. We are dedicated to raising the standard of programming. ACCU exists for programmers at all levels of experience, from students and trainees to experienced developers. As well as publishing magazines, we run a respected annual developers’ conference, and provide targeted mentored developer projects. The articles in this magazine have all been written by programmers, for programmers – and have been contributed free of charge. To find out more about ACCU’s activities, or to join the organisation and subscribe to this magazine, go to. Membership costs are very low as this is a non-profit organisation. The official magazine of ACCU accu {cvu} STEVE LOVE FEATURES EDITOR The New Informs The Old few weeks ago, I finally finished reading the Freeman and Price book Growing object oriented software, guided by tests. I bought it a couple of years ago, and (for shame!) have only just got round to reading it. For even more shame, I decided once I’d finished it to read a book that’s been left practically untouched for far longer, Kent Beck’s Test-driven development. The reason I’d not got round to reading that one is that there’s so much commentary and discussion about TDD – within ACCU, and on countless forums – I felt I’d already read it, in a way. What was most interesting for me was the reading of these two books back to back, and in reverse order, so to speak. Going back a decade or so with Kent’s book gave me new insights on the more modern practice, which also fed new comprehension of Growing..... The basic premise seems to be very similar, with the keeping of a to-do list, writing code test first, getting fast feedback, keeping the code ‘clean’. The New has differences to the Old, for example, getting a ‘walking skeleton’ in place, with acceptance tests, which drives a slightly different approach to development. Indeed, this difference of approach seems to have spawned an entire debate: that of ‘Classic’ (or ‘Detroit’) versus ‘London-style’ TDD. This seems to me to be similar to the differences between ‘Mockists’ and ‘Classicists’ as described by Martin Fowler in his article ‘Mocks aren’t stubs’, but goes further than that. The idea of aiming first for a full end-to-end test (with the help of Mock Objects) drives design differently to beginning with the simplest piece of functionality that represents measurable progress, as in ‘classic’ TDD. I’ve heard this described as ‘outside-in’ design versus ‘inside-out’. I’m pretty sure I don’t yet understand either approach well enough to comment on the better-ness of either one. However, one of those insights I mentioned that came from reading both books, was that the more modern approach looks to me like a natural progression of the classic approach, and that the use of Mock Objects to explore the relationships between collaborating objects is complementary to testing publicly visible state. Of one thing I am certain: whether you write tests in ‘classic’ or ‘London’ style is less important than your tests being clear and useful – and that you’ve written some! A Volume 25 Issue 2 May 2013 Features Editor Steve Love cvu@accu.org Regulars Editor Jez Higgins jez@jezuk.co.uk Contributors Pete Goodliffe, Martin Janzen, Paul F. Johnson, Filip van Laenen, Chris Oldwood, Roger Orr, Richard Polton, Mark Radford ACCU Chair Alan Griffiths chair@accu.org ACCU Secretary Giovanni Asproni secretary@accu.org ACCU Membership Craig Henderson accumembership@accu.org ACCU Treasurer R G Pauer treasurer@accu.org Advertising Seb Rose ads@accu.org Cover Art Pete Goodliffe Print and Distribution Parchment (Oxford) Ltd Design Pete Goodliffe 2 | | MAY 2013 ADVERTISE WITH US The ACCU magazines represent an effective, targeted advertising channel. 80% of our readers make purchasing decisions or recommend products for their organisations. To advertise in the pages of C Vu or Overload, contact the advertising officer at ads@accu.org. Our advertising rates are very reasonable, and we offer advertising discounts for corporate members. Some articles and other contributions use terms that are either registered trade marks or claimed as such. The use of such terms is not intended to support nor disparage any trade mark claim. On request we will withdraw all references to a specific trade mark and its owner. C Vu without written permission from the copyright holder. {cvu}. DIALOGUE 18 Standards Report Mark Radford looks at some features of the next C++ Standard. 19 Code Critique Competition Competition 81 and the answers to 80. 24 Letter to the Editor Martin Janzen reflects on Richard Polton’s article. REGULARS 22 Bookcase The latest roundup of book reviews. 24 ACCU Members Zone Membership news. SUBMISSION DATES C Vu 25.3:1 st June 2013 C Vu 25.4:1 st August 2013 Overload 116:1 st July 2013 Overload 117:1 st September 2013 FEATURES 3 Bug Hunting Pete Goodliffe implores us to debug effectively. 6 Tar-Based Back-ups Filip van Laenen rolls his own with some simple tools. 8 ACCU Conference 2013 Chris Oldwood shares his experiences from this year’s conference. 10 Writing a Cross Platform Mobile App in C# Paul F. Johnson uses Mono to attain portability. 12 Let’s Talk About Trees Richard Polton puts n-ary trees to use parsing XML. 16 Team Chat Chris Oldwood considers the benefits of social media in the workplace.. MAY 2013 | | 3 {cvu} Bug Hunting Pete Goodliffe implores us to debug effectively. If debugging is the process of removing software bugs, then programming must be the process of putting them in. ~ Edsger Dijkstra t’s open season. A year-round season. There are no permits required, no restrictions levied. Grab yourself a shotgun and head out into the open software fields to root out those pesky varmints, the elusive bugs, and squash them, dead. Well, it’s not really as saccharin that. But sometimes you end up working on code in which you swear the bugs are multiplying and ganging up on you. A shotgun is the only response. The story is an old one, and it goes like this: Programmers write code. Programmers aren’t perfect. The programmer’s code isn’t perfect. It therefore doesn’t work perfectly first time. So we have bugs. If we bred better programmers we’d clearly breed better bugs. Some bugs are simple mistakes that are obvious to spot and easy to fix. When we encounter these, we are lucky. The majority of bugs, the ones we invest hours of effort tracking down, losing our follicles and/or hair pigment in the search, are the nasty, subtle issues. These are the odd surprising interactions, or unexpected consequences of the actions we instigate. The seemingly non-deterministic behaviour of software that looks so very simple. It can only have been infected by gremlins. This isn’t a problem limited to newbie programmers who don’t know any better. Experts are just as prone. The pioneers of our craft suffered; the eminent computer scientist Maurice Wilkes wrote in [1]: I well remember [...] on one of my journeys between the EDSAC room and the punching equipment that ‘hesitating at the angles of stairs’ the realisation came over me with full force that a good part of the remainder of my life was going to be spent in finding errors in my own programs. So face it. You’ll be doing a lot of debugging. You’d better get used to it. And you better get good at it. (At least you can console yourself that you’ll have plenty of chance to practice.) An economic concern How much time do you think is spent debugging? Add up the effort of all of the programmers in every country around the world. Go on, guess. Greg Law (who provided me with the initial impetus to write this – as well as collating an amount of excellent material that I have wilfully stolen) points out that a staggering $312bn per year is spent on the wage bills for programmers debugging their software. To put that in perspective, that’s two times all Euro-zone bailouts since 2008! This huge, but realistic, figure comes from research carried out by Cambridge University’s Judge Business School [2]. You have a responsibility to fix bugs faster: to save the global economy. The state of the world is in your hands. It’s not just the wage bill, though. Consider all the other implications of buggy software: shipping delays, cancelled projects, the reputation damage from unreliable software, and the cost of bugs fixed in shipping software. An ounce of prevention It would be remiss of any article on debugging to not stress how much better it is to actively prevent bugs manifesting in the first place, rather than attempt a post-bug cure. An ounce of prevention is worth a pound of cure. If the cost of debugging is astronomical, we should primarily aim to mitigate this by not creating bugs in the first place. This, in a classic editorial sleight-of-hand, is material for a different article, and so we won’t investigate the theme exhaustively here. Suffice to say, we should always employ sound engineering techniques that minimise the likelihood of unpleasant surprises. Thoughtful design, code review, pair programming, and a considered test strategy (including TDD practices and fully automated unit test suites) are all of the utmost importance. Techniques like assertions, defensive programming and code coverage tools will all help minimise the likelihood of errors sneaking past. We all know these mantras. Don’t we? But how diligent are we in employing such tactics? Avoid injecting bugs into your code by employing sound engineering practices. Don’t expect quickly-hacked out code to be of high quality. The best bug-avoidance advice is to not write incredibly ‘clever’ (which often equates to complex) code. Brian Kernighan states: Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. Martin Fowler reminds us: Any fool can write code that a computer can understand. Good programmers write code that humans can understand. Bug hunting Beware of bugs in the above code; I have only proved it correct, not tried it. ~ Donald Knuth Being realistic, no matter how sound your code-writing regimen, some of those pernicious bugs will always manage to squeeze through the defences and require you to don the coder’s hunting cap and an anti-bug shotgun. How should we go about finding and eliminating them? This can be a Herculean task, akin to finding a needle in a haystack. Or, more accurately, a needle in a needle stack. Finding and fixing a bug is like solving a logic puzzle. Generally the problem isn’t too hard when approached methodically; the majority of bugs are easily found and fixed in minutes. There are two ‘vectors’ that make a bug hard to fix: how reproducible it is, and how long it is between the cause of the bug itself (the ‘software fault’) and you noticing. When a I Becoming a Better Programmer # 80 PETE GOODLIFFE Pete Goodliffe is a programmer who never stays at the same place in the software food chain. He has a passion for curry and doesn’t wear shoes. Pete can be contacted at pete@goodliffe.net or @petegoodliffe no matter how sound your code- writing regimen, some of those pernicious bugs will always manage to squeeze through the defences 4 | | MAY 2013 {cvu} bug scores high on both, it’s almost impossible to track down without sharp tools and a keen intellect. If you plot frequency versus time-to-fix you get a curve asymptotically approaching infinite time to fix. In other words, the hard bugs are few in number, but that’s where we will spend most of our time. There are a number of practical techniques and strategies we can employ to solve the puzzle and locate the fault. The first, and most important thing, is to investigate and characterise the bug. Give yourself the best raw material to work with: Reduce it to the simplest set of reproduction steps possible. Sift out all the extraneous fluff that isn’t contributing to the problem, and only serves to distract. Ensure that you are focusing on a single problem. It can be very easy to get into a tangle when you don’t realise you’re conflating two separate – but related – faults into one. Determine how repeatable the problem is. How frequently do your repro steps demonstrate the problem? Is it reliant on a simple series of actions? Does it depend on software configuration, or the type of machine you’re running on? Do peripheral devices attached make any difference? These are all crucial data points in the investigation work that is to come. In reality, when you’ve constructed a single set of reproduction steps, you really have won most of the battle. Here are some useful debugging strategies: Lay traps You have errant behaviour. You know a point when the system seems correct (maybe it’s at start-up, but hopefully a lot later through the repro steps), and you can get it to a point where its state is invalid. Find places in the code path between these two points, and set traps to catch the fault. Add assertions or tests to verify the system invariants that must hold. Add diagnostic print-outs to see the state of the code so you can work out what’s going on. As you do this, you’ll gain a greater understanding of the code, reasoning more about the structure of the code, and will likely add many more assertions to the mix to prove your assumptions hold. Some of these will be genuine assertions about invariant conditions in the code, others will be assertions relevant to this particular run. Both are valid tools to help you pinpoint the bug. Eventually a trap will snap, and you’ll have the bug cornered. Assertions and logging (even the humble printf) are potent debugging tools. Use them often. Many of these diagnostic logs and assertions may be valid to leave in the code after you’ve found and fixed the problem. Learn to binary chop Aim for a binary-chop strategy, to focus in on bugs as quickly as possible. Rather than single-stepping through code paths, work out the start of a chain of events, and the end. Then partition the problem space into two, and work out if the middle point is good or bad. Based on this information, you’ve narrowed the problem space to something half the size. Repeat this a few times, and you’ll soon have homed-in on the problem. Employ this technique with trap-laying. Or with the other techniques below. Employ software archaeology Software archaeology describes the art of mining through the historical records in your version control system. This can provide an excellent route into the problem; it’s often a simple way to hunt a bug. Determine a point in the near past of the codebase when this bug didn’t exist. Armed with your reproducible test case, step forwards in time to determine which code changeset caused the breakage. Again, a binary chop strategy is the best bet here. Once you find the breaking code change, the cause of the fault is usually obvious, and the fix self-evident. (This is another compelling reason to make series of small, frequent, atomic check-ins, rather than massive commits covering a range of things at once.) Do not despise tests Invest time as you develop your software to write a suite of unit tests. This will not only help shape how you develop and verify the code you’ve initially written. It acts as a great early warning device for changes you make later; it acts like the miner’s canary – the test fails long before the problem becomes complex to find and expensive to fix. These tests can also act as great points from which to begin debugging sessions. A simple, reproducible unit test case is a far simpler scaffold to debug than a fully running program that has to spin up and have a series of manual actions run to reproduce the fault. For this reason, it’s advisable to write a unit test to demonstrate a bug, rather than start to hunt it from a running ‘full system’. Once you have a suite of tests, consider employing a code coverage tool to inspect how much of your code is actually covered by the tests. You may be surprised. A simple rule of thumb is: if your test suite does not exercise it, then you can’t believe it works. Even if it looks like it’s OK now, without a test harness then it’ll be very likely to get broken later. Untested code is a breeding ground for bugs. Tests are your bleach. When you finally determine the cause of a bug, consider writing a simple test that clearly illustrates the problem, and add it to the test suite before you really fix the code. This takes some genuine discipline, as once you find the code culprit, you’ll naturally want to fix it ASAP and publish the fix. Instead, first write a test harness to demonstrate the problem, and use this harness to prove that you’ve fixed it. The test will serve to prevent the bug coming back in the future. Invest in sharp tools The are many tools that are worth getting accustomed to, including memory checkers like electric fence, and swiss-army knife tools like Valgrind. These are worth learning now rather than reaching for them at the last minute. If you know how to use a tool before you have a problem that demands it, you’ll be far more effective. Learning a range of tools will prevent you from cracking a nut with a pneumatic drill. Of course, the tool of debugging champions is the debugger. This is the king of tools that allows you to break into the execution of a running program, step forwards by a single instruction, or step in – and out of – functions. Some advanced debuggers even allow you to step backwards. (Now, that’s real voodoo.) In some circles there is a real disdain for the debugger. Real programmers don’t need a debugger. To some extent this is true; being overly reliant on such a tool is a bad thing. Single-stepping through code mindlessly can trick you into focusing on the micro, rather than thinking about the overall shape of the code. But it’s not a sign of weakness. Sometimes it’s just far easier and quicker to pull out the big guns. Don’t be afraid to use the right tool for the job. Learn how to use your debugger well. Then use it at the right times. Remove code to exclude it from cause analysis When you can reproduce a fault, consider removing everything that doesn’t appear to contribute to the problem to help focus in on the offending lines of code. Disable other threads that shouldn’t be involved. MAY 2013 | | 5 {cvu} Remove subsections of code that do not look like they’re related. It’s common to discover objects indirectly attached to the ‘problem area’, for example via a message bus or a notifier-listener mechanism. Physically disconnect this coupling (even if you’re convinced it’s benign). If you still reproduce the fault, you have proven your hunch about isolation, and have reduced the problem space. Then consider removing or skipping over sections of code leading up to the error (as much as makes practical sense). Delete, or comment out blocks that don’t appear to be involved. Cleanliness prevents infection Don’t allow bugs to stay in your software for longer than necessary. Don’t let them linger. Don’t dismiss problems as known issues. This is a dangerous practice. It can lead to broken window syndrome [3]; making it gradually feel the norm and acceptable to have buggy behaviour. This lingering bad behaviour can mask the causes of other bugs you’re hunting. One project I worked on was demoralisingly bad in this respect. When given a bug report to fix, before managing to reproduce the initial bug you’d encounter ten different issues on the way that all also needed to be fixed, and may (or may not) have contributed to the bug on question. Oblique strategies Sometimes you can bash your head against a gnarly problem for hours and get nowhere. It’s important to learn when you should simply stop and walk away. A break can give you fresh perspective. This can help you to think more carefully. Rather than running headlong back into the code, take a break to consider the problem description and code structure. Go for a walk and step away from the keyboard. (How many times have you had those ‘eureka’ moments in the shower? Or in the toilet?! It happens to me all the time.) Describe the problem to someone else. Often when describing any problem (including a bug hunt) to another person, you instantly explain it to yourself and solve it. Failing another actual, live, person, you can follow the rubber duck strategy described by the Pragmatic Programmers [4]. Talk to an inanimate object on your desk to explain the problem to yourself. It’s only a problem if the rubber duck starts to talk back. Don't rush away Once you find and fix a bug, don’t rush mindlessly on. Stop for a moment and consider if there are other related problems lurking in that section of code. Perhaps the problem you’ve fixed is a pattern that repeats in other sections of the code. Is there further work that you could do to shore up the system with the knowledge you just gained? Non-reproducible bugs Having attempted to form a set of reproduction steps, sometimes you discover that you can’t. It’s just not possible. From time to time we uncover nasty, intermittent bugs. The ones that seem to be caused by cosmic rays rather than any direct user interaction. These are the gnarly bugs that take ages to track down, often because we never get a chance to see them on a development machine, or when running in a debugger. How do we go about finding these? Keep records of the factors that contribute to the fault. Over time you many spot a pattern that will help you identify the common causes. As you get more information start to draw conclusions. Perhaps identify more data points to keep in the record. Consider adding more logging and assertions in beta/release builds to help gather information from the field. If it’s a really pressing problem, set up a test farm to run long running-soak tests. If you can automate driving the system in a representative manner then you can accelerate the hunting season. There are a few things that are known to contribute to such unreliable bugs. You may find they provide hints as to where to start investigating: Threaded code; as threads entwine and interact in non-deterministic and hard-to-reproduce ways, they often contribute to freaky intermittent failures. Often this behaviour is very different when you pause the code in a debugger, so is hard to observe forensically. Network interaction, which is by definition laggy and may drop or stall at any point in time. Code that presumes access to local storage works (because, most often, it does) will not scale to storage over a network. The variable speed of storage (spinny disks, database operations, or network transactions) may change the behaviour of your program, especially if you are balanced precariously on the edge of timeout thresholds. Memory corruption, where your aberrant code overwrites the stack or heap, can lead to a myriad of unreproducible strangenesses that are very hard to detect. Software archaeology is often the easiest route to diagnose these errors. Conclusion Debugging isn’t easy. But it’s our own fault. We wrote the bugs. Effective debugging is an essential skill for any programmer. Acknowledgments The inspiration for this article came from a conversation I had with Greg Law about his excellent ACCU 2013 conference presentation on debugging. Greg’s company, Undo Software, creates a most impressive ‘backwards debugger’ that you may want to look at. Check it out at undo- software.com. References [1] Maurice Wilkes, Memoirs of a Computer Pioneer. The MIT Press. 1985. ISBN 0-262-23122-0 [2] Cambridge Research puts the global cost of debugging at $312billion annually. reference.- 7 [3] Broken Windows Theory Broken_windows_th eory [4] Andrew Hunt and David Thomas, The Pragmatic Programmer. Addison Wesley. ISBN 0-201- 61622-X. Questions 1.Assess how much of your time you think you spend debugging. Consider every activity that isn’t writing a fresh line of code in a system. 2.Do you spend more time debugging new lines of code you have written, or on adjustments to existing code? 3.Does the existence of a suite of unit tests for existent code change the amount of time you spend debugging, or the way you debug? 4.Is it realistic to aim for bug-free software? Is this achievable? When is it appropriate to genuinely aim for bug-free software? What determines the optimal amount of ‘bugginess’ in a product? Stop for a moment and consider if there are other related problems lurking in that section of code 6 | | MAY 2013 {cvu} Tar-Based Back-ups Filip van Laenen rolls his own with some simple tools. few months ago, I found out that I had to change the back-up strategy on my personal laptop. Until then I had used Areca [1], which in itself worked fine, but I was looking for something that could be scripted and used from the command line, in addition to be easier to install and maintain. As often is the case in the Linux world, it turned out that you can easily script a solution together on your own using some basic building blocks. For this particular task, the building blocks are Bash [2], tar, rm and split, together with sha256sum and cmp to build a conditional copying function. Why use a script? What was my problem with Areca? First of all, from time to time, Areca had to be updated. In the Linux world, this is usually a good thing, but not if the new version is incompatible with the old archives. This can also cause problems when restoring archives, e.g. from one computer to another, or after a complete reinstallation of the operating system. Furthermore, since Areca uses a graphical user interface, scripting and running the back-up process from the command line (or crontab) wasn’t possible. Notice that these problems were generic, and not particular to Areca. Before deciding to script a solution together, I looked for an alternative solution that was scriptable and easy to install, but without success. That is, except for the suggestions to build my own solution using tar. Getting started Listing 1 shows the start of my tar-based back-up script. It starts with a shebang interpreter directive to the Bash shell. Then it checks the number of arguments that were provided to the script – it should be exactly one, otherwise the script exits here. Next it sets up four environment variables: a base directory in BASEDIR , the back-up directory where all archives will be stored in BACKUPDIR , the number of the current month (two digits) in MONTH , and the first argument passed to the script in LEVEL . The LEVEL variable represents the back-up level, i.e. 1 if only the most important directories should be archived, 2 if some less important directories should be archived too, etc… Backing up a Directory Next we define a two parameter function that backs up a particular directory to a file. Listing 2 shows how this function looks, together with some examples of how it can be used. First it logs to the console that it’s going to back up. Next it uses tar to do the actual archiving. Notice that the output of tar is redirected to a log file. That way we keep the console output tidy, and at the same time can browse through the log file if something went wrong. That’s also why we included v (verbosely list files processed) in the option list for tar, together with c (create a new archive), p (preserve file permissions), z (zip) and f (use archive file). Finally the function creates a SHA-256 [3] digest from the result. This digest can be used to decide whether two archive files are identical or not without having to compare large, multi-GB files. The variable MONTH is used to create rolling archives. In Listing 2, the directories bin and dev will always be backed up to the same archive file, but for the Documents and Thunderbird directory, a new one will be created every month. Of course, if the script is run a second time during the same month, the archive file for the Documents and Thunderbird directory will be overwritten. Also, the same will happen when the script is run a year later: the one year old archive file will then be overwritten with a fresh back-up. If you want some other behaviour, like e.g. a new archive every week or every day, you simply have to define your own variable and use date to set it. Tailor to your needs in your own back-up script! Listing 3 shows how LEVEL can be used to differentiate between important and often-changing directories on the one hand, and more stable directories you do not want to archive every time you run your script on the other hand. Currently my back-up script has three levels, but I’m considering splitting off the small archives from level 1 in a separate level, so I could add a line to crontab to take a quick back-up of some important directories once every day. Splitting large files Next, I’d like to split large files into chunks that are easier to handle when transferring them to external media. This makes it easier to move archives between computers or to external media. Listing 4 shows a function that splits a large file into pieces of 4 GB (hence the magic number 4,294,967,296 = 4 × 230), together with a loop that finds all files that should be split. Let’s start with a look at the function that splits the files. It receives one parameter, the path to the file. The first thing the function does is to extract A FILIP VAN LAENEN Filip van Laenen is a chief technologist at the Norwegian software company Computas. He has a special interest in software engineering, security, Java and Ruby, and likes to do some hacking on his Ubuntu laptop in his spare time. He can be contacted at f.a.vanlaenen@ieee.org function back_up_to_file { echo "Backing up $1 to $2." tar -cvpzf ${BACKUPDIR}/$2.tar.gz\ ${BASEDIR}/$1 &> ${BACKUPDIR}/$2.log sha256sum -b ${BACKUPDIR}/$2.tar.gz\ > ${BACKUPDIR}/$2.sha256 } back_up_to_file bin bin back_up_to_file dev dev back_up_to_file Documents Documents-${MONTH} back_up_to_file .thunderbird/12345678.default\ Thunderbird-${MONTH} Listing 2 #!/bin/bash ## Creates a local back-up. The resulting files # can be dumped to a media device. if [[ $# -ne 1 ]]; then echo "Usage:" echo " `basename $0` <LEVEL>" echo "where LEVEL is the back-up level." exit fi BASEDIR=/home/filip BACKUPDIR=${BASEDIR}/backup MONTH=`date +%m` LEVEL=$1 Listing 1 MAY 2013 | | 7 {cvu} the file name from the path, so that we can log to the console in a nice way which file we’re going to split. Next it removes any chunks it finds from the previous run, using option f to suppress any error messages in case there aren’t any chunks present. Then it does the splitting into chunks of 4 GB, using option d to create numeric suffixes instead of alphabetic. This means that if the function would split a file called dev.tar.gz, the names of the resulting chunks would be dev.tar.gz.00, dev.tar.gz.01, etc… Finally, when the function is done, it removes the original file, because we don’t need to have it around any more. The function is called inside a loop, which goes through all files having the .tar.gz extension. For each file it uses stat to calculate the total size ( -c%s ), and then compares it to 4 GB. If the file is larger, our function to split the file is called. Done Finally, at the end of the script, we write to the console that we’re done ( echo "Done." ). I like to do that to indicate explicitly that everything went well, especially since this script can take a while. Storing the back-ups There’s a little detail in Listing 1 that we haven’t dealt with yet: where do we store the back-ups? The script as it stands can be used to create local back-ups, i.e. putting the back-up files on the same disk as the original data, on the one hand, or write the back-ups directly to an external disk on the other hand. Since I have enough space on my hard disk, I like to create the back-up files locally first, and then plug in the external disk to transfer the files. That’s also why I create SHA-256 digests, so I can detect when a back-up file hasn’t changed and doesn’t need to be transferred to the external disk. Listing 5 shows how the back-up files we just created can be copied conditionally to an external drive. It loops through all the SHA-256 digests in the directory with the back-up files, and compares them to the SHA-256 digests in the target directory using cmp (silently, though the option s ). If both files exist, and their content is the same, cmp will return 0. In that case, we don’t need to copy files to the target directory, and can continue with the next SHA-256 digest. Otherwise we call the function that copies the set of files associated to the SHA-256 digest. The function to do that takes one parameter: the basename of the SHA- 256 digest file, but without the extension. The set of files we then want to copy consists of either the back-up file as a whole, or the different chunks resulting from the split function, in addition to the log file and of course the SHA-256 digest. We therefore have to start by removing the old back- up file or the chunks from the split function. Next, we copy the back-up file or the chunks in a small loop that lets us log to the console what we’re doing. Finally, we also copy the log file and the file with the SHA-256 digest. Notice that copying the SHA-256 digest file is the last thing we do: if the script is interrupted, we want to be sure that the next run will try and copy this file set again. The code in Listing 5 forms the body of its own script, separate from the code in the other listings. In fact, the script contains only three more things: the definition of BACKUPDIR and TARGETDIR , and writing to the console that we’re done. It assumes that we want to keep a copy of the back-up files on our hard disk, hence the use of cp to transfer the files to the target directory. If you’d rather move the back-up files to the target directory, you should not only use mv instead of cp to transfer the files, but also remember to remove the set of files from the back-up directory in case of identical SHA-256 digests. References [1] See [2] See [3] See # Backup of directories subject to changes if [ ${LEVEL} -ge 1 ]; then back_up_to_file bin bin-${MONTH} back_up_to_file Documents Documents-${MONTH} back_up_to_file .thunderbird/12345678.default\ Thunderbird-${MONTH} back_up_to_file dev dev-${MONTH} … fi # Backup of relatively stable directories if [ ${LEVEL} -ge 2 ]; then back_up_to_file Drawings Drawings back_up_to_file Photos/2010 Photos-2010 back_up_to_file Movies/2013 Movies-2010 back_up_to_file .fonts fonts … fi # Backup of stable directories if [ ${LEVEL} -ge 3 ]; then back_up_to_file Music Music … fi Listing 3 function split_large_file { FILENAME=$(basename $1) echo "Going to split ${FILENAME}." rm -f $1.0* split -d -b 4294967296 $1 $1. rm $1 } for f in ${BACKUPDIR}/*.tar.gz do FILESIZE=$(stat -c%s $f) if (( $FILESIZE > 4294967296 )); then split_large_file $f fi done function copy_files { rm -f "${TARGETDIR}/$1.tar.gz"* for f in ${BACKUPDIR}/$1.tar.gz* do FILENAME=$(basename $f) echo "Copying ${FILENAME}." cp $f "${TARGETDIR}" done cp ${BACKUPDIR}/$1.log "${TARGETDIR}" cp ${BACKUPDIR}/$1.sha256 "${TARGETDIR}" } for f in ${BACKUPDIR}/*.sha256 do FILENAME=$(basename $f) BASEFILENAME=\ `echo ${FILENAME} | sed -e 's/.sha256$//'` cmp -s ${BACKUPDIR}/${FILENAME}\ "${TARGETDIR}/${FILENAME}" > /dev/null if [ $? -eq 0 ]; then echo "Skipping ${BASEFILENAME}." else copy_files ${BASEFILENAME} fi done Listing 5 Listing 4 8 | | MAY 2013 {cvu} ACCU Conference 2013 Chris Oldwood shares his experiences from this year’s conference. t’s April once again and that can only mean one thing – apart from the school holidays and Easter eggs – it’s the ACCU Conference. This year saw one of the biggest changes to the conference – a new venue. And not just a new hotel but in a new city too! For the last 5 years I’ve only ever been to the same hotel in Oxford and so with much trepidation I headed down to Bristol. One of my biggest ‘worries’ was what was going to replace all those long standing traditions, like ‘Chutneys Tuesday’? But hey, we’re all agile these days so we should embrace change, right? Wednesday Once again I didn’t get to partake in one of the tutorial days on the Tuesday which was a shame as they looked excellent as usual. Instead I made my way down on the Wednesday and arrived in the early afternoon. That meant I missed lunch, but also more importantly the keynote from Eben Upton about the Raspberry Pi and a talk from Jonathan Wakely about SFINAE. The comments coming through on Twitter about these, and the other parallel talks, generated much gnashing of teeth as I cursed my late arrival. Not wanting to take things lightly I dived head-first into Johan Herland’s session about Git. I’ve done a little messing around with Git and have read the older 1 st edition O’Reilly book but I wasn’t sure whether I’d really understood it. Luckily Johan walked us slowly through how Git works in theory, and then in practice. I’m glad I saw this as it seems I was on the right track but he explained some things much better than the book. I also got to quiz him in the bar later about how some Subversion concepts might translate to Git, or not as i t seems, whi ch was priceless. Next up, was Pete Goodliffe doing the live version of his C Vu column on Becoming a Better Programmer. This was split into two parts with the first being Pete discussing what we even mean by ‘better’. He provided some of his thoughts and there were the usual array of highly entertaining slides to back them up – you are always guaranteed a good show. The second part was provided by various speakers (chosen by Pete) who got to spend 5 or so minutes discussing a topic that t hey bel i eve makes t hem a bet t er pr ogr ammer. Unsurprisingly these varied greatly from the practical, such as Automation (Steve Love), to the more philosophical – The Music of Programming (Didier Verna). The audience got to have a quick vote on what they felt was the most useful and Seb Rose’s Deliberate Practice got the nod. Once the main sessions have finished for the day the floor is opened up to everyone in the guise of Lightning Talks. These are short 5 minute affairs where anyone can let off steam, share a tip or plug something (non- commercial). Even though it was only the first evening there was a full program with talks about such topics as Design Sins (Pete Goodliffe), C++ Active Objects (Calum Grant), BDD with Boost Test (Guy Bolton King), Communities (Didier Verna) and an attempt at Just a Minute from Burkhard Kloss. With 12 talks in total it was a good start. Al t hough not directly part of the ACCU conference, the Bristol & Bath Scrum Group held an evening event afterwards where James Grenning talked about TDD. Although it had been a long day already I couldn’t resist squeezing one more talk in, especially from someone like this. Being aimed at a wider audience than just developers meant there were an interesting assortment of questions afterwards which was useful. One in particular was the common question of writing the test first versus immediately after which always causes a interesting debate. Thursday A full English breakfast and plenty of coffee set me up for the day and I was greeted with my first 2013 keynote, courtesy of Brian Marick. He started with an interesting tangent about crickets and how they tune in to a mate and eventually got onto the topic of how to cope with the inevitable natural decay older programmers will suffer from. The thing that has stuck with me most is the advice of converting ‘goal attainment’ to ‘maintaining invariants’. This he explained by showing how a baseball fielder might try to catch a ball by moving himself so he sees a linear trajectory rather than trying to anticipate a parabolic path. This was one of the most enjoyable keynotes I’ve seen. I didn’t have much choice in what I went to after Brian as it was my turn to step up to the plate. This was my third year of speaking and I’d like to say I might finally be getting the hang of it. At least, I don’t think anyone fell asleep. Unbeknownst to me until I checked my Twitter feed afterwards but there was a small bug in the code on one of my slides. This made my next choice easy – The Art of Reviewing Code with Arjan van Leeuwen. There was plenty of sound advice here, particularly around the area of getting started in code reviews where it’s important to make both parties comfortable to avoid a sense of personal attack. As Arjan pointed out, time is often the perceived barrier to doing reviews, but it’s reminded me how valuable it can be. That was only a short session and the other 45 minutes I spent with Ewan Milne as he discussed Agile Contracts. Although I don’t get involved (yet?) in that side of the process I still find it useful to comprehend the other parts of an agile approach. Understanding how the different forms of contract attempt to transfer the risk from one side to the other was enlightening – especially when you consider the role lawyers try to play in the process. Ewan normally has his hands full with organising the lightning talks so it was good to see him speak for longer t han 30 seconds. My final session for the day was to I MAY 2013 | | 9 {cvu} be spent with Michel Grootjans. With a title of Ruby and Rails for n00bs I felt that suited my knowledge of Ruby right down to the ground and hoped I would get to see what some of the fuss is about. It actually turned out to be way more useful than I expected because Michel developed a simple web app using a full-on TDD approach too. Not only did I get a small taste for what Ruby and Rails is about but I also saw someone develop a different sort of application using different tools in a more enterprise-y way. Once more, after the main sessions had completed, most of us convened to the main hall to listen to another round of lightning talks. This time there was a total of 13 topics with an even wider range than the day before. Notably for me, given my attendance at an earlier session on Git, was a rant from Charles Bailey about Git being evil. There were also complaints about poor variable naming (Simon Sebright) and why anyone would use C++ when D exists (Russel Winder, naturally). On the more useful front we saw Dmitry Kandalov implement an Eclipse plug-in in 5 minutes and a C++ technique that seems close to C#’s async/await mechanism (Stig Sandnes). The abusive C++ award though goes to Phil Nash with his <- operator for implementing extension methods. Oh, and Anders Schau Knatten used ‘Science’ to help us decide that C# is in fact the best programming language. Friday What better start to the day than a keynote from the very person we have to thank for C++ – Bjarne Stroustrup. It’s been some years since he graced the ACCU conference with his presence and so like many I was looking forward to what he had to say about the modern state of C++. His presentation was generally about the new features we now have in C++ 11 as he had a separate session planned for C++ 14. However there was as much about how the established practices (e.g. RAII) are still the dominant force and critical to its effectiveness. Naturally there were plenty of questions and he pulled no punches when airing his opinion on the relationship between C and C++. With my C++ side ignited I felt it was only right that I attend Nico Josuttis’ talk about move semantics and how that plays with the exception safety guarantee of a function like push_back() . He entered the murkier depths of C++ to show how complex this issue is for those who produce C++ libraries. When someone like Nico says C++ is getting ‘a little scary’ you know you need to pay attention. My ‘moment of the conference’ happened here when, in response to a question for Nico about the std::pair class, Jonathan Wakely instantly rattled off the C++ standard section number to help him find the right page… We all love writing fresh, new code, but many of us spend our lives wallowing in the source code left to us by others. Cleaning Code by Mike Long was a session that showed you why refactoring is important and what some of the tools and techniques you can use to help in the fight against entropy. This was a very well attended talk and rightly so with a good mix of the theoretical and practical. One tool in particular for finding duplicate code certainly looked sexy and will definitely be getting a spin. After another round of coffee I decided to close the day off by listening to the C Vu editor (Steve Love) explain why C# is such a Doddle to learn and use. Yes, his tongue very firmly placed in his cheek. As someone who uses C# for a living it’s easy to forget certain things that you take for granted with something like C++, such as the complexity guarantees of the core containers. Generics also came in for a bit of a bashing as a watered down version of templates. Anyone who thinks the world of C# is dragon free would have done well to attend. The final set of lightning talks took their cue from the volcano fiasco a few years ago. Back then, due to speaker problems caused by a lack of air transport, a set of 15 minute lightning keynotes were put together instead and that’s the length these ones adopted. Seb Rose opened the proceedings with a response to an earlier lightning talk about whether the term ‘passionate’ is a useful one for describing the kind of people we want to work with, given its dictionary definition. Much nodding of heads suggested he was probably right. He was followed by me trying to show how many of the old texts, such as the papers by David Parnas, are still largely relevant today. And, more importantly they’re often cheap. Tom Gilb was next up to answer a question I had posed in my t al k about quant i f yi ng robustness. Let’s face it, we knew he would. Finally Didier Verna got to extend his earlier slot on The Pete Goodliffe Show to go into more detail about the similarities he sees between music and programming. I’ve never really given Jazz a second thought before, and even though we only got a 30 second burst of his own composition my interest is definitely piqued. The Friday evening always plays host to The Conference Dinner, which is a sort of banquet where we get to spend a little more time mingling with the various speakers and attendees. This is a perfect opportunity to corner a speaker and ask some questions you didn’t get a chance to earlier. Jon made sure the tables regularly got mixed up to keep the flow of people moving between courses which helps you mix with people you might not normally know. After the dinner there was the Bloomberg Lounge to keep us entertained through the night, if you fancied staying up until silly o’clock. Saturday There was another change to the session structure this year as the Saturday keynote was moved to the end of the day; instead the normal sessions started earlier. Sadly I overdid the conference dinner again and so an early start was never really on the cards. How to Program Your Way Out of a Paper Bag seemed like the ideal eventual start to the day. Frances Buontempo had sold the idea well – is it possible to actually write a program to get out of a paper bag? Obviously there was a certain amount of artistic licence, but ultimately she did it, and along the way we got to find out a whole lot about machine learning. I was a little worried there might be a bit too much maths at that time of day but it was well within even my meagre reach. My final session of the conference was to be with Hubert Matthews – A History of a Cache. This was a case study of some work he been involved in. The session had a wonderful narrative as he started by explaining how the system was originally designed, and then went on to drop the bomb on how he needed to find a huge performance boost with the usual array of ‘impossible’ constraints. Each suggested improvement brought about a small win, but not enough by itself and that’s what made it entertaining. It also goes to show what can be achieved sometimes without going through a rewrite. Epilogue I keep expecting the magic of this conference to wear off, but so far it seems to be holding fast. I have looked around at some of the other conferences but I’m just not as impressed by the content or the price for that matter. I thought the new venue worked well and even though it was a little further to travel it wasn’t exactly onerous. More of the talks were filmed this year and so hopefully I should be able to catch up on some of those I missed. With 5 concurrent sessions running in each time slot you’re never going to get to see everything you want to, but that’s just another reason to keep coming back year-after-year – to try and catch up on everything you’ve missed in previous years. Of course in the meantime the world has moved on and there’s another load of new stuff to see and learn! 10 | | MAY 2013 {cvu} Writing a Cross Platform Mobile App in C# Paul F. Johnson uses Mono to attain portability. A brief piece of history any years back, Ximian (a small bunch of very nice people) decided to write an open source version of the .NET language based on the ECMA documentation. Initially for Linux, it soon spread to Mac, BSD and many other platforms (including Windows). This was good and fine. Novell then bought Ximian and signed what was considered (in the non-SuSE part of the open source community at least) as a deal with the devil – the devil being Microsoft. Time moved on. Novell was bought out and so Xamarin was formed, their task, to carry on developing the open source Mono framework which was fast growing to be a recognised force for good. While all of this was going on, Google moved into the mobile phone business with Android and Apple released their iPhone. Android (as you may know) has a Linux kernel at its heart and apps are coded in Java. iPhones use Objective-C for the language of choice. Google controlled its app store and Apple, in true Apple fashion, pretty much dictated under the guise of ‘quality’ what could and could not be distributed through them. This is fine and dandy with one problem – as with the old 8-bit systems of old, if you wanted your app to run on both iPhone and Android, you had to do a lot of work to port the code over, that or employ that rare breed developers that can work in both Objective C and Java. It doesn’t take a genius to realise that if a company can come up with a method to write once, deploy many as was the case with .NET, then they would win the day and praises be sung. Step forth Xamarin. Using the mono framework, they released .NET for both iPhone and Android. While the UI aspect is not the same, a large amount of core functionality could be moved between the platforms with minimal work (it is after all just using the .NET framework that we all love and use) reducing both development time and final cost. For the iPhone, as the code generated reverts back to ObjC and is linked against Apple’s SDK, apps created with Monotouch (the iOS version) are available in the iOS store. What this small series is going to show is how simple it is to achieve both an iPhone and Android version of the same app with essentially the same code. I will be porting some code I wrote [1] quite a few years back to run on both platforms. It isn’t going to do anything amazing, but will allow you to download, read and reply to your gmail. Xamarin have released versions of monotouch and monodroid that will run on the emulator (Android) or simulator (iOS) [2] so you can see and test the final product. The source code for these articles is held online [3]. My recommendation is that you install Xamarin Studio to code with. While there are plugins for VisualStudio 2010 and 2012, my experience with them has not been great, whereas Xamarin Studio is rock solid. Let’s get on with it then The basis of this app is communicating with the Google servers to allow a user to read and reply to their emails. To do this, we need a basic SMTP and POP3 system. SMTP is supported natively, POP3 isn’t, but it’s not difficult to code a small POP3 library that allows access to the facilities. A word of warning When writing code that will work between both iOS and Android, it is not only the UI that needs to be considered. Monotouch for .NET developers is a much simpler system to use. Instantating new classes which generate new views is very similar to how it is done in a standard Winforms application NewView nv = new NewView(params); will create a new instance of NewView with whatever parameters are needed to be passed in – it is essentially the same as in a winforms application. Android development is not like this. For Android, the safest way to think about how an app is structured is that there are a lot of small apps (called Activities) that you need to get to work together. While you can certainly pass certain objects between activities (the likes of string , int , bool etc), passing the likes of classes or bitmaps is not going to happen. To start a new activity Intent i = new Intent(this, typeof(class)); StartActivity(i); where class is the name of the activity class being started. Passing simple objects can be done with string hello = “Hello”; … i.PutExtra(“name”, hello); and read back in the receiving class using string message = base.Intent.GetStringExtra("content"); Alright, it’s not rocket science, but it leads to two problems; portability (it’s not available in iOS) and propagation (the next activity will also have to have the same PutExtra / GetExtra code to receive the data). This difficulty can be overcome by using either a standard interface block or better than that, a public static class. The big advantage of having the static class is that generics, arrays, bitmaps and anything else that can be bundled into a static class can be used. It is also completely portable between the platforms – as long as nothing platform specific is included in there of course! Of course, there is nothing to stop instantiation between classes on Android in the more usual .NET form, but it will not fire up the activity, so no view is shown unless a bit of extra legwork is done. I will be avoiding that route for this series! UI design This app will not win any design awards, but then it’s not meant to. It is simple and functional. The UI is greatly different between iOS and Android. To that end, I will concentrate on that aspect for the remainder of this article. Android The way to think about how to design for Android is to think in either vertical or horizontal boxes. Take the following M PAUL F. JOHNSON Paul used to teach and was one time editor of a little known magazine called C Vu. He now writes code professionally for a living – primarily for Android and iOS, but only ever in .NET thanks to Xamarin.Android and Xamarin.iOS. MAY 2013 | | 11 {cvu} While it would seem a simple enough design, it has to be considered along the lines of boxes within boxes viz We have a horizontal outer, next layer are two horizontals. The one on the right now has 4 verticals with the bottom one having two horizontals in. Planning can be a bit tricky on deciding which way the layout has to be, but it’s not that bad. By default, a new layout contains a vertical LinearLayout . Within each layout, you can pretty much put any type of view (most of the widget classes are derived from the View class, so you have a TextView , EditView , ImageView and so on). Android here becomes very similar to .NET in that the views are similar to the standard .NET views (for example TextView = Label , EditView = TextBox , ImageView = PictureBox ), but like the .NET widgets, these views can be ‘themed’ using XML. A view can be used by any number of activities on Android. Monodroid (thankfully) comes with a UI designer as part of the Monodevelop or VS plug in. SetContentLayout(Resource.Layout.foo); And that’s it to get the UI to display. Attaching events to widgets is simple as well. My UI has a TextView called textView . TextView text = FindViewById<TextView>(Resource.Id.textView); To attach a click event can be done in a number of ways 1.text.Click += delegate {…;}; 2.text.Click += (object s, EventArgs e) => { someMethod(s,e); } 3.text.Click += delegate(object s, EventArgs e) {…;}; 4.text.Click += HandleClick; Each has a different purpose 1.Used for performing a particular task where the event parameters can be completely ignored (for example, performing a calculation or calling another method with any number of parameters, the return value of which is used in some way) 2.Used as a both a standard event and also it allows for methods to be overloaded (so pass s , e and say an int , string and bool as well) 3.Similar to (1), except now the event parameters are being passed in and can therefore be accessed and worked with. 4. HandleClick does what it says on the tin. This is call to the method HandleClick . The object and eventargs are passed into the call. This is handled outside of the OnCreate method. iOS As you may expect from Apple, everything on their devices is a rich experience and for that to happen, the developer has to be free to allow their mind to roam, not be constrained by box limitations and generally whatever they want to go, can go. All iOS UI development had to be done on a Mac. This may change in the future, but for now, it’s safe to say that all design will be done using XCode. XCode is free to download from Apple. The most recent version of Xamarin.iOS will allow you to code for Apple devices on a PC, as long as there is a networked Mac for XCode to be accessed on. With XCode, you can put things wherever you like and don’t have the same rigid design constraints as you do for Android or Windows Phone. Unlike Android though, the communication between the iOS UI and application is a bit more complex. With iOS, you have two types of interface, an outlet and an action. Don’t let the names fool you; an outlet is the one that reacts when you click on it, the action is the receiver. A widget can be both an action and outlet. Take the following code btnClickMe.TouchDown += delegate { btnClickMe.SetTitle ("Clicked", UIControlState.Highlighted); }; Here, btnClickMe is both the outlet ( TouchDown event) and the action ( SetTitle ). When creating the UI though, it is usually sufficient to say if an object is an outlet or an action. iOS calls the view into existence when the class it belongs to is called into existence. However, there are some considerations to add along to that. public override void ViewDidLoad() This method is called immediately after the class has been instantated. At this point, you can either add in what you want the outlets to do, or call another method to do that for you (which can be preferable sometimes). This is similar to the Android OnCreate method. public override void ViewDidUnload() called when the class is finished with. This removes the view, so freeing up the memory it previously occupied. Unlike Android, the types of (say) Click are different. Typically in Android, you have Click. In iOS, there are 9 different Touch events covering cancel, drag, clicks inside of an object and even a plain normal click ( TouchDown ). It could be considered overkill, or it could be considered as giving the developer far greater control over every aspect of the development cycle. Either way, there are a lot of them. Memory management This is not an issue for iOS. The ViewDidUnload() method removes the view, frees the memory and makes life easy. Not so on Android. The reason for this is easy enough. Monodroid is C# on top of Java. Think of it more as a glue layer than anything. When an object is created in C#, the C# GC disposes of the object when it’s done with. The problem is this. When dealing with the UI, the glue creates a Java object for (say) the TextView widget and everything to do with that widget is handled through the glue layer. At the end of it’s life, the C# GC will clear away only the reference it has used. It does not dispose of the underpinning object from the Java layer – the Java object sits there, hogging memory until the app falls over dead. For Android, there are two simple methods to ensure you don’t run out of memory 1.Whenever you can, if a process is memory intensive (typically anything to do with graphics), employ something like using (Bitmap bmp = CreateBitmapFromFile(filename)) { } . Once out of scope, the memory is freed up. 2.At the end of the activity, explicitly dispose of the objects by calling the GC. protected override void OnDestroy() { base.OnDestroy(); GC.Collect(); } will do this for you. That’s enough for this time. Next time I’ll start to look at code and how it differs between the platforms to do the same task. References [1] [2] [3] 12 | | MAY 2013 {cvu} Let’s Talk About Trees Richard Polton puts n-ary trees to use parsing XML. his article will show how to define a tree data structure in both C# and F# and then will proceed to create a tree and load the contents of an XML file containing SPAN data into it. Let’s start with a quick recap over tree structures. The classic binary tree, which contains a value at each node, might be represented in C# as shown in Listing 1. As can be seen, the data structure is defined recursively. That is, it is defined in terms of itself. Therefore, any node contains zero, one (because the code has allowed null in the setter) or two subtrees in addition to a value of type T . Such a tree might be initialised using var t = BinaryTree.Node( 5, BinaryTree.Node( 8, BinaryTree.Leaf(9), BinaryTree.Leaf(7)), .Node( 2, BinaryTree.Leaf(1), BinaryTree.Leaf(3))); In F# we might define the tree structure as type tree = | Node of 'T * tree * tree | Leaf of 'T which also makes it clearer that any single (sub-)tree is either a branch point, containing both a value and left and right branches, or a leaf, containing only a value. We might then create an object of this type using let t = Node (5, Node ( 8, Leaf 9, Leaf 7), Node ( 2, Leaf 1, Leaf 3)) See [1] and [2] for further information on the definition and traversal of binary tree structures. Let us now generalise this to an n-ary tree. In C# we might write this as Listing 2, which is roughly the C# equivalent of the F# tree definition given by the discriminated union (see [3] for a discussion of Algebraic Data Types) type tree = | Node of 'T * tree list Let us now pause awhile and divert our attention to the reason why this subject presented itself in the first place. XML. XML – it’s supposed to be the Holy Grail of data formats, easily consumed by both the computer and the lucky human reader. I recently had the distinct pleasure of working with some SPAN XML files [4] published by the Australian Stock Exchange. These files are freely available for download and a snippet from one of these files is reproduced here. This snippet (Listing 3), lightly edi ted, was extracted from ASXCLEndOfDayRiskParameterFile130305.spn As might be expected, the XML represents a hierarchical data set. The highest-level element in the snippet, clearingOrg , contains both simple T RICHARD POLTON Richard has enjoyed functional programming ever since discovering SICP and feels heartened that programming languages are evolving back to LISP. He likes ‘making it better’ and enjoys riding his bike when he can’t. He can be contacted at richard.polton@shaftesbury.me <clearingOrg> <ec>ASXCLF</ec> <name>ASX Clear Futures</name> <curConv> <fromCur>AUD</fromCur> <toCur>USD</toCur> <factor>0.000000</factor> </curConv> <pbRateDef> <r>1</r> <isCust>1</isCust> <acctType>H</acctType> </pbRateDef> <pbRateDef> <r>4</r> <isCust>1</isCust> <acctType>H</acctType> </pbRateDef> </clearingOrg> Listing 3 public class BinaryTree<T> { public T Value { get; private set; } public BinaryTree<T> Left { get; private set; } public BinaryTree<T> Right { get; private set; } public BinaryTree(T value, BinaryTree<T> left, BinaryTree<T> right) { Left = left; Right = right; Value = value; } } public static class BinaryTree { public static BinaryTree<T> Node<T>(T value, BinaryTree<T> left, BinaryTree<T> right) { return new BinaryTree<T>(value, left, right); } public static BinaryTree<T> Leaf<T>(T value) { return new BinaryTree<T>(value, null, null); } } Listing 1 public class NaryTree<T> { public Tuple<T,List<NaryTree<T>>> Node { get; private set; } public List<NaryTree<T>> SubTrees { get { return Node.Item2; } } public NaryTree(T value, List<NaryTree<T>> subTrees) { Node = Tuple.Create(value, subTrees); } } Listing 2 MAY 2013 | | 13 {cvu} and complex data elements, eg name and pbRateDef respectively. (Before you ask, no, I didn’t change the names of the elements. They really are called ec and r !) We want to load the XML and parse it into a data structure using F#. We want to do this so that we can subsequently query the data set automatically instead of having to rely on eyeballs and Notepad. I say Notepad because, although the data sets are not especially large, they do appear to be large enough to cause both Internet Exploder’s and Visual Studio’s XML renderers to fail, which leaves the ever-faithful Notepad as our key inspection vehicle. The first attempt at parsing this XML made use of discriminated unions like the below: type SpanXMLClearingOrg = | Ec of string | Name of string | CurConv of SpanXMLCurConv list | PbRateDef of SpanXMLPbRateDef list gi ven pri or si mi l ar defi ni t i ons for SpanXMLCurConv and SpanXMLPbRateDef . This layout maps trivially to the XML representation and so building a parser for this is very easy. Whilst it may be possible to parse this XML using LINQ to XML using a dictionary as demonstrated in [5], in this version of the parser, the XML is read using recursive functions such as seen in Listing 4. As can be seen, the function makes use of an accumulator (see article in previous CVu for a quick intro or htdp.org [6]) to store the state of the parsed structure up until the current point. In the example code the state is called acc and is a list of SpanXMLClearingOrg . Other than that the parser simply repeats the above form for each data structure that is to be read from the XML. That is, compare the name of the current element with one of a set of possible names and take the appropriate action, which is one of converting the element value to a specific data type, eg int , or reading an embedded data structure, eg PbRateDef . The result is then prepended to the accumulated list of data structures loaded thus far and then the function is called again. If the name of the current element does not match any of the possible names then the function exits returning the accumulated list to the caller. Thus the tree is built up as the XML is consumed. In the end we had a tree of data but unfortunately it turned out to be very difficult to query. So much so, in fact, that an alternative representation was sought. Instead of the ‘natural’ mapping from XML to structures as shown above, we chose to use a traditional functional tree data structure. In the literature, for example [7], functional tree structures are presented for binary trees. They look like this: type tree = | Leaf of string | Node of tree * tree In other words, every node in the tree contains either two further trees or a value, in this case a string. Note that the data structure is defined recursively. Our tree, however, is slightly different. It is not a binary tree but is an n-ary tree (where n depends on the actual location in the tree). Also each node has one or more values. Additionally, each of the different levels of the tree, at least in the XML, can only be created from a well-defined subset of data types. We can tackle the fact that a node has a value as well as a subtree by defining our tree structure as type tree = | Leaf of string | Node of string * tree * tree This is a bit unsatisfactory, though, primarily because of the unnecessary distinction between Leaf and Node as all the nodes in our tree contain data. However, we can modify the definition to accomodate this and extend to multiple sub-trees using type tree<'T> = | Node of 'T * tree<'T> list Et voilà! Well, almost. We now have a recursive tree structure whose every node can contain a datum as well as zero (because the list can be empty) or more sub-trees. The next challenge is how to render our data structures such that they will fit in this new tree. We can solve this trivially by defining an algebraic data type to be the union of all the possible types of data that can be stored at a node. In order to retain the structure of the original XML, we choose to create records (which are like ‘C’ structures) that hold the data values and then the union refers to all the record types. So, for example, we can define the record type SpanXMLCurConv = { FromCur : string ToCur : string; Factor : float; } to represent the currency conversion data element curConv . This XML element does not contain any complex XML elements itself but its parent, the XML element clearingOrg , clearly does. We choose to represent clearingOrg as the record type SpanXMLClearingOrg = { Ec : string; Name : string; } Note that the nested complex XML elements are not stored within the record in this implementation (unlike in the first implementation of the parser). This is because we will be storing the nested complex elements in the list of sub-trees. However, we still need to define a union so that it is possible to store one of a number of distinct data types in the data value of the node. So we write type nodeType = | .... | SpanXMLCurConv of SpanXMLCurConv | ... | SpanXMLClearingOrg of SpanXMLClearingOrg | ... where the first of the two names in the union is the name of the discriminator and the second is the name of the type that is stored therein. Now we can rewrite our tree type definition as type tree = | Node of nodeType * tree list let rec readClearingOrg (reader:System.Xml.XmlReader) acc = match reader.Name with | "ec" -> SpanXMLClearingOrg.Ec (reader.ReadElementContentAsString()) :: acc |> readClearingOrg reader | "name" -> SpanXMLClearingOrg.Name (reader.ReadElementContentAsString()) :: acc |> readClearingOrg reader | "curConv" -> (SpanXMLClearingOrg.CurConv (readCurConv (reader.ReadStartElement() ; reader) [] )) :: acc |> readClearingOrg (reader.ReadEndElement() ; reader) | "pbRateDef" -> (SpanXMLClearingOrg.PbRateDef (readPbRateDef (reader.ReadStartElement() ; reader) [] )) :: acc |> readClearingOrg (reader.ReadEndElement() ; reader) | _ -> acc Listing 4 14 | | MAY 2013 {cvu} The advantage of a data structure of this form is the ease by which it can be traversed and, therefore, queried. Given the above definition, we can write queries to extract all curConv elements very simply (Listing 5). If we want to find a specific conversion, say from GBP for example, then we could modify our function to take an extra parameter and to use this as a guard in the ‘match’ (Listing 6). It couldn’t be easier. This works because of the power of the F# pattern matching. This is analogous to the switch statement in C-style languages except that the pattern that is being matched is not constrained to compile- time constants. Type matching, as here, is commonplace, as are more sophisticated matches on the return values of functions. Look at Functional.Switch for an example of a similar construct in C# (both prior editions of CVu and functional-utils-csharp [8] on Google Code). So it looks like the pain of transforming the XML into our new tree structure is going to pay dividends (boom! boom!). All that is missing now is that transformation. The ‘read’ functions all have the same format. On account of there being so many record types having such similar structure, we created a code generator to simplify the work. This code generator produces the basic reader function which we then manually modify to account for the nested structures. (This was a trade-off; time to code vs time to edit by hand, and the latter won the day.) For the terminally curious, the code generator lives in the span-for-margin project [9]. Notice that, although findAllCurConv is a very simple query function, it has a shortcoming in that it only returns those nodes which satisfy the criterion supplied and does not provide the route taken through the tree in order to reach them. We want to modify the function so that a path to each successful node is also returned. First, then, we need to change the internal find function to return a 2-tuple, having the matching node and the path to the matching node as its components. This 2-tuple becomes our accumulator. Therefore, on a successful match we return (node, (uNode :: path |> List.rev)) :: acc where node is the Node which has been matched, uNode is the SpanXML record, path is a list of SpanXML records traversed to reach this point and acc is the accumulator. Note that we have to reverse the path list once we have a match because functional lists prepend new items to the head rather than append to the tail. If the function fails to find a matching node, i.e. we have an unsuccessful termination condition, then at the bottom of a given branch we just return the current state of the accumulator. In the ‘inbetween’ state where we have a node which does not match but is not a leaf node, i.e. it has a non-empty list of sub-trees, we need to prepend this node to the path and then call the recursive find function again for each of the subtrees under this node. And so we can write Listing 7: collect is the F# analogue of SelectMany , or more precisely, SelectMany i s based upon t he al gori t hm encapsulated by collect . That is, given a function which accepts a single element and which returns a list, evaluate this function for every element in the container and flatten the results into a single list. Now suppose we want to find the Div nodes in the tree which satisfy some predicate. We could write very similar code to findCurConvWithPath , changing only the nodeType name in the match (Listing 8) using, for example: let divDateChk fromCur (curConv:SpanXMLCurConv) = curConv.FromCur = fromCur findDivs (divDateChk "1-Apr-2013") theTree Clearly, the findNodeTypeWithPath pattern will be repeated for all node types to be queried in the tree. Instead of copying the entire function perhaps there is some way we can generalise the findN function. Active patterns [7] are the obvious choice here. This would leave us with let findNodeWithPath actPattern f tree = let rec findNode tree acc path = match tree with | actPattern .... but the problem with this is that it does not appear to be possible to pass an Active Pattern as a parameter to a function. If any of you know how to do this, my email address is in the byline. Otherwise, huh! So much for all functions being first-class objects in F#. Therefore, we would like to be let findAllCurConv theTree = let rec findAllCurConv' theTree acc = match theTree with | Node (SpanXMLCurConv (_), _) as node -> node :: acc | Node (_, subTrees) -> subTrees |> List.collect (fun node -> findAllCurConv' node acc findAllCurConv' theTree [] Listing 5 let findCurConvFrom fromCur theTree = let rec findCurConvFrom' theTree acc = match theTree with | Node (SpanXMLCurConv (curConv), _) as node when curConv.FromCur = fromCur -> node :: acc | Node (_, subTrees) -> subTrees |> List.collect (fun node -> findCurConvFrom' node acc) findCurConvFrom' theTree [] let allConversionsFromGBP = findCurConvFrom "GBP" theTree Listing 6 let findCurConvWithPath fromCur tree = let rec findCurConv tree acc path = match tree with | Node (SpanXMLCurConv (cc) as uNode, _) as node when curConv.FromCur = fromCur -> (node, (uNode :: path |> List.rev)) :: acc | Node (_, []) -> acc | Node (uNode, trees) -> trees |> List.collect (fun node -> findCurConv node acc (uNode :: path)) findCurConv tree [] [] Listing 7 let findDivsWithPath pred tree = let rec findDivs tree acc path = match tree with | Node (SpanXMLDiv (div) as uNode, _) as node when pred div -> (node, (uNode :: path |> List.rev)) :: acc | Node (_, []) -> acc | Node (uNode, trees) -> trees |> List.collect (fun node -> findDivs node acc (uNode :: path)) findDivs tree [] [] let findDivs f tree = findDivsWithPath f tree |> List.map first Listing 8 MAY 2013 | | 15 {cvu} able to define a general Active Pattern which accepts a parameter. This parameter would then be the type name that we wish to check. let (|Check|) theType input = ... However, this quickly becomes unwieldy leading to a worse mess of code than we had in the original problem and so we must seek an alternative approach. Given that we are not going to be able to use an Active Pattern, let us pass instead a predicate-like function that returns an option (again, see previous CVu and Google Code [8]). Even though adopting this approach means that we will have to perform an additional pattern match step outside of our generic function, it should be an improvement. See Listing 9. In this function, pattern is a function with signature (tree -> (nodeType * 'a) option) . For example, the following function divNode could be used as the pattern . let divNode input = match input with | Node (SpanXMLDiv (record) as uNode, _) as node -> Some(uNode,node) | _ -> None However, this doesn’t allow us to filter the Div nodes of interest as we can do so in findDivsWithPath . If we modify the function to accept an additional parameter then we can pass a curried function into the find function. So we write let divNode f input = match input with | Node (SpanXMLDiv (record) as uNode, _) as node when f record -> Some(uNode,node) | _ -> None where divNode has been redefined to accept a predicate f . Now we can write let divs = findNodeWithPath (divNode fn) tree for some given value of fn to populate divs with all the Div nodes in tree that satisfy fn . An example of fn is let fn (div:SpanXMLDiv) = div.SetlDate > 20100301 With this solution it is still necessary to copy and edit the XNode function for each of the types in the tree but this is a simpler piece of code which does nothing more than return a success value or None , a reasonable compromise. Finally we present the boiler-plate code to populate one of the SpanXMLxxx records, specifically the SpanXMLClearingOrg . The steps are simple. We initialise a dictionary which records the state (incomplete, for the most part) of the current record being created. Therefore, this dictionary contains an entry for each of the fields in the record, i.e. each of the simple XML elements contained within the clearingOrg XML element. Next we define a function, read , which transforms the element into a field in the record. The simple elements are read in directly through an appropriate conversion. Again, this could probably be performed using LINQ-to- XML in the manner demonstrated in [5], especially as we are using a dictionary to store the state, but we will persist with the recursive solution for now. The complex elements are read in using their own equivalent read function and prepended to the state. Note that there are, in principle, two separate vehicl es for retaini ng the st ate information; the dictionary already discussed for the simple types and a list for each of the complex types. Having read the clearingOrg element and its constituent parts we then construct the SpanXMLClearingOrg record setting the fields accordingly and concatenating all the lists of complex XML elements together into a single list, the list of subtrees. Given equivalent definitions of readCurConv and readPbRateDef we can write Listing 10. And there we have it. A lightning-fast discussion of n-ary trees followed by a somewhat more long-winded, yet still abbreviated, example of one in action in the Real World [10]. It’s not all work, work, work [11] though. Trees have other uses. For example, one could have written Colossal Cave [12] using a tree structure. Suppose we wanted to recreate something like the ‘maze of twisty little passages, all alike’ or, indeed, the ‘maze of twisty little passages, all different’. First we need to design the tree structure. We might choose the mutually- recursive type tree = | Corridor of int * int * room list | DeadEnd | Exit and room = | Room of int * tree list The integers would be references into simple arrays of adjectives, so that the description of the nodes in the tree can be varied. This tree does not directly support cyclic data. To do that with the above structure it would be necessary to use generator functions and slightly redefine the Corridor and Room to refer to delayed objects. In such a way, a previous state could be substituted for a new node in the tree. let findNodeWithPath pattern tree = let rec findNode tree acc path = match pattern tree with | Some(uNode,node) -> (node, (uNode :: path |> List.rev)) :: acc | _ -> match tree with | Node (_, []) -> acc | Node (uNode, trees) -> trees |> List.collect (fun node -> findNode node acc (uNode :: path)) findNode tree [] [] Listing 9 let readClearingOrg (reader:System.Xml.XmlReader) let dict = ["ec","":>obj; "name","":>obj; ] |> toDict let rec read curConv pbRateDef = match reader.Name with | "ec" as name -> dict.[name] <- readAsString reader ; read curConv pbRateDef | "name" as name -> dict.[name] <- readAsString reader ; read curConv pbRateDef | "curConv" as name -> read (Node (readCurConv reader) :: curConv) pbRateDef | "pbRateDef" as name -> read curConv (Node (readPbRateDef reader) :: pbRateDef) | _ -> curConv, pbRateDef reader.ReadStartElement() let curConv, pbRateDef = read [] [] reader.ReadEndElement() SpanXMLClearingOrg( { Ec = dict.["ec"] :?> string Name = dict.["name"] :?> string }), (curConv @ pbRateDef) Listing 10 16 | | MAY 2013 {cvu} This, however, we leave as an exercise for the reader, particularly the reader who feels that they ought to contribute an article to CVu but just can’t think of a topic. References [1] Tree structures [2] Traversing trees [3] Algebraic Data Type Algebraic_data_type [4] ASX Risk Parameter file [5] Linq-to-XML example 9719526/seq-todictionary [6] Recursive functions using the Accumulator pattern 2003-09-26/Book/curriculum-Z-H-39.html [7] Expert F# v2.0, Don Syme [8] Functional C# [9] Span parser on Google Code- margin/ [10] [11] All+work+and+no+play+makes+Jack+a+dull+boy [12] Colossal Cave walkthrough adventure.html Let’s Talk About Trees (continued) Team Chat Chris Oldwood considers the benefits of social media in the workplace. s I write this MSN Messenger is taking its last few breaths before Microsoft confine it to history. Now that they own Skype they have two competing products and I guess one has to go. I’m sad to see it be retired because it was the first instant messaging product I used to communicate with work colleagues whilst I was both in and out of the office. At my first programming job back in the early 90s the company used Pegasus Mail for email as they were running Novell NetWare. They also used TelePathy (a DOS based OLR) to host some in-house forums and act as a bridge to the online worlds of CompuServe, CIX, etc. Back then I hardly knew anyone with an email address and it was a small company so I barely got any traffic. The conferencing system (more affectionately known as TP) on the other hand was a great way to ‘chat’ with my work colleagues in a more asynchronous fashion. Although some of the conversations were social in nature, having access to the technical online forums was an essential developer aid. Even the business (a small software house) used it occasionally, such as to ‘connect’ the marketing and development teams. Whereas email was used in a closed, point-to- point manner, the more open chat system allowed for the serendipitous water-cooler moments through the process of eavesdropping. As the Internet took off the landscape changed dramatically with the classic dial-up conferencing systems and bulletin boards (BBS’s) trying to survive the barrage of web based forums and ubiquitous access to the Usenet. Although I did a couple of contracts at large corporations I still had little use for office email and that continued when I joined a small finance company around the turn of the millennium. It was nice being back in a small company – working with other fathers who also had a desire to actually spend time with their families – because it meant we could set up remote working. The remote access was VPN based (rather than remote desktop) which meant that we would have to configure Outlook locally to talk to the Exchange server in the office. This was somewhat harder back then and it was just another memory hog to have cluttering up your task bar. A few of us had been playing with this new MSN Messenger thing, which, because we were signed up personally meant that whether we were at home or in the office we easily talk to each other. Given our desire to distribute our working hours in a more family friendly manner that meant we often found ourselves working (remotely) alongside a team-mate in the evening. Instant messaging soon became an integral part of how the team communicated. With the likelihood that at least one of us was working from home we could still discuss most problems when needed. Of course there was always the option to pick up the old fashioned telephone if the limited bandwidth became an issue or the emoticon count reached epidemic proportions. Even 3- and 4-way conversations seemed to work quite painlessly. However shared desktops and whiteboards felt more like pulling teeth, even over a massive 128 Kbps broadband connection. Eventually I had to move and I ended up back at one of those big corporations – one that was the complete opposite of my predecessor. Here A we often found ourselves working (remotely) alongside a team- mate in the evening In the Tool Box # 2 MAY 2013 | | 17 {cvu} everything was blocked, you couldn’t (or shouldn’t) install anything without approval and instant messaging was blocked by the company firewall. In this organisation email ruled. This was not really surprising because The Business, development teams, infrastructure teams, etc. were all physically separated. Consequently emails would grow and grow like a snowball as they acquired more recipients, questions and replies until eventually they would finally die (probably under their own weight) and just clog up the backup tapes. The company’s technical forums were also run using email distribution lists. Anyone brave enough to post a question had to consider the value of potentially getting an answer versus spending the next 20 minutes dealing with the deluge of Out of Office replies from the absent forum participants. They even had a special ‘Reply All’ plug-in that would pop up a message box to check if you were really, really, really sure that every recipient you were intending to spam actually needed to see your finest display of English prose and vast knowledge of the subject matter. Little known to most employees the company actually ran an internal IRC style chat service. Presumably, in an attempt to reduce the pummelling the Exchange Server was taking, they forced their developers to ‘discover’ it by making the chat client start up every time they logged in. They also disbanded the email distribution lists and set up IRC channels instead. Even the ACCU had its own channel! It may sound like a draconian tactic, but it worked, and I for one am really glad they did. Suddenly the heydays of the conferencing system I had used back in the beginning were available once more. Although there was a ‘miscellaneous’ topic where a little social chit-chat went on I’d say that by-and-large the vast majority of the public traffic was work related. Both junior and senior developers could easily get help from other employees on a range of technical subjects covering tools and languages. Naturally, given the tighter feedback loop, the conversations easily escalated to the level of ‘what problem are you trying to solve exactly?’ which is often where the real answer lies. One particular channel was set up to try and enable more cross pollination of internal libraries and tools. In an organisation of their size I would dread to think how many logging libraries and thread pools had been implemented by different teams over the years. Our system also had its own dedicated channel too which made communicating with our off-shore teams less reliant on email. Given the number of development branches and test environments in use this was a blessing that kept the inbox level sane. The service recorded all conversations, which I’m sure to some degree kept the chatter honest, but more importantly transcripts were available via a search engine which made FAQs easier to handle. When it came time to move contracts once more I was sorely disappointed to find myself back where I was originally with the last company. Actually it was worse because there were no internal discussion lists either that I could find. Determined not to let my inbox get spammed with pointless chatter I set up a simple IRC server for our team to use. My desire was to sell its benefits to other teams and perhaps even get some communities going, even if we had to continue hosting the server ourselves. Internally the company had Office Communicator (OC), which in the intervening years had acquired the same chat product my previous client used, but sadly this extra add-on was never rolled out and so we remained with our simple IRC setup. Contact with some of the support teams was occasionally via OC but For me IRC style communication has been perfect for the more mundane stuff. For example things like owning up to a build break, messing with a test environment, forwarding links to interesting blog posts or just polling to see if anyone is up for coffee. Using a persistent chat service (or enabling client side logging) also allows it be used as a record of events which can be particularly useful when diagnosing a production problem. I suspect that from a company’s perspective they are worried that such as service will be abused and used for ‘social networking’ instead, which is probably why they blocks sites like Twitter and Facebook. However, if teams are left to their own devices they will fill the void anyway and so a company is better off providing their own service which everyone expects will be monitored and so will probably self-regulate. But the biggest benefit must surely come from the sharing of knowledge in both the technical and problem domains. As the old saying goes, “ A rising tide lifts all boats. ” we often found ourselves working (remotely) alongside a team- mate in the evening Write for us! C Vu and Overload rely on article contributions from members. That’s you! Without articles there are no magazines. We need articles at all levels of software development experience; you don’t have to write about rocket science or brain surgery. What do you have to contribute? What are you doing right now? What technology are you using? What did you just explain to someone? What techniques and idioms are you using? For further information, contact the editors: cvu@accu.org or overload@accu.org 18 | | MAR 2013 {cvu} Standards Report Mark Radford looks at some features of the next C++ Standard. n my last few standards reports I’ve been going on about the forthcoming ISO C++ standards meeting in Bristol. Well, it is forthcoming no longer and is currently (at the time of writing) taking place. The delegates number about 100 (which is very much on the high side, although not all of them are there every day) and, whereas meetings have traditionally lasted five days, they are now extended with Bristol being the first six day meeting. The pre-meeting mailing contained 96 papers (compare with 41 and 71 papers in the pre-meeting mailings for the early and late 2012 meetings, respectively). Given that the meeting is in the UK for the first time in six years I was disappointed that, because of work commitments, I was unable to attend. However I managed to visit on Wednesday evening, which was a good time to be there owing to the Concepts Lite presentation which I will talk about below. In November 2012’s CVu I gave a summary of the structure of the committee: at the time there were three working groups and six study groups. Since then activity has increased so that there are now four working groups and eleven (!) study groups. In addition to the traditional Core, Library and Evolution groups, there is now a separate Library Evolution working group. The list of study groups now consists of: Concurrency and Parallelism (SG1), Modules (SG2), File System (SG3), Networking (SG4), Transactional Memory (SG5), Numerics (SG6), Reflection (SG7), Concepts (SG8), Ranges (SG9), Feature Test (SG10), Database Access (SG11). Note that not all study groups meet daily during the week of the meeting. For example, the Database group (tasked with ‘creating a document that specifies a C++ library for accessing databases’) only had its first meeting on Thursday morning. Before going any further I’d like to talk briefly about one of the deliverables a standards committee can produce: that is, a technical specification, or TS for short. Readers may have come across a technical report (TR) before, such as TR1 which proposed various extensions to the library for C++0x. A TR is informational whereas, by contrast, a TS is normative. More information about this can be found on ISO’s web site [1]. Readers will no doubt be aware of the Concepts proposal and its troubled journey through the process leading to the C++11 standard, only to be pulled at the eleventh hour. The story of Concepts, in my opinion, should serve as a cautionary warning: the original proposal inspired more ideas and the whole thing grew and grew in complexity. In the end, its removal from the C++11 (C++0x at the time) standard was a pragmatic necessity in order to ship the new standard that had become long overdue. Now, Concepts are back on the agenda for the future of C++, reinvented in the form of Concepts Lite. The current main source of information on Concepts Lite is the paper ‘Concepts Lite: Constraining Templates with Predicates’ by Andrew Sutton, Bjarne Stroustrup, Gabriel Dos Reis (N3580). There is also a web site [2]. Given the history of this feature (alluded to above), I had concerns about its reintroduction. Therefore, I was glad I had the chance to go to the Wednesday evening presentation given by Andrew Sutton. This was the same presentation he gave at the ACCU conference and it can downloaded [3]. I found myself liking Concepts Lite. My original understanding was (and I can’t remember where it came from) that the aim was for the feature to be in C++14. However, this matter came up at the presentation and Andrew Sutton said this wasn’t going to happen, rather there would be a TS instead. Currently there are no library proposals, but the TS will probably include some library features (or there may even be a separate TS for a constrained library). This proposal has generated a lot of interest among the committee, and I expect it will so do so among t he C++ community in general. Therefore, I will spend the rest of this report on it, and go into some more detail. Concepts Lite Concepts Lite offer an effective approach to constraining template arguments without the complexity of the original Concepts. They do, however, leave open a migration path to full Concepts. Currently though, they are much simpler than Concepts were. In particular, there is no attempt to check the definition of the template: the constraints are checked only at the point of use. This is a big difference when compared to the Concepts originally proposed: Concepts Lite are intended to check the use – and not the definition – of templates. Other good points include: observed compile-time gains of between 15% and 25% (according to Andrew Sutton), templates can be overloaded on their constraints, and the constraint check is syntactic only. That last point is another source of simplification. Consider an Equality_Comparable constraint: this would enable the compiler to check that a template argument type is comparable using operator== , but there is no mechanism for attempting to evaluate whether or not the operator== has the correct semantics. Regarding overloading, function templates would be selected on the basis that the more constrained template is the better match. The icing on the cake is that much of Concepts Lite has been implemented on a branch of GCC 4.8 in an experimental prototype [3]. That wraps up another standards report. As usual, N3580 and all the other submitted papers can be found on the website [4]. Finally, I would like to thank Steve Love for his flexibility with deadlines. References [1]- all.htm?type=ts [2] [3] [4] I MARK RADFORD Mark Radford has been developing software for twenty-five years, and has been a member of the BSI C++ Panel for fourteen of them. His interests are mainly in C++, C# and Python. He can be contacted at mark@twonine.co.uk MAY 2013 | | 19 {cvu} Code Critique Competition 81 Set and collated by Roger Orr. A book prize is awarded for the best entry Please note that participation in this competition is open to all members, whether novice or expert. Readers are also encouraged to comment on published entries, and to supply their own possible code samples for the competition (in any common programming language) to scc@accu.org. Last Issue's Code I have been starting to use IPv6 and have tried to write a routine to print abbreviated IPv6 addresses following the proposed rules in RFC 5952. It’s quite hard – especially the rules for removing consecutive zeroes. Can you check it is right and is there a more elegant way to do it? Here is a summary of the rules: Rule 1. Suppress leading zeros in each 16bit number Rule 2. Use the symbol "::" to replace consecutive zeroes. For example, 2001:db8:0:0:0:0:2:1 must be shortened to 2001:db8::2:1. If there is more than one sequence of zeroes shorten the longest sequence – if there are two such longest sequences shorten the first of them. Rule 3. Use lower case hex digits. The code is in Listing 1. /* cc80.h */ #include <iosfwd> void printIPv6(std::ostream & os, unsigned short const addr[8]); /* cc80.cpp */ #include "cc80.h" #include <iostream> #include <sstream> namespace { // compress first sequence matching 'zeros' // return true if found bool compress(std::string & buffer, char const *zeros) { std::string::size_type len = strlen(zeros); std::string::size_type pos = buffer.find(zeros); if (pos != std::string::npos) { buffer.replace(pos, len, "::"); return true; } return false; } } void printIPv6(std::ostream & os, unsigned short const addr[8]) { std::stringstream ss; ss << std::hex << std::nouppercase; for (int idx = 0; idx != 8; idx++) { if(idx) ss << ':'; ss << addr[idx]; } // might be spare colons either side of // the compressed set while (compress(buffer, ":::")) ; os << buffer; } /* testcc80.cpp */ #include <iostream> #include <sstream> #include "cc80.h" struct testcase { unsigned short address[8]; char const *expected; } testcases[] = { { {0,0,0,0,0,0,0,0}, "::" }, { {0,0,0,0,0,0,0,1}, "::1" }, { {0x2001,0xdb8,0,0,0,0xff00,0x42,0x8329}, "2001:db8::ff00:42:8329" }, }; #define MAX_CASES sizeof(testcases) / sizeof(testcases[0]) int test(testcase const & testcase) { std::stringstream ss; printIPv6(ss, testcase.address); if (ss.str() == testcase.expected) { return 0; } std::cout << "Fail: expected: " << testcase.expected << ", actual: " << ss.str() << std::endl; return 1; } int main() { int failures(0); for (int idx = 0; idx != MAX_CASES; ++idx) { failures += test(testcases[idx]); } return failures; } Listing 1 Listing 1 (cont’d) ROGER ORR Roger has been programming for over 20 years, most recently in C++ and Java for various investment banks in Canary Wharf and the City. He joined ACCU in 1999 and the BSI C++ panel in 2002. He may be contacted at rogero@howzatt.demon.co.uk 20 | | MAY 2013 {cvu} Critiques I obviously failed to produce an interesting enough example this time as nobody wrote a critique. That may of course be because few readers are interested in IPV6: I believe the readership of this magazine mostly comes from countries where the shortage of IPV4 addresses is not yet a serious problem. Take-up of IPV6 is most prevalent in countries where the use of the Internet is developing rapidly, such as India and China. Either that, or nobody thought there were any problems with the code. Commentary The first trouble with the code above is the use of an array of 8 short integers to represent an IPV6 address. There may be problems with network byte ordering if the IP addresses used as examples are passed unchanged to a network call. It would be a lot better to use the standard data structures for IP addresses such as in this case in6_addr . It is surprisingly hard to print out (or read in) IPV6 addresses by hand. Fortunately there are very few cases when this is advisable – using a standard facility is very strongly recommended. We do not at present have such a facility in C++ although the networking study group is discussing proposals for a network address class or classes; if a consensus is reached and adopted we might have a standard C++ way to do this before too long. In the meantime you could use boost ( boost::asio::ip::address ): see the to_string method of that class. The function inet_ntop is one standard way to do this in C. char dst[INET6_ADDRSTRLEN]; if (!inet_ntop(AF_INET6, addr, dst, sizeof(dst))) { // handle error... } I would probably try to avoid critiquing the user’s code as provided and focus their attention on using a standard facility. However, once this has been accomplished, I might return to their code and point out that searching the string for "0:…" incorrectly matches the initial zero against any hex number with a trailing zero digit. The test cases provided by the user failed to cover this case. Such failings in test coverage are quite common. For example, a bug was discovered with the streaming of doubles in Visual Studio 2012 (http:// connect.microsoft.com/VisualStudio/feedback/details/778982). I am sure Microsoft have test coverage of this operation; but obviously their test data set lacked adequate coverage. The trouble with doing the abbreviation of the longest run of zeros with the textual representation is that there are boundary conditions at both the beginning and end of the string. I think the easiest algorithm is to pass through the binary representation to find the start address and length of the longest run and then use this information when converting the representation to characters. The algorithm though misses another special case – that of IPV4 mapped and compatible addresses. These have an alternative convention for display which emphases the IPV4 ‘nature’ of the address. So, for example, the IPV6 address 0:0:0:0:0:ffff:c00:280 would be displayed as ::ffff:192.0.2.128 on many platforms. This is would hopefully provide another reason to reinforce why using the standard function is normally preferable to writing your own. Finally I notice that the code to join the eight short integers together with a colon delimiter is addressed by the recent C++ proposal N3594 (‘ std::join() : An algorithm for joining a range of elements ’). Code Critique 81 (Submissions to scc@accu.org by Jun 1st) I am new to C++ and trying to write some objects to disk and read them back in. How can I get the pointer to the objects that are read back in? Where would you start with trying to help this newcomer? The code is in Listings 2, 3, 4 and 5 (note: it uses a few C++11 features so will need modifying to run on a non-conformant compiler): /* * Bike.cpp */ #include "Bike.h" //Bike::Bike() {} // TODO Auto-generated stub Bike::~Bike() {} // TODO Auto-generated stub std::ostream& operator << (std::ostream& os, Bike &m){ os << std::left << std::setw(10) << m.getAddress() << "\t" << m.getName() << "\t" << m.getPrice() << "\t" << m.getMake(); return os; } Listing 2 /* * Bike.h */ #ifndef BIKE_H_ #define BIKE_H_ #include <iostream> #include <string> #include <vector> #include <iterator> #include <algorithm> #include <iomanip> #include <ios> class Bike { Bike* address; // Pointer to Bike object std::string name; double price; std::string make; public: //Bike(); // eliminate to avoid ambiguity Bike(Bike* a, const std::string& n = "unknown", double p=0.01, const std::string& m="garage") : address(a), name(n), price(p), make(m){} virtual ~Bike(); inline std::string getName(){return name;} inline double getPrice(){return price;} inline std::string getMake(){return make;} inline Bike* getAddress(){return address;} static void writeToDisk( std::vector<Bike> &v); static void readFromDisk(std::string); static void splitSubstring(std::string); static void restoreObject( std::vector<std::string> &); }; std::ostream& operator << (std::ostream& os, Bike &b); #endif /* BIKE */ Listing 2 MAY 2013 | | 21 {cvu} You can also get the current problem from the accu-general mail list (next entry is posted around the last issue's deadline) or from the ACCU website (). This particularly helps overseas members who typically get the magazine much later than members in the UK and Europe. /* * file_io.cpp */ #include "Bike.h" #include <fstream> #include <iomanip> #include <iostream> #include <iterator> #include <vector> #include <cstring> #include <sstream> #include <algorithm> // Write objects to disk void Bike::writeToDisk(std::vector<Bike> &v){ std::ofstream out_2("bike_2.dat"); for (auto b:v){ out_2 << b.getAddress() << ':' << b.getName() << ':'<< b.getPrice() << ':' << b.getMake() << std::endl; } out_2.close(); } //-------------------------------------------- //Read from disk into vector and make objects void Bike::readFromDisk( std::string bdat) // "bike_2.dat" { std::cout << "\nStart reading: \n"; std::vector<char> v2; std::ifstream in(bdat); copy(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>(), std::back_inserter(v2)); in.close(); for(auto a:v2){ std::cout << a; // Debug output } std::string s2(&(v2[0])); // Vector in String std::cout << "\nExtract members:\n"; while (!s2.empty()){ // objects separated by \n size_t posObj = s2.find_first_of('\n'); std::string substr = s2.substr(0,posObj); s2=s2.substr(posObj+1); splitSubstring(substr); } } void Bike::splitSubstring (std::string t){ // Save the address and the members in v3 std::vector<std::string> v3{(4)}; size_t posM; // [in substring] int i; for (i=0; i<4; i++){ posM = t.find_first_of(':'); v3[i] = t.substr(0,posM); if (posM==std::string::npos) break; t=t.substr(posM+1); } for(auto member:v3){ std::cout << std::setw(10) << std::left << member << " \t";} restoreObject(v3); std::cout << std::endl; v3.clear(); } Listing 4 void Bike::restoreObject(std::vector<std::string> &v3){ Bike* target; // I want the object here ... double p; std::stringstream ss(v3[2]); ss >> p; Bike dummy{&(dummy),v3[1], p, v3[3]}; target = &(dummy); std::cout << "\nRestore: " << *target << std::endl; } Listing 4 (cont’d) /* * main_program.cpp */ #include "Bike.h" #include <fstream> #include <iomanip> #include <iostream> #include <iterator> #include <vector> #include <cstring> #include <sstream> #include <algorithm> int main(){ std::cout << "start\n"; std::vector<Bike> v; Bike thruxton{&(thruxton), "Thruxton", 100.00 , "Triumph"}; Bike sanya{&(sanya)}; Bike camino{&(camino), "Camino ", 150.00, "Honda"}; Bike vespa{&(vespa), "Vespa ", 295.00, "Piaggio"}; v.push_back(thruxton); v.push_back(sanya); v.push_back(camino); v.push_back(vespa); for(Bike b:v) std::cout << b << std::endl; // using overloaded << operator Bike::writeToDisk(v); // restore objects Bike::readFromDisk("bike_2.dat"); // where are the restored objects?? return 0; } Listing 5 22 | | MAY 2013 {cvu} Patterns Refactoring to Patterns By Joshua Kerievsky, published by Addison Wesley ISBN: 978- 032121335 Reviewed by Alan Lenton For some reason this book escaped my notice until recently, which is a pity, because it’s a very useful book indeed. Quite a lot of programmers, even those using agile methods, seem to think that patterns are merely something that you spot at the design stage. This is not the case, though it’s useful if you do spot a pattern early on. Programs evolve, and as they do, patterns become more obvious, and indeed may not have been appropriate at earlier stages of the evolution. The book, as its title implies, deals with evolving programs, and does it very well. The bulk of the book takes a relatively small number of patterns and, using real world examples, gives a step by step analysis, with Java code, of how to refactor into the pattern. As long as readers do treat these as examples, rather than something set in stone, they will learn a lot about the arts of identifying patterns and the nitty gritty of refactoring. I also liked the pragmatism of the author. Unlike some pattern freaks, he freely admits that there are times when using a specific pattern is overkill, especially where the problem is simple. Most people, myself included, when the idea of patterns are first grasped, tend to see patterns in everything and immediately implement them. This is frequently inappropriate, and rather than making the program structure clearer, muddies the waters. There are a number of warnings in the book against this approach. I was very impressed by this book. In fact it is one o f a small number of books that has made it to my work desk, where it fits, both intellectually and literally, in between the Gang of Four’s Design Patterns, and Martin Fowler’s Refactoring! Highly recommended. Elemental Design Patterns By Jason McC. Smith, published by Addison-Wesley ISBN: 978- 0321711922 Reviewed by Alan Lenton. Android Android Programming Unleashed By B.M. Harwan, published by Sams Reviewed by Paul F. Johnson Not recommended – not even slightly recommended unless you like levelling up beds and even then, I can think of better books. This is my first review in what seems an etern ity and unfortunately, it's not a good one. The Android market it getting bigger by the minute and with that, more and more books are coming out professing to show you how, in 200 pages, you can go from a user to someone who can create an app that redefines the landscape for apps out there. This is no exception. It starts by wasting the first chapter telling you how to install the Android SDK. Why? The installer pretty much does everything for you now. Sure you may need to know how to set up the emulators and you may wish to not just accept the defaults, but why waste a chapter on it? That said, I have the same issue with most books of this ilk; “let’s use a chapter to show some screen dumps of how to install Visual Studio”. Just annoying. Okay, that bit over. What’s left? Code errors everywhere, poor explanations of how things work and why they’re done like that and did I mention stuff that plain doesn’t compile? No? There is quite a bit of it. Ok, let’s look at a particular example on page 188. A nice simple media player. public class PlayAudioAppActivity extends Activity { @override Bookcase The latest roundup of book reviews. If you want to review a book, your first port of call should be the members section of the ACCU website, which contains a list of all of the books currently available. If there is something that you want to review, but can’t find on there, just ask. It is possible that we can get hold of it. After you’ve made your choice, email me and if the book checks out on my database, you can have it. I will instruct you from there. Remember though, if the book review is such a stinker as to be awarded the most un-glamorous ‘not recommended’ rating, you are entitled to another book completely free. Thanks to Pearson and Computer Bookshop for their continued support in providing us with books. Jez Higgins (publicity@accu.org) MAY 2013 | | 23 {cvu} public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstance); setContentView(R.layout.activity_ play_audio_app); Button playButton = (Button)findViewById(R.id.playbtn ); playButton.setOnClickListener(new Button.onClickListener() { public void onClick(View v) { MediaPlayer mp = MediaPlayer.create(PlayAudioAppAc tivity.this, R.raw.song1); mp.Start(); } }); Looks ok, except for the 2 lines that do anything – ( MediaPlayer mp = ... and mp.Start() ) What’s it doing? That’s right, it creates an instance u sing the Activity context and then uses a file in the raw directory. What raw directory? Unle ss the author created one, there isn’t one. It then starts the media player. No sort of trapping or defensive coding, just hey, it works or I’ll leave you to puzzle out why it didn’t – and given quite a lot of the code is written in the same way, the poor ol’ user is left scratching their head and wondering why SAMs didn’t include a source code CD or not limit getting the code for 30 days past purchase of the book. Now, let’s add some insult to injury. The book claims to cover up to 4.1.2, so let’s look at something that varies massively over the versions – animation. Prior to version 3, animation was pretty awful. It worked, but wasn’t really that good. Google rewrote huge chunks for version 3 and animation was there and happy. What does this book say about the differences? Nothing. It sticks to what is there prior to version 3. The only saving grace is the section on using animation using XML. Android comes with SQLite databases as stand ard. Why then does the author go about creating a custom database using ArrayLists? I could really rip into this book and I mean serio usly rip into it, but at the end of the day life is too short to waste my time trying to find code in there that works as it should. Given the author is also a time-served lecturer with an ‘easy to understand’ style, I’m amazed this managed to get past the technical editor’s eye – unless said technical editor is one of his students... Beginning Android 4 Application Development By Wei-Meng Lee, published by Wrox, ISBN 978-1-118-19954-1 Reviewed by Paul F. Johnson Recommended with reservations. There are plenty of awful Android books out there (see my other review for one such example). Lots of errors in the code, broken examples, wasted paper, illogical layouts and well, pretty much a waste of a tree. This is NOT one of those books. This is a rather good book. Not amazing, but still far better than a lot of things out there. From the word go, there are screen shots a-plenty, lots of code examples with the emphasis definitely on trying things out for yourself. But therein lies the problem with the book. It is all well and good having example code, but not when you have to disappear onto a website and dig around for it (it is why this review is on Recommended and not Highly Recommended). A major omission is the lack of anything on graphics handlin g. While it does show you how to display graphics, there is nothing on drawing or use of the camera. An omission which while understandable, does detract from this book quite a lot. Drawing leads into long and short presses, drags, canvases and other fun bits and pieces. Perhaps for the next edition this could be included? Here’s hoping! The author of this work does know what he is on abou t with a clear way to his writing style. I will happily admit that I don’t do Java. I’ve never understood it and really, it doesn’t make too much sense to me. I do, however, program for Android using Xamarin.Android (or Monodroid as it was). There is only one or two books out there that are dedicated to using .NET on Android. The beauty of this book though is that it explains how the system works and how events are used and as long as you know the equivalent in .NET world, this book provides you with a great resource that is currently missing. The book covers just about all of the main parts of An droid development (including data persistence, maps, messaging and networking) up to Ice Cream Sandwich. Jellybean doesn’t appear to be in the book. All in all, this is one of the better books out there for Android development. It’s good, but has its failings. Miscellaneous API Design for C++ By Martin Reddy, published by Morgan Kaufmann ISBN: 978- 0123850034 Reviewed by Alan Lenton Martin Reddy has written a very useful book on the art and science of Application Programming Interfaces (APIs), and along the way has produced a book chock full of useful hints and help for more junior programmers. It is not a book for someone wanting to learn to program in C++, but if you have been programming in C++ for a year or so, then you will find this book will help you move toward towards program design instead of just ‘coding’. Obviously, the book concentrates on API desig n, but along the way it covers selected patterns, API styles, performance, testing and documentation. As a bonus it also covers scripting and extensibility, and I found the section on plugins particularly useful. An appendix covers the varied technical issues involved in building both static and dynamic libraries on Windows Mac and Linux. The only minor disagreement I would have with the author is with the extent to which he goes to move internal details out of header files in the name of preventing the API users from doing anything that might allow them to access those features. From my point of view, using the API is a type of contract between the API writer and the API user. If the user is foolish enough to break that contract then he or she has to take the consequences in terms of broken code when a new version of the library comes out. In any case this sort of behaviour should be picked up by code review in any halfway decent software studio. That is, however, a minor niggle, and this book rep resents a rich seam for programmers to mine for good programming practices – even if you aren’t writing API, your use of them will improve dramatically! The Essential Guide To HTML5: Using Games To Learn HTML5 And JavaScript (Paperback) By Jeanine Meyer, published by FRIENDS OF ED ISBN: 978- 1430233831 Reviewed by Alan Lenton I really can’t recommend buying this book. It seems to have been written mainly for people with a very short attention span, and therefore skips on explaining why you do things in a specific way. The chosen way of displaying programs listings, while it might have be useful for annotating each line, makes it impossible to look at the program flow, or consider the over all design. The one correct idea – that of incremental program development – becomes merely a vehicle for large spaced out repetitive chunks of code which probably extend the size of the book by as much as 20%. The code itself, is, how shall I put it, somewhat less than optimal, and not conducive to creating good coding habits by those learning from the book. For instance, in the dice game example, the code for drawing a dot on the dice is repeated in a ‘cut and paste’ style every time a dot is drawn, instead of being gathered into a function and called each time it is needed. I shudder to think about what sort of web site someone who learned from this book would put together. Fortunately, perhaps, they are not likely to learn enough from the book to make a web site work. A triumph of enthusiasm over pedagogy. Definitely not recommended! 24 | | MAY 2013 REVIEWS accu ACCU Information Membership news and committee reports {cvu} View from the Chair Alan Griffiths chair@accu.org I’ve been given special dispensation by the C Vu editor to submit this report ‘late’ (that is, after the conference and AGM). I know I enjoyed the conference and believe that most of those who could attend did so too. This was the first year away from Oxford, from what I saw it was a mostly successful move. There were a few ‘opportunities for improvement’ but I’m sure that the conference committee will be considering carefully what lessons can be applied for next year. As this is written after the AGM it is possible to report on proceedings there. We had a number of votes and proxies registered on the motions for constitutional change before the meeting, but both these and the votes at the meeting were overwhelmingly in favour of the proposed changes. There were two constitutional motions passed: one p roposed by Roger Orr and Ewan Milne to rationalise the committee posts required by the constitution; and, a much larger one proposed by Giovanni Asproni and Mick Brooks to support voting by members that cannot attend the AGM. Last year’s AGM made changes to the constit ution that required constitutional motions be notified in advance and that preregistered and proxy votes on these motions be accepted. There was also a call for the committee to be more transparent about the way the organisation runs. In line with this we’ve used the members mai ling list to prepare the proposed changes to the constitution. Drafts of these motions were posted to the list and updated in response to addressed in advance of the AGM and the final wording we had was passed quickly. The committee has been taking other steps over th e year to make the operation of the organisation more transparent. As part of this minutes of the committee meetings are now published on the accu-members mailing list once they are approved. Also, while committee meetings have always been open to members (subject to prior arrangement with the secretary) they can now be attended remotely. At this year’s AGM there was also a call from th e floor to ensure that committee members from overseas could attend committee meetings. This didn’t move to a vote as the same technology that allows members to attend remotely is already in use by committee members. One notable failure by the committee was that we did n’t have the accounts ready for the AGM. This has happened before, but was unexpected: the treasurer got the figures to the accountant in what we believed was good time and we only realised that the accounts going to be late when they didn’t appear as expected. In the end, the accounts were actually available for the AGM, but no-one present (neither committee members, nor the honorary auditors) had had a chance to review them. We will be investigating further at the next committee meeting. As anticipated by my last report we’ve had a coupl e of people stand down from the committee – Mick Brooks has been replaced as Membership Secretary by Craig Henderson. Tom Sedge and Stewart Brodie have also stepped down. My last report also mentioned the ‘hardship f und’. This was originally created to support the memberships of individuals who could not finance themselves. However, there have been decreasing calls on this fund over the years and while it is still possible to donate, nothing has been paid out for quite some time. The committee needs guidance on how to proceed: Should we continue accepting contributions to the fund? And what do we do with the money already donated? We do sometimes offer concessionary me mberships to members in financial difficulties. So one option for using the hardship fund could be to ‘make up’ the difference (effectively transferring the money to our general budget). It would also be possible to spend the money in new ways (supporting attendance at the Conference for example). If you can suggest something else then the committee would be pleased to consider it. We still have no volunteer to moderate the accu- cont acts mailing list. This isn’t an onerous task (there are a few emails each week to classify as ‘OK’, ‘Spam’ or ‘needs fixing’) but we don’t currently have a replacement for this role. Is this something you could do for the ACCU? Please contact me at chair@accu.org about any of the items above . Letter to the Editor Dear Editor, Not having used F# before, it was interesting to read Richard Polton's article, ‘Comparing Algorithms’, in the March 2013 C Vu, in which he compares a variety of iterative and recursive solutions to the first Project Euler problem (sum the multiples of 3 or 5 below 1000). As a didactic exercise, this is all well and good. The problem itself, though, strikes me as being very similar to the one in the famous story about Carl Friedrich Gauss; and indeed it turns out that the sum of all multiples of i less than or equal to n can be found (in plain old C) without any loop at all: int sum(int i, int n) { return i * (n/i * (n/i + 1))/2; } We can use this to find the sums of the multiples of 3 and of 5, then remove the ones we’ve double-counted: int euler1(int i1, int i2, int n) { return sum(i1, n-1) + sum(i2, n-1) - sum(i1*i2, n-1); } In C++, if the arguments are constants we can convert function arguments to template parameters, reducing our runtime cost all the way to zero by doing the work at compile time; and in C++11 we should be able to accomplish the same thing simply by sticking constexpr in front of both functions. I think the lesson is that, while iteration, recursion, functional programming, templates, C++11, and all our other flashy tools and techniques each have their place, in our eagerness to try out our new capabilities we mustn’t lose sight of the problem we originally set out to solve. Sincerely, Martin Janzen (martin.janzen@gmail.com) If you read something in C Vu that you particularly enjoyed, you disagreed with or that has just made you think, why not put pen to paper (or finger to keyboard) and tell us about it? Log in to post a comment
https://www.techylib.com/en/view/secrettownpanamanian/cvu_accu
CC-MAIN-2017-22
refinedweb
21,931
61.56
All members of the base class must be Protected and then to make the class itself invisible to the form you could mark it MustInherit. This assumes your heirarchy is compiled into its own namespace as a dll. The user of your form will be able to see the names of your base classes by typing, for example, “Dim cc as” as it will be listed by Intellisense. However, that is all, the user will be able to do – he/she will not be able to instantiate or study the guts of the classes. However, you will need an efficient obfuscator if you want to defend against the Reflector decompiler. REGISTER or login: Discuss This Question:
http://itknowledgeexchange.techtarget.com/itanswers/visual-basic-designing-a-class-library/
CC-MAIN-2014-15
refinedweb
116
68.91
Prism is a set of libraries that allow developers to compose applications from separate components into a composite application. Composite meaning that the application functionality is split up into different modules that do not necessarily know about each other and then brought together to create an application. From the Prism documentation: “Composite applications provide many benefits, including the following: The Prism documentation is actually very good with showing you how to accomplish individual tasks. Where the documentation falls short is when you want to bring the differing concepts together. For example, the documentation does lead you through creating an application and showing a view, what it does not show you is how to create a view that possibly contains multiple “child” views The goals for this article are But before we get to that we have to know; Head on over to the Prism web site,, and download the Prism package. The site also serves as the community portal to ask questions of the Prism development team. Unzip the archive to the folder of your choice then open that folder up in explorer to view the files. The folder will contain several batch files that will conveniently open up several different sections of the Prism project. The two batch files that we are interested in at this time are named “Desktop & Silverlight – Open Composite Application Library” and “Desktop only – Open Composite Application Library”. The first batch file will open up a solution that will compile the libraries to use in WPF and Silverlight. If you are not doing any Silverlight application that you can use the second batch file. But you cannot use the libraries interchangeably (I think, I have not verified this as I do not do Silverlight development but otherwise there would be no need for separate projects). So, double click the batch file of your choice and the Prism solution will load up into Visual Studio 2008 (as of this writing). Then build the solution. The output libraries will be placed in <Prism root>CAL->Desktop I am going to assume that you know how to create an application solution, reference libraries and create class libraries in Visual Studio so I am not going to explain those details in depth. If you do not, you should study those items first. The first thing to do is to fire up Visual Studio 2008. Then create a new WPF application and name it whatever you want. For the purpose of this article I will name my solution “PrismArticle”. This is going to be the “shell” for our application. The shell is just a container to display the primary user interface. The shell can contain one of more views that are displayed to the user. Note that some of the code presented is more or less boilerplate code and copied from the Prism documentation.. But… Everything up to step 8 should be pretty much self explanatory except for step 5. Step 5 is where we setup a ContentControl in the shell window and named it “MainRegion”. Prism uses a concept called a Region that defines an area where a view is going to be displayed. If we had a module that mapped itself to the MainRegion, then that view would appear in that region. We will be doing just that in the next section. Step 9 is where the application main window is created and shown. Step 10 is where a catalog of the modules that the application uses is created. There are several different ways to accomplish this but for our example we are going to use a ConfigurationModuleCatalog which reads a configuration file and loads the modules defined in that file. Step 11 is where the application starts up and instantiates the Bootstrapper. Before we create our first module we need to do a bit of configuration. Remember that we wanted to load our modules at runtime. To do that we have to have a place for the modules to be. So, in the solution folder create a “bin” folder, and then inside that folder create a “modules” folder. The bin folder is where we will put the executable and the modules folder is where the modules are going to go. Open up the project properties and on the Build tab set the output path to the bin folder that we just created. Now for our first module. One thing that I deviate from the Prism documentation is that the Prism docs describe creating the regions to show the views in the shell. What I am going to do is to create a module that is shown in the main window and defines the regions for the application. This way the shell application remains static and the modules define the application. So our first module is the view that is going to be shown in the MainRegion that we defined before. Add a Class Library project to the solution. For the sake of this example, I named my module project “MainWindowModule”. Open the Project properties select the Build tab and then change the output path to the modules folder under the bin folder that we created earlier. Rename the Class1.cs file to MainWindow.cs. This will also rename the class to MainWindow. Add a reference to the Microsoft.Practices.Composite.dll. Then add a using statement to the top of the file: using Microsoft.Practices.Composite.Modularity. Add a private variable to the class named _regionManager of type IRegionManager. The RegionManager allows us to access the regions defined in the application. Add a constructor to the class that accepts an IRegionManager parameter. Inside the constructor, make the _regionManager equal to the IRegionManager passed in. Edit the class definition so that the class inherits from IModule. IModule is the interface that Prism uses to discover and initialize the modules. The method that we need to implement is the Initialize method. Inside the Initialize method, add the MainWindowView to the MainRegion through the region manager: _regionManager.Regions["MainRegion"].Add(new MainWindowView()); Now we need a MainWindowView to show in the MainRegion. Just to make things a bit tidy, add a new folder to our solution named “Views”. Inside the Views folder, add a new WPF user control named MainWindowView. To make everyone happy, you have to add another using statement to include the Views now. using MainWindowModule.Views; Now, after all that what do you think will happen when you build and run the application now? Well, try it and see what happens. Go ahead. I will wait. Ready? What you should have seen is the same window we saw before we created the module and jumped through all those other hoops. If you set a break point in the Initialize method of the module you will find out that the method in not called. So what is up with that? Well before we can see the view in the main window we have to… To configure the application to load our modules we have to add a configuration file to the executable project. So add a New Item -> Application Configuration File. I named my file App.config. This is the configuration file that the application is going to read to create the ConfigurationModuleCatalog in the Bootstrapper class. Add the following code to the app config file: <configSections> <section name=“modules“ type=“Microsoft.Practices.Composite.Modularity.ModulesConfigurationSection, Microsoft.Practices.Composite“ /> </configSections> <modules> <module assemblyFile=“Modules/MainWindowModule.dll“ moduleType=“MainWindowModule.MainWindow, MainWindowModule“ moduleName=“MainWindowModule“ /> </modules> The Modules section defines what module to load and where to load it from. The “assemblyFile” attribute defines from where to load the module from. In this case we are loading the module from the Modules folder. The “moduleType” attribute is the name of the class that we want to load. The Prism docs call this a “type” which might be misleading for a beginner. This is the namespace and name of the class that implements the IModule interface. The last attribute simply defines the module name. There are other attributes that I will leave for another time. This is sufficient to get us going. Now if you run the application you show at least get a stop at the break point you set earlier. But, chances are that you will see a blank window. Unless you open up the MainWindowView XAML file and put something in the window you won’t see anything. Go ahead and experiment and when you are finished playing around we will go on to the next phase. Now that we know how to create and load a module the next thing that we want to do is to create a couple of child windows that we will display in the MainWindowView. We are not going to do anything fancy. Adding child views to the MainWindow is relatively painless. It’s basically the same as what we did for the MainWindowModule expect that the regions that we are going to define are in the MainWindowView. So, open up the MainWindowView XAML file and delete any content that you might have put there to experiment with. If you did do any experimenting you might have noticed that the contents of the MainWindowView were confined to a specific size when you resized the window. This is because of the Width and Height attributes in the view being set to 300. Go ahead and delete those two settings so that the view will fill the parent window. Now add a Grid layout control and define two columns. Add a content control to column zero and add another content control to column 1. Being so imaginative I named the region in column 0 “LeftChild” and the region in column 1 “RightChild”. Of course you are free to improve on that design J Add 2 more class libraries to the solution; name one “ChildOneModule” and the other “ChildTwoModule”. The setup for these modules pretty much mimics the steps we followed to create the MainWindowView. The code for both is about the same except for the region names. Here is what I did. Feel free to experiment. The ChildOneView I simply changed the background color and added a label to identify the view. I did the same to the ChildTwoView except I made the color different. The final application will look like this when it’s all said and done. Final result from all this There we have downloaded and complied the Prism Library. Created a project that created a shell window using Prism, added a module to serve as the main window view and then finally added two more modules that served as two child views and loaded into the application dynamically loaded at runtime. This allows the UI views for the application to be developed separately from each other and to be totally independent code. Hopefully this is just the beginning of an exploration of the Prism framework. Depending on my work load and motivation I may continue writing about this. Next I think that I will explore getting our two child views to communication with each without them having to know anything about each other. Here are links to the code for this article. Rename the archive from .doc to .zip before opening, this is a wordpress requirement. The code is presented as is with no warranty implied or guaranteed. prism-article-part-1 This is the code for the initial project prism-article-part-2 This is the code for the second part of the article prism-article-part-3 This is the final code solution Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
http://www.codeproject.com/articles/35804/Getting-started-with-Prism-2-formerly-known-as-the-Composite-Application-Library.aspx
CC-MAIN-2014-42
refinedweb
1,946
63.59
Pylons Cheat Sheet May 13, 2009 § Leave a Comment SqlAlchemy in Three Minutes May 10, 2009 § Leave a Comment The documentations of SqlAlchemy gets better in every version, but I can never remember the steps of creating Engine, Index, and Session. So, I created 3 minutes tutorial on how to define the ORM class using declaration_base(), build that table, populates, and fetch. Python: Object to JSON April 27, 2009 § Leave a Comment Python: using Memcache Client April 23, 2009 § Leave a Comment For some reason, it’s always hard to find example on how to create memcache client object using Python. This time, I will remember: import memcache memc = memcache.Client(['127.0.0.1:11211']): Python: Drinking the Tokyo Kool-Aid April 16, 2009 § 1 Comment After reading what LightCloud can do, of course, it’s only natural to create object that serialized to Tokyo. And that exactly what I did. The project (called Hail) is still infant, but the profile tests already answers some of my questions and curiosity about LightCloud (and Tokyo). One obvious weakness I need to tackle: Serializing is too slow. Questions that got answered: - Slowness is not caused by the size of the object, instead it is caused by number of items. - LightCloud does execute a lot of function calls. Most of the are really fast though. - EDIT: Tokyo is fast! Especially after I compare it with Memcache. But LightCloud is not. Tokyo is not as fast as I thought… but this is not final thought, I should create profile_test on raw tokyo tyrant node. On top of that LightCloud overhead is not negligible. - Serializing to cjson is faster than cPickle. That’s surprising. Next, I should test getting items from both memcache and tokyo. I’m expecting it to be really fast. References:.
http://rapd.wordpress.com/category/python/page/2/
CC-MAIN-2013-20
refinedweb
300
72.97
This family of languages really leads to a new way of thinking, evident in the J incunabulum (the C interpreter that started J, purportedly written in one afternoon) [1]. The code looks really dense and borderline gibberish at first glance, but I found it very expressive after a good read. [1]: A few bits I've noticed over 25+ years in the industry: Tell me what your product is. What it does, where it works, how it does it, what it requires. Is it a physical product (or is it shipped in one), an interactive application, a Web service, a programming language / tool? Tell me what the fuck it is EVERY GODDAMNED TIME YOU COMMUNICATE ABOUT THE PRODUCT. It doesn't have to be long or detailed, you can link to your detailed description in the communication. But your press releases, emails, Tweets, blog posts, marketing collateral, etc., are going to get passed around, word-of-mouthed, and/or pulled out of drawers (or browser history / searches) for weeks, months, and years to come. Make them work for you. The Economist's practice of briefly introducing any individual, no matter how famous or obscure, is a wonderful practice of microcontent contextualization. "Using the Economist house style offers an elegant alternative, wherein virtually all people and organizations are identified explicitly, no matter how prominent. For example, you might see 'Google, a search giant', 'GE, an American conglomerate', or 'Tim Cook, boss of Apple'." Tell me how to try it out. Preferably for 60-90 days (a 30 day cycle can go far too fast. I've been very, very impressed with New Relic's "use it for free, convert upmarket for additional features" model, and it's apparently worked well for them. For small accounts, their cost of sales is effectively nil (and for large accounts, COS is always a PITA). But for those large accounts, you've got a proven track record with the prospect, and they really know what they're getting. Put your tech docs front and center. As a technical lead / director, my questions are "how the fuck do I make this thing work", and if you can't tell me It's been observed many times that those who have the best appreciation for how a product works are those who use it directly, and secondly, those who either service it or support those using it. John Sealy Brown's The Social Life of Information addresses this with both Xerox copier repairmen and support staff. Use this to your advantage two ways: let these people share and collaborate, even if informally For the repairmen, this was a morning coffee break turned out to be a hugely valuable cross-training and troubleshooting feature. For phone support, after an "expert system" and changes in technology separating phone reps from technicians, researchers noted two reps who consistently provided good advice: one was a veteran from the earlier stage, the other a recent hire who sat across from the other and learned from her. Similarly, user support groups (mailing lists, Web forums, Usenet groups), in which users interact and share knowledge with one another directly (Hacker News would be an instance) are often (though not always) far more useful than direct tech support. Provide clear pricing information. This has been noted from Jacob Nielsen on forward as the information people are most interested in. Make damned sure that whatever process or workflow you've created online works, and for as many possible end-user environments as possible. Keeping interfaces as simple and legible as possible is a huge bonus. Remove distractions from your transactional webpages. Once someone's homed in on a product, focus on that, though you may mention alternatives or (truly useful) related products. Every additional piece of information on the screen is an opportunity to confuse and lose the sale. I've been restyling many websites simply for my own use (1000+), and simply removing distracting elements produces a far more productive environment. Ensure your pages are legible. Backgrounds should be light, foregrounds light (and where, with extreme reluctance, you invert these, separation should be clear). DO NOT SCALE FONTS IN PX. On far, far too many devices this renders as unreadable, particularly from older (e.g., more senior w/in the organization) readers. Grey-on-grey is just cause to fire whomever suggested or required it. See ContrastRebellion: Don't organize your website according to internal corporate structures. Your website is an outward facing tool, and should address the needs of users, not of internal departments. Lenovo's laptop site organization would be highly typical of this: I want a Linux-capable, large-display, full-keyboard, trackpoint device. The rest I generally don't give a shit about, and its product line confuses me every fucking goddamned time I try to buy something there (usually every 2-3 years). I'm not a sufficiently frequent customer that I keep up with every last change, but I've spent thousands of dollars on IBM/Lenovo products, as an individual (hundreds of thousands to millions as an enterprise customer). And of course: test all of this, don't simply take my word for it. But yes, I've walked from far, far, far too many product pages, from free software projects to Fortune 10 companies to edgy app devs. Life's too fucking short for that shit. What is your product? Why would I use your product? How does your product work? What does your product cost? ("Still working on it" is fine, but say so) What countries are you available in? Dropbox caters to a single market and the message is more simple for them. A "How it works" with subsection for both target market would help. multiple sided products always have trouble selling effective messages and would like to see examples if you guys know of any. I am doing a redesign of my site on this topic. Was targeted at companies earlier and now I will have trouble converting network'rs. I can see the problem, but solutions need more deep thought. Working on it. Submitted site to Peek. Want to see how it turns out. Then they write a blog post about it. Submit it to HN, get to the front page, get lots of potential customers... And there is still no information on their site about who they are and how it works... No, I think those came across quite clearly. He wants to know how it works, i.e. what is required of him, and what will the process of getting funded look like. That's a difference.. This random user is a prick. 1. Why didnt he scroll to the bottom of the page? I noticed an about us link in the footer. 2. When Im curious about companies, I look at their blogs. Sometimes they use a blog CMS system. Why didnt this guy check the links in the header, like the link to your blog? 3. This guy has a baby babbling in the background. Maybe he was distracted? Does anyone know of anything like that, but that's _not_ random, where I could actually send volunteers from my current users to my sight, and have their clicks and voice recorded and sent to me? Is there such a business that works well at a reasonable price? What is this site? What is thingumajig.io? Its a webby thingumajig? Sign up? Sign up for what? Oh it's a website for web something. nice font. I got the impression that the designers were trying to be clever by integrating the tutorial into an actual project page - and going to the Ramen project explains a lot about the process. However, that's intuition from using the web a lot, not a logical step. It's the same kind of intuition that gamers have when crawling a dungeon and you know that taking the short route will almost certainly be a Bad Idea. This backfires in another way: I also wonder if there are only four projects on the site? Can I search for more? It makes me think that the projects there are just dummy pages to demonstrate how the site works. What I like the most about it is that the user is genuinely interested in the service. But he acts natural and realizes he doesn't see an easy way to get more info on it. He could try to read the blog, or search for small print, but that's not what the average user is going to do. I'm going to try Peek soon! However, even that's a little confusing because it is itself a project -- so a user might wonder what the heck they are looking at, site info or some other project? UserTesting (the folks behind Peek) shot us over a promo code to get the first 100 of you to the front of the line if you want to give it a whirl: ramenreader ....well, I have an idea what kind of websites I will try to submit... Michael and John are reunited... I mean, recall in the Graphics Programming Black Book, when Michael starts off in the introduction with, "What was it like working with John Carmack on Quake? Like being strapped onto a rocket during takeoff in the middle of a hurricane." [1] Plus, Michael's quote from the announcement, "I now fully expect to spend the rest of my career pushing VR as far ahead as I can." Great things are ahead! If you've missed Michael's writings on VR, you are in for a real treat: Why Virtual Reality is Hard (And Where It Might Be Going): PDF:... PowerPoint:... Two Possible Paths into the Future of Wearable Computing: Part 1 VR... Two Possible Paths into the Future of Wearable Computing: Part 2 AR... When it comes to resolution, it's all relative... Latency the sine qua non of AR and VR... Raster-Scan Displays: More Than Meets The Eye... Game Developers Conference and space-time diagrams... Why virtual isn't real to your brain-... Why virtual isn't real to your brain: judder-... Down the VR rabbit hole: Fixing judder... [1] On the upside we have an unlimited budget to make VR real and on the downside the team can always start again with VC money if necessary. So if we buy into the notion that social presence in VR worlds will be big, somebody's going to have to build this. The technology exists, but it looks very awkward:... Not only does that have to be translated into a consumer product, but you need to capture someone's face while they're wearing the VR headset, which makes it even harder. Since VR headsets already touch your face, I would imagine the product would have to be some kind of extension of that - a larger contact area filled with sensors that reconstruct your expression perfectly. What I mean is the people generally angry about the acquisition was not due to the personnel but Facebook itself so this should change nothing. All this shows was the Oculus was already going to get Abrash and that Facebook decided this would be better to announce after they got acquired. If I was a game studio building a VR game with an Oculus kit, I'd be continuing to work on it, but I'd be calling Sony and trying to get in line for a Morpheus. I'm choosing optimism. been trying to hire Michael Abrash forever. [...] About once a quarter we go for dinner and I say 'are you ready to work here yet? So between Gabe and John, Michael could probably be dining for free every day of the week ;) Abrash has been the front facing member of Valve's efforts @ VR. His "What VR could, should, and almost certainly will be within two years" (1) paper was mind boggling as an Oculus Dev Kit owner. This is going to be like watching the "Dream Team" come together in one place, and I'm guessing that this ends all speculation about whether or not Carmack sticks around under FB considering the collaborative history between these two. (1)... I just wouldn't have predicted that their comeback to the limelight would be working for Facebook. In my eyes, they were "bigger" than that (obviously not monetarily). They "meant" more to me. This is all subjective stuff I realize, and yes I've heard a zillion times "how good it is for VR", but it kind of indirectly gives a message that the best thing a genius who is already capable of changing the world can do is work for Facebook instead of do their own thing. Call me a softy, but something just warms my heart when I see smart people stand out on their own, unswayed by the massive "power monoliths" surrounding them, and STILL kick ass. That's what Facebook did! And that was awesome! I just hope that spirit of entrepreneurship doesn't fade, and that geniuses know their power lies within themselves not in deep pockets of any company. Congrats to all involved though I can only imagine what kind of crazy office days are ahead. The sequel to "Masters of Doom" is yet to be written. In the same way I thought look to John Carmack for any signs of trouble [0], I can look at Abrash being signed as a sign that everything is fine. On a related note, I always get a kick out of this Amazon review of Abrash's book by Carmack [1]. 0: 1: It was John Carmack who sold me on the Oculus Dev Kit 1, now this. It seems as though Valve has been fairly hush-hush about their VR ongoings throughout what I'll call "Oculus' rising", so I'm curious for more detail as to what went on internally at Valve with VR, and if Abrash joining Oculus means more about their VR efforts and future (i.e. is Valve done even trying to build something? Is some other partnership brewing between the two?) The problem is that under FB, this will end up being the metafaceverse.com platform, that you can only access under their umbrella, just as with the current FB "platform". And you will be subject to their terms and conditions within their walled garden both as a user and a developer. That's not the kind of platform the internet needs. This won't be another WWW but another AOL. Doesn't change a my feelings toward Facebook one bit. They could wake up from their drunken bender tomorrow, say "We bought what?" and Oculus would be dead beyond any hope of resurrection by Monday. If it was anyone except Facebook, I would feel optimistic. It's like Microsoft buying Apple. You know the first thing they would is burn that business to ground and dance gleefully in the ashes while their lawyers geared up to sue everyone in the world. In one fell-swoop, all the naysayers about the FB acquisition were proven wrong. Love it!." <standard disclaimers about personal viewpoints and preferences> Just want to focus on the pursuit of perfection that I find so energizing - to put another way, if you had someone this passionate running each of the major airlines, I wonder what air travel would be like instead of the race-to-the-bottom experience it is now. This is the most ridiculous thing I've ever heard. 'After flying into a cloud of paint and superglue the windscreen wipers failed to work resulting in a dangerous collision'. (As if that happens every day and as if any other car would do better.) If the naysayers keep up their petulant trolling then this car will be good for a road trip in Afghanistan some time soon. Did this remind anyone else of when the smartest kid in the room was forced to apologize for something and you got the classic non apology apology? Keep building great cars Elon and changing the world. Understand that we understand that there will be (I almost said bumps in the road) and that no one expected you to be perfect in every way from the very beginning. Trust someone close to you to help write these things. "When you're doing something as new as we are with Tesla you're going to draw an outsized amount of scrutiny. Even though these fires were both in extreme circumstances, and that fires are sadly a regular occurrence for all vehicle makers, as a brand new concept it's not good enough for us to say 'We're as safe as any other comparable high end vehicle' We have to go a step further. And so today I'm announcing......" I mean I'm just throwing something together quickly but I'm trying to put some substance here vs sounding randomly snarky. Titanium has unbelievable tensile strength for its weight, but there's no good reason to make an "underbody shield" out of titanium except for publicity. It would make way more sense to use steel (and maybe you could make a case for something ultra light weight, like carbon fiber, but probably not). His intent is to PR+burnish the added safety feature. Instead of selling it as an objective demonstration of the leadership tact that Tesla takes in ensuring driver security, he gets passive-aggressive. Instead of laying out a tremendous history of safety as a foundation for a vision of the future of driving, he lords it as an accomplished achievement... which means the first time someone gets stuck inside the car and is burned alive, all these statements will bite him in the ass. It doesn't matter if that happened 100 times in gas cars the same year. Those manufacturers weren't overselling it. In aggressively projecting strength, it expresses weakness. Here is full statistical analysis of why it was a real problem.... Personally I think the ground clearance is still a bit on the low side. It looks like it lost a bolt or something in the first impact image... oops. # elongation and tensile strength. ## The ballistic standard for armour (RHA) is a 1/4 steel plate. Ballistic Alu is roughly 1/2 inch or double the thickness used here, in most applications. How can a software update impact ground clearance at highway speeds? Is this some special capability of the suspension in a Tesla or are more cars capable of this type of adjustment?How can a software update impact ground clearance at highway speeds? Is this some special capability of the suspension in a Tesla or are more cars capable of this type of adjustment? "However, to improve things further, we provided an over- the-air software update a few months ago to increase the default ground clearance of the Model S at highway speeds, substantially reducing the odds of a severe underbody impact." I don't doubt that the Tesla Model S is a very safe car as tests have shown. With that said, how many deaths and serious injuries would have been expected considering the same number of miles driven with normal cars? Are Teslas actually substantially safer than other cars or are there just few enough out there that no serious injuries have happened? "The odds of fire in a Model S, at roughly 1 in 8,000 vehicles, are five times lower than those of an average gasoline car..." What matters is the miles driven by cars, not the number of cars on the roads. It seems likely that other cars are driven longer distances, and Tesla cars are probably used by many owners as a second car. They need us to help spread the truth, as much as we need significant improvements in the automotive/transportation industry.-... Battery swap was always a gimmick -- you had to return to the same swap station later to get your same battery back or pay a huge fee. Come on. It looks like they decided fires are worse PR than this gimmick is good PR. I recall one Tesla caused death[1], and I'm sure there have been more. Not that I really think Tesla is any more dangerous than any other car in this regard though. [1]... In case you missed it, a link to be notified for the Kickstarter: Your writing is clear and easy to follow, and your intelligence definitely shines through. I never thought I'd say this, but you may actually have a shot at pulling this off. I mean the next Minecraft, Angry Birds, etc is going to come from somewhere/someone, why not you? Keep it up! And looking forward to the next update. I wonder if you could use this to import and export meshes from a physics sim? If you could turn the brick wall, for instance, into a Havok mesh, simulate knocking it down, and then convert the results back into voxel land you could do some really neat turn-based persistent-world destruction stuff. The most iconic example I can think of is .kkrieger, the 96kb first person shooter that has (relatively) amazing graphics: Video here: There might be valuable lessons to be had in that domain that might save you some time. How well-supported are dynamic features like animated characters or destruction? (Voxatron-style) I'd hold off on your claims on AWESOME EMERGENT AI before you actually have it up and running. The capabilities are simple to describe, but actually implementing them in a way that's performant and not horribly buggy has stumped well-funded teams of experienced developers. This has lots of useful applications. E.g Do you know those graphics about a submarine of the WW2, or a Spanish galleon in which you could see what is inside, like in the book "incredible cross sections"? With your tech you could make this but dynamic and alive!! peering what you are interested in. While most of the scene is static, you could move some things a little and make it alive. You should contact one of those amazing artist and show them what you have. There is no way they would resist an offer of working on something like this. I do think the grass looks like those old cartoons where the character is wearing a plaid outfit, and as they move, the plaid pattern stays still... Really great stuff! Something simple to say like emergent AI can be ridiculously complex in practice. I bet you really have all the experience you claim to have, but I still don't expect you to get very far. You have quite a few descriptions of how the game will end up, but saying things like "it will be fun and all these other things" dismisses how you're going to make it that way. I think the coolest promise was that the game would be deterministic. I'm not sure if you have lots of experience making games, but in my experience games written from the ground up never really become complete games. If you're not already, you may want to consider hiring a team or getting help developing this so that you can focus on the things you think you can do most effectively or that are most crucial to the final gameplay. Anyway, I really hope this is going to be all you say it will be. Good luck. :) If so, I think trying to call it, "open source," puts you in the position where you might be perceived as being disingenuous. I also think it's less clear that way. My point is, talk about what you've done more than what you intend to do. Everybody can talk about what they intend to do, almost nobody does it. What you've done so far is interesting enough, talk about that for now. Have you set fire to any of the materials in your generated world yet? It would be interesting to see a fire spread through one of your houses ... fire is usually one of the things either done well or done horribly in a game (in my opinion, anyways) ... In that light, this is an interesting long-term strategic move on Musk's part. It arms him with a "we've been selling in this state for X years with Y thousand satisfied customers, so how can this be so problematic that it needs restriction?" argument for his lobbying efforts a few years down the line. Imagine if Tesla hadn't opened stores in these locations - they would be indefinitely, unconditionally barred from doing so unless they had flouted the auto dealer rules and went forward with the stores regardless. Now they have a foothold. When you realize that the stakeholders (in this case, New York State Politicians) have a political interest in you flouting their rules then the rules just don't seem that rul-y anymore. It's also what's going to get their foot in Texas, as well. Elon Musk is one smart dude. Politicians who stand up for this kind of nonsense should be ashamed. When Tesla grows, they will need more than 5 dealerships in order to reach more of the population. When a new competitor tries to sell direct, these rules will make it impossible for them to compete on an even playing field with Tesla and therefore have to revert to the old dealership model. Win for Tesla, loss for free markets and competition. I don't... how do I put this nicely. This is a kid. He is smart. He looked at the problem from a new angle. He came up with a nice hack. Presumably we want more kids with more of a hacking spirit. I hope he doesn't read Hacker News. We see a savings of $400 million and think "we should do this!" But it's a drop in the bucket even if it were that much of a savings. If each government employee needs to change their font, or needs to set it as the default font, or needs technical support to configure the defaults in their word processor. If IT needs to modify images to use this font as a default. Just these actions are going to cost a significant portion of that $400 million when you consider it across the millions of federal staff. This also assumes things like the government is actually paying for ink or toner in quantity, instead of, for instance, holding a contract with Xerox who charges per impression rather than based on how much ink you use. It also assumes that there is no difference in legibility between the fonts. That people with vision impairments will not have difficulty with reading the document. An easy way to think about whether an initiative like this is reasonable is to think about whether it makes a lot of sense for any individual to do. Do you think you, individually, could realize any significant savings by changing your fonts? If it only makes sense when millions of people do it at once, and even then only when certain assumptions are met, and then only saves a few dollars per person per year, then it actually is more likely to cost a lot more in overhead to make sure it happens than it will ever save. Second, intentionally or otherwise, he managed to divorce the savings ratio from the type of ink being used--whether you laser-print, inkjet-print, or press-print your text on paper, you're going to use x% less ink or toner with one font versus another. However, the selection of a font should take things into consideration besides the relative amount of ink needed to produce a body of text. Human and machine readability should also be significant concerns. And I would like to point out that a cost savings of $136 million represents less than two seconds worth of spending at the US governments current spend rate of $3.5 trillion per year. I don't know about anyone else, but I can't even imagine that level of spending! Interesting and subtle change. However it will likely be net negative. Most high volume copiers/printers are laser and/or covered by a cost per copy maintenance agreement. Meaning that most organizations pay the same price for a page regardless of how much toner is used on that page. Contrast this with the cost of enforcing a single font family across millions of systems and documents. There are a large number of unseen costs here. Imagine 10 years from now some vendor responding to an RFP for healthcare.gov v2.0. The government insisting that the source code be converted to garamond for the weekly status reports. The HN posts that day will be about how ridiculous of a requirement this is. There is a whole class of typefaces optimized for high speed, low cost/low quality printing, which pre-compensates the letterform for expected ink bleeding, so called Ink Traps[1][2]. They are highly optimized for a specific printing method, the font size and the paper-quality used, and don't translate well to non-ink based printing. The problem with current desktop publishing fonts is that they can't possibly be optimized for every single use case on screen and for all of the myriad types of printing so robustness while maintaining legibility is key. Especially if the product is expected to be photocopied I would always go for a reasonable bolder weight, uncondensed typeface rather than losing information. Also make sure the 8 is distinct enough from a 6 [3] (Times New Roman beats Arial by lengths in this aspect) [1] [2]-... [3]... I use a Brother printer that cost me 40 2-4 years ago.I can buy 20 cartridges from Amazon that work perfectly for just 12.90 with shipping on Amazon Prime. That's 65p each.A single original Brother cartridge can easily cost 16.44 from Amazon or 7.62 each when bought in a pack of 4 (I think the largest quantity they sell together).So these copy cartridges are over 10x cheaper. I've used them ever since I got this printer with no ill effects. The printer still makes create printouts and prints photos great too. I've heard that perhaps they break your printer faster than original cartridges but if this is true when I'm happy to just spend the extra 40 ever few years to just buy a new printer. I'll still have saved far more than that on ink alone (I print quite a lot). If anything perhaps this is the solution to cheaper printing instead? Also, random note. Once I went a Korean friends house and they had a normal inkjet printer with 4 gallons of ink in large pots of top of it. These had small tubes feeding down into the cartridges. They never had to replace the cartridges and they would never run out of ink. Apparently this is quite common in Korea although I've never seen it before or since myself in the UK.From googling it was something like this: they had much larger ink containers. It seems it's called a "continuous ink system". It's pretty cool to look into anyway, even if you don't do a huge amount of printing. Think about it: for the sake of optimizing ink use, the trivial solution is 1) Use the smallest font sizes possible 2) Use the 'thinnest' font that arguably uses the least ink. However optimizing a single varible in this way is clearly not desirable, because it defeats the goal of printing documents. A document is meant for someone to read, no? :) Most offices that I've seen use laser printers. Toner isn't cheap but it's cheaper by several orders of magnitude over the ink in an inkjet printer they're using for the comparison here. the GPO's efforts to become more environmentally sustainable were focused on shifting content to the Web. This is the right answer. It's a permanent solution to a long-term problem. Teen to government: Change your typeface, save millions What he's really saying is: "Spend millions changing your typeface, maybe save millions." There are laws that dictate how forms and paper must appear. Changing the font could have many unintended consequences that will need to be studied and tested for, probably by high-priced consultants. And of course you'll have to test if the new forms are as readable by low-vision citizens and people with other disabilities. But have to hand it to a 14 year old at least thinking about this stuff. Still a worthwhile thing to report, I guess, but somehow manages to still be very "the media is clueless" BTW: More ink is saved by image detection & changes than fonts. And, this is all half-baked. My $0.02 on why this wouldn't fly- he's examining the problem from a bird's eye view, ie, the entire government expenditure. Documents, however, are printed by teams, usually small one's for whom even a 30% ink savings wouldn't make a dent compared to the money they spend elsewhere. Thus no motivation for each team, and thus no major movement to change behavior. If the teams are anything like ones that I've been a part of, a lead will look at a document printed in Garamond, proclaim he doesn't like it/can't read it, and ask for it to be reprinted in readable format. I never really made any measurements, but I remember its documentation mentioned a savings of up to 40% of ink. The normal mode of the printer is NLQ [1], so it would be quite big when compare to NLQ. [1] Not to say it's not a good idea, there's just potentially a lot of side effects. Congrats to the kid, he got his 15 minutes of fame. I hope it will motivate him to continue improving this world. The benefit for the rest of us is that hopefully with all of this attention, someone more qualified will come along and actually start some significant changes. And is it really necessary these days that Acrobat comes up with a different print dialog from Firefox, which is different from another one? I think for this solution to work they should actually consider even more extreme type faces, font sizes, and shades of gray. How are we to know that just making the letters "weight" lower wouldn't have the same effect?Clearly we should commission a team of 12 experts to study which fonts cost the most to print, their legibility by a group of 100 Americans who represent the diverse age and backgrounds of American Citizens, and how fast they can read them, factoring their average wage to also value the man power cost of the new fonts. To this end I'm submitting to my senator a proposal that outlines a $1 billion earmark for research in to the cost savings available through a mandate to use an alternate, but yet undetermined font. Additionally to avoid copyright issues on fonts, $4 billion will be set aside to find a team to create a new public domain font that will be accessible to anyone. In as soon as 5 years we should have a new font selected, and as early as 2030 all new documents will be printed in the new font. Lastly all existing public works will be reprinted in the new font. We expect completion of this project by 2050. By 2050 the war with Russia, and China should be over, and the United States of the Northern Hemisphere will be operating in only one language Chinglussian. All documents will be printed in this. Adding the additional characters that Chinglussian requires should only cost another 8 Bitcoin. (the rate of inflation on BTC is expected to be practically infinite as all the worlds wealth packs in to 40M coins). We have already reserved those 8 Bitcoins, so as long as they aren't lent to another group in the next 35 years the proposed budget will account for that. Briefly: Acetylcholinesterase terminates acetylcholine neurotransmission events by deactivating the acetylcholine, allowing it to be reused. An acetylcholinesterase inhibitor such as the Donepezil used in the article inhibits the action of acetylcholinesterase, which in turn enhances acetylcholine neurotransmission in a dose-dependent manner. Highly potent acetylcholinesterase inhibitors are used as poisons (Sarin gas, for example) because they interfere with all of the acetylcholine-based neurotransmission that happens throughout your brain and body. Less potent inhibitors are used at lower doses in Alzheimer's disease as it is hoped that they will improve cognitive function and perhaps even slow disease progression. Thus far the results have been mixed. Now the bad news: Cholinergic neurotransmission is widespread through your brain and your body. Acetylcholinesterase inhibitors are a very blunt and non-specific way to manipulate that neurotransmission. Unfortunately, you can't just enhance memory formation and learning related neurotransmission, you amplifiy cholinergic transmission indiscriminately everywhere. As a result, it's possible to get some quite negative effects as well. There are reports of acetylcholinesterase inhibitors causing or at least inducing PTSD-like symptoms ( ). Furthermore, we just don't know the long-term effects of these medications on young, healthy adults as they've primarily been studied in elderly populations. In short: It's potentially very unwise to use Donepezil or similar medications for the purposes of enhancing your learning or your memory. Leave the experimentation to the carefully controlled studies until more is known on these powerful substances. They just casually put that there, but I don't think most readers will be exactly familiar with what that means? It's basically raising the baselevel of what is one of the most common neurotransmitters. It's a carpet-bomb, not the targeted strike the article makes it out to be. In unusual cases temporarily tweaking learning rate can be profitable, and it could apply to brain too. What you eat has the largest effect on your brain chemistry. On the positive side, things that were cutting-edge hard problems in the 80s are now homework assignments or fun side projects. For instance, write a ray tracer, a spreadsheet, Tetris, or an interactive GUI. On the negative side, there seems to be a huge amount of stagnation in programming languages and environments. People are still typing the same Unix commands into 25x80 terminal windows. People are still using vi to edit programs as sequential lines of text in files using languages from the 80s (C++) or 90s (Java). If you look at programming the Eniac with patch cords, we're obviously a huge leap beyond that. But if you look at programming in Fortran, what we do now isn't much more advanced. You'd think that given the insane increases in hardware performance from Moore's law, that programming should be a lot more advanced. Thinking of Paul Graham's essay "What you can't say", if someone came from the future I expect they would find our current programming practices ridiculous. That essay focuses on things people don't say because of conformity and moral forces. But I think just as big an issue is things people don't say because they literally can't say them - the vocabulary and ideas don't exist. That's my problem - I can see something is very wrong with programming, but I don't know how to explain it. There is always a need for two types of languages, higher level domain languages and general purpose languages. Building general purpose languages is a process of trying to build abstractions that always have a well-defined translation into something the machine understands. It's all about the cold hard facts of logic, hardware and constraints. Domain languages on the other hand do exactly what he describes, "a way of encoding thought such that the computer can help us", such as Excel or Matlab, etc. If you're free from the constraint of having to compile arbitrary programs to physical machines and can instead focus on translating a small set of programs to an abstract machine then the way you approach the language design is entirely different and the problems you encounter are much different and often more shallow. What I strongly disagree with is claiming that the complexities that plague general purpose languages are somehow mitigated by building more domain specific languages. Let's not forget that "programming" runs the whole gamut from embedded systems programming in assembly all the way to very high level theorem proving in Coq and understanding anything about the nature of that entire spectrum is difficult indeed. If you are using card[0][12] to refer to Card::AceSpades, well, time to learn enums or named constants. If, on the other hand, the array can be sorted, shuffled, and so on, what value is it to show an image of a specific state in my code? There's a reason we don't use symbolic representation of equations, and it has nothing to do with ASCII. It's because this is implemented on a processor that simulates a continuous value with a discrete value, which introduces all kinds of trade offs. We have a live thread on that now: why is aaaaaa not (aaa)(aaa). I need to be able to represent exactly how the computation is done. If I don't care, there is Mathematica, and and the like, to be sure. If you disagree with me, please post your response in the form of an image. And then we will have a discussion with how powerful textual representation actually is. I'll use words, you use pictures. Be specific. Coming from a mathematician with more than enough programming experience under his belt, programming is far more rigorous than mathematics. The reason nobody writes math in code is not because of ASCII, and it's not even because of the low-level hardware as someone else mentioned. It's because math is so jam-packed with overloaded operators and ad hoc notation that it would be an impossible feat to standardize any nontrivial subset of it. This is largely because mathematical notation is designed for compactness, so that mathematicians don't have to write down so much crap when trying to express their ideas. Your vision is about accessibility and transparency and focusing on problem solving. Making people pack and unpack mathematical notation to understand what their program is doing goes against all three of those! So where is this coming from? PS. I suppose you could do something like, have layovers/mouseovers on the typeset math that give a description of the variables, or something like that, but still sum(L) / len(L) is so much simpler and more descriptive than \sigma x_i / n The Aurora demo did not look like a big improvement until maybe where the TodoMVC demo beats even Polymer in LOC count and readability. I've been thinking of similar new "programming" as the main computer UI, to ensure it's easy to use and the main UI people know. Forget Steve Jobs and XEROX, they threw out the baby with the bath water. Using a computer is really calling some functions, typing some text input in between, calling some more. Doing a few common tasks today is And the same yet annoyingly different UI deal on another forum, on youtube, facebook, etc. Just imagine what the least skilled computer users could do if you gave them a computing interface that didn't reflect the world of fiefdoms that creates it.And the same yet annoyingly different UI deal on another forum, on youtube, facebook, etc. Just imagine what the least skilled computer users could do if you gave them a computing interface that didn't reflect the world of fiefdoms that creates it. opening a web browser clicking Email reading some replying getting a reply back, possibly a notification clicking HN commenting on an article in a totally different UI than email going to threads tab manually to see any response FaceTwitterEtsyRedditHN fiefdoms proliferate because of the separation between the XEROX GUI and calling a bunch of functions in Command Line. Siri and similar AI agents are the next step in simple UIs. What people really want to do is And when you send Dustin and his circle of acquaintances a more private message, youAnd when you send Dustin and his circle of acquaintances a more private message, you tell Dustin you don't agree with his assessment of Facebook's UI changes type/voice your disagreement share with public To figure out if more people agreed with you or DustinTo figure out if more people agreed with you or Dustin type it share message with Dustin and his circle of designers/hackers That should be the UI more or less. Implement it however, natural language, Siri AI, a neat collection of functions.That should be the UI more or less. Implement it however, natural language, Siri AI, a neat collection of functions. sentiment analysis of comments about Dustin's article compared to mine Today's UI would involve going to a cute blog service because it has a proper visual template. This requires being one of the cool kids and knowing of this service. Then going to Goolge+ or email for the more private message. Then opening up an IDE or some text sentiment API and going through their whole other world of incantations. Our glue/CRUD programming is a mess because using computers in general is a mess. To understand why programming remains hard it just takes a few minutes of working on a lower-level system, something that does a little I/O or has a couple of concurrent events, maybe an interrupt or two. I cannot envision a live system that would allow me to debug those systems very well, which is not to say current tools couldn't be improved upon. One thing I've noticed working with embedded ARM systems is that we now have instruction and sometimes data trace debuggers that let us rewind the execution of a buggy program to some extent. The debugger workstations are an order of magnitude more powerful than the observed system so we can do amazing things with our trace probes. However, high-level software would need debugging systems an order of magnitude more powerful than the client they debug as well. Sometime the post not say: We want to make a program about everything. To make that possible, is necesary a way to express everything that could be need to be communicate. Words/Alphabet provide the best way. In a normal language, when a culture discover something (let say, internet) and before don't exist words to describe internet-things then it "pop" from nowhere to existence. Write language have this ability in better ways than glyphs. In programming, if we need a way to express how loop things, then will "pop" from nowhere that "FOR x IN Y" is how that will be. Words are more flexible. Are cheap to write. Faster to communicate and cross boundaries. But of course that have a Editor helper so a HEX value could be show as a color is neat - But then if a HEX value is NOT a color?, then you need a very strong type system, and I not see how build one better than with words. Thank you for all the work on Light Table, and I'm looking forward to seeing what the team does with Aurora. But the problem of being unobservable is harder. Literate programming might help in making chunks more accessible for understanding/replacing/toggling, but live flow forwards-backwards, it would not. But I have recently coded up an event library that logs the flow of the program nicely. Used appropriately, it probably could be used to step in and out as well. I am not convinced that radical new tools are needed. We just have to be true to our nature as storytellers. I find it puzzling why he talks about events as being problems. They seem like ideal ways of handling disjointed states. Isn't that how we organize our own ways? I also find it puzzling to promote Excel's model. I find it horrendous. People have done very complex things with it which are fragile and incomprehensible. With code, you can read it and figure it out; literate programming helps this tremendously. But with something like Excel or XCode's interface builder, the structure is obscured and is very fragile. Spreadsheets are great for data entry, but not for programming-type tasks. I think creation is rather easy; it is maintenance that is hard. And for that, you need to understand the code. def stddev(x): avg = sum(x)/len(x) return sqrt(sum((xi-avg)**2 for xi in x) / len(x)) stddev xs = let avg = sum xs / length xs in sqrt $ sum [(x-avg)**2 | x <- xs] / length xs That said, I think that fundamentally the problem isn't with programming, it's with US. :) Human beings are imprecise, easily confused by complexity, unable to keep more than a couple of things in mind at a time, can't think well in dimensions beyond 3 (if that), unable to work easily with abstractions, etc. Yet we're giving instructions to computers which are (in their own way) many orders of magnitude better at those tasks. Short of AI that's able to contextually understand what we're telling them to do, my intuition is that the situation is only going to improve incrementally. I thought the `person.walk()` example, however, was misplaced. The whole point of encapsulation is to avoid thinking about internal details, so if you are criticizing encapsulation for hiding internal details you are saying that encapsulation never has any legitimate use. I was left wondering if that was Chris's position, but convinced it couldn't be. The sentiments expressed in the conclusion of Harel's article Statecharts in the Making: A Personal Account[3] really jumped out at me last year. When I read your blog post, I got the impression you are reaching related conclusions: "If asked about the lessons to be learned from the statecharts story, I would definitely put tool support for executability and experience in real-world use at the top of the list. Too much computer science research on languages, methodologies, and semantics never finds its way into the real world, even in the long term, because these two issues do not get sufficient priority. One of the most interesting aspects of this story is the fact that the work was not done in an academic tower, inventing something and trying to push it down the throats of real-world engineers. It was done by going into the lion's den, working with the people in industry. This is something I would not hesitate to recommend to young researchers; in order to affect the real world, one must go there and roll up one's sleeves. One secret is to try to get a handle on the thought processes of the engineers doing the real work and who will ultimately use these ideas and tools. In my case, they were the avionics engineers, and when I do biological modeling, they are biologists. If what you come up with does not jibe with how they think, they will not use it. It's that simple." [1] [2]... [3]... I felt that the article takes a somewhat depressing view. Sure, these days we probably do all spend a lot of time getting two pieces of code written by others to work together. The article suggests there's no fun or creativity in that, but I find it plenty interesting. I see it as standing on the shoulders of giants, rather than just glumly fitting pipes together. It's the payoff of reusable code and modular systems. I happily use pre-made web servers, operating systems, network stack, code libraries etc. Even though it can be frustrating at times when things don't work, in the end my creations wouldn't even be possible without these things. In many cases, it's the edge cases and feature creep that makes software genuinely terrible and by the time you layer in all that knowledge, it is a mess. I don't care if you use VIM, EMACS, Visual Studio, or even some fancy graphical programming system. Complexity is complexity and managing and implementing that complexity is a complex thing. Until we have tools to better manage complexity, we will have messes and the best tool to manage complexity are communication related, not software related. There will always be things we wish to say in our programs that in all known languages can only be said poorly. Re graphics: A picture is worth 10K words - but only those to describe the picture. Hardly any sets of 10K words can be adequately described with pictures. Make no mistake about it: Computers process numbers - not symbols. We measure our understanding (and control) by the extent to which we can arithmetize an activity. We could do similar things to visualize actor systems, handle database manipulation and the like. The problem is that all we are really doing is asking for visualization aids that are only good at small things, and we have to build them, one at a time. Without general purpose visualizations, we need toolsets to build visualizations, which needs more tools. It's tools all the way down. You can build tools for a narrow niche, just like the lispers just build their DSLs for each individual problem. But even in a world without a sea of silly parenthesis and a syntax that is built for compilers, not humans, under every single line of easy, readable, domain-centric code lies library code that is 100% incidental complexity, and we can't get rid of it. Languages are hard. Writing code that attempts to be its own language is harder still. But those facts are not really the problem: They are a symptom. The real problem is that we are not equipped to deal with the detail we need to do our jobs. Let's take, for instance, our carefree friends that want to build contracts on top of Bitcoin, by making them executable. I am sure a whole lot of people here realize their folly: The problem is that no problem that is really worth putting into a contract is well defined enough to turn it into code. We work with a level of ambiguity that our computers can't deal with. So what we are doing, build libraries on top of libraries, each a bit better, is about as good a job as we can do. I do see how, for very specific domains, we can find highly reusable, visual high level abstractions. But the effort required to build that, with the best tools out there, just doesn't make any practical sense for a very narrow domain: We can build it, but there is no ROI. I think the best we can do today is to, instead of concentrate so much on how shiny each new tool really is, to go back to the real basics of what makes a program work. The same things that made old C programs readable works just as well in Scala, but without half the boilerplate. We just have to forget about how exciting the new toys can be, or how smart they can make us feel, and evaluate them just on the basis of how can they really help us solve problems faster. Applying proper technique, like having code that has a narrative and consistent abstraction levels, will help us build tools faster, and therefore make it cheaper to, eventually, allow for more useful general purpose visualization plugins. Imagine an environment like a lisp machine, where all the code you run is open and available for you to inspect and edit.Imagine a vast indexed, cross-referenced, and mass-moderated collection of algorithm implementations and code snippets for every kind of project that's ever been worked on, at your fingertips. Discussing how we might want slightly better ways to write and view the code we have written is ignoring the elephant problem- that everything you write has probably been written cleaner and more efficiently several times before. If you don't think that's fucked up, think about this:The only reason to lock down your code is an economic one, despite that all the code being made freely usable would massively increase the total economic value of the software ecosystem. I'm more interested in programs that understand programs and their run-time characteristics. It'd be nice to query a system that could predict regressions in key performance characteristics based on a proposed change (something like a constraint propagation solver on a data-flow graph of continuous domains); even in the face of ambiguous type information. Something like a nest of intelligent agents that can handle the complexity of implementation issues in concert with a human operator. We have a lot of these tools now but they're still so primitive. The truth is that programming is one of the most complex human undertakings by nature, and many of the difficulties faced by programmers - such as the invisible and unvisualizable nature of software - are intractable. There are still no silver bullets.... While in some cases that would be great, I'm not entirely sure more abstraction is what I want. Having a decent understanding of the different layers involved, from logic gates right up to high-level languages, has helped me tremendously as a programmer. For example, when writing in C, because I know some of the optimisations GCC makes, I know where to sacrifice efficiency for readability because the compiler will optimise it out anyway. I would worry that adding more abstraction will create more excuses not to delve into the inner workings, which wouldn't be to a programmer's benefit. Interested to hear thoughts on this! Things have not stayed stale for the past 20~30 years, in fact, state of programming have not stayed stale even in the recent 10 years. We've been progressively solving problems we face, inventing tools, languages, frameworks to make our lives easier. Which further allows us to solve more complicated problems, or similar problems faster. Problems we face now, like concurrency, big data, lack of cheap programmers to solve business problems were not even problems before, they are now, because they are possible now. Once we solve those problems of today, we will face new problems, I don't know what they would be, but I am certain many of them would be problems we consider impractical or even impossible today. However, thinking about computation as only simple programs minimizes the opportunities in the opposite domain: using computation to supplement the inherently fragile and limited modeling that human brains can perform. While presenting simplicity and understanding can help very much in realizing a simple mental model as a program, it won't help if the program being written is fundamentally beyond the capability of a human brain to model. The overall approach is very valuable. Tooling can greatly assist both goals, but the tooling one chooses in each domain will vary greatly. I really can't wait for programming to be more than just if statements and thinking about code as a grouping of ascii files and glueing libraries together. Things like Akka are nice steps in that direction. The article then compares some verbose C++ with a mathematical equation. That is hardly a fair comparison, the C++ code can be written and read by a human in a text editor, right click the equation > inspect element ... it's a gif. I loaded the gif into a text editor, it's hardcore gibberish. Personally, I would stick with the verbose C++. As each new version of LT comes out I feel that it's suffering more and more from a clear lack of direction. And that makes me sad. Doesn't help with the mathematical notation, though (Although it would be possible to do something about that, I suppose). especially after I saw rich hickey's presentation "simple made easy" (my notes on it [1]). I'm actually on a mission now to find ways to do things that are more straight forward. One of my finds is [2] 'microservices', which I think will resonate with how I perceive software these days. [1]...[2] I think it boils down to a cultural failure, like the article mentions at the end. For example, I am a programmer myself. Which means that I generate and work with lots of static, cryptic colorful ASCII text program sources. If I stop doing that, I'm not a programmer anymore. By definition. I really think that is the definition of programming, and that is the big issue. I wonder if the current version of Aurora derives any inspiration from "intentional programming"? Also wonder when we can see a demo of the new version. So I find myself getting "cold" and then coming back into it. The thing about taking a week to set up a dev environment is spot on. It's completely insane that it should take a week of work just to sit down and write a for-next loop or change a button's text somewhere. The problem with programming is simple: it's full of programmers. So every damn little thing they do, they generalize and then make into a library. Software providers keep making languages do more -- and become correspondingly more complex. When I switched to Ocaml and F# a few years ago, I was astounded at how little I use most of the crap clogging up my programming system. I also found that while writing an app, I'd create a couple dozen functions. I'd use a couple dozen more from the stock libraries. And that was it. 30-40 symbols in my head and I was solving real-world problems making people happy. Compare that to the mess you can get into just getting started in an environment like C++. Crazy stuff. There's also a serious structural problem with OOP itself. Instead of hiding complexity and providing black-box components to clients, we're creating semi-opaque non-intuitive messes of "wires". A lot of what I'm seeing people upset about in the industry, from TDD to stuff like this post, has its roots in OOP. Having said all that and agreeing with the author, I'm a bit lost as to just what the heck he is ranting on about. I look forward to seeing more real tangible stuff -- I understand he's working on it. Best of luck. Would love to hear more about what makes them ideal freelance clients. As a former contractor/freelancer, I specifically made a point of staying far, far away from these kinds of clients. I've been freelancing in mentoring start-ups for the last 6 months. Everyone told me startups have no money and that it's a fruitless pursuit but here i am talking to 1 new startup almost every single day. I always give them the first session free (no time limit) and more than two-thirds come back for a paid session. I've mentored around 60 startups in the last 3 months alone (all around the globe). Most fun i've ever heard. Incredibly rewarding. In fact, i'm now working on building an actual mentoring platform. I spend the rest of my time consulting small to medium size companies. It's great that he's made this lifestyle work for him, but I'm not convinced I'd like to be one of his clients. A technology company with a developer on staff one day per week? Coordinating a project is difficult enough when everybody is full-time. ("Sure thing, I'll tackle that bug in six days" is not a recipe for a functional sprint.) My solution has been to charge hard at whatever milestone I've committed to, working as a de facto team member, and then taking the next month off. This works well with my lifestyle, since I try to take each project in a new city and I live cheaply. What I would say to the author: you want fulfilling? Participate in the optimistic urgency of a new tech venture fully - then take your time off when you've finished. If you can't afford to spend that much time away from developing your startup, then how can you expect your clients to wait while you take time off from theirs? One thing I'm unsure about is if it's wise to do consulting in the same space my startup is in (fitness & health data aggregation and analysis), or if I should stick to unrelated technical work (java, elasticsearch, angularjs), to avoid potential trouble with non-compete agreements and such. The actual paper is at... What Naur means by "theory" is some combination of what we'd now call "model" and "design". Naur, of course, put the N in BNF and played a leading role in creating Algol. - Carmack - Abrash - Alexandrescu - Kent Beck Cannot say I'm not a little jelly of those who get to spend time with these fine gents. [0]: I would ask if there are any improvements between using wrap or just using clang. I have to say: well executed. This is a really good representation of how well Bootstrap can be implemented. From Retina display to mobile, the layout was clearly well thought-out and considered. Interesting product and well-done design. Stuck this in the file for not only routing issues, but design and implementation inspiration. [1] - They employ 600+ staff serving over a thousand persons with disabilities and are currently starting their own transit arm to support the agency. They operate something like 2 dozen buses and large vans across 50+ recurring destinations. [1]... These sorts of things fascinate me in that the average non-designer has little knowledge over the intricacies involved in producing a beautiful typeface that scales to many dimensions accurately and produces a printout that works around the physical limitations of ink. My attempt to create a typeface resulted in a font that looked very good at 10pt and started to fall apart a few points larger or smaller. I gave up and decided to leave that to the professionals. Of course, back then, there weren't large collections of high quality and free fonts sponsored by large players like Google and Microsoft, so the novelty of having a monospaced programming/terminal font with just the right size dot in the zero, slash in the 7 and serifed 1 was worth the few days of nerding around to make a janked up version I could enjoy at precisely the size I wanted to see it. EDIT: OK, check these out: Here is a very interesting example of this. A physical process distorts the "clean" image in the final product, so the distortion is mapped and doubly reversed, so that a "clean" final product is generated from an intentionally distorted original. As long as the physical distortion is consistent and predictable, you could do this with anything. I'm thinking the same technique could be applied to improve volume printers. Instead of ink traps you have thermoplastic traps. The article mentions that Unicorn's out-of-band garbage collection is problematic because the way it works - running the GC after every request, and requiring turning off the normal GC - is overkill. But there the community is working on a better solution. In particular, Aman Gupta described this very same problem and created a gem which improves out-of-band garbage collector, by only running it when it is actually necessary, and by not requiring one to turn off the normal GC. Phusion Passenger (even the open source version) already integrates with this improved out-of-band garbage collector through a configuration option. This all is described here:... Just one caveat: it's still a work in progress. There's currently 1 known bug open that needs reviewing. Besides the GC stuff, Phusion Passenger also has a very nice feature called passenger_max_requests. It allows you to automatically restart a process after it has processed the given number of requests, thereby lowering its peak memory usage. As far as I know, Unicorn and Puma don't support this (at least not out of the box; whether there are third party tools for this, I don't know). And yes, this feature is in open source. I totally agree with codinghorror that a blog without comments in not a blog, this is a prime example. No way to respond to the author without jumping through crazy hoops. As to the issue. 1. NEVER use unicorn oobgc that ships with unicorn or the old one that ships with passenger. Use gctools on 2.1.1 or this on 2.0.... If you are disabling GC you are doing it wrong and creating rogue processes. 2. Expect memory doubling with Ruby 2.1.1. Not happy with that? You have 2 options. Tune it down by reducing RUBY_GC_HEAP_OLDOBJECT_LIMIT_FACTOR. At 1 your memory consumption will be on par with 2.0. It ships with the 2 default. Option 2, wait for a future release of Ruby, this will be fixed in 2.2 maybe even patched a bit more in 2.1.2 . See: and and-... As for the, full-of-bait, title. Ruby's GC is ready for production and being used in production in plenty of places. Just don't go expecting rainbows if you disable it. And expect memory doubling with 2.1.1 if left untuned. You can choose how much you want the memory to increase from 2.0 No, you should be using Puma.[0] Unicorn is a work of art and it is incredibly simple, but with that comes a lot of waste. Puma won't fix this problem as it lies in MRI, but you will be able to run way less processes so total memory consumption won't be such an issue. Ruby 2.1 comes with an asterisk. It's a lot faster but you should take some time to tune the GC to your application's needs. Aman Gupta[1] has some excellent posts on his blog about how to do this. On Rails apps that I have upgraded from 2.0 to 2.1 we have seen around 25% (and up to as high as 50% in some places) decrease in response times. The GC oddities will all certainly get better in Ruby 2.2 (and maybe even in minor releases of 2.1 but I doubt it). 0 - 1 - See for more information. No. Any reason why more environments don't adopt this approach? It seems entirely efficient, reasonable and well-designed... ... especially since Ruby 2.0 as the GC is much, much faster. I'll be honest, I don't think the memory bloat is that problematic if you design the app well (business logic definitely prevents this some time)... but in general you can pass most of that off to a background worker, or pre-cache responses so you aren't bloating your app server instances/threads. I thought it was me. Also, Dustin Curtis seems to forget (or not understand) that Facebook is the same company that made a decision to implement AJAX at the expense of pageviews, at a time when that decision was highly controversial (the era of the Empire of MySpace). You can ding the management at Facebook for a lot of things, but this really isn't one of them. The bigger story, really, is that poor people use Facebook on a computer, and thus that is where web-based experience optimization is focused. If you don't have a smartphone, or your smartphone sucks, you're going to be on the web; otherwise, why aren't you using your iPhone or iPad? (And remember, that's where Facebook derives a majority of their revenue -- so if there's going to be a conspiracy, it's going to be a conspiracy to get you to stop using the website, and to buy a high-ad-revenue-generating iPhone). Welcome to the wacky user landscape of 2014, where the Web is for nerds and poor people. I like that Julie used Medium for her thoughts, rather than a Facebook post. Experimentation with others' products and services is super cool. > The old design was worse for many of the things we value and try to improve. Like how much people share and converse with their friends. [old design:] The "only icons" on the left + "icons AND text labels" for "Share/Like/Comment" + much higher text density on the right constantly shift your thinking form "photo/visual" to "reading/writing", it mind-fucks you in a very subtle way, so your brain ends up focusing on the only thing that makes sense: (a) the overall visual structure (that was beautifully designed, I admit) and (b) the photos. If you want user engagement beyond the "click like" level you need to focus people towards the "reading/writing/verbal" mode of interaction. Like, if you have to read a button's label to know what it does, this puts your mind into "reading mode" so the comment that immediately follows the link/button has more chances of actually being read and of the people actually writing a reply instead of just clicking a like and staring at a cute picture. They really got this right (either through someone's insight or metrics, I dunno) with the "Like Comment Share" links - getting rid of the icons pushed you more towards "text/words mode" thinking, which is exactly the mode you need to be in to actually post a comment, and a comment is more content so it will be a positive feedback loop for even more and so on. (Also, another obvious bad idea was the left bar - while theoretically good for screen estate, it's essentially "mystery meat navigation" to unsophisticated desktop users. Also it puts less focus on the Apps. Also by putting the active contacts list in the bottom left corner pushes them out of your mental focus.) EDIT+: ...now that it really got me thinking of it, I can't believe how incredibly bad the "old new" design was. How did they even chose to deliver that? It looked like textbook "design driven design", it didn't focus at all on how the users think and what they actually do on Facebook. One thing I want to understand is if the concern is about accommodating people on less-than-the-latest tech or smaller screens, etc. then we've solved largely for that via responsive design. It's not hard to detect that I have enough real estate to support having a 2x larger photo in my feed. Why not adjust as needed? How am I supposed to make myself feel superior now? Show what the feed looks like with a news stories posted by a few people (fortunately FB is now smart enough to coalesce them), a bunch of moronic memes, one line stupid text, and a few long posts with ~100 comments with lots of debate, and that's more representative of my facebook newsfeed. Why can't Facebook adapt the news feed to be the best for each individual, both content wise and design? I have a 27" screen, why degrade my experience, as a minority when you are completely capable of enhancing it. Enhance the 11, 13 and 17 inch screens too, and let us all have the best experience possible. The idea that the majority should be the only number worth optimizing is one that should be completely dismissed. So, you can try to roll out a layout that makes the "News Feed all about the content" (wtf?), but you can't design the love back in. This speaks to the value FB sees in low-quality, high-reach experiences. Well, this and the WhatsApp acquisition. It's a very mature and reasonable response to Dustin's armchair speculation. People are dropping facebook. It's just becoming a worse user experience each time they change anything.... I have never thought of FB as a bastion of design...and I have not yet been swayed to think or see otherwise. I am using a mac book pro. My request header is yelling at you that I am. Your argument makes no sense, if you agree that you know I am not suffering from the lack of a scroll pad. What about that! And, maybe it's just me, but I hate links from medium because on HN they strictly say (medium.com) with no information as to who they are. Much, much prefer personal blog links where there is some context. After I had this experience two or three times I figured I'd stay away from SONY products. Is it wrong for me to also admit that ever since the "Root Kit Debacle" from Sony, I cringe a little at the idea of plugging a Sony product into my PC? Or am I just being paranoid? I imagine it's terribly expensive. "Pricing available upon request". EDIT: That's right. $1000.... I am not interested in the note taking, although it may prove useful at some point, I want it as a large e-ink reader for technical books. The iRex Iliad had a big screen and you could write on it with a stylus. It ran linux and didn't use proprietary file formats, so was great for actually doing stuff. BUT The refresh rate on the screen meant that doing anything with the stylus was painful. It lagged way too much. I see nothing in the specs for the sony device that refers to this problem with e-ink, and no video demo. Anyone have better info? But still: $1100? When an iPad (which can do so much more) is ~$500 ? Once again, Sony seems to be miscalculating. Except, there is so few informations on the software.It seems the supported sync service is worldox [1], as it's the only link in the sidebar and there is no explicit mention of any other solution. Does this means one has to contract this service provider just to wirelessly sync this device ? Of course, no mention of an SDK or any third party integration. As usual with Sony, the hardware seems perfect and the software an afterthought. [1]... For me then, it would go from "yeah, its kinda neat" to "I really ought to consider giving them my money for this" The problem with the iPad, however, is that it's not good for marking up documents. It's great for reading legal cases, but not for marking them up and taking margin notes. Personally, I'm one of those people that gets a lot more out of having paper in my hand and scribbling on it than I do just reading something off a computer screen. I'm really intrigued by this product:..., which lets you print out PDF's onto special paper so that when you write on it with a digital pen, the markings are reintegrated onto the digital copy. Unfortunately, it's really expensive! Also, 10" is on the small side for what's ideal. A standard piece of paper is 13" diagonal. I've been looking at the 12.2" Samsung, which also has a digitizer, but Samsung's Android skin is just god-awful. It's a shame nobody makes a 12"+ Baytrail Windows 8 tablet with good battery life... This product seems to really tackle this niche. Apparently Sony is going to be showing it off this week at the ABA tech show in Chicago. Does anyone know how qr-lpd compares to e-ink?... Speed in general? How is it to write notes on? Linux/wireless support? $1000 +, closed to common eReader document types and no path to openness for developers. Add in Sony's miserable record for supporting their customers after they move to the next flavor of the week and this is a great illustration of their march towards increasing irrelevance. I hope Sony actually goes through with this. I currently use an ipad mini & notesplus with a jot pro - it's a good setup and works well, but I still find myself reaching for legal pads half the time. Is this reader any different? Just looking at the page, I don't quite get what makes it different and HN worthy? and please make a external monitor version! preferably 24" so I can have a secondary monitor dedicated to word-processing. even though refresh times might be slow for anything else having an e-paper external monitor for word-processing would make total sense from an ergonomics perspective. a lot of people spend many hours a day writing/editing text and e-paper is much more eye-friendly. Also, from the images it does look like it would be "e-ink" but I see no mention of it on the page. Is it really "e-ink" (like Kindle) or just "e-paper", which is just a transflective LCD (Pebble, Notion Ink Adam, etc). Surface Pro, Galaxy Tab, Asus Vivotab Note. Each hit vastly different price ranges (Surface Pro ~$900 high-quality device, Galaxy Tab rounds out $500 mark, and Vivotab Note hits $300). I doubt Sony can beat the Vivotab Note on price / performance, and I doubt it can win on flexibility vs Android or Surface Pro. I know they can be considered bad practice, but in practice you use at at least a couple of them at least once in every project! And you use it because the alternative would be even uglier. (Also, what's the point in having a language with a separate namespace for functions and variables - Perl and Common Lisp being the only other ones I know of - if you can't at least have fun with variable variables and using a string directly as a function :) ) ...also, they've "downgraded" PHP's closures mechanism. I mean, with: ... return function foo($a, $b) use ($outer1, $outer2) { ... } Their VM may be awesome, but their language is horrid - they take away the "fun" features of PHP but don't fix any of the bad language design issues. It's like throwing away the baby and keeping the bath water - yeah, the water will keep you alive for a few more days in the desset, but the baby can actually be fun to play with. Has anyone else played with Hack in a productionish environment? I'm just wondering what deployments and stuff are actually looking like in the world outside of Facebook. p.s. tutorial that really exposed me to hack is here: Are there any benchmarks proving that HHVM improves performance? Can I get a better performance than my current setup of Nginx + uWSGI + Flask ? The indie game developers care about originality, passion, the sweat and hard months of work, the dedication to the craft. I think the point of Asher's essay is to show how much love and effort went into it, and that they were indeed the first to ship a full, polished game with that concept. That's where their pride and satisfaction comes from. The startup people care about end user experience, how good the PR is, and ultimately how numbers matter more than everything else. I don't think there's a wrong or right vision - it's two very different communities. Indie game devs dream of making amazing games with other talented, inspiring people - and as long as they make enough money to live not too uncomfortably, they're fine. Their biggest dream is to receive an IGF award and see their game on Steam. Maybe make enough money to be able to start a studio with a bunch of their friends, but definitely not to "scale" to EA-size. Startup people dream of growing their company to Facebook size, making billions of dollars, scaling, and being on Techcrunch. It's two very different communities, and it's fun to see the two worlds collide. Addendum: if you feel like this post is vindictive, bitter, etc.- remember: the best way to interpret a view different than yours is to understand that there is a worldview in which those statements are perfectly coherent, logical, and meaningful. Asher, Greg, and all the other people mentioned in this post are successful, highly respected members of the indie game dev community - not a bunch of guys who are angry for whatever silly reason. I played Threes, and I liked it. And I feel for these guys having to watch everybody and his brother pile on to the idea they had to work so hard to tease out into reality. But here is some hard truth: none of that matters. Nobody cares how hard you had to work to get from idea to product. All they care about is what you have produced at the end of all that work. What makes it better or worse is how it stacks up relative to the competition -- even the competition that is shamelessly riffing off your core ideas -- not how much sweat you put into it. And I gotta say, having played 2048, 1024 and Threes (the Android versions, at least), I think of the three of them 1024 stands up the best. It takes the core ideas in Threes and sands them down into a game that is easier to grasp and plays faster, without becoming so simple (a la 2048) that it becomes a game a script can beat. Threes makes you swipe-swipe-swipe after every game to get your score and "sign" it (why do I care about signing it?) before you can play again; 1024 just moves you straight on to the next game. Mobile games need to be simple and streamlined, and 1024 understands that imperative better than Threes does. I say all this to help others understand why I would point to this essay as an example of how not to respond to a problem like a barrage of cloners. It's because this essay sees the world entirely from the developers' perspective -- look how hard we worked! Look how long we labored! Look how subtle our decisions were! -- which is exactly the wrong angle. You want your communications to speak from the customer's perspective, not from your own. Customers don't give you brownie points for how hard you worked on something. All they care about is how to get the best product for the best price. So if you put your heart and soul into something, and then someone comes along, tweaks your thing and makes it better, the way to respond isn't to ask people to respect how hard you worked; it's to look closely at the new thing, understand why people like it better, and then bring that understanding to your next iteration or your next product. The mechanics of the two games are very similar, and obviously 2048 is a direct descendent of threes - but I wouldn't go so far to say that one is better than the other. Threes has claim to originality, and first publication, so significant credit does need to go to Asher Vollmer, Greg Wohlwend and composer Jimmy Hinson of Sirvo for their original invention. But, Threes does have some "issue" - one is really poor startup times. It's slow enough that I am more likely to play 2048 in my browser, than bother firing up Threes on my iPhone. The piece assignment in threes, is also somewhat less pleasing to my experience than in 2048, for whatever reason. Also - sometimes you are looking for nice quick fun - I get a nice rush of (finger mashing) 2048 to the 512 stage, and then very, very quickly racing to 2048 instinctively (plus the crush of defeat if I make a flickering mistake and get my pieces out of place). Threes requires a lot more attention - I can't really play it at full-key-flick-speed - Not every game has to be chess. If you read through the emails, and design history on the "making of" - it really, really emphasizes how damn hard it is to build that original kernel of genius. And then the piling on of all the clones/knockoffs/descendants shows how trivial it is for others to stand on the shoulders of genius. One challenge of the AppStore (and obviously the Android stores, and simply by definition the Web) - is that there is no real way to "reward" the original developers for their many months of hard work, when others can simply clone, tweak the artwork and mechanics (or in the case of Zynga, just the artwork) - and release and market their own duplicate of a game after someone else has done all the hard work. But, sometimes this opportunity to reinvent is good - I've tried a lot of podcast apps - because I listen to podcasts for about 4-6 hours/day, and, while "Cast" is my current preferred App, I'm looking forward to what Marco does with Overcast. I would have hated it if we couldn't have lots of diversity in that marketplace. (And I would have shot myself if I had to use Apple's (original, horrible) "reel-reel" podcast player). Another approach though are apps like Vesper - It's "another" notepad app - but the developers (Q Branch's John Gruber, Brent Simmons, and Dave Wiskus), took months and months to polish and refine till it creates a totally different notepad experience (and, in my opinion, the best one on the iPhone) - isn't it good that they had the opportunity to build something in the notepad category, in a different way? All in all though, I hope that Sirvo's Asher Vollmer, Greg Wohlwend and Jimmy Hinson get the credit they deserve for building the "first of". Spoiler alert: at one point it was a game about argyle socks and monsters (Argoyle). They even have a SWAT team that will go out and build prototypes in days and launch them on the App store as quickly as possible to get some users. They've even launched games with the exact same name as the popular game in hopes of tricking people into using their version of the game. The entire thing is despicable to me, but I guess that's just the nature of the gaming industry these days. Most companies are ripping off each other, so true innovation is hard to come by, and isn't really appreciated anymore. The funny thing is that he also admitted that they have run out of successful games to rip off, so they might actually have to build their own games. This is something the developers are known for. Greg's earlier game, Ridiculous Fishing, not only had it's own internal Twitter app ("Byrdr") with it's own ARG mini-game - including a fake website with SQL injection vulnerabilities and a voicemail hacking sidequest. This is one of the most simple, elegant and original game ideas of recent times. One of those that make you wonder how has no one managed to stumble on it before. It is inevitable it got copied. The reason why it got copied and why 1024/2048 got really popular is that they have overdone the original. The interface is just too funky, there's fluff, fluff and decoration. Rubbery UI makes you feel like you are fighting with the app every time you use it. There are also those smileys on tiles too. So what you have is an idea that looks more complicated than needed (with 1s and 2s being special) and the execution that looks cluttered. That's just asking for a simpler clone - exactly what they got in 1024 and 2048. Now they have an unenviable task of trying to convince players that added complexity in their version is by design. That or try and slim down the game for faster pace (and perhaps add "basic" mode that mimics clones' simpler mechanics). But this line "Others rifled off that they thought 2048 was a better game than Threes. That all stung pretty bad. We know Threes is a better game, we spent over a year on it. " The fact that someone spent less time on a game, and based it on your game, does not make it a WORSE game. It's just unfortunate for you. Then the developer put "Gameplay similar to Threes" or something like that on the page. I thought it was a nice gesture. But, overall, I felt for the Threes developers. I'm glad to see this posted to HN. Instead, they are expressing grief (having been accused of cloning the... clones), understanding of how ideas evolve and an awesome release of 45,000 words of internal discussions, sketches, prototype designs of their work of 14 months to get to release. If you're interested in game design, this is pure gold. As someone who pooped out a low quality clone of Threes for the purpose of teaching myself d3 ( ), I can say that there is a mile of difference between the polish of Threes vs 2048. Also, I agree with the 3's creator when he says that 2048 is essentially broken. I had played 3s before playing 2048. I got 1024 on my first play through, and the middle part of the game was so tedious I resorted to the alternating up, left strategy just so I could advance the game. It's a little weird that a clone of a clone got so much attention. I was addicted to Threes when I first got it. I played dozens of games per session, and multiple sessions per day. So it was definitely addictive. But, as it turned out, I only played Threes for about as many days. The flame that burns brightest burns out the soonest, I suppose. Give me a break, this same diatribe could be spouted by anybody who has built anything of significance. Yes, if you build something great, people will copy it, just as your precious snowflake was inspired by others as well. This isn't anything unique to gaming, it isn't anything unique to 3s, it is an immovable fact of life. Are people copying the product we've poured the last 18 months into? Damn right they are, and if we don't do a better job of executing then we will rightfully get buried. The gaming industry in general is incredibly derivative, it is the modus operandi. I ran a gaming studio for a while and you bet we did our share of "being inspired" as well as our share of "inspiring others". It is just a fact of life. I think the thing that gets my goat here is the waxing on that 2048 is a worse game because it is easier and all the people who played that just don't "get" the careful 14 months of planning that went into 3s. Let's get something straight here, 3s is a great mobile game, but it is just that, a mobile game for playing at bus stops. And the one and only measure of success there is how much fun people have playing it. Flappy Bird is stupid, but it is also entertaining for no real reason. Chess on the other hand, is rather smart, and also entertaining. Both have their place. And yes, we can cry about how society is going down the drain and only appreciates dumbed down games, but 3s is pretty simple so let's not throw stones shall we? Phew, ok, who needs a coffee? Is it a good thing that Threes is so hard it's like pushing a rock uphill, until you inevitably can't keep it up and it comes crashing down on you? If someone invented the 15 Puzzle today (the one where you slide the tiles around in a 4x4 grid), for example, but dressed it up and tweaked it so you couldn't beat it, people would probably start having fun with the possible version on the side. Also knowing other people had "beaten" 2048 initially helped to made it more addictive. Also, time/effort/money spent developing a game does not make it better or worse than other games. Some dead simple things are awesome, and some things that took forever aren't. Again, I have and like Threes quite a bit, but the time it took to make doesn't make it better than anything else. I haven't played the knockoffs, but if they are doing well I suspect they are decent games in their own right. People seem to get stuck on the idea that a good game is good because of it's mechanic. Therefore if someone uses your mechanic, you're stuffed. A mechanic is only part of what makes a game really good. It's a similar mistake to having a feature focus in a product company. It has been fun to see all the riffing off the Threes concept over the past couple of weeks. And I'm sure Asher Vollmer and team will benefit from it all. There is more interest in all the games, they'll have extra ideas from the clones that come out, they find out for free some ideas that don't work. It will help them raise the bar on Threes and make it a better, more successful game. ""?""" I don't know what I'd do in their position; feeling disheartened is definitely one. It's a great game - granted I'm not a fan of the sound design so get frustrated sometimes - the game itself is fun and addictive. I don't think this post will convince as many people as they think to switch to the original, but I hope it does them some good. It really pisses me off always I read from somebody how he got burned by a rip-off. If you do it right 2048 will make YOU famous and all future products of you will automatically get more attention, even if you don't make any money on Threes (which is a way worse name than 2048 in the eyes of hackers, btw). Talk to blogs, Youtube reviewers and to us HN users and show us how awesome your product is and if it is really better than 2048 then you will automatically win the crowd. Think about how much attention (and money) PSY now gets for everything he does, although he didn't get as much money directly from Gangnam Style as he could have gotten. Just complaining and hoping that people will support you because it would be fair is cheap, sad, and it won't happen anyway. I bet there's an effect there. I bet it's in Three's favor. And I bet any freshman-level stats student could rigorously show it. Amazing... Threes invented a wonderful game mechanic, and I'm reminded of the amazing indie games particularly on Kongregate. It's really something special to see all the creativity and joy that a great computer game can create. My advice to the Threes inventors would be: rise above the imitators. Indeed, see them for what they are, gestures of respect (with the exception of 1024, who's makers are just assholes). One concrete step I'd take if I were you is to request that the web knock-offs in particular at the very least mention and/or link back to Threes (perhaps an iTunes link[1]). [1] With that in mind, and with all fairness to the creators of Threes for their hard work, as evidenced in the article, I feel put off by their choice of the word 'rip-off'. I say this as someone who has never played Threes, and never would have, but enjoyed many of the different forks and iterations of 2048. Yesterday, I tried to pay and download Threes, but it said it requires iOS 6. I never upgrade my iOS devices after too many screwups from Apple. So not sure if I will ever play Threes. I don't know much about iOS development, but I wonder why a game which is basically a 4x4 grid doesn't work on every single version of iOS. 1024 works just fine. 2048 is a game that was HACKED together and displayed on HACKER news and made open source for the sole purpose of independent HACKING, and indie creativity. In fact, 2048 has got to be the best case study of how HACKING went viral, not so much about how the game went viral, even if that is what theoretically happened. From that perspective, the THREEs game is just collateral damage and not really what matters here. The Threes game's developers in effect are all crying about how people are misusing their ideas, copying all the wrong details, and not copying what is the true flattery of the game in the first place. And they wrote a blog post to brag about it all! But little do they understand that people (hackers) take what they like and leave the rest. I expect better web design from the team behind Threes, which I bought and liked. When you are stuck in a company that can't innovate because a shitty site leads to more money due to inertia, then you know you are on your way down. This leads to your best developers thinking "what the fuck did I waste all my time for?" and they will leave in no uncertain terms. I got to use this alternative design on my second Facebook account that I used for app development, while my personal account didn't have it enabled. I really disliked like the new sidebar design. The concept was similar to what GMail has done lately, with text links replaced by only graphical icons. I found it really difficult to remember what each icon linked to, and I'd have to go through and hover over each icon one by one. My theory (which I think has as much evidence to back it up as Dustin's) is that if the feed performed better in this design, it was because the poorly designed menu made it more difficult to navigate the rest of the site! Users didn't want the news feed to change, and the users were right. If you trust your metrics and nothing else, you have to be very sure that your metrics encompass every aspect of the reality you are modelling. If they just tell you about clicks and sales, they might be missing longer-term objectives like user satisfaction and retention. However, it's a cheap argument to make, because the Hard Thing is to decide how many months of crappy numbers are you going to withstand before you admit that your Beautiful New Design in fact isn't any good? Six months? Two years? And it's not just revenue you look at. How's overall engagement? Sharing rates? Communication? Discovery? The article is a shallow snipe; the real issues here are hard, interesting, and unexplored by this piece. Don't think of it in terms of pure design. Think of it in terms of cost. Everything has a cost and sometimes good design's real cost is in user behavior. Pageviews and time on site could go down because people aren't going through so many steps to get to what they want. There are a lot of metrics that aren't that useful without the context of the ultimate conversion numbers for your site/app/product/project. Facebook and Google are advertising companies. The financial metric they care about is advertising revenue per user and number of users. It's not much different than a SAAS app in that way. Other metrics are important, but that is the metric that pays the bills. A beautiful design that doesn't improve the core metrics is like a multi million dollar super bowl commercial that flops. Sure, it might be really cool and well produced, but if it doesn't sell your product, you might as well light that money on fire. The net effect is the same. Whatever is cleanest and most elegant is not necessarily the most user-friendly design, never mind the optimal design from the point of view of user engagement. Actually, the question of the piece is a good one. It's really about what you're optimizing for. As every halfway decent manager knows, you get what you measure. Which means deciding what to measure is one of the most important decisions you can make. So, in this case, do you measure user engagement time for individual sessions? Or is there some sort of "engagement longevity" which might show a better timeline keeps people visiting more often over a longer period of time? The other possible approach would be to see what could be done to make events and profile pages more appealing to spend time on. There may not be a way to do that if the timeline satisfies people, but it would be worth investigating. If you're going to work strictly by the short-term numbers, you might as well be the bubonic plague. "Good news! We're up 32% in London! Quarterly bonuses for all the fleas, and gift cards for the rats at the all-hands!" And so, in companies like Facebook and Google, it doesn't matter what you know, it only matters what you can prove. Meanwhile your competitors in the market are unburdened by the need for proof and shout down at you from the mountain in the distance when they arrive. And your solution is to do LESS TESTING? We don't know what we're doing, so let's cut back on the amount of data we can use to inform our decisions? > "We are slaves to the numbers. We dont operate around innovation. We only optimize." I don't see why numbers should ever stop you from innovating. The difference between "innovating" and "optimizing" is just a difference of scale. You can make a huge change to your layout or site function and look at the numbers it the same way you'd look at a font and color change. The quote above seems to say that people shouldn't make decisions based on numbers, and that's absurd for a company like Facebook. What should be the basis of their decisions then? Management's gut reaction? Whoever feels the strongest about a change wins? Customer surveys and user metrics matter - both are often numbers. The real issue here isn't that Facebook uses numbers too much. If they made the wrong choice, it's because they put too much emphasis on the wrong numbers. Users had access to the site as long as they stayed on the phone to our special 2 dollar per minute phone line. It worked, but it was a pain to work for a company like that. I was fresh out of school and just wanted to get better at my trade, but wasn't allowed to do the best I could. Frustrating. Needless to say, things have changed in that industry, gotten a lot trickier, and the company has had to switch into different avenues. They now offer payment solutions and run a huge dating site. I really do like the new treatment and I think they should have gone with this and figured out how to recover the revenue stream later. Given how much Facebook traffic is going to mobile instead of desktop, this wouldn't have a large impact over the long run. I think this is actually a rational-- or at least natural-- course of action. As you get more eminent, the stakes are also higher, and when you have more to lose you tend to take less risk. In fact, it'd be surprising if a big company continued taking risks by trusting non-structural decisions. This is probably related to the phenomenon that large organizations tend to fall into bureaucracy. In fact the two questions are probably overlapping, if not identical. How can you grow big and famous and take on big responsibilities without losing your ability to trust your intuition and care about the feel and usability of the product? How can you stop yourself from degenerating into bureaucracy? I'm pretty confident it's possible. Steve Jobs managed it. My own hunch is that the trick is to hire people who don't care about money too much. The kind of people who think, if we lose a bit of revenue, who cares? Which is paradoxical, my hunch continues, because people like this will eventually make better products in the long run, and end up increasing revenue in a thousand different little ways. Doesn't this only apply to CEOs who run companies that give away their products to indirectly monetize it? If you had a product you sold to your customers wouldn't this improvement in usability/product quality be a no-brainer because better product = more sales = more revenue? I can't help but feel that something has gone wrong when Facebook - or any company - will deliver its users a worse product for the sake of few more dollars. The people at Facebook are extremely talented. It's a shame they're stuck with this business model. It would be awesome to see how good they could make Facebook if this wasn't tying them down. Yes, the larger images were nice to look at - but they got in the way of actually viewing the content for me. My personal viewing habits of the newsfeed are to give facebook a glance over once a day with my morning coffee. The purpose is to get an overview - quickly. The newer look got in the way of that, especially when viewing in smaller windows. There are also all the folk who aren't looking at it on large displays, and maybe consistency of experience is important too. Sure - maybe there's a metrics issue too. But I've seen more than my fair share of usability tests where things that my "design" persona like end up being disliked by the people who actually use the site. But Google learned to listen to more right-brain arguments so maybe FB can too. And its more rational to say here are concrete numbers clearly affecting the bottomline vs well our 5 experts think this design is better so we are sticking with it. Without any "higher mission" at all, Facebook has to resort to these lowest-common-denominator values. I only hope that someone with better values can gain an edge someday, and refuses to be acquired/neutralized by Facebook. [0] Until then, they will provide the minimal user experience that keeps them on top of the hill with as much ad inventory as possible. Actually, the older version of the design we tested would have been positive for revenue had we shipped it. But there were a number of other issues that made it harder for people to use (which also resulted in them liking it less.) I am not a facebook fan or an affiliate, and I do resent few of their design decisions, but earning money is well within their framework of morality. there is no such thing in the world like "performing too well". if a better design led to less user engagements, it means the product, in its bare bone, not valuable to users. Shouldn't then the most rational choice be to start with a crude initial design an use a reinforcement learning algorithm to optimize it according to the metrics? Just like Google of 5-7 years ago, they're also spreading their focus on many projects, and in a few years probably forgetting about them and ignoring them, if they don't turn into big cash cows for them almost immediately. Then expect Facebook to kill a lot of services, just like Google did. Maybe Facebook found that people really actually liked the other variant better? Or maybe they were just ambivalent about it, and if we've learned anything about widely deployed social media sites, it's that you need a really, really good reason to change things. And to add just a bit more on the "contrived" notion: My Facebook feed looks very similar to the first page, with big, colourful pictures dominating my news food. If my network had people posting short twitter-like missives, I suppose it would look like that. Outside of trivial CSS differences, the only real variation is that I don't have the confusing iconography down the left, instead using that massive area of white space for descriptive text. See the trend lines for Futurama: difference between all the episodes make having a "trend" very doubtful. Especially season 5 is a wildly varying season where if you take one episode away the line would completely flip. Much the same can be said for The Next Generation where you have basically clouds where seemingly at random a line is drawn through it. Yes, I know there are statistical methods for determining trends, but without data on their accuracy they are pretty much worthless. And you really should use a threshold for those accuracies if you're presenting this kind of data to a very wide audience. Honestly: is "Homer the Smithers" the best episode of The Simpsons? I doubt anyone would truly put it on their "best ever" list. It's really more "solid" than great. Most importantly: it doesn't rub anyone the wrong way. Is "Saddlesore Galactica" one of the worst episodes ever? No. It's extremely funny and the story is structured well. It gets lots of very low votes from viewers who favor realism over humor (the episode is implausible with the horse racing then gets silly/fantasy). The episode's score reflects a community desire rather than an objective opinion. Here's a few interesting ones I've come across: * The Wire () Known for being a slow starting show, this is visible with the season trend lines. * The Shield () Season 4 is such a massive outlier. * Seinfeld () Held very steady until the last season. Here's proof that IMDb is bullshit: Simpson Tide is very highly rated. That episode is one of the absolute worst. Here's a rough overview: S1: terrible! S2: promise! S3: very good! S3-S8: the absolute best! S9-S10: still very goodbut not as good S11: definite decline S12: yep. S13-17: ok wow this is pretty bad. S18-19: a little better S20-21: definitely better S22-25: actually pretty good! The series has been extremely underrated since Season 20 or so when it came out of the slump that began with Season 11. It's not the Star Trek: TNG Deep Space 9: Enterprise: Or in each season Game of Thrones: Or took a while to hit their stride, then left right after the peak Seinfeld: Had a story arc: B5 Or were clearly failing: Andromeda: Sliders: Futureama: Or are experiencing a revival I wish this could be correlated against ratings data. And or course: Dr. Who edit: Also Law & Order and Law & Order SVU and Law & Order CI and the Stargate series and Battlestar Galactica (1978) recent caprica The 4th episode of True Detective was 9.8. I sometimes feel this way about TV in general (early stuff is better). Example (circa 1967-1968):... BTW, I was born in '84 and not 1884. ;-) 11% 1 star ratings with a pretty remarkable demographic distribution. In general an alternate IMDB algorithm probably would give a truer image if you clip of the extreme ratings 1 and 10 before averaging, thereby getting rid of most fanboy/rage votes. Sorkin co-wrote the first four seasons. I was expecting the dip in S05 but I did not expect such a dramatic upturn in S07. Notice how first and last episode of season 2 are way up there. "Now cracks a noble heart.Good night, sweet prince,And flights of angels sing thee to thy rest!" I wish the team all the best at Dropbox, and I'm sure Dropbox will benefit immensely from their remarkable talent for building amazing software. At the same time, though, I wish they would have just started charging $10 a month for the service! It explains clearly what happened; it isn't overly congratulatory to themselves; it puts a clear emphasis on how their users can export their data; it thanks those who helped them on the journey; it beautifully summarizes everything they built and stood for, from the solid typography, to the interactive timeline, to the team photos, to the simple, clean choice of a "Epilogue" as the title. And it'll be the perfect homepage come July 1st too. Sad to see such a high-quality product shut down. I've looked to Readmill for design inspiration a lot over the past year. Bottom line: to become everyone's all-in-one cloud, synced, folder. This would be the platform, a ~/user/ in the cloudBottom line: to become everyone's all-in-one cloud, synced, folder. This would be the platform, a ~/user/ in the cloud - Audiogalaxy Dec 2012: online iTunes-like audio library, synced across/streamed to all of my devices - Snapjoy Dec 2012: online iPhoto-like experience, synced... - Mailbox Mar 2013: can Dropbox be the new Gmail? If Google search needs disruption, Gmail is no different - Zulip Mar 2014: online chat and team collaboration with file/screenshot/text/etc sharing integrated to a whole new level. Maybe Droplr/CloudApp on steroids - Readmill Mar 2014: online ezine/book library... maybe doc management?! PS: from their Sold and Endorse acquisitions I can only speculate that they might have a(n) (e)commerce play in their mind. Also hoping they implement the payment protocol (BIP70), which gives a much better user experience and improved security. Instead of copy pasting an address, a signed payment request is sent to the users Bitcoin wallet with a message stating something like "Bob's shop has requested a payment of 10USD (20mBTC) - accept?". Some particularly insidious coin stealing malware has been developed that modifies the payment address in the clipboard to be changed to an attackers address, and the whole UX around copying long Base58 encoded strings is horrible. Furthermore, the signed payment request serves as a receipt. With BIP70, the UX of bitcoin payments surpasses that of CC payments, IMO. Stripe are obviously taking the risk of the volatility so will probably want to keep the bitcoin float that they hold fairly small. They also need to keep a reasonable margin on these transactions and watch for people who don't complete transactions unless the price moves in their favour (after the price has been quoted). I assume refunds are of bitcoin to the agreed dollar value not the same number of bitcoins as was spent, otherwise there would be risks there too. Edit: Found this in other story:...). I used Stripe for several months, but then they said my business is "too high a risk" for them, 7 years in business (longer than Stripe), hosting company in Ireland, very low charge-back rate, all customers more than happy, good support etc! Since then opened a merchant account with Elavon after referal from our bank for credit cards and started using Bitpay for bitcoin, not only have lower fees (0% in case of Bitpay + 30$ a month for professional account), but also registered with Mastercard 3D Secure and Verified by Visa, which Stripe doesn't offer either. I'm so glad they integrated bitcoin, which I think will be a really good contribution to make btc spread amongst normal users. That's great to see them becoming more of a payment processor versus the simple credit card processor they were. I love stripe, I love btc, and seeing them together is just really cool and a big step for both. [0]: Now, under one provider, we can easily accept CC and BTC. This is great news for consumers because it means coinbase and stripe are now in head-to-head competition. These are both well funded startups with great usability. Bring on the feature war and lower transaction fees! This is most exciting because this will enable great micropayment support on stripe, enabling a whole new breed of marketplace. Also, it is now easy to offer paid anonymous consumption of an API. This is a whole new world of opportunity! [Edit: Fixed bad grammar] Any plans for an option to accept fiat and convert to BTC? Example:... (I found this to be one of the most impressive examples used by Edward Tufte in his books). Reading these old proofs is quite tedious but having this visualization makes it much easier to follow. Still, trying to understand Euclid makes you thankful for the more than 2000 years of advancements in mathematical notation and theory. ps: vector editor is not my website.?... To me that would be the most significant reason to do it. Rather than picking and choosing specific companies, the money behind YC VC is betting that the basket of companies as a whole is going to perform well on aggregate (thanks to power law). It's really putting faith in the YC selection process / mentoring multiplier as a whole rather than any particular company (which they can do later after demo day). The YC VC program (and it's earlier incarnation) made sense to me because VCs wanted access to YC deal flow. But now with the new program traditional LPs are investing at the same time (i.e., acceptance to YC) as YC LPs, but with much worse terms. Maybe I'm missing something here? OK, yes, I'm being selfish here, but this is just the way it is for us... moving, even for 3 months, just isn't an option and may never be. But that's really the main thing preventing us from taking a stab at doing YC. Of course, we do have a similar accelerator/incubator here in The Startup Factory, but competition and more choices are a Good Thing. :-) I gained a lot of weight because of medications (normal weight is 210lbs, which is fine for my 6' 4" frame, but medication caused me to balloon up to over 444lbs). I have not been able to work at my peak for many years. I'm now almost 45, and I feel like I'm starting to get my life back. Now that I'm off the main drug that treated my disorder (risperidone) my weight is starting to drop. I know people are scared of mental illness. I see it in their faces, or the way they treat me differently as time goes by. But that's okay, I have close friends who have accepted me for who I am without that fear. My wife wishes I wouldn't tell people about my history. My health is no one's business but mine. However, I choose to tell people about it, because of the stigma. Because I'm neither ashamed or afraid for people to know. I _will_ lose friends, work, and opportunities because of my choice to be open about it, but I don't care because I want to fight the stigma. Everyone has a friend or family member that struggles with some form of mental illness. Everyone. I have seen too many people suffer in silence, and some even take their own lives because the pain is too much. I was suicidal years ago. I suffered horribly for many months on end, waking up in the morning and just focussing on getting through the next hour, until I finally reached the end of the day and could go back to sleep so I could have some relief. There is no shame in mental illness. People used to be afraid of people who had heart disease, as if they might "catch something" from them. The brain is the most complex organ in our bodies, and it's prone to have problems just like any other organ. My name is Miles Forrest. I have wrestled with mental illness for many years, and I'm happy to say I have overcome it with help from doctors, family, friends, and God (if you're offended by my attribution to God, please don't be. I respect a person's right to believe whatever they want, all I ask is they respect my right to believe whatever I want). I can't say I'm cured, because there's a possibility I might relapse at some point in the future. But I have acquired the skills, knowledge, and support network that I know, without a doubt, I would be able to beat it back down again. Mental illness doesn't define me, but learning to fight, persevere and lean on others when I need to has made me a better man. You can mock or ridicule me if you want, but I'm not talking to you. I'm talking to the man or woman out there who is afraid there might be something wrong with their mind, and who feel alone and afraid. I know how scary it is. I know how you feel like you're the only person in the world who has felt the way you do. You're not, and you are not alone. If you are that person, email me at miles@coderpath.com, and I will walk with you as a friend and stranger to get you help. Sadly, it seems mental illnesses are one of the great taboos of today (and don't even get me started on the state of mental health care in the US). Similarly, mental illnesses are extremely misunderstood, and people tend to distrust people who suffer from one even though illnesses such as depression may affect 5 to 10% of the population [1] and as much as one in four adults are affected by a mental illness in general in a given year [2]. A significant portion of the population is affected, but for the most part it remains unadvisable to talk about it. It's the elephant in the room. This is compounded by the fact American culture in particular tends to disproportionately value extroversion and appearance of happiness. This leads many people to remain closeted by fear of repercussions, both on one's social and work life. Even worse, it prevents people from seeking necessary help because of the attached stigma ("but I'm not crazy!"). There are known cases where people are punished for having seeked professional help. For exemple, people who admitted to "suicidal tendencies", however serious, may be refused US visas [3]. The discrepancy between how willingly people talk about their trip to a doctor vs. a therapist is huge and obvious, and it shouldn't be. Now why should this be relevant for the HN crowd? As someone who's very close to these issues, it seems to me this is one of the few social issues where the tech industry is not as progressive as it could be. Our industry tends to produce myths of super(wo)men with alpha personalities; we admire leaders, disrupters, bigger-than-life personalities, sometimes even assholes. Furthermore, this is a small world where, for better or for worse, a lot depends on word-of-mouth and personal reputation, and where "cultural fit" is openly hailed as a criterion for employment despite the vagueness of the term, which can hide what would otherwise be considered blatant discrimination (cf. that article on ageism not so long ago). The same goes for founders: would you think twice about investing in a non-established individual with a history of OCD? Depression? What I am getting at is that mental illness is a combination of neurobiological and psychological causes, not a weakness in character -- but in an industry that values strength of character above everything else, the fact many ignore this can be extremely destructive. We can do better. The author has done the world a great service by publishing his story. I hope more follow suit. [1] [2]... [3]... It should not be taken as a signal that "outing" oneself is advisable for others in comparable situations. This guy is very fortunate that he is well established in a career and can point to good performance in his positions, unaffected (from the employer's point of view) by his condition. Others are much more vulnerable to prejudice and discrimination, and might be better advised to stay closeted. Though many object to psychiatrys perceived encroachment into normality, we rarely hear such complaints about the rest of medicine. Few lament that nearly all of us, at some point in our lives, seek care from a physician and take all manner of medications, most without need of a prescription, for one physical ailment or another. If we can accept that it is completely normal to be medically sick, not only with transient conditions such as coughs and colds, but also chronic disorders such as farsightedness, lower back pain, high blood pressure or diabetes, why cant thats like equating a cough with tuberculosis or lung cancer.-... Acknowledgement of the mental illness issue is one part of the problem, which will hopefully lead to better, more integrated treatment lines in the future. As with all spectrum disorders, people seem to focus on the visible, uncontainable, and publicly dangerous 0.1% and ignore that 99.9% of people with the disorder or "on the spectrum" are not dangerous, wouldn't fit most people's image of "mentally ill", and can be very well-adjusted. I tend to think of mood disorders as anti-psychopathy. Psychopaths have low or nonexistent mood and emotional sensitivity, which is why they're social high performers and (if ambitious) excel in the work world. Some mood disorders seem to be uncorrelated to context (i.e. episodes happen "for no reason") and that's probably more true of the severe cases, but most people with mood disorders are normal people with hypersensitivity, such as the OP whose brain would take personal criticism extremely seriously, unable to block it out or cope. Aaron Swartz comes to mind as a archetypical anti-psychopath. They tend to be moralistic, less fearful of negative consequences when doing what they think is right, and prone to mood and anxiety disorders. Anti-psychopathy isn't a desirable thing. It can be just as ill-adjusted. Just as psychopathy tends to be good for the individual (in terms of material prosperity, social rank, and sexual access) but bad for society, anti-psychopathy tends to be good for society but harmful to the individual. What's happening right now, in Silicon Valley, is a battle to the death between real technologists (who tend to be anti-psychopaths) and the mainstream business culture of entitled executives and board-whores (psychopaths). With Snapchat and Clinkle setting the tone in the current Valley, rents becoming unaffordable, and no-poach agreements all over the Valley, psychopaths seem to be winning. I think that mood disorders in particular require a certain balance. People tend to do unwise or harmful things, especially when inexperienced, and those with mood disorders are not exceptions. You have to own your actions, even if you made them in a struggle that most people wouldn't understand. That said, it's also important to realize "it's not me, it's them" and keep your pride intact. Mental health issues often give you a front-row seat for how shitty people can be when they think you're weak. Much of what comes out of these disorders isn't harmful in the least. It's just slightly embarrassing, but plenty of people will hang you out to dry just because they're weak, useless cowards. This may be why people with mood disorders (at least, the milder kind that won't interfere with ethical behavior; a truly "manic" person, noting that mania-- not the milder hypomania-- is very rare even in people with bipolar, does not know who he is) tend to evolve into moralistic, hyper-ethical anti-psychopaths. I'll give a semi-fictional example. Let's say you're a programmer and you have a hypomanic episode. You still go to work, don't cause any issues, and spend 2 weeks building something you were never assigned to do. It turns out to be really good work and useful to the company (as much, or moreso, than putting that time in on your assigned work) but your boss is pissed off that you were working on this side project, instead of your assigned work, and tags you as "unreliable". A morally decent person would recognize that as wrong (it's health discrimination, and counterproductive, to punish people with "creative flare-ups") but, even still, stories like that are so common in Silicon Valley as to be unremarkable. Anti-psychopaths tend to need an R&D environment where they're measured by performance over time, rather than minute-by-minute superficial reliability (at which they can't possibly compete) and those, sadly, tend to be turning rare in the current anti-intellectual (and pro-psychopathic) environment. MH treatment is underfunded in England (and this has recently been written into commissioning contracts) and it is worse for children and young people. In patient beds for children are limited. A child who needs an in patient bed may have to travel hundreds of miles to get that bed. They may even need to travel to a different country. A child in the south of England may not have a bed available anywhere in England and might need to go to Scotland for a bed. Apart from the obvious cost of distance and the distress of being so far from home (although getting distance from an abusive home can be useful) that child is now under a different legal system. Thus, the rules for detaining them against their will; force feeding; forced medication; etc etc are all slightly different. The "stigma" against mental illness makes sense in a lot of ways. I do not mean: that the mentally ill deserve fewer legal rights than others, deserve any kind of bad treatment or violence or ridicule, shouldn't be "accepted", or bear any "responsibility" for their condition. I do mean: life is full of subtle social contracts that mental illness often causes people to flout. Mental illness (in many cases) makes people less predictable and reliable. Harder to deal with. Some people reading this will say "obviously that is true, which we all acknowledge but have no reason to dwell on, and that is why it is a complex situation that demands awareness". Others will say "that is false and you are a bad person". First group, I refer you to second group. If you are 100% committed to the goals of your organization (growing a startup, winning a war, whatever), you will be very hesitant to add a mentally ill person to your team/company/platoon. This makes sense. It sucks. Being mentally ill sucks. This is one of the ways. That doesn't necessarily mean anything needs to or can be done to change it. At the same time, I don't think he is ill. While I don't doubt that he is suffering, I don't think it it is helpful to class his suffering as an illness. I don't think anyone argues that his symptoms are caused by an infection or a defect in an organ, so his disorder lacks the physical basis for a typical illness. At the same time, he has symptoms. And therapy, and possibly drugs, make him feel subjectively better. He chooses to engage in a regime of therapy which (presumably) has self reported benefits. But I don't think it is helpful to think of his plight like we think of malaria or polio or heart disease. When we talk about 'emotional disorders', we implicitly take on an enormous amount of cultural context as well as normative judgements about how someone 'should' feel. And the danger is that one will come to believe that an unpleasant mental state in an otherwise healthy brain is something to be cured through the application of science. That being said, I agree with the main point -- that there is no shame in his mental state. I suppose my point is that it is not necessary (and should not be necessary) to reclassify what a disease is in order for a class of people to maintain their dignity. And above all, I wish this man well and by no means mean to diminish his pain, or the courage it took to write this. I love examples like that where a company's policies result in incentives that are so well-aligned with those of their users. Does anyone have other good examples to share? [0] and are two examples. At what point in your development process do you say "I want this application, which will be distributed to unknown persons, to contain the means to control my AWS account."? "We were made aware" does not equal "we are downloading apps and inspecting them." If they were doing that, that would be great! But let's not leap to conclusions. If you'd like to send an email like this to your users, send me an email (in profile) and I can query our database and check to see if any of them are including their api keys. The advantages of doing this are 1) showing Amazon thinks for the customers (well, also for itself) 2) proves it has pro-actively notified the customer and done its due diligence. This step could serve as a solid proof in any dispute on later security issues or/and related costs. Smart, I will say. +1
http://hackerbra.in/news/1396087322
CC-MAIN-2018-26
refinedweb
23,191
70.13
bool True when the rigidbody sweep intersects any collider, otherwise false. Tests if a rigidbody would collide with anything, if it was moved through the Scene. Tests if a rigidbody would collide with anything, if it was moved through the Scene. This is similar to doing a Physics.Raycast for all points contained in any of a Rigidbody's colliders and returning the closest of all hits (if any) reported. This is useful for AI code, say if you need to know that an object would fit through a gap without colliding with anything. Note that this function only works when a primitive collider type (sphere, cube or capsule) or a convex mesh is attached to the rigidbody object - concave mesh colliders will not work, although they can be detected in the Scene by the sweep. See Also: Physics.SphereCast, Physics.CapsuleCast, Rigidbody.SweepTestAll. using UnityEngine; using System.Collections; public class ExampleClass : MonoBehaviour { public float collisionCheckDistance; public bool aboutToCollide; public float distanceToCollision; public Rigidbody rb; void Start() { rb = GetComponent<Rigidbody>(); } void Update() { RaycastHit hit; if (rb.SweepTest(transform.forward, out hit, collisionCheckDistance)) { aboutToCollide = true; distanceToCollision = hit.distance; } } }
https://docs.unity3d.com/kr/2019.1/ScriptReference/Rigidbody.SweepTest.html
CC-MAIN-2020-40
refinedweb
187
55.24
import urllib from random import choice from sgmllib import SGMLParser class LinkExplorer(SGMLParser): def reset(self): SGMLParser.reset(self) self.links = [] # list with the urls def start_a(self, attrs): """ fill the links with the links in the page """ for k in attrs: if k[0] == 'href' and k[1].startswith('http'): self.links.append(k[1]) def explore(parser,s_url,maxvisit=10,iter=0): """ pick a random link in the page s_url and follow its links recursively """ if iter < maxvisit: # it will stop after maxvisit iteration print '(',iter,') I am in',s_url usock = urllib.urlopen(s_url) # download the page parser.reset() # reset the list parser.feed(usock.read()) # parse the current page if len(parser.links) > 0: explore(parser,choice(parser.links),maxvisit,iter+1) else: # if the page has no links to follow print 'the page has no links' # test the crawler starting from the python's website parser = LinkExplorer() explore(parser,"")Let's go! ( 0 ) I am in ( 1 ) I am in ( 2 ) I am in ( 3 ) I am in ( 4 ) I am in ( 5 ) I am in ( 6 ) I am in ( 7 ) I am in ( 8 ) I am in ( 9 ) I am in really nice, thanks man ;) SGMLlib is now deprecated and has been outright removed from Python 3. :(
http://glowingpython.blogspot.it/2011/06/crawling-web-with-sgmlparser.html
CC-MAIN-2015-48
refinedweb
212
60.55
Welcome to the new Parasoft forums! We hope you will enjoy the site and try out some of the new features, like sharing an idea you may have for one of our products or following a category. chasepaymentech CC encryption I'm trying to dynamically encrypt credit card info before passing it t to our API's (simulating the process in the UI, using dynamically-generated PIE settings for the payment with our client chasepaymentech specific .js (). The sample results of the getkey.js are: //---------------------------------------------------------------------- // (c) Copyright. //---------------------------------------------------------------------- // PIE version: 1.2.1 var PIE = {}; // PIE namespace // dynamically-generated PIE settings PIE.L = 6; PIE.E = 4; PIE.K = "70E99B247C0E6B77679F65F1D721B120"; PIE.key_id = "2595de71"; PIE.phase = 0; it then uses for encryption of the credit card no, ccv, and embed key option passed in. Before I dive to far into this, I was wondering if anyone else has integrated with the chasepaymentech solution. 0 Finally moving forward with trying to code this in SoaTest, somehow. Will post back If I determine a solution.0
https://forums.parasoft.com/discussion/5254/chasepaymentech-cc-encryption
CC-MAIN-2022-40
refinedweb
172
60.72
JustCode is invaluable when working with these languages because you no longer have to compile the solution to find errors. Many compilers will stop analysis as soon as it fails to compile a project, failing to provide a complete and valid list of errors. JustCode, however, will continue analyzing your code after it has encountered an error and will provide a complete list of all errors and warnings. When modifying code, the code analysis engine will show you all errors and warnings almost instantly. JustCode helps with web applications as well. The code analysis engine provides on-the-fly error check and warnings for ASP.NET and HTML. To find these errors with Visual Studio alone, you would need to run your web application, which takes a long time especially for large web sites. Further, you do not get a list of errors, forcing you to figure out HTML errors at run time. With JustCode, you no longer have to run web sites to find issues in HTML or ASP.NET, because errors and warnings are indicated as you type, or as the solution updates. With JustCode, you can easily discover JavaScript errors and warnings on-the-fly as you type and quickly navigate through these errors and warnings with the Error List window. JustCode checks the entire solution on-the-fly for XAML errors and warnings and saves you a lot of time tracking down invalid XAML. For example, when you forget to declare a XAML namespace, or when a dependency property is renamed or removed, JustCode notifies you immediately. JustCode checks your CSS code for syntax errors or typo-induced invalid CSS properties or values. These issues can be tough to track down on your own, but with JustCode, you know immediately when there is a problem. The JustCode analysis engine now detects Razor-specific syntax warnings and errors, in addition to traditional code and markup issues. The accompanying messages will aid you in understanding what went wrong, so corrections can be made. JustCode provides support for LESS dynamic stylesheet language. Support for LESS helps web developers build and style their website projects quickly and easily. Navigation features, refactorings and other options have been added with the LESS support to make LESS development effortless. You can create and use code templates for LESS as well. With support for Windows, JustCode enables you to analyze WinRT and Windows Store applications for errors and warnings. Also, you can develop applications in C#, VB.NET, JavaScript and HTML using all of the available features in JustCode. The JustCode warnings and errors (called code problems) provide for easier, more intuitive navigation and control. JustCode even provides all the information and options needed to handle errors and warnings in your code. You can easily navigate to the error, change its type or disable quick-fixes. You don’t have to tell JustCode twice - ignoring errors or searching for similar problems in your code has never been easier. JustCode provides the option to disable showing the solution-wide analysis for a given language. You can also exclude specific files--or entire projects--that you don’t want checked for errors and warnings, very useful for designer generated files. Once you have excluded a file or a project, no errors or warnings will be reported. JustCode can provide inspection details for errors and warnings as follows: With dedicated technical support Purchase individual products or any of the bundles
http://www.telerik.com/products/justcode/code-analysis-and-error-check.aspx
CC-MAIN-2014-15
refinedweb
573
54.42
My solution got TLE on a test case contains thousands of 1. But I cannot figure out why. The time complexity is O(n), and the stack size keeps only 1 in this test case. It's strange that it got TLE. public class Solution { public int largestRectangleArea(int[] height) { int max = 0, i = 0; Stack<Integer> stack = new Stack<Integer>(); while (i < height.length) { if (stack.empty() || height[i] > height[stack.peek()]) { stack.push(i++); } else if (height[i] < height[stack.peek()]) { int top = stack.pop(); max = Math.max(max, height[top] * (stack.empty() ? i : i-stack.peek()-1)); } else { i++; } } while (!stack.empty()) { int top = stack.pop(); max = Math.max(max, height[top] * (stack.empty() ? i : i-stack.peek()-1)); } return max; } } The reason could be class stack which is implemented internally as a growing array. Try replacing stack with LinkedList and use addFirst getFirst and removeFirst and see if it solves the problem. Mine passed the second time. There is also some randomness in the judging I guess.
https://discuss.leetcode.com/topic/7576/why-does-this-o-n-stack-based-solution-get-tle
CC-MAIN-2017-47
refinedweb
171
72.53
Let’s have a look at the structural diagram from the Introduction once more: If you have followed the instructions of the page on Software prerequisits and installation, you are done with the yellow box in the figure. This page will tell you first how to configure and write the few code bits that your node needs before running (blue box), and then how to deploy the node and make it run as shown in the violet box. It goes like this: Get the Nodesoftware and make a copy of the example node. Auto-create a new settings file and put your database connection there. Assign names from the VAMDC dictionary to your data to make them globally understandable. Start your node and test it. But let’s take it step by step: Let’s give the directory which holds your copy of the NodeSoftware a name and call it $VAMDCROOT. (It is called NodeSoftware by default and exists whereever you downloaded and extracted it, unless you moved it elsewhere and/or renamed it, which is no problem to do) a name and call it $VAMDCROOT. Let’s also assume the name of the dataset is YourDBname. Inside $VAMDCROOT you find several subdirectories. For setting up a new node, you only need to care about the one called nodes/ which contains the files for several nodes already, plus the example node. The first thing to do, is to make a copy of the ExampleNode: $ export VAMDCROOT=/your/path/to/NodeSoftware/ $ # (the last line is for Bash-like shells, for C-Shell use `setenv` instead of `export` $ cd $VAMDCROOT/nodes/ $ cp -a ExampleNode YourDBname $ cd YourDBname/ Note In the following you always work within this newly created directory for your node. You should not need to touch any files or run commands outside it. The first thing to do inside your node directory is to run: $ ./manage.py This will generate a new file settings.py for you. This file is where you override the default settings which reside in settings_default.py (which you should not edit!). There are only a few configuration items that you need to fill The structure for filling in this information is already inside the newly created file. You can leave the default values for now, if you do not yet know what to fill in. There are only three more files that you will need to care about in the following: all of which will be explained in detail in the following. By data model we mean the piece of Python code that tells Django the layout of the database, including the relations between the tables. By database we mean the actual relational database that is to hold the data. (See also The main concepts behind the implementation). There are two basic scenarios to come up with these two ingredients. Either the data are already in a relational database, or you want to create one. If you want to deploy the VAMDC node software on top of an existing relational database, the data model for Django can be automatically generated by running: $ ./manage.py inspectdb > node/models.py This will look into the database that you told Django about in settings.py above and create a Python class for each table in the database and attributes for these that correspond to the table columns. An example may look like this: from django.db.models import * class Species(Model): id = IntegerField(primary_key=True) name = CharField(max_length=30) ion = IntegerField() mass = DecimalField(max_digits=7, decimal_places=2) class Meta: db_table = u'species' There is one important thing to do with these model definitions, apart from checking that the columns were detected correctly: The columns that act as a pointer to another table need to be replaced by ForeignKeys, thereby telling the framework how the tables relate to each other. This is best illustrated in an example. Suppose you have a second model, in addition to the one above, that was auto-detected as follows: class State(Model): id = IntegerField(primary_key=True) species = IntegerField() energy = DecimalField(max_digits=17, decimal_places=4) ... Now suppose you know that the field called species is acutally a reference to the species-table. You would then change the class State as such: class State(Model): id = IntegerField(primary_key=True) species = ForeignKey(Species) energy = DecimalField(max_digits=17, decimal_places=4) ... Note You will probably have to re-order the classes inside the file models.py. The class that is referred to needs to be defined before the one that refers to it. In the example, Species must be above State. Let’s add a third model: class Transition(Model): id = IntegerField(primary_key=True) species = ForeignKey(Species) upper_state = ForeignKey(State, related_name='transup') lower_state = ForeignKey(State, related_name='translo') wavelength = FloatField() The important thing here is the related_name. Whenever you want to define more than one ForeignKey to the same model, you need to set this to an arbitrary name. This is because Django will automatically set up the reverse key for you and needs to give it a unique name. The reverse key in this example could be used to get all the Transitions that have a given State as upper or lower state. More on this at Setting the related name of a field. Once you have finished your model, you should test it. Continuing the example above you could do something like: $ ./manage.py shell >>> from node.models import * >>> allspecies = Species.objects.all() >>> allspecies.count() # the number of species is returned >>> somestates = State.objects.filter(species__name='He') >>> for state in somestates: print state.energy >>> sometransitions = Transition.objects.filter(wavelength__lt=500) >>> atransition = sometransitions[5] >>> othertransitions = atransition.upper_state.transup.objects.all() >>> othertransitions.count() # gives the number of transitions with the # same upper state. Detailed information on how to use your models to run queries can be found in Django’s own excellent documentation: In this case we assume that the data are in ascii tables of arbitrary layout. The steps now are as follows: First of all, you need to think about how the data should be structured. Data conversion (units, structure etc) can and should be done while importing the data since this saves work and execution time later. Since the data will need to be represented in the common XSAMS format, it is recommended to adopt a layout with separate tables for species, states, processes (radiative, collisions etc) and references. Deviating data models are certainly possible, but will involve some more work on the query function (see below). In any case, do not so much think about how your data is structured now, but how you want it to be structured in the database, when writing the models. Writing your data models is best learned from example. Have a look at the example from Case 1 above and at file $VAMDCROOT/nodes/vald/node/models.py inside the NodeSoftware to see how the model for VALD looks like. Keep in mind the following points: Once you have a first draft of your data model, you test it by running (inside your node directory): $ ./manage.py sqlall node This will (if you have no error in the models) print the SQL statements that Django will use to create the database, using the connection information in settings.py. If you do not know SQL, you can ignore the output and move straight on to creating the database: $ ./manage.py syncdb Now you have a fresh empty database. You can test it with the same commands as mentioned at the end of Case 1 above, replacing “Species” and “State” by your own model names. Note There is no harm in deleting the database and re-creating it after improving your models. After all, the database is still empty at this stage and syncdb will always create it for you from the models, even if you change your database engine in settings.py. The command for re-creating the tables in the database (deleting all data!) is ./manage.py reset node. Note If you use MySQL as your database engine, we recommend its internal storage engine InnoDB over the standard MyISAM. You can set this in your settings.py by adding ‘OPTIONS’: {“init_command”: “SET storage_engine=INNODB”} to your database setup. We also recommend to use UTF8 as default in your MySQL configuration or create your database with CREATE DATABASE <dbname> CHARACTER SET utf8; How you fill your database with information from ascii-files is explained in the next chapter: How to get your data into the database. You can do this now and return here later, or continue with the steps below first. Before we go on to the remaining two ingredients, the query function and the dictionaries, we need to have an understanding on how they play together in the XML generator. As you remember from The XSAMS schema, the goal is to run queries on your models and pass on the output to the generator so that it can looped over them to fill the hierarchical XSAMS structure. In order to make this work, we need to name the variables that you pass into the generator (as explained below) and the loop variables that you use in the Returnables. For example, continuing on the model above: Assume you have made a selection of your Transition model; you pass this on under the name RadTrans; the generator loops over it, calling each Transition insite its loop RadTran (note the singular!). RadTran is now a single instance of your Transition model and has the wavelength as RadTran.wavelength since we called the field this way above. The entry in the RETURNABLES would therefore look like ‘RadTranWavelenth’:’RadTran.wavelength’ - where the first part is the keyword from the VAMDC dictionary (which the generator knows where in the schema it should end up) and the second part tells it how to get the value from the query results that it got from your query function. Do not fret if this sounded complicated, it will become clear in the examples below. Just read the previous paragraph again after that. Here is a table that lists the variables names that you can pass into the generator and the loop variables that you use in the Returnables. The one is simply the plural of the other. The third and fourth columns are for an inner loop. So for example the generator loops over all Atoms, calling each atom insteance Atom. To extract all states being a part of this particualar Atom, the generator will assume that there is an iterable States defined on each Atom over which it will iterate. So it will loop over Atom.States, calling each of state AtomState in the inner loop, like this: for Atom in Atoms: [...] for AtomState in Atom.States: [...] It is up to you to make sure the Atom.States is defined if you want to output state information. This is covered in the next section. Now that we have a working database and data model and know in principle how the generator works, we simply need to tell the framework how to run a query and pass the output to the generator. This is done in a single function called setupResults() which must be written in the file node/queryfunc.py in your node directory. It works like this: In a concrete example of an atomic transition database, it looks like this: from django.db.models import Q from vamdctap.sqlparse import * from dictionaries import * from models import * LIMIT = 10000 def setupResults(sql): q = sql2Q(sql) transs = Transition.objects.filter(q).order_by('wavelength') ntranss = transs.count() if ntranss > LIMIT: percentage = '%.1f'%(float(LIMIT)/ntranss *100) limitwave = transs[LIMIT].wavelength transs = Transition.objects.filter(q,Q(vacwave__lt=limitwave)) else: percentage=None spids = set( transs.values_list('species_id',flat=True) ) species = Species.objects.filter(id__in=spids) nspecies = species.count() nstates = 0 for specie in species: subtranss = transs.filter(species=specie) up=subtranss.values_list('upper_state_id',flat=True) lo=subtranss.values_list('lower_state_id',flat=True) sids = set(up+lo) specie.States = State.objects.filter(id__in = sids) nstates += len(sids) headerinfo={'TRUNCATED':percentage, 'COUNT-ATOMS':nspecies, 'COUNT-STATES':nstates, 'COUNT-RADIATIVE':ntranss 'APPROX-SIZE':ntranss*0.001 } return {'RadTrans':transs, 'Atoms':species, 'HeaderInfo':headerinfo } Explanations on what happens here: Note As you might have noticed, all restrictions are passed to the Transitions model in the above example. This does not mean that we cannot put constraints on e.g. the species here. We simply use the models ForeignKey in that case in the RESTRICTABLES. An entry there could e.g. be ‘AtomIonCharge’:’species__ion’ which will use the ion field of the species model. Depending on your database layout, it might not be possible to pass all restrictions to a single model. Then you need to write a more advanced query than the shortcuts in Lines 7-8. Note We are well aware that adapting the above example to your data is a non-trivial task unless you know Python and Django reasonably well. There is a more complete example in ExampleNode/node/queryfunc.py and you can also have a look at the other nodes’ queryfunc.py which are included in the NodeSoftware. And, of course, we are willing to assist you in this step, so feel free to contact us about this. More comprehensive information on how to run queries within Django can be found at. As the last important step before the new node works, we need to define how the data relates to the VAMDC dictionary. If you have not done so yet, please read The VAMDC dictionary before continuing. What needs to be put into the file node/dictionaries.py is the definition of two variables that map the individual fields of the data model to the names from the dictionary, like this: RESTRICTABLES = {\ 'AtomSymbol':'species__name', 'AtomIonCharge':'species__ion', 'RadTransWavelength':'wavelength', } RETURNABLES={\ 'NodeID':'YourNodeName', # constant strings work 'AtomIoncharge':'Atom.ion', 'AtomSymbol':'Atom.name', 'AtomStateEnergy':'AtomState.energy', 'RadTransWavelength':'RadTran.wavelength', } Note Note for example the use of the names Atom and AtomState on the right-hand side of the dictionary definition. These are examples of the “loop variables” mentioned in the table above and act as shortcuts to the nested data you are storing. As we have learned from writing the query function above, we can use the RESTRICTABLES to match the VAMDC dictionary names to places in our data model. The key in each key-value-pair is a name from the VAMDC dictionary and the values are the field names of the model class that you want to query primarily (Transition, in the example above, line 10). The RESTRICTABLES example give fits our query function from above, so we know that the “main” model is the Transitions. Now if a query like “AtomIonCharge > 1” comes along, this can be translated into Transition.objects.filter(species__ion__gt=1) without further ado, which is exactly what where2q() does. Note that we here used a ForeignKey to the Species model; the values in the RESTRICTABLES need to be written from the perspective of the queried model. Note Even if you chose to not use the RESTRICTABLES in your setupResults() and treat the incoming queries manually, you are still encouraged to fill the keys (with the values being empty), because they are automatically provided to the VAMDC registry so that external services can figure out which names make sense to query at this node. Equivalent to how the RESTRICTABLES take care of translating from global names to your custom data model when the query comes in, the RETURNABLES do the opposite on the way back, i.e. when the data reply is sent by the generator, as we have already seen above. Again the keys of the key-value-pairs are the global names from the VAMDC dictionary. The values now are their corresponding places in the QuerySets that are constructed in setupResults() above. This means that the XML generator will loop over the QuerySet, getting each element, and try to evaluate the expression that you put in the RETURNABLES. Continuing our example from above, where the State model has a field called energy, so each object in the QuerySet will have that value accessible at AtomState.energy. Note that the first part before the dot is not the name of your model, but the loop variable inside the generator as it is listed in the second (or forth, in the case of an inner loop) column of the table above. There is only one keyword that you must fill, all the others depend on your data. The obligatory one is NodeID which you should set to a short string that is unique to your node. It will be used in the internal reference keys of an XSAMS document. By including the NodeID, we make these keys globally unique within VAMDC which will facilitate the merging of data that come from different nodes. is where you can browse all the available keywords. Note Again, at least the keys of the RETURNABLES should be filled (even if you use your own generator for the XML output) because this allows the registry to know what kind of data your node holds before querying it. Now you should have everything in place to run your node. If you still need to fill your database with the import tool, now is the time to do so according to How to get your data into the database. Django comes with a built-in server for testing. You can start it with: $ ./manage.py runserver This will use port 8000 at your local machine which means that you should be able to browse to and hopefully see a positive status message. You should also be able to run queries by accessing URLS like: ALL WHERE AtomIonCharge > 1 replacing the last part by whatever restriction makes sense for your data set. Note The URL has to be URL-encoded when testing from a script or similar. Web browsers usually do that for you. To also see the statistics headers, you can use wget -S -O output.xml “<URL>”. You should run several different test queries to your node, using all the Restrictables that you defined. Make sure that the output values matches your expectations. There is a very convenient software called TAPvalidator (see) which can be used to query a node, browse the output and check that it is valid with respect to the xsams standard. Once your node does what it should do with the test server, you can start thinking about deploying it.
http://readthedocs.org/docs/vamdc-nodesoftware/en/release/newnode.html
crawl-003
refinedweb
3,083
62.38
Credit Modeling with Dask complex task graphs in the real world This post explores a real-world use case calculating complex credit models in Python using Dask. It is an example of a complex parallel system that is well outside of the traditional “big data” workloads. This is a guest post Hi All, This is a guest post from Rich Postelnik,. Thanks Rich! This is cross-posted at Anaconda’s Developer Blog. P.S. If others have similar solutions and would like to share them I’d love to host those on this blog as well. The Problem: def final_equation(inputs): out1 = equation1(inputs) out2_1, out2_2, out2_3 = equation2(inputs, out1) out3_1, out3_2 = equation3(out2_3, out1) ... out_final = equation_n(inputs, out,...) return out_final This boils down to a dependency and ordering problem known as task scheduling. DAGs to the rescue A directed acyclic graph (DAG) is commonly used to solve task scheduling problems. Dask is a library for delayed task computation that makes use of directed graphs at its core. dask.delayed is a simple decorator that turns a Python function into a graph vertex. If I pass the output from one delayed function as a parameter to another delayed function, Dask creates a directed edge between them. Let’s look at an example: def add(x, y): return x + y >>> add(2, 2) 4 So here we have a function to add two numbers together. Let’s see what happens when we wrap it with dask.delayed: >>> add = dask.delayed(add) >>> left = add(1, 1) >>> left Delayed('add-f6204fac-b067-40aa-9d6a-639fc719c3ce') add now returns a Delayed object. We can pass this as an argument back into our dask.delayed function to start building out a chain of computation. >>> right = add(1, 1) >>> four = add(left, right) >>> four.compute() 4 >>> four.visualize() Below we can see how the DAG starts to come together. Mock credit example Let’s assume I’m a mortgage bank and have 10 people applying for a mortgage. I want to estimate the group’s average likelihood to default based on years of credit history and income. hist_yrs = range(10) incomes = range(10) Let’s also assume that default is a function of the incremented years history and half the years experience. While this could be written like: def default(hist, income): return (hist + 1) ** 2 + (income / 2) I know in the future that I will need the incremented history for another calculation and want to be able to reuse the code as well as avoid doing the computation twice. Instead, I can break those functions out: from dask import delayed @delayed def increment(x): return x + 1 @delayed def halve(y): return y / 2 @delayed def default(hist, income): return hist**2 + income Note how I wrapped the functions with delayed. Now instead of returning a number these functions will return a Delayed object. Even better is that these functions can also take Delayed objects as inputs. It is this passing of Delayed objects as inputs to other delayed functions that allows Dask to construct the task graph. I can now call these functions on my data in the style of normal Python code: inc_hist = [increment(n) for n in hist_yrs] halved_income = [halve(n) for n in income] estimated_default = [default(hist, income) for hist, income in zip(inc_hist, halved_income)] If you look at these variables, you will see that nothing has actually been calculated yet. They are all lists of Delayed objects. Now, to get the average, I could just take the sum of estimated_default but I want this to scale (and make a more interesting graph) so let’s do a merge-style reduction. @delayed def agg(x, y): return x + y def merge(seq): if len(seq) < 2: return seq middle = len(seq)//2 left = merge(seq[:middle]) right = merge(seq[middle:]) if not right: return left return [agg(left[0], right[0])] default_sum = merge(estimated_defaults) At this point default_sum is a list of length 1 and that first element is the sum of estimated default for all applicants. To get the average, we divide by the number of applicants and call compute: avg_default = default_sum[0] / 10 avg_default.compute() # 40.75 To see the computation graph that Dask will use, we call visualize: avg_default.visualize() And that is how Dask can be used to construct a complex system of equations with reusable intermediary calculations. How we used Dask in practice For our credit modeling problem, we used Dask to make a custom data structure to represent the individual equations. Using the default example above, this looked something like the following: class Default(Equation): inputs = ['inc_hist', 'halved_income'] outputs = ['defaults'] @delayed def equation(self, inc_hist, halved_income, **kwargs): return inc_hist**2 + halved_income This allows us to write each equation as its own isolated function and mark its inputs and outputs. With this set of equation objects, we can determine the order of computation (with a topological sort) and let Dask handle the graph generation and computation. This eliminates the onerous task of manually passing around the arguments in the code base. Below is an example task graph for one particular model that the bank actually does. This graph was a bit too large to render with the normal my_task.visualize() method, so instead we rendered it with Gephi. The output of the model is about 100 times the size of the input so we do some aggregation at the end via tree reduction. This accounts for the more structured bottom half of the graph. The large green node at the bottom is our final output. Final Thoughts diagnostics such as time spent running each task and resources used. Also, you can easily distribute your computation with dask distributed dask dataframe. Full Example from dask import delayed @delayed def increment(x): return x + 1 @delayed def halve(y): return y / 2 @delayed def default(hist, income): return hist**2 + income @delayed def agg(x, y): return x + y def merge(seq): if len(seq) < 2: return seq middle = len(seq)//2 left = merge(seq[:middle]) right = merge(seq[middle:]) if not right: return left return [agg(left[0], right[0])] hist_yrs = range(10) incomes = range(10) inc_hist = [increment(n) for n in hist_yrs] halved_income = [halve(n) for n in incomes] estimated_defaults = [default(hist, income) for hist, income in zip(inc_hist, halved_income)] default_sum = merge(estimated_defaults) avg_default = default_sum[0] / 10 avg_default.compute() avg_default.visualize() # requires graphviz and python-graphviz to be installed Acknowledgements Special thanks to Matt Rocklin, Michael Grant, Gus Cavanagh, and Rory Merritt for their feedback when writing this article. blog comments powered by Disqus
http://matthewrocklin.com/blog/work/2018/02/09/credit-models-with-dask
CC-MAIN-2018-09
refinedweb
1,098
51.48
> Setup: somewhere there should be storage of dependencies. In my script, > .java and .class files lived in the same directory (no -d option), and I > added .dep files for each source as well in the same directory. Each > .dep file was a text file with a list of dependencies, one per line, > given as class names (outer classes only, no inner classes listed); it > represents the dependencies in the source tree of the given class, not > to include classes present in JARs and so on in the (non-source) > classpath, nor including the class itself. Timestamp of the .dep file is > significant. For efficiency, it would be possible to store a single deps > database in some format, listing timestamp, dependent class name, and > all source dependencies of that class. Or .dep files could be placed in > a special separated directory. It is neccessary to decide here do we want intermediate files generated by ant? If yes - dependancy tracking will work faster, but we need to specify where to store this files cause this files could add some garbage to distributive if will strore them in dest directory or add this garbage to the source diectory. If no - dependancy tracking will work slower, but we will not care about this files. As for me, I like first, cause what the faster solution is beter for me. > Algorithm: > > 1. Prepare list of classes to compile. Scan the source tree (given > includes/excludes, etc.) for source files. A source file is out of date > if any of the following are true: > > 1a. It has no .class file. > > 1b. Its .class file is older than the source file. > > 1c. It has no .dep file. > > 1d. Its .dep file is older than the source file. > > 1e. One or more of the source files listed in its .dep file is missing. > > 1f. One or more of the source files listed in its .dep file is newer > than the considered source file. > > 2. Run the selected Java compiler on the source files thus gleaned. It > should not matter how that compiler does dependency analysis, or even if > it does any; all required files ought to have been explicitly listed > anyway. > > 3. Again using the same list of source files, find the freshly-compiled > .class files and parse them. A full bytecode library should not be > necessary, only ability to parse the constant pool. All classes > referenced at compile time should be listed as class constants in this > pool. (My original script simply grepped the binary .class file for > likely references using a conservative approximation, but doing it right > should not be that hard.) Remember to search all inner-class files. > (JDK-1.0-style package-private outer classes might be a problem here--it > may be necessary to check the "source" attribute in the class file to > handle these.) There are some tricky compiler behaviours here. Sometimes you cannot receive all dependancy info from constant pool. Do not forget about optimizer! I analyzed javac generated bytecode (1.2.2) and compared it to jikes. Jikes fro example remove from constant pool unused classes, but javac stores it there. That's why you cannot rely on jikes generated .class file and you can on javac generated. Exist a lot of complex examples using interfaces, inheritance, inner classes and static variables where very difficult for you to track dependancies (indirect dependencies). Here is simple one: public class A extends B { public int a = 1; public A() { print(); } public static void main(String args[]) { new A(); } } public class B extends C { public int b = 2; void print() { System.out.println(i); } } public class C implements I { public int c = 3; } public interface I { static int i = 100; } "A" and "B" constant pools don't contain anything about I. In optimized code dependencies can be resolved only by java class parsing (class file doesn't contain full info). [...] In general I agree with you and your algorithm looks pretty good. One thing we need too decide: do we need .dep files or no? Vitaly
http://mail-archives.apache.org/mod_mbox/ant-dev/200007.mbox/%3C013b01bff320$54852c20$40b7729e@ple.trw.com%3E
CC-MAIN-2016-22
refinedweb
673
75.1
Getopt::GUI::Long use Getopt::GUI::Long; # pass useful config options to Configure Getopt::GUI::Long::Configure(qw(display_help no_ignore_case capture_output)); GetOptions(\%opts, ["GUI:separator", "Important Flags:"], ["f|some-flag=s", "A flag based on a string"], ["o|other-flag", "A boloean"], ); # or use references instead of a hash (less tested, however): GetOptions(["some-flag=s", "perform some flag based on a value"] => \$flag, ["other-flag=s", "perform some flag based on a value"] => \$other); # displays auto-help given the input above: % opttest -h Usage: opttest [OPTIONS] Other Arguments OPTIONS: Important Flags: -f STRING A flag based on a string -o A boloean Help Options: -h Display help options -- short flags preferred --help Display help options -- long flags preferred --help-full Display all help options -- short and long # or long help: % opttest --help Usage: opttest [OPTIONS] Other Arguments OPTIONS: Important Flags: --some-flag=STRING A flag based on a string --other-flag A boloean Help Options: -h Display help options -- short flags preferred --help Display help options -- long flags preferred --help-full Display all help options -- short and long # or a GUI screen: (see ). This also can turn normal command line programs into web CGI scripts as well (automatically). If the Getopt::GUI::Long program is installed as a CGI script then it will automatically prompt the user for the same variables. The Getopt::GUI::Long module can work identically to the Getopt::Long module but really benefits from some slightly different usage conventions described below. Option strings passed should be formatted in one of the following ways: Empty strings are ignored by the non-GUI version of the command, but are treated as vertical separators between questions when displaying the GUI screen. EG: "some-flag|optional-flag=s" This is the standard method by which Getopt::Long does things and is merely treated the same way here. In this case, the text presented to the user screen will be the first name in the list ("some-flag") in the above option. The type of wdget displayed with the text will depend on the optional =s/i/whatever flag and will be either a checkbox, entry box, ... EG: ["some-flag|optional-flag=s", 'Prompt text', OTHER], The values passed in this array are as follows: Same as always, and as above. The help text that should be shown to the user in the graphical interface. In the example above rather than "some-flag" being shown, "Prompt text" will be shown next to the widget instead. If the prompt text is equal to "!GUI" then this option will not be displayed (automatically at least) within the GUI. Beyond the name and description, key value pairs can indicate more about how the option should be handled. Forces a screen option to be filled out by the user. These allows you to build custom QWizard widgets to meet a particular question need. It's highly useful for doing menus and single choice fields that normally command line options don't handle well. For example consider a numeric priority level between 0 and 10. The following question definition will give them a menu rather than a fill in the blank field: ['priority=i','Priority Level', question => { type => 'menu', values => [1..10] }] Note you can specify multiple question widgets if needed as well, though this will probably be rare in usage. Any of the following items can be passed as well, which will be added to the QWizard question structure. See the QWizard documantion on "QUESTION DEFINITIONS" for details on the usage of these. (Warning: Replaces the text already extracted from the prompt text described above). (Warning: Replaces the option name extracted from the position 0 standard flag specification string above. Do not use this unless you really know what you're doing.) [others TBD] Flags that start with GUI: are not passed to the normal Getopt::Long routines and are instead for internal GUI digestion only. If the GUI screen is going to be displayed (remember: only if the user didn't specify any options), these extra options control how the GUI behaves. Some of these options requires some knowledge of the QWizard programming system. Knowledge of QWizard should only be required if you want to make use of those particular extra features. EG: ['GUI:guionly', { type => 'checkbox', name => 'myguiflag'}] Specifies a valid QWizard question(s) to only be shown when the gui is displayed, and the specification is ignored during normal command line usage. EG: ['GUI:separator', 'Task specific options:'] Inserts a label above a set of options to identify them as a group. EG: ['GUI:screen', 'Next Screen Title', ...] Specifies that a break in the option requests should occur and the remaining options should appear on another screen(s). This allows applications with a lot of options to reduce the complexity it offers users and offers a more "wizard" like approach to helping them decide what they're trying to do. You can also make this next screen definition conditional by defining an earlier option that may be, say, a boolean flag called "feature_flag". Using this you can then only go into the next screen if the "feature_flag" was set by doing the following: ['feature-flag', 'turn on a special feature needing more options'], ['GUI:screen', 'Next Screen Title', doif => 'feature-flag'] ['feature-arg1', 'extra argument #1 for special feature'], ... Also, if you need to do more complex calculations use the qwparam() function of the passed in QWizard object in a subroutine reference instead: ['feature1','Turn on feature #1"], ['feature2','Turn on feature #2"], ['GUI:screen', 'Next Screen Title', doif => sub { return ($_[1]->qwparam('feature1') && $_[1]->qwparam('feature2')); }] EG: ['GUI:otherargs', 'Files to process:'] Normally the GUI screen shows a "Other Arguments:" option at the bottom of the main GUI screen to allow users to entry additional flags (needed for file names, etc, and other non-option arguments to be passed). However, since it doesn't know what these arguments should be it can only provide a generic "Other Arguments:" description. This setting lets you change that text to something specific to what your application experts, such as "Files:" or "HTML Files:" or something that helps the user understand what is expected of them. If you want to self-handle the argument prompting using other QWizard constructs, then use the nootherargs token described below instead. EG: ['GUI:nootherargs', 1] Normally the GUI screen shows a "Other Arguments:", or programmer described text as described above, option at the bottom of the main GUI screen. If you're going to handle the additional arguments yourself in some way (using either some GUI:guionly or (GUI:otherprimaries and GUI:submodules) flags), then you should specify this so the other arguments field is not shown. You're expected, in your self-handling code, to set the __otherargs QWizard parameter to the final arguments that should be passed on. EG: ['GUI:nosavebutton', 1] Normally the GUI screen offers a "save" menu that lets users save their current screen settings for future calls. Using this setting turns off this behavior so the button isn't shown. EG: ['GUI:otherprimaries', primaryname => { title => '...', questions => [...] }] Defines other primaries to be added to the QWizard primary set. EG: ['GUI:submodules', 'primaryname'] Defines a list of other primaries that should be called after the initial one. EG: ['GUI:post_answers', sub { do_something(); }] Defines an option for QWizard post_answers subroutines to run. EG: ['GUI:actions', sub { do_something(); }] Defines an option for QWizard actions subroutines to run. EG: ['GUI:hook_finished', sub { do_something(); }] Defines subroutine(s) to be called after the GUI has completely finished. EG: ['GUI:run_button', 'My Run Button'] Defines the text to use for the final "Run" button (which normally just says "Run"). If display_help is defined, and the above token is specified Getopt::GUI::Long takes over the output for --version output as well. EG: ['GUI:VERSION','0.9'] Produces the --version help option: Help Options: -h Display help options -- short flags preferred --help Display help options -- long flags preferred --help-full Display all help options -- short and long --version Display the version number And also auto-handles the --version switch: % PROGRAM --version Version: 0.9 If you call Getopt::GUI::Long's Configure routine, it will accept a number of configure tokens and will pass the remaining ones to the Getopt::Long Configure routine. The tokens that it recognizes itself are described below: The Getopt::GUI::Long package will auto-display help messages based on the text included in the GetOptions call. No more writing those silly usage() functions! Note that this differs from the Getopt::Long's implementation of the auto_help token in that the information is pulled from the extended GetOptions called instead of the pod documentation. The display_help token will automatically add the following options to the options the application will accept, and will catch and process them as well. Command line help preferring short options if present in the help specification. Command line help preferring long options if present in the help specification. Shows all available option names for a given option If the default GUI is not showing up because no_gui has been specified, a sure can still call the application with only the --gui flag to make it appear. If the no_gui option hasn't been set and the user doesn't want to see the GUI then they can use the --no-gui flag as the only argument to ensure it doesn't appear. This tells the Getopt::GUI::Long module that it should caputure the resulting STDOUT and STDERR results from the script and display the results in a window once the script has finished. This option defaults to not presenting a GUI form for the user to fill out unless they specify --gui as the first and only argument on the command line. By default the GUI will always pop up if zero-arguments have been specified (or the help info will be displayed if no_gui is set). This options specifies that zero arguments is a normal usage case. Thus the only way to force the GUI or help to appear will be the command line --gui flag. The Getopt::GUI::Long qwizard object is stored at $Getopt::GUI::Long::GUI_qw, which is usable for other GUI screens you may need to create after the options screens have been processed. You can also use it during the script to optionally display a progress meter by making use of the QWizard::set_progress function. However, you should test to see if the GUI screen mode was actually used before operating with the object though. As an example: $Getopt::GUI::Long::GUI_qw->set_progress(3/5) if ($Getopt::GUI::Long::GUI_qw); If programs desire to not require this module, the following code snippit can be used instead which will not fail even if this module is not available. To be used this way, the LocalGetOptions and LocalOptionsMap functions should be copied to your perl script. LocalGetOptions(\%opts, ["h|help", "Show help for command line options"], ["some-flag=s", "perform some flag based on a value"]); sub LocalGetOptions { if (eval {require Getopt::GUI::Long;}) { import Getopt::GUI::Long; # optional configure call Getopt::GUI::Long::Configure(qw(display_help no_ignore_case capture_output)); return GetOptions(@_); } require Getopt::Long; import Getopt::Long; # optional configure call Getopt::Long::Configure(qw(auto_help no_ignore_case)); GetOptions(LocalOptionsMap(@_)); } sub LocalOptionsMap { my ($st, $cb, @opts) = ((ref($_[0]) eq 'HASH') ? (1, 1, $_[0]) : (0, 2)); for (my $i = $st; $i <= $#_; $i += $cb) { if ($_[$i]) { next if (ref($_[$i]) eq 'ARRAY' && $_[$i][0] =~ /^GUI:/); push @opts, ((ref($_[$i]) eq 'ARRAY') ? $_[$i][0] : $_[$i]); push @opts, $_[$i+1] if ($cb == 2); } } return @opts; } If a Getopt::GUI::Long script is installed as a CGI script, then the Getopt::GUI::Long system will automatically create a web front end for the perl script. It will present the user with all the normal arguments that it would normally to a Gtk2 or other windowing system. It will not present the box for generic additional arguments since this is not safe to do. If you trust your users (ie, you have an authentication system in place) then you can set the allowcgiargs GUI variable to make this box appear. Example invocation (not generally recommended): ['GUI:allowcgiargs',1] It also allows you to not present certain options to web users that you will to command line users (some options may not be safe for CGI use). You can do this by setting the nocgi variable in option definitions you wish to disallow via CGI. E.G., if you had an option to specify a location where to load configuration a file from, this would likely be unsafe to publish in a CGI script. So remove it: ["c|config-file","Load a specific configuration file", nocgi => 1] See the getopttest program in the examples directory for an exmaple script that uses a lot of these features. Wes Hardaker, hardaker@users.sourceforge.net Getopt::GUI::Long is free software; you can redistribute it and/or modify it under the same terms as Perl itself. perl(1) modules: QWizard This module was originally named Getopt::Long::GUI but the Getopt::Long author wanted to reserve the Getopt::Long namespace entirely for himself and thus it's been recently renamed to Getopt::GUI::Long instead. The class tree isn't as clean this way, as this module still inherits from Getopt::Long but it everything still works of course.
http://search.cpan.org/~hardaker/Getopt-GUI-Long-0.92/Long.pm
CC-MAIN-2016-44
refinedweb
2,243
56.08
I want to develop an application that will send MMS to different user?But the problem is how to detect if their phone is capable of receiving MMS or not?I want to send an image e.g. picture of an events that will be send to users in a youth organization. I am looking forward to anyone who can help me solve this problem. By the way, i am using php to develop this system.As one of the feature of my project, SMS-Based Registration system for Christian Youth Fellowship, a church youth organization. Normally, in the chain of transmission to the end user, an MMS will arrive at the recipient's carrier service MMSC server which stores the data before outgoing transmission, but will also evaluate the end users capability to receive this message, and will reject the message at this point. If you use a MMS API service, you should get a response back that informs you of this event in which case you can remove the number from your distribution list. Ok.This is my sample code for i dont know where to place MMS image or how to send MMS. <?php // load the nusoap libraries. These are slower than those built in PHP5 but don't require you to recompile PHP include_once("nusoap/lib/nusoap.php"); // create the client and define the URL endpoint $client = new nusoap_client(''); // set the character encoding, utf-8 is the standard. $client->soap_defencoding = 'UTF-8'; // check if we generated an error in creating the client / assigning the endpoint $err = $client->getError(); if ($err) {// Display the error $error_message = 'Constructor error: ' . $err; } // Call the SOAP method, note the definition of the xmlnamespace as the third parameter in the call and how the posted message is added to the message string $result = $client->call('sendMMS, array( 'uName' => 'username', 'uPin' => 'password', 'MSISDN' => '0917xxxxxxx', 'messageString' => 'Test message', 'Display' => '0', 'udh' => '', 'mwi' => '', 'coding' => '0' ), ""); // Check for a fault if ($client->fault) { $error_message = "Fault Generated: \ "; } else {// Check for errors $err = $client->getError(); if ($err) {// Display the error $error_message = "An unknown error was generated: \ } else {// Display the result if ($result == "201") { $error_message = "Message was successfully sent!"; } else { $error_message = "Server responded with a $result message"; } } }
https://www.sitepoint.com/community/t/mms-application/31978
CC-MAIN-2017-34
refinedweb
367
57.91
Quake and DarkPlaces rcon client.Suppor such games like Xonotic, Nexuiz and other Darkplaces and Quakes rcon [1] protocol and client implementation. Works with such games like Xonotic, Nexuiz, Warsow and other games with Quakes rcon. Features - Support old Quake rcon and new Darkplaces secure rcon protocols. - Support both IPv4 and IPv6 connections. - Bundled console client. - Well tested, test coverage near 100%. - Works with python 2.6+, 3.2+. Installation - execute pip install xrcon - or run pip install -e git+ to install development version from github Usage Using as library: from xrcon.client import XRcon rcon = XRcon('server', 26000, 'password') rcon.connect() # create socket try: data = rcon.execute('status') # on python3 data would be bytes type finally: rcon.close() For more info read XRcon docstrings. Using console client: $ xrcon -s yourserver:26001 -p password command If you want use IPv6 address it should be put inside square brackets. For example: $ xrcon -s [1080:0:0:0:8:800:200C:417A]:26002 -p password status $ xrcon -s [1080:0:0:0:8:800:200C:417B] -p password status If port is omitted then by default would be used port 26000. You may also change type of rcon, by default would be used secure time based rcon protocol. This protocol works only in Darkplaces based games. For instance: $ xrcon -s warsowserver:44400 -p password -t 0 status 0 means old (unsecure) quakes rcon, 1 means secure time base rcon, and 2 is secure challenge based rcon protocol. You may also create ini configuration file in your home directory .xrcon.ini. For example: [DEFAULT] server = someserver:26000 password = secret type = 1 timeout = 0.9 [other] server = someserver:26001 [another] server = otherserver password = otherpassword type = 0 timeout = 1.2 Then if you wants execute command on this servers just do: $ xrcon status # for DEFAULT server $ xrcon -n other status # for other server $ xrcon -n another status # for another server License LGPL 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/xrcon/
CC-MAIN-2017-47
refinedweb
338
66.44
Ooops, it seems to me, that I have to rework the 'documentation' to be more generic... > The instructions require that certain DLLs are present. If they are > DLLs which are not normally shipped with Win95/98 then why aren't they > just included in the installation package? : As mentioned in the VSoup95/98/NT part of my homepage, the RSXNT-DLLs are not required for this beta of VSoup95/98/NT. That section also contains a link to the RSXNT site (although obsolete). > What is this yarn IO that was mentioned? Do I need to use it in > Win98? If so, what does it do? YarnIO is intended to run under OS/2 only. So don't care about it. > Ok, I'll stop here because I don't have enough information to even ask > intelligent questions. I hope someone can pare the information down > to just what I need to know. Thanks. I'll try to give you a simple script for VSoups IO (hopefully you'll catch the idea): - put vsoup.exe into your path (e.g. c:\my-binaries, or c:\windows or whatsoever) - create the following subdir structure: c:\vsoup c:\vsoup\in-mail c:\vsoup\in-news c:\vsoup\out - in c:\vsoup\in-news create a file named 'newsrc' which contains the news groups you'd like to receive; format as follows: de.rec.fahrrad: alt.test! comp.os.os2.announce: and so on... Note, that fetching of alt.test is disabled due to the trailing '!', the ':' enable group reception. - for mail reception use the following script: c: cd \vsoup\in-mail vsoup -n pop3://username:password@my.pop3.server rem rem the next (but one) line for message import into yarn rem import -u Change 'pop3://...' to fulfill your own needs - for news reception use the following script: c: cd \vsoup\in-news vsoup -m -h c:\vsoup\in-news nntp://username:password@my.news.server rem rem the next (but one) line for message import into yarn rem import -u Change 'nntp://...' to fulfill your needs. Note that most news server do not require 'username:password', thus 'nntp://my.news.server' will be enough. - for news & mail transmission use the following script (assuming Yarn puts the replies into c:\vsoup\out\reply.zip and unzip.exe exists somewhere in the path): c: cd \vsoup\out unzip -o reply.zip vsoup -s smtp://my.smtp.gateway nntp://username:password@my.news.server rem rem the next (but one) line for message import into yarn rem import -u The above import is required for status messages generated by VSoup. 'smtp://...' has to be adopted according to your needs (smtp:// does not know anything about usernames and passwords), 'nntp://...' has to be modified as in the section above. If the above scripts do not work immediately don't commit suicide (or something more harmful), try to execute the scripts in single-step-mode (i.e. tap them in manually and check where they fail). If they are working, I'd be grateful to get some feedback so that I can adopt documentation accordingly! Have fun & happy hacking Hardy PS: for more advanced options refer to the online documentation. I'll be glad to receive any feedback (and of course additions, enhancements etc) according the documentation -- VSoup Homepage:
http://www.vex.net/yarn/list/199901/0052.html
crawl-001
refinedweb
552
67.35
Asked by: Svcutil.exe issues: generates twice the same elements or generates codes that do not compile Question Hello, I ran into trouble with svcutil tool. I'm starting from a hand-written WSDL file and want to generate service code out of it. The WSDL file contains references to external schemas (that are given as parameter to svcutil.exe as we are generating from local files). The first problem occurs when I use the /ser:Auto switch (no /ser switch at all). Some of the classes generated (as partial) are defined multiple times with same fields. The generated code resulting contains errors. The second issue occurs when I use the /ser:XmlSerializer switch to force svcutil.exe to use the same serializer for all the elements found. Again, the generated code contains errors. I found another thread reporting similar error: The hand-written WSDL files was working fine until I added soap:fault elements in it. After some test, I found what was the pattern. It seems that when an element is used both in soap:header/soap:body AND in soap:fault in a message, svcutil.exe don't understand that these are the same XML elements. This, however, can be forced by using the /ser:XmlSerializer switch. However, as stated before, when forcing the XmlSerializer, the generated code contains errors at the annotation level of the operation that can launch the fault. The error in the code is that the typeof paramter of the FaultContractAttribute annotation refers to the XML file namespace, not the .NET replaced one (specified using the /n switch). On top of this, the FaultMessage don't exist in the generated code, so manually modifying the namespace in the generated code is not sufficent (event if that would not be good, as modification of generated code is not good practice I guess...). Some background on the project: The aim is to build interoperable code, hence the hand written WSDL file. Services will be implemented both with WCF and Axis2. This is why we would like to solve this not by rearranging the WSDL file, as it must be BP 1.1 compliant and as clean as possilble. PS: I originally posted this in another part of the forum: I don't know why but in this part of the forum, the code looks ugly and the editor complains of my original post beeing too long, so I skiped the code parts... All replies From the post in the other forum, it looks like your wsdl have some problems. // CODEGEN: Generating message contract since the operation GetQuote is neither RPC nor document wrapped. 1) Put your headers in a separate message part. 2) Rename the "body" message part to "parameters". 3) Remove references to the message part in the soap:body binding. (Each of your message should have only one part. Hence, the soap:body binding will use that one.) An First, thanks for helping! Doing this generates a code that is a bit different, but the fault annotation is still wrong. This is what I end up with:Code Snippet // CODEGEN: Generating message contract since the wrapper name (Name) of message GetQuoteRequest does not match the default value (GetQuote) [System.ServiceModel.OperationContractAttribute(Action="urn:GetQuote", ReplyAction="*")] [System.ServiceModel.FaultContractAttribute(typeof(), Action="urn:GetQuote", Name="FaultMessage")] [System.ServiceModel.XmlSerializerFormatAttribute()] WsdlToCode.Generated.GetQuoteResponse GetQuote(WsdlToCode.Generated.GetQuoteRequest request); The comment is different, but I can't manage to see what's wrong.
https://social.msdn.microsoft.com/Forums/vstudio/en-US/abfa7b04-8a7f-4785-bdde-3da26e9f2d30/svcutilexe-issues-generates-twice-the-same-elements-or-generates-codes-that-do-not-compile?forum=wcf
CC-MAIN-2019-39
refinedweb
576
57.16
This program should ask how many of an animal are left in the wild 5 times. Then it should use a second method to output the same information. But i cant figure this out; every time i change anything based on previous questions here i just add to the number of errors. import java.util.Scanner; class animals { public static void main(String[] args) { int[] q1 = question(); output(q1); System.exit(0); } // exit main public static int[] question() { String[] wild = { "Komodo Dragon", "Mantee", "Kakapo", "Florida Panther", "White Rhino" }; int number = 0; int[] record = {}; for (int i = 1; i <= 5; i++) { System.out.println(wild[number] + ":"); Scanner scanner = new Scanner(System.in); System.out.println("How many are left in the wild?"); int howMany = scanner.nextInt(); record = new int[] {howMany}; number++; }//end for loop return record; }// end method question public static void output(int[] q1){ System.out.println("There are " + q1[0] + " Komodo Dragons in the wild"); System.out.println("There are " + q1[1] + " Mantees in the wild"); System.out.println("There are " + q1[2] + " Kakapos in the wild"); System.out.println("There are " + q1[3] + " Florida Panthers in the wild"); System.out.println("There are " + q1[4] + " White Rhinos in the wild"); }//end method output } // end class animals There are 3 Komodo Dragons in the wild Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 at animals.output(animals.java:39) at animals.main(animals.java:13) This doesn't make sense int[number] record = {}; most like what you meant was int[] record = new int[wild.length]; and instead of for (int i = 1; i <= 5; i++) { you need for (int i = 0; i < wild.length; i++) { instead of the following which creates an array of 1 value [0] record = new int[] {howMany}; which will produce the following when you try to access [1] Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 you need record[i] = howMany; As you write each line of code in your IDE (or your editor) you should see if that compiles and if it doesn't adding more lines is unlikely to help. I suggest you try to compile and test as often as possible so you know where the source of your errors are and when you get a bug, you can step through the code in your debugger to see why the program is not doing what you expect.
https://codedump.io/share/YPFsPM25WR3r/1/why-do-my-simple-arrays-not-work
CC-MAIN-2016-50
refinedweb
395
63.59
In an effort to better protect our production data, last year we choose to setup a readonly production console. This allows developers to poke around production data without having to worry that they might accidentally change something they shouldn't. In this post, I will break down exactly what we did in order to accomplish this for our Ruby on Rails application. Before I dive into the specifics for each database, I want to first mention that we use a completely separate server for console access. Using a separate server allows us to tweak application settings in order to achieve readonly access. In order to deploy these changes we use Ansible. When Ansible runs a deploy it looks for the console box tag to know what settings and configs need to be deployed to that particular box. MySQL The first thing we did was setup a user with readonly access in MySQL. Then, in order to make our application readonly for MySQL, all we simply had to do was put the readonly user credentials in our database.yml file on our console server box. production: adapter: mysql2 encoding: utf8 reconnect: true pool: 16 database: "prod_db" username: "readonly" password: "you_wish" host: "127.0.0.1" strict: false Now any time someone opens up a Rails console on our console server it is automatically using the readonly credentials from the config. However, there are still times when we want to be able to allow devs to edit data via the console. In order to accomplish this, we setup a bash script which is used to open a Rails console. In this bash script we choose to use a lesser known feature that Rails offers, DATABASE_URL. If you set the DATABASE_URL variable in your environment, Rails will use it to connect to your database rather than reading from your database.yml file. This allows us to override our database configs when we need to. We set it up in our bash script like so: #!/bin/bash cd /application_path if [ "$1" = 'write' ]; then export DATABASE_URL="mysql2://write_username:write_password@host/db_name" fi RAILS_ENV=production /usr/local/bin/bundler exec rails console Now if a developer needs to edit data they can simply open up a write console using the command console write. Redis To handle setting up Redis as readonly we choose to override our Redis client to explicitly block any write commands. Since we have a Ruby on Rails application we use the redis-rb gem in order to talk to Redis. To block write commands we first collected all the commands that were write based by calling the command method on our Redis client. For reference, Rails.cache.data will simply give you your Redis client. dev> Rails.cache.data => #<Redis client v4.0.3 for redis://127.0.0.1:6379/15> The command method will return an array of all the commands your Redis instance will respond to along with some additional information about each command. dev> Rails.cache.data.command.first(3) => [["expireat", 3, ["write", "fast"], 1, 1, 1], ["setnx", 3, ["write", "denyoom", "fast"], 1, 1, 1], ["getrange", 4, ["readonly"], 1, 1, 1]] To filter out only the write commands we simply checked for the "write" value in the list of command attributes. WRITE_COMMANDS = Rails.cache.data.command.map { |a| a[0] if a[2].include?('write') }.compact.to_set Once we had a list of write commands, we overrode the process method in our gem to raise an error if any of those methods were called. def process(commands) if commands.flatten.any? { |c| WRITE_COMMANDS.include?(c.to_s) } raise NotImplementedError, "REDIS_ACCESS_MODE is set to 'readonly', disallowing writes" end # additional method logic end Those two pieces allow us to block Redis write commands. But, the question still remains, how do we block those write commands ONLY on our console box? Once again, we turned to our environment variables and our bash console script. In our console script we set our environment variables based on if the console was the default readonly or if it was a write console. #!/bin/bash cd /application_path if [ "$1" = 'write' ]; then export DATABASE_URL="mysql2://write_username:write_password@host/db_name" export REDIS_ACCESS_MODE="" else export REDIS_ACCESS_MODE="readonly" fi RAILS_ENV=production /usr/local/bin/bundler exec rails console Then, in our redis.rb initializer file in our application, we monkey patched the process method to return an error if a write command was called in readonly access mode. if ENV['REDIS_ACCESS_MODE'] == 'readonly' class Redis class Client WRITE_COMMANDS = ::Rails.cache.data.command.map { |a| a[0] if a[2].include?('write') }.compact.to_set.freeze def process(commands) if commands.flatten.any? { |c| WRITE_COMMANDS.include?(c.to_s) } raise NotImplementedError, "REDIS_ACCESS_MODE is set to 'readonly', disallowing writes" end # additional method logic end end end end BOOM! The console box was now readonly for MySQL and for Redis by default. Only one piece of the puzzle was left, Elasticsearch. Elasticsearch Elasticsearch is at the cornerstone of our application so we needed that to be readonly as well. To talk to Elasticsearch we use the elasticsearch-ruby gem. Much the same way we did Redis, we found the core method used to make external requests to Elasticsearch, perform_resquest and patched it so that it would raise an error whenever a write method was executed. Since we talk to Elasticsearch using HTTP requests, the methods we wanted to block were PUT, POST, and DELETE. module Elasticsearch module Transport class Client if ENV['ELASTICSEARCH_ACCESS_MODE'] == 'readonly' def perform_request(method, path, params={}, body=nil, headers=nil) raise 'Elasticsearch is in readonly mode.' if method.to_s.match?(/PUT|POST|DELETE/) method = @send_get_body_as if 'GET' == method && body transport.perform_request(method, path, params, body, headers) end end end end end Once again, we also choose to use an environment variable to determine whether or not we should be patching the perform_request method. We then took that environment variable and added it to our bash script. Our completed bash script looks like this: #!/bin/bash cd /application_path if [ "$1" = 'write' ]; then export DATABASE_URL="mysql2://write_username:write_password@host/db_name" export REDIS_ACCESS_MODE="" export ELASTICSEARCH_ACCESS_MODE="" else export REDIS_ACCESS_MODE="readonly" export ELASTICSEARCH_ACCESS_MODE="readonly" fi RAILS_ENV=production /usr/local/bin/bundler exec rails console This script ensures that when a dev or support person is opening a console using the console command, by default it will be readonly. When necessary, they can call console write if they need to update any data. Even though it is very easy to open a write console, the vast majority of the time people are working in readonly consoles. The readonly consoles have proven themselves many times over by saving people from making silly mistakes while browsing production data. Other Options There are many other ways to approach data safety when it comes to working with production data. This is just one approach and the one we have chosen to use at Kenna. One other very popular option is to make a replica, or clone, of your data and then allow people to run whatever queries they want against that replica or clone. The downside to this is that getting an up-to-date replica every time you need it can be time consuming depending on the size of your dataset. In addition, cloning a single database such as MySQL is pretty straightforward. However, when you are working with 3 different data stores, such as we do at Kenna, it is a lot more effort to replicate all of that data together. At Kenna, devs have the ability to clone production data, but it is only available in MySQL at the moment. Normally, a MySQL clone is only used to check high risk migrations or scripts that are going to change a lot of production data at once. Beyond that, we have found our readonly console has worked great for our use case because the majority of the time devs and support simply want to look at up-to-date production data. Hope you found this post useful! As always, please let me know if you have any questions! 🤗 Discussion This article is gold for any team running Rails and needing to limit access! I love that it is running on a separate server as well. I could see having two console servers and only allowing write access on one as well. This way, you could only provide credentials to specific people for the write server. While it can be useful to have access to real-time production data, I think this lowers the bar too much to actually 'poke around'. In most cases, I think there are 2 options. Either a database copy is OK (which can be incremental and pretty close to the production instance), but anonimysed. Or, in case your application is on fire, you actually need write access to the database. Then a read only console will not do. For our use case, a lot of times support will get an inquiry about some data and this allows them to go and dig through all the details to figure out what is happening and why the data looks the way it does. In our case, "poking around" for our support team is a daily normal Molly done it again! Just wondering - does anyone have access to a read-write Rails console? This would be a great idea for junior devs or incoming hires that aren't familiar with the DB yet but want to poke around. I'm gonna float this to my company. Yep! You can open a write console anytime you want by issuing the command console writeEven though its easy, people only open write consoles if they absolutely have to change something otherwise everyone loves the read-only consoles bc they feel "safe" in them Is the console an interactive, Ruby-specific thing? Like interactive Python? Or did you create a custom CLI to your poke at your infra? It is a Rails specific thing. You can read more about it in the rails guides if you are interested.
https://dev.to/molly_struve/how-to-setup-a-readonly-rails-console-1j1a
CC-MAIN-2020-50
refinedweb
1,664
61.67
this is what i think would be in the commented part:this is what i think would be in the commented part: public class ImagePuzzle { public void solveBlackPuzzle() { Picture input = new Picture(FileChooser.pickAFile()); Picture output = null; if (input != null) { input.show(); ///////////////////////////////////////////////////// // here i would grab the pixels, read their RGB values and change them. ////////////////////////////////////////////////////// output.show(); String directory = "/home/user/"; output.write(directory + "black-puzzle-solution.png"); } } method to decrease red get the pixels; define an integer that will work as a counter for (int= 0; i < my pixels number; i++) { p = pixels; value = p.getRed(); p.setRed(something....value*0,2) now it should show the picture, with the red value changed... } when i manage to get the syntax correct, the code is compiled and it shows the open directory dialog, i choose an image, it shows me the image and nothing more happens. otherwise i cant manage to have the correct syntax. i understand my structure asdoes it make sense to include the method i want inside public void solveBlackPuzzle? I have a class called Pixel, Picture and FileChooser.does it make sense to include the method i want inside public void solveBlackPuzzle? I have a class called Pixel, Picture and FileChooser. public Class { public void solveBlackPuzzle { } } If i try to create my Pixel object inside this part of the code, it tells me i am doing something illegal. thanks in advance and kind regards.
https://community.oracle.com/message/10779597
CC-MAIN-2015-32
refinedweb
238
64
Sometimes, you need to store more complex data in your app than just simple key/value pairs saved with a text file or Shared Preferences. Databases are ideal for storing complex data structures and are particularly suited to storing records, where each block of data stored uses the same fields, formatted in the same manner. This works like a table or an Excel spreadsheet, and, like Excel, it allows for much more dynamic manipulation and logical organization of data. It’s thanks to databases that many machine-learning and big data applications are possible. Databases also make everyday tools like Facebook possible. As a result it’s a skill in high demand. Programmers will eventually need to learn to use databases This is why programmers will eventually need to learn to use databases. That way, your data will be organized and you’ll have no difficulty retrieving passwords, user data or whatever other information you need. And this also happens to be a great way to store data on an Android device as well. To do all this, we’ll be using SQLite. Introducing SQLite SQL databases are relational databases where data is stored in tables. The Structured Query Language (SQL) is the declarative language used to query those databases so that you can add, remove and edit data. For more on SQL itself, check out this article. SQLite is an implementation of a relational database, specifically aimed for embedded scenarios. It’s ideal for the likes of an Android app. The easiest way to imagine a relational database is to think of it as a series of tables. What’s cool is SQLite doesn’t require a dedicated relational database management system (RDBMS)— it is used directly from your code, rather than via a server or external resource. Your data is saved into a file locally on your device, making it a powerful and surprisingly easy way to store persistent data on Android. SQLite is open-source, easy to use, portable, and highly cross-compatible. There’s no need to install anything additional if you want to start using SQLite in Android Studio. Android provides the classes which you can use to handle your database. Android developers can use the SQLiteOpenHelper to use SQL commands. That’s what we’ll be looking at in this post. In the next few sections, you’ll learn create a table this way and in the process, you’ll hopefully start to feel comfortable with SQLite, SQL, and databases in general. Creating your first database Start a new empty Android Studio project. Now create a new class by right-clicking the package on the left and choosing New > Java Class. I’ve called mine ‘Database’. We want to extend SQLiteOpenHelper class and so enter that as the superclass. To recap: this means we’re inheriting methods from that class, so our new class can act just like it. Right now, your code will be underlined red because you need to implement the inherited methods and add the constructor. The finished article should look like so: package com.androidauthority.sqliteexample; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class Database extends SQLiteOpenHelper { public Database(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) { super(context,name,factory, version); } @Override public void onCreate(SQLiteDatabase db) { } @Override public void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion) { } } The first thing to do is to simplify our constructor. Add these variables: public static final int DATABASE_VERSION = 1; public static final String DATABASE_NAME = "MyDatabase.db"; With that done, update your constructor like so: public Database(Context context) { super(context,DATABASE_NAME,null, DATABASE_VERSION); } Break it down and you can see that we’re calling our database ‘MyDatabase.db’. Now, whenever we make a new Database object from this class, the constructor will build that database for us. Creating tables Now we’re ready to start populating it with some data! This data takes the form of a table and hopefully you’ll see why this is useful. What kind of thing might we use a database for in the real world? Well, how about CRM – customer relationship management? This is what big companies use to keep track of their customers’ details. It’s how they know to call us with special offers in which we may be interested. It’s how your magazine subscription always knows when it’s time for a renewal – that might be a good example to use. In other words, we’re using our powers for evil. To that end, we’re going to need some more variables so that we can build our table and start populating it with data. Logically, that might look something like this: public static final String TABLE_NAME = "SUBSCRIBERS"; public static final String COLUMN_NAME = "NAME"; public static final String COLUMN_MAGAZINE_TITLE = "MAGAZINE_TITLE"; public static final String COLUMN_RENEWAL_DATE= "RENEWAL_DATE"; public static final String COLUMN_PHONE = "PHONE_NUMBER"; Now the publishers who we’re building our app for will be able to query when a certain use is due for a renewal and easily grab their phone number to give them a buzz. Imagine trying to do this without SQL; you’d be forced to create multiple text files with different names for each user, or one text file with an index so you know which line to retrieve information from different text files. Then you’d have to delete and replace each entry manually with no way to check when things got out of sync. Searching for information by name would be a nightmare. You might end up using your own made-up shorthand. It would get very messy, very fast. While it might be possible to avoid using tables with a little creativity— all this can be a little daunting at first— it is an invaluable skill to learn in the long run and will actually make your life a lot easier. It’s also pretty much required if you ever have dreams of becoming a ‘full stack’ developer or creating web apps. SQL is pretty much required if you ever have dreams of becoming a ‘full stack developer’ or creating web apps. To build this table, we need to use execSQL. This lets us talk to our database and execute any SQL command that doesn’t return data. So it’s perfect for building our table to begin with. We’re going to use this in the onCreate() method, which will be called right away when our object is created. @Override public void onCreate(SQLiteDatabase db) { db.execSQL("create table " + TABLE_NAME + " ( " + COLUMN_NAME + " VARCHAR, " + COLUMN_MAGAZINE_TITLE + " VARCHAR, " + COLUMN_RENEWAL_DATE + " VARCHAR, " + COLUMN_PHONE + " VARCHAR);"); } What’s happening here is we’re talking to our database and telling it to create a new table with a specific table name, which we’ve defined in our string. If we break the rest of that long ugly string down, it actually contains a number of easy-to-understand SQL commands: create table + TABLE_NAME( COLUMN_NAME + VARCHAR, COLUMN_MAGAZINE_TITLE + VARCHAR, COLUMN_RENEWAL_DATE + VARCHAR, COLUMN_PHONE + VARCHAR) SQLite will also add another column implicitly called rowid, which acts as a kind of index for retrieving records and increases incrementally in value with each new entry. The first record will have the rowid ‘0’, the second will be ‘1’, and so on. We don’t need to add this ourselves but we can refer to it whenever we want. If we wanted to change the name of a column, we would manually create one with the variable INTEGER PRIMARY KEY . That way, we could turn our ‘rowid’ into ‘subscriber_id’ or something similar. The rest of the columns are more straightforward. These are going to contain characters (VARCHAR) and they will each be named by the variables we created earlier. Here is a good resource where you can see the SQL syntax on its own for this command and many others. If we break the string down, it actually contains a number of easy-to-understand SQL commands The other method, onUpgrade, is required for when the database version is changed. This will drop or add tables to upgrade to the new schema version. Just populate it and don’t worry about it: @Override public void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); onCreate(db); } DROP TABLE is used to delete the existing data. Here we’re deleting the table if it already exists before rebuilding it. See the previous post for more. If all that’s in place, you’ve built your first database. Well done! In future, if we to refer to a database that was already created, then we would use getReadableDatabase() or getWriteableDatabase() to open the database ready for reading-from or writing-to. Inserting data To insert new data as a row, simply use db.insert(String table, String nullColumnHack, ContentValues). But what are ContentValues? This is a class used by Android that can store values to be resolved by the ContentResolver. If we create a ContentValues object and fill it with our data, we can pass that to our database for assimilation. It looks like this: contentValues.put(COLUMN_NAME, "Adam"); contentValues.put(COLUMN_MAGAZINE_TITLE, "Women's World"); contentValues.put(COLUMN_RENEWAL_DATE, "11/11/2018"); contentValues.put(COLUMN_PHONE, "00011102"); db.insert(TABLE_NAME, null, contentValues); db.close(); Another option would be to use database.execSQL() and input the data manually: db.execSQL("INSERT INTO " + TABLE_NAME + "(" + COLUMN_NAME + "," + COLUMN_MAGAZINE_TITLE + "," + COLUMN_RENEWAL_DATE + "," + COLUMN_PHONE + ") VALUES('Adam','Women's World','11/11/2018','00011102')"); db.close(); This does the exact same thing. Remember to always close the database when you’re finished with it. You weren’t brought up in a barn, were you? Optional Of course, to really use this database properly, we would probably want to populate our columns using objects. We could use the following class to add new subscribers to our list: public class SubscriberModel { private String ID, name, magazine, renewal, phone; public String getID() { return ID; } public String getName() { return name; } public String getRenewal() { return renewal; } public String getMagazine() { return magazine; } public String getPhone() { return phone; } public void setName(String name) { this.name = name; } public void setMagazine(String magazine) { this.magazine = magazine; } public void setRenewal(String renewal) { this.renewal = renewal; } public void setPhone(String phone) { this.phone = phone; } } Then we could easily build as many new subscribers as we liked and take the variables from there. Better yet, we can also retrieve data from our database this way to build new objects. For instance, we might use something like the following to read through a list of clients and then populate an array list using those objects. This uses a ‘cursor’, which you’ll learn about in the next section. public ArrayList<Subscribers> getAllRecords() { SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.query(TABLE_NAME, null, null, null, null, null, null); ArrayList<Subscribers> subs = new ArrayList<>(); Subscribers subscribers; if (cursor.getCount() > 0) { for (int i = 0; i < cursor.getCount(); i++) { cursor.moveToNext(); subscribers = new Subscribers(); subscribers.setName(cursor.getString(1)); subscribers.setMagazine(cursor.getString(2)); subs.add(subscribers); } } cursor.close(); db.close(); return subs; } Retrieving data and using cursors We’ve written an awful lot of code so far without testing anything, which always gets me a little bit itchy. Problem is, there’s not much to see here at the moment. To test if this is working, we need to query and return some of the data we’ve inserted. To do that we need to use a cursor. Cursors allow the manipulation of whole results sets and let us process our rows sequentially. This is handy if you ever want to perform some kind of algorithm on a row-by-row basis. You’ll see what I mean. First, we need to create our cursor, which we will do with query. Which looks like this: Cursor cursor = db.query(TABLE_NAME, null, null, null, null, null, null); We could then use this to create an ArrayList or pull out individual bits of data. By creating a little method like this: public String returnName() { SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.query(TABLE_NAME, null, null, null, null, null, null); cursor.moveToFirst(); return cursor.getString(1); } Then we could access that from our MainActivity.java and show it on a TextView, like so: Database database = new Database(this); TextView textView = (TextView)findViewById(R.id.TextView); textView.setText(database.returnName()); I had to create a TextView with the ID ‘TextView’. This should display the name ‘Adam’ on the screen seeing as the cursor has been moved to the first entry and is grabbing a string from position 1 – which is where we put the name (ID is 0). If we were using this for real, we would probably use a “for” loop and use that to grab data from every entry. For example: for (int i = 0; i < cursor.getCount(); i++) { cursor.moveToNext(); //Get useful data such as names of people who need to renew here } Likewise, we might read our database this way and then use those strings to build objects for each subscriber. Closing comments Other useful things we can do include updating rows with database.update and deleting records with database.delete. With a bit of organization, you can start handling your data in a logical and intuitive manner and open up lots of opportunities for powerful apps in the future. you’ve created a whole world of opportunities for your programming career Few things are as valuable as data. Now that you know a way to handle larger datasets logically and keep them stored for future reference, you’ve created a whole world of opportunities for your programming career. >.
http://linksoftvn.com/a-sqlite-primer-for-android-app-developers/
CC-MAIN-2019-39
refinedweb
2,265
64.51
PicFx – Windows Phone Picture Effects Application – Part 2 - Posted: Oct 19, 2010 at 6:00 AM - 16,856 Views The first part of this short series showed how to create the base Windows Phone application and how to implement a Black & White and Sepia effect. The basic Windows Phone picture manipulation workflow was explained, and I showed how to load, resize, take, and save an image. The User Interface with the Pivot control template was introduced and some important Windows Phone development key points were also discussed. We also learned how to implement the Black & White and the Sepia effect with the reusable Tint and Contrast & Brightness modification effects. In this second, final part of the series, we will learn how to make the application more responsive by offloading the image processing computation to a background thread. Furthermore, how to implement a nice vintage Polaroid-like and a miniature faking (tilt shift) effect will be demonstrated, along with how to brand the finished image with a custom logo. The video below introduces the complete PicFx application features and demonstrates how to use them. It was recorded with the application running in the emulator. Background music is “A Silent Goodbye” by NCThompson In the last article, we drilled down from the UI Crust with the Pivot control template and the Windows Phone Application Bar through the UI Mantle with the UI functionality until we finally reached the Effects Core with the image processing algorithms. As in the first part, we again start our journey on the surface of the application. Some things have changed on the surface of the app—it still uses the Windows Phone Application Bar, but the open source Pivot control implementation from CodePlex was replaced by the official control from Microsoft. The WrapPanel from the official Silverlight for Windows Phone Toolkit is now also used. As you can see in Figure 1, thumbnails of the two new effects are shown on the second Pivot page. Figure 1: The Pivot layout of the extented PicFx application The current MainPage.xaml: XAML <phoneCtrls:Pivot <phoneCtrls:PivotItem <Grid Height="510" VerticalAlignment="Top" > <Image Name="Viewport" Stretch="Uniform" /> <ProgressBar Name="ProgessBar" IsIndeterminate="True" Height="20" Width="200" Visibility="Collapsed" HorizontalAlignment="Center" VerticalAlignment="Center" /> </Grid> <> An Indeterminate ProgressBar was added to the first Pivot item overlaying the Image, which shows the selected picture. The ProgressBar is hidden by default and only made visible when the picture with the full resolution is processed and saved. The ListBox with the thumbnails of the effects (see Figure 1) is still data-bound to the StaticResource “effects,” an instance of the EffectItems class that consists of EffectItem elements: C# public class EffectItems : ObservableCollection<EffectItem> { public EffectItems() { Add( new EffectItem(new BlackWhiteEffect(), "data/icons/BlackWhite.png")); Add( new EffectItem(new SepiaEffect(), "data/icons/Sepia.png")); Add( new EffectItem(new TiltShiftEffect(), "data/icons/TiltShift.png")); Add( new EffectItem(new PolaroidEffect(), "data/icons/PolaYellow.png", "Pola")); } } The two new EffectItems are added and the vintage Polaroid-like effect gets a custom display name—“Pola”—to avoid a mix-up with the original Polaroid brand. I also added Clint Rutkas' Coding4Fun About control as an Application Bar menu item. This control is a typical about page which provides some information about the app and Coding4Fun..MenuItems> <shell:ApplicationBarMenuItem </shell:ApplicationBar.MenuItems> </shell:ApplicationBar> </phone:PhoneApplicationPage.ApplicationBar> The first part introduced the Windows Phone picture manipulation workflow and explained how to load, resize, take, and save an image. This section will show how to keep the UI responsive by performing the image processing asynchronously. The two new effects introduced in this article are more computationally expensive. If these would be applied to the original sized picture, the UI thread would get blocked for a few seconds. This is a No Go for a professional application and in order to pass the Marketplace validation, an app has to be responsive and needs to avoid hang-ups. This and other important requirements are defined in the official Windows Phone 7 Application Certification Requirements document. To achieve a good responsiveness of the application, the work has to be offloaded from the UI thread to a background thread. Here is where Silverlight's multi-threading strength comes into play. There is only one problem—due to its base classes, the WriteableBitmap can't be used in a non-UI thread. As we know from the first article, the WriteableBitmap uses the RGB color space to represent the pixels. It's actually just a 32-bit integer array that stores the alpha, red, green, and blue (ARGB) byte components for all the pixels in a 1D array, and stores the width and the height as integer properties. This leads us to the natural solution: perform the whole cascade of image processing effects with an integer array (pixels) along with the width and height and only copy the final result back to WriteableBitmap on the UI thread. No sooner said than done, the following code is executed when the user hits the Save button: C# if (ListBoxEffects.SelectedItem == null) { return; }// Set Save.. state and get UI parameters Viewport.Opacity = 0.2; ProgessBar.Visibility = Visibility.Visible; var effect = ((EffectItem)ListBoxEffects.SelectedItem).Effect; var dispatcher = Dispatcher;ThreadPool.QueueUserWorkItem((state) => { try { // Apply Effect on int[] since WriteableBitmap // can't be used in background thread var width = original.PixelWidth; var height = original.PixelHeight; var resultPixels = effect.Process(original.Pixels, width, height); // Convert int[] to WriteabelBitmap // WriteableBitmap ctor has to be invoked on the UI thread dispatcher.BeginInvoke(() => { // Turbo copy the pixels to the WriteableBitmap var result = new WriteableBitmap(width, height); Buffer.BlockCopy(resultPixels, 0, result.Pixels, 0, resultPixels.Length * 4); // Save WriteableBitmap var name = String.Format( "PicFx_{0:yyyy-MM-dd_hh-mm-ss-tt}.jpg", DateTime.Now); result.SaveToMediaLibrary(name); }); } finally { // Set controls to initial state dispatcher.BeginInvoke(() => { ProgessBar.Visibility = Visibility.Collapsed; Viewport.Opacity = 1; }); } }); The ProgressBar is shown during the asynchronous processing and the Opacity of the Image control is reduced (Figure 2). The actual image processing with the selected effect is performed on a background thread. Using the ThreadPool class and its QueueUserWorkItem method accomplishes this. The ThreadPool provides a pool of threads and the QueueUserWorkItem is used to queue a work operation for processing. The main benefit is that resources aren't unnecessarily hogged—the creation of a thread takes some time and each thread needs certain resources such as its own memory stack. Also note that, for common computational scenarios, it's best to keep a balance between threads and processor cores. A thread pool avoids the creation overhead through a certain amount of threads that are kept alive and all the queued work is executed one after another by these threads. The IEffect's new Process method overload with the pixels integer array and size parameters is used inside the background thread processing. Read more about the IEffect interface change below. After the effects processing chain is done, a new WriteableBitmap is then instantiated on the UI thread with the use of the Page's Dispatcher, which executes code on the UI thread. Then the integer pixels array is copied to the WriteableBitmap's Pixels property with the fast BlockCopy. The BlockCopy method copies a block of bytes in one single operation in memory, just like the good ol' memcpy. The final bitmap is then saved to the picture library/photo album with the SaveToMediaLibrary extension method that was introduced in the first part. Finally, the ProgessBar is again hidden and the Image's opacity is restored. Figure 2: Saving a picure shows the ProgressBar over the semi-transparent Image Now that we made the image processing asynchronous and the UI is responsive even when complex computations are performed, it's time to leverage this feature for some advanced effects. The IEffect interface had to be changed for the asynchronous WriteableBitmap-less processing. The new Process method overload expects the pixels as ARGB32 integer array, and the width and height of the bitmap as parameters. The return value is the processed bitmap as integer pixel array of the same size. Figure 3: The changed IEffect interface As we learned in the first part, the end user effects are called composite effects (outer core), which are made out of various, reusable base effects (inner core). This composite effect gives a picture an old-touch so it looks like it was taken with an old, Polaroid-like camera. Figure 4: Vintage Polaroid-like effect applied to the sample picture The Polaroid-like composite effect uses three internal base effects: a Gaussian blur, an effect that adds a black vignette, and the Tint base effects introduced in the first part (Figure 5). Figure 5: The class diagram of the PolaroidEffect Old photos weren't as sharp as modern photos and therefore the Blurriness property defines how much the picture will be blurred. The Vignette property controls the size of the round vignette. Additionally, the amount of tinting and the tint color can be changed with properties. C# public class PolaroidEffect : IEffect { readonly GaussianBlurEffect blurFx; readonly VignetteEffect vignetteFx; readonly TintEffect tintFx; readonly BitmapMixer mixer; public string Name { get { return "Vintage"; } } public float Blurriness { get { return blurFx.Sigma; } set { blurFx.Sigma = value; } } public float Vignette { get { return vignetteFx.Size; } set { vignetteFx.Size = value; } } public float Tinting { get { return mixer.Mixture; } set { mixer.Mixture = value; } } public Color TintColor { get { return tintFx.Color; } set { tintFx.Color = value; } } public PolaroidEffect() { blurFx = new GaussianBlurEffect { Sigma = 0.15f }; vignetteFx = new VignetteEffect(); tintFx = TintEffect.Sepia; mixer = new BitmapMixer { Mixture = 0.5f }; } public WriteableBitmap Process(WriteableBitmap input) { var width = input.PixelWidth; var height = input.PixelHeight; return Process(input.Pixels, width, height) .ToWriteableBitmap(width, height); } public int[] Process(int[] inputPixels, int width, int height) { var resultPixels = blurFx.Process(inputPixels, width, height); resultPixels = vignetteFx.Process(resultPixels, width, height); var tintedPixels = tintFx.Process(resultPixels, width, height); return mixer.Mix(resultPixels, tintedPixels, width, height); } } First the input is blurred and the vignette is added. Afterward, a new Sepia-tinted version of the processed image is created. In the last processing step, the non-tinted and the tinted bitmap are mixed together with the use of the new BitmapMixer class. This results in a slight Sepia tint rather than the full Sepia tone. The vintage Polaroid-like effect uses three base effects and a mixer to achieve the old look. Now it's time to see how its Inner Core effects work. There are several different available blur algorithms, and one of the most common is the Gaussian blur. The Gaussian blur applies a Gaussian function to an image in order to smooth it and reduce details. The naïve implementation uses a convolution kernel, which is basically a 2D array of n x n elements. In the case of a Gaussian filter the kernel values represent a discrete 2D Gaussian function, which has the typical bell shape. The usual kernel has a size of 5 x 5, though other kernels range from 7 x 7 on up. Figure 6: Gaussian blur applied to the sample image During the actual image processing, a pixel of the input image is multiplied with all of the kernel elements. The products of the pixel-kernel-element multiplication are summed and divided, and then the result is assigned as the output pixel. This is done for all the pixels of the input image. The disadvantage of this approach is that the computation time increases when the blurring is increased. In order to blur the image more, the kernel size is usually enlarged, thus meaning n x n multiplications need to be performed for each pixel. Fortunately, in 1995 Ian T. Young and Lucas J. van Vliet invented a better algorithm that is independent of the width. They describe the method in detail in their paper, “Recursive implementation of the Gaussian filter.” It gets even better—Andrew Marshall already implemented the recursive Gaussian filter in C# for his Silverlight and CUDA interop blog post and allowed me the use it. As you can imagine, the implementation is quite complex and could make up an article on its own. In fact, Young & van Vliet already wrote this article by writing their paper. Please read it if you want to know the mathematical details behind the GaussianBlurEffect class. The effect of vignetting reduces the brightness of the pixels towards the edges. This is done by computing the pixel's distance to the center and multiplying this with the pixel color. This generates the vignette effect as a fadeout to black towards the edges. Figure 7: A black vignette The Process method of the VignetteEffect implements the vignetting. C# public int[] Process(int[] inputPixels, int width, int height) { // Prepare some variables var resultPixels = new int[inputPixels.Length]; var ratio = width > height ? height * 32768 / width : width * 32768 / height; // Calculate center, min and max var cx = width >> 1; var cy = height >> 1; var max = cx * cx + cy * cy; var min = (int)(max * (1 - Size)); var diff = max - min; var index = 0; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { var c = inputPixels[index]; // Extract color components var a = (byte)(c >> 24); var r = (byte)(c >> 16); var g = (byte)(c >> 8); var b = (byte)(c); // Calculate distance to center // and adapt aspect ratio var dx = cx - x; var dy = cy - y; if (width > height) { dx = (dx * ratio) >> 15; } else { dy = (dy * ratio) >> 15; } int distSq = dx * dx + dy * dy; if (distSq > min) { // Calculate vignette var v = ((max - distSq) << 8) / diff; v *= v; // Apply vignette var ri = (r * v) >> 16; var gi = (g * v) >> 16; var bi = (b * v) >> 16; // Check bounds r = (byte)(ri > 255 ? 255 : (ri < 0 ? 0 : ri)); g = (byte)(gi > 255 ? 255 : (gi < 0 ? 0 : gi)); b = (byte)(bi > 255 ? 255 : (bi < 0 ? 0 : bi)); // Combine components c = (a << 24) | (r << 16) | (g << 8) | b; } resultPixels[index] = c; index++; } } return resultPixels; } The x and y coordinate of the image's center and the aspect ratio are calculated. As you can see, only fast integer operations are used again. Inside the loop, the color components of each input pixel are extracted and the distance vector to the center is calculated with respect to the picture's aspect ratio. The squared length of the distance vector is tested against the minimum vignette size. If the pixel falls within the range, the scaled distance length is multiplied with each color component. The result is an adapted brightness as described above. The last step ensures that the color components are in the byte range and then combines these to the result integer pixel color. As the name might imply, the purpose of the BitmapMixer class is to mix two images. The Mix method mixes two ARGB32 integer bitmaps of the same size and returns the mixed bitmap. This is actually an alpha blending operation where the Mixture property defines the opacity of the input2 image. A Mixture value of 0 means input1 is fully visible and a value of 1 means that input2 is shown—everything in between is a mix of both. C# public float Mixture { get; set; }public int[] Mix(int[] inputPixels1, int[] inputPixels2, int width, int height) { // Prepare some variables var resultPixels = new int[inputPixels1.Length]; var m = Mixture; var mi = 1 - m; for (var i = 0; i < inputPixels1.Length; i++) { // Extract color components var c1 = inputPixels1[i]; var a1 = (byte)(c1 >> 24); var r1 = (byte)(c1 >> 16); var g1 = (byte)(c1 >> 8); var b1 = (byte)(c1); var c2 = inputPixels2[i]; var a2 = (byte)(c2 >> 24); var r2 = (byte)(c2 >> 16); var g2 = (byte)(c2 >> 8); var b2 = (byte)(c2); // Mix it! var d = ((byte)(a1 * mi + a2 * m) << 24) | ((byte)(r1 * mi + r2 * m) << 16) | ((byte)(g1 * mi + g2 * m) << 8) | ((byte)(b1 * mi + b2 * m)); // Set result color resultPixels[i] = d; } return resultPixels; } The color components of the two input images are extracted. Each color component of input2 is then multiplied with the Mixture factor and input2 is multiplied with the inverse of the Mixture. Then, both color component products are added and the new values are combined to form the new integer output pixel. Now that we've learned the details of some of the new Inner Core effects, it's time to use some of them in a different combination and make an interesting Outer Core effect. The digital tilt shift effect lets a scene look like a miniature scale model. It's quite popular nowadays and you might have seen it applied to video in some ads. It's commonly called miniature faking and produces a nice result if it's applied to a photo that was taken from a high angle. Figure 8: The tilt shift Effect applied to a photo of Dresden that I have taken from a Ferris wheel In the first processing stage the TiltShiftEffect increases the contrast of the image with the BrightnessContrastModification effect, which was introduced in the first part. Afterward, the picture gets blurred with the GaussianBlurEffect. The blurred version is then combined with the non-blurred to produce the shallow depth of field of a close-up shot. Figure 9: The class diagram of the TiltShiftEffect The UpperFallOff property defines the relative y coordinate where the depth of field (camera focus) is completely faded out. The LowerFadeOff defines the lower focus counterpart: C# public float UpperFallOff { get; set; } public float LowerFallOff { get; set; }private int[] contrastedPixels; private int[] blurredPixels;public int[] Process( int[] inputPixels, int width, int height) { // Increase contrast CreateBlurredBitmap(inputPixels, width, height); // Mix the fade off return ProcessOnlyFocusFadeOff( inputPixels, width, height); }private void CreateBlurredBitmap( int[] inputPixels, int width, int height) { // Increase contrast contrastedPixels = contrastFx.Process( inputPixels, width, height); // Blur blurredPixels = blurFx.Process( contrastedPixels, width, height); }public int[] ProcessOnlyFocusFadeOff( int[] inputPixels, int width, int height) { // Check if the cache is empty if (contrastedPixels == null || blurredPixels == null) { CreateBlurredBitmap(inputPixels, width, height); } var resultPixels = blurredPixels; // If not fully blurred? if (UpperFallOff < LowerFallOff) { // Prepare some variables resultPixels = new int[inputPixels.Length]; // Calculate fade area var uf = (int)(UpperFallOff * height); var lf = (int)(LowerFallOff * height); var fo = ((lf - uf) >> 1); var mf = uf + fo; var mfu = mf; var mfl = mf; // Limit fall off and calc inverse if (fo > height * MaxFallOffFactor) { fo = (int)(height * MaxFallOffFactor); mfu = uf + fo; mfl = lf - fo; } var ifo = 1f / fo; // Blend var index = 0; for (var y = 0; y < height; y++) { for (var x = 0; x < width; x++) { var c2 = contrastedPixels[index]; // Above or below the fading area if (y < mfu || y > mfl) { var c = blurredPixels[index]; // Inside the fading area, // but not in the focused area if (y > uf || y < lf) { // Extract color components var a1 = (byte)(c >> 24); var r1 = (byte)(c >> 16); var g1 = (byte)(c >> 8); var b1 = (byte)(c); var a2 = (byte)(c2 >> 24); var r2 = (byte)(c2 >> 16); var g2 = (byte)(c2 >> 8); var b2 = (byte)(c2); // Calculate blending float m = y < mf ? (mfu - y) : (y - mfl); m *= ifo; if (m > 1) { m = 1f; } var mi = 1 - m; // Mix it! c = ((byte)(a1 * m + a2 * mi) << 24) | ((byte)(r1 * m + r2 * mi) << 16) | ((byte)(g1 * m + g2 * mi) << 8) | ((byte)(b1 * m + b2 * mi)); } // Set result color resultPixels[index] = c; } else { resultPixels[index] = c2; } index++; } } } return resultPixels; } As you can see, the processing is split into three methods and two member variables are used to cache both the contrast-increased result and the blurred result. This is useful when only the FallOff properties are changed interactively in real-time, which is described below. Figure 10: The simulated depth of field fade out The actual processing mixes the contrast-increased image and the blurred image by using a linear fading function. Figure 10 illustrates this. The red color represents the blurred version and the gray stands for the contrast-increased image. This fading uses the FallOff properties, converts these properties into absolute values, and calculates some y coordinates, which are needed for the fade in/out. Inside the loop, the color components of both bitmaps are extracted and the mixture factor is computed. Then the color components are multiplied with the factors like in the BitmapMixer's Mix method. The last step combines the component results and sets the integer pixel of the result image. The Windows Phone is a nice multitouch device with very good usability. Its multitouch power is used in the PicFx app to let the user interactively change the FallOff properties of the TiltShiftEffect; therefore, the focused area can be altered in an intuitive way. Silverlight and the Windows Phone Silverlight version provide the static Touch class, which has only one member, the FrameReported event. This event is fired each time a set of touch points is registered. An event handler is attached in the Initialize method of the MainPage. Please note that one would actually encapsulate the following code in a separate class like ViewModel for the effect, but I decided to leave this out to keep the code simpler and focused on the nitty gritty. C# private void Initialize() { // Attach touch event handler Touch.FrameReported += Touch_FrameReported; // ... }private void Touch_FrameReported( object sender, TouchFrameEventArgs e) { SetTiltShiftFocus(e.GetTouchPoints(Viewport)); }private void SetTiltShiftFocus(IList<TouchPoint> points) { IEffect effect = null; if (ListBoxEffects != null) { var item = ListBoxEffects.SelectedItem as EffectItem; if (item != null) { effect = item.Effect; } } var tiltFx = effect as TiltShiftEffect; if (tiltFx == null) { return; } var result = Viewport.Source; var isManipulating = points.Any( p => p.Action == TouchAction.Down || p.Action == TouchAction.Move); if (isManipulating) { if (points.Count > 1) { var y1 = (int)points[0].Position.Y; var y2 = (int)points[1].Position.Y; // FallOff is expected as relative coordinate var ih = 1f / resized.PixelHeight; // Topmost point is upper FallOff if (y1 < y2) { tiltFx.UpperFallOff = y1 * ih; tiltFx.LowerFallOff = y2 * ih; } else { tiltFx.UpperFallOff = y2 * ih; tiltFx.LowerFallOff = y1 * ih; } // Apply selected effect var processed = tiltFx.ProcessOnlyFocusFadeOff(resized); // Add FallOff marker lines const int markerHeight = 4; processed.FillRectangle( 0, y1 - markerHeight, resized.PixelWidth, y1 + markerHeight, Colors.LightGray); processed.FillRectangle( 0, y2 - markerHeight, resized.PixelWidth, y2 + markerHeight, Colors.LightGray); result = processed; } } else { // Apply selected effect result = tiltFx.Process(resized); } // Show the result ShowImage(result); } Every time the multitouch event is fired, the SetTiltShiftFocus method gets called. This method converts the absolute coordinates into relative and assigns the values to the appropriate properties. The topmost point is always interpreted as UpperFallOff. Two small, gray rectangles are drawn at the position of the FallOff values to give the user some feedback. This is done with the WriteableBitmapEx' FillRectangle extension method. To keep the UI responsive, the ProcessOnlyFocusFadeOff method of the TiltShiftEffect is called, and this method uses the cached contrast-increased and blurred images by mixing them. This speeds the process up a lot up. Now it's time to brand our final image with a custom logo before it gets saved. This watermark is useful to customize or add information to a photo. Figure 11: Watermark logo applied to the sample image The Watermarker class has the Watermark property, which represents a WriteableBitmap that is used as watermark logo. The RelativeSize defines the size of the logo relative to the size of the input bitmap it should get applied to: C# public class Watermarker { public WriteableBitmap Watermark { get; private set; } public float RelativeSize { get; set; } public Watermarker(string relativeResourcePath) { Watermark = new WriteableBitmap(0, 0) .FromResource(relativeResourcePath); RelativeSize = 0.4f; } public WriteableBitmap Apply(WriteableBitmap input) { // Resize watermark var w = Watermark.PixelWidth; var h = Watermark.PixelHeight; var ratio = (float) w / h; h = (int) (input.PixelHeight * RelativeSize); w = (int) (h * ratio); var watermark = Watermark.Resize( w, h, WriteableBitmapExtensions.Interpolation.Bilinear); // Blit watermark into copy of the input // Bottom right corner var result = input.Clone(); var position = new Rect( input.PixelWidth - w, input.PixelHeight - h, w, h); result.Blit(position, watermark, new Rect(0, 0, w, h)); return result; } } The constructor provides an easy way to pass a bitmap from the resource stream. In the Apply method, the watermark bitmap is scaled with the use of the WriteableBitmapEx' Resize method. After this the position is calculated, the watermark logo is blitted into the bottom right corner of the input image and the result is returned. Note that the WriteableBitmapEx' Blit method is used here. An instance of the Watermarker class is created in the MainPage.xaml.cs. C# private void Initialize() { watermarker = new Watermarker("data/watermark.png"); // ... }private void ApplySelectedEffectAndSaveAsync() { // ... // Turbo copy the pixels to the WriteableBitmap var result = new WriteableBitmap(width, height); Buffer.BlockCopy( resultPixels, 0, result.Pixels, 0, resultPixels.Length * 4); // Apply logo result = watermarker.Apply(result); // Save WriteableBitmap var name = String.Format( "PicFx_{0:yyyy-MM-dd_hh-mm-ss-tt}.jpg", DateTime.Now); result.SaveToMediaLibrary(name); // ... } The watermark is applied after the image processing was performed and before the picture gets saved to the media library. In the first part we drilled down from the UI Crust with the Pivot control template and the Windows Phone Application Bar through the UI Mantle. Finally we reached the Effects Core with the Black & White, Sepia, BrightnessContrast, and Tint effects. In this second part, we again journeyed to the core, starting on the surface in order to learn how to keep the UI responsive with asynchronous processing. We then entered the core and l explained the Polaroid-like vintage, its Gaussian blur, the Vignette effects, and the BitmapMixer. I also demonstrated the miniature faking Tilt Shift effect, including the multitouch manipulation of its parameters. The last step showed how to add a custom logo watermark to the final picture. This short series, or two articles, if you will, has come to end. Yep, it's over now—BUT Coding4Fun has released this development stage of the PicFx app for free on the Marketplace! Furthermore, I continued my work on this project and shipped it with enhanced effects, without watermark, but with extra features and a bunch of new effects, including essential ones like auto adjust, soften and many more. Check out the app called Pictures Lab aimed to be nothing less than THE image effects addition to the Windows Phone Pictures Hub. René Schulte is a .Net, Silverlight and Windows Phone.
http://channel9.msdn.com/coding4fun/articles/PicFx--Windows-Phone-Picture-Effects-Application--Part-2
CC-MAIN-2014-15
refinedweb
4,327
54.83
#include <wx/docview.h> The document class can be used to model an application's file-based data. It is part of the document/view framework supported by wxWidgets, and cooperates with the wxView, wxDocTemplate and wxDocManager classes. A normal document is the one created without parent document and is associated with a disk file. Since version 2.9.2 wxWidgets also supports a special kind of documents called child documents which are virtual in the sense that they do not correspond to a file but rather to a part of their parent document. Because of this, the child documents can't be created directly by user but can only be created by the parent document (usually when it's being created itself). They also can't be independently saved. A child document has its own view with the corresponding window. This view can be closed by user but, importantly, is also automatically closed when its parent document is closed. Thus, child documents may be convenient for creating additional windows which need to be closed when the main document is. The docview sample demonstrates this use of child documents by creating a child document containing the information about the parameters of the image opened in the main document. Constructor. Define your own default constructor to initialize application-specific data. Destructor. Removes itself from the document manager. Activate the first view of the document if any. This function simply calls the Raise() method of the frame of the first view. You may need to override the Raise() method to get the desired effect if you are not using a standard wxFrame for your view. For instance, if your document is inside its own notebook tab you could implement Raise() like this: If the view is not already in the list of views, adds the view and calls OnChangedViewList(). Returns true if the document hasn't been modified since the last time it had been saved. Notice that this function returns false if the document had been never saved at all, so it may be also used to test whether it makes sense to save the document: if it returns true, there is nothing to save but if false is returned, it can be saved, even if it might be not modified (this can be used to create an empty document file by the user). Closes the document, by calling OnSaveModified() and then (if this returned true) OnCloseDocument(). This does not normally delete the document object, use DeleteAllViews() to do this implicitly. Calls wxView::Close() and deletes each view. Deleting the final view will implicitly delete the document itself, because the wxView destructor calls RemoveView(). This in turns calls OnChangedViewList(), whose default implemention is to save and delete the document if no views exist. Virtual method called from OnCloseDocument(). This method may be overridden to perform any additional cleanup which might be needed when the document is closed. The return value of this method is currently ignored. The default version does nothing and simply returns true. This method is called by OnOpenDocument() to really load the document contents from the specified file. Base class version creates a file-based stream and calls LoadObject(). Override this if you need to do something else or prefer not to use LoadObject() at all. This method is called by OnSaveDocument() to really save the document contents to the specified file. Base class version creates a file-based stream and calls SaveObject(). Override this if you need to do something else or prefer not to use SaveObject() at all. Returns a pointer to the command processor associated with this document. Gets a pointer to the associated document manager. Gets the document type name for this document. See the comment for m_documentTypeName. Return true if this document had been already saved. Gets a pointer to the template that created the document. Intended to return a suitable window for using as a parent for document-related dialog boxes. By default, uses the frame associated with the first view. Gets the filename associated with this document, or "" if none is associated. A convenience function to get the first view for a document, because in many cases a document will only have a single view. Gets the title for this document. The document title is used for an associated frame (if any), and is usually constructed by the framework from the filename. Return the document name suitable to be shown to the user. The default implementation uses the document title, if any, of the name part of the document filename if it was set or, otherwise, the string unnamed. Returns true if this document is a child document corresponding to a part of the parent document and not a disk file as usual. This method can be used to check whether file-related operations make sense for this document as they only apply to top-level documents and not child ones. Override this function and call it from your own LoadObject() before streaming your own data. LoadObject() is called by the framework automatically when the document contents need to be loaded. Override this function and call it from your own LoadObject() before streaming your own data. LoadObject() is called by the framework automatically when the document contents need to be loaded. Call with true to mark the document as modified since the last save, false otherwise. You may need to override this if your document view maintains its own record of being modified. Called when a view is added to or deleted from this document. The default implementation saves and deletes the document if no views exist (the last one has just been removed). If notifyViews is true, wxView::OnChangeFilename() is called for all views. This virtual function is called when the document is being closed. The default implementation calls DeleteContents() (which may be overridden to perform additional cleanup) and sets the modified flag to false. You can override it to supply additional behaviour when the document is closed with Close(). Notice that previous wxWidgets versions used to call this function also from OnNewDocument(), rather counter-intuitively. This is no longer the case since wxWidgets 2.9.0. Called just after the document object is created to give it a chance to initialize itself. The default implementation uses the template associated with the document to create an initial view. For compatibility reasons, this method may either delete the document itself if its initialization fails or not do it in which case it is deleted by caller. It is recommended to delete the document explicitly in this function if it can't be initialized. Override this function if you want a different (or no) command processor to be created when the document is created. By default, it returns an instance of wxCommandProcessor. The default implementation calls OnSaveModified() and DeleteContents(), makes a default title for the document, and notifies the views that the filename (in fact, the title) has changed.. Constructs an output file stream for the given filename (which must not be empty), and calls SaveObject(). If SaveObject() returns true, the document is set to unmodified; otherwise, an error message box is displayed. Removes the view from the document's list of views, and calls OnChangedViewList(). Discard changes and load last saved version. Prompts the user first, and then calls DoOpenDocument() to reload the current file. Saves the document by calling OnSaveDocument() if there is an associated filename, or SaveAs() if there is no filename. Prompts the user for a file to save to, and then calls OnSaveDocument(). Override this function and call it from your own SaveObject() before streaming your own data. SaveObject() is called by the framework automatically when the document contents need to be saved. Override this function and call it from your own SaveObject() before streaming your own data. SaveObject() is called by the framework automatically when the document contents need to be saved. Sets the command processor to be used for this document. The document will then be responsible for its deletion. Normally you should not call this; override OnCreateCommandProcessor() instead. Sets the document type name for this document. See the comment for m_documentTypeName. Sets if this document has been already saved or not. Normally there is no need to call this function as the document-view framework does it itself as the documents are loaded from and saved to the files. However it may be useful in some particular cases, for example it may be called with false argument to prevent the user from saving the just opened document into the same file if this shouldn't be done for some reason (e.g. file format version changes and a new extension should be used for saving). Sets the pointer to the template that created the document. Should only be called by the framework. Sets the filename for this document. Usually called by the framework. Calls OnChangeFilename() which in turn calls wxView::OnChangeFilename() for all views if notifyViews is true. Sets the title for this document. The document title is used for an associated frame (if any), and is usually constructed by the framework from the filename. Updates all views. If sender is non-NULL, does not update this view. hint represents optional information to allow a view to optimize its update. A pointer to the command processor associated with this document. Filename associated with this document ("" if none). true if the document has been modified, false otherwise. A pointer to the template from which this document was created. Document title. The document title is used for an associated frame (if any), and is usually constructed by the framework from the filename..
https://docs.wxwidgets.org/3.0/classwx_document.html
CC-MAIN-2019-09
refinedweb
1,606
56.35
Submitted by Peter O'Hanlon on by Peter O'Hanlon Downloads Intel Voice Recognition and Synthesis [PDF 404KB] Audio File Writer Source [ZIP 2KB] Abstract: Ever since touch devices became popular, there has been a sense that we can improve on the methods that we use to interact with our technology. Voice recognition and voice synthesis are going to play a large part in the way we interact with systems in the future. This technological future we have been envisioning for the last few decades is now, finally achievable. Intel® Perceptual Computing SDK is a set of tools designed to help us achieve it. Why are voice recognition and voice synthesis so important? Imagine a world without sound, a world where you couldn't tell someone what you wanted; a world, if you like, where your boss couldn't give you feedback and tell you how great a job you are doing. Sounds pretty grim, doesn't it? Surprisingly though, we've been happy enough to interact with our computers in this very way. But what if there was a better way? A way where the computer provides instant vocal feedback. A way where your voice controls the computer. What if you were freed of the need to actually use a keyboard or screen, and yet you still have meaningful control of your applications? Who can forget that scene in Star Trek where Scottie picked up the mouse and spoke into it? Oh, how we laughed at the idea of being able to really tell a computer what to do. Why, you'll always have to use a mouse and keyboard won't you? Recently, I had the opportunity to work with the Intel Perceptual Computing SDK to see what it can do. Part of the SDK covers speech recognition and speech synthesis, and I will cover what I discovered about this as we progress through this article. Along the way, we'll write some code and talk about things such as accents, context, free form text, and dictionaries. Oh, we'll have a wonderful time, and I hope that you'll want to incorporate speech into your applications. A particular area of interest to me is how we can build more accessible applications. I'm not just talking about making applications compliant with various disability legislations, but how we can make applications work in environments where touching a screen or a mouse/keyboard isn’t possible or practical. For example, if you're baking in the kitchen and your hands are covered in flour, you don't want to be touching your screen. However, with perceptual computing, you could be trying out a new recipe, following a top chef as they demonstrate it, and advance to the next stage of the baking process simply by using voice commands. Why what you say and how you say it matters With the technology that's available now, it's getting to the stage that voice recognition is becoming more and more straightforward. So, I can’t see any reason for not using it right now, can you? Well, there may be one or two reasons I'll cover now. When I was writing my first application with speech recognition in it, the code was easy to write. As you’ll soon see, it was very simple. The problem came when I actually ran the application and tried to test it. Living in the North East of England, my accent is quite broad, and when I spoke, the recognition modules had a tough time decoding what I was saying. This was because the API, at the time, was geared towards a nice, neutral American accent. Fortunately, the team at Intel is really on the ball, so new language packs are rolling out to ease the recognition of other accents. You, on the other hand, have a neutral American accent and you're raring to go. "Is there anything else I need to know?" I hear you ask. Well, yes there is. Speech recognition isn't that hard to code now, but getting your app to understand context is. What do I mean by context? Real speech recognition takes you beyond just using a dictionary of a few words. Speech recognition means that your application really needs to be able to "understand" what you meant when you said "Open the file menu" because you might also say "Click the file option" or "Select the first menu item." This is beyond the scope of this article, but if you are interested in integrating this level of ability in to your applications, I would suggest that you spend time researching Natural Language Processing. One final note before we get to the code. I find that using a high quality microphone is a great help when using speech recognition. A basic voice recognition sample By this point, you may be wondering if I'm going to show you any code. Well, you need wonder no more—let’s take a look at a basic C# example. This is possibly the simplest code you've ever seen, but it is a great illustration of how much work Intel has put into the SDK, and how much it has done to help developers get started with the tools. To keep things simple, this is going to be a Windows* console application, and we are just going to write whatever the SDK detects to the console window. Once we have created our console application (I've called mine SpeechRecognition.Sample1), we are going to create a class that inherits from UtilMPipeline. This class, provided as part of the SDK, removes the boiler plate that we need to write (more on this later). Note: The first few samples are provided in both C# and C++. We will see that the two code bases are virtually identical, so we provide the other examples in C# only. C# code using System; namespace SpeechRecognition.Sample1 { public class SpeechPipeline : UtilMPipeline { public SpeechPipeline() { EnableVoiceRecognition(); this.LoopFrames(); } public override void OnRecognized(ref PXCMVoiceRecognition.Recognition data) { Console.WriteLine(data.dictation); base.OnRecognized(ref data); } } } Most of this code is fairly self-explanatory. In the constructor, we enable voice recognition; cunningly enough, the method to do this is called EnableVoiceRecogntion. Then we use the LoopFrames method to tell the SDK to loop through its detection cycle. This effectively puts the application into a big loop. We override the OnRecognized method so that we can write out the words that are recognized. Notice that we are writing out the data.dictation. As we are going to be running the recognition in dictation mode, we access this to get at what was said. When we cover command mode, we'll see what else is available to us to work out what was said. When we run the application, it's apparent that the SDK waits for natural language breaks before it writes anything out through OnRecognized. Now, running this code couldn't be simpler. Simply instantiate the class and you can talk to your computer. C++ code #include <iostream> #include "util_pipeline.h" class CppMPipeline : public UtilPipeline { public: CppMPipeline() { EnableVoiceRecognition(); LoopFrames(); } virtual void PXCAPI OnRecognized(PXCVoiceRecognition::Recognition *data) { std::wcout << data->dictation } }; As you can see, this is virtually identical to the C# implementation. Getting started with speech recognition really is that straightforward. Making our own speech pipeline One of the really surprising things is how little you actually have to do. There's a lot taken care of, behind the scenes, for us. It's worthwhile, at this point, to actually look at what's going on. I'm only going to cover this in C# code here, as the theory is exactly the same for the C++ version. We're going to cover this now because we're going to need this infrastructure later on. So, let's start off by creating our class. This time, it's not going to inherit from UtilMPipeline. (Note that this isn't going to be the exact class that Intel provides, we're going to be making it more convenient for our purposes, but it will provide the same hook points.) C# code public class SpeechPipeline : IDisposable { public void Dispose() { } } We make our class disposable because we have a few unmanaged resources that we need to clean up when we finish with it. Next, we're going to add a constructor to this class. In this constructor, we are going to create a session that we will maintain for the lifetime of this class instance. C# code PXCMSession session; public SpeechPipeline() { PXCMSession.CreateInstance(out session); } Here we see a very common pattern in the SDK. CreateInstance actually returns a status pxcmStatus that tells us whether or not the call worked. To get the populated value, the method has an out parameter that provides us with the populated instance. An important thing to note here is that the C# version always uses PXCMSession, but the C++ version can return PXCSession or PXCMSession depending on whether we are using it as single threaded or multi-threaded. Please read the SDK documentation on this because understanding this is absolutely vital if you're writing in C++. Sorry, but the C# version supports multi-threading out of the box. The eagle-eyed reader may notice that the session is actually a private member. This is because we are going to use it elsewhere in the class, and as it's disposable, let's put it into our Dispose method. C# code public void Dispose() { if (session != null) { session.Dispose(); } } As we saw, in our original classes, we have an EnableVoiceRecognition method. Now that we have a session, let's create our own EnableVoiceRecognition method. C# code UtilMCapture capture; PXCMVoiceRecognition voiceRecognition; public void EnableVoiceRecognition() { PXCMVoiceRecognition.ProfileInfo pinfo; session.CreateImpl<PXCMVoiceRecognition>(PXCMVoiceRecognition.CUID, out voiceRecognition); voiceRecognition.QueryProfile(0, out pinfo); capture = new UtilMCapture(session); capture.LocateStreams(ref pinfo.inputs); voiceRecognition.SetProfile(ref pinfo); voiceRecognition.SubscribeRecognition(0, OnRecognized); } Again, we are going to create a member variable (voiceRecognition) that will be used to actually control the voice recognition. To initialize it, we call session.CreateImpl, using the PXCMVoiceRecognition type as the generic type. Once we have this, we call QueryProfile to access the parameters that can be used to configure the voice recognition. The next couple of lines instantiate one of the more interesting parts of the system, the UtilMCapture allows us to pull together multiple streams of input, such as the audio or video stream, in one easy and consistent manner. Finally, we set up the profile that we are going to use for the voice recognition and subscribe to the voice recognition event. Our OnRecognized method looks like this now: C# code public void OnRecognized(ref PXCMVoiceRecognition.Recognition data) { Console.WriteLine(data.dictation); } One thing to be aware of is that the dictation property is actually a Unicode string. While this doesn't have much of a practical effect in our C# code, it is something that we have to be aware of when we are using it in C++. Now, both of our capture and voiceRecognition members are disposable, so we'll add them into our Dispose method like this: C# code if (voiceRecognition != null) { voiceRecognition.ProcessAudioEOS(); voiceRecognition.Dispose(); } if (capture != null) { capture.Dispose(); } There's an unfamiliar looking method in there. That method tells our application that the audio stream has come to a stop, and it should process any streams internally that haven't been cleared yet. This helps to ensure that we don't leave things in an unstable state. We've come a long way here, and if we look back, we see that there's one thing left for us to hook in to LoopFrames: C# code public void LoopFrames() { while (true) { PXCMAudio sample= null; PXCMScheduler.SyncPoint[] syncPoint = new PXCMScheduler.SyncPoint[2]; try { capture.ReadStreamAsync(out sample, out syncPoint[0]); voiceRecognition.ProcessAudioAsync(sample, out syncPoint[1]); PXCMScheduler.SyncPoint.SynchronizeEx(syncPoint); } finally { if (sample != null) sample.Dispose(); if (syncPoint != null) PXCMScheduler.SyncPoint.Dispose(syncPoint); } } } In the loop, we simply read from the asynchronous audio stream and process the voice recognition audio stream. We aren't going to get a recognizable word or sentence every run through this loop, so we are letting the SDK build up the audio stream for analysis here. The scheduler then effectively marshals things back together via a synchronization point. Again, we are going to be good citizens and dispose of resources when we don't need them. For those who are keen to know what this all looks like in C++, here it is: C++ code #include "stdafx.h" #include <iostream> #include <string> #include "util_pipeline.h" class MyHandler : public PXCVoiceRecognition::Recognition::Handler { public: virtual void PXCAPI OnRecognized(PXCVoiceRecognition::Recognition *data) { std::wcout << data->dictation << std::endl; } }; class CppPipeline { public: CppPipeline() { PXCSession_Create(&session); EnableVoiceRecognition(); LoopFrames(); } void EnableVoiceRecognition() { PXCVoiceRecognition::ProfileInfo pinfo; session->CreateImpl<PXCVoiceRecognition>(&voiceRecognition); voiceRecognition->QueryProfile(0, &pinfo); capture = new UtilCapture(session); capture->LocateStreams(&pinfo.inputs); voiceRecognition->SetProfile(&pinfo); voiceRecognition->SubscribeRecognition(0, new MyHandler); } void LoopFrames() { while (true) { PXCSmartSPArray syncPoint(2); PXCSmartPtr<PXCAudio> audio; capture->ReadStreamAsync(&audio, &syncPoint[0]); voiceRecognition->ProcessAudioAsync(audio, &syncPoint[1]); syncPoint.SynchronizeEx(); } } ~CppPipeline() { if (voiceRecognition) { voiceRecognition->ProcessAudioEOS(); voiceRecognition->Release(); } if (capture) { capture->Release(); } if (session) { session->Release(); } } private: PXCSession* session; PXCVoiceRecognition* voiceRecognition; UtilCapture* capture; }; Obviously, there is more to this, so let's start by beefing up our two implementations so that they both support different languages (remember, a problem I had originally was it understanding my accent). Please note that this sample relies on you having installed other language packs when you installed the SDK. If you didn't install the packs, please feel free to skip over this section. The key to being able to manipulate the languages is all handled through the profile. Inside the profile, there is an id called language that specifies the current language. This seems like a good place for us to start manipulating our language. We will use this to both print out our current language, and choose another one. All we need to do is add the following line after we call QueryProfile (assuming we want to use British English instead): C# code pinfo.language = PXCMVoiceRecognition.ProfileInfo.Language.LANGUAGE_GB_ENGLISH; C++ code pinfo.language = PXCVoiceRecognition::ProfileInfo::LANGUAGE_GB_ENGLISH; Moving beyond dictation So far, we've been concentrating on using the dictation facilities of the SDK. If that were all we had available, it would be pretty impressive, but we can go so much further and support command and control functionality by supplying a dictionary that will be used to control the commands we use. To use a dictionary, we have to create one and add it to the voice recognition after we have enabled voice recognition, and before we start looping through the frames. To do this, we simply need to add a method that looks something like this: C# code string[] commands; public void AddGrammar(string[] grammar) { int gid; commands = grammar; voiceRecognition.CreateGrammar(out gid); for (int i = 0; i < grammar.Length; i++) { voiceRecognition.AddGrammar(gid, i, grammar[i]); } voiceRecognition.SetGrammar(gid); } Here, we are providing the ability to use a pre-defined array of words/phrases in our application. This is known as a grammar. To use a grammar in the SDK, we call CreateGrammar to create a context that will contain our grammar words and phrases. Next, we add the individual grammar items using AddGrammar before we finally choose which grammar context to apply via SetGrammar. We save the array of words to a member because that way we receive the command in the OnRecognized method changes. So, let's see what that looks like now. C# code public void OnRecognized(ref PXCMVoiceRecognition.Recognition data) { if (data.label < 0) Console.WriteLine(data.dictation); else Console.WriteLine(commands[data.label]); } The OnRecognized method looks a lot different. The label property tells us the index of the item that it has identified from the grammar. So, if the label is -1, it means that we are not using dictation mode and we can continue to use the dictation property. If the label is 0 or greater, we simply retrieve the grammar command using the zero-based index in the array. Speech synthesis While it's great being able to recognize words and phrases, we can go one better than that and actually have our application talk to us. While text to speech has been available for a while, it's never really taken off other than in specialist form factors (such as a SatNav). The SDK makes creating voice synthesis very easy. Uncharacteristically, Intel hasn't provided a UtilPipeline equivalent piece of code for voice synthesis, so we will roll this functionality into the code we have been writing so far. Unlike voice recognition, speech synthesis happens in one-off bursts. In other words, it's not waiting for data to come into it from the sensors, so we don't need to put our code into the LoopFrames method. Instead, we are going to create a one-off method to take care of the processing. C# code public void Say(string sentence) { if (string.IsNullOrWhiteSpace(sentence)) return; PXCMVoiceSynthesis.ProfileInfo pinfo; PXCMVoiceSynthesis voiceSynthesis; session.CreateImpl<PXCMVoiceSynthesis>(PXCMVoiceSynthesis.CUID, out voiceSynthesis); voiceSynthesis.QueryProfile(out pinfo); voiceSynthesis.SetProfile(ref pinfo); int sid; voiceSynthesis.QueueSentence(sentence, out sid); var audioWriter = new VoiceOut(pinfo.outputs.info); while (true) { PXCMAudio sample = null; PXCMScheduler.SyncPoint syncPoint = null; var status = voiceSynthesis.ProcessAudioAsync(sid, out sample, out syncPoint); if (status < pxcmStatus.PXCM_STATUS_NO_ERROR) break; status = syncPoint.Synchronize(); audioWriter.WriteAudio(sample); syncPoint.Dispose(); sample.Dispose(); if (status < pxcmStatus.PXCM_STATUS_NO_ERROR) break; } audioWriter.Close(); } The first parts of this method should be familiar by now. We get and set our profile. The interesting part is where we queue up the sentence for the voice synthesizer. There's a fair bit that goes on with this section, so we need to be aware that while the voice synthesizer creates an audio file, it isn't actually responsible for playing the audio file. Instead, we delegate that responsibility to another class that Intel provides in the SDK. This functionality is covered in the code samples you get when you install the SDK and so it is not covered here. After the SDK is installed, the code samples can be located under the base directory of the SDK install at %PCSDK%\framework\CSharp\voice_synthesis.cs\VoiceOut.cs. Summary We have covered using the built-in SDK functionality to enable speech recognition. We then looked at how we could recreate this ourselves, using the same techniques that are used in the SDK. Once we had this in place, we saw how easy it was to start recognizing new languages with the SDK. As well as looking at Command mode, we introduced the ability to work with predefined grammars before we finished the discussion with an introduction of speech synthesis. Useful Links Perceptual Computing SDK Perceptual Computing SDK Help Perceptual Computing SDK Showcase Applications Intel and the Intel logo are trademarks of Intel Corporation in the U.S. and/or other countries. *Other names and brands may be claimed as the property of others. Intel sample sources are provided to users under the Intel Sample Source Code License Agreement deives s. said on intel sou do brasil e estou totalmente desanimado baixei o sdk intalei o visual studio abri o FF_SpeechRecognition para poder usar em português comando de vóz no meu pc por fim já faz 2 dias que venho passando nervoso porque não tem um tutorial apresentavel que me ensine como colocar um comando de vóz para pelo menos abrir um aplicativo bom vou procurar outras coisas já que a intel não é capaz de ter um tutorial mais simplificado. Add a CommentTop (For technical discussions visit our developer forums. For site or software product issues contact support.)Please sign in to add a comment. Not a member? Join today
https://software.intel.com/en-us/articles/voice-recognition-and-synthesis-using-the-intel-perceptual-computing-sdk
CC-MAIN-2016-36
refinedweb
3,308
55.74
D Strings vs C++ StringsWhy have strings built-in to the core language of D rather than entirely in a library as in C++ Strings? What's the point? Where's the improvement? Concatenation Operator C++ Strings are stuck with overloading existing operators. The obvious choice for concatenation is += and +. But someone just looking at the code will see + and think "addition". He'll have to look up the types (and types are frequently buried behind multiple typedef's) to see that it's a string type, and it's not adding strings but concatenating them. Additionally, if one has an array of floats, is '+' overloaded to be the same as a vector addition, or an array concatenation? In D, these problems are avoided by introducing a new binary operator ~ as the concatenation operator. It works with arrays (of which strings are a subset). ~= is the corresponding append operator. ~ on arrays of floats would concatenate them, + would imply a vector add. Adding a new operator makes it possible for orthogonality and consistency in the treatment of arrays. (In D, strings are simply arrays of characters, not a special type.) Interoperability With C String Syntax Overloading of operators only really works if one of the operands is overloadable. So the C++ string class cannot consistently handle arbitrary expressions containing strings. Consider: const char abc[5] = "world"; string str = "hello" + abc; That isn't going to work. But it does work when the core language knows about strings: const char[5] abc = "world"; char[] str = "hello" ~ abc; Consistency With C String Syntax There are three ways to find the length of a string in C++: const char abc[] = "world"; : sizeof(abc)/sizeof(abc[0])-1 : strlen(abc) string str; : str.length() That kind of inconsistency makes it hard to write generic templates. Consider D: char[5] abc = "world"; : abc.length char[] str : str.length Checking For Empty Strings C++ strings use a function to determine if a string is empty: string str; if (str.empty()) // string is empty In D, an empty string has zero length: char[] str; if (!str.length) // string is empty Resizing Existing String C++ handles this with the resize() member function: string str; str.resize(newsize); D takes advantage of knowing that str is an array, and so resizing it is just changing the length property: char[] str; str.length = newsize; Slicing a String C++ slices an existing string using a special constructor: string s1 = "hello world"; string s2(s1, 6, 5); // s2 is "world" D has the array slice syntax, not possible with C++: char[] s1 = "hello world"; char[] s2 = s1[6 .. 11]; // s2 is "world" Slicing, of course, works with any array in D, not just strings. Copying a String C++ copies strings with the replace function: string s1 = "hello world"; string s2 = "goodbye "; s2.replace(8, 5, s1, 6, 5); // s2 is "goodbye world" D uses the slice syntax as an lvalue: char[] s1 = "hello world"; char[] s2 = "goodbye ".dup; s2[8..13] = s1[6..11]; // s2 is "goodbye world" The .dup is needed because string literals are read-only in D, the .dup will create a copy that is writable. Conversions to C Strings This is needed for compatibility with C API's. In C++, this uses the c_str() member function: void foo(const char *); string s1; foo(s1.c_str()); In D, strings can be converted to char* using the .ptr property: void foo(char*); char[] s1; foo(s1.ptr); although for this to work where foo expects a 0 terminated string, s1 must have a terminating 0. Alternatively, the function std.string.toStringz will ensure it: void foo(char*); char[] s1; foo(std.string.toStringz(s1)); Array Bounds Checking In C++, string array bounds checking for [] is not done. In D, array bounds checking is on by default and it can be turned off with a compiler switch after the program is debugged. String Switch Statements Are not possible in C++, nor is there any way to add them by adding more to the library. In D, they take the obvious syntactical forms: switch (str) { case "hello": case "world": ... } where str can be any of literal "string"s, fixed string arrays like char[10], or dynamic strings like char[]. A quality implementation can, of course, explore many strategies of efficiently implementing this based on the contents of the case strings. Filling a String In C++, this is done with the replace() member function: string str = "hello"; str.replace(1,2,2,'?'); // str is "h??lo" In D, use the array slicing syntax in the natural manner: char[5] str = "hello"; str[1..3] = '?'; // str is "h??lo" Value vs Reference C++ strings, as implemented by STLport, are by value and are 0-terminated. [The latter is an implementation choice, but STLport seems to be the most popular implementation.] This, coupled with no garbage collection, has some consequences. First of all, any string created must make its own copy of the string data. The 'owner' of the string data must be kept track of, because when the owner is deleted all references become invalid. If one tries to avoid the dangling reference problem by treating strings as value types, there will be a lot of overhead of memory allocation, data copying, and memory deallocation. Next, the 0-termination implies that strings cannot refer to other strings. String data in the data segment, stack, etc., cannot be referred to. D strings are reference types, and the memory is garbage collected. This means that only references need to be copied, not the string data. D strings can refer to data in the static data segment, data on the stack, data inside other strings, objects, file buffers, etc. There's no need to keep track of the 'owner' of the string data. The obvious question is if multiple D strings refer to the same string data, what happens if the data is modified? All the references will now point to the modified data. This can have its own consequences, which can be avoided if the copy-on-write convention is followed. All copy-on-write is is that if a string is written to, an actual copy of the string data is made first. The result of D strings being reference only and garbage collected is that code that does a lot of string manipulating, such as an lzw compressor, can be a lot more efficient in terms of both memory consumption and speed. Benchmark Let's take a look at a small utility, wordcount, that counts up the frequency of each word in a text file. In D, it looks like this: import std.file; import std.stdio; int main (char[][] args) { int w_total; int l_total; int c_total; int[char[]] dictionary; writefln(" lines words bytes file"); for (int i = 1; i < args.length; ++i) { char[] input; int w_cnt, l_cnt, c_cnt; int inword; int wstart; input = cast(char[])std.file.read(args[i]);]++; } writefln("%8s%8s%8s %s", l_cnt, w_cnt, c_cnt, args[i]); l_total += l_cnt; w_total += w_cnt; c_total += c_cnt; } if (args.length > 2) { writefln("--------------------------------------%8s%8s%8s total", l_total, w_total, c_total); } writefln("--------------------------------------"); foreach (char[] word1; dictionary.keys.sort) { writefln("%3d %s", dictionary[word1], word1); } return 0; } (An alternate implementation that uses buffered file I/O to handle larger files.) Two people have written C++ implementations using the C++ standard template library, wccpp1 and wccpp2. The input file alice30.txt is the text of "Alice in Wonderland." The D compiler, dmd, and the C++ compiler, dmc, share the same optimizer and code generator, which provides a more apples to apples comparison of the efficiency of the semantics of the languages rather than the optimization and code generator sophistication. Tests were run on a Win XP machine. dmc uses STLport for the template implementation. The following tests were run on linux, again comparing a D compiler (gdc) and a C++ compiler (g++) that share a common optimizer and code generator. The system is Pentium III 800MHz running RedHat Linux 8.0 and gcc 3.4.2. The Digital Mars D compiler for linux (dmd) is included for comparison. These tests compare gdc with g++ on a PowerMac G5 2x2.0GHz running MacOS X 10.3.5 and gcc 3.4.2. (Timings are a little less accurate.) wccpp2 by Allan Odgaard #include <algorithm> #include <cstdio> #include <fstream> #include <iterator> #include <map> #include <vector> bool isWordStartChar (char c) { return isalpha(c); } bool isWordEndChar (char c) { return !isalnum(c); } int main (int argc, char const* argv[]) { using namespace std; printf("Lines Words Bytes File:\n"); map<string, int> dict; int tLines = 0, tWords = 0, tBytes = 0; for(int i = 1; i < argc; i++) { ifstream file(argv[i]); istreambuf_iterator<char> from(file.rdbuf()), to; vector<char> v(from, to); vector<char>::iterator first = v.begin(), last = v.end(), bow, eow; int numLines = count(first, last, '\n'); int numWords = 0; int numBytes = last - first; for(eow = first; eow != last; ) { bow = find_if(eow, last, isWordStartChar); eow = find_if(bow, last, isWordEndChar); if(bow != eow) ++dict[string(bow, eow)], ++numWords; } printf("%5d %5d %5d %s\n", numLines, numWords, numBytes, argv[i]); tLines += numLines; tWords += numWords; tBytes += numBytes; } if(argc > 2) printf("-----------------------\n%5d %5d %5d\n", tLines, tWords, tBytes); printf("-----------------------\n\n"); for(map<string, int>::const_iterator it = dict.begin(); it != dict.end(); ++it) printf("%5d %s\n", it->second, it->first.c_str()); return 0; }
http://www.digitalmars.com/d/1.0/cppstrings.html
CC-MAIN-2014-42
refinedweb
1,559
65.22
The idea of run-time type identification (RTTI) seems fairly simple at first: It lets you find the exact type of an object when you have only a reference to the base type. However, the need for RTTI uncovers a whole plethora of interesting (and often perplexing) OO design issues, and raises fundamental questions of how you should structure your programs. Feedback This chapter looks at the ways that Java allows you to discover information about objects and classes at run time. This takes two forms: Traditional RTTI, which assumes that you have all the types available at compile time and run time, and the reflection mechanism, which allows you to discover class information solely at run time. The traditional RTTI will be covered first, followed by a discussion of reflection. Feedback. Feedback Thus, you generally create a specific object (Circle, Square, or Triangle), upcast it to a Shape (forgetting the specific type of the object), and use that anonymous Shape reference in the rest of the program. Feedback. Feedback. Feedback. Feedback. Feedback. Feedback. Feedback. Feedback To understand how RTTI works in Java, you must first know how type information is represented at run time. This is accomplished through a special kind of object called the Class object, which contains information about the class. In fact, the Class object is used to create all of the regular objects of your class. Feedback Theres a Class object for each class that is part of your program. That is, each time you write and compile a new class, a single Class object is also created (and stored, appropriately enough, in an identically named .class file). At run time, when you want to make an object of that class, the Java Virtual Machine (JVM) thats executing your program first checks to see if the Class object for that type is loaded. If not, the JVM loads it by finding the .class file with that name. Thus, a Java program isnt completely loaded before it begins, which is different from many traditional languages. Feedback Once the Class object for that type is in memory, it is used to create all objects of that type. If this seems shadowy or if you dont really believe it, heres a demonstration program to prove it: Feedback //: c10:SweetShop.java // Examination of the way the class loader works. import com.bruceeckel.simpletest.*; class Candy { static { System.out.println("Loading Candy"); } } class Gum { static { System.out.println("Loading Gum"); } } class Cookie { static { System.out.println("Loading Cookie"); } } public class SweetShop { private static Test monitor = new Test(); public static void main(String[] args) { System.out.println("inside main"); new Candy(); System.out.println("After creating Candy"); try { Class.forName("Gum"); } catch(ClassNotFoundException e) { System.out.println("Couldn't find Gum"); } System.out.println("After Class.forName(\"Gum\")"); new Cookie(); System.out.println("After creating Cookie"); monitor.expect(new String[] { "inside main", "Loading Candy", "After creating Candy", "Loading Gum", "After Class.forName(\"Gum\")", "Loading Cookie", "After creating Cookie" }); } } ///:~ Each of the classes Candy, Gum, and Cookie have a static clause that is executed as the class is loaded for the first time. Information will be printed to tell you when loading occurs for that class. In main( ), the object creations are spread out between print statements to help detect the time of loading. Feedback You can see from the output that each Class object is loaded only when its needed, and the static initialization is performed upon class loading. Feedback A particularly interesting line is: Class.forName("Gum"); This method is a static member of Class (to which all Class objects belong). A Class object is like any other object, so you can get and manipulate a reference to it (thats what the loader does). One of the ways to get a reference to the Class object is forName( ), which takes a String containing the textual name (watch the spelling and capitalization!) of the particular class you want a reference for. It returns a Class reference, which is being ignored here; the call to forName( ) is being made for its side effect, which is to load the class Gum if it isnt already loaded. In the process of loading, Gums static clause is executed. Feedback In the preceding example, if Class.forName( ) fails because it cant find the class youre trying to load, it will throw a ClassNotFoundException (ideally, exception names tell you just about everything you need to know about the problem). Here, we simply report the problem and move on, but in more sophisticated programs, you might try to fix the problem inside the exception handler. Feedback Java provides a second way to produce the reference to the Class object: the class literal. In the preceding program this would look like: Gum.class; which is not only simpler, but also safer since its checked at compile time. Because it eliminates the method call, its also more efficient. Feedback Class literals work with regular classes as well as interfaces, arrays, and primitive types. In addition, theres a standard field called TYPE that exists for each of the primitive wrapper classes. The TYPE field produces a reference to the Class object for the associated primitive type, such that: My preference is to use the .class versions if you can, since theyre more consistent with regular classes. Feedback So far, youve seen RTTI forms dont know that a Shape is necessarily a Circle, so the compiler doesnt allow you to perform a downcast assignment without using an explicit cast. Feedback Theres a third form of RTTI in Java. This is the keyword instanceof, which tells you if an object is an instance of a particular type. It returns a boolean so you use it in the form of a question, like this: if(x instanceof Dog) ((Dog)x).bark(); The if statement checks to see if the object x belongs to the class Dog before casting x to a Dog. Its important to use instanceof before a downcast when you dont have other information that tells you the type of the object; otherwise, youll end up with a ClassCastException. Feedback Ordinarily, you might be hunting for one type (triangles to turn purple, for example), but you can easily tally all of the objects by using instanceof. Suppose you have a family of Pet classes: //: c10:Pet.java package c10; public class Pet {} ///:~ //: c10:Dog.java package c10; public class Dog extends Pet {} ///:~ //: c10:Pug.java package c10; public class Pug extends Dog {} ///:~ //: c10:Cat.java package c10; public class Cat extends Pet {} ///:~ //: c10:Rodent.java package c10; public class Rodent extends Pet {} ///:~ //: c10:Gerbil.java package c10; public class Gerbil extends Rodent {} ///:~ //: c10:Hamster.java package c10; public class Hamster extends Rodent {} ///:~ In the coming example, we want to keep track of the number of any particular type of Pet, so well need a class that holds this number in an int. You can think of it as a modifiable Integer: Feedback //: c10:Counter.java package c10; public class Counter { int i; public String toString() { return Integer.toString(i); } } ///:~ Next, we need a tool that holds two things together: an indicator of the Pet type and a Counter to hold the pet quantity. That is, we want to be able to say how may Gerbil objects are there? An ordinary array wont work here, because you refer to objects in an array by their index numbers. What we want to do here is refer to the objects in the array by their Pet type. We want to associate Counter objects with Pet objects. There is a standard data structure , called an associative array, for doing exactly this kind of thing. Here is an extremely simple version: Feedback //: c10:AssociativeArray.java // Associates keys with values. package c10; import com.bruceeckel.simpletest.*; public class AssociativeArray { private static Test monitor = new Test(); private Object[][] pairs; private int index; public AssociativeArray(int length) { pairs = new Object[length][2]; } public void put(Object key, Object value) { if(index >= pairs.length) throw new ArrayIndexOutOfBoundsException(); pairs[index++] = new Object[] { key, value }; } public Object get(Object key) { for(int i = 0; i < index; i++) if(key.equals(pairs[i][0])) return pairs[i][1]; throw new RuntimeException("Failed to find key"); } public String toString() { String result = ""; for(int i = 0; i < index; i++) { result += pairs[i][0] + " : " + pairs[i][1]; if(i < index - 1) result += "\n"; } return result; } public static void main(String[] args) { AssociativeArray map = new AssociativeArray(6); map.put("sky", "blue"); map.put("grass", "green"); map.put("ocean", "dancing"); map.put("tree", "tall"); map.put("earth", "brown"); map.put("sun", "warm"); try { map.put("extra", "object"); // Past the end } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Too many objects!"); } System.out.println(map); System.out.println(map.get("ocean")); monitor.expect(new String[] { "Too many objects!", "sky : blue", "grass : green", "ocean : dancing", "tree : tall", "earth : brown", "sun : warm", "dancing" }); } } ///:~ Your first observation might be that this appears to be a general-purpose tool, so why not put it in a package like com.bruceeckel.tools? Well, it is indeed a general-purpose toolso useful, in fact, that java.util contains a number of associative arrays (which are also called maps) that do a lot more than this one does, and do it a lot faster. A large portion of Chapter 11 is devoted to associative arrays, but they are significantly more complicated, so using this one will keep things simple and at the same time begin to familiarize you with the value of associative arrays. Feedback In an associative array, the indexer is called a key, and the associated object is called a value. Here, we associate keys and values by putting them in an array of two-element arrays, which you see here as pairs. This will just be a fixed-length array that is created in the constructor, so we need index to make sure we dont run off the end. When you put( ) in a new key-value pair, a new two-element array is created and inserted at the next available location in pairs. If index is greater than or equal to the length of pairs, then an exception is thrown. Feedback To use the get( ) method, you pass in the key that you want it to look up, and it produces the associated value as the result or throws an exception if it cant be found. The get( ) method is using what is possibly the least efficient approach imaginable to locate the value: starting at the top of the array and using equals( ) to compare keys. But the point here is simplicity, not efficiency, and the real maps in Chapter 11 have solved the performance problems, so we dont need to worry about it here. Feedback The essential methods in an associative array are put( ) and get( ), but for easy display, toString( ) has been overridden to print the key-value pairs. To show that it works, main( ) loads an AssociativeArray with pairs of strings and prints the resulting map, followed by a get( ) of one of the values. Feedback Now that all the tools are in place, we can use instanceof to count Pets: //: c10:PetCount.java // Using instanceof. package c10; import com.bruceeckel.simpletest.*; import java.util.*; public class PetCount { private static Test monitor = new Test(); private static Random rand = new Random(); static String[] typenames = { "Pet", "Dog", "Pug", "Cat", "Rodent", "Gerbil", "Hamster", }; // Exceptions thrown to console: public static void main(String[] args) { Object[] pets = new Object[15]; try { Class[] petTypes = { Class.forName("c10.Dog"), Class.forName("c10.Pug"), Class.forName("c10.Cat"), Class.forName("c10.Rodent"), Class.forName("c10.Gerbil"), Class.forName("c10.Hamster"), }; for(int i = 0; i < pets.length; i++) pets[i] = petTypes[rand.nextInt(petTypes.length)] .newInstance(); } catch(InstantiationException e) { System.out.println("Cannot instantiate"); System.exit(1); } catch(IllegalAccessException e) { System.out.println("Cannot access"); System.exit(1); } catch(ClassNotFoundException e) { System.out.println("Cannot find class"); System.exit(1); } AssociativeArray map = new AssociativeArray(typenames.length); for(int i = 0; i < typenames.length; i++) map.put(typenames[i], new Counter()); for(int i = 0; i < pets.length; i++) { Object o = pets[i]; if(o instanceof Pet) ((Counter)map.get("Pet")).i++; if(o instanceof Dog) ((Counter)map.get("Dog")).i++; if(o instanceof Pug) ((Counter)map.get("Pug")).i++; if(o instanceof Cat) ((Counter)map.get("Cat")).i++; if(o instanceof Rodent) ((Counter)map.get("Rodent")).i++; if(o instanceof Gerbil) ((Counter)map.get("Gerbil")).i++; if(o instanceof Hamster) ((Counter)map.get(( "%% (Pet|Dog|Pug|Cat|Rodent|Gerbil|Hamster)" + " : \\d+", typenames.length) }); } } ///:~ In main( ) an array petTypes of Class objects is created using Class.forName( ). Since the Pet objects are in package c09, the package name must be used when naming the classes. Feedback Next, the pets array is filled by randomly indexing into petTypes and using the selected Class object to generate a new instance of that class with Class.newInstance( ), which uses the default (no-arg) class constructor to generate the new object. Feedback Both forName( ) and newInstance( ) can generate exceptions, which you can see handled in the catch clauses following the try block. Again, the names of the exceptions are relatively useful explanations of what went wrong (IllegalAccessException relates to a violation of the Java security mechanism). Feedback After creating the AssociativeArray, it is filled with key-value pairs of pet names and Counter objects. Then each Pet in the randomly-generated array is tested and counted using instanceof. The array and AssociativeArray are printed so you can compare the results. Feedback Theres a rather narrow restriction on instanceof: You can compare it to a named type only, and not to a Class object. In the preceding example you might feel that its tedious to write out all of those instanceof expressions, and youre right. But there is no way to cleverly automate instanceof by creating an array of Class objects and comparing it to those instead (stay tunedyoull see an alternative). This isnt as great a restriction as you might think, because youll eventually understand that your design is probably flawed if you end up writing a lot of instanceof expressions. Feedback Of course, this example is contrivedyoud probably put a static field in each type and increment it in the constructor to keep track of the counts. You would do something like that if you had control of the source code for the class and could change it. Since this is not always the case, RTTI can come in handy. Feedback Its interesting to see how the PetCount.java example can be rewritten using class literals. The result is cleaner in many ways: //: c10:PetCount2.java // Using class literals. package c10; import com.bruceeckel.simpletest.*; import java.util.*; public class PetCount]; if(o instanceof Pet) ((Counter)map.get("class c10.Pet")).i++; if(o instanceof Dog) ((Counter)map.get("class c10.Dog")).i++; if(o instanceof Pug) ((Counter)map.get("class c10.Pug")).i++; if(o instanceof Cat) ((Counter)map.get("class c10.Cat")).i++; if(o instanceof Rodent) ((Counter)map.get("class c10.Rodent")).i++; if(o instanceof Gerbil) ((Counter)map.get("class c10.Gerbil")).i++; if(o instanceof Hamster) ((Counter)map.get("class c10) }); } } ///:~ Here, the typenames array has been removed in favor of getting the type name strings from the Class object. Notice that the system can distinguish between classes and interfaces. Feedback You can also see that the creation of petTypes does not need to be surrounded by a try block since its evaluated at compile time and thus wont throw any exceptions, unlike Class.forName( ). Feedback When the Pet objects are dynamically created, you can see that the random number is restricted so it is between one and petTypes.length and does not include zero. Thats because zero refers to Pet.class, and presumably a generic Pet object is not interesting. However, since Pet.class is part of petTypes, the result is that all of the pets get counted. Feedback The Class.isInstance method provides a way to dynamically call the instanceof operator. Thus, all those tedious instanceof statements can be removed in the PetCount example: //: c10:PetCount3.java // Using isInstance() package c10; import com.bruceeckel.simpletest.*; import java.util.*; public class PetCount]; // Using Class.isInstance() to eliminate // individual instanceof expressions: for(int j = 0; j < petTypes.length; ++j) if(petTypes[j].isInstance(o)) ((Counter)map.get(petTypes[j].toString()))) }); } } ///:~ You can see that the isInstance( ) method has eliminated the need for the instanceof expressions. In addition, this means that you can add new types of pets simply by changing the petTypes array; the rest of the program does not need modification (as it did when using the instanceof expressions). Feedback When querying for type information, theres an important difference between either form of instanceof (that is, instanceof or isInstance( ), which produce equivalent results) and the direct comparison of the Class objects. Heres an example that demonstrates the difference: //: c10:FamilyVsExactType.java // The difference between instanceof and class package c10; import com.bruceeckel.simpletest.*; class Base {} class Derived extends Base {} public class FamilyVsExactType { private static Test monitor = new Test(); static void test(Object x) { System.out.println("Testing x of type " + x.getClass()); System.out.println("x instanceof Base " + (x instanceof Base)); System.out.println("x instanceof Derived " + (x instanceof Derived)); System.out.println("Base.isInstance(x) " + Base.class.isInstance(x)); System.out.println("Derived.isInstance(x) " + Derived.class.isInstance(x)); System.out.println("x.getClass() == Base.class " + (x.getClass() == Base.class)); System.out.println("x.getClass() == Derived.class " + (x.getClass() == Derived.class)); System.out.println("x.getClass().equals(Base.class)) "+ (x.getClass().equals(Base.class))); System.out.println( "x.getClass().equals(Derived.class)) " + (x.getClass().equals(Derived.class))); } public static void main(String[] args) { test(new Base()); test(new Derived()); monitor.expect(new String[] { "Testing x of type class c10.Base", "x instanceof Base true", "x instanceof Derived false", "Base.isInstance(x) true", "Derived.isInstance(x) false", "x.getClass() == Base.class true", "x.getClass() == Derived.class false", "x.getClass().equals(Base.class)) true", "x.getClass().equals(Derived.class)) false", "Testing x of type class c10.Derived", "x instanceof Base true", "x instanceof Derived true", "Base.isInstance(x) true", "Derived.isInstance(x) true", "x.getClass() == Base.class false", "x.getClass() == Derived.class true", "x.getClass().equals(Base.class)) false", "x.getClass().equals(Derived.class)) true" }); } } ///:~ The test( ) method performs type checking with its argument using both forms of instanceof. It then gets the Class reference and uses == and equals( ) to test for equality of the Class objects. ==, there is no concern with inheritanceits either the exact type or it isnt. Feedback Java performs its RTTI using the Class object, even if youre doing something like a cast. The class Class also has a number of other ways you can use RTTI. Feedback First, you must get a reference to the appropriate Class object. One way to do this, as shown in the previous example, is to use a string and the Class.forName( ) method. This is convenient because you dont need an object of that type in order to get the Class reference. However, if you do already have an object of the type youre interested in, you can fetch the Class reference by calling a method thats part of the Object root class: getClass( ). This returns the Class reference representing the actual type of the object. Class has many interesting methods demonstrated in the following example: Feedback //: c10:ToyTest.java // Testing class Class. import com.bruceeckel.simpletest.*; interface HasBatteries {} interface Waterproof {} interface Shoots {} class Toy { // Comment out the following default constructor // to see NoSuchMethodError from (*1*) Toy() {} Toy(int i) {} } class FancyToy extends Toy implements HasBatteries, Waterproof, Shoots { FancyToy() { super(1); } } public class ToyTest { private static Test monitor = new Test(); static void printInfo(Class cc) { System.out.println("Class name: " + cc.getName() + " is interface? [" + cc.isInterface() + "]"); } public static void main(String[] args) { Class c = null; try { c = Class.forName("FancyToy"); } catch(ClassNotFoundException e) { System.out.println("Can't find FancyToy"); System.exit(1); } printInfo(c); Class[] faces = c.getInterfaces(); for(int i = 0; i < faces.length; i++) printInfo(faces[i]); Class cy = c.getSuperclass(); Object o = null; try { // Requires default constructor: o = cy.newInstance(); // (*1*) } catch(InstantiationException e) { System.out.println("Cannot instantiate"); System.exit(1); } catch(IllegalAccessException e) { System.out.println("Cannot access"); System.exit(1); } printInfo(o.getClass()); monitor.expect(new String[] { "Class name: FancyToy is interface? [false]", "Class name: HasBatteries is interface? [true]", "Class name: Waterproof is interface? [true]", "Class name: Shoots is interface? [true]", "Class name: Toy is interface? [false]" }); } } ///:~ You can see that class FancyToy is quite complicated, since it inherits from Toy and implements the interfaces HasBatteries, Waterproof, and Shoots. In main( ), a Class reference is created and initialized to the FancyToy Class using forName( ) inside an appropriate try block. Feedback The Class.getInterfaces( ) method returns an array of Class objects representing the interfaces that are contained in the Class object of interest. Feedback If you have a Class object, you can also ask it for its direct base class using getSuperclass( ). This, of course, returns a Class reference that you can further query. This means that at run time, you can discover an objects entire class hierarchy. Feedback The newInstance( ) method of Class can, at first, seem like just another way to clone( ) an object. However, you can create a new object with newInstance( ) without an existing object, as seen here, because there is no Toy objectonly cy, which is a reference to ys Class object. This is a way to implement a virtual constructor, which allows you to say I dont know exactly what type you are, but create yourself properly anyway. In the preceding example, cy is just a Class reference with no further type information known at compile time. And when you create a new instance, you get back an Object reference. But that reference is pointing to a Toy object. Of course, before you can send any messages other than those accepted by Object, you have to investigate it a bit and do some casting. In addition, the class thats being created with newInstance( ) must have a default constructor. In the next section, youll see how to dynamically create objects of classes using any constructor, with the Java reflection API (Application Programmer Interface). Feedback The final method in the listing is printInfo( ), which takes a Class reference and gets its name with getName( ), and finds out whether its an interface with isInterface( ). Thus, with the Class object you can find out just about everything you want to know about an object. Feedback If you dont know the precise type of an object, RTTI will tell you. However, theres a limitation: The type must be known at compile time in order for you to be able to detect it using RTTI and do something useful with the information. Put another way, the compiler must know about all the classes youre working with for RTTI. Feedback This doesnt seem like that much of a limitation at first, but suppose youre given a reference to an object thats not in your program space. In fact, the class of the object isnt even available to your program at compile time. For example, suppose you get a bunch of bytes from a disk file or from a network connection, and youre told that those bytes represent a class. Since the compiler cant know about this class that shows up later while its compiling the code for your program, how can you possibly use such a class? Feedback, that it exposes parts of itself, and that it allows provides a structure for component-based programming through JavaBeans (described in Chapter 14). Feedback Another compelling motivation for discovering class information at run time is to provide the ability to create and execute objects on remote platforms across a network. This is called Remote Method Invocation (RMI), and it allows a Java program to have objects distributed across many machines. This distribution can happen for a number of reasons. For example, perhaps youre doing a computation-intensive task, and in order to speed things up, you want to break it up and put pieces on machines that are idle. In other situations you might want to place code that handles particular types of tasks (e.g., Business Rules in a multitiermatrix inversions, for examplebut inappropriate or too expensive for general-purpose programming. Feedback The class Class (described previously in this chapter) supports the concept of reflection, and the the JDK documentation.) Thus, the class information for anonymous objects can be completely determined at run time, and nothing need be known at compile time. Feedback Its important to realize that theres nothing magic about reflection. When you. Feedback You. Feedback. Feedback. Feedback.. Feedback. Feedback. Feedback. Feedback Chapter 14 contains a GUI version of this program (customized to extract information for Swing components) so you can leave it running while youre writing code, to allow quick lookups. Feedback R. Feedback. Feedback. Feedback). Feedback Solutions to selected exercises can be found in the electronic document The Thinking in Java Annotated Solution Guide, available for a small fee from. [50] Especially in the past. However, Sun has greatly improved its HTML Java documentation so that its easier to see base-class methods.
http://www.faqs.org/docs/think_java/TIJ312.htm
CC-MAIN-2017-04
refinedweb
4,214
57.06
#include <sys/types.h> #include <sys/ddi.h> int copyout(const void *driverbuf, void *userbuf, size_t cn); This interface is obsolete. ddi_copyout(9F) should be used instead. Source address in the driver from which the data is transferred. Destination address in the user program to which the data is transferred. Number of bytes moved. copyout() copies data from driver buffers to user data space. Addresses that are word-aligned are moved most efficiently. However, the driver developer is not obligated to ensure alignment. This function automatically finds the most efficient move algorithm according to address alignment. Under normal conditions, a 0 is returned to indicate a successful copy. Otherwise, a a −1 is returned to the caller, driver entry point routines should return EFAULT. copy). If the specified argument contains an invalid address, an error code is returned. 1 struct device { /* layout of physical device registers */ 2 int control; /* physical device control word */ 3 int status; /* physical device status word */ 4 short recv_char; /* receive character from device */ 5 short xmit_char; /* transmit character to device */ 6 }; 7out(rp, arg, sizeof(struct device))) 19 return(EFAULT); 20 break; 21 ... 22 } 23 ... 24 } See attributes(5) for a description of the following attributes: attributes(5), ioctl(9E) , bcopy(9F), copyout(9F) instead. Driver defined locks should not be held across calls to this function. copyout() should not be used from a streams driver. See M_COPYIN and M_COPYOUT in STREAMS Programming Guide .
http://docs.oracle.com/cd/E36784_01/html/E36886/copyout-9f.html
CC-MAIN-2017-04
refinedweb
238
58.89
RunFromProcess provides a console application that you can use to launch an application as a child of another process, under the same system user and having exactly the same security parameters as the parent process. The syntax is pretty simple, as described when launching RunFromProcess in Windows. You must first specify the name of the parent process or its ID, followed by the complete path of the program to run as the child. The latter process inherits the user and the security parameters of the parent. If you are running a version of Windows after Vista with the User Account Control turned on, administrative rights might be needed to be able to use RunFromProcess. In other words, you might be required to make use of the “admin” argument before all the other arguments and execute the command afterwards. Otherwise, the application might fail to work. Additionally, the “nomsg” prefix, placed before all the other arguments, prevents RunFromProcess from displaying any error message. By default, a program scheduled to run in Windows launches under a SYSTEM account but with RunFromProcess you can launch it under the currently logged-on user. This is one of the cases this application comes in handy. RunFromProcess facilitates launching a process as the child of another process in Windows. As it involves working with processes and understanding how Windows works under the hood, it is not suitable for beginners but it can be of use to tech-savvy, advanced users. RunFromProcess 2013 Crack + Free Registration Code RunFromProcess Crack Keygen is a user32.dll function to start an application. When it’s called, it takes the name of the application being started as its first parameter, along with a friendly name to be displayed to the user in the system tray. The application will be launched under the user making the call, and the process will run with the same user/permissions as the parent process. In other words, the parent process gets the child’s context and permissions. The process being launched can’t access any system resources (i.e., it can’t lock the cursor). Another parameter has been added to allow the parent to specify whether the child should run as a console or a windowed application. To use this function, it first checks whether the program was scheduled to run under a user account that has UAC enabled. If not, it calls the function EnableRaising of the application’s main executable module (m_hProcess of the WndProc) as described in RegisterWindowMessage. If it is enabled, it checks for the flag which makes the main executable module ask if the app wants to run under the user account that called this function. It then takes the current user name and path, and uses it to determine which security context (user and security level) the program should run under. It then calls CreateProcessA to launch the application. Sample Usage: First you must enable RunFromProcess: HMODULE hmodDLL = LoadLibrary( TEXT(“kernel32.dll”) ); SetWindowsHookEx( WH_SHELL, CallbackProc, hmodDLL, 0 ); Then you can use RunFromProcess to launch your own application under the current user account: int main( int argc, char *argv[] ) { LPCTSTR pszCmdFileName = argv[0]; LPCTSTR pszExecutable = argv[1]; EnableRaising( TRUE ); // Let’s find out the parent process’ process id DWORD pid = GetProcessIdByName( pszExecutable ); PROCESS_INFORMATION piProcInfo; RunFromProcess 2013 Serial Key Supplies a simple console application to launch a program as a child process of another program. This program must be a built-in Windows program. Programs to launch: “notepad.exe” – An easy way to write a quick one liner. “notepad.exe” – A program I always have ready. RunFromProcess Crack Mac Syntax: RunFromProcess Crack Mac [“executable name”, [“arguments”], [“arguments”], [“arguments”], [], [“arguments”], [“arguments”], [“arguments”], [], [“arguments”] ] Note: the “nomsg” prefix is a command-line switch to suppress any error messages displayed by RunFromProcess. Examples: RunFromProcess “notepad.exe” “MyApp.exe” RunFromProcess “notepad.exe” “C:\App1.exe” “C:\App2.exe” Notes: You must have a Windows program installed as “executable name”. You may use an argument with up to 10 arguments. The path to the program cannot contain wildcards. Notes: If you wish to schedule a program on login, you can’t use the above syntax but you need to put the command in a batch file, scheduled to run at login. You can read about scheduling in the accepted answer of the following question: How to launch a program at Windows login, not using a GUI? Other similar tools that can be used to launch a child process within a parent process are the following: StartsHook: Start a Windows “console helper” process using CMD.EXE as your handler. The helper then executes the startup helper CMD.EXE with the startup parameter “-sta”. This launch helper runs as SYSTEM under the logged-on user’s account. StartService: Start a Windows “console helper” process using SC.EXE as your handler. The helper then executes the startup helper SC.EXE with the startup parameter “-staserver”. This launch helper runs as SYSTEM under the logged-on user’s account. These are all I can think of right now. I’ll try to update this answer if I find something new. Note: I am not affiliated with the authors of any of these tools. 09e8f5149f RunFromProcess 2013 Runs a specified program as a child of the specified parent. Currently, the application will be launched as the child of the specified parent even though it is actually being launched under different system accounts. If the current user’s credentials do not permit the specified user access to the specified parent, the specified application will fail to run and the specified error message will be displayed. The Application.RunFromProcess method should be used instead because it does not require administrator rights. However, Application.RunFromProcess doesn’t provide the automation you need to achieve high-level of functionality. C# Code: using System; using System.Diagnostics; using System.IO; namespace RunFromProcess { /// /// Host a process as a child of the current application. /// /// Executable file path. This is the command to be executed. /// Executable application name. This is the application to be launched as a child of the current process. /// Parameters to be passed to the application. /// If either /// or /// is /// null. /// /// If has /// an unexpected syntax. For example, if does not look like a valid /// executable file or if the name of the executable /// file is too long, or if the path to has unanticipated paths /// such as %WINDIR%. What’s New in the? Launches an application as a child of another running process. Parameters: – For the first argument you specify the parent process. RunFromProcess will provide you with the process ID or the full path of the parent. – For the second argument you provide the name of the program to run. A full path is expected. If the parent process doesn’t have a console, RunFromProcess will launch the child process in a separate console window. – For all the following arguments you can provide a description (utf8 encoded). – You may provide additional arguments if needed. You can access them with GetChildAsArray() and ClearGetChildAsArray(). Results: If the program succeeds it returns a status code of 0 and the process handle of the launched process. If the program fails it returns a status code of 1 and the process handle of the parent process. NOTE: RunFromProcess closes the process handle returned by the parent process. Example: package main import ( “fmt” “syscall” “os” “os/exec” ) func main() { createConsole(GetRootAsArray()) fmt.Println(“Press any key to exit…”) key, _ := syscall.ReadKey() fmt.Println(“You pressed:”, key) if err := wait(); err!= nil { fmt.Println(“Child process exited with code:”, err.Code) } } // While waiting for child to start or to be killed func wait() error { id, err := executeCommand(“notepad.exe”, nil) if err!= nil { return err } parent, err := runFromProcess(id) if err!= nil { return err } status, err := runFromProcess(parent.ID, “processID”) if err!= nil { return err } if status == 0 { System Requirements: 1GB RAM 100MB HDD OS: Windows 8.1 64 bit / Windows 7 64 bit Graphics: NVIDIA GeForce GTX 560 or ATI Radeon HD 5770 DirectX: Version 11 Network: Broadband Internet connection Sound: DirectX compatible sound card Additional Notes: Steam version is download only The game is an Xbox 360 game so if you have an Xbox 360 you will be able to play on that. Controls: Keyboard / Controller (X360, PS3, PC) This is
https://epkrd.com/runfromprocess-free-download/
CC-MAIN-2022-27
refinedweb
1,384
65.52
A while ago I made two posts: Algorithm Selection was about different algorithms for scaling digital sound, and Experimenting with Inline Assembly in C talking about how to use Inline Assembly in C. For this lab, I will join both things by making a better algorithm using Inline Assembly. Here is the logic behind it: Instead of going through every single element in the array, we can use vector registers to operate with 8 elements at a time (8 elements of 16 bit each = 128 bits). To make sure the operation is as efficient as possible, we will implement this with inline assembly. And here are the changes: // This variable will hold the last address of the array int16_t* limit; // Will be used for the assembler code: the volume will now be // stored in register 22, and a cursor for the array (for looping) // will be stored in register r20 // - Question: Is there an alternate approach for this? // - Answer: Yes. Instead of naming the registers we are going to use, // we can leave it to the compiler. If we do this, the asm() instruction // will have to change, since we will not be able to use the name of // the register anymore register int16_t volumeInt asm("r22"); register int16_t *arrCursor asm("r20"); // First and last address of the array arrCursor = arr; limit = arr + LENGTH; Those are the variables I will need. Now, for the algorithm that goes inside the loop: // Here I am duplicating the volume factor in vector v1.8 // - Question: What do you mean by "duplicating"? // - Answer: By duplicating, I mean that the volume factor // will be repeated through the vector. For example, say the // volume factor is "19" and the vector has 8 lanes. The vector // register will then be filled as "1919191919191919" asm("dup v1.8h, w22"); // While we did not reach the last element of the array... while(arrCursor < limit) { asm( // Load eight shorts into the vector v0.8 (q0) "ldr q0, [x20] " // Multiply vector v0.8 by the volume factor and save // into v0.8 "sqdmulh v0.8h, v0.8h, v1.8h " // Store the value of v0.8 back in the array (all 8 shorts at once) // and advance the cursor to the next 8 shorts (16 bytes) "str q0, [x20],#16 " // Using "arrCursor" as input/output : "+r"(arrCursor) // Specifying that "limit" is a read-only register : "r"(limit) : ); } Another question that arises is: do we need the input/output sections in the inline assembly in this case, since we are addressing the registers directly? In theory, no, we wouldn't need it; however, if we do not specify it, the compiler will be confused: the compiler does not know what the asm procedure is doing, so it will see it as a "black box". Since it is a black box, the compiler is unaware that the controls for the loop while(arrCursor < limit) are being changed in it. In other words, the compiler will think that it is actually an infinite loop, and will replace it with a faster alternative. We explicitly tell the compiler that the arrCursor is being modified, so it will be aware that the loop is not infinite, and must be checked every iteration. The result was slightly better than the previous implementation (which was around 0.22 seconds): the new version can finish in around 0.19 seconds. My guess is that the previous implementation was already been vectorized by the compiler, so the difference was not too significant. Inline Assembly in mjpegtools The next part of the lab is to pick an open source library that uses Inline Assembly. The library I choose is called mjpegtools. According to the documentation, Programs for MJPEG recording and playback and simple cut-and-paste editting and MPEG compression of audio and video under Linux. These are the instances of Inline Assembly I found: file utils/cpuinfo.c // In the instructions below, the application is moving the values // from register B to register source index, placing the bytes 0x0f // and 0xa2, and then exchanging the contents of the two registers. // I don't know what the instructions from those bytes are, so sadly, // I can't really tell what these sections are doing or if they could // be better. // The platform is obviously for x86, but the variation seem to be if // the platform is 64 bits or not: the 32 bits will use the prefix "e", // while the 64 bit version will use "r" (extended registers) // What happens on other platforms? If I did not miss anyting, there // are no other platforms supported. #define CPUID ".byte 0x0f, 0xa2; " #ifdef __x86_64__ asm("mov %%rbx, %%rsi" #else asm("mov %%ebx, %%esi" #endif CPUID"" #ifdef __x86_64__ "xchg %%rsi, %%rbx" #else "xchg %%esi, %%ebx" #endif // ... #define RDTSC ".byte 0x0f, 0x31; " asm volatile (RDTSC : "=A"(i) : ); file utils/cpu_accel.c #ifdef HAVE_X86CPU /* Some miscelaneous stuff to allow checking whether SSE instructions cause illegal instruction errors. */ static sigjmp_buf sigill_recover; static RETSIGTYPE sigillhandler(int sig ) { siglongjmp( sigill_recover, 1 ); } typedef RETSIGTYPE (*__sig_t)(int); static int testsseill() { int illegal; #if defined(__CYGWIN__) /* SSE causes a crash on CYGWIN, apparently. Perhaps the wrong signal is being caught or something along those line ;-) or maybe SSE itself won't work... */ illegal = 1; #else __sig_t old_handler = signal( SIGILL, sigillhandler); if( sigsetjmp( sigill_recover, 1 ) == 0 ) { asm ( "movups %xmm0, %xmm0" ); illegal = 0; } else illegal = 1; signal( SIGILL, old_handler ); #endif return illegal; } static int x86_accel (void) { long eax, ebx, ecx, edx; int32_t AMD; int32_t caps; /* Slightly weirdified cpuid that preserves the ebx and edi required by gcc for PIC offset table and frame pointer */ #if defined(__LP64__) || defined(_LP64) # define REG_b "rbx" # define REG_S "rsi" #else # define REG_b "ebx" # define REG_S "esi" #endif #define cpuid(op,eax,ebx,ecx,edx) asm ( "push %%"REG_b" " "cpuid " "mov %%"REG_b", %%"REG_S" " "pop %%"REG_b" " : "=a" (eax), "=S" (ebx), "=c" (ecx), "=d" (edx) : "a" (op) : "cc", "edi") asm ("pushf" "pop %0" "mov %0,%1" "xor $0x200000,%0" "push %0" "popf" "pushf" "pop %0" : "=a" (eax), "=c" (ecx) : : "cc"); if (eax == ecx) // no cpuid return 0; cpuid (0x00000000, eax, ebx, ecx, edx); if (!eax) // vendor string only return 0; AMD = (ebx == 0x68747541) && (ecx == 0x444d4163) && (edx == 0x69746e65); cpuid (0x00000001, eax, ebx, ecx, edx); if (! (edx & 0x00800000)) // no MMX return 0; caps = ACCEL_X86_MMX; /* If SSE capable CPU has same MMX extensions as AMD and then some. However, to use SSE O.S. must have signalled it use of FXSAVE/FXRSTOR through CR4.OSFXSR and hence FXSR (bit 24) here */ if ((edx & 0x02000000)) caps = ACCEL_X86_MMX | ACCEL_X86_MMXEXT; if( (edx & 0x03000000) == 0x03000000 ) { /* Check whether O.S. has SSE support... has to be done with exception 'cos those Intel morons put the relevant bit in a reg that is only accesible in ring 0... doh! */ if( !testsseill() ) caps |= ACCEL_X86_SSE; } cpuid (0x80000000, eax, ebx, ecx, edx); if (eax < 0x80000001) // no extended capabilities return caps; cpuid (0x80000001, eax, ebx, ecx, edx); if (edx & 0x80000000) caps |= ACCEL_X86_3DNOW; if (AMD && (edx & 0x00400000)) // AMD MMX extensions { caps |= ACCEL_X86_MMXEXT; } return caps; } #endif #ifdef HAVE_ALTIVEC /* AltiVec optimized library for MJPEG tools MPEG-1/2 Video Encoder * Copyright (C) 2002 James Klicman <james@klicman.org> * * The altivec_detect() function has been moved here to workaround a bug in a * released version of GCC (3.3.3). When -maltivec and -mabi=altivec are * specified, the bug causes VRSAVE instructions at the beginning and end of * functions which do not use AltiVec. GCC 3.3.3 also lacks support for * '#pragma altivec_vrsave off' which would have been the preferred workaround. * * This AltiVec detection code relies on the operating system to provide an * illegal instruction signal if AltiVec is not present. It is known to work * on Mac OS X and Linux. */ static sigjmp_buf jmpbuf; static void sig_ill(int sig) { siglongjmp(jmpbuf, 1); } int detect_altivec() { volatile int detected = 0; /* volatile (modified after sigsetjmp) */ struct sigaction act, oact; act.sa_handler = sig_ill; sigemptyset(&act.sa_mask); act.sa_flags = 0; if (sigaction(SIGILL, &act, &oact)) { perror("sigaction"); return 0; } if (sigsetjmp(jmpbuf, 1)) goto noAltiVec; /* try to read an AltiVec register */ altivec_copy_v0(); detected = 1; noAltiVec: if (sigaction(SIGILL, &oact, (struct sigaction *)0)) perror("sigaction"); return detected; } #endif The code above is a bit cryptic, to say the least. Again, the platform is x86 and other platforms don't see to be supported. What it does is, again, not exactly obvious, but I can guess: the Inline Assembly seems to deal a lot with vector registers and vectorization, so it probably sets up a very efficient way to deal with multiple data that needs a single instruction (SIMD). This makes sense, since it is a library for MJPEG, dealing with big streams of data. Since I am not exactly sure what the code does, I can't say I have a strong opinion about it. It does seem like it has a good reason to be there: enforcing vectorization. I am not sure, however, if it really needs to be written in assembly or could be left to the compiler to optimize it. I would say that the loss in portability is definitely a problem, since other architectures are becoming more popular now: it would probably be a good idea to write more cases for the other platforms, or look for an alternative solution.
https://hcoelho.com/blog/50/MoreInlineAssembly
CC-MAIN-2022-05
refinedweb
1,529
56.49
Answered by: Rare unusual crash where public static readonly variables are null Question - User1683 posted I'm experiencing a semi-rare issue where accessing public static readonly instances is throwing NullReferenceException. I really don't know where to begin trying to figure this out, and my attempts to reproduce it reliably have failed. I know it's happening from crash reports provided from Crashlytics, and by occasional log entries during development. Here is a sample of what the problem code looks like: public class MySingleton { public static readonly MySingleton Instance = new MySingleton(); } The caller will do MySingleton.Instance, and it will throw NullReferenceException. The greater mystery is that it can succeed for some time and then fail later. Currently occurring on Xamarin iOS 7.2.3, both in Release (llvm/sgen/refcount/type sharing) and Debug (sgen/refcount/type sharing). Anyone experienced this or have any ideas on how I might create a test case for it?Wednesday, August 6, 2014 4:49 AM Answers All replies - User1683 posted I think this issue may share the same root cause as this bug:, August 6, 2014 6:03 AM - User1683 posted Minor correction, the last recorded example of this was with 7.2.0. I don't presently have evidence of it occurring on 7.2.3, even though I feel sure it has.Wednesday, August 6, 2014 7:57 AM - User12119 posted I am experiencing a rare but very real problem with Xamarin.iOS 8.4.0.16 when trying int to string conversion. It is so rare that I cannot reproduce it myself. But in production it occurs about 8% of the time, seemingly with faster devices. Saw your post on I'm trying to figure out how to fix this. I thought of making an initial call to let the static constructor finish. But I have no way of knowing if this will fix it, because I cannot reproduce on my devices!Saturday, November 15, 2014 10:28 PM - User12119 posted Actually my idea would not fix this problem. How the heck do you make sure static readonly variables inside a private class are initialized!? In other words, how to make this not return null?? namespace System { static class EmptyArray<T> { public static readonly T[] Value = new T [0]; } }Saturday, November 15, 2014 10:31 PM - User39 posted @OZGURAKSU?: can you post stack traces / crash reports?Monday, November 17, 2014 10:56 AM - User12119 posted @RolfBjarneKvinge? Hi Rolf. I have limited reporting from Production so stack trace is limited but clear enough: Object reference not set to an instance of an object at System.NumberFormatter.ResetCharBuf (Int32 size) [0x00000] in <filename unknown>:0 at System.NumberFormatter.FastIntegerToString (Int32 value, IFormatProvider fp) [0x00000] in <filename unknown>:0 Looking at Mono's source I have identified that a call to EmptyArray<char>.Valuemust be returning null. I'm attempting a fix by calling ToString on an Int32 prior to any thread launches, but I don't have enough detailed know-how to be sure this will be a fix. Maybe you could comment. As I've mentioned, I am not able to reproduce this on the devices available to me. I can tell you the devices that had this error on launch so far: iPad Air iPad (4th generation) iPhone 5 iOS versions: 7.1.2 8.1 NOTE: Second launch on some of these worked fine.Monday, November 17, 2014 11:09 AM - User39 posted @OZGURAKSU?: yeah, looks like you're running into bug #16489. You can always try to call ToString on an Int32 prior to any thread launching, but my initial hunch would be that it won't help (I think somehow that static field got nulled out, and nothing will make it change back). My advice would be to reopen that bug report, and ask for ideas how to help track it down.Monday, November 17, 2014 1:12 PM - User12119 posted @RolfBjarneKvinge? Actually there is another bug report confirmed that is still open here: I wish I understood Zoltan's comment at the end there.Monday, November 17, 2014 1:18 PM - User12119 posted @RolfBjarneKvinge? You may be right about it being somehow set to null. Because I observed now that it happens during regular app usage even after initialization. That means there's nothing I can do at this time short of avoiding ToString, which is not an option. Thanks anyway Rolf. I will reopen that bug to hopefully get some attention to this.Monday, November 17, 2014 2:11 PM - User39 posted @OZGURAKSU: Zoltan's comment is about Mono internals, there's no need to understand it (there's nothing you can do on your side). I can also reproduce the issue on my Mac with the test case from bug #23242.Monday, November 17, 2014 3:36 PM - User12119 posted @RolfBjarneKvinge? That's good news. Thanks very much Rolf. I appreciate it.Monday, November 17, 2014 6:34 PM - User12119 posted @RolfBjarneKvinge? Rolf can I ask you a question? I noticed that you had LLVM enabled for your test. Marek before you didn't and they didn't run into it. I had also used LLVM to help improve performance. Could disabling LLVM make the difference?Monday, November 17, 2014 7:20 PM - User12119 posted To anyone reading this with similar problems: I suspect LLVM is the culprit, but I will not know for sure until I release my fix and see the results. I have encountered Null Exceptions in non-static variables as well and thought it was an application bug but some variables that should not be null are being set to null somehow. I'd advise anyone reading this to thoroughly test LLVM compiled binaries, especially if you are making extensive use of background threads and/or have an event-driven architecture as I do.Monday, November 17, 2014 9:02 PM - User1683 posted Just wanted to chime in and say that yes, we still get variations of this crash from time to time. We had to disable things like logging in our released apps (which used int.ToString() frequently) to reduce how often it happened. Frankly I am a bit disappointed it took this long for anyone from Xamarin to reply to this thread.Tuesday, November 18, 2014 12:05 AM - User1683 posted @OZGURAKSU We also use LLVM, but I can't recall if this started happening before or after we enabled it. I've only reproduced this accidentally a couple of times during development, so it's extremely hard to build a test case around. Every time we release a new version of our app with a new Xamarin.iOS version, it happens in the wild atleast a half dozen times in the first couple of weeks with various configurations and devices.Tuesday, November 18, 2014 12:08 AM - User12119 posted @Jahmai? Since there is not much else to do, I'd rather sacrifice the performance improvement than lose customers due to arbitrary exceptions at this time. I'm going to try disabling LLVM and I will report back on this thread whether or not this indeed was the problem.Tuesday, November 18, 2014 1:23 AM - User1683 posted @OZGURAKSU Very reasonable course of action. Look forward to hearing about the result. Thanks.Tuesday, November 18, 2014 2:26 AM - User1683 posted Thanks Rolf, what Xamarin.iOS release can we expect this in?Tuesday, November 18, 2014 9:41 AM - User1683 posted ThanksTuesday, November 18, 2014 9:44 AM - User12119 posted FYI I'm not seeing any error with the LLVM-disabled update.Thursday, November 27, 2014 11:52 AM - User12119 posted Actually I did see it again. It is really random. So it's probably not LLVM issue.Wednesday, December 10, 2014 7:44 AM - User39 posted @Jahmai: The fix will be included in Xamarin.iOS 8.6.Wednesday, December 10, 2014 9:22 AM - User1683 posted @RolfBjarneKvinge? Great! Any idea when that might be? ;)Wednesday, December 10, 2014 9:44 AM - User39 posted @Jahmai: the first Alpha should be out this week, and the Stable release is planned for early January.Wednesday, December 10, 2014 9:48 AM - User12119 posted @RolfBjarneKvinge? Thanks for that update Rolf.Friday, December 12, 2014 8:30 PM
https://social.msdn.microsoft.com/Forums/en-US/c7b92c7d-8f73-4469-966d-4c57d52701d5/rare-unusual-crash-where-public-static-readonly-variables-are-null?forum=xamarinios
CC-MAIN-2021-43
refinedweb
1,378
65.22
Hi, First and foremost, this is not homework (believe it or not some forums freak out about this, so wanted to get this out of the way). I took a Java course in college and want to get back into it. I can do some simple stuff, but am more interested in the basis of object oriented programming (in other words not doing everything in the main method). Here is the code I'm working with: import javax.swing.*; public class Experiment { public static void main(String [] args) { String number1 = JOptionPane.showInputDialog(null, "Please enter your first number"); String number2 = JOptionPane.showInputDialog(null, "Please enter your second number"); Double getnumber1 = Double.parseDouble(number1); Double getnumber2 = Double.parseDouble(number2); JOptionPane.showMessageDialog(null, "The number's are " + getnumber1 + "and" + getnumber2); //JOptionPane.showMessageDialog(null, "The numbers added together are" + addNumbers() ); } /* public double addNumbers() { double total; total = getnumber1 + getnumber2; return total; } */ } What I'm doing I'm using the JOptionPane simple dialog boxes to try and add together some numbers generated by users. I like JOptionPane, so please don't suggest using Scanner. What I'm trying to do is have the addNumbers part return up to the last JOptionPane message which will show the user the total. I commented out the parts that don't work, the last part of the program and the last JOptionPane message dialog. What I want to do (ideally) is do all the calculations out of the main method and then be able to call them when needed. So the last part of the code may be totally incorrect (just the commented out part) and the last JOptionPane (also commented out). So can someone explain to me in simple terms the syntax for calling other methods and such? If I'm totally off base and am doing everything completely wrong, please let me know as well.
http://www.javaprogrammingforums.com/java-theory-questions/4762-need-help-understanding-method-calls-such.html
CC-MAIN-2015-35
refinedweb
308
54.42
This action might not be possible to undo. Are you sure you want to continue? day1 GENESIS 1:1 — 2:17 The Beginning 1 In the beg inn ing God created the heavens and the e arth. 2 Now the earth was formless and empty, darkness was over the surface of the deep, and the Spir it of God was hovering over the waters. mark sacred times, and days and y ears, 15 and let them be lights in the v ault of the sky to give light on the earth.” And it was so. 16 God made two g reat lights — the greater light to govern the day and the lesser light to govern the night. He also made the s tars. 17 God set them in the vault of the sky to give light on the earth, 18 to govern the day and the night, and to sepa rate l ight from darkness. And God saw that it was good. 19 And t here was evening, and t here was morning — the fourth day. 20 And God said, “Let the water teem with living creat ures, and let birds fly above the earth across the v ault of the sky.” 21 So God cre ated the g reat creatures of the sea and every living thing with which the water teems and that moves about in it, according to their k inds, and every w inged bird according to its kind. And God saw that it was good. 22 God blessed them and said, “Be fruitf ul and increase in number and fill the water in the seas, and let the birds increase on the earth.” 23 And there was even ing, and there was morning — the f ifth day. 24 And God said, “Let the land produce living creat ures according to t heir k inds: the livestock, the creat ures that move a long the g round, and the wild animals, each according to its kind.” And it was so. 25 God made the wild an i mals accord ing to t heir k inds, the livestock accord ing to t heir k inds, and all the creat ures that move a long the g round according to their k inds. And God saw that it was good. 26 Then God said, “Let us make man kind in our ima ge, in our likeness, so that they may rule over the fish in the sea and the birds in the sky, over the livestock and all the wild animals, a and over all the creat ures that move a long the ground.” 3 And God said, “Let there be light,” and there was light. 4 God saw that the light was good, and he sepa rated the light from the dark ness. 5 God c alled the light “day,” and the darkness he called “night.” And there was even ing, and there was morning — the f irst day. 6 And God said, “Let there be a v ault be tween the waters to sepa rate water from water.” 7 So God made the vault and sep arated the water under the v ault from the water above it. And it was so. 8 God called the vault “sky.” And there was eve ning, and there was morning — the sec ond day. 9 And God said, “Let the water under the sky be gathered to one place, and let dry g round appear.” And it was so. 10 God c alled the dry g round “land,” and the gathered waters he c alled “seas.” And God saw that it was good. 11 Then God said, “Let the land pro duce vegetation: seed-bearing plants and trees on the land that bear f ruit with seed in it, according to t heir var ious k inds.” And it was so. 12 The land produced veg etation: plants bearing seed according to t heir k inds and t rees bearing fruit with seed in it according to t heir k inds. And God saw that it was good. 13 And t here was evening, and t here was morning — the third day. 27 So God created mankind in his own image, 14 And God said, “Let t here be lights in the vault of the sky to sepa rate the day from in the image of God he created them; the night, and let them serve as signs to male and female he created them. a 26 Probable reading of the original Hebrew text (see Syriac); Masoretic Text the earth DAY 1 28 God blessed them and said to them, “Be fruitf ul and increase in number; fill the e arth and subdue it. Rule over the fish in the sea and the birds in the sky and over every living creat ure that moves on the ground.” 29 Then God said, “I give you every seed-bearing p lant on the face of the whole earth and every tree that has fruit with seed in it. They will be y ours for food. 30 And to all the beasts of the earth and all the birds in the sky and all the creat ures that move along the ground — everything that has the breath of life in it — I give every g reen p lant sev enth day he rested from all his work. 3 Then God blessed the seventh day and made it holy, because on it he rested from all the work of creating that he had done. Adam and Eve 2 t rees that were pleasing to the eye and good for food. In the midd le of the garden were the tree of life and the tree of the knowledge of good and evil. 10 A river watering the garden f lowed from Eden; from there it was sepa rated into four headw aters. 11 The name of the first is the Pishon; it w inds through the entire land of Hav i lah, where t here is gold. 12 (The gold of that land is good; aromatic resin d and onyx are also there.) 13 The name of the second river is the Gihon; it w inds through the entire land of Cush. e 14 The name of the t hird river is the Ti gris; it runs a long.” MATTHEW 1:1 — 1:25 The Genealogy of Jesus the Messiah 1 This is the genea log y f of Jesus the Mes sia h g the son of Dav id, the son of Abra ham: 2 Abraham was the father of Isaac, Isaac the father of Jacob, Jacob the father of Jud ah and his brothers, 5 Now no s 3 Jud ah the fat her of Perez and Zerah, hrub had yet appeared on the earth a and no plant had yet s prung up, for the whose mother was Tamar, Lord God had not sent rain on the e arth and Perez the father of Hezron, there was no one to work the g round, 6 but Hezron the father of Ram, 4 Ram the fat her of Amm inadab, streams b came up from the e arth and watered 7 the whole surface of the g round. Then the Amminadab the father of Nahshon, Lord God formed a man c from the dust of the Nahshon the father of Salmon, 5 Sal ground and breathed into his nostrils the breath mon the father of Boaz, w hose of life, and the man became a living being. mother was Rahab, 8 Now the Lord God had plant ed a gar Boaz the father of Obed, whose moth den in the east, in Eden; and there he put the er was Ruth, man he had formed. 9 The Lord God made Obed the father of Jesse, 6 and Jesse the fat her of King Dav id. all k inds of trees grow out of the g round — 4 This is the account of the heavens and the earth when they were created, when the Lord God made the earth and the heavens. a 5 Or land ; also in verse 6 b 6 Or mist c 7 The Hebrew for man (adam) sounds like and may be related to the Hebrew for ground (adamah) ; it is also the name Adam (see verse 20). d 12 Or good; pearls e 13 Possibly southeast Mesopotamia f 1 Or is an account of the origin g 1 Or Jesus Christ. Messiah (Hebrew) and Christ (Greek) both mean Anointed One; also in verse 18. DAY 1 3 Dav id was the father of Solomon, whose mother had been Uriah’s wife, 7 Solomon the fat her of Rehoboa m, Rehoboam the father of Abijah, Abijah the father of Asa, 8 Asa the fat her of Jehoshaphat, Jehoshaphat the father of Jehoram, Jehoram the father of Uzziah, 9 Uzzia h the fat her of Jot ham, Jotham the father of Ahaz, Ahaz the father of Hezek iah, 10 Hezek ia h the fat her of Manasseh, Manasseh the father of Amon, Amon the father of Josiah, 11 and Josia h the fat her of Jecon ia h a and his brothers at the time of the exile to Babylon. 12 After the exile to Babylon: Jeconia h was the father of Shea ltiel, Shea ltiel the father of Zer ubbabel, 13 Zer ubbabel the fat her of Abihud, Abihud the father of Eliak im, Eliak im the father of Azor, 14 Azor the fat her of Zadok, Zadok the father of Akim, Akim the father of Elihud, 15 Elihud the fat her of Eleaz ar, Eleazar the father of Matthan, Matthan the father of Jacob, 16 and Ja cob the father of Joseph, the husband of Mary, and Mary was the mother of Jesus who is called the Messia h. 17 Thus t here were four teen generat ions in all from Abraham to Dav id, fourteen from Dav id to the exile to Babylon, and fourteen from the exile to the Messiah. Joseph Accepts Jesus as His Son 18 This is how the b irth of Jesus the Messiah came about b: His mother Mary was pledged to be married to Joseph, but before they came to gether, she was found to be pregnant t hrough the Holy Spirit. 19 Because Joseph her husband was faithf ul to the law, and yet c did not want to expose her to public disg race, he had in mind to divorce her quietly. 20 But after he had considered this, an angel of the Lord appeared to him in a d ream and said, “Joseph son of Dav id, do not be a fraid to take Mary home as your wife, because what is conceived in her is from the Holy Spirit. 21 She will give birth to a son, and you are to give him the name Jesus, d because he will save his people from their sins.” 22 All this took place to fulfill what the Lord had said through the prophet: 23 “The virg in will conceive and give birth to a son, and they will call him Immanuel” e (which means “God with us”). 24 When Jo seph woke up, he did what the angel of the Lord had commanded him and took Mary home as his wife. 25 But he did not consummate their marriage until she gave birth to a son. And he gave him the name J esus. PSALM 1:1 — 1. a 11 That is, Jehoiachin; also in verse 12 b 18 Or The origin of Jesus the Messiah was like this c 19 Or was a righteous man and d 21 Jesus is the Greek form of Joshua, which means the Lord saves. e 23 Isaiah 7:14 DAY 2 REWIND Genesis 1:1 – 2:17; Matthew 1; Psalm 1 IT’S ALL ABOUT BEGINNINGS. Genesis 1 – 2 describes the origination of the universe, from nothingness to God’s creation of everything you see. The story moves from the beginning of space and time to the start of every plant, animal, and person on earth. Matthew 1 traces Jesus’ roots from Abraham to Joseph, his earthly father, and tells of his miraculous birth to a virgin, Mary. And Psalm 1 explains how you can make your first moves toward a life close to God. D day2 GENESIS 2:18 — 4:16 18 The Lord God said, “It is not good for the man to be a lone. I will make a helper suit able for him.” 19 Now the Lord God had formed out of the g round all the wild animals and all the birds in the sky. He brought them to the man to see what he would name them; and what ever the man called each living creat ure, that was its name. 20 So the man gave names to all the livestock, the birds in the sky and all the wild animals. But for Adam a no suitable helper was f ound. 21 So the Lord God c aused the man to fall into a deep sleep; and while he was sleeping, he took one of the man’s ribs b and then closed up the p lace with f lesh. 22 Then the Lord God made a woman from the rib c he had taken out of the man, and he brought her to the man. 4 23 The man said, “This is now bone of my bones and flesh of my flesh; she shall be called ‘woman,’ for she was taken out of man.” 24 That is why a man leaves his father and mother and is united to his wife, and they be come one flesh. 25 Adam and his wife were both naked, and they felt no shame. The Fall 3 Now the serpent was more c rafty than any of the wild animals the Lord God had made. He said to the woman, “Did God really say, ‘You must not eat from any tree in the garden’?” 2 The woma n said to the serpent, “We may eat fruit from the trees in the garden, 3 but God did say, ‘You must not eat fruit from the tree that is in the midd le of the garden, and you must not touch it, or you will die.’ ” 4 “You will not cer tainly die,” the serpent said to the woma n. 5 “For God k nows that when you eat from it your eyes will be opened, and you will be like God, knowing good and evil.” 6 When the woma n saw that the f ruit rea lized a mong the trees of the garden. 9 But the Lord God called to the man, “Where are you?” 10 He an s wered, “I heard you in the gar den, and I was a fraid because I was naked; so I hid.” 11 And he said, “Who told you that you were naked? Have you eaten from the tree that I commanded you not to eat from?” a 20 Or the man b 21 Or took part of the man’s side c 22 Or part DAY 2 5 12 The man said, “The woma n you put here with me — she gave me some fruit from the tree, and I ate it.” 13 Then the Lord God said to the woma n, “What is this you have done?” The woma n said, “The serpent deceived me, and I ate.” 14 So the Lord God said to the ser pent, , “Be cause c lothed tak en. 24 After he drove the man out, he p laced on the east side e of the Garden of Eden cherubim and a flaming sword flashing back and forth to g uard the way to the tree of life. Cain and Abel 4 Adam c made love to his wife Eve, and she became pregnant and gave birth to Cain. f She said, “With the help of the Lord I have brought forth g a man.” 2 Later she gave b irth to his brother Abel. Now Abel kept f locks, and Cain worked the soil. 3 In the course of time Cain brought some of the fruits of the soil as an offering to the Lord. 4 And Abel also brought an offer ing — fat portions from some of the firstborn of his f lock. The Lord looked with favor on Abel and his offering, 5 but on Cain and his offering he did not look with favor. So Cain was very angry, and his face was downcast. 6 Then the Lord said to Cain, “Why are you ang ry? Why is your face downcast? 7 If you do what is r ight, will you not be accept ed? But if you do not do what is r ight, sin is crouching at your door; it desires to have you, but you must rule over it.” 8 Now Cain said to his brother Abel, “Let’s go out to the f ield.” h W hile they were in the field, Cain attacked his brother Abel and k illed him. 9 Then the Lord said to Cain, “Where is your brother Abel?” “I d on’t know,” he replied. “Am I my broth er’s keeper?” 10 The Lord said, “What have you done? Listen! Your brother’s blood c ries out to me from the ground. 11 Now you are under a curse and driven from the g round, which opened a 15 Or seed b 15 Or strike c 20,1 Or The man d 20 Eve probably means living. e 24 Or placed in front f 1 Cain sounds like the Hebrew for brought forth or acquired. g 1 Or have acquired h 8 Samaritan Pentateuch, Septuagint, Vulgate and Syriac; Masoretic Text does not have “Let’s go out to the field.” DAY 2 its mouth to receive your brother’s blood from your hand. 12 When you work the g round, it will no longer y ield f inds me will kill me.” 15 But the Lord said to him, “Not so a; any one who k ills. MATTHEW 2:1 — 2:18 The Magi Visit the Messiah 2 After Jesus was born in Bethlehem in Judea, during the time of King Herod, Magi c from the east came to Jer usalem 2 and asked, “Where is the one who has been born king of the Jews? We saw his star when it rose and have come to worship him.” 3 When King Herod heard this he was dis turbed, and all Jer usalem with him. 4 When he had called together all the people’s c hief priests and teachers of the law, he asked them where the Messia h was to be born. 5 “In Beth lehem.’ d ” 6 it rose went ahead of them until it stopped over the place w here the c hild was. 10 When they saw the star, they were overjoyed. 11 On com ing to the house, they saw the child with his mother Mary, and they bowed down and wor shiped him. Then they opened t heir treasures and presented him with gifts of gold, frankin cense and myrrh. 12 And having been w arned in a d ream not to go back to Herod, they re turned to their country by another route. The Escape to Egypt 13 When they had gone, an an gel of the Lord appeared to Joseph in a dream. “Get up,” he said, “take the c hild and his mother and escape to Egypt. Stay there until I tell you, for Herod is going to s earch for the child to kill him.” 14 So he got up, took the c hild and his mother during the n ight and left for Egypt, 15 where he stayed unt il the death of Hero d. And so was fulf illed what the Lord had said t hrough the prophet: “Out of E gypt I called my son.” e 16 When Hero d rea lized that he had been outw itted by the Magi, he was fur ious, and he gave orders to kill all the boys in Bethle hem and its vicinit y who were two years old and under, in accordance with the time he had learned from the Magi. 17 Then what was said through the prophet Jeremiah was fulf illed: 18 “A voice is heard in Ramah, weeping and great mourning, Rachel weeping for her children and refusing to be comforted, because they are no more.” f PSALM 2:1 — 2 Psalm 2 1 Why do the nations conspire g and the peoples plot in vain? 2 The kings of the earth rise up and the rulers band together against the Lord and against his anointed, saying, a 15 Septuagint, Vulgate and Syriac; Hebrew Very well b 16 Nod means wandering (see verses 12 and 14). c 1 Traditionally wise men d 6 Micah 5:2,4 e 15 Hosea 11:1 f 18 Jer. 31:15 g 1 Hebrew; Septuagint rage DAY 3 7. REWIND Genesis 2:18 – 4:16; Matthew 2:1 – 18; Psalm 2 SIN RUINS GOOD THINGS. Genesis 2 – 4 displays God’s flawless plan for human beings to get along with him and each other. But it also shows Adam and Eve rebelling against the Lord’s command, shattering the relationships they enjoyed. Matthew 2 describes Jesus’ wondrous birth and the worship he receives from awestruck Magi. Yet the young family has to flee murderous Herod. Psalm 2 offers a surprising Old Testament picture of Jesus reigning as king. But it also exposes a world rising up to oppose him. D day3 GENESIS 4:17 — 6:22 17 Cain made love to his wife, and she be came pregnant and gave birth to Enoch. Cain was then building a city, and he named it af ter his son Enoch. 18 To Enoch was born Irad, and Irad was the father of Mehujael, and Me hujael was the father of Methushael, and Me thushael was the father of Lamech. 19 Lamech marr ied k inds of tools out of, c saying, “God has granted me another child in place of Abel, s ince Cain k illed him.” 26 Seth also had a son, and he named him Enosh. At that time people began to call on d the name of the Lord. From Adam to Noah 5 This is the written account of Adam’s family line. a 9 Or will rule them with an iron scepter (see Septuagint and Syriac) b 22 Or who instructed all who work in c 25 Seth probably means granted. d 26 Or to proclaim DAY 3 When God created mank ind, he made them in the likeness of God. 2 He created them male and female and blessed them. And he named them “Mank ind” a when they were created. 3 When Adam had l ived l ived 105 years, he became the father b of Enosh. 7 After he became the fa ther Alto gether, E nosh lived a total of 905 years, and then he died. 12 When Kenan had lived 70 years, he be came the father of Mahalalel. 13 After he be came the fat her of Ma ha la lel, Kenan l ived 840 years and had other sons and daughters. 14 Altogether, Kenan l ived Altogeth er, Mahalalel lived a total of 895 y ears, E noch had lived 65 years, he be came the father of Methuselah. 22 After he be came the father of Methuselah, Enoch walked faithf ully with God 300 years and had other sons and daughters. 23 Altogether, Enoch lived a total of 365 years. 24 Enoch walked faithf ully with God; then he was no more, because God took him away. 8 25 When Met hus el ah had l ived 187 y ears, he became the fat her of Lamech. 26 After he became the fat her of Lamech, Met husel ah lived 782 years and had other sons and daugh ters. 27 Altogether, Methuselah lived a total of 969 years, and then he died. 28 When La mech had lived 182 years, he had a son. 29 He named him Noah c and said, “He will comfort us in the labor and painf ul toil of our hands caused by the g round the Lord has c ursed.” 30 After Noah was born, Lamech lived 595 years and had other sons and daughters. 31 Altogether, Lamech l ived a total of 777 years, and then he died. 32 After Noah was 500 years old, he became the father of Shem, Ham and Japheth. Wickedness in the World 6 When human beings began to inc rease in number on the earth and daughters were born to them, 2 the sons of God saw that the daughters of humans were beautif ul, and they marr ied any of them they chose. 3 Then the Lord said, “My Spirit will not contend with d humans fore ver, for they are mortal e; their days will be a hundred and twent y years.” 4 The Nephilim were on the earth in t hose days — a nd also afterward — when the sons of God went to the daughters of humans and had child ren by them. They were the heroes of old, men of renown. 5 The Lord saw how g reat the wickedness of the human race had become on the earth, and that every inc linat ion of the t houghts of the human heart was only evil all the time. 6 The Lord reg retted that he had made hu man beings on the earth, and his heart was deeply troubled. 7 So the Lord said, “I will wipe from the face of the earth the human race I have created — and with them the an imals, the birds and the creat ures that move a long the g round — for I reg ret that I have made them.” 8 But Noah found favor in the eyes of the Lord. Noah and the Flood 9 This is the ac c ount of Noah and his family. a 2 Hebrew adam b 6 Father may mean ancestor; also in verses 7-26. c 29 Noah sounds like the Hebrew for comfort. d 3 Or My spirit will not remain in e 3 Or corrupt DAY 3 9 Noah was a righ t eous man, blame l ess a mong the people of his time, and he walked faithf ul ly with God. 10 Noah had t hree sons: Shem, Ham and Japheth. 11 Now the earth was corr upt in God’s sight and was full of violence. 12 God saw how cor rupt the earth had become, for all the peo ple on earth had corr upted their ways. 13 So God said to Noah, “I am going to put an end to all people, for the earth is f illed with vio lence because of them. I am surely going to destroy both them and the earth. 14 So make yourself an ark of cypress a wood; make r ooms in it and coat it with pitch inside and out. 15 This is how you are to b uild it: The ark is to be three hund red cubits long, fift y cubits wide and thirt y cubits high. b 16 Make a roof for it, leaving below the roof an opening one cubit c high all a round. d Put a door in the side of the ark and make lower, midd le and upper decks.17 I am going to bring f loodwaters on the earth to destroy all life under the heavens, every creat ure that has the breath of life in it. Every thing on earth will perish. 18 But I will establish my covenant with you, and you will enter the ark — you and your sons and your wife and your sons’ w ives with you. 19 You are to bring into the ark two of all living crea tures, male and female, to keep them a live with you. 20 Two of every kind of bird, of every kind of animal and of every kind of creat ure that moves a long the g round will come to you to be kept a live. 21 You are to take every kind of food that is to be eaten and store it away as food for you and for them.” 22 Noah did ev erything just as God com manded him. MATTHEW 2:19 — 3:17 The Return to Nazareth 19 After Herod died, an angel of the Lord appeared in a dream to Joseph in Egypt 20 and said, “Get up, take the c hild and his moth er and go to the land of Israel, for t hose who were trying to take the child’s life are dead.” 21 So he got up, took the c hild and his mother and went to the land of Israel. 22 But when he heard that Arc helaus was reigning in Judea in place of his father Herod, he was a fraid to go t here. Having been warned in a dream, he withdrew to the district of Galilee, 23 and he went and l ived in a town called Naz areth. So was fulf illed what was said through the prophets, that he would be called a Naz are.’ ” e 4 John’s c lothes were made of camel’s hair, and he had a leather belt a round his waist. His food was locusts and wild honey. 5 People went out to him from Jer usalem and all Judea and the whole reg ion of the Jordan. 6 Confessing their sins, they were baptized by him in the Jordan River. 7 But when he saw many of the Phar isees and Sadducees coming to where he was bap tizing, he said to them: “You brood of vipers! Who w arned you to f lee from the coming w rath? 8 Produce fruit in keeping with repen tance. 9 And do not think you can say to your selves, ‘We have Abraham as our father.’ I tell you that out of these stones God can raise up child ren for Abraham. 10 The ax is already at the root of the trees, and every tree that does not produce good fruit will be cut down and thrown into the fire. 11 “I bapt ize you with f water for repentance. But after me comes one who is more powerf ul than I, whose sandals I am not worthy to car ry. He will baptize you with f the Holy Spirit and fire. 12 His winnowing fork is in his hand, and he will c lear his threshing f loor, gather ing his wheat into the barn and burning up the chaff with unquenchable fire.” a 14 The meaning of the Hebrew for this word is uncertain. b 15 That is, about 450 feet long, 75 feet wide and 45 feet high or about 135 meters long, 23 meters wide and 14 meters high c 16 That is, about 18 inches or about 45 centimeters d 16 The meaning of the Hebrew for this clause is uncertain. e 3 Isaiah 40:3 f 11 Or in DAY 4 10 The Baptism of Jesus 13 Then Jesus came from Galilee to the Jor dan to be baptized by John. 14 But John t ried to deter him, saying, “I need to be baptized by you, and do you come to me?” 15 Jesus replied, “Let it be so now; it is prop er for us to do this to fulf ill all righteousness.” Then John consented. 16 As soon as Jesus was baptized, he went up out of the water. At that moment heaven was opened, and he saw the Spirit of God de s cend i ng like a dove and alight i ng on him. 17 And a v oice from heaven said, “This is my Son, whom I love; with him I am well pleased.” REWIND Genesis 4:17 – 6:22; Matthew 2:19 – 3:17; Psalm 3 ALL PEOPLE SIN. By the days of Noah in Genesis 4 – 6, the horror of human wickedness deeply troubles God’s heart. The Lord grows so sorry he made people that he decides to wipe them from the face of earth. Matthew 2 – 3 pictures John the Baptist telling everyone they need to repent — to stop sinning and turn back to God. And Psalm 3 came straight from King David’s heart when his son Absalom tried to topple him from the throne. No one is without sin. D PSALM 3:1 — 3:8. day4 GENESIS 7:1 — 9:17 7 The Lord then said to Noah, “Go into the ark, you and your whole family, be cause I have found you righteous in this gen erat ion. 2 Take with you seven p airs of every kind of clean animal, a male and its mate, and one pair of every kind of unc lean animal, a male and its mate, 3 and also seven pairs of every kind of bird, male and female, to keep their various k inds a live throughout the earth. 4 Seven days from now I will send rain on the earth for fort y days and fort y nights, and I will wipe from the face of the earth every living creat ure I have made.” 5 And Noah did all that the Lord com manded him. 6 Noah was six hund red years old when the f loodwaters came on the earth. 7 And Noah a In Hebrew texts 3:1-8 is numbered 3:2-9. b 2 The Hebrew has Selah (a word of uncertain meaning) here and at the end of verses 4 and 8. DAY 4 11 and his sons and his wife and his sons’ w ives entered the ark to escape the waters of the f lood. 8 Pairs of c lean and unc lean animals, of birds and of all creat ures that move a long the ground, 9 male and female, came to Noah and entered the ark, as God had commanded Noah. 10 And after the seven days the flood waters came on the earth. 11 In the six hund redth year of Noa h’s life, on the seventeenth day of the second month — on that day all the springs of the g reat deep burst forth, and the floodgates of the heavens were opened. 12 And rain fell on the earth for ty days and fort y nights. 13 On that very day Noah and his sons, Shem, Ham and Japheth, together with his wife and the w ives of his t hree sons, entered the ark. 14 They had with them every wild ani mal according to its kind, all livestock accord ing to t heir k inds, every creat ure that m oves a long the g round according to its kind and every bird according to its kind, everything with w ings. 15 Pairs of all creat ures that have the breath of life in them came to Noah and entered the ark. 16 The animals going in were male and female of every living thing, as God had commanded Noah. Then the Lord shut him in. 17 For fort y days the f lood kept comi ng on the e arth, and as the waters inc reased they lifte d the ark high a bove the e arth. 18 The waters rose and increased greatly on the earth, and the ark f loated on the surface of the water. 19 They rose greatly on the earth, and all the high mountains under the ent ire heavens were covered. 20 The waters rose and covered the mountains to a depth of more than fif teen cubits. a , b 21 Every liv i ng t hing that m oved on land perished — birds, live stock, wild anim als, all the creatures that swarm over the earth, and all mank ind. 22 Everyt hing on dry land that had the breath of life in its nostrils died. 23 Eve ry liv i ng t hing on the face of the earth was w iped out; people and anim als and the creatures that move a long the g round and the birds were w iped from the earth. Only Noah was left, and t hose with him in the ark. 24 The waters flooded the earth for a hun dred and fift y c losed, and the rain had stopped falling from the sky. 3 The water re ceded steadily from the earth. At the end of the hund red and fift y days the water had gone down, 4 and on the seventeenth day of the seventh month the ark came to rest on the mountains of Ara rat. 5 The waters continued to recede until the tenth month, and on the f irst day of the tenth m onth the tops of the mountains became visible. 6 After fort y days Noah opened a window he had made in the ark 7 and sent out a raven, and it kept flying back and forth until the wa ter had dried up from the earth. 8 Then he sent out a dove to see if the water had receded from the surface of the ground. 9 But the dove could find nowhere to perch because there was wa ter over all the surface of the e arth; so it re turned to Noah in the ark. He reached out his hand and took the dove and brought it back to himself in the ark. 10 He waited seven more days and again sent out the dove from the ark. 11 When the dove ret urned to him in the eve ning, there in its beak was a freshly plucked olive leaf ! Then Noah knew that the water had receded from the earth. 12 He waited sev en more days and sent the dove out again, but this time it did not ret urn to him. 13 By the f irst day of the f irst month of No ah’s six hundred and f irst year, the water had dried up from the earth. Noah then removed the covering from the ark and saw that the sur face of the g round was dry. 14 By the twent yseventh day of the second month the e arth was completely dry. 15 Then God said to Noah, 16 “Come out of the ark, you and your wife and your sons and t heir w ives. 17 Bring out every kind of living creat ure that is with you — the birds, the an imals, and all the creat ures that move a long the g round — so they can multiply on the 8 a 20 That is, about 23 feet or about 6.8 meters b 20 Or rose more than fifteen cubits, and the mountains were covered DAY 4 e arth and be fruitf ul and increase in number on it.” 18 So Noah came out, together with his sons and his wife and his sons’ w ives. 19 All the an imals and all the creatures that move a long the g round and all the birds — everything that moves on land — came out of the ark, one kind after another. 20 Then Noah b uilt an altar to the Lord and, taking some of all the clean animals and c lean birds, he sacr if iced burnt of fer ings on it. 21 The Lord smelled the pleasing aroma and said in his heart: “Never again will I curse the ground because of humans, even though a every inc linat ion of the human heart is evil from childhood. And never a gain will I de stroy all living creat ures, as I have done. 22 “As long as the earth endures, seedtime and harvest, cold and heat, summer and winter, day and night will never cease.” God’s Covenant With Noah 9 Then God b lessed Noah and his sons, saying to them, “Be fruitf ul and increase in number and fill the e arth. 2 The fear and d read of you will fall on all the beasts of the earth, and on all the birds in the sky, on every creature that moves a long the g round, and on all the fish in the sea; they are given into your hands. 3 Every thing that lives and moves about will be food for you. Just as I gave you the green plants, I now give you everything. 4 “But you must not eat meat that has its life blood still in it. 5 And for your lifeblood I will surely demand an accounting. I will demand an accounting from every animal. And from each human being, too, I will demand an ac counting for the life of another human being. 6 “Whoever sheds human blood, by humans shall their blood be shed; for in the image of God has God made mankind. 7 As for you, be fruitf ul and increase in number; multiply on the earth and increase upon it.” 12 8 Then God said to Noah and to his sons with him: 9 “I now establish my covenant with you and with your descendants after you 10 and with every living creat ure that was with you — the birds, the livestock and all the wild animals, all those that came out of the ark with you — every living creat ure on earth. 11 I establish my covenant with you: Never again will all life be destroyed by the waters of a f lood; never a gain will there be a f lood to de stroy the earth.” 12 And God said, “This is the sign of the covenant I am making bet ween me and you and every living creat ure with you, a covenant for all generations to come: 13 I have set my rainbow in the clouds, and it will be the sign of the covenant between me and the earth. 14 Whenever I b ring clouds over the earth and the rainbow appears in the c louds, 15 I will remember my covenant bet ween me and you and all living creat ures of every kind. Never again will the waters become a f lood to de stroy all life. 16 Whenever the rainbow appears in the c louds, I will see it and remember the everlasting covenant bet ween God and all liv ing creat ures of every kind on the earth.” 17 So God said to Noah, “This is the sign of the covenant I have established bet ween me and all life on the earth.” MATTHEW 4:1 — 4:22 Jesus Is Tested in the Wilderness 4 Then Jesus was led by the Spirit into the wilderness to be tempted b by the devil. 2 After fasting fort y days and fort y n ights, he was hung ry. 3 The tempter came to him and said, “If you are the Son of God, tell these stones to become bread.” 4 Jesus ans wered, “It is written: ‘Man shall not live on bread a lone, but on every word that comes from the mouth of God.’ c ” 5 Then the devil took him to the holy city and had him stand on the highest point of the temple. 6 “If you are the Son of God,” he said, “throw yourself down. For it is written: “ ‘He will command his angels concerning you, a 21 Or humans, for b 1 The Greek for tempted can also mean tested. c 4 Deut. 8:3 DAY 4 13 and they will lift you up in their hands, so that you will not strike your foot against a stone.’ a ” 7 Jesus an s wered him, “It is also written: ‘Do not put the Lord your God to the test.’ b ” 8 Again, the devil took him to a very high mountain and showed him all the kingdoms of the w orld and their splendor. 9 “All this I will give you,” he said, “if you will bow down and worship me.” 10 Jesus said to him, “Away from me, Satan! For it is written: ‘Worship the Lord your God, and serve him only.’ c ” 11 Then the devi l left him, and angels came and attended him. Jesus Begins to Preach 12 When Jesus h eard that John had been put in prison, he withd rew to Galilee. 13 Leaving Naza reth, he went and l ived in Capernaum, which was by the lake in the area of Zebu lun and Naphtali — 14 to fulf ill.” rew. They were casting a net into the lake, for they were fish ermen. 19 “Come, follow me,” Jesus said, “and I will send you out to fish for people.” 20 At once they left their nets and followed him. 21 Going on from t here, he saw two other brothers, James son of Zebedee and his broth er John. They were in a boat with t heir father Zebedee, prepar i ng t heir nets. Jesus c alled them, 22 and immed iately they left the boat and their father and followed him. PROVERBS 1:1 — 1:7 1 The proverbs of Solomon son of Dav id, king of Israel: 2 for gaining wisdom and instruction; for understanding words of insight; 3 for receiving instruction in prudent behavior, doing what is right and just and fair; 4 for giving prudence to those who are simple, e knowledge and discretion to the young — 5 let the wise listen and add to their learning, and let the discerning get guidance — 6 for understanding proverbs and parables, the sayings and riddles of the wise. f 7 The fear of the Lord is the beginning of knowledge, but fools g despise wisdom and instruction. REWIND Genesis 7:1 – 9:17; Matthew 4:1 – 22; Proverbs 1:1 – 7 GOD STRIKES BACK AT SIN. In Genesis 7 – 9 God sends a flood to cover the entire world, then offers humankind a fresh start and a promise never again to flood the earth and destroy all life. In Matthew 4 Jesus battles temptation by hitting back at the devil with God’s powerful words. The Lord announces the end of darkness and the arrival of his kingdom, and he calls his first followers to help him spread the news. Proverbs 1 invites you to listen closely to God’s wisdom and learn to do right. D a 6 Psalm 91:11,12 b 7 Deut. 6:16 c 10 Deut. 6:13 d 16 Isaiah 9:1,2 e 4 The Hebrew word rendered simple in Proverbs denotes a person who is gullible, without moral direction and inclined to evil. f 6 Or understanding a proverb, namely, a parable, / and the sayings of the wise, their riddles g 7 The Hebrew words rendered fool in Proverbs, and often elsewhere in the Old Testament, denote a person who is morally deficient. DAY 5 14 and may Canaan be the slave of Japheth.” 28 Af ter 29 Noah died. the flood Noah lived 350 years. lived a total of 950 years, and then he The Table of Nations day5 GENESIS 9:18 — 11:9 The Sons of Noah 18 The sons of Noah who came out of the ark were Shem, Ham and Japheth. (Ham was the father of Canaan.) 19 These were the t hree sons of Noah, and from them came the people who were scattered over the whole earth. 20 Noah, a man of the soil, pro ceeded a to plant a vineyard. 21 When he d rank some of its wine, he became drunk and lay uncovered inside his tent. 22 Ham, the father of Canaan, saw his father naked and told his two brothers outside. 23 But Shem and Japheth took a gar ment and laid it across their shoulders; then they walked in backward and covered their fat her’s naked body. T heir faces were t urned, 10 This is the account of Shem, Ham and Japheth, Noah’s sons, who them selves had sons after the flood. The Japhethites 2 The sons ites. d 5 (From t hese the maritime peoples spread out into their ter r itor ies by t heir c lans within t heir nations, each with its own lang uage.) The Hamites 6 The sons of Ham: Cush, Egypt, Put and Canaan. 7 The sons of Cush: Seba, Hav i lah, Sabtah, Raamah and Sabtek a. The sons of Raamah: Sheba and Dedan. 8 Cush was the fat her e of Nimrod, who be came a mighty warrior on the earth. 9 He was a mighty hunter before the Lord; that is why it is said, “Like Nimrod, a mighty hunter before the Lord.” 10 The f irst centers of his kingdom were Babylon, Uruk, Akk ad and Kalneh, in f Shinar. g 11 From that land he went to Assyria, where he built Nineveh, Rehoboth Ir, h Calah 12 and Resen, which is bet ween Nine veh and Calah — which is the great city. 13 Egypt was the father of the Lud ites, Anam ites, Leh abites, Napht uh ites, 14 Path r usites, Kaslu a 20 Or soil, was the first b 27 Japheth sounds like the Hebrew for extend. c 2 Sons may mean descendants or successors or nations; also in verses 3, 4, 6, 7, 20-23, 29 and 31. d 4 Some manuscripts of the Masoretic Text and Samaritan Pentateuch (see also Septuagint and 1 Chron. 1:7); most manuscripts of the Masoretic Text Dodanites e 8 Father may mean ancestor or predecessor or founder; also in verses 13, 15, 24 and 26. f 10 Or Uruk and Akkad — all of them in g 10 That is, Babylonia h 11 Or Nineveh with its city squares DAY 5 15 hites (from whom the Phi l is t ines came) and Caphtorites. 15 Canaan was the father of Sidon his firstborn, a and of the Hittites, 16 Jebu s ites, Amor ites, Gir g a s hites, 17 Hiv ites, Ark ites, Sinites,18 Ar vadites, Zemarites and Hamathites. Later the Canaanite c lans scat tered 19 and the borders of Canaan reached from Sidon to ward Gerar as far as Gaza, and then toward Sodom, Gomorrah, Admah and Zeboyim, as far as Lasha. 20 These are the sons of Ham by t heir c lans and lang uages, in their territories and nations. The Semites 21 Sons were also born to Shem, whose older brother was b Japheth; Shem was the ancestor of all the sons of Eber. 22 The sons of Shem: Elam, Ashu r, Arphaxad, Lud and Aram. 23 The sons of Aram: Uz, Hul, Gether and Meshek. c 24 Arphaxad was the father of d Shelah, and Shelah the father of Eber. 25 Two sons were born to Eber: One was named Peleg, e because in his time the earth was div ided; his broth er was named Joktan. 26 Joktan was the father of Almod ad, Shel eph, Haz arm av eth, Jer ah, 27 Had or am, Uzal, Dik l ah, 28 Obal, Abimae l, Sheb a, 29 Ophir, Havilah and Jobab. All these were sons of Joktan. 30 The region where they lived stretched from Mesha tow ard Sephar, in the eastern hill country. 31 These are the sons of Shem by t heir c lans and lang uages, in their territories and nations. 32 These are the c lans of Noa h’s sons, ac cording to their lines of descent, within their nations. From these the nations spread out over the earth after the flood. The Tower of Babel 11 Now the w hole w orld had one lan guage and a common speech. 2 As people moved eastward, f they found a plain in Shinar g and sett led there. 3 They said to each other, “Come, let’s make bricks and bake them thoroughly.” They used brick instead of stone, and tar for mortar. 4 Then they said, “Come, let us build our selves a city, with a tower that reaches to the heavens, so that we may make a name for our selves; otherw ise we will be scattered over the face of the whole earth.” 5 But the Lord came down to see the city and the tower the people were building. 6 The Lord said, “If as one people speaking the same lang uage they have beg un to do this, then nothing they plan to do will be impos sible for them. 7 Come, let us go down and conf use their lang uage so they will not under stand each other.” 8 So the Lord scat tered them from there over all the earth, and they stopped building the city. 9 That is why it was c alled Babel h — because there the Lord conf used the lang uage of the w hole w orld. From there the Lord scat tered them over the face of the whole earth. MATTHEW 4:23 — 5:20 Jesus Heals the Sick 23 Jesus went throughout Gal i lee, teaching in t heir synagogues, proc laimi ng the good news of the kingdom, and healing every disease and sickness among the people. 24 News about him spread all over Syria, and people brought to him all who were ill with various diseases, t hose sufferi ng sev ere pain, the demonpossessed, those having seizures, and the par alyzed; and he h ealed them. 25 Large crowds from Gal i l ee, the Dec apol is, i Jer us al em, Judea and the reg ion a cross the Jordan fol lowed him. Introduction to the Sermon on the Mount 5 Now when Jesus saw the crowds, he went up on a mountainside and sat down. His a 15 Or of the Sidonians, the foremost b 21 Or Shem, the older brother of c 23 See Septuagint and 1 Chron. 1:17; Hebrew Mash. d 24 Hebrew; Septuagint father of Cainan, and Cainan was the father of e 25 Peleg means division. f 2 Or from the east ; or in the east g 2 That is, Babylonia h 9 That is, Babylon; Babel sounds like the Hebrew for confused. i 25 That is, the Ten Cities DAY 5 16 k inds of evil against you because of me. 12 Rejoice and be glad, because g reat is your reward in heav en, for in the same way they persec uted the prophets who were before you. Salt and Light 13 “You are the salt of the earth. But if the salt loses its saltiness, how can it be made salty again? It is no longer good for anyt hing, ex cept to be thrown out and trampled underfoot. 14 “You are the light of the world. A town built on a hill cannot be hidden. 15 Neither do people light a lamp and put it under a bowl. Instead they put it on its stand, and it g ives light to everyone in the house. 16 In the same way, let your light shine before others, that they may see your good deeds and glorif y your Father in heaven. The Fulfillment of the Law 17 “Do not think that I have come to abolish the Law or the Prophets; I have not come to abolish them but to fulf ill them. 18 For truly I tell you, until heaven and earth disappear, not the smallest letter, not the least stroke of a pen, will by any means disappear from the Law unt il every t hing is accomplished. 19 Therefore anyone who sets aside one of the least of these commands and teaches others accordingly will be called least in the king dom of heaven, but whoe ver practice s and teaches t hese commands will be c alled g reat in the kingdom of heaven. 20 For I tell you that unless your righteousness surpasses that of the Pharisees and the teachers of the law, you will certainly not enter the kingdom of heaven.” PSALM 4:1 — 4:8 In Hebrew texts 4:1-8 is numbered 4:2-9. b 2 Or seek lies c 2 The Hebrew has Selah (a word of uncertain meaning) here and at the end of verse 4. d 4 Or In your anger (see Septuagint) DAY 6 17 REWIND Genesis 9:18 – 11:9; Matthew 4:23 – 5:20; Psalm 4 THE LORD LOOKS OUT FOR YOUR GOOD. Genesis 9 – 11 details the spread of Noah’s descendants after the flood, concluding with the sad story of Babel, where p eople once again arrogantly challenge God. But Matthew 4 – 5 lets you glimpse how the Lord intends to remake the world for the better. Jesus declares good news. He heals the sick, frees the oppressed, and details the best blessings of his kingdom. Psalm 4 shows that God never leaves you alone in your distress. He gives joy and peaceful sleep. D day6 GENESIS 11:10 — 13:18 From Shem to Abram 10 This is the account of Shem’s family line. Two y ears after the f lood, when Shem was 100 years old, he became the father a of Ar phaxad. 11 And after he became the father of Arphaxad, Shem lived 500 years and had other sons and daughters. 12 When Ar phaxad had lived 35 years, he became the fat her of Shelah. 13 And after he bec ame the father of Shelah, Arphaxad lived 403 years and had other sons and daugh ters. b 14 When She l ah had lived 30 years, he bec ame the father of Eber. 15 And after he ecame the father of Eber, Shelah lived 403 b years and had other sons and daughters. 16 When Eber had l ived 34 y ears, he became the father of Peleg. 17 And after he became the father of Peleg, Eber lived 430 years and had other sons and daughters. 18 When Pe leg had lived 30 y ears, he be came the father of Reu. 19 And after he became the father of Reu, Peleg lived 209 years and had other sons and daughters. 20 When Reu had l ived 32 years, he became the father of Ser ug. 21 And after he became the father of Ser ug, Reu lived 207 years and had other sons and daughters. 22 When Ser ug had lived 30 y ears, he be came the father of Nahor. 23 And after he became the father of Nahor, Ser ug lived 200 years and had other sons and daughters. 24 When Nahor had lived 29 years, he be came the father of Terah. 25 And after he became the father of Terah, Nahor lived 119 years and had other sons and daughters. 26 Af ter Terah had lived 70 y ears, he be came a live, Haran died in Ur of the Chaldea ns, in the land of his birth. 29 Abram and Nahor both marr ied. The name of Abram’s wife was Sa rai, and the name of Nahor’s wife was Mil kah; she was the daughter of Haran, the father of both Milk ah and Isk ah. sett led there. 32 Te rah lived 205 years, and he died in Harran. a 10 Father may mean ancestor; also in verses 11-25. b 12,13 Hebrew; Septuagint (see also Luke 3:35, 36 and note at Gen. 10:24) 35 years, he became the father of Cainan. 13 DAY 6 sevent yfive years old when he set out from Harran. 5 He took his wife Sarai, his nephe w Lot, all the possessions they had accumulated and the people they had acquired in Harran, and they set out for the land of Canaan, and they ar rived there. 6 Abram traveled t hrough the land as far as the site of the great tree of Moreh at Shechem. At that time the Canaanites were in the land. 7 The Lord appeared to A bram and said, “To your offspring c I will give this land.” So he built an altar t here to the Lord, who had ap peared to him. 8 From t here he went on toward the h ills east of Bethel and pitched his tent, with Beth el on the west and Ai on the east. T here he built an altar to the Lord and called on the name of the Lord. 9 Then A bram set out and continued to ward the Negev. Abram in Egypt 10 Now there was a famine in the land, and bram went down to Egypt to live there for a A while because the famine was severe. 11 As he was about to enter Egypt, he said to his wife Sarai, “I know what a beautiful woma ngyp tians saw that Sarai was a very beautif ul wom an. 15 And when Pharaoh’s off icials saw her, they praised her to Pharaoh, and she was tak en into his palace. 16 He treated Abram well for her sake, and Abram acquired sheep and catt le, male and female donkeys, male and fe male servants, and camels. 17 But the Lord inf licted ser ious d ise ase s on Pharaoh and his household because of Abram’s wife Sarai. 18 So Pharaoh summoned Abram. “What have you done to me?” he said. “Why d idn every thing he had. Abram and Lot Separate 13 So Abram went up from Egypt to the Negev, with his wife and everyt hing he had, and Lot went with him. 2 Abram had become very wealthy in livestock and in silver and gold. 3 From the Ne gev he went from place to place until he came to Bethel, to the p lace between Bethel and Ai where his tent had been earl ier 4 and where he had f irst built an altar. There Abram called on the name of the Lord. 5 Now Lot, who was mov i ng about with Abram, also had f locks and herds and tents. 6 But the land could not supp ort them while they stayed tog ether, for t heir poss essions were so g reat that they were not able to stay tog ethe r. 7 And quar r el i ng a rose bet ween Abram’s herders and Lot’s. The Canaanites and Perizzites were also living in the land at that time. 8 So Abram said to Lot, “Let’s not have any quarreling bet ween you and me, or bet ween your herders and mine, for we are c lose rela tives. a 2 Or be seen as blessed b 3 Or earth / will use your name in blessings (see 48:20) c 7 Or seed DAY 6 19 a mong the cities of the plain and pitched his tents near Sodom. 13 Now the people of Sodom were wicked and were sinn ing greatly a gainst the Lord. 14 The Lord said to A bram after Lot had parted from him, “Look a round from where you are, to the n orth and south, to the east and west. 15 All the land that you see I will give to you and your offspring a fore ver. 16 I will make your offspring like the dust of the earth, so that if anyone could count the dust, then your offspring c ould be counted. 17 Go, walk through the length and b readth of the land, for I am giving it to you.” 18 So A bram went to live near the g reat trees of Mamre at Hebron, where he p itched his tents. There he built an altar to the Lord. MATTHEW 5:21 — 5:42 Murder 21 “You have heard that it was said to the people long ago, ‘You s hall not murder, b and anyone who murders will be subject to judg ment.’ 22 But I tell you that anyone who is a ng ry with a brother or sister c , d will be sub ject to judgment. Again, anyone who says to a brother or sister, ‘Raca,’ e is answerable to the court. And anyone who says, ‘You fool!’ will be in danger of the fire of hell. 23 “Therefore, if you are offering your gift at the altar and there remember that your broth er or sister has something against you, 24 leave your gift there in front of the altar. F irst go and be reconciled to them; then come and of fer your gift. 25 “Sett le matters quickly with your adver sary who is taking you to court. Do it while you are still together on the way, or your ad versary may hand you over to the judge, and the judge may hand you over to the off icer, and you may be thrown into prison. 26 Truly I tell you, you will not get out until you have paid the last penny. Adultery 27 “You have h eard that it was said, ‘You shall not comm it adultery.’ f 28 But I tell you that anyone who looks at a woma n lustful ly has already comm itted adultery with her in his heart. 29 If your right eye causes you to stumble, gouge it out and throw it away. It is better for you to lose one part of your body than for your whole body to be thrown into hell. 30 And if your r ight hand causes you to stumble, cut it off and throw it away. It is bet ter for you to lose one part of your body than for your whole body to go into hell. Divorce 31 “It has been said, ‘Anyone who divorce s his wife must give her a certificate of divorce.’ g 32 But I tell you that anyone who divorces his wife, except for sexua l immoralit y, makes her the victim of adultery, and anyone who mar ries usalem, for it is the city of the Great King. 36 And do not s wear by your head, for you cannot make even one hair white or black. 37 All you need to say is simply ‘Yes’ or ‘No’; anything beyond this comes from the evil one. h Eye for Eye 38 “You have heard that it was said, ‘Eye for eye, and tooth for tooth.’ i 39 But I tell you, do not resist an evil person. If anyone s laps you on the right c heek, turn to them the other a 15 Or seed ; also in verse 16 b 21 Exodus 20:13 c 22 The Greek word for brother or sister (adelphos) refers here to a fellow disciple, whether man or woman; also in verse 23. d 22 Some manuscripts brother or sister without cause e 22 An Aramaic term of contempt f 27 Exodus 20:14 g 31 Deut. 24:1 h 37 Or from evil i 38 Exodus 21:24; Lev. 24:20; Deut. 19:21 DAY 7 20 c heek.” PSALM 5:1 — 5:12. REWIND Genesis 11:10 – 13:18; Matthew 5:21 – 42; Psalm 5 GOD WON’T GIVE UP ON HUMANKIND. Just when it looks like p eople might be trapped in sin forever, Genesis 11 – 13 reveals the first steps of God’s plan to save us. The Lord commands Abraham to leave his home country, promising him land and countless descendants. In Matthew 5 Jesus gives fresh ideas for getting along with adversaries and the opposite sex. And Psalm 5 offers hope in a cruel world. God hears your prayers, and because of his great love, he lets you come close to him. D day7 GENESIS 14:1 — 16:16 Abram Rescues Lot 14 At the time when Amraphel was king of Shinar, b Arioch king of El l asar, Kedorlaomer king of Elam and Tidal king of Goy im, 2 these k ings went to war a gainst Bera king of Sodom, Birsha king of Gomor rah, Shinab king of Admah, Shemeber king of Zeboyim, and the king of Bela (that is, a In Hebrew texts 5:1-12 is numbered 5:2-13. b 1 That is, Babylonia; also in verse 9 DAY 7 21 Zoar). 3 All these latter k ings joined forces in the Valley of Sidd im (that is, the Dead Sea Valley). 4 For t welve y ears they had been sub ject to Kedorlaomer, but in the thirteenth year they rebelled. 5 In the four teenth year, Kedorl aomer and the k ings allied with him went out and de feated the Repha ites in Ashteroth Karna im, the Zuzites in Ham, the E mites in Shaveh Kiriathaim 6 and the Horites in the hill coun try of Seir, as far as El Paran near the des ert. 7 Then they t urned back and went to En Mishpat (that is, Kadesh), and they conquered the whole territor y of the Ama lekites, as well as the Amorites who were living in Hazez on Tamar. 8 Then the king of Sod om, the king of Gomorrah, the king of Admah, the king of Zeboyim and the king of Bela (that is, Zoar) marched out and drew up t heir batt le lines in the Valley of Sidd im 9 against Kedorlaomer king of Elam, Tidal king of Goyim, Amra phel king of Shinar and Arioch king of Ella sar — four k ings against five. 10 Now the Val ley of Sidd im was full of tar pits, and when the k ings of Sodom and Gomorrah fled, some of the men fell into them and the rest fled to the hills. 11 The four k ings seized all the goods of Sodom and Gomorrah and all t heir food; then they went away. 12 They also carr ied off A bram’s nephew Lot and his possessions, since he was living in Sodom. 13 A man who had escaped came and report ed this to A bram the Hebrew. Now A bram was living near the g reat trees of Mamre the Amor ite, a brother a of Eshkol and Aner, all of whom were allied with A bram. 14 When Abram heard that his relative had been tak en captive, he called out the 318 trained men born in his household and went in pursuit as far as Dan. 15 During the n ight A bram di vided his men to attack them and he routed them, pursuing them as far as Hobah, n orth of Damasc us. 16 He recovered all the goods and brought back his relative Lot and his pos sessions, together with the women and the other people. 17 Af t er A bram ret urned from defeat i ng Kedorlaomer and the k ings al l ied with him, the king of Sodom came out to meet him in the Valley of Shaveh (that is, the K ing’s Val ley). 18 Then Melc hiz ed ek king of Sa l em brought out bread and wine. He was p riest of God Most High, 19 and he blessed A bram, say ing, your self.” 22 But Abram said to the king of Sodom, “With raised hand I have s worn an oath to the Lord, God Most High, Creator of heav en and earth, 23 that I will accept nothing be longing to you, not even a thread or the strap of a sandal, so that you will never be able to say, ‘I made Abram rich.’ 24 I will accept noth ing, b your very great reward. c ” 2 But A bram said, “Sovereign Lord, what can you give me s ince I remain childless and the one who will inherit d my estate is Elie zer of Damasc us?” 3 And A a 13 Or a relative; or an ally b 1 Or sovereign c 1 Or shield; / your reward will be very great d 2 The meaning of the Hebrew for this phrase is uncertain. DAY 7 22 can count them.” Then he said to him, “So shall your offspring a be.” 6 Abram believed the Lord, and he credit ed it to him as righteousness. 7 He also said to him, “I am the Lord, who brought you out of Ur of the Chaldeans to give you this land to take possession of it.” 8 But A bram said, “Sovereign Lord, how can I know that I will gain possession of it?” 9 So the Lord said to him, “Bring me a heifer, a goat and a ram, each three years old, a long with a dove and a young pigeon.” 10 Abram brought all t hese to him, cut them in two and arranged the halves opposite each other; the b irds, however, he did not cut in half. 11 Then b irds of prey came down on the carcasses, but Abram drove them away. 12 As the sun was sett ing, A bram fell into a deep s leep, and a t hick and dreadf ul dark ness came over him. 13 Then the Lord said to him, “Know for certain that for four hun dred years your descendants will be strang ers in a count ry not t heir own and that they will be enslaved and mistreated there. 14 But I will punish the nat ion they serve as slaves, and afterward they will come out with g reat possessions. 15 You, however, will go to your ancestors in peace and be buried at a good old age. 16 In the fourth generat ion your descen dants will come back here, for the sin of the Amorites has not yet reached its full measure.” 17 When the sun had set and darkness had fallen, a smoking firepot with a blazing t orch app eared and p assed bet ween the piece s. 18 On that day the Lord made a cov enant with Abram and said, “To your descendants I give this land, from the Wadi b of Egypt to the great river, the Euphrates — 19 the land of the Kenites, Kenizzites, Kadmonites, 20 Hitt ites, Perizzites, Rephaites, 21 Amor ites, Canaan ites, Girgashites and Jebusites.” Hagar and Ishmael 16 Now Sarai, A bram’s wife, had borne him no child ren. But she had an Egyptian slave named Hagar; 2 so she said to Abram, “The Lord has kept me from having child ren. Go, sleep with my slave; perhaps I can build a family through her.” Abram agreed to what Sarai said. 3 So after bram had been living in Canaan ten years, A Sarai his wife took her Egyptian slave Hagar and gave her to her husband to be his wife. 4 He slept with Hagar, and she conceived. When she knew she was pregnant, she be gan to despise her mistress. 5 Then Sarai said to Abram, “You are responsible for the w rong I am suffering. I put my slave in your arms, and now that she k nows she is pregnant, she despises me. May the Lord judge bet ween an g el of the Lord told her, “Go back to your mistress and submit to her.” 10 The angel added, “I will inc rease your de scendants so much that they will be too nu merous to count.” 11 The angel of the Lord also said to her: “You are now pregnant and you will give birth to a son. You shall name him Ishmael, c for the Lord has heard of your misery. 12 He will be a wild donkey of a man; his hand will be against everyone and everyone’s hand against him, and he will live in hostility d all his brothers.” toward 13 She gave this name to the Lord who s poke to her: “You are the God who sees me,” for she said, “I have now seen e the One who sees me.” 14 That is why the well was called Beer Lahai Roi f ; it is still there, bet ween Ka desh and Bered. 15 So Hagar bore Abram a son, and Abram gave the name Ishmael to the son she had borne. 16 Abram was eighty-six y ears old when Hagar bore him Ishmael. a 5 Or seed b 18 Or river c 11 Ishmael means God hears. d 12 Or live to the east / of e 13 Or seen the back of f 14 Beer Lahai Roi means well of the Living One who sees me. 23 MATTHEW 5:43 — 6:24 rew ard will you get? Are not even the tax collectors doing that? 47 And if you greet only your own people, what are you doing more than others? Do not even pagans do that? 48 Be perfect, therefore, as your heavenly Father is perfect. DAY 7 “, b but deliver us from the evil one. c ’ 14 For if you forg ive other people when they sin against you, your heavenly Father will also forgive you. 15 But if you do not forgive others their sins, your Father will not forg ive your sins. Giving to the Needy Fasting “Be careful not to practice your righ teousness t heir reward in full. 3 But when you give to the needy, do not let your left hand know what your right hand is doing, 4 so that your giving may be in secret. Then your Fa ther, who sees what is done in secret, will re ward you. 16 “When you fast, do not look som ber as the hypocrites do, for they disfigu re their faces to show others they are fasting. Tru ly I tell you, they have received t heir reward in full. 17 But when you fast, put oil on your head and wash your face, 18 so that it will not be obv ious to others that you are fasting, but only to your Father, who is unseen; and your Fat her, who sees what is done in secret, will reward you. 6 Prayer 5 “And when you pray, do not be like the hypoc rites, for they love to pray standing in the synagogues and on the street corners to be seen by others. Truly I tell you, they have received t heir reward in full. 6 But when you pray, go into your room, c lose the door and pray to your Father, who is unseen. Then your Fat her, who sees what is done in secret, will reward you. 7 And when you pray, do not keep on babbling like pagans, for they t hink they will be heard because of their many words. 8 Do not be like them, for your Fat her k nows what you need before you ask him. 9 “This, then, is how you should pray: Treasures in Heaven 19 “Do not store up for yourselves treasures on earth, where moths and verm in destroy, and where thieves b reak in and steal. 20 But store up for yourselves treasures in heav en, w here moths and vermin do not destroy, and where t hieves do not break in and steal. 21 For where your treasure is, t here your heart will be also. 22 “The eye is the lamp of the body. If your eyes are healthy, d your whole body will be full of l ight. 23 But if your eyes are unhealthy, e your w hole body will be full of darkness. If then the light within you is darkness, how great is that darkness! 24 “No one can serve two masters. Either you will hate the one and love the other, or you will be devoted to the one and despise the oth er. You cannot serve both God and money.” a 43 Lev. 19:18 b 13 The Greek for temptation can also mean testing. c 13 Or from evil ; some late manuscripts one, / for yours is the kingdom and the power and the glory forever. Amen. d 22 The Greek for healthy here implies generous. e 23 The Greek for unhealthy here implies stingy. DAY 8 24 PSALM 6:1 — 6:10 Psalm 6 a as your master. And Psalm 6 promises that the Lord hears your crying when you flood your bed with tears.. REWIND Genesis 14 – 16; Matthew 5:43 – 6:24; Psalm 6 THE LORD KNOWS WHAT HE’S DOING. In Genesis 14 – 16 Abraham doesn’t understand how God can make a childless man the father of a mighty nation, so he sleeps with a slave to produce a son. But in Matthew 5 – 6 God dares you to do life his way. Jesus challenges you to love your enemies like he does, to trust him with your needs, and to choose him day8 GENESIS 17:1 — 18:33 The Covenant of Circumcision 17 When Abram was ninet y-nine y ears old, the Lord appeared to him and said, “I am God Almighty c; walk before me faithf ul ly and be blameless. 2 Then I will make my covenant bet ween me and you and will greatly increase your numbers.” 3 Abram fell face down, and God said to him, 4 “As for me, this is my covenant with you: You will be the fat her of many nat ions. 5 No longer will you be c alled A bram d ; your name will be Abraham, e for I have made you a father of many nations. 6 I will make you very fruitf ul; I will make nations of you, and k ings will come from you. 7 I will establish my cov enant as an everlasting covenant bet ween me and you and your descendants after you for the generations to come, to be your God and the God of your descendants after you. 8 The whole land of Canaan, where you now reside as a foreigner, I will give as an everlasting pos session to you and your descendants after you; and I will be their God.” 9 Then God said to Abraham, “As for you, you must keep my covenant, you and your descendants af ter you for the generat ions to come. 10 This is my covenant with you and your descendants after you, the covenant you are to keep: Every male a mong you shall be circumcised. 11 You are to undergo circumci a In Hebrew texts 6:1-10 is numbered 6:2-11. b Title: Probably a musical term c 1 Hebrew El-Shaddai d 5 Abram means exalted father. e 5 Abraham probably means father of many. 25 sion, and it will be the sign of the covenant between me and you. 12 For the generat ions to come every male a mong you who is e ight days old must be circumcised, including t hose born in your household or bought with mon ey from a foreigner — those who are not your offspring. 13 Whether born in your household or bought with your money, they must be cir cumcised. My covenant in your f lesh is to be an everlasting covenant. 14 Any uncircumcised male, who has not been circ umc ised in the f lesh, will be cut off from his people; he has broken my covenant.” 15 God also said to Abraham, “As for Sarai your wife, you are no longer to call her Sarai; her name will be Sara h. 16 I will bless her and will surely give you a son by her. I will bless her so that she will be the mother of nations; k ings of peoples will come from her.” 17 Abraham fell facedown; he laughed and said to himself, “Will a son be born to a man a hund red years old? Will Sara h bear a child at the age of ninet y?” 18 And Abraham said to God, “If only Ishmael might live under your blessing!” 19 Then God said, “Yes, but your wife Sar ah fruitf ul and will greatly increase his numbers. He will be the fat her of t welve rulers, and I will make him into a g reat nat ion. 21 But my covenant I will establish with Isaac, whom Sarah will bear to you by this time next year.” 22 When he had finished speaking with Abra ham, God went up from him. 23 On that very day Abraham took his son Ishmael and all those born in his household or b ought with his money, every male in his household, and circumcised them, as God told him. 24 Abraham was ninet y-nine years old when he was circ umcised, 25 and his son Ishmael was thirteen; 26 Abraham and his son Ishmael were both circ umcised on that very day. 27 And every male in Abraham’s house hold, inc luding those born in his household or bought from a foreigner, was circumcised with him. The Three Visitors 18 The Lord appeared to Abraham near the g reat trees of Mamre while he was sitt ing at the ent rance, b do not pass your servant by. 4 Let a litt le water be brought, and then you may all wash your feet and rest under this tree. 5 Let me get you somet hing to eat, so you can be refreshed and then go on your way — now that you have come to your servant.” “Very well,” they answered, “do as you say.” 6 So Abra h am hurried into the tent to Sara h. “Quick,” he said, “get three sea hs c of the finest f lour and k nead it and bake some bread.” 7 Then he ran to the herd and se lected a choice, tender calf and gave it to a servant, who hurried to prepare it. 8 He then brought some curds and milk and the calf that had been pre pared, and set these before them. W hile they ate, he stood near them under a tree. 9 “Where is your wife Sar a h?” they asked him. “There, in the tent,” he said. 10 Then one of them said, “I will sure ly ret urn to you about this time next year, and Sarah your wife will have a son.” Now Sarah was listening at the entrance to the tent, which was behind him. 11 Abraham and Sara h were already very old, and Sara h was past the age of childbearing. 12 So Sara h ret urn to you at the appointed time next year, and Sarah will have a son.” a 19 Isaac means he laughs. b 3 Or eyes, Lord c 6 That is, probably about 36 pounds or about 16 kilograms DAY 8 DAY 8 26 15 Sara h was a fraid, so she lied and said, “I did not laugh.” But he said, “Yes, you did laugh.” Abraham Pleads for Sodom 16 When the men got up to leave, they looked down toward Sodom, and Abraham walked a long with them to see them on their way. 17 Then the Lord said, “Shall I hide from Abraham what I am about to do? 18 Abraham will surely become a g reat and powerful na tion, and all nations on e arth will be blessed t hrough him. a 19 For I have chosen him, so that he will direct his children and his house hold after him to keep the way of the Lord by doing what is right and just, so that the Lord will bring about for Abraham what he has promised him.” 20 Then the Lord said, “The outc ry against Sodom and Gomorrah is so g reat and their sin so grievous 21 that I will go down and see if what they have done is as bad as the outc ry that has reached me. If not, I will know.” 22 The men t urned away and went tow ard Sodom, but Abraham remained standing be fore the Lord. b 23 Then Abraham approached him and said: “Will you sweep away the righ teous with the wicked? 24 What if there are fifty righteous people in the city? Will you really sweep it away and not spare c the p lace for the sake of the fift y righteous people in it? 25 Far be it from you to do such a t hing — to kill the righteous with the wicked, treating the righteous and the wicked a like. Far be it from you! Will not the Judge of all the earth do right?” 26 The Lord said, “If I find fift y righteous people in the city of Sodom, I will s pare the whole place for their sake.” 27 Then Abra ham spoke up a gain: “Now that I have been so bold as to speak to the Lord, though I am nothing but dust and ash es, 28 what if the number of the righteous is five less than fifty? Will you destroy the whole city for lack of five people?” “If I find fort y-five t here,” he said, “I will not destroy it.” 29 Once again he spoke to him, “What if only fort y are found there?” He said, “For the sake of fort y, I will not do it.” 30 Then he said, “May the Lord not be an gry, but let me speak. What if only thirt y can be found there?” He answered, “I will not do it if I find thir ty there.” 31 Abra ham said, “Now that I have been so bold as to speak to the Lord, what if only twent y can be found there?” He said, “For the sake of twent y, I will not destroy it.” 32 Then he said, “May the Lord not be an gry, but let me speak just once more. What if only ten can be found there?” He ans wered, “For the sake of ten, I will not destroy it.” 33 When the Lord had finished speaking with Abrah am, he left, and Abrah am re turned home. MATTHEW 6:25 — 7:23 Do Not Worry 25 “Therefore I tell you, do not worr y about your life, what you will eat or drink; or about your body, what you will wear. Is not life more than food, and the body more than c lothes? 26 Look at the birds of the air; they do not sow or reap or store away in barns, and yet your heavenly Father f eeds them. Are you not much more valuable than they? 27 Can any one of you by worr ying add a single hour to your life d ? 28 “And why do you wor r y about c lothes? See how the flowers of the f ield grow. They do not labor or spin. 29 Yet I tell you that not even Solomon in all his splendor was dressed like one of these. 30 If that is how God clothes the grass of the f ield, which is here today and tomorrow is thrown into the fire, will he not much more c lothe you — you of little faith? 31 So do not wor r y, saying, ‘What shall we eat?’ or ‘What shall we drink?’ or ‘What shall we wear?’ 32 For the pagans run after all t hese things, and your heavenly Father k nows that a 18 Or will use his name in blessings (see 48:20) b 22 Masoretic Text; an ancient Hebrew scribal tradition but the Lord remained standing before Abraham c 24 Or forgive; also in verse 26 d 27 Or single cubit to your height 27 you need them. 33 But seek f irst his kingdom and his righteousness, and all these things will be given to you as well. 34 Therefore do not worr y about tomorrow, for tomorrow will worr y a bout itself. Each day has enough trou ble, f irst take the p lank out of your own eye, and then you will see clear ly to remove the speck from your brother’s eye. 6 “Do not give dogs what is sac red; do not throw your pearls to pigs. If you do, they may trample them under t heir feet, and turn and tear you to pieces. Ask, Seek, Knock 7 “Ask and it will be given to you; seek and you will find; k nock and the door will be opened to you. 8 For everyone who asks re ceives; the one who seeks finds; and to the one who k nocks, the door will be opened. 9 “Which of you, if your son asks for bread, will give him a stone? 10 Or if he asks for a fish, will give him a snake? 11 If you, then, t hough you are evil, know how to give good g ifts to your child ren, how much more will your Father in heaven give good gifts to those who ask him! 12 So in everything, do to others what you would have them do to you, for this sums up the Law and the Prophets. The Narrow and Wide Gates 13 “Enter t hrough DAY 8 are ferocious wolves. 16 By t heir fruit you will recognize them. Do people pick g rapes from thornbushes, or figs from thistles? 17 Likew ise, every good tree b ears good f ruit, but a bad tree bears bad fruit. 18 A good tree cannot bear bad fruit, and a bad tree cannot bear good fruit. 19 Every tree that does not bear good f ruit is cut down and thrown into the fire. 20 Thus, by their fruit you will recognize them.” True and False Disciples 21 “Not ev eryone who says to me, ‘Lord, Lord,’ will enter the kingdom of heaven, but only the one who does the will of my Fat her who is in heaven. 22 Many will say to me on that day, ‘Lord, Lord, did we not prophesy in your name and in your name drive out demons and in your name perform many mirac les?’ 23 Then I will tell them plainly, ‘I never knew you. Away from me, you evildoers!’ ” PROVERBS 1:8 — 1:19! DAY 9 28 19 Such are the paths of all who go after ill-gotten gain; it takes away the life of those who get it. REWIND Genesis 17 – 18; Matthew 6:25 – 7:23; Proverbs 1:8 – 19 GOD NEVER BREAKS HIS PROMISES. When God swears in Genesis 17 – 18 that Abraham and Sarah will produce a son, the elderly woman laughs. But God himself reminds her nothing is too hard for him. Matthew 6 – 7 declares that the Lord cares for you far more than flowers, which he clothes with magnificent splendor. He won’t leave you unfed or unclothed, and he grants your good requests. Proverbs 1 assures you that God’s wisdom keeps you from joining in evil people’s sins. D day9 GENESIS 19:1 — 20:18 Sodom and Gomorrah Destroyed 19 The two angels arr ived at Sodom in the even ing, and Lot was sitting in the gateway of the city. When he saw them, he got up to meet them and bowed down with his face to the g round. 2 “My lords,” he said, “please turn aside to your servant’s house. You can wash your feet and spend the n ight and then go on your way early in the morning.” “No,” they answered, “we will spend the night in the square.” 3 But he insisted so strongly that they did a 14 Or were married to go with him and entered his house. He pre pared a meal for them, baking bread without yeast, and they ate. 4 Before they had gone to bed, all the men from every part of the city of Sodom — both young and old — sur rounded the house. 5 They called to Lot, “Where are the men who came to you tonight? Bring them out to us so that we can have sex with them.” 6 Lot went outside to meet them and shut the door beh ind b reak down the door. 10 But the men in side be longs to you? Get them out of here, 13 because we are going to destroy this place. The outcry to the Lord against its people is so great that he has sent us to destroy it.” 14 So Lot went out and spoke to his sons-inlaw, who were pledged to marr y a his daugh ters. He said, “Hurr y and get out of this place, because the Lord is about to destroy the city!” But his sons-in-law thought he was joking. 15 With the com i ng of dawn, the angels u rged Lot, saying, “Hurry! Take your wife and your two daughters who are here, or you will be swept away when the city is punished.” 16 When he hesitated, the men g rasped his hand and the hands of his wife and of his two daughters and led them safely out of the city, for the Lord was mercif ul to them. 17 As soon as they had brought them out, one of them said, “Flee for your lives! Don’t look back, and 29 on’t stop anywhere in the plain! Flee to the d mountains or you will be swept away!” 18 But Lot said to them, “No, my lords, a please! 19 Your b serv ant has found favor in your b eyes, and you b have s hown g reat kind ness g rant this request too; I will not overthrow the town you speak of. 22 But flee there quickly, because I cannot do anything until you r each it.” (That is why the town was called Zoar. c ) 23 By the time Lot reached Zoar, the sun had risen over the land. 24 Then the Lord rained down burning sulfur on Sodom and Gomorrah — from the Lord out of the heav ens. 25 Thus he overthrew those cities and the entire plain, destroying all those living in the cities — a nd also the vegetation in the land. 26 But L ot’s wife looked back, and she became a pillar of salt. 27 Early the next morning Abraham got up and ret urned to the place where he had stood before the Lord. 28 He looked down toward Sodom and Gomorrah, toward all the land of the plain, and he saw dense smoke rising from the land, like smoke from a furnace. 29 So when God de stroyed the cities of the plain, he remembered Abraham, and he brought Lot out of the catastrophe that over threw the cities where Lot had lived. Lot and His Daughters 30 Lot and his two daughters left Zoar and sett led in the mountains, for he was a fraid to stay in Zoar. He and his two daughters lived in a cave. 31 One day the older daughter said to the younger, “Our father is old, and there is no man a round here to give us children — as is the custom all over the earth. 32 Let’s get our father to drink wine and then sleep with him and preserve our family line t hrough our fa ther.” DAY 9 33 That n ight they got their father to drink wine, and the older daughter went in and s lept with him. He was not a ware of it when she lay down or when she got up. 34 The next day the older daughter said to the younger, “Last n ight I s lept with my fa ther. L et’s get him to d rink wine a gain to night, and you go in and sleep with him so we can preserve our family line through our fat her.” 35 So they got their father to d rink wine that night also, and the younger daugh ter went in and slept with him. Again he was not aware of it when she lay down or when she got up. 36 So both of L ot’s daughters became preg nant by t heir father. 37 The older daughter had a son, and she named him Moab d ; he is the fa ther of the Moabites of today. 38 The younger daughter also had a son, and she named him Ben-Ammi e; he is the father of the Ammon ites f of today. Abraham and Abimelek 20 Now Abraham moved on from there into the region of the Negev and lived between Kadesh and Shur. For a while he stayed in Gerar, 2 and there Abraham said of his wife Sarah, “She is my sister.” Then Abim elek king of Gerar sent for Sarah and took her. 3 But God came to Abim elek in a d ream sis ter,’ and didn’t she also say, ‘He is my brother’? I have done this with a c lear conscience and clean hands.” 6 Then God said to him in the d ream, “Yes, I know you did this with a c lear conscience, and so I have kept you from sinning against me. That is why I did not let you touch her. 7 Now ret urn the man’s wife, for he is a proph et, and he will pray for you and you will live. But if you do not ret urn her, you may be sure that you and all who belong to you will die.” a 18 Or No, Lord ; or No, my lord b 19 The Hebrew is singular. c 22 Zoar means small. d 37 Moab sounds like the Hebrew for from father. e 38 Ben-Ammi means son of my father’s people. f 38 Hebrew Bene-Ammon DAY 9 30 8 Ear ly the next morning Abimelek sum moned all his off icials, and when he told them all that had happened, they were very much a fraid. 9 Then Abimelek called Abra ham in and said, “What have you done to us? How have I w ronged you that you have b rought such g reat g uilt upon me and my kingdom? You have done things to me that should nev er be done.” 10 And Abimelek asked Abraham, “What was your reason for doing this?” 11 Abra h am re plied, “I said to my s elf, ‘There is surely no fear of God in this p lace, and they will kill me bec ause catt le and male and female slaves and gave them to Abraham, and he ret urned Sara h his wife to him. 15 And Abimelek said, “My land is before you; live wherever you like.” 16 To Sar a him elek’s household from conceiv ing because of Abraham’s wife Sarah. MATTHEW 7:24 — 8:22 The Wise and Foolish Builders 24 “Therefore everyone who hears t hese ords of mine and puts them into practice is w like a wise man who built his h ouse on the rock. 25 The rain came down, the streams rose, and the w inds blew and beat a gainst that house; yet it did not fall, because it had its foundation on the rock. 26 But everyone who hears t hese words of mine and does not put them into practice is like a foolish man who built his house on sand. 27 The rain came down, the s treams rose, and the w inds blew and beat a gainst that house, and it fell with a g reat crash.” 28 When Jesus had finished saying these t hings, the crowds were amazed at his teach ing, 29 because he taught as one who had au thorit y, and not as their teachers of the law. Jesus Heals a Man With Leprosy 8 When Jesus came down from the moun tainside, large crowds fol lowed him. 2 A man with leprosy b came and k nelt before him and said, “Lord, if you are willing, you can make me clean.” 3 Jesus r eached out his hand and touched the man. “I am willing,” he said. “Be c lean!” Immed iately he was c leansed of his lepros y. 4 Then Jesus said to him, “See that you don’t tell anyone. But go, show yourself to the priest and offer the gift Moses commanded, as a tes timony to them.” The Faith of the Centurion 5 When J esus had ent ered Cap er n au m, a centurion came to him, asking for help. 6 “Lord,” he said, “my servant lies at home par alyzed, suffering terribly.” 7 Jesus said to him, “Shall I come and heal him?” 8 The cent ur ion replied, “Lord, I do not de serve to have you come under my roof. But just say the word, and my servant will be healed. 9 For I myself am a man under aut horit y, with soldiers under me. I tell this one, ‘Go,’ and he goes; and that one, ‘Come,’ and he c omes. I say to my servant, ‘Do this,’ and he does it.” 10 When Jesus heard this, he was a mazed! a 16 That is, about 25 pounds or about 12 kilograms b 2 The Greek word traditionally translated leprosy was used for various diseases affecting the skin. DAY 9 31 Let it be done just as you believed it would.” And his servant was healed at that moment. Jesus Heals Many 14 When Jesus came into Peter’s h ouse, he saw Peter’s mother-in-law lying in bed with a fever. 15 He touched her hand and the fever left her, and she got up and began to wait on him. 16 When even ing came, many who were de mon-possessed were brought to him, and he d rove c rowd a round him, he gave orders to cross to the other side of the lake. 19 Then a teacher of the law came to him and said, “Teacher, I will follow you wherever you go.” 20 Jesus replied, “Foxes have d ens and b irds have n ests, but the Son of Man has no place to lay his head.” 21 Another disc iple said to him, “Lord, f irst let me go and bury my father.” 22 But Jesus told him, “Follow me, and let the dead bury their own dead.” PSALM 7:1 — 7:9 Psalm 7 b A shiggaion. 5 then let my enemy pursue and overtake me; let him trample my life to the ground and make me sleep in the dust.. REWIND Genesis 19 – 20; Matthew 7:24 – 8:22; Psalm 7:1 – 9 IT’S WISE TO LISTEN AND OBEY. Genesis 19 – 20 shows the Lord destroying the cities of Sodom and Gomorrah because of their disobedience. In Matthew 7:24 – 27 Jesus warns that people who ignore his words are like a man who builds a house on sand. When a storm blows hard, his home crashes down. But anyone who acts on his words stays safe. Psalm 7 says those who do good can go to God and find refuge, a place where no one can tear them to pieces. D 3 Lord my God, if I have done this and there is guilt on my hands — 4 if I have repaid my ally with evil or without cause have robbed my foe — a 17 Isaiah 53:4 (see Septuagint) b In Hebrew texts 7:1-17 is numbered 7:2-18. c Title: Probably a literary or musical term d 5 The Hebrew has Selah (a word of uncertain meaning) here. DAY 10 32 day10 GENESIS 21:1 — 23:20 The Birth of Isaac 21 Now the Lord was gracious to Sarah as he had said, and the Lord did for Sara h what he had promised. 2 Sarah became pregnant and bore a son to Abraham in his old age, at the very time God had promised him. 3 Abra ham gave the name Isaac a to the son Sarah bore him. 4 When his son Isaac was eight days old, Abraham circumcised him, as God commanded him. 5 Abraham was a hund red years old when his son Isaac was born to him. 6 Sara h said, “God has brought me laughter, and everyone who hears about this will laugh with me.” 7 And she added, “Who would have said to Abraham that Sara h would nurse chil dren? Yet I have b orne him a son in his old age.” Hagar and Ishmael Sent Away 8 The c hild grew and was weaned, and on the day Isaac was w eaned Abraham held a great feast. 9 But Sara h saw that the son whom Hagar the Egyptian had b orne to Abraham was mock i ng, 10 and she said to Abraham, “Get rid of that slave woman and her son, for that woma n’s son will never share in the in heritance with my son Isaac.” 11 The mat ter dist ressed Abra ham great ly because it concerned his son. 12 But God said to him, “Do not be so distressed about the boy and your slave woman. Listen to whatever Sara h tells you, because it is through Isaac that your offspring b will be reckoned. 13 I will make the son of the slave into a nat ion also, because he is your offspring.” 14 Ear ly the next morning Abraham took some food and a skin of water and gave them to Hagar. He set them on her shoulders and then sent her off with the boy. She went on her way and wandered in the Desert of Be ers c alled to Hagar from heaven and said to her, “What is the matter, Hagar? Do not be a fraid; God has heard the boy crying as he lies there. 18 Lift the boy up and take him by the hand, for I will make him into a great nation.” 19 Then God opened her eyes and she saw a well of water. So she went and f illedim elek and Phicol the commander of his forces said to Abraham, “God is with you in everything you do. 23 Now swear to me here before God that you will not deal falsely with me or my children or my de scendants. Show to me and the country where you now reside as a foreigner the same kind ness I have shown to you.” 24 Abraham said, “I s wear it.” 25 Then Abraham complained to Abimelek about a well of water that Abimelek’s servants had s eized. 26 But Abimelek said, “I don’t know who has done this. You did not tell me, and I heard about it only today.” 27 So Abra ham b rought sheep and cattle and gave them to Abimelek, and the two men made a treat y. 28 Abraham set apart seven ewe lambs from the f lock, 29 and Abimelek asked Abraham, “What is the meaning of these seven ewe lambs you have set a part by them selves?” 30 He replied, “Acc ept t hese seven l ambs from my hand as a witness that I dug this well.” 31 So that place was called Beersheba, d be cause the two men swore an oath there. 32 After the treat y had been made at Beer sheba, Abimelek and Phicol the commander a 3 Isaac means he laughs. b 12 Or seed c 16 Hebrew; Septuagint the child d 31 Beersheba can mean well of seven and well of the oath. DAY 10 33 of his forces ret urned to the land of the Phi listines. 33 Abraham planted a tama risk tree in Beersheba, and there he called on the name of the Lord, the Eternal God. 34 And Abra ham stayed in the land of the Philist ines for a long time. Abraham Tested 22 Some time later God tested Abra ham. He said to him, “Abraham!” “Here I am,” he replied. 2 Then God said, “Take your son, your only son, whom you love — Isaac — a nd go to the reg ion of Moria h. Sacrifice him there as a burnt offering on a mountain I will show you.” 3 Early the next morning Abraham got up and loaded his donkey. He took with him two of his servants and his son I sa of fering and placed it on his son Isaac, and he himself carried the fire and the k nife. As the two of them went on together, 7 Isaac spoke up and said to his father Abraham, “Father?” “Yes, my son?” Abraham replied. “The fire and wood are here,” Isaac said, “but where is the lamb for the burnt offering?” 8 Abra ham answered, “God himself will prov ide the lamb for the burnt offering, my son.” And the two of them went on together. 9 When they r eached the place God had told him about, Abraham built an altar there and arranged the wood on it. He b ound his son Isaac and laid him on the altar, on top of the wood. 10 Then he r eached out his hand and took the k nife t here in a thick et he saw a ram a caught by its horns. He went over and took the ram and sacr if iced it as a burnt offering instead of his son. 14 So Abra ham called that place The Lord Will Pro vide. And to this day it is said, “On the moun tain of the Lord it will be prov ided.” 15 The ang el of the Lord c alled to Abra ham from heaven a second time 16 and said, “I swear by myself, dec lares the Lord, that be cause you have done this and have not with held your son, your only son, 17 I will surely bless you and make your descendants as nu merous as the stars in the sky and as the sand on the seashore. Your descendants will take possession of the cities of their enemies, 18 and t hrough your offspring b all nat ions on earth will be blessed, c because you have obeyed me.” 19 Then Abraham ret urned to his servants, and they set off together for Beersheba. And Abraham stayed in Beersheba. Nahor’s Sons 20 Some time lat e r Abra h am was told, “Milk ah is also a mother; she has b orne sons to your brother Nahor: 21 Uz the firstborn, Buz his brother, Kemuel (the father of Aram), 22 Kesed, Hazo, Pild ash, Jidlaph and Bet hu el.” 23 Bethuel became the father of Rebeka h. Milk ah bore these e ight sons to Abraham’s brother Nahor. 24 His concubine, whose name was Reumah, also had sons: Tebah, Gaham, Tahash and Maak ah. The Death of Sarah 23 Sarah lived to be a hund red and twent y-seven y ears ites. d He said, 4 “I am a foreigner and stranger a mong you. Sell me some propert y for a buria l site here so I can bury my dead.” a 13 Many manuscripts of the Masoretic Text, Samaritan Pentateuch, Septuagint and Syriac; most manuscripts of the Masoretic Text a ram behind him b 18 Or seed c 18 Or and all nations on earth will use the name of your offspring in blessings (see 48:20) d 3 Or the descendants of Heth; also in verses 5, 7, 10, 16, 18 and 20 DAY 10 34 5 The Hit t ites replied to Abraham, 6 “Sir, listen to us. You are a mighty prince a mong us. Bury your dead in the choicest of our tombs. None of us will refuse you his tomb for burying your dead.” 7 Then Abraham rose and bowed down be fore f ield. Ask him to sell it to me for the full price as a buria l site among you.” 10 Ephron the Hit t ite was sitting a mong his people and he replied to Abraham in the hearing of all the Hitt ites who had come to the gate of his city. 11 “No, my lord,” he said. “Listen to me; I give a you the field, and I give a you the cave that is in it. I give a it to you in the presence of my people. Bury your dead.” 12 Again Abraham b owed down before the people of the land 13 and he said to Ephron in their hearing, “Listen to me, if you will. I will pay the price of the f ield. Accept it from me so I can bury my dead there.” 14 Ephron ans wered Abraham, 15 “Listen to me, my lord; the land is w orth four hund red shekels b of silver, but what is that bet ween you and me? Bury your dead.” 16 Abraham a greed to Ephron’s terms and weighed out for him the p rice he had n amed in the hearing of the Hittites: four hund red shekels of silver, according to the weight cur rent among the merchants. 17 So Ephron’s field in Machp elah near Mamre — both the f ield and the cave in it, and all the trees within the borders of the f ield — was deede d 18 to Abrah am as his propert y in the presence of all the Hittites who had come to the gate of the city. 19 Af terw ard Abrah am buried his wife Sarah in the cave in the f ield of Machp elah near Mamre (which is at Hebron) in the land of Canaan. 20 So the f ield and the cave in it were deeded to Abraham by the Hitt ites as a buri al site. MATTHEW 8:23 — 9:13 Jesus Calms the Storm 23 Then he got into the boat and his disc i ples followed him. 24 Suddenly a furious storm came up on the lake, so that the waves s wept over the boat. But Jesus was sleeping. 25 The disciples went and woke him, saying, “Lord, save us! We’re going to drown!” 26 He replied, “You of litt le faith, why are you so a fraid?” Then he got up and rebuked the w inds and the waves, and it was complete ly calm. 27 The men were a mazed and asked, “What kind of man is this? Even the w inds and the waves obey him!” Jesus Restores Two DemonPossessed Men 28 When he ar r ived at the othe r side in the reg ion of the Gada renes, c two demonpos s essed men com i ng from the t ombs met him. They were so violent that no one could pass that way. 29 “What do you want with us, Son of God?” they shouted. “Have you come here to tort ure us before the ap pointed time?” 30 Some distance from them a large herd of pigs was feeding. 31 The demons begged Jesus, “If you d rive report ed all this, inc luding what had happened to the demon-possessed men. 34 Then the whole town went out to meet Jesus. And when they saw him, they pleaded with him to leave their region. Jesus Forgives and Heals a Paralyzed Man 9 Jesus stepped into a boat, c rossed over and came to his own town. 2 Some men brought to him a para lyzed man, lying on a mat. When Jesus saw their f aith, he said to the man, “Take heart, son; your sins are forgiven.” a 11 Or sell b 15 That is, about 10 pounds or about 4.6 kilograms c 28 Some manuscripts Gergesenes; other manuscripts Gerasenes DAY 11 35 3 At this, some of the teachers of the law said to themselves, “This fellow is blaspheming!” 4 Knowing t heir t houghts, Jesus said, “Why do you entertain evil thoughts in your hearts? 5 Which is eas ier: to say, ‘Your sins are for given,’ or to say, ‘Get up and walk’? 6 But I want you to know that the Son of Man has authorit y on earth to forgive sins.” So he said to the para lyzed man, “Get up, take your mat and go home.” 7 Then the man got up and went home. 8 When the c rowd saw this, they were f illed with awe; and they praised God, who had given such authorit y to man. The Calling of Matthew 9 As Jesus went on from t here, he saw a man amed Matt hew sitt ing at the tax collector’s n booth. “Follow me,” he told him, and Mat thew got up and followed him. 10 While Jesus was having dinner at Mat thew’s house, many tax collectors and sin ners merc y, not sacrif ice.’ a For I have not come to call the righteous, but sinners.” PSALM 7:10 — 7:17 10 My shield b is God Most High, who saves the upright in heart. 11 God is a righteous judge, a God who displays his wrath every day. 12 If he does not relent, c will sharpen his sword; he. REWIND Genesis 21 – 23; Matthew 8:23 – 9:13; Psalm 7:10 – 17 GOD DESERVES YOUR TRUST. Genesis 21 – 23 shows Abraham acting on a divine command to sacrifice his much-loved son, a test agonizing beyond imagination. In Matthew 8 – 9 people face intense challenges like paralysis, deadly waters, and legions of demons. And in Psalm 7 David finds himself face to face with swords and flaming arrows. In each of these grim situations, God proves he’s worth trusting. No matter what you endure today, you can be sure the Lord is on your side. D day11 GENESIS 24:1 — 24:67 Isaac and Rebekah 24 Abraham was now very old, and the Lord had blessed him in every way. 2 He said to the senior serv ant in his house hold, the one in c harge of all that he had, “Put your hand under my thigh. 3 I want you to swear by the Lord, the God of heaven and the God of earth, that you will not get a wife for my son from the daughters of the a 13 Hosea 6:6 b 10 Or sovereign c 12 Or If anyone does not repent, / God DAY 11 36 Canaanites, a mong whom I am liv ing, 4 but will go to my country and my own relatives and get a wife for my son Isaac.” 5 The ser v ant asked him, “What if the woman is unw illing to come back with me to this land? S hall I then take your son back to the country you came from?” 6 “Make sure that you do not take my son back t here,” Abraham said. 7 “The Lord, the God of heaven, who brought me out of my fa ther wom an is unw illing to come back with you, then you will be released from this oath of mine. Only do not take my son back there.” 9 So the servant put his hand under the thigh of his master Abraham and s wore an oath to him concerning this matter. 10 Then the ser vant left, taking with him ten of his master’s camels loaded with all k inds of good things from his master. He set out for Aram Naharaim b and made his way to the town of Nahor. 11 He had the camels k neel down near the well outside the town; it was toward even ing, the time the women go out to draw water. 12 Then he prayed, “Lord, God of my mas ter Abraham, make me successf ul I saac. By this I will know that you have shown kindness to my master.” 15 Before he had finished praying, Rebeka h came out with her jar on her shoulder. She was the daughter of Bet huel son of Milk ah, who was the wife of Abraham’s brother Nahor. 16 The woma n was very beaut if ul, a virg in; no man had ever slept with her. She went down to the spring, f illed her jar and came up again. 17 The servant hurr ied to meet her and said, “Please give me a litt le water from your jar.” 18 “Drink, my lord,” she said, and quick ly lowered the jar to her hands and gave him a drink. 19 After she had given him a d rink, she said, “I’ll draw water for your camels too, until they have had e nough to d rink.” 20 So she quickly emptied her jar into the trough, ran back to the well to draw more water, and drew enough for all his camels. 21 Without saying a word, the man watched her closely to learn whether or not the Lord had made his journey suc cessf ul. ans wered him, “I am the daughter of Bethuel, the son that Milk ah bore to Nahor.” 25 And she add ed, “We have plent y of straw and fodder, as well as room for you to spend the night.” 26 Then the man bowed down and wor shiped the Lord, 27 saying, “Praise be to the Lord, the God of my master Abraham, who has not abandoned his kindness and faithf ul ness to my master. As for me, the Lord has led me on the journey to the house of my mas ter’s relatives.” 28 The young wom a neka h tell what the man said to her, he went out to the man and found him standing by the camels near the spring. 31 “Come, you who are b lessed t heir feet. 33 Then food was a 7 Or seed b 10 That is, Northwest Mesopotamia c 22 That is, about 1/5 ounce or about 5.7 grams d 22 That is, about 4 ounces or about 115 grams 37 set before him, but he said, “I will not eat until I have told you what I have to say.” “Then tell us,” Laban said. 34 So he said, “I am Abra ham’s serv ant. 35 The Lord has blessed my master abundant ly, and he has become wealthy. He has given him sheep and cattle, silver and gold, male and female servants, and camels and donkeys. 36 My master’s wife Sara h has borne him a son in her old age, and he has given him every thing he owns. 37 And my master made me s wear an oath, and said, ‘You must not get a wife for my son from the daughters of the Ca naanites, in w hose land I live, 38 but go to my father’s family and to my own clan, and get a wife for my son.’ 39 “Then I asked my master, ‘What if the woman will not come back with me?’ 40 “He re plied, ‘The Lord, before whom I have walked faithfully, will send his angel with you and make your journey a success, so that you can get a wife for my son from my own clan and from my fat her’s family. 41 You will be released from my oath if, when you go to my clan, they refuse to give her to you — then you will be released from my oath.’ 42 “When I came to the spring tod ay, I said, ‘Lord, God of my master Abraham, if you will, please g rant success to the journey on which I have come. 43 See, I am standing beside this spring. If a y oung woma n comes out to draw water and I say to her, “Please let me drink a litt le water from your jar,” 44 and if she says to me, “Drink, and I’ll draw water for your camels too,” let her be the one the Lord has chosen for my master’s son.’ 45 “Be fore I finished praying in my h eart, Rebekah came out, with her jar on her shoul der. She went down to the spring and drew water, and I said to her, ‘Please give me a drink.’ 46 “She quick ly lowered her jar from her shoulder and said, ‘Drink, and I’ll water your camels too.’ So I d rank, and she watered the camels also. 47 “I asked her, ‘Whose daughter are you?’ “She said, ‘The daughter of Bethuel son of Nahor, whom Milk ah bore to him.’ “Then I put the ring in her nose and the a 55 Or she DAY 11f ulness to my master, tell me; and if not, tell me, so I may know which way to turn.” 50 La banra h am’s servant heard what they said, he bowed down to the g round be fore the Lord. 53 Then the servant brought out gold and silver jewelr y woma neka h and asked her, “Will you go with this man?” “I will go,” she said. 59 So they sent t heir sister Rebeka h on her way, a long with her nurse and Abraham’s ser vant and his men. 60 And they blessed Rebek ah and said to her, “Our sister, may you increase to thousands upon thousands; may your offspring possess the cities of their enemies.” 61 Then Re beka h and her attend ants got r eady and mounted the camels and went back with the man. So the servant took Rebeka h and left. 62 Now I saac had come from Beer Lahai DAY 11 38 Roi, for he was living in the Negev. 63 He went out to the f ield one evening to meditate, a and as he looked up, he saw camels approaching. 64 Rebeka h also looked up and saw Isaac. She got down from her camel 65 and asked the ser vant, “Who is that man in the f ield coming to meet us?” “He is my master,” the servant ans wered. So she took her veil and covered herself. 66 Then the serv ant told I saac all he had done. 67 Isaac b rought her into the tent of his mother Sara h, and he marr ied Rebeka h. So she bec ame his wife, and he loved her; and Isaac was comforte d after his mother’s death. MATTHEW 9:14 — 9:38 Jesus Questioned About Fasting 14 Then John’s disciples came and a sked him, “How is it that we and the Pharisees fast often, but your disciples do not fast?” 15 Jesus ans wered, “How can the g uests of the brideg room m ourn while he is with them? The time will come when the bridegroom will be taken from them; then they will fast. 16 “No one sews a p atch of unshrunk c loth on an old garment, for the p atch will pull away from the garm ent, making the tear worse. 17 Neit her do people pour new wine into old wineskins. If they do, the skins will burst; the wine will run out and the wine skins will be ruined. No, they pour new wine into new wineskins, and both are pre served.” Jesus Raises a Dead Girl and Heals a Sick Woman 18 While he was saying this, a synagogue leader came and k nelt before him and said, “My daughter has just died. But come and put your hand on her, and she will live.” 19 Jesus got up and went with him, and so did his dis ciples. 20 Just then a woma n who had been subject to bleeding for t welve y ears came up behind him and touched the edge of his cloak. 21 She said to herself, “If I only touch his cloak, I will be healed.” 22 Jesus t urned and saw her. “Take heart, daughter,” he said, “your faith has healed you.” And the woman was healed at that mo ment. 23 When Jesus entered the synagogue lead er merc y on us, Son of Dav id!” 28 When he had gone in doors, the b lind men came to him, and he a sked them, “Do you believe that I am able to do this?” “Yes, Lord,” they replied. 29 Then he t ouched t heir eyes and said, “Ac cording to your faith let it be done to you”; 30 and their sight was restored. Jesus w arned them sternly, “See that no one k nows about this.” 31 But they went out and spread the news about him all over that region. 32 While they were going out, a man who was demon-possessed and c ould not talk was brought to Jesus. 33 And when the demon was driven out, the man who had been mute spoke. The c rowd was a mazed and said, “Nothing like this has ever been seen in Israel.” 34 But the Pharisees said, “It is by the prince of demons that he drives out demons.” The Workers Are Few 35 Jesus went t hrough all the towns and v illages, teaching in t heir synagogues, pro claiming the good news of the kingdom and heal ing every disease and sick ness. 36 When he saw the c rowds, he had compassion on them, because they were harassed and help less, like sheep without a shepherd. 37 Then he said to his disciples, “The harvest is plentif ul but the workers are few. 38 Ask the Lord of the harvest, therefore, to send out workers into his har vest field.” a 63 The meaning of the Hebrew for this word is uncertain. 39 PSALM 8:1 — 8:9 d with glory and honor. 6 You made them rulers over the works of your hands; you put everything under their f feet: 7 all flocks and herds, and the animals of the wild, 8 the birds in the sky, and the fish in the sea, all that swim the paths of the seas. 9 Lord, our Lord, how majestic is your name in all the earth! REWIND Genesis 24; Matthew 9:14 – 38; Psalm 8 THE DETAILS BELONG TO GOD. The Lord might seem too lofty to notice your life. But Genesis 24 shows him bringing together a specific man and woman to advance his DAY 12 plans. In Matthew 9 Jesus says he acts in new ways that exceed our expectations, like raising the dead, healing the sick, and giving sight to the blind. And Psalm 8 says God made you and every other human being extraordinary. You’re crowned with his glory, so you can count on him to lead your life. D day12 GENESIS 25:1 — 26:35 The Death of Abraham 25 Abra h am had taken another wife, whose name was Ket urah. 2 She bore him Zimran, Jok shan, Medan, Mid ian, Ish bak and Shua h. 3 Jokshan was the father of Sheba and Ded an; the descend ants of De dan were the Ashu rites, the Letushites and the Leu mm ites. 4 The sons of Midia n were Ephah, Epher, Hanok, Abida and Eldaah. All these were descendants of Ket urah. 5 Abra h am left everything he owned to Isaac. 6 But while he was still living, he gave g ifts to the sons of his conc ubines and sent them away from his son I saac to the land of the east. 7 Abraham l ived a hund red and sevent y f ield of Ephron son of Zohar the Hittite, 10 the f ield Abraham had bought from the Hittites. g T here Abraham was buried with his wife a In Hebrew texts 8:1-9 is numbered 8:2-10. b Title: Probably a musical term c 4 Or what is a human being that you are mindful of him, / a son of man that you care for him? d 5 Or him e 5 Or than God f 6 Or made him ruler . . . ; / . . . his g 10 Or the descendants of Heth DAY 12 40 Sara h. 11 After Abraham’s death, God blessed his son Isaac, who then lived near Beer La hai Roi. Ishmael’s Sons 12 This is the account of the family line of Abraham’s son Ishmael, whom Sara h’s slave, Hagar the Egyptian, bore to Abraham. 13 These are the n ames of the sons of Ish mael, listed in the order of their birth: Neba ioth the firstborn of Ishmael, Kedar, Adbeel, Mibsam, 14 Mishma, Dumah, Massa, 15 Ha dad, Tema, Jetur, Naphish and Kedemah. 16 These were the sons of Ishmael, and t hese are the names of the t welve triba l rulers ac cording to their sett lements and camps. 17 Ish mael l ived a hund red and thir t y-seven years. He breathed his last and died, and he was gathered to his people. 18 His descendants set tled in the area from Havilah to Shur, near the eastern border of Egypt, as you go toward Ashur. And they lived in hostilit y toward a all the tribes related to them. Jacob and Esau 19 This is the account of the family line of Abraham’s son Isaac. Abraham became the father of Isaac, 20 and I saac was fort y years old when he married Re bekah daughter of Bethuel the Aramean from Paddan Aram b and sister of Laban the Ara mean. 21 Isaac prayed to the Lord on behalf of his wife, because she was childless. The Lord answered his prayer, and his wife Rebeka h, t here were twin boys in her womb. 25 The f irst to come out was red, and his whole body was like a hairy garment; so they named him Esau. c 26 After this, his brother came out, with his hand grasping Esau’s heel; so he was named Jacob. d Isaac was sixt y years old when Rebekah gave birth to them. 27 The boys grew up, and Esau be came a skillful hunter, a man of the open country, while Jacob was content to stay at home a mong the tents. 28 Isaac, who had a taste for wild game, loved Esau, but Rebekah loved Jacob. 29 Once when Jacob was cooking some stew, Esau came in from the open country, fam ished. 30 He said to Jacob, “Quick, let me have some of that red stew! I’m famished!” (That is why he was also called Edom. e ) 31 Jacob replied, “First sell me your birth right.” 32 “Look, I am about to die,” Esau said. “What good is the birthright to me?” 33 But Jacob said, “Swear to me f irst.” So he s wore an oath to him, selling his birthr ight to Jacob. 34 Then Ja cob gave Esau some bread and some lentil stew. He ate and drank, and then got up and left. So Esau despised his birthright. Isaac and Abimelek 26 Now there was a famine in the land — besides the prev ious famine in Abra ham b less you. For to you and your descendants I will give all these lands and will confirm the oath I swore to your fat her Abra ham. 4 I will make your descen dants as numerous as the stars in the sky and will give them all these lands, and through your offspring f all nations on e arth will be blessed, g 5 because Abraham obeyed me and did everything I required of him, keeping my a 18 Or lived to the east of b 20 That is, Northwest Mesopotamia c 25 Esau may mean hairy. d 26 Jacob means he grasps the heel, a Hebrew idiom for he deceives. e 30 Edom means red. f 4 Or seed g 4 Or and all nations on earth will use the name of your offspring in blessings (see 48:20) DAY 12 41 commands, my decrees and my instructions.” 6 So Isaac stayed in Gerar. 7 When the men of that place asked him about his wife, he said, “She is my sister,” be cause he was a fraid to say, “She is my wife.” He thought, “The men of this place m ight kill me on account of Rebeka h, because she is beautif ul.” 8 When I saac had been there a long time, Abimelek king of the Philistines looked down from a window and saw Isaac caressing his wife Reb ek a h. 9 So Abimelek summoned Isaac and said, “She is really your wife! Why did you say, ‘She is my sister’?” Isaac ans wered him, “Because I t hought I might lose my life on account of her.” 10 Then Abimelek said, “What is this you have done to us? One of the men might well have slept with your wife, and you would have brought g uilt upon us.” 11 So Abimelek gave orders to all the peo ple: “Anyone who harms this man or his wife shall surely be put to death.” 12 Isaac planted c rops in that land and the same year reaped a hund redfold, because the Lord blessed him. 13 The man became rich, and his wealth continued to grow until he be came very w ealthy. 14 He had so many f locks and herds and servants that the Philistines en vied him. 15 So all the wells that his father’s serv ants had dug in the time of his father Abra ham, the Phil ist ines stopped up, fill ing them with earth. 16 Then Abim e lek said to Isaac, “Move away from us; you have become too powerf ul for us.” 17 So Isaac moved away from t here and en camped in the Valley of Gerar, where he set tled. 18 Isaac reopened the wells that had been dug in the time of his father Abraham, which the Philistines had stopped up after Abraham died, and he gave them the same n ames his father had given them. 19 Isaac’s servants dug in the valley and dis covered a well of fresh water t here. m oved on from t here and dug another well, and no one quarreled over it. He named it Rehoboth, c saying, “Now the Lord has given us room and we will flourish in the land.” 23 From t here he went up to Beersheba. 24 That n ight the Lord appeared to him and said, “I am the God of your father Abraham. Do not be a fraid, for I am with you; I will bless you and will increase the number of your descendants for the sake of my servant Abra ham.” 25 Isaac built an altar t here and called on the name of the Lord. There he pitched his tent, and there his servants dug a well. 26 Meanwhile, Abimelek had come to him from Gerar, with Ahuzzath his persona l ad viser and Phicol the commander of his forces. 27 Isaac a sked them, “Why have you come to me, since you were hostile to me and sent me away?” 28 They ans wered, “We saw clearly that the Lord was with you; so we said, ‘There ought to be a sworn agreement between us’ — be tween us and you. Let us make a treat y with you 29 that you will do us no harm, just as we did not harm you but always treated you well and sent you away peacefully. And now you are blessed by the Lord.” 30 Isaac then made a feast for them, and they ate and d rank. 31 Early the next morning the men s wore an oath to each other. Then Isaac sent them on their way, and they went away peacef ully. 32 That day Isaac’s serv ants came and told him about the well they had dug. They said, “We’ve found water!” 33 He called it Shibah, d and to this day the name of the town has been Beersheba. e Jacob Takes Esau’s Blessing 34 When Esau was fort y years old, he mar ried Judith daughter of Beeri the Hittite, and also Basemath daughter of Elon the Hitt ite. 35 They were a source of g rief to Isaac and Re bekah. a 20 Esek means dispute. b 21 Sitnah means opposition. c 22 Rehoboth means room. d 33 Shibah can mean oath or seven. e 33 Beersheba can mean well of the oath and well of seven. DAY 12 42 MATTHEW 10:1 — 10:31 Jesus Sends Out the Twelve 10 Jesus called his twelve disciples to him and gave them authorit y to drive out impure spirits and to heal every disease and sick ness. 2 These are the names of the t welve apos tles: f irst, Simon (who is called Peter) and his brother And rew; James son of Zebedee, and his brother John; 3 Phil ip and Bar t holomew; Thomas and Matthew the tax collector; James son of Alphaeus, and Thaddaeus; 4 Simon the Zealot and Judas Iscariot, who betrayed him. 5 These t welve Jesus sent out with the fol lowing instructions: “Do not go a mong the Gentiles or enter any town of the Samaritans. 6 Go rather to the lost sheep of Israel. 7 As you go, proc laim this message: ‘The kingdom of heaven has come near.’ 8 Heal the sick, raise the dead, c leanse those who have leprosy, a d rive out demons. Freely you have received; freely give. 9 “Do not get any gold or sil ver or copper to take with you in your belts — 10 no bag for the journey or extra shirt or sandals or a staff, for the worker is worth his keep. 11 Whatev er s heep a mong wolves. Therefore be as shrewd as snakes and as innocent as doves. 17 Be on your g uard; you will be handed over to the local councils and be f logged in the synagogues. 18 On my ac count you will be brought before governors and k ings as witnesses to them and to the Gentiles. 19 But when they arrest you, do not worr y about what to say or how to say it. At that time you will be given what to say, 20 for it will not be you speaking, but the Spirit of your Father speaking through you. 21 “Brother will bet ray brother to death, and a father his c hild; child ren will rebel a gainst rael before the Son of Man comes. 24 “The student is not above t he teacher, nor a servant a bove his master. 25 It is enough for students to be like their teachers, and servants like their masters. If the head of the house has been called Beelz ebul, how much more the members of his household! 26 “So do not be a fraid of them, for there is nothing concealed that will not be disc losed, or hidden that will not be made k nown. 27 What I tell you in the dark, speak in the daylight; what is whispered in your ear, pro claim from the roofs. 28 Do not be a fraid of those who kill the body but cannot kill the soul. Rather, be a fraid of the One who can destroy both soul and body in hell. 29 Are not two sparrows sold for a penny? Yet not one of them will fall to the ground outside your Fa ther’s care. b 30 And even the very hairs of your head are all numbered. 31 So d on’t be a fraid; you are worth more than many sparrows.” PROVERBS 1:20 — 1:33 Wisdom’s Rebuke 20 Out in the open wisdom calls aloud, she raises her voice in the public square; 21 on top of the wall c she cries out, at the city gate she makes her speech: 22 “How long will you who are simple love your simple ways? How long will mockers delight in mockery and fools hate knowledge? 23 Repent at my rebuke! Then I will pour out my thoughts to you, a 8 The Greek word traditionally translated leprosy was used for various diseases affecting the skin. b 29 Or will ; or knowledge c 21 Septuagint; Hebrew / at noisy street corners 43.” REWIND Genesis 25 – 26; Matthew 10:1 – 31; Proverbs 1:20 – 33 DON’T MISS GOD’S BEST. Genesis 25 – 26 tells the story of one of history’s most foolish trades, where Esau swaps his privileges as firstborn son for a pot of red stew. In Matthew 10 Jesus warns against letting yourself be scared by people rather than respecting the God who leads you home to heaven. And Proverbs 1 shows calamity overtaking p eople who don’t live by God’s wisdom. When you go against the Lord’s commands, you risk missing out on good things he plans for you. D DAY 13 day13 GENESIS 27:1 — 28:22 27 When Isaac was old and his eyes were so weak that he c ould no longer see, he called for Esau his older son and said to him, “My son.” “Here I am,” he answered. 2 Isaac said, “I am now an old man and don’t know the day of my d eath.eka h was listening as Isaac spoke to his son Esau. When Esau left for the open country to hunt game and bring it back, 6 Re beka h said to her son Jacob, “Look, I over heard your father say to your brother Esau, 7 ‘Bring me some game and prepare me some tasty food to eat, so that I may give you my blessing in the presence of the Lord before I die.’ 8 Now, my son, listen caref ully and do what I tell you: 9 Go out to the f lock and bring me two choice young g oats, so I can prepare some tasty food for your fat her, just the way he l ikes it. 10 Then take it to your father to eat, so that he may give you his blessing before he dies.” 11 Jacob said to Reb eka h his mother, “But my brother Esau is a hairy man while I have smooth skin. 12 What if my father touches me? Iw ould appear to be tricking him and would bring down a c urse on myself rather than a blessing.” 13 His mother said to him, “My son, let the curse fall on me. Just do what I say; go and get them for me.” 14 So he went and got them and brought them DAY 13 44 to his mother, and she prepared some tasty food, just the way his father liked it. 15 Then Rebekah took the best clothes of Esau her older son, w hich fat her and said, “My fa ther.” “Yes, my son,” he answered. “Who is it?” 19 Jacob said to his fat her, “I am Esau your firstborn. I have done as you told me. P lease c lose to his fat her Isaac, who touched him and said, “The voice is the voice of Jacob, but the hands are the hands of Esau.” 23 He did not rec ogn ize him, for his hands were hairy like t hose of his brother Esau; so he proceeded to b less k issed Ja cob had scarcely left his father’s presence, his brother Esau came in from hunting. 31 He too prepared some tasty food and brought it to his fat her. Then he said to him, “My fat her, please sit up and eat some of my game, so that you may give me your blessing.” 32 His fa t her Isaac a sked him, “Who are you?” “I am your son,” he answered, “your first born, Esau.” 33 Isaac trembled violently and said, “Who was it, then, that hunted game and brought it to me? I ate it just before you came and I blessed him — and indeed he will be blessed!” 34 When Esau heard his fat her’s words, he burst out with a loud and bitter cry and said to his father, “Bless me — me too, my father!” 35 But he said, “Your brother came deceit fully and took your blessing.” 36 Esau said, “Isn’t he right ly named Ja cob a ? This is the second time he has taken advantage of me: He took my birthright, and now he’s taken my blessing!” Then he a sked, “Haven’t you reserved any blessing for me?” 37 Isaac ans wered Esau, “I have made him lord over you and have made all his relat ives his servants, and I have sustained him with grain and new wine. So what can I possibly do for you, my son?” 38 Esau said to his fat her, “Do you have only one blessing, my father? Bless me too, my fa ther!” Then Esau wept aloud. 39 His fat her Isaac ans wered him, “Your dwelling will be away from the earth’s richness, away from the dew of heaven above. 40 You will live by the sword and you will serve your brother. But when you grow restless, you will throw his yoke from off your neck.” a 36 Jacob means he grasps the heel, a Hebrew idiom for he takes advantage of or he deceives. 45 41 Esau held a g rudge against Jacob because of the blessing his fat her had given him. He said to himself, “The days of mourning for my father are near; then I will kill my brother Jacob.” 42 When Re beka h was told what her old er son Esau had said, she sent for her youn ger son Jacob and said to him, “Your brother Esau is planning to a venge himself by killing you. 43 Now then, my son, do what I say: Flee at once to my brother Laban in Harran. 44 Stay with him for a while until your brother’s fury subsides. 45 When your brother is no longer an gry with you and forgets what you did to him, I’ll send word for you to come back from there. Why should I lose both of you in one day?” 46 Then Re beka h said to Isaac, “I’m dis gusted with living because of these Hittite women. If Jacob takes a wife from among the women of this land, from Hittite women like these, my life will not be worth living.” So Isaac c alled for Jacob and b lessed him. Then he commanded him: “Do not marr y a Canaanite woma n. 2 Go at once to Paddan Aram, a to the house of your moth er’s father Bethuel. Take a wife for yourself there, from a mong the daughters of Laban, your mother’s brother. 3 May God Almighty b bless you and make you fruitf ul and increase your numbers until you become a communit y of peoples. 4 May he give you and your descen dants ah, who was the mother of Jacob and Esau. 6 Now Esau learned that I saac had b lessed Jacob and had sent him to Paddan Aram to take a wife from there, and that when he blessed him he commanded him, “Do not mar r y a Canaanite woma n,” 7 and that Jacob had obeyed his father and mother and had gone to Paddan Aram. 8 Esau then rea l ized how displeasing the Canaanite women were 28 DAY 13 to his father Isaac; 9 so he went to Ishmael and married Mahalath, the sister of Nebaioth and daughter of Ishmael son of Abraham, in addi tion to the w ives he already had. Jacob’s Dream at Bethel 10 Jacob left Beersheba and set out for Har ran. 11 When he reached a certain place, he stopped for the night because the sun had set. Taking one of the stones there, he put it un der his head and lay down to sleep. 12 He had a d ream in which he saw a stairway resting on the earth, with its top reaching to heav en, off spring. d 15 I am with you and will w atch over you wherever you go, and I will bring you back to this land. I will not leave you unt il I have done what I have promised you.” 16 When Ja cob a woke from his sleep, he t hought, “Surely the Lord is in this p lace, and I was not aware of it.” 17 He was a fraid and said, “How awesome is this place! This is none other than the house of God; this is the gate of heaven.” 18 Ear ly re turn safely to my father’s household, then the Lord f will be my God 22 and g this stone that I have set up as a pillar will be God’s house, and of all that you give me I will give you a tenth.” a 2 That is, Northwest Mesopotamia; also in verses 5, 6 and 7 b 3 Hebrew El-Shaddai c 13 Or There beside him d 14 Or will use your name and the name of your offspring in blessings (see 48:20) e 19 Bethel means house of God. f 20,21 Or Since God . . . father’s household, the Lord g 21,22 Or household, and the Lord will be my God, 22then DAY 13 46 MATTHEW 10:32 — 11:15 32 “Whoe ver ac k nowledges me before oth ers, I will also ack nowledge before my Father in heaven. 33 But whoever disowns me before others, I will disown before my Father in heaven. 34 “Do not sup p ose that I have come to bring peace to the earth. I did not come to bring p eace, but a s word. 35 For I have come to turn “ ‘a man against his father, a daughter against her mother, a daughter-in-law against her mother-inlaw — 36 a man’s enemies will be the members of his own household.’ a 37 “Anyone who loves their father or moth er more than me is not worthy of me; anyone who loves their son or daughter more than me is not worthy of me. 38 Whoever does not take up t heir cross and follow me is not worthy of me. 39 Whoe ver finds their life will lose it, and whoever loses t heir life for my sake will find it. 40 “Any one who welcomes you welcomes me, and anyone who welcomes me welcomes the one who sent me. 41 Whoever welcomes a prophet as a prophet will receive a prophet’s rew ard, and whoe ver welcomes a righteous person as a righteous person will receive a righteous person’s rew ard. 42 And if anyone gives even a cup of cold water to one of t hese litt le ones who is my disciple, truly I tell you, that person will certainly not lose their re ward.” Jesus and John the Baptist 11 Af ter Jesus had finished instructing his t welve disciples, he went on from there to teach and preach in the towns of Gal ilee. b 2 When John, who was in pris on, heard about the deeds of the Messia h, sy c are c leansed, the deaf hear, the dead are raised, and the good news is proclaimed to the poor. 6 Blessed is anyone who does not stum ble on account of me.” 7 As John’s disc iples were leaving, Jesus be gan to s peak to the crowd about John: “What did you go out into the wilderness to see? A reed s wayed by the wind? 8 If not, what did you go out to see? A man d ressed in fine c lothes? No, those who wear fine c lothes are in k ings’ palaces. 9 Then what did you go out to see? A prophet? Yes, I tell you, and more than a prophet. 10 This is the one about whom it is written: “ ‘I will send my messenger ahead of you, who will prepare your way before you.’ d 11 Truly I tell you, among those born of wom en there has not risen anyone greater than John the Baptist; yet whoever is least in the kingdom of heaven is greater than he. 12 From the days of John the Baptist until now, the kingdom of heaven has been subjected to vio lence, e and violent people have been raiding it. 13 For all the Prophets and the Law prophesied until John. 14 And if you are willing to accept it, he is the Elijah who was to come. 15 Who ever has ears, let them hear.” PSALM 9:1 — 9:6 Psalm 9 f ,. a 36 Micah 7:6 b 1 Greek in their towns c 5 The Greek word traditionally translated leprosy was used for various diseases affecting the skin. d 10 Mal. 3:1 e 12 Or been forcefully advancing f Psalms 9 and 10 may originally have been a single acrostic poem in which alternating lines began with the successive letters of the Hebrew alphabet. In the Septuagint they constitute one psalm. g In Hebrew texts 9:1-20 is numbered 9:2-21. 47. REWIND Genesis 27 – 28; Matthew 10:32 – 11:15; Psalm 9:1 – 6 LET GOD RULE YOUR FAMILY. There’s not much to admire about Isaac and Rebekah’s family portrait in Genesis 27 – 28, from parents who play favorites to sons who battle to outdo each other. In Matthew 10 Jesus warns that families will disagree about him, possibly creating enemies within the same house. But in Psalm 9 you see God enthroned as a praiseworthy king. When you let God rule your house, you discover endless reasons to be glad and give him thanks. D day14 GENESIS 29:1 — 30:43 Jacob Arrives in Paddan Aram 29 Then Jacob continued on his journey and came to the land of the eastern peoples. 2 There he saw a well in the open country, with t hree f locks of sheep lying near it because the f locks were watered from that a 17 Or delicate DAY 14 well. The stone over the mouth of the well was large. 3 When all the f locks were gathered there, the shepherds would roll the stone away from the well’s mouth and water the sheep. Then they would ret urn the stone to its place over the mouth of the well. 4 Jacob asked the shepherds, “My brothers, where are you from?” “We’re from Harran,” they replied. 5 He said to them, “Do you know La ban, f locks to be gathered. Water the sheep and take them back to past ure.” 8 “We c an’t,” they replied, “until all the f locks are gathered and the stone has been rolled away from the mouth of the well. Then we will water the sheep.” 9 While he was still talking with them, Ra chel came with her father’s sheep, for she was a shepherd. 10 When Jacob saw Rachel daugh ter of his uncle Laban, and Laban’s sheep, he went over and r olled the s tone away from the mouth of the well and watered his uncle’s sheep. 11 Then Jacob k issed Rachel and began to weep a loud. 12 He had told Rachel that he was a relative of her father and a son of Rebek ah. So she ran and told her father. 13 As soon as Laban heard the news about Jacob, his sister’s son, he hurried to meet him. He embraced him and k issed him and brought him to his home, and there Jacob told him all these things. 14 Then Laban said to him, “You are my own f lesh and blood.” Jacob Marries Leah and Rachel After Jacob had stayed with him for a whole month, 15 Laban said to him, “Just be cause you are a relative of mine, should you work for me for nothing? Tell me what your wages should be.” 16 Now La b an had two daugh t ers; the name of the older was Leah, and the name of the younger was Rac hel. 17 Leah had weak a eyes, but Rachel had a lovely figu re and was DAY 14 48 beautif ul. 18 Jacob was in love with Rachel and said, “I’ll work for you seven y ears in ret urn for your younger daughter Rachel.” 19 Laban said, “It’s better that I give her to you than to some other man. Stay here with me.” 20 So Jacob served seven years to get Ra chel, but they seemed like only a few days to him because of his love for her. 21 Then Jacob said to Laban, “Give me my wife. My time is completed, and I want to make love to her.” 22 So Laban brought together all the peo ple, t here was Leah! So Jacob said to Laban, “What is this you have done to me? I s erved you for Rachel, d idn’t I? Why have you deceived me?” 26 Laban replied, “It is not our custom here to give the younger daughter in marriage be fore the older one. 27 Finish this daughter’s brida l week; then we will give you the youn ger one also, in ret urn at tendant. 30 Jacob made love to Rac hel less. 32 Leah became pregnant and gave birth to a son. She named him Reu ben, a for she said, “It is because the Lord has seen my misery. Surely my husband will love me now.” 33 She conceived a gain, and when she gave birth to a son she said, “Because the Lord eard that I am not loved, he gave me this one h too.” So she named him Simeon. b 34 Again she conceived, and when she gave birth to a son she said, “Now at last my hus band will become attached to me, because I have borne him three sons.” So he was named Levi. c 35 She conceived a gain, and when she gave birth to a son she said, “This time I will praise the Lord.” So she named him Judah. d Then she stopped having children. When Rac hel saw that she was not bearing Jacob any child ren, she be came jealous of her sister. So she said to Jacob, “Give me children, or I’ll die!” 2 Ja cob bec ame ang ry with her and said, “Am I in the place of God, who has kept you from having children?” 3 Then she said, “Here is Bil hah, my ser vant. Sleep with her so that she can bear child ren for me and I too can build a family through her.” 4 So she gave him her serv ant. e 7 Rac hel’s ser v ant Bil h ah conceived a gain and bore Jacob a second son. 8 Then Rac hel said, “I have had a g reat struggle with my sister, and I have won.” So she named him Naphtali. f 9 When Leah saw that she had stopped hav ing children, she took her servant Zilpah and gave her to Jacob as a wife. 10 Lea h’s ser vant Zilpah bore Jacob a son. 11 Then Leah said, “What good fortune!” g So she named him Gad. h 12 Lea h’s serv ant Zilpah bore Jacob a sec ond son. 13 Then Leah said, “How happy I am! The women will call me happy.” So she named him Asher. i 14 During wheat harvest, Reuben went out into the fields and found some mand rake plants, which he brought to his mother Leah. 30 a 32 Reuben sounds like the Hebrew for he has seen my misery; the name means see, a son. b 33 Simeon probably means one who hears. c 34 Levi sounds like and may be derived from the Hebrew for attached. d 35 Judah sounds like and may be derived from the Hebrew for praise. e 6 Dan here means he has vindicated. f 8 Naphtali means my struggle. g 11 Or “A troop is coming!” h 11 Gad can mean good fortune or a troop. i 13 Asher means happy. 49 ret urn for your son’s man drakes.” 16 So when Ja cob came in from the fields that even ing, Leah went out to meet him. “You must sleep with me,” she said. “I have h ired you with my son’s mand rakes.” So he slept with her that night. 17 God lis tened to Leah, and she became pregnant and bore Jacob a f ifth son. 18 Then Leah said, “God has rewarded me for giving my serv ant to my husband.” So she named him Issachar. a 19 Leah con ceived again and bore Jacob a sixth son. 20 Then Leah said, “God has pre sented me with a precious gift. This time my husband will t reat me with honor, because I have borne him six sons.” So she named him Zebu lun. b 21 Some time lat e r she gave birth to a daughter and named her Dinah. 22 Then God re membered Rac hel; he lis tened to her and enabled her to conceive. 23 She be came pregnant and gave b irth to a son and said, “God has taken away my dis grace.” 24 She named him Joseph, c and said, “May the Lord add to me another son.” Jacob’s Flocks Increase 25 After Rac hel gave birth to Joseph, Jacob said to Laban, “Send me on my way so I can go back to my own homeland. 26 Give me my w ives and child ren, for whom I have s erved you, and I will be on my way. You know how much work I’ve done for you.” 27 But Laban said to him, “If I have found favor in your eyes, p lease stay. I have learned by div inat ion that the Lord has blessed me bec ause of you.” 28 He added, “Name your wages, and I will pay them.” 29 Ja cob said to him, “You know how I have worked for you and how your livestock has fared under my care. 30 The litt le you had DAY 14 t hing for me, I will go on tending your f locks and watching over them: 32 Let me go through all your f locks to day and remove from them every speckled or spotted sheep, every dark-colored lamb and every spotted or speckled goat. They will be my wages. 33 And my honest y will test if y for me in the fut ure, whenever you check on the wages you have paid me. Any goat in my pos session that is not speckled or spotted, or any lamb that is not dark-colored, will be consid ered stolen.” 34 “Agreed,” said La ban. “Let it be as you have said.” 35 That same day he removed all the male goats that were streaked or spotted, and all the speckled or spotted female goats (all that had white on them) and all the darkcolored lambs, and he placed them in the care of his sons. 36 Then he put a three-day journey bet ween himself and Jacob, while Jacob con tinued to tend the rest of Laban’s flocks. 37 Jacob, howe ver, took f resh-cut branche s from poplar, almond and p lane t rees and made white s tripes on them by peeling the bark and exposing the white inner wood of the branch es. 38 Then he placed the peeled branches in all the watering troughs, so that they w ould be directly in front of the f locks when they came to drink. When the f locks were in heat and came to d rink, 39 they mated in front of the branches. And they bore young that were streaked or speckled or spotted. 40 Jacob set apart the young of the f lock by themselves, but made the rest face the streaked and darkcolored animals that belonged to Laban. Thus he made sepa rate f locks for himself and did not put them with Laban’s animals. 41 When ever the stronger females were in heat, Jacob would p lace the branches in the troughs in front of the animals so they would mate near the branches, 42 but if the animals were weak, he w ould not place them t here. So the weak a 18 Issachar sounds like the Hebrew for reward. b 20 Zebulun probably means honor. c 24 Joseph means may he add. DAY 14 50 animals went to Laban and the strong ones to Jacob. 43 In this way the man grew exceeding ly prosperous and came to own large f locks, and female and male servants, and camels and donkeys. MATTHEW 11:16 — 11:30 16 “To what can I compare this generat ion? They are like child ren sitting in the market placesa rd, a friend of tax collectors and sinners.’ But wisdom is proved right by her deeds.” Woe on Unrepentant Towns 20 Then Jesus began to denounce the towns in which most of his mirac les had been per formed, h eavens? No, you will go down to Hades. a For if the mirac les that were per formed, Fa ther, Lord of heaven and earth, because you have hidden these things from the wise and learned, and revealed them to litt le child ren. 26 Yes, Fat her, for this is what you were pleased to do. 27 “All t hings have been comm itted to me a 23 That is, the realm of the dead by my Fat her. No one k nows the Son except the Father, and no one k nows the Father except the Son and those to whom the Son chooses to reveal him. 28 “Come to me, all you who are wear y and burdened, and I will give you rest. 29 Take my yoke upon you and learn from me, for I am gent le and humble in heart, and you will find rest for your s ouls. 30 For my yoke is easy and my burden is light.” PSALM 9:7 — 9:12. REWIND Genesis 29 – 30; Matthew 11:16 – 30; Psalm 9:7 – 12 RUN TO GOD AS YOUR REFUGE. In Genesis 29 – 30 Jacob the deceiver gets played, tricked into working seven years for a woman he didn’t want to marry. In Matthew 11, towns that saw scores of miracles still refuse to repent — to stop sinning and turn back to God — and Jesus warns they’re headed for Hades. When it seems like no one else wants to follow God, remember Psalm 9. The Lord protects you in troubling times. He never abandons p eople who seek him. D DAY 15 51 day15 GENESIS 31:1 — 31:55 Jacob Flees From Laban 31 Jacob heard that Laban’s sons were say ing, “Jacob has taken every t hing our father o wned and has g ained all this wealth from what belonged to our father.” 2 And Jacob not iced that Laban’s att it ude to ward him was not what it had been. 3 Then the Lord said to Jacob, “Go back to the land of your fathers and to your relatives, and I will be with you.” 4 So Jacob sent word to Rac hel and Leah to come out to the f ields where his f locks were. 5 He said to them, “I see that your fat her’s at tit ude toward me is not what it was before, but the God of my father has been with me. 6 You know that I’ve w orked for your father with all my strength, 7 yet your father has cheated me by changing my wages ten times. How ever, God has not allowed him to harm me. 8 If he said, ‘The speckled ones will be your wages,’ then all the f locks gave birth to speck led young; and if he said, ‘The s treaked ones will be your wages,’ then all the f locks bore streaked young. 9 So God has taken away your father’s livestock and has given them to me. 10 “In breeding season I once had a d ream in which I looked up and saw that the male goats mating with the f lock were streaked, speck led or spotted. 11 The angel of God said to me in the dream, ‘Jacob.’ I answered, ‘Here I am.’ 12 And he said, ‘Look up and see that all the male goats mating with the f lock are streaked, speckled or spotted, for I have seen all that Laban has been doing to you. 13 I am the God of Bethel, where you anointed a pillar and a 18 That is, Northwest Mesopotamia here you made a vow to me. Now leave this w land at once and go back to your native land.’ ” 14 Then Rac hel and Leah replied, “Do we still have any share in the inheritance of our father’s estate? 15 Does he not regard us as for eigners? Not only has he sold us, but he has used up what was paid for us. 16 Surely all the wealth that God took away from our father belongs to us and our child ren. So do what ever God has told you.” 17 Then Jacob put his child ren and his w ives on camels, 18 and he d rove all his livestock ahead of him, a long with all the goods he had acc umu lated in Paddan Aram, a to go to his father Isaac in the land of Canaan. 19 When Laban had gone to s hear his sheep, Rachel stole her father’s household gods. 20 Moreover, Jacob deceived Laban the Ara mean by not telling him he was running away. 21 So he fled with all he had, c rossed the Eu phrates River, and headed for the hill country of Gilead. Laban Pursues Jacob 22 On the t hird day Laban was told that Ja cob caref ul not to say anything to Jacob, either good or bad.” 25 Ja cob had pitched his tent in the hill country of Gilead when Laban overtook him, and Laban and his relatives c amped there too. 26 Then Laban said to Jacob, “What have you done? You’ve deceived me, and you’ve carried off my daughters like captives in war. 27 Why did you run off secretly and deceive me? Why d idn’t you tell me, so I could send you away with joy and singing to the music of timbrels and harps? 28 You d idn’t even let me kiss my grandchild ren and my daughters goodbye. You have done a foolish thing. 29 I have the power to harm you; but last night the God of your father said to me, ‘Be caref ul not to say anything to Jacob, either good or bad.’ 30 Now you have gone off because you longed to re turn to your father’s household. But why did you steal my gods?” DAY 15 52 31 Jacob ans wered Laban, “I was a fraid, be cause I t hought you would take your daugh ters away from me by force. 32 But if you find anyone who has your gods, that person shall not live. In the presence of our relat ives,a h’s tent, he entered Rachel’s tent. 34 Now Rac hel had taken the household gods and put them inside her camel’s sadd le and was sitting on them. Laban searched through everything in the tent but found nothing. 35 Rachel said to her fat her, “Don’t be ang ry, my lord, that I cannot s tand up in your pres ence; I’m having my per iod.” So he s earched but could not find the household gods. 36 Jacob was ang ry and took Laban to task. “What is my c rime?” he asked Laban. “How have I w ronged you that you hunt me down? 37 Now that you have searched t hrough all my goods, what have you found that belongs to your household? Put it here in front of your relatives and mine, and let them judge be tween the two of us. 38 “I have been with you for twen t y years now. Your s heep and goats have not miscar ried, nor have I eaten rams from your f locks. 39 I did not b ring you animals torn by wild beasts; I bore the loss myself. And you de manded payment from me for whatever was stolen by day or night. 40 This was my situa tion: The heat consumed me in the daytime and the cold at night, and sleep fled from my eyes. 41 It was like this for the twent y years I was in your household. I worked for you four teen years for your two daughters and six years for your f locks, and you c hanged ans wered Jacob, “The women are my daughters, the child ren are my child ren, and the f locks are my f locks. All you see is mine. Yet what can I do today about these daughters of mine, or about the children they have borne? 44 Come now, let’s make a cov enant, you and I, and let it serve as a witness bet ween us.” 45 So Jacob took a s tone and set it up as a pillar. 46 He said to his relatives, “Gather some stones.” So they took s tones and piled them in a heap, and they ate there by the heap. 47 Laban called it Jegar Sahadut ha, and Jacob called it Galeed. a 48 Laban said, “This heap is a witness be tween you and me today.” That is why it was called Galeed. 49 It was also called Mizpah, b because he said, “May the Lord keep watch bet ween you and me when we are away from each other. 50 If you mistreat my daughters or if you take any w ives besides my daughters, even though no one is with us, remember that God is a witness bet ween you and me.” 51 La ban also said to Jacob, “Here is this heap, and here is this pillar I have set up be tween you and me. 52 This heap is a witness, and this pillar is a witness, that I will not go past this heap to your side to harm you and that you will not go past this heap and pil lar to my side to harm me. 53 May the God of Abraham and the God of Nahor, the God of their father, judge bet ween us.” So Jacob took an oath in the name of the Fear of his father I saac. 54 He offered a sacri fice t here in the hill count ry and inv ited his relatives to a meal. After they had eaten, they spent the night there. 55 Early the next morning Laban k issed his grandchild ren and his daughters and b lessed them. Then he left and ret urned home. c MATTHEW 12:1 — 12:21 Jesus Is Lord of the Sabbath 12 At that time Jesus went through the grainf ields on the Sabbath. His dis ciples were hung ry and began to pick some heads of g rain and eat them. 2 When the Pharisees saw this, they said to him, “Look! a 47 The Aramaic Jegar Sahadutha and the Hebrew Galeed both mean witness heap. b 49 Mizpah means watchtower. c 55 In Hebrew texts this verse (31:55) is numbered 32:1. DAY 15 53 Your disciples are doing what is unlawf ul on the Sabbath.” 3 He an s wered, “Haven’t you read what Dav id did when he and his companions were hung ry? 4 He entered the h ouse of God, and he and his companions ate the consec rated bread — which was not lawf ul k nown what these w ords mean, ‘I desire merc y, not sacrif ice,’ a you would not have condemned the innocent. 8 For the Son of Man is Lord of the Sabbath.” 9 Go ing on from that place, he went into their synagogue, 10 and a man with a shriveled hand was there. Looking for a reason to bring charges against Jesus, they asked him, “Is it lawf ul lawf ul withd rew from that lace. A large c rowd followed him, and he p healed all who were ill. 16 He warned them not to tell others about him. 17 This was to fulf ill PSALM 9:13 — 9:20. REWIND Genesis 31; Matthew 12:1 – 21; Psalm 9:13 – 20 EVERYONE GETS PICKED ON. The people in Genesis 31 think Jacob is trying to steal from his uncle, so he packs up his family and runs. In Matthew 12 the Lord’s hungry disciples face the wrath of religious rule keepers for picking grain on a day of Sabbath rest. And in Psalm 9 David complains about his enemies’ a 7 Hosea 6:6 b 21 Isaiah 42:1-4 c 16 The Hebrew has Higgaion and Selah (words of uncertain meaning) here; Selah occurs also at the end of verse 20. DAY 16 54 relentless attacks. When you feel bullied by your world, you’re not alone. Everyone suffers, but you have a God who never forgets you need him. D day16 GENESIS 32:1 — 33:20 Jacob Prepares to Meet Esau 32 a Jacob also went on his way, and the angels of God met him. 2 When Ja cob saw them, he said, “This is the camp of God!” So he named that place Mahanaim. b 3 Jacob sent messengers a head cat tle and donkeys, sheep and g oats, male and female servants. Now I am sending this mes sage to my lord, that I may find favor in your eyes.’ ” 6 When the messengers ret urned to Jacob, they said, “We went to your brother Esau, and now he is coming to meet you, and four hun dred men are with him.” 7 In g reat fear and dist ress Jacob div ided the people who were with him into two g roups, c and the f locks and herds and camels as well. 8 He t hought, “If Esau comes and attacks one group, d the g roup d that is left may escape.” 9 Then Jacob p rayed, “O God of my father Abraham, God of my father Isaac, Lord, you who said to me, ‘Go back to your country and your relatives, and I will make you prosper,’ 10 I am unworthy of all the kindness and faith fulness you have shown your servant. I had only my staff when I c rossed this Jordan, but now I have become two camps. 11 Save me, I pray, from the hand of my brother Esau, for I am a fraid he will come and attack me, and also the mothers with their child ren. 12 But you have said, ‘I will surely make you prosper and will make your descendants like the sand of the sea, which cannot be counted.’ ” 13 He spent the n ight t here, and from what he had with him he selected a gift for his brother Esau: 14 two hund red female goats and twenty male goats, two hund red ewes and twent y rams, 15 thirt y female camels with their y oung, forty cows and ten bulls, and twent y female donkeys and ten male donkeys. 16 He put them in the care of his servants, each herd by itself, and said to his servants, “Go a head of me, and keep some space between the herds.” 17 He instructed the one in the lead: “When my brother Esau meets you and asks, ‘Who do you belong to, and w here are you going, and who owns all t hese animals in front of you?’ 18 then you are to say, ‘They be long to your servant Jacob. They are a gift sent to my lord Esau, and he is coming behind us.’ ” 19 He also instructed the second, the t hird and all the others who followed the h erds: “You are to say the same thing to Esau when you meet him. 20 And be sure to say, ‘Your servant Jacob is coming beh ind us.’ ” For he thought, “I will pacif y him with these gifts I am sending on a head; later, when I see him, perhaps he will receive me.” 21 So Jacob’s gifts went on a head of him, but he himself spent the night in the camp. Jacob Wrestles With God 22 That n ight Jacob got up and took his two ives, his two female servants and his elev w en sons and c rossed the ford of the Jabbok. 23 After he had sent them across the stream, he sent over all his possessions. 24 So Jacob was left a lone, and a man wrestled with him till daybreak. 25 When the man saw that he could not overpower him, he touched the socket of a In Hebrew texts 32:1-32 is numbered 32:2-33. b 2 Mahanaim means two camps. c 7 Or camps d 8 Or camp 55 Jacob’s hip so that his hip was w renched as he wrest led with the man. 26 Then the man said, “Let me go, for it is daybreak.” But Jacob replied, “I will not let you go un less you bless me.” 27 The man a sked iel, b saying, “It is because I saw God face to face, and yet my life was spared.” 31 The sun rose above him as he passed Pe niel, c and he was limping because of his hip. 32 Therefore to this day the Isr aelites do not eat the tendon attached to the socket of the hip, because the socket of Jacob’s hip was touched near the tendon. Jacob Meets Esau 33 Jacob looked up and t here was Esau, coming with his four hund red men; so he div ided the child ren among Leah, Ra chel and the two female servants. 2 He put the female servants and their child ren in front, Leah and her child ren next, and Rachel and Joseph in the rear. 3 He himself went on ahead and bowed down to the g round seven times as he approached his brother. 4 But Esau ran to meet Jacob and embraced him; he t hrew his arms a round his neck and k issed him. And they wept. 5 Then Esau looked up and saw the women and child ren. “Who are these with you?” he asked. Jacob answered, “They are the child ren God has graciously given your servant.” 6 Then the female serv ants and t heir chil dren approached and bowed down. 7 Next, Leah and her children came and b owed down. Last of all came Joseph and Rachel, and they too bowed down. DAY 16 8 Esau a sked, “What’s the meaning of all these f locks and herds I met?” “To find favor in your eyes, my lord,” he said. 9 But Esau said, “I already have plent y, my brother. Keep what you have for yourself.” 10 “No, please!” said Jacob. “If I have found favor in your eyes, accept this gift from me. For to see your face is like seeing the face of God, now that you have received me fa vorably. Ja cob said to him, “My lord k nows that the child ren are tender and that I must care for the ewes and cows that are nursing their y oung. If they are driven hard just one day, all the animals will die. 14 So let my lord go on ahead of his servant, while I move a long slowly at the pace of the f locks and herds be fore me and the pace of the child ren, unt il I come to my lord in Seir.” 15 Esau said, “Then let me leave some of my men with you.” “But why do that?” Jacob a sked. “Just let me find favor in the eyes of my lord.” 16 So that day Esau started on his way back to Seir. 17 Jacob, however, went to Suk koth, where he built a place for himself and made shelters for his livestock. That is why the p lace is called Sukkoth. d 18 Af ter Jacob came from Paddan Aram, e he arrived safely at the city of Shec hem in Canaan and c amped within s ight of the city. 19 For a hun d red pieces of silver, f he bought from the sons of Hamor, the father of She chem, the plot of ground w here he pitched his tent. 20 There he set up an altar and called it El Elohe Israel. g MATTHEW 12:22 — 12:45 Jesus and Beelzebul 22 Then they b rought him a demon-possessed man who was blind and mute, and Jesus healed a 28 Israel probably means he struggles with God. b 30 Peniel means face of God. c 31 Hebrew Penuel, a variant of Peniel d 17 Sukkoth means shelters. e 18 That is, Northwest Mesopotamia f 19 Hebrew hundred kesitahs; a kesitah was a unit of money of unknown weight and value. g 20 El Elohe Israel can mean El is the God of Israel or mighty is the God of Israel. DAY 16 56 him, so that he could both talk and see. 23 All the people were astonished and said, “Could this be the Son of David?” 24 But when the Pharisees heard this, they said, “It is only by Beelzebul, the p rince of de mons, that this fellow drives out demons.” 25 Jesus knew t heir thoughts and said to them, “Every kingdom div ided against itself will be ruined, and every city or household di vided a gainst itself will not s tand. 26 If Satan drives out Satan, he is div ided a gainst himself. How then can his kingdom stand? 27 And if I d rive out demons by Beelz ebul, by whom do your people drive them out? So then, they will be your judges. 28 But if it is by the Spirit of God that I d rive out demons, then the king dom of God has come upon you. 29 “Or again, how can anyone enter a strong man’s house and carr y off his possessions un less he f irst ties up the s trong man? Then he can plunder his house. 30 “Whoe ver is not with me is a gainst me, and whoever does not gather with me scatters. 31 And so I tell you, every kind of sin and slan der can be forg iven, but blasphemy a gainst the Spirit will not be forgiven. 32 Anyone who speaks a word against the Son of Man will be forg iven, but anyone who speaks against the Holy Spirit will not be forgiven, either in this age or in the age to come. 33 “Make a tree good and its f ruit b rings evil t hings out of the evil stored up in him. 36 But I tell you that everyone will have to give account on the day of judg ment for every empt y ans wered, “A wicked and adulterous generation asks for a sign! But none will be given it except the sign of the prophet Jonah. 40 For as Jonah was three days and t hree n ights in the belly of a huge fish, so the Son of Man will be three days and three nights in the h eart of the earth. 41 The men of Nineveh will stand up at the judgment with this generat ion and condemn it; for they repented at the preach ing im pure spirit comes out of a person, it goes through arid places seeking rest and does not find it. 44 Then it says, ‘I will ret urn to the house I left.’ When it arrives, it f inds the house unoccupied, swept c lean and put in order. 45 Then it goes and takes with it seven other spirits more wicked than itself, and they go in and live there. And the final cond ition of that person is worse than the f irst. That is how it will be with this wicked generation.” PROVERBS 2:1 — 2:11. 57 10 For wisdom will enter your heart, and knowledge will be pleasant to your soul. 11 Discretion will protect you, and understanding will guard you. REWIND Genesis 32 – 33; Matthew 12:22 – 45; Proverbs 2:1 – 11 THERE HAS TO BE A BETTER WAY. Many years after Esau wanted to kill Jacob, they manage in Genesis 32 – 33 to patch up their friendship. Matthew 12 shows a group of religious hypocrites so blinded by sin they sneer at Jesus’ teaching and accuse him of being partners with the devil. But Proverbs 2 depicts a better way to do life. Get God’s wisdom now, then stay on his path. It’s your best chance to avoid the pain of sin. D day17 GENESIS 34:1 — 35:29 Dinah and the Shechemites 34 Now Dinah, the daughter Leah had borne to Jacob, went out to visit the women of the land. 2 When Shechem son of Hamor the Hiv ite, the ruler of that area, saw her, he took her and raped her. 3 His heart was d rawn to Dinah daughter of Jacob; he loved the young woman and spoke tenderly to her. 4 And Shechem said to his fat her Hamor, “Get me this girl as my wife.” 5 When Jacob heard that his daughter Di DAY 17 nah had been defiled, his sons were in the fields with his livestock; so he did nothing about it until they came home. 6 Then Shechem’s fat her Hamor went out to talk with Jacob. 7 Meanwhile, Jacob’s sons had come in from the f ields as soon as they heard what had happened. They were shocked and furious, because Shechem had done an outra geous thing in a Israel by sleeping with Jacob’s daughter — a thing that should not be done. 8 But Ha mor said to them, “My son She chem has his heart set on your daughter. Please give her to him as his wife. 9 Intermar ry with us; give us your daughters and take our daughters for yourselves. 10 You can sett le among us; the land is open to you. Live in it, trade b in it, and acquire propert y in it.” 11 Then Shec hem said to Dinah’s fat her Bec ause t heir sister Dinah had been de filed, Jacob’s sons replied deceitfully as they spoke to Shechem and his father Hamor. 14 They said to them, “We c an’t do such a thing; we can’t give our sister to a man who is not circumcised. That would be a disg race to us. 15 We will enter into an agreement with you on one cond ition only: that you become like us by circumcising all your males. 16 Then we will give you our daughters and take your daughters for ourselves. We’ll set t le a mong you and become one people with you. 17 But if you will not agree to be circumcised, we’ll take our sister and go.” 18 Their pro posa l friend ly toward us,” they said. “Let them live in our land and t rade in it; the land has plent y of room for them. We can marr y their daughters and they can marr y a 7 Or against b 10 Or move about freely; also in verse 21 DAY 17 58 ours. 22 But the men will agree to live with us as one people only on the cond it ion that our males be circumcised, as they themselves are. 23 Won’t t heir lives tock, t heir prope r t y ah’s brothers, took their swords and attacked the unsusp ecting city, kill ing every male. 26 They put Hamor and his son Shec hem to the s word and took Dinah from Shechem’s house and left. 27 The sons of Jacob came upon the dead bodies and loot ed the city where a their sister had been de filed. 28 They seized their f locks and herds and donkeys and everyt hing else of t heirs in the city and out in the f ields. 29 They carr ied off all t heir wealth and all t heir women and child ren, taking as plunder everyt hing in the houses. 30 Then Ja cob said to Simeon and Levi, “You have brought trouble on me by making me obnoxious to the Canaanites and Periz zites, the people living in this land. We are few in number, and if they join forces against me and attack me, I and my household will be destroyed.” 31 But they replied, “Should he have treated our sister like a prostit ute?” Jacob Returns to Bethel 35 Then God said to Jacob, “Go up to Bethe l and settle there, and build an altar t here to God, who appeared to you when you were f leeing from your brothe r Esau.” 2 So Jacob said to his household and to all who were with him, “Get rid of the foreign gods you have with you, and purif y yourselves and c hange your c lothes. 3 Then come, let us go up to Bethel, where I will build an altar to God, who ans wered a round them so that no one pursued them. 6 Ja cob and all the people with him came to Luz (that is, Bethel) in the land of Ca naan. 7 There he b uilt an altar, and he called the place El Bethel, b because it was there that God revealed himself to him when he was fleeing from his brother. 8 Now Deborah, Rebeka h’s nurse, died and was buried under the oak outside Bethel. So it was named Allon Bakuth. c 9 After Jacob ret urned from Paddan Aram, d God appeared to him again and blessed him. 10 God said to him, “Your name is Jacob, e but you will no longer be called Jacob; your name will be Israel. f ” So he named him Israel. 11 And God said to him, “I am God Al mighty g; be fruitf ul and increase in number. A nation and a communit y of nations will come from you, and k ings will be a mong your de scendants. 12 The land I gave to Abraham and Isaac I also give to you, and I will give this land to your descendants after you.” 13 Then God went up from him at the place where he had talked with him. 14 Ja cob set up a stone pillar at the p lace where God had talked with him, and he p oured out a d rink offering on it; he also poured oil on it. 15 Jacob called the place where God had talked with him Bethel. h The Deaths of Rachel and Isaac 16 Then they moved on from Bethel. W hile they were still some distance from Ephrath, Rachel began to give birth and had great dif ficult y. 17 And as she was having g reat diff i cult y in childbirth, the midw ife said to her, “Don’t despair, for you have another son.” 18 As she breathed her last — for she was dy ing — she named her son Ben-Oni. i But his father named him Benjamin. j 19 So Ra c hel died and was buried on the a 27 Or because b 7 El Bethel means God of Bethel. c 8 Allon Bakuth means oak of weeping. d 9 That is, Northwest Mesopotamia; also in verse 26 e 10 Jacob means he grasps the heel, a Hebrew idiom for he deceives. f 10 Israel probably means he struggles with God. g 11 Hebrew El-Shaddai h 15 Bethel means house of God. i 18 Ben-Oni means son of my trouble. j 18 Benjamin means son of my right hand. DAY 17 59 way to Ephrath (that is, Bethlehem). 20 Over her tomb Jacob set up a pillar, and to this day that pillar marks Rachel’s tomb. 21 Is rael moved on a gain and pitched his tent beyond Migdal Eder. 22 While Israel was living in that region, Reuben went in and slept with his father’s concubine Bilhah, and Israel heard of it. Jacob had t welve sons: 23 The sons of Leah: Reuben the firstborn of Jacob, Simeon, Levi, Jud ah, Issac har and Zebu lun. 24 The sons of Rachel: Joseph and Benjamin. 25 The sons of Rachel’s servant Bilhah: Dan and Naphtali. 26 The sons of Lea h’s servant Zilpah: Gad and Asher. These were the sons of Jacob, who were born to him in Paddan Aram. 27 Ja cob came home to his father Isaac in Mamre, near Kiriath Arba (that is, Hebron), where Abraham and Isaac had stayed. 28 Isaac lived a hund red and e ighty years. 29 Then he breathed his last and died and was gathered to his people, old and full of y ears. And his sons Esau and Jacob buried him. MATTHEW 12:46 — 13:17 Jesus’ Mother and Brothers 46 While Jesus was s till talk i ng to the c rowd, his mother and brothers stood outside, wanting to speak to him. 47 Someone told him, “Your mother and brothers are standing out side, Parable of the Sower 13 That same day Jesus went out of the house and sat by the lake. 2 Such large crowds gathered a round him that he got into a 15 Isaiah 6:9,10 (see Septuagint) a boat and sat in it, while all the people stood on the s hore. 3 Then he told them many t hings in parables, saying: “A farmer went out to sow his seed. 4 As he was scattering the seed, some fell a long the path, and the birds came and ate it up. 5 Some fell on rocky places, where it did not have much soil. It sprang up quick ly, because the soil was shallow. 6 But when the sun came up, the plants were scorched, and they withered because they had no root. 7 Oth er seed fell a mong thorns, w hich grew up and c hoked the p lants. 8 Still other seed fell on good soil, w here it produced a crop — a hundred, sixt y or thirt y times what was sown. 9 Whoever has ears, let them hear.” 10 The dis c iples came to him and a sked, “Why do you s peak to the people in parables?” 11 He re plied, “Be c ause the knowl e dge of the sec rets of the kingdom of heaven has been given to you, but not to them. 12 Who ever fulf illed the prophec y bec ause they see, and your ears bec ause they hear. 17 For truly I tell you, many prophets and righteous peo ple longed to see what you see but did not see it, and to hear what you hear but did not hear it.” DAY 18 60 PSALM 10:1 —.” REWIND Genesis 34 – 35; Matthew 12:46 – 13:17; Psalm 10:1 – 11 YOU DON’T HAVE TO ADD TO THE WORLD’S EVIL. The rape, murder, and plunder recounted in Genesis 34 should make you uncomfortable. So should the thought of anyone being too cold to understand and apply God’s words, like in Matthew 12 – 13. Psalm 10 presents more tragic pictures, like the wicked hunting the weak and murdering the innocent. You live in a world of widespread evil. But every time you choose to do good, you stand on God’s side. D day18 GENESIS 36:1 — 37:36 Esau’s Descendants 36 This is the account of the family line of Esau (that is, Edom). 2 Esau took his w ives from the women of Canaan: Adah daughter of Elon the Hit t ite, and Ohol ibamah daughter of Anah and granddaughter of Zibeon the Hiv ite — 3 also Basemath daughter of Ishmael and sister of Nebaioth. 4 Adah bore El iphaz to Esau, Base math bore Reuel, 5 and Oholibamah bore Jeush, Jalam and Korah. These were the sons of Esau, who were born to him in Canaan. 6 Esau took his w ives and sons and daughters and all the members of his household, as well as his livestock and all his other animals and all the goods he had acquired in Canaan, and moved to a land some distance from his broth er Jacob. 7 Their possessions were too g reat for them to remain together; the land where they were staying could not a Psalms 9 and 10 may originally have been a single acrostic poem in which alternating lines began with the successive letters of the Hebrew alphabet. In the Septuagint they constitute one psalm. b 5 See Septuagint; Hebrew / they are haughty, and your laws are far from DAY 18 61 support them both because of their live stock. 8 So Esau (that is, Edom) sett led in the hill country of Seir. 9 This is the ac count emath. 11 The sons of Eliphaz: Teman, Omar, Zepho, Gatam and Kenaz. 12 Esau’s son Eliphaz also had a con cubine named Timna, who bore him Ama lek. T hese were grands ons of Esau’s wife Adah. 13 The sons of Reuel: Nahath, Zerah, Shammah and Miz zah. T hese were grandsons of E sau’s wife Basemath. 14 The sons of E sau’s wife Oholibamah daughter of Anah and granddaughter of Zibeon, whom she bore to Esau: Jeush, Jalam and Korah. 15 These were the c hiefs among Esau’s de scendants: The sons of Eliphaz the firstb orn of Esau: Chiefs Teman, Omar, Zepho, Kenaz, 16 Korah, a Gatam and Ama lek. T hese were the c hiefs descended from Eli phaz in Edom; they were grandsons of Adah. 17 The sons of Esau’s son Reuel: Chiefs Nahath, Zerah, Shammah and Mizz ah. T hese were the c hiefs de scended from Reuel in Edom; they were grandsons of E sau’s wife Base math. 18 The sons of Esau’s wife Oholibamah: Chiefs Jeush, Jalam and Korah. T hese were the chiefs descended from Esau’s wife Oholibamah daughter of Anah. 19 These were the sons of Esau (that is, Edom), and these were their chiefs. 20 These were the sons of Seir the Hor ite, who were living in the region: Lotan, Shobal, Zibeon, Anah, 21 Di shon, Ezer and Dishan. These sons of Seir in Edom were Horite chiefs. 22 The sons of Lotan: Hori and Homam. b Timna was Lo tan’s sister. 23 The sons of Shobal: Alvan, Mana hath, Ebal, Shepho and Onam. 24 The sons of Zibeon: Aiah and Anah. This is the Anah who discovered the hot springs c in the desert while he was grazing the don keys of his father Zibeon. 25 The children of Anah: Dishon and Ohol ib Di shon, Ezer and Dishan. T hese were the Hor ite c hiefs, accord ing to t heir div isions, in the land of Seir. The Rulers of Edom 31 These were the k ingsu sham died, Ha d ad son of Bedad, who defeated Midia n in the country of Moab, succeeded him as king. His city was named Avith. 36 When Hadad died, Samlah from Masre kah succeeded him as king. a 16 Masoretic Text; Samaritan Pentateuch (also verse 11 and 1 Chron. 1:36) does not have Korah. b 22 Hebrew Hemam, a variant of Homam (see 1 Chron. 1:39) c 24 Vulgate; Syriac discovered water; the meaning of the Hebrew for this word is uncertain. d 26 Hebrew Dishan, a variant of Dishon DAY 18 62 37 When Samlah died, Shau l from Reho both on the river succeeded him as king. 38 When Shau l died, Baal-Hanan son of Akbor succeeded him as king. 39 When Baal-Hanan son of Akbor died, Hadad a succeeded him as king. His city was n amed Pau, and his w ife’s name was Mehetabel daughter of Ma tred, the daughter of Me-Zahab. 40 These were the c hiefs descended from Esau, by name, according to their c lans and regions: Timna, Alv ah, Jet heth, 41 Ohol iba mah, Elah, Pinon, 42 Kenaz, Teman, Mibz ar, 43 Magd iel and Iram. T hese were the chiefs of Edom, according to their sett lements in the land they oc cupied. This is the family line of Esau, the father of the Edomites. Joseph’s Dreams 37 Jacob lived in the land where his fa ther had stayed, the land of Canaan. 2 This is the account of Jacob’s family line. Joseph, a young man of seventeen, was tending the f locks with his brothers, the sons of Bilhah and the sons of Zilpah, his father’s w ives, and he b rought their father a bad report about them. 3 Now Israel loved Joseph more than any of his other sons, because he had been born to him in his old age; and he made an ornate b robe for him. 4 When his brothers saw that their father loved him more than any of them, they hated him and could not speak a kind word to him. 5 Joseph had a d ream, and when he told it to his brothers, they hated him all the more. 6 He said to them, “Listen to this d ream I had: 7 We were binding s heaves of grain out in the f ield when suddenly my s heaf rose and stood upr ight, while your sheaves gathered a round mine and bowed down to it.” 8 His brothers said to him, “Do you intend to reign over us? Will you act ua lly rule us?” And they hated him all the more because of his dream and what he had said. 9 Then he had another d ream, and he told it to his brothers. “Listen,” he said, “I had an other dream, and this time the sun and moon and eleven stars were bowing down to me.” 10 When he told his fa t her as well as his brothers, his father rebuked him and said, “What is this d ream you had? Will your mother and I and your brothers act ua lly come and bow down to the g round before you?” 11 His brothers were jealous of him, but his fa ther kept the matter in mind. Joseph Sold by His Brothers 12 Now his brothers had gone to graze t heir father’s f locks near Shechem, 13 and Israel said to Joseph, “As you know, your brothers are grazing the f locks near Shechem. Come, I am going to send you to them.” “Very well,” he replied. 14 So he said to him, “Go and see if all is well with your brothers and with the f locks, and bring word back to me.” Then he sent him off from the Valley of Hebron. When Joseph arrived at Shechem, 15 a man found him wandering a round in the f ields and asked him, “What are you looking for?” 16 He replied, “I’m looking for my brothers. Can you tell me w here they are grazing their flocks?” 17 “They have moved on from here,” the man answered. “I heard them say, ‘Let’s go to Dothan.’ ” So Joseph went after his brothers and f ound them near Dothan. 18 But they saw him in the distance, and before he reached them, they plotted to kill him. 19 “Here c omes that dreamer!” they said to each other. 20 “Come now, let’s kill him and t hrow him into one of t hese cisterns and say that a ferocious animal devoured him. Then we’ll see what comes of his dreams.” 21 When Reuben heard this, he t ried to res cue him from their hands. “Let’s not take his a 39 Many manuscripts of the Masoretic Text, Samaritan Pentateuch and Syriac (see also 1 Chron. 1:50); most manuscripts of the Masoretic Text Hadar b 3 The meaning of the Hebrew for this word is uncertain; also in verses 23 and 32. 63 life,” he said. 22 “Don’t shed any blood. Throw him into this cistern here in the wilderness, but don’t lay a hand on him.” Reuben said this to rescue him from them and take him back to his father. 23 So when Jo seph came to his brothers, they stripped him of his robe — the ornate robe he was wearing — 24 and they took him and threw him into the cistern. The cistern was empt y; there was no water in it. 25 As they sat down to eat t heir meal, they looked up and saw a caravan of Ishmaelites coming from Gilead. Their camels were load ed ites and not lay our h ands on him; after all, he is our brother, our own f lesh and blood.” His brothers agreed. 28 So when the Midia nite merc hants came by, his brothers pulled Joseph up out of the cistern and sold him for twenty shekels a of silver to the Ishmaelites, who took him to Egypt. 29 When Reu ben returned to the cistern and saw that Joseph was not there, he tore his c lothes. 30 He went back to his brothers and said, “The boy isn’t t here! W here can I turn now?” 31 Then they got Jo s eph’s robe, slaugh tered a goat and dipped the robe in the blood. 32 They took the ornate robe back to t heir fa ther and said, “We found this. Examine it to see whether it is your son’s robe.” 33 He recogn ized it and said, “It is my son’s robe! Some feroc ious animal has devoured him. Joseph has surely been torn to pieces.” 34 Then Jacob tore his c lothes, put on sack cloth and mourned for his son many days. 35 All his sons and daughters came to comfort him, but he ref used to be comforted. “No,” he said, “I will continue to mourn until I join my son in the g rave.” So his father wept for him. 36 Meanwhile, the Midia nites b sold Joseph in Egypt to Potiphar, one of Pharaoh’s off i cials, the captain of the guard. DAY 18 MATTHEW 13:18 — 13:35 18 “Lis ten then to what the parable of the sower means: 19 When anyone hears the mes sage a bout the kingdom and does not under stand it, the evil one comes and snatches away what was sown in their heart. This is the seed sown a long the path. 20 The seed falling on rocky ground refers to someone who hears the word and at once receives it with joy. 21 But since they have no root, they last only a short time. When trouble or pers ec ut ion comes because of the word, they quickly fall away. 22 The seed falling a mong the t horns refers to someone who hears the word, but the worries of this life and the deceitfulness of wealth choke the word, making it unfruitful. 23 But the seed falling on good soil refers to some one who hears the word and understands it. This is the one who produces a crop, yield ing a hundred, sixt y or thirt y times what was sown.” The Parable of the Weeds 24 Jesus told them an other parable: “The kingdom of heaven is like a man who s owed good seed in his f ield. 25 But while everyone was sleeping, his enemy came and sowed w eeds among the wheat, and went away. 26 When the w heat sprout e d and formed heads, then the weeds also appeared. 27 “The owner’s serv ants came to him and said, ‘Sir, d idn’t you sow good seed in your f ield? W here then did the weeds come from?’ 28 “ ‘An enemy did this,’ he replied. “The servants asked him, ‘Do you want us to go and pull them up?’ 29 “ ‘No,’ he an s wered, ‘because w hile you are pulling the weeds, you may uproot the wheat with them. 30 Let both grow togeth er until the harvest. At that time I will tell the harvesters: First collect the weeds and tie them in bund les to be burned; then gather the wheat and bring it into my barn.’ ” The Parables of the Mustard Seed and the Yeast 31 He told them another parable: “The king dom of heaven is like a mustard seed, which a a 28 That is, about 8 ounces or about 230 grams b 36 Samaritan Pentateuch, Septuagint, Vulgate and Syriac (see also verse 28); Masoretic Text Medanites DAY 19 64 man took and planted in his f ield. sixt y pounds a of f lour until it worked all through the dough.” 34 Jesus spoke all t hese t hings to the c rowd in parables; he did not say anyt hing to them without using a parable. 35 So was fulfilled what was spoken through the prophet: “I will open my mouth in parables, I will utter things hidden since the creation of the world.” b REWIND Genesis 36 – 37; Matthew 13:18 – 35; Psalm 10:12 – 18 GOD IS KING FOREVER. Like other clans around it, the line of Esau detailed in Genesis 36 has centuries of chiefs and kings. The young Joseph introduced in Genesis 37 will one day grow up to work for the ruler of Egypt. Jesus teaches about God’s kingdom in Matthew 13. And Psalm 10 calls God the eternal king who sides with the helpless and holds evildoers accountable. All of Scripture shows God as the King of kings. Let him rule your life now and forever. D PSALM 10:12 — 10:18 33 Or about 27 kilograms b 35 Psalm 78:2 day19 GENESIS 38:1 — 39:23 be came pregnant and gave birth to a son, who was named Er. 4 She conceived again and gave birth to a son and n amed born, was wicked in the Lord’s sight; so the Lord put him to death. 8 Then Ju d ah said to Onan, “Sleep with your brother’s wife and fulf ill your duty to her 65 as a brother-in-law to raise up offspring for your brother.” 9 But Onan knew that the child would not be his; so whenever he slept with his brother’s wife, he spilled his semen on the g round to keep from prov iding offspring for his brother. 10 What he did was wicked in the Lord’s sight; so the Lord put him to death also. 11 Ju dah then said to his daughter-in-law Tamar, “Live as a widow in your father’s household until my son Shelah g rows up.” For he thought, “He may die too, just like his brothers.” So Tamar went to live in her father’s household. 12 After a long time Judah’s wife, the daugh ter of Shua, died. When Judah had recovered from his g rief, he went up to Timnah, to the men who were shearing his sheep, and his friend Hirah the Adullamite went with him. 13 When Ta mar was told, “Your fatherin-law is on his way to Timnah to shear his sheep,” 14 she took off her widow’s c lothes, covered herself with a veil to disg uise herself, and then sat down at the entrance to Enaim, which is on the road to Timnah. For she saw that, though Shelah had now g rown up, she had not been given to him as his wife. 15 When Ju d ah saw her, he thought she was a prostit ute, for she had covered her face. 16 Not rea lizing that she was his daughter-inlaw, he went over to her by the roadside and said, “Come now, let me sleep with you.” “And what will you give me to sleep with you?” she asked. 17 “I’ll send you a young goat from my f lock,”, DAY 19 “Where is the shrine prost it ute who was be side the road at Enaim?” “There h asn’t been any shrine prostitute here,” they said. 22 So he went back to Ju dah and said, “I d idn’t find her. Besides, the men who lived there said, ‘There hasn’t been any shrine pros tit ute here.’ ” 23 Then Judah said, “Let her keep what she has, or we will become a laughingstock. Af ter all, I did send her this young goat, but you didn’t find her.” 24 About t hree months later Judah was told, “Your daughter-in-law Tamar is g uilty of prost it ut ion, and as a result she is now preg nant.” Judah said, “Bring her out and have her burned to death!” 25 As she was being brought out, she sent a message to her father-in-law. “I am pregnant by the man who owns these,” she said. And she added, “See if you recogn ize whose seal and cord and staff these are.” 26 Judah recogn ized them and said, “She is more righteous than I, s ince I wouldn’t give her to my son Shelah.” And he did not s leep with her again. 27 When the time came for her to give b irth, t here were twin boys in her womb. 28 As she was giving birth, one of them put out his hand; so the midw ife took a scarlet thread and tied it on his w rist and said, “This one came out f irst.” 29 But when he drew back his hand, his brother came out, and she said, “So this is how you have broken out!” And he was named Perez. a 30 Then his brother, who had the scar let thread on his w rist, came out. And he was named Zerah. b Joseph and Potiphar’s Wife 39 Now Joseph had been taken down to Egypt. Potiphar, an Egypt ian who was one of Pharaoh’s off icials, the captain of the g uard, bought him from the Ishmaelites who had taken him there. 2 The Lord was with Jo s eph so that he prosp ered, and he lived in the house of his Egypt ian master. 3 When his master saw that the Lord was with him and that the Lord a 29 Perez means breaking out. b 30 Zerah can mean scarlet or brightness. DAY 19 66 gave him success in everyt hing he did, 4 Jo seph found favor in his eyes and became his attend ant. Potiphar put him in c harge of his household, and he ent rusted to his care every t hing he owned. 5 From the time he put him in c harge of his household and of all that he owned, the Lord blessed the house hold of the Egypt ian because of Joseph. The blessing of the Lord was on everyt hing Pot iphar had, both in the house and in the f ield. 6 So Pot iphar left everything he had in Jo seph’s care; with Joseph in c harge, he did not conc ern himself with anything exc ept the food he ate. Now Joseph was well-built and handsome, 7 and after a w hile his master’s wife took notice of Joseph and said, “Come to bed with me!” 8 But he ref used. “With me in c harge,” he told her, “my master does not concern him self with anything in the house; everything he owns he has entrusted to my care. 9 No one is greater in this house than I am. My mas ter has withheld nothing from me except you, because you are his wife. How then could I do such a wicked thing and sin a gainst God?” 10 And t hough she spoke to Jos eph day after day, he ref used to go to bed with her or even be with her. 11 One day he went into the house to at tend to his duties, and none of the household ser vants was inside. 12 She caught him by his c loak and said, “Come to bed with me!” But he left his c loak in her hand and ran out of the house. 13 When she saw that he had left his c loak in her hand and had run out of the house, 14 she c alled her household serv ants. “Look,” she said to them, “this Hebrew has been b rought to us to make sport of us! He came in here to s leep with me, but I screamed. 15 When he heard me scream for help, he left his cloak be side me and ran out of the house.” 16 She kept his c loak mas ter h eard the story his wife told him, saying, “This is how your slave treated me,” he burned with anger. 20 Joseph’s master took him and put him in prison, the place where the k ing’s prisoners were con fined. But while Joseph was there in the prison, 21 the Lord was with him; he s howed him kindness and granted him favor in the eyes of the prison warden. 22 So the warden put Jo seph in charge of all those held in the prison, and he was made responsible for all that was done t here. 23 The warden paid no attention to anyt hing under Joseph’s care, because the Lord was with Joseph and gave him success in whatever he did. MATTHEW 13:36 — 13:58 The Parable of the Weeds Explained 36 Then he left the crowd and went into the ouse. His disc iples came to him and said, h “Explain to us the parable of the weeds in the field.” 37 He ans wered, “The one who sowed the good seed is the Son of Man. 38 The f ield ev eryt hing that causes sin and all who do evil. 42 They will t hrow them into the blazing fur nace, where there will be weeping and gnash ing of teeth. 43 Then the righteous will s hine like the sun in the kingdom of their Father. Whoever has ears, let them hear. The Parables of the Hidden Treasure and the Pearl 44 “The kingdom of heaven is like treasure hidden in a f ield. When a man found it, he hid it again, and then in his joy went and sold all he had and bought that field. 45 “Again, the kingdom of heaven is like a merchant looking for fine pearls. 46 When he found one of g reat value, he went away and sold everything he had and bought it. DAY 19 67 The Parable of the Net 47 “Once again, the kingdom of heaven is like a net that was let down into the lake and caught all k inds of fish. 48 When it was full, the fishermen pulled it up on the shore. Then they sat down and collected the good fish in baskets, but threw the bad away. 49 This is how it will be at the end of the age. The angels will come and sepa rate the wicked from the righteous 50 and throw them into the blaz ing furnace, where there will be weeping and gnashing of teeth. 51 “Have you understood all t hese t hings?” Jesus asked. “Yes,” they replied. 52 He said to them, “Therefore every teach er of the law who has become a disc iple in the kingdom of heaven is like the owner of a house who brings out of his storeroom new treasures as well as old.” A Prophet Without Honor 53 When Jesus had finished these para bles, he moved on from there. 54 Coming to his hometown, he began teaching the people in their syna gogue, and they were a mazed. “Where did this man get this wisdom and these miracu lous powers?” they asked. 55 “Isn’t this the carp enter’s son? Isn’t his mother’s name Mary, and a ren’t his brothers James, Joseph, Simon and Judas? 56 Aren’t all his sis ters with us? W here then did this man get all these things?” 57 And they took offense at him. But Jesus said to them, “A prophet is not without honor except in his own town and in his own home.” 58 And he did not do many mirac les t here because of their lack of faith. PSALM 11:1 — 11:7. REWIND Genesis 38 – 39; Matthew 13:36 – 58; Psalm 11 THE WORLD CAN BE APPALLING. You live in the world of Genesis 38 – 39, a place home to people like Judah, Tamar, and Potiphar’s wife. In Matthew 13 Jesus informs you that some of the world’s inhabitants belong to the devil. And Psalm 11 asserts that wicked people aim to destroy the world’s foundations and wonders what good people can do about it. But God will put an end to evil. He will let the upright see him up close. D DAY 20 68 day20 GENESIS 40:1 — 41:40 The Cupbearer and the Baker 40 Some time later, the cupbearer and the baker of the king of E gypt of fended their master, the king of Egypt. 2 Phar aoh was ang ry with his two off icials, the chief cupbearer and the chief baker, 3 and put them in custody in the house of the captain of the g uard, in the same prison where Joseph was conf ined. 4 The captain of the g uard assigned them to Joseph, and he attended them. After they had been in custody for some time, 5 each of the two men — t he cupbearer and the baker of the king of Egypt, who were being held in prison — had a dream the same n ight, and each d ream had a meaning of its own. 6 When Jo s eph came to them the next morning, he saw that they were dejected. 7 So he asked Pharaoh’s off icials who were in cus tody with him in his master’s house, “Why do you look so sad today?” 8 “We both had d reams,” they answered, “but there is no one to interpret them.” Then Joseph said to them, “Do not in terpretations belong to God? Tell me your dreams.” 9 So the c hief cupb earer told Joseph his d ream. He said to him, “In my d ream I saw a vine in front of me, 10 and on the vine were three branches. As soon as it budded, it blos somed, and its clusters ripened into g rapes. 11 Pharaoh’s cup was in my hand, and I took the grapes, s queezed them into Pharaoh’s cup and put the cup in his hand.” 12 “This is what it means,” Joseph said to him. “The three branches are three days. 13 Within t hreear a 16 Or three wicker baskets aoh and get me out of this prison. 15 I was forc ibly carried off from the land of the Hebrews, and even here I have done nothing to deserve being put in a dungeon.” 16 When the c hief baker saw that Joseph had given a favorable inter pretat ion, he said to Joseph, “I too had a d ream: On my head were t hree baskets of bread. a 17 In the top bas ket were all k inds of baked g oods for Pharaoh, but the birds were eating them out of the bas ket on my head.” 18 “This is what it means,” Joseph said. “The three baskets are three days. 19 Within t hree days Pharaoh will lift off your head and im pale your body on a pole. And the b irds will eat away your flesh.” 20 Now the t hird day was Pharaoh’s birth day, and he gave a feast for all his off icials. He lifted up the heads of the chief cupbearer and the chief baker in the presence of his off icials: 21 He restored the c hief cupbearer to his po sition, so that he once again put the cup into Pharaoh’s hand — 22 but he impaled the chief baker, just as Joseph had said to them in his interpretation. 23 The c hief cupbearer, however, did not re member Joseph; he forgot him. Pharaoh’s Dreams 41 When two full years had p assed, Pharaoh had a dream: He was stand ing by the Nile, 2 when out of the river t here came up seven cows, sleek and fat, and they g razed a mong the reeds. 3 Af ter them, seven other cows, ugly and g aunt, came up out of the Nile and s tood beside those on the riverbank. 4 And the cows that were ugly and g aunt ate up the seven sleek, fat cows. Then Pharaoh woke up. 5 He fell a sleep a gain and had a second d ream: Seven heads of g rain, h ealthy and good, were growing on a single stalk. 6 After them, seven other heads of g rain sprouted — thin and scorched by the east wind. 7 The thin heads of g rain swallowed up the seven healthy, full h eads. Then Pharaoh woke up; it had been a dream. 8 In the morning his mind was troubled, so he sent for all the magicians and wise men of 69 gypt. Pharaoh told them his dreams, but no E one could interpret them for him. 9 Then the c hief cupbearer said to Pharaoh, “Today I am reminded of my shortcomings. 10 Pharaoh was once ang ry with his serv ants, and he imprisoned me and the chief baker in the house of the captain of the g uard. 11 Each of us had a d ream the same n ight, and each d ream had a meaning of its own. 12 Now a young Hebrew was there with us, a servant of the captain of the g uard. We told him our d reams, and he interpreted them for us, giv ing each man the interpretation of his dream. 13 And t hings t urned out exactly as he inter preted them to us: I was restored to my posi tion, and the other man was impaled.” 14 So Pharaoh sent for Joseph, and he was quickly brought from the dungeon. When he had shaved and changed his clothes, he came before Pharaoh. 15 Pharaoh said to Joseph, “I had a d ream, and no one can interpret it. But I have heard it said of you that when you hear a dream you can interpret it.” 16 “I cannot do it,” Joseph replied to Phar aoh, “but God will give Pharaoh the ans wer he desires.” 17 Then Phar aoh said to Joseph, “In my dream I was standing on the bank of the Nile, 18 when out of the river t here came up seven cows, fat and sleek, and they g razed a mong the reeds. 19 After them, seven other cows came up — scrawny and very ugly and lean. I had never seen such ugly cows in all the land of Egypt. 20 The lean, ugly cows ate up the seven fat cows that came up f irst. 21 But even after they ate them, no one could tell that they had done so; they l ooked just as ugly as before. Then I woke up. 22 “In my d ream I saw seven h eads of grain, full and good, growing on a single s talk. 23 Af ter them, seven other heads sprouted — w ith ered and thin and scorched by the east wind. 24 The thin heads of g rain swallowed up the seven good heads. I told this to the magicians, but none of them could explain it to me.” 25 Then Jo s eph said to Phar a oh, “The dreams of Pharaoh are one and the same. God has revealed to Pharaoh what he is about to a 38 Or of the gods DAY 20 do. 26 The seven good cows are seven years, and the seven good heads of g rain are seven years; it is one and the same d ream. 27 The seven lean, ugly cows that came up afterward are seven years, and so are the seven worth less h eads of g rain s corched by the east wind: They are seven years of famine. 28 “It is just as I said to Phar aoh: God has shown Pharaoh what he is about to do. 29 Seven y ears d ream was given to Pharaoh in two forms is that the matter has been firm ly decided by God, and God will do it soon. 33 “And now let Pharaoh look for a discern ing and wise man and put him in c harge of the land of Egypt. 34 Let Pharaoh app oint commissioners over the land to take a f ifth of the harvest of Egypt during the seven years of abundance. 35 They s hould collect all the food of these good years that are coming and store up the g rain under the authorit y off icials. 38 So Pharaoh asked them, “Can we find anyone like this man, one in whom is the spirit of God a ?” 39 Then Pharaoh said to Joseph, “Since God has made all this k nown to you, there is no one so discerning and wise as you. 40 You shall be in charge of my palace, and all my people are to subm it to your orders. Only with re spect to the throne will I be greater than you.” MATTHEW 14:1 — 14:21 John the Baptist Beheaded 14 At that time Herod the tetrarch heard the reports about Jesus, 2 and he said to his attendants, “This is John the Baptist; he DAY 20 70 has risen from the dead! That is why miracu lous powers are at work in him.” 3 Now Herod had arrested John and bound him and put him in prison because of Hero dias, his brother Philip’s wife, 4 for John had been saying to him: “It is not lawf ul for you to have her.” 5 Herod wanted to kill John, but he was a fraid of the people, because they consid ered John a prophet. 6 On Herod’s birthday the daughter of He rodias danced for the guests and pleased Her od so much 7 that he promised with an oath to give her whatever she asked. 8 Prompted by her mother, she said, “Give me here on a plat ter the head of John the Bapt ist.” 9 The king was distressed, but because of his o aths and his dinner g uests, he ordered that her request be granted 10 and had John beheaded in the prison. 11 His head was brought in on a plat ter and given to the girl, who carried it to her mother. 12 John’s disciples came and took his body and buried it. Then they went and told Jesus. Jesus Feeds the Five Thousand 13 When Jesus h eard what had happened, he withd rew by boat priv ately to a solitary place. Hearing of this, the c rowds followed him on foot from the towns. 14 When Jesus landed and saw a large c rowd, he had compas sion on them and healed their sick. 15 As even ing app roached, the disc ip les came to him and said, “This is a remote place, and it’s already getting late. Send the crowds away, so they can go to the villages and buy themselves some food.” 16 Jesus re plied, satisf ied, and the disc iples picked up t welve basket f uls of broken pieces that were left over. 21 The num a 17 Or covenant of her God ber of those who ate was about five thousand men, besides women and children. PROVERBS 2:12 — 2:22. REWIND Genesis 40:1 – 41:40; Matthew 14:1 – 21; Proverbs 2:12 – 22 EVERYONE NEEDS HELP. The cupbearer and baker of Genesis 40 – 41 were rotting in prison, unfortunate guys who offended Egypt’s king. John the Baptist is beheaded in Matthew 14, the victim of an evil family’s rage. And Jesus finds himself followed by thousands of hurting and hungry p eople. But Proverbs 2 explains where you can get help DAY 21 71 when you need it. God’s wisdom saves you from wicked people. His insights help you find the path to life. D day21 GENESIS 41:41 — 42:38 Joseph in Charge of Egypt 41 So Pharaoh said to Joseph, “I hereby put you in c harge of the whole land of Egypt.” 42 Then Phar aoh took his signet ring from his finger and put it on Joseph’s finger. He d ressed him in robes of fine linen and put a gold c hain a round his neck. 43 He had him ride in a chariot as his second-in-command, a and people shouted before him, “Make way b !” Thus he put him in charge of the whole land of Egypt. 44 Then Phar aoh, c to be his wife. And Joseph went through out the land of Egypt. 46 Joseph was thirt y years old when he en tered the serv ice of Pharaoh king of Egypt. And Joseph went out from Pharaoh’s presence and traveled throughout Egypt. 47 During the seven years of abundance the land produced plent if ully. 48 Joseph collected all the food produced in those seven years of abundance in Egypt and stored it in the cities. In each city he put the food g rown in the f ields surround ing it. 49 Joseph stored up huge quantities of grain, like the sand of the sea; it was so much that he s topped keeping records because it was beyond measure. 50 Be fore the y ears of famine came, two sons were born to Joseph by Asenath daughter of Potiphera, p riest of On. 51 Joseph named his firstborn Manasseh d and said, “It is because God has made me forget all my trouble and all my father’s household.” 52 The second son he named Ephra im e and said, “It is because God has made me fruitf ul in the land of my suffering.” 53 The seven years of abund ance in Egypt came to an end, 54 and the seven years of fam ine fam i ne had spread over the whole country, Joseph o pened all the store houses and sold g rain to the Egyptians, for the famine was severe throughout Egypt. 57 And all the world came to Egypt to buy grain from Joseph, because the famine was se vere every where. Joseph’s Brothers Go to Egypt 42 When Jacob learned that there was g rain in Egypt, he said to his sons, “Why do you just keep looking at each oth er?” 2 He continued, “I have heard that there is grain in Egypt. Go down there and buy some for us, so that we may live and not die.” 3 Then ten of Joseph’s brothers went down to buy g rain from Egypt. 4 But Jacob did not send Benjam in, Joseph’s brother, with the others, because he was a fraid that harm might come to him. 5 So Israel’s sons were a mong those who went to buy g rain, for there was famine in the land of Canaan also. 6 Now Jo s eph was the gov e r nor of the land, the person who sold grain to all its peo ple. So when Joseph’s brothers arr ived, they bowed down to him with their faces to the ground. 7 As soon as Joseph saw his brothers, a 43 Or in the chariot of his second-in-command ; or in his second chariot b 43 Or Bow down c 45 That is, Heliopolis; also in verse 50 d 51 Manasseh sounds like and may be derived from the Hebrew for forget. e 52 Ephraim sounds like the Hebrew for twice fruitful. DAY 21 72 he r ecognized them, but he pretended to be a stranger and spoke harshly to them. “Where do you come from?” he asked. “From the land of Canaan,” they replied, “to buy food.” 8 Alt hough Jos eph recog n ized his broth ers, they did not recognize him. 9 Then he re membered his dreams a bout them and said to them, “You are spies! You have come to see where our land is unprotected.” 10 “No, my lord,” they ans wered. “Your ser vants have come to buy food. 11 We are all the sons of one man. Your serv ants are honest men, not spies.” 12 “No!” he said to them. “You have come to see where our land is unprotected.” 13 But they re plied, “Your serv ants were twelve brothers, the sons of one man, who lives in the land of Canaan. The youngest is now with our father, and one is no more.” 14 Jos eph said to them, “It is just as I told you: You are spies! 15 And this is how you will be tested: As surely as Pharaoh lives, you will not leave this place unless your youngest brother comes here. 16 Send one of your num ber, Jo seph said to them, “Do this and you will live, for I fear God: 19 If you are honest men, let one of your brothers stay here in prison, while the rest of you go and take g rain back for your starving house holds. 20 But you must bring your youngest brother to me, so that your words may be veri fied and that you may not die.” This they pro ceeded to do. 21 They said to one another, “Surely we are being punished because of our brother. We saw how distressed he was when he pleaded with us for his life, but we would not listen; that’s why this distress has come on us.” 22 Reu ben replied, “Didn’t I tell you not to sin a gainst the boy? But you wouldn’t lis ten! Now we must give an accounting for his blood.” 23 They did not rea lize that Joseph a 34 Or move about freely c ould understand them, since he was using an interpreter. 24 He t urned away from them and began to weep, but then came back and spoke to them again. He had Simeon taken from them and bound before their eyes. 25 Joseph gave orders to fill t heir bags with grain, to put each man’s silver back in his sack, and to give them prov isions re turned,” he said to his brothers. “Here it is in my sack.” Their h earts sank and they t urned to each other trembling and said, “What is this that God has done to us?” 29 When they came to t heir fat her hon est men; we are not spies. 32 We were t welve brothers, sons of one father. One is no more, and the youngest is now with our father in Canaan.’ 33 “Then the man who is lord over the land said to us, ‘This is how I will know wheth er you are hone st men: L eave one of your brothers here with me, and take food for your starving households and go. 34 But bring your youngest brother to me so I will know that you are not s pies but honest men. Then I will give your brother back to you, and you can trade a in the land.’ ” 35 As they were empt ying t heir sacks, t here in each m an’s sack was his p ouch fat her, “You may put both of my sons to death if I do not bring DAY 21 73 him back to you. Entrust him to my care, and I will bring him back.” 38 But Jacob said, “My son will not go down t here with you; his brother is dead and he is the only one left. If harm comes to him on the journey you are taking, you will bring my gray head down to the g rave in sorrow.” MATTHEW 14:22 — 15:9 Jesus Walks on the Water 22 Imm ed iatel y Jesus made the disc iples get into the boat and go on a head of him to the other side, while he dismissed the crowd. 23 Af ter he had dism issed them, he went up on a mountainside by himself to pray. Later that night, he was there a lone, 24 and the boat was already a considerable distance from land, buffeted by the waves because the wind was against it. 25 Short ly before dawn Jesus went out to them, walking on the lake. 26 When the dis ciples saw him walking on the lake, they were terrif ied. “It’s a ghost,” they said, and cried out in fear. 27 But J esus imm ed ia tel y a fraid and, beg inn ing to sink, cried out, “Lord, save me!” 31 Immed iately Jesus reached out his hand and caught him. “You of litt le faith,” he said, “why did you doubt?” 32 And when they c limbed into the boat, the wind died down. 33 Then those who were in the boat worshiped him, saying, “Truly you are the Son of God.” 34 When they had c rossed over, they landed at Gennesa ret. 35 And when the men of that place recognized Jesus, they sent word to all the sur round ing count ry. People brought all their sick to him 36 and begged him to let the sick just touch the edge of his c loak, and all who touched it were healed. That Which Defiles 15 Then some Pharisees and teachers of the law came to Jesus from Jer usalem and asked, 2 “Why do your disciples b reak the tradition of the elders? They don’t wash their hands before they eat!” 3 Jesus replied, “And why do you break the command of God for the sake of your trad i tion? 4 For God said, ‘Honor your fat her and mother’ a and ‘Anyone who curses their father or mother is to be put to death.’ b 5 But you say that if anyone dec lares that what might have been used to help their father or mother is ‘de voted to God,’ 6 they are not to ‘honor their father or mother’ with it. Thus you nullif y the word of God for the sake of your trad ition. 7 You hyp oc rites! Isaiah was right when he prophesied about you: 8 “ ‘These people honor me with their lips, but their hearts are far from me. 9 They worship me in vain; their teachings are merely human rules.’ c ” PSALM 12:1 — 12:8 Psalm 12 d For the director of music. According to sheminith. e, a 4 Exodus 20:12; Deut. 5:16 b 4 Exodus 21:17; Lev. 20:9 c 9 Isaiah 29:13 d In Hebrew texts 12:1-8 is numbered 12:2-9. e Title: Probably a musical term DAY 22 I will now arise,” says the Lord. “I will protect them from those who malign them.” 6 And the words of the Lord are flawless, like silver purified in a crucible, like gold a refined seven times. 7 You, Lord, will keep the needy safe and will protect us forever from the wicked, 8 who freely strut about when what is vile is honored by the human race. REWIND Genesis 41:41 – 42:38; Matthew 14:22 – 15:9; Psalm 12 SOMETIMES YOU WIN. Joseph might have given up hope he would ever be rescued from prison, but in Genesis 41 the Lord lifts him to the top of one of the most potent nations in world history. In Matthew 14 Peter fears he’s seen a ghost, but Jesus gives him a shot at walking on water. And Psalm 12 notes that when the poor are plundered, God rises up to protect them. Even when you feel defeated by evil, at the right time the Lord helps you win. D day22 GENESIS 43:1 — 44:34 The Second Journey to Egypt 43 Now the famine was still severe in the land. 2 So when they had eaten all the grain they had brought from Egypt, t heir fa 74 ther said to them, “Go back and buy us a litt le more food.” 3 But Judah said to him, “The man warned us solemnly, ‘You will not see my face again unless your brother is with you.’ 4 If you will send our brother a long with us, we will go down and buy food for you. 5 But if you will not send him, we will not go down, because the man said to us, ‘You will not see my face again unless your brother is with you.’ ” 6 Is r ael asked, “Why did you b ring this trouble on me by telling the man you had an other brother?” 7 They re plied, “The man questioned us closely a bout ourselves and our family. ‘Is your father s till living?’ he asked us. ‘Do you have another brother?’ We simply ans wered his questions. How were we to know he w ould say, ‘Bring your brother down here’?” 8 Then Judah said to Israel his fat her, “Send the boy a long with me and we will go at once, so that we and you and our children may live and not die. 9 I myself will guarantee his safe ty; you can hold me persona lly responsible for him. If I do not bring him back to you and set him here before you, I will bear the blame before you all my life. 10 As it is, if we had not delayed, we could have gone and returned twice.” 11 Then t heir father Israel said to them, “If it must be, then do this: Put some of the best products of the land in your bags and take them down to the man as a gift — a lit tle balm and a little honey, some spices and myrrh, some pistachio nuts and almonds. 12 Take double the a mount of silver with you, for you must return the silver that was put back into the mouths of your sacks. Perhaps it was a mistake. 13 Take your brother also and go back to the man at once. 14 And may God Almighty b grant you merc y before the man so that he will let your other brother and Benja min come back with you. As for me, if I am bereaved, I am bereaved.” 15 So the men took the g ifts and double the a mount of silver, and Benjam in also. They hurr ied down to Egypt and presented them selves to Joseph. 16 When Joseph saw Benja min with them, he said to the stewa rd of his a 6 Probable reading of the original Hebrew text; Masoretic Text earth b 14 Hebrew El-Shaddai 75 ouse, “Take these men to my house, slaugh h ter f irst time. He wants to attack us and overpower us and s eize us as s laves and take our donkeys.” 19 So they went up to Joseph’s stewa rd and spoke to him at the entrance to the house. 20 “We beg your pardon, our lord,” they said, “we came down here the first time to buy food. 21 But at the place where we s topped for the night we opened our sacks and each of us found his silver — the exact weight — in the mouth of his sack. So we have brought it back with us. 22 We have also brought add it iona l silver with us to buy food. We don’t know who put our silver in our sacks.” 23 “It’s all r ight,” he said. “Don’t be a fraid. Your God, the God of your father, has giv en you treasure in your s acks; I received your silver.” Then he brought Simeon out to them. 24 The stewa rd took the men into Joseph’s house, gave them water to wash their feet and prov ided fodder for t heir donk eys. 25 They prepared t heir g ifts for Jos eph’s ar r iva l at noon, because they had heard that they were to eat there. 26 When Joseph came home, they present ed to him the gifts they had brought into the house, and they bowed down before him to the ground. 27 He a sked them how they were, and then he said, “How is your aged father you told me about? Is he still living?” 28 They replied, “Your servant our fat her is still a live and well.” And they bowed down, prostrating themselves before him. 29 As he looked about and saw his brother Benjamin, his own mother’s son, he asked, “Is this your youngest brother, the one you told me a bout?”.” DAY 22 32 They s erved him by himself, the broth ers by themselves, and the Egyptians who ate with him by themselves, because Egyptians could not eat with Hebrews, for that is detest able to Egyptians. 33 The men had been seat ed before him in the order of their ages, from the firstborn to the youngest; and they looked at each other in astonishment. 34 When por tions were s erved to them from Joseph’s table, Benjamin’s portion was five times as much as anyone else’s. So they feasted and drank freely with him. A Silver Cup in a Sack 44 Now Joseph gave t hese instruct ions to the stewa rd of his house: “Fill the men’s sacks with as much food as they can carr y, and put each man’s silver in the mouth of his sack. 2 Then put my cup, the silver one, in the mouth of the youngest one’s sack, a long with the silver for his g rain.” And he did as Joseph said. 3 As morn ing dawned, the men were sent on their way with their donkeys. 4 They had not gone far from the city when Joseph said to his stewa rd, “Go after those men at once, and when you catch up with them, say to them, ‘Why have you repaid good with evil? 5 Isn’t this the cup my master d rinks from and also uses for divination? This is a wicked t hing you have done.’ ” 6 When he c aught up with them, he re peated t hese words to them. 7 But they said to him, “Why does my lord say such things? Far be it from your servants to do anything like that! 8 We even brought back to you from the land of Canaan the silver we found inside the mouths of our s acks. So why w ould we s teal silver or gold from your master’s h ouse? g round and opened it. 12 Then the stew ard proceeded to s earch, beg inning with the oldest and ending with the youngest. And the cup was found in Benjamin’s sack. 13 At this, DAY 22 76 they tore t heir c lothes. Then they all loaded their donkeys and ret urned to the city. 14 Jo seph was still in the house when Ju d re plied. “What can we say? How can we prove our innocence? God has uncovered your ser vants’ g uilt. We are now my lord’s slaves — we ourselves and the one who was found to have the cup.” 17 But Joseph said, “Far be it from me to do such a thing! Only the man who was found to have the cup will become my s lave. The rest of you, go back to your father in peace.” 18 Then Ju d ah went up to him and said: “Pardon your servant, my lord, let me speak a word to my lord. Do not be angry with your serv ant, though you are equal to Pharaoh himself. 19 My lord a sked his serv ants, ‘Do you have a father or a brother?’ 20 And we an swered, ‘We have an aged father, and there is a young son born to him in his old age. His brother is dead, and he is the only one of his mother’s sons left, and his father loves him.’ 21 “Then you said to your serv ants, ‘Bring him down to me so I can see him for myself.’ 22 And we said to my lord, ‘The boy can not leave his father; if he leaves him, his father will die.’ 23 But you told your servants, ‘Unless your youngest brother comes down with you, you will not see my face a gain.’ 24 When we went back to your servant my father, we told him what my lord had said. 25 “Then our fat her said, ‘Go back and buy a litt le more food.’ 26 But we said, ‘We cannot go down. Only if our youngest brother is with us will we go. We cannot see the man’s face unless our youngest brother is with us.’ 27 “Your serv ant my fat her g rave in misery.’ a 14 Some manuscripts blind guides of the blind 30 “So now, if the boy is not with us when I go back to your servant my father, and if my father, whose life is closely bound up with the b oy’s life, 31 sees that the boy isn’t there, he will die. Your servants will bring the gray head of our fat her down to the g rave in sor row. 32 Your servant guaranteed the boy’s safe ty.” MATTHEW 15:10 — 15:39 10 Jesus c alled the c rowd to him and said, “Listen and understand. 11 What goes into someone’s mouth does not defile them, but what comes out of their mouth, that is what def iles them.” 12 Then the dis c iples came to him and asked, “Do you know that the Pharisees were offended when they heard this?” 13 He re plied, “Every plant that my heav enly Father has not planted will be p ulled up by the roots. 14 Leave them; they are blind g uides. a If the blind lead the blind, both will fall into a pit.” 15 Peter said, “Explain the parable to us.” 16 “Are you still so dull?” Jesus a sked them. 17 “Don’t you see that what e ver enters the mouth goes into the stomach and then out of the body? 18 But the things that come out of a person’s m outh come from the heart, and these def ile them. 19 For out of the heart come evil thoughts — murder, adultery, sexu al immoralit y, theft, false testimony, slander. 20 These are what def ile a person; but eating with unwashed hands does not def ile them.” The Faith of a Canaanite Woman 21 Leav i ng that place, Jesus withd rew to the region of Tyre and Sidon. 22 A Canaanite woman from that vicinit y came to him, crying out, “Lord, Son of Dav id, have merc y on me! DAY 22 77 My daughter is demon-possessed and suffer ing terribly.” 23 Jesus did not ans wer a word. So his dis ciples came to him and urged him, “Send her away, for she keeps crying out after us.” 24 He ans wered, “I was sent only to the lost sheep of Israel.” 25 The woma n came and k nelt before him. “Lord, help me!” she said. 26 He re plied, “It is not right to take the children’s bread and toss it to the dogs.” 27 “Yes it is, Lord,” she said. “Even the dogs eat the c rumbs that fall from their master’s table.” 28 Then Jesus said to her, “Woma n, you have great faith! Your request is granted.” And her daughter was healed at that moment. Jesus Feeds the Four Thousand 29 Jesus left t here and went a long the Sea of Galilee. Then he went up on a mountainside and sat down. 30 Great c rowds came to him, bringing the lame, the blind, the crippled, the mute and many others, and laid them at his feet; and he healed them. 31 The people were a mazed when they saw the mute speaking, the crippled made well, the lame walking and the blind seeing. And they praised the God of Israel. 32 Jesus called his disc iples to him and said, “I have compassion for these people; they have already been with me three days and have nothing to eat. I do not want to send them away hung ry, or they may collapse on the way.” 33 His disc iples ans wered, “Where could we get enough b read in this remote place to feed such a crowd?” 34 “How many loaves do you have?” Jesus asked. “Seven,” they replied, “and a few small fish.” 35 He told the c rowd to sit down on the ground. 36 Then he took the seven loaves and the fish, and when he had given thanks, he broke them and gave them to the disc iples, and they in turn to the people. 37 They all ate and were satisfied. Afterw ard the dis ciples picked up seven basket f uls of broken a In Hebrew texts 13:1-6 is numbered 13:2-6. pieces that were left over. 38 The number of those who ate was four thousand men, besides women and child ren. 39 After Jesus had sent the crowd away, he got into the boat and went to the vicinit y of Magadan. PSALM 13:1 — 13:6. REWIND Genesis 43 – 44; Matthew 15:10 – 39; Psalm 13 THANK GOD FOR SUPPER. Genesis 43 describes a famine so severe that Jacob’s family faces starvation if they don’t go on a long journey to another country. Matthew 15 shows hungry people stranded in a remote place with no food. And Psalm 13 relates loud rumblings of spiritual hunger. So don’t take your food for granted today or ever. Literal food is a gift straight from God, and the Lord is also the only one able to satisfy your soul. D DAY 23 78 day23 GENESIS 45:1 — 47:12 Joseph Makes Himself Known 45 Then Joseph could no longer control himself before all his attendants, and he c ried out, “Have everyone leave my pres ence!” So there was no one with Joseph when he made himself k nown to his brothers. 2 And he wept so loudly that the Egyptians heard him, and Pharaoh’s household heard about it. 3 Joseph said to his brothers, “I am Joseph! Is my father s till living?” But his brothers were not able to answer him, because they were ter rif ied at his presence. 4 Then Joseph said to his brothers, “Come close to me.” When they had done so, he said, “I am your brother Joseph, the one you sold into Egypt! 5 And now, do not be distressed and do not be ang ry with yourselves for sell ing me here, because it was to save lives that God sent me a head of you. 6 For two y ears now there has been famine in the land, and for the next five years there will be no plowing and reaping. 7 But God sent me a head of you to preserve for you a remnant on e arth and to save your lives by a g reat deliverance. a 8 “So then, it was not you who sent me here, but God. He made me father to Pharaoh, lord of his entire household and ruler of all E gypt. 9 Now hurr y back to my fat her and say to him, ‘This is what your son Joseph says: God has made me lord of all E gypt. Come down to me; don’t delay. 10 You shall live in the reg ion of Goshen and be near me — you, your children and grandchildren, your f locks and herds, and all you have. 11 I will prov ide for you there, be cause five years of famine are still to come. Otherw ise you and your household and all who belong to you will become destit ute.’ 12 “You can see for your selves, and so can my brother Benjamin, that it is really I who am speaking to you. 13 Tell my father about all the honor accorded me in Egypt and about everyt hing you have seen. And b ring my fa ther down here quickly.” 14 Then he t hrew his arms a round his brother Benjam in and wept, and Benjam in embraced him, weeping. 15 And he k issed all his brothers and wept over them. Afterward his brothers talked with him. 16 When the news reached Pharaoh’s palace that Joseph’s brothers had come, Pharaoh and all his off icials were p leased. 17 Pharaoh said to Joseph, “Tell your brothers, ‘Do this: Load your animals and return to the land of Ca naan, 18 and b ring your fat her and your fam ilies back to me. I will give you the best of the land of E gypt and you can enjoy the fat of the land.’ 19 “You are also directed to tell them, ‘Do this: Take some carts from E gypt for your child ren and your w ives, and get your fat her and come. 20 Never mind a bout your belong ings, because the best of all Egypt will be yours.’ ” 21 So the sons of Israel did this. Joseph gave them carts, as Pharaoh had commanded, and he also gave them prov isions for their journey. 22 To each of them he gave new clothing, but to Benjamin he gave three hund red shekels b of silver and five sets of clothes. 23 And this is what he sent to his father: ten donkeys loaded with the best t hings of Egypt, and ten female donkeys loaded with grain and b read and oth er prov isions for his journey. 24 Then he sent his brothers away, and as they were leaving he said to them, “Don’t quarrel on the way!” 25 So they went up out of E gypt and came to their father Jacob in the land of Canaan. 26 They told him, “Joseph is still a live! In fact, he is ruler of all Egypt.” Jacob was stunned; he did not believe them. 27 But when they told him everything Joseph had said to them, and when he saw the carts Joseph had sent to carr y him back, the spirit of t heir fat her Jacob re a 7 Or save you as a great band of survivors b 22 That is, about 7 1/2 pounds or about 3.5 kilograms 79 vived. 28 And Israel said, “I’m conv inced! My son Joseph is still a live. I will go and see him before I die.” Jacob Goes to Egypt 46 So Israel set out with all that was his, and when he reached Beersheba, he offered sacr if ices to the God of his father Isaac. 2 And God s poke to Israel in a vision at night and said, “Jacob! Jacob!” “Here I am,” he replied. 3 “I am God, the God of your fa t her,” he said. “Do not be a fraid to go down to Egypt, for I will make you into a g reat nation there. 4 I will go down to E gypt with you, and I will surely bring you back again. And Joseph’s own hand will close your eyes.” 5 Then Jacob left Beersheba, and Isr ae l’s sons took their father Jacob and their chil had sent to transport him. 6 So Jacob and all his offspring went to Egypt, taking with them their livestock and the possessions they had ac quired in Canaan. 7 Jacob brought with him to Egypt his sons and grandsons and his daugh ters and granddaughters — a ll his offspring. 8 These are the names of the sons of Isra el (Jacob and his descendants) who went to Egypt: Reuben the firstborn of Jacob. 9 The sons of Reuben: Hanok, Pallu, Hezron and Karmi. 10 The sons of Simeon: Jemuel, Jam in, Ohad, Ja k in, Zohar and Shau l the son of a Can aan. DAY 23 13 The sons of Issachar: Tola, Puah, a Jashub b and Shimron. 14 The sons of Zebu lun: Sered, Elon and Jahleel. 15 These were the sons Leah bore to Jacob in Paddan Aram, c besides his daughter Dinah. These sons and daughters of his were thirt y- three in all. 16 The sons of Gad: Zephon, d Hagg i, Shuni, Ezbon, Eri, Arodi and Areli. 17 The sons of Asher: Imnah, Ishvah, Ishv i and Beriah. Their sister was Serah. The sons of Beriah: Heber and Malk iel. 18 These were the child ren born to Jacob by Zilpah, whom Laban had given to his daugh ter Leah — sixteen in all. 19 The sons of Jacob’s wife Rachel: Jos eph and Benjam in. 20 In Egypt, Manasseh and Ephraim were born to Joseph by Asenath daughter of Po tiphera, priest of On. e 21 The sons of Benjamin: Bela, Beker, Ashbel, Gera, Naaman, Ehi, Rosh, Muppim, Huppim and Ard. 22 These were the sons of Rac hel hah, whom Laban had given to his daughter Rachel — seven in all. 26 All those who went to Egypt with Jacob — those who were his direct descendants, not counting his sons’ w ives — numbered six t ysix persons. 27 With the two sons f who had been born to Joseph in Egypt, the members of Jacob’s family, w hich went to Egypt, were sevent y g in all. a 13 Samaritan Pentateuch and Syriac (see also 1 Chron. 7:1); Masoretic Text Puvah b 13 Samaritan Pentateuch and some Septuagint manuscripts (see also Num. 26:24 and 1 Chron. 7:1); Masoretic Text Iob c 15 That is, Northwest Mesopotamia d 16 Samaritan Pentateuch and Septuagint (see also Num. 26:15); Masoretic Text Ziphion e 20 That is, Heliopolis f 27 Hebrew; Septuagint the nine children g 27 Hebrew (see also Exodus 1:5 and note); Septuagint (see also Acts 7:14) seventy-five DAY 23 80 28 Now Jacob sent Judah a head of him to Jo seph to get directions to Goshen. When they arrived in the region of Goshen, 29 Joseph had his chariot made ready and went to Goshen to meet his father Israel. As soon as Joseph ap peared before him, he threw his arms a round a long their f locks and herds and everything they own.’ 33 When Pharaoh calls you in and asks, ‘What is your occupa tion?’ 34 you should answer, ‘Your serv ants have tended livestock from our boyhood on, just as our fat hers did.’ Then you will be al lowed to settle in the reg ion of Goshen, for all shepherds are detestable to the Egyptians.” Joseph went and told Pharaoh, “My father and brothers, with their f locks and h erds w hile, because the famine is severe in Canaan and your servants’ f locks have no pas ture. So now, please let your servants sett le in Goshen.” 5 Pharaoh said to Joseph, “Your fat her and your brothers have come to you, 6 and the land of Egypt is before you; sett le your father and your brothers in the best part of the land. Let them live in Goshen. And if you know of any among them with special abilit y, put them in charge of my own livestock.” 7 Then Jo seph brought his father Jacob in and presented him before Pharaoh. After Ja 47 cob blessed b Pharaoh, 8 Pharaoh asked him, “How old are you?” 9 And Jacob said to Pharaoh, “The years of my pilg rimage are a hund red and thirt y. My years have been few and diff icult, and they do not equal the years of the pilg rimage of my fat hers.” 10 Then Jacob blessed c Pharaoh and went out from his presence. 11 So Joseph sett led his fat her and his broth ers in Egypt and gave them propert y in the best part of the land, the district of Rameses, as Pharaoh directed. 12 Joseph also prov ided his father and his brothers and all his father’s household with food, according to the number of their children. MATTHEW 16:1 — 16:20 The Demand for a Sign 16 The Pharisees and Sadducees came to Jesus and tested him by asking him to show them a sign from heaven. 2 He re plied, “When even ing. disc i ples forgot to take b read. 6 “Be caref ul,” Jesus said to them. “Be on your g uard a gainst the yeast of the Pharisees and Sadducees.” 7 They dis c ussed this a mong themselves and said, “It is because we d idn’t bring any bread.” 8 Aware of t heir disc uss ion, Jesus a sked, “You of little faith, why are you talking among yourselves about having no bread? 9 Do you still not understand? D on’t you remem ber the five loaves for the five thousand, and how many basketf uls you gathered? 10 Or the seven loaves for the four thousand, and how a 29 Hebrew around him b 7 Or greeted c 10 Or said farewell to d 2,3 Some early manuscripts do not have When evening comes . . . of the times. DAY 23 81 many basketf uls you gathered? 11 How is it you don’t understand that I was not talking to you about bread? But be on your g uard against the yeast of the Pharisees and Sadducees.” 12 Then they understood that he was not telling them to g uard against the y east used in bread, but against the teaching of the Pharisees and Sad ducees. Peter Declares That Jesus Is the Messiah 13 When Jesus came to the reg ion of Caesa rea Philippi, he asked his disciples, “Who do people say the Son of Man is?” 14 They replied, “Some say John the Bapt ist; others say Elijah; and still others, Jeremiah or one of the prophets.” 15 “But what about you?” he asked. “Who do you say I am?” 16 Simon Peter ans wered, “You are the Mes siah, the Son of the living God.” 17 Jesus re plied, “Blessed are you, Simon son of Jonah, for this was not revealed to you by f lesh and blood, but by my Father in heav en. 18 And I tell you that you are Peter, a and on this rock I will b uild my c hurch, and the gates of Hades b will not overcome it. 19 I will give you the keys of the kingdom of heaven; whatever you bind on earth will be c bound in heaven, and whatever you loose on earth will be c loosed in heaven.” 20 Then he ordered his disc iples not to tell anyone that he was the Messiah. PSALM 14:1 — 14:7 Psalm 14 For the director of music. Of David.! REWIND Genesis 45:1 – 47:12; Matthew 16:1 – 20; Psalm 14 FIGURE OUT WHO GOD REALLY IS. Joseph’s brothers get the surprise of their lives in Genesis 45 – 47 when their long-lost sibling reveals his identity. Famous words recorded in Matthew 16 show that, unlike the masses, Peter recognizes Jesus as the Messiah, the Son of God. But the fool of Psalm 14 doesn’t bother to figure out anything. He dismisses the Lord as unreal or irrelevant and refuses to rethink his conclusion. God is the one who sees us from heaven. He’s the one who saves. D 1 The fool d says in his heart, “There is no God.” They are corrupt, their deeds are vile; there is no one who does good. 2 The Lord looks down from heaven on all mankind to see if there are any who understand, any who seek God. a 18 The Greek word for Peter means rock. b 18 That is, the realm of the dead c 19 Or will have been d 1 The Hebrew words rendered fool in Psalms denote one who is morally deficient. DAY 24 82 day24 GENESIS 47:13 — 48:22 Joseph and the Famine 13 There was no food, however, in the w hole reg ion because the famine was severe; both Egypt and Canaan wasted away because of the famine. 14 Joseph col lected all the money that was to be found in Egypt and Canaan in payment for the g rain they were buying, and he brought it to Pharaoh’s palace. 15 When the mone y of the people of E gypt and Canaan was gone, all Egypt came to Joseph and said, “Give us food. Why should we die before your eyes? Our money is all gone.” 16 “Then b ring your livestock,” said Joseph. “I will sell you food in exchange for your live stock, since your money is gone.” 17 So they brought their livestock to Joseph, and he gave them food in exchange for their horses, their sheep and goats, their cattle and donk eys. And he brought them through that year with food in exchange for all their livestock. 18 When that year was over, they came to him the following year and said, “We can not hide from our lord the fact that since our money is gone and our livestock belongs to you, there is nothing left for our lord ex ceptos eph bought all the land in E gypt for Pharaoh. The Egyptians, one and all, sold their f ields, because the famine was too severe for them. The land became Pharaoh’s, 21 and Joseph reduced the people to serv it ude, a from one end of Egypt to the other. 22 However, he did not buy the land of the priests, because they received a regu lar allotment from Phar aoh and had food enough from the allotment Pharaoh gave them. That is why they did not sell their land. 23 Jo s eph said to the people, “Now that I have bought you and your land today for Pharaoh, here is seed for you so you can plant the g round. 24 But when the crop c omes in, give a f ifth of it to Pharaoh. The other four- fifths you may keep as seed for the f ields and as food for yourselves and your households and your children.” 25 “You have s aved our lives,” they said. “May we find favor in the eyes of our lord; we will be in bondage to Pharaoh.” 26 So Joseph establ ished it as a law concern ing land in Egypt — still in force today — that a f ifth of the produce belongs to Pharaoh. It was only the land of the priests that did not become Pharaoh’s. 27 Now the Israelites sett led in Egypt in the reg ion of Goshen. They acquired proper t y there and were fruitf ul and increased greatly in number. 28 Jacob l ived in Egypt seventeen years, and the years of his life were a hundred and fort yseven. 29 When the time drew near for Israel to die, he called for his son Joseph and said to him, “If I have found favor in your eyes, put your hand under my thigh and promise that you will show me kindness and faithf ulness. Do not bury me in Egypt, 30 but when I rest with my fathers, carr y me out of Egypt and bury me where they are buried.” “I will do as you say,” he said. 31 “Swear to me,” he said. Then Jo s eph swore to him, and Israel worshiped as he leaned on the top of his staff. b Manasseh and Ephraim 48 Some time later Joseph was told, “Your father is ill.” So he took his two sons Manasseh and Ephraim a long with him. 2 When Jacob was told, “Your son Joseph has come to you,” Israel rallied his strength and sat up on the bed. 3 Jacob said to Joseph, “God Alm ighty c ap peared to me at Luz in the land of Canaan, and there he blessed me 4 and said to me, ‘I am going to make you fruitful and inc rease a 21 Samaritan Pentateuch and Septuagint (see also Vulgate); Masoretic Text and he moved the people into the cities b 31 Or Israel bowed down at the head of his bed c 3 Hebrew El-Shaddai DAY 24 83 your numbers. I will make you a commun i ty of peoples, and I will give this land as an everlasting possession to your descendants af ter you.’ 5 “Now then, your two sons born to you in Egypt before I came to you here will be reck oned as mine; Ephraim and Manasseh will be mine, just as Reuben and Simeon are mine. 6 Any chil d ren born to you after them will be yours; in the territor y they inherit they will be reckoned under the names of their broth ers. 7 As I was ret urning from Paddan, a to my sorrow Rac hel died in the land of Canaan while we were s till on the way, a litt le distance from Ephrath. So I buried her there beside the road to Ephrath” (that is, Bethlehem). 8 When Is rael saw the sons of Joseph, he asked, “Who are these?” 9 “They are the sons God has giv en me here,” Joseph said to his father. Then Israel said, “Bring them to me so I may bless them.” 10 Now Israel’s eyes were failing because of old age, and he could hardly see. So Joseph brought his sons c lose to him, and his father k issed them and embraced them. 11 Israel said to Joseph, “I never expected to see your face again, and now God has allowed me to see your children too.” 12 Then Jo seph removed them from Isra el’s k nees and b owed down with his face to the g round.13 And Joseph took both of them, Ephraim on his right toward Israel’s left hand and Manasseh on his left toward Israel’s right hand, and brought them c lose to him. 14 But Israel reached out his right hand and put it on Ephraim’s head, t hough dis pleased; so he took hold of his father’s hand to move it from Ephraim’s head to Manasseh’s head. 18 Joseph said to him, “No, my father, this one is the firstborn; put your r ight hand on his head.” 19 But his fat her ref used and said, “I know, my son, I know. He too will become a people, and he too will become g reat. Nevertheless, his younger brother will be greater than he, and his descendants will become a g roup of nations.” 20 He blessed them that day and said, “In your c and take you c back to the land of your c fathers. 22 And to you I give one more ridge of land d than to your brothers, the ridge I took from the Amorites with my sword and my bow.” MATTHEW 16:21 — 17:13 Jesus Predicts His Death 21 From that time on Jesus began to explain to his disciples that he must go to Jer usalem and suffer many things at the hands of the elders, the c hief priests and the teachers of the law, and that he must be k illed and on the third day be raised to life. 22 Peter took him aside and began to rebuke him. “Never, Lord!” he said. “This shall never happen to you!” 23 Jesus t urned and said to Peter, “Get be hind me, Satan! You are a stumbling block to me; you do not have in mind the concerns of God, but merely human concerns.” 24 Then J esus said to his disciples, “W hoever a 7 That is, Northwest Mesopotamia b 20 The Hebrew is singular. c 21 The Hebrew is plural. d 22 The Hebrew for ridge of land is identical with the place name Shechem. DAY 24 84 ants to be my disciple must deny themselves w and take up their c ross and follow me. 25 For whoever wants to save their life a will lose it, but whoever loses their life for me will find it. 26 What good will it be for someone to gain the w hole w orld, yet forfeit their soul? Or what can anyone give in exc hange for their soul? 27 For the Son of Man is going to come in his Father’s glor y with his angels, and then he will reward each person according to what they have done. 28 “Truly I tell you, some who are standing here will not taste d eath before they see the Son of Man coming in his kingdom.” The Transfiguration 17 After six days Jesus took with him Peter, James and John the brother of James, and led them up a high mountain by themselves. 2 There he was transf igu red be fore them. His face shone like the sun, and his clothes became as white as the light. 3 Just then there appeared before them Moses and Elijah, talking with Jesus. 4 Pe ter said to Jesus, “Lord, it is good for us to be here. If you wish, I will put up three shelters — one for you, one for Moses and one for Elijah.” 5 While he was s till speaking, a bright cloud covered them, and a voice from the cloud said, “This is my Son, whom I love; with him I am well pleased. Listen to him!” 6 When the dis c iples heard this, they fell facedown to the g round, terrif ied. disc iples a sked him, “Why then do the teachers of the law say that Elijah must come first?” 11 Jesus replied, “To be sure, Elijah comes and will restore all things. 12 But I tell you, Elijah has already come, and they did not rec ognize him, but have done to him everything they w ished. In the same way the Son of Man is going to suffer at their hands.” 13 Then the disc iples understood that he was talking to them about John the Baptist. PROVERBS 3:1 — 3:10.. REWIND Genesis 47:13 – 48:22; Matthew 16:21 – 17:13; Proverbs 3:1 – 10 EVERYONE HAS TO TRUST. In Genesis 47 – 48 old Jacob stands before Pharaoh, hoping for kindness from the most powerful man on earth. In Matthew 16 – 17 Jesus foresees his own tortured suffering and death, then gets strength from his Father’s words to face what lies ahead. Proverbs 3 tells you how to trust God right now. You count on God wholeheartedly, more than you rely on a 25 The Greek word means either life or soul ; also in verse 26. b 6 Or will direct your paths 85 your own insights. When you trust yourself to his will, he makes your paths straight. D day25 GENESIS 49:1 — 50:26 Jacob Blesses His Sons DAY 25 49 13 “Zebulun will live by the seashore and become a haven for ships; his border will extend toward Sidon. 2 “Assemble and listen, sons of Jacob; listen to your father Israel. 14 “Issachar is a rawboned f donkey lying down among the sheep pens. g 15 When he sees how good is his resting place and how pleasant is his land, he will bend his shoulder to the burden and submit to forced labor. Then Jacob called for his sons and said: “Gather a round so I can tell you what will happen to you in days to come. a 5 The meaning of the Hebrew for this word is uncertain. b 8 Judah sounds like and may be derived from the Hebrew for praise. c 10 Or from his descendants d 10 Or to whom tribute belongs; the meaning of the Hebrew for this phrase is uncertain. e 12 Or will be dull from wine, / his teeth white from milk f 14 Or strong g 14 Or the campfires; or the saddlebags h 16 Dan here means he provides justice. i 19 Gad sounds like the Hebrew for attack and also for band of raiders. j 21 Or free; / he utters beautiful words k 22 Or Joseph is a wild colt, / a wild colt near a spring, / a wild donkey on a terraced hill DAY 25 86 23 With bitterness archers attacked him; they shot at him with hostility. 24 But his bow remained steady, his strong arms stayed a limber, because of the hand of the Mighty One of Jacob, because of the Shepherd, the Rock of Israel, 25 because of your father’s God, who helps you, because of the Almighty, b who blesses you with blessings of the skies above, blessings of the deep springs below, blessings of the breast and womb. 26 Your father’s blessings are greater than the blessings of the ancient mountains, c the bounty of the age-old than hills. Let all these rest on the head of Joseph, on the brow of the prince among d his brothers. 27 “Benjamin is a ravenous wolf; in the morning he devours the prey, in the evening he divides the plunder.” 28 All t hese are the t welve t ribes of Israel, and this is what their father said to them when he blessed them, giving each the blessing ap propriate to him. The Death of Jacob 29 Then he gave them t hese instruct ions: “I am about to be gathered to my people. Bury me with my fathers in the cave in the f ield of Ephron the Hittite, 30 the cave in the f ield of Machpelah, near Mamre in Canaan, which Abraham bought a long with the field as a buria l place from Ephron the Hittite. 31 There Abraham and his wife Sara h were buried, there Isaac and his wife Rebekah were buried, and there I buried Leah. 32 The f ield and the cave in it were bought from the Hittites. e ” 33 When Jacob had finished giving instruc tions to his sons, he drew his feet up into the bed, breathed his last and was gathered to his people. 50 Joseph threw himself on his father and wept over him and k issed him. 2 Then Jo seph directed the physic ians in his serv ice to embalm his father Israel. So the physicians embalmed him, 3 taking a full fort y days, for that was the time required for em balming. And the Egyptians mourned for him sevent y Ca naan.” Now let me go up and bury my father; then I will ret urn.’ ” 6 Phar aoh said, “Go up and bury your fa ther, as he made you swear to do.” 7 So Joseph went up to bury his fat her. All Pharaoh’s off ic ials accompan ied him — t he dign itaries of his c ourt and all the dign itar ies of Egypt — 8 besides all the members of Joseph’s household and his brothers and those belonging to his father’s household. Only their children and t heir f locks and herds were left in Goshen. 9 Chariots and horsemen f also went up with him. It was a very large com pany. 10 When they reached the threshing f loor of Atad, near the Jordan, they lamented loud ly and bitterly; and there Joseph observed a seven-day per iod of mourning for his fat her. 11 When the Canaanites who lived t here saw the mourning at the threshing f loor of Atad, they said, “The Egypt ians are holding a sol emn ceremony of mourning.” That is why that place near the Jordan is called Abel Miz raim.g 12 So Jacob’s sons did as he had commanded them: 13 They carried him to the land of Ca naan and buried him in the cave in the f ield of Machpelah, near Mamre, which Abraham had b ought a long with the field as a buria l place from Ephron the Hittite. 14 After bury ing his fat her, Joseph ret urned to E gypt, to gether with his brothers and all the others who had gone with him to bury his father. a 23,24 Or archers will attack . . . will shoot . . . will remain . . . will stay b 25 Hebrew Shaddai c 26 Or of my progenitors, / as great as d 26 Or of the one separated from e 32 Or the descendants of Heth f 9 Or charioteers g 11 Abel Mizraim means mourning of the Egyptians. 87 Joseph Reassures His Brothers 15 When Joseph’s brothers saw that their father was dead, they said, “What if Joseph holds a g rudge against us and pays us back for all the w rongs we did to him?” 16 So they sent word to Joseph, saying, “Your father left t hese instruct ions before he died: 17 ‘This is what you are to say to Joseph: I ask you to forgive your brothers the sins and the w rongs they committed in treating you so badly.’ Now please forg ive the sins of the servants of the God of your father.” When their message came to him, Joseph wept. 18 His brothers then came and t hrew them selves down before him. “We are your slaves,” they said. 19 But Joseph said to them, “Don’t be a fraid. Am I in the place of God? 20 You intended to harm me, but God intended it for good to ac complish what is now being done, the saving of many lives. 21 So then, don’t be a fraid. I will prov ide for you and your children.” And he re assured them and spoke kindly to them. The Death of Joseph 22 Jo seph stayed in Egypt, a long with all his father’s family. He lived a hund red and ten years 23 and saw the third generation of Ephraim’s children. Also the children of Ma kir son of Manasseh were placed at birth on Joseph’s knees. carr y my bones up from this place.” 26 So Jo seph died at the age of a hund red and ten. And after they embalmed him, he was placed in a coff in in Egypt. DAY 25 zures and is suffering greatly. He often falls into the fire or into the water. 16 I brought him to your disciples, but they c ould not heal him.” 17 “You unb el iev i ng and per v erse genera tion,” Jesus replied, “how long shall I stay with you? How long shall I put up with you? Bring the boy here to me.” 18 Jesus rebuked the de mon, and it came out of the boy, and he was healed at that moment. 19 Then the disciples came to J esus in private and asked, “Why couldn’t we drive it out?” 20 He re plied, “Because you have so lit tle faith. Truly I tell you, if you have faith as small as a mustard seed, you can say to this mountain, ‘Move from here to there,’ and it will move. Nothing will be imp ossible for you.” [21] b Jesus Predicts His Death a Second Time 22 When they came together in Galilee, he said to them, “The Son of Man is going to be delivered into the h ands of men. 23 They will kill him, and on the third day he will be raised to life.” And the disc iples were f illed with grief. The Temple Tax MATTHEW 17:14 — 18:9 24 Af ter Jesus and his disc iples arrived in Capernaum, the collectors of the two-drach ma temple tax came to Peter and asked, “Doesn’t your teacher pay the temple tax?” 25 “Yes, he does,” he replied. When Peter came into the house, Jesus was the f irst to speak. “What do you think, Si mon?” he asked. “From whom do the k ings of the earth collect duty and taxes — from their own children or from others?” 26 “From others,” Peter ans wered. “Then the children are exempt,” J esus said to him. 27 “But so that we may not c ause of fense, go to the lake and throw out your line. Take the f irst fish you catch; open its mouth and you will find a four-drachma coin. Take it and give it to them for my tax and yours.” Jesus Heals a Demon-Possessed Boy The Greatest in the Kingdom of Heaven 14 When they came to the crowd, a man ap proached Jesus and k nelt before him. 15 “Lord, have merc y on my son,” he said. “He has sei 18 At that time the disc iples came to Jesus and asked, “Who, then, is the greatest in the kingdom of heaven?” a 23 That is, were counted as his b 21 Some manuscripts include here words similar to Mark 9:29. DAY 26 88 2 He called a litt le c hild to him, and placed the c hild among them. 3 And he said: “Truly I tell you, unless you change and become like litt le children, you will never enter the king dom of heaven. 4 Therefore, whoever takes the lowly position of this child is the greatest in the kingdom of heaven. 5 And whoever welcomes one such child in my name welcomes me. 5 who lends money to the poor without interest; who does not accept a bribe against the innocent. Causing to Stumble Genesis 49 – 50; Matthew 17:14 – 18:9; Psalm 15 6 “If any one caus e s one of these lit t le ones — those who believe in me — to stum ble, it would be better for them to have a large millstone hung a round their neck and to be drowned in the d epths of the sea. 7 Woe to the world because of the things that cause people to stumble! Such things must come, but woe to the person through whom they come! 8 If your hand or your foot causes you to stum ble, cut it off and throw it away. It is better for you to enter life m aimed t hrown into the fire of hell.” Whoever does these things will never be shaken. REWIND BE BLAMELESS. Jacob unleashes harsh words in Genesis 49 – 50, making a last blessing of his sons into a diary of their sins and the consequences that will befall them. Jesus speaks blunt truth in Matthew 17 – 18, saying it’s better to be thrown into the sea with a large millstone around your neck than to trip people up. Aim to be the person David describes in Psalm 15, someone who walks with God consistently. That person won’t be shaken. D PSALM 15:1 — 15:5; day26 EXODUS 1:1 — 3:22 The Israelites Oppressed 1 These are the names of the sons of Israel who went to Egypt with Jacob, each with his family: 2 Reuben, Simeon, Levi and Judah; 3 Issac har, Zebu lun and Benjam in; 4 Dan and Naphta l i; Gad and Asher. 5 The descendants of Jacob numbered sevent y a in all; Joseph was already in Egypt. 6 Now Jo seph and all his brothers and all a 5 Masoretic Text (see also Gen. 46:27); Dead Sea Scrolls and Septuagint (see also Acts 7:14 and note at Gen. 46:27) seventy-five 89 that generation died, 7 but the Israel ites were exceed ingly fruit f ul; they mult iplied great ly, increased in numbers and became so numer ous that the land was f illed with them. 8 Then a new king, to whom Joseph meant nothing, came to power in E gypt. 9 “Look,” he said to his people, “the Israelites have become far too numerous for us. 10 Come, we must deal shrewdly with them or they will become even more numerous and, if war b reaks out, will join our enem ies, fight a gainst us and leave the country.” 11 So they put slave masters over them to oppress them with forced labor, and they built Pithom and Rameses as store cities for Phar aoh. 12 But the more they were oppressed, the more they multiplied and spread; so the Egyp tians came to dread the Israelites 13 and worked them ruthlessly. 14 They made their lives bitter with h arsh labor in brick and mortar and with all k inds of work in the f ields; in all their harsh labor the Egyptians worked them ruthlessly. 15 The king of Egypt said to the Hebrew midw ives, whose names were Shiphrah and Puah, 16 “When you are helping the Hebrew women during childbirth on the delivery stool, if you see that the baby is a boy, kill him; but if it is a girl, let her live.” 17 The midw ives, how ever, f eared God and did not do what the king of Egypt had told them to do; they let the boys live. 18 Then the king of Egypt summoned the midw ives and asked them, “Why have you done this? Why have you let the boys live?” 19 The midw ives ans wered Pharaoh, “He brew women are not like Egyptian women; they are vigorous and give b irth before the midw ives arrive.” 20 So God was kind to the midw ives and the people inc reased and became even more nu merous. 21 And because the midw ives feared God, he gave them families of their own. 22 Then Phar aoh gave this order to all his people: “Every Hebrew boy that is born you must t hrow into the Nile, but let every girl live.” The Birth of Moses 2 Now a man of the tribe of Levi married a Lev ite woman, 2 and she became preg nant and gave birth to a son. When she saw DAY 26 that he was a fine child, she hid him for three months. 3 But when she could hide him no longer, she got a papyr us basket a for him and coated it with tar and pitch. Then she placed the c hild in it and put it a mong the reeds a long the bank of the Nile. 4 His sister stood at a distance to see what would happen to him. 5 Then Phar aoh’s daughter went down to the Nile to bathe, and her attendants were walking a long the riverbank. She saw the bas ket among the reeds and sent her female slave to get it. 6 She opened it and saw the baby. He was crying, and she felt sorr y for him. “This is one of the Hebrew babies,” she said. 7 Then his sister asked Pharaoh’s daughter, “Shall I go and get one of the Hebrew women to nurse the baby for you?” 8 “Yes, go,” she ans wered. So the girl went and got the baby’s mother. 9 Pharaoh’s daugh ter said to her, “Take this baby and nurse him for me, and I will pay you.” So the woma n took the baby and nursed him. 10 When the child grew older, she took him to Pharaoh’s daughter and he became her son. She named him Moses, b saying, “I drew him out of the water.” Moses Flees to Midian 11 One day, after Moses had g rown up, he went out to w here his own people were and watched them at their hard labor. He saw an Egyptian beating a Hebrew, one of his own people. 12 Looking this way and that and see ing no one, he k illed the Egyptian and hid him in the sand. 13 The next day he went out and saw two Hebrews fighting. He asked the one in the w rong, “Why are you hitting your fellow Hebrew?” 14 The man said, “Who made you ruler and judge over us? Are you thinking of killing me as you k illed the Egyptian?” Then Moses was a fraid and thought, “What I did must have become known.” 15 When Pharaoh heard of this, he t ried to kill Moses, but Moses fled from Pharaoh and went to live in Midian, where he sat down by a well. 16 Now a priest of Midia n had seven daughters, and they came to draw water and fill the troughs to water their father’s f lock. a 3 The Hebrew can also mean ark, as in Gen. 6:14. b 10 Moses sounds like the Hebrew for draw out. DAY 26 90 17 Some shepherds came a long and d rove them away, but Moses got up and came to their res cue and watered their flock. 18 When the g irls returned to Reuel their father, he a sked them, “Why have you re turned so early today?” 19 They ans wered, “An Egypt ian resc ued us from the shepherds. He even drew water for us and watered the flock.” 20 “And w here is he?” Reu e l asked his daughters. “Why did you leave him? Inv ite him to have something to eat.” 21 Moses agreed to stay with the man, who gave his daughter Zipporah to Moses in mar riage. 22 Zipp orah gave birth to a son, and Moses named him Gershom, a saying, “I have become a foreigner in a foreign land.” 23 Dur i ng that long perio d, the king of Egypt died. The Israel ites g roaned in t heir slavery and c ried out, and their cry for help because of their slavery went up to God. 24 God heard their groaning and he remem bered his covenant with Abraham, with Isaac and with Jacob. 25 So God looked on the Isra elites and was concerned about them. Moses and the Burning Bush 3 Now Moses was tending the flock of Jethro his father-in-law, the p riest of Midia n, and he led the f lock to the far side of the wilderness and came to Horeb, the mountain of God. 2 There the angel of the Lord appeared to him in f lames of fire from within a bush. Moses saw that though the bush was on fire it did not burn up. 3 So Moses t hought, “I will go over and see this s trange, b the God of Abraham, the God of Isaac and the God of Jacob.” At this, Moses hid his face, because he was a fraid to look at God. 7 The Lord said, “I have in deed seen the misery of my people in Egypt. I have heard them crying out because of their slave drivers, and I am concerned a bout ites and Jebusites. 9 And now the cry of the Israelites has reached me, and I have seen the way the Egyptians are oppressing them. 10 So now, go. I am sending you to Pharaoh to b ring b rought the people out of Egypt, you Mo ses, “I am who I am. d This is what you are to say to the Israelites: ‘I am has sent me to you.’ ” 15 God also said to Moses, “Say to the Isra elites, ‘The Lord, e the God of your fathers — the God of Abraham, the God of Isaac and the God of Jacob — has sent me to you.’ “This is my name forever, the name you shall call me from generation to generation. 16 “Go, as semble the elders of Israel and say to them, ‘The Lord, the God of your fathers — the God of Abraham, Isaac and Jacob — app eared to me and said: I have watched over you and have seen what has been done to you in Egypt. 17 And I have promised to bring you up out of your misery in Egypt into the land of the Canaanites, Hittites, Am or ites, Per izzites, Hiv ites and Jebusites — a land flowing with milk and honey.’ a 22 Gershom sounds like the Hebrew for a foreigner there. b 6 Masoretic Text; Samaritan Pentateuch (see Acts 7:32) fathers c 12 The Hebrew is plural. d 14 Or I will be what I will be e 15 The Hebrew for Lord sounds like and may be related to the Hebrew for I am in verse 14. DAY 26 91 18 “The el ders of fer sacr if ices to the Lord our God.’ 19 But I know that the king of E gypt will not let you go unless a mighty hand compels him. 20 So I will stretch out my hand and strike the Egyp tians with all the wonders that I will perform among them. After that, he will let you go. 21 “And I will make the Egypt ians favorably disposed toward this people, so that when you leave you will not go empt y-handed. 22 Every woman is to ask her neighbor and any wom an living in her house for articles of silver and gold and for clothing, which you will put on your sons and daughters. And so you will plunder the Egyptians.” MATTHEW 18:10 — 18:35 The Parable of the Wandering Sheep 10 “See that you do not despise one of t hese litt le ones. For I tell you that t heir angels in heaven always see the face of my Father in heaven. [11] a 12 “What do you t hink? If a man owns a hund red sheep, and one of them wanders away, will he not leave the ninet y-nine on the hills and go to look for the one that wandered off ? 13 And if he f inds it, truly I tell you, he is happier about that one s heep than about the ninet y-nine that did not wander off. 14 In the same way your Father in heaven is not willing that any of these litt le ones should perish. Dealing With Sin in the Church 15 “If your broth er or sister b sins, c go and oint out their fault, just bet ween the two of p you. If they listen to you, you have won them over. 16 But if they will not listen, take one or two others a long, so that ‘every matter may be established by the test imony of two or t hree witnesses.’ d 17 If they s till refuse to listen, tell it to the c hurch; and if they refuse to listen even to the church, treat them as you would a pagan or a tax collector. 18 “Tru ly I tell you, whatever you bind on earth will be e bound in heaven, and whatever you loose on earth will be e loosed in heaven. 19 “Again, truly I tell you that if two of you on e arth a gree about anything they ask for, it will be done for them by my Father in heaven. 20 For where two or t hree gather in my name, there am I with them.” The Parable of the Unmerciful Servant 21 Then Peter came to Jesus and asked, “Lord, how many times shall I forg ive my brother or sister who sins against me? Up to seven times?” 22 Jesus an s wered, “I tell you, not seven times, but sevent y-seven times. f 23 “Therefore, the kingdom of heaven is like a king who wanted to sett le accounts with his ser vants. 24 As he began the sett lement, a man who owed him ten thousand bags of gold g was brought to him. 25 Since he was not able to pay, the master ordered that he and his wife and his children and all that he had be sold to re pay the debt. 26 “At this the servant fell on his k nees be fore him. ‘Be patient with me,’ he begged, ‘and I will pay back everything.’ 27 The ser vant’s master took pity on him, canceled the debt and let him go. 28 “But when that ser v ant went out, he found one of his fellow servants who owed him a hundred silver coins. h He grabbed him and began to choke him. ‘Pay back what you owe me!’ he demanded. 29 “His fellow serv ant fell to his k nees and begged him, ‘Be pat ient with me, and I will pay it back.’ 30 “But he ref used. Instead, he went off and had the man thrown into prison until he could pay the debt. 31 When the other servants saw what had happened, they were outraged and went and told their master everything that had happened. 32 “Then the mas ter c alled the servant in. a 11 Some manuscripts include here the words of Luke 19:10. b 15 The Greek word for brother or sister (adelphos) refers here to a fellow disciple, whether man or woman; also in verses 21 and 35. c 15 Some manuscripts sins against you d 16 Deut. 19:15 e 18 Or will have been f 22 Or seventy times seven g 24 Greek ten thousand talents; a talent was worth about 20 years of a day laborer’s wages. h 28 Greek a hundred denarii; a denarius was the usual daily wage of a day laborer (see 20:2). DAY 27 92 ‘You wicked servant,’ he said, ‘I canceled all that debt of yours because you begged me to. 33 Shouldn’t you have had merc y on your fel low servant just as I had on you?’ 34 In anger his master handed him over to the jailers to be tort ured, until he should pay back all he owed. 35 “This is how my heav enly Father will treat each of you unless you forg ive your brother or sister from your heart.” PSALM 16:1 — 16. REWIND Exodus 1 – 3; Matthew 18:10 – 35; Psalm 16 GOD COMES TO THE RESCUE. Exodus 1 – 3 begins one of the most famous sagas of the ancient world, the Lord freeing his people from slavery in Egypt. Matthew 18 contains one of the Bible’s most tender pictures, a shepherd searching for a lost lamb until he happily brings it home. That same chapter offers you the Lord’s solid help for reconnecting with friends after a fight. And Psalm 16 is a classic song of looking to God for a hand. Pray those words and make them your own. D day27 EXODUS 4:1 — 6:12 Signs for Moses 4 Moses ans wered, g round and it be came a s nake, and he ran from it. 4 Then the Lord said to him, “Reach out your hand and a Title: Probably a literary or musical term b 10 Or holy 93 take it by the tail.” So Moses reached out and took hold of the snake and it t urned in side your c loak.” So Moses put his hand into his c loak, and when he took it out, the skin was leprous a — it had become as white as snow. 7 “Now put it back into your c loak,” he said. So Moses put his hand back into his c loak, and when he took it out, it was restored, like the rest of his flesh. 8 Then the Lord said, “If they do not be lieve you or pay attention to the f irst sign, they may believe the second. 9 But if they do not believe t hese two s igns or listen to you, take some water from the Nile and pour it on the dry g round. The water you take from the river will become blood on the ground.” 10 Mo ses said to the Lord, “Pardon your serv ant, Lord. I have never been eloquent, neither in the past nor since you have spo ken to your servant. I am slow of speech and tongue.” 11 The Lord said to him, “Who gave hu man beings their mouths? Who makes them deaf or mute? Who gives them sight or makes them blind? Is it not I, the Lord? 12 Now go; I will help you speak and will teach you what to say.” 13 But Mo ses said, “Pardon your serv ant, Lord. Please send someone else.” 14 Then the Lord’s ang er burned a gainst Moses and he said, “What about your brother, Aaron the Lev ite? I know he can s peak well. He is already on his way to meet you, and he will be glad to see you. 15 You shall s peak to him and put words in his mouth; I will help both of you speak and will teach you what to do. 16 He will s peak to the people for you, and it will be as if he were your mouth and as if you were God to him. 17 But take this staff in your hand so you can perform the signs with it.” DAY 27 Moses Returns to Egypt 18 Then Moses went back to Jethro his fa ther-in-law and said to him, “Let me ret urn to my own people in Egypt to see if any of them are still alive.” Jethro said, “Go, and I wish you well.” 19 Now the Lord had said to Mo s es in Midian, “Go back to Egypt, for all those who wanted to kill you are dead.” 20 So Moses took his wife and sons, put them on a donkey and started back to E gypt. And he took the staff of God in his hand. 21 The Lord said to Mo ses, “When you ret urn ref used to let him go; so I will kill your firstborn son.’ ” 24 At a lodging p lace on the way, the Lord met Moses b and was about to kill him. 25 But Zipporah took a f lint k nife, cut off her son’s foreskin and touched Moses’ feet with it. c “Surely you are a bridegroom of blood to me,” she said. 26 So the Lord let him a lone. (At that time she said “bridegroom of b lood,” re ferring to circumcision.) 27 The Lord said to Aar on, “Go into the wilderness to meet Moses.” So he met Mo ses at the mountain of God and k issed him. 28 Then Mo s es told Aaron everything the Lord had sent him to say, and also about all the signs he had commanded him to perform. 29 Mos es and Aaron brought tog ether all the elders of the Israel ites, 30 and Aaron told them everything the Lord had said to Moses. He also performed the s igns before the peo ple, 31 and they believed. And when they heard that the Lord was concerned about them and had seen t heir misery, they bowed down and worshiped. Bricks Without Straw 5 Afterw ard Moses and Aaron went to Pharaoh and said, “This is what the Lord, the God of Israel, says: ‘Let my people a 6 The Hebrew word for leprous was used for various diseases affecting the skin. b 24 Hebrew him c 25 The meaning of the Hebrew for this clause is uncertain. DAY 27 94 go, so that they may hold a fest ival t hree-day journey into the wilderness to offer sacrif ices to the Lord our God, or he may s trike us with plagues or with the sword.” 4 But the king of Egypt said, “Mo ses peo ple with straw for making bricks; let them go and gather their own straw. 8 But require them to make the same number of bricks as before; don’t reduce the quota. They are lazy; that is why they are crying out, ‘Let us go and sacri fice wherev er you can find it, but your work will not be reduced at all.’ ” 12 So the people scattered all over E gypt to gather stubble to use for straw. 13 The slave drivers kept pressing them, say ing, “Complete the work required of you for each day, just as when you had s traw.” 14 And Pharaoh’s slave drivers beat the Israelite over seers they had appointed, demanding, “Why haven’t you met your quota of bricks yesterday or today, as before?” 15 Then the Is r aelite overseers went and appealed to Pharaoh: “Why have you treat ed your servants this way? 16 Your servants are given no s traw, yet we are told, ‘Make bricks!’ Your servants are being beaten, but the fault is with your own people.” 17 Phar aoh said, “Lazy, that’s what you are — lazy! That is why you keep saying, ‘Let a 3 Hebrew El-Shaddai b 3 See note at 3:15. us go and sacrif ice to the Lord.’ 18 Now get to work. You will not be given any straw, yet you must produce your full quota of bricks.” 19 The Israelite overseers rea lized ob noxious to Pharaoh and his off icials and have put a sword in their hand to kill us.” God Promises Deliverance 22 Mo ses.” Then the Lord said to Moses, “Now you will see what I will do to Pharaoh: Be cause of my mighty hand he will let them go; because of my mighty hand he will drive them out of his country.” 2 God also said to Moses, “I am the Lord. 3 I app eared to Abraham, to Isaac and to Ja cob as God Almighty, a but by my name the Lord b I did not make myself fully k nown to them. 4 I also established my covenant with them to give them the land of Canaan, where they resided as foreigners. 5 Moreover, I have heard the groaning of the Israelites, whom the Egypt ians are enslaving, and I have remem bered my covenant. 6 “Therefore, say to the Israelites: ‘I am the Lord, and I will bring you out from under the yoke of the Egyptians. I will free you from be ing slaves to them, and I will redeem you with an outstretched arm and with m ighty acts of judgment. 7 I will take you as my own people, and I will be your God. Then you will know that I am the Lord your God, who b rought you out from under the yoke of the Egyptians. 8 And I will bring you to the land I s wore with uplifted hand to give to Abraham, to Isaac and to Jacob. I will give it to you as a posses sion. I am the Lord.’ ” 9 Moses rep orted this to the Israel ites, but 6 DAY 27 95 they did not listen to him because of their dis couragement and harsh labor. 10 Then the Lord said to Moses, 11 “Go, tell Pharaoh king of Egypt to let the Israelites go out of his country.” 12 But Moses said to the Lord, “If the Isra elites will not listen to me, why would Phar aoh listen to me, since I s peak with faltering lips a ?” MATTHEW 19:1 — 19:15 Divorce The Little Children and Jesus 13 Then peop le b rought lit t le child ren to Jesus for him to p lace his h ands on them and pray for them. But the disciples rebuked them. 14 Jesus said, “Let the litt le child ren come to me, and do not hinder them, for the kingdom of heaven belongs to such as these.” 15 When he had placed his hands on them, he went on from there. PSALM 17:1 — 17:5 19 When Jesus had finished saying these t hings, he left Galilee and went into the reg ion of Judea to the other side of the Jordan. 2 Large c rowds followed him, and he healed them there. 3 Some Pharisees came to him to test him. They a sked, “Is it lawf ul for a man to divorce his wife for any and every reason?” 4 “Haven’t you read,” he replied, “that at the beg inning the Creator ‘made them male and female,’ b 5 and said, ‘For this reason a man will leave his fat her and mother and be united to his wife, and the two will become one f lesh’ c ? 6 So they are no lon ger two, but one flesh. Therefore what God has joined together, let no one sepa rate.” 7 “Why then,” they asked, “did Moses com mand that a man give his wife a certificate of divorce and send her away?” 8 Jesus re plied, “Moses perm itted you to divorce your w ives because your hearts were hard. But it was not this way from the begin ning. 9 I tell you that anyone who divorces his wife, except for sex ua l immoral it y, and mar ries another woman commits adultery.” 10 The disc iples said to him, “If this is the situation between a husband and wife, it is better not to marr y.” 11 Jesus re plied, . REWIND Exodus 4:1 – 6:12; Matthew 19:1 – 15; Psalm 17:1 – 5 FIGHT FOR WHAT’S RIGHT. Moses has to toughen up when the Lord tells him in Exodus 4 – 6 how to confront the powerful king of Egypt and demand freedom for the Hebrew slaves. In Matthew 19 Jesus commands his followers to fight to keep husbands and wives united and describes God’s stance on divorce. And David pens a rallying cry for a 12 Hebrew I am uncircumcised of lips; also in verse 30 b 4 Gen. 1:27 c 5 Gen. 2:24 DAY 28 96 justice in Psalm 17, asking God to vindicate him because he’s kept his heart pure. D day28 EXODUS 6:13 — 8:32 Family Record of Moses and Aaron 13 Now the Lord spoke to Moses and Aar on about the Israelites and Pharaoh king of Egypt, and he commanded them to bring the Israelites out of Egypt. 21 The sons of Izhar were Korah, Ne pheg and Zikri. 22 The sons of Uz ziel were Mishael, Elzaphan and Sithri. 23 Aaron mar r ied Elisheba, daughter of Amm inadab and sister of Nahshon, and she bore him Nad ab and Abihu, Eleazar and Ithamar. 24 The sons of Kor ah were Assir, El kanah and Abia saph. T hese were the Korahite clans. 25 Eleaz ar son of Aaron marr ied one of the daughters of Putiel, and she bore him Phinehas. These were the heads of the Lev ite families, clan by clan. 26 It was this Aaron and Moses to whom the Lord said, “Bring the Israelites out of Egypt by their div isions.” 27 They were the ones who spoke to Pharaoh king of Egypt about bring ing the Israelites out of Egypt — this same Moses and Aaron. 14 These were the heads of t heir fami l ies a: Aaron to Speak for Moses The sons of Reuben the firstborn son of Israel were Hanok and Pallu, Hezron and Karmi. T hese were the c lans of Reu ben. 15 The sons of Sim eon were Jemuel, Jam in, Ohad, Jak in, Zohar and Shau l the son of a Canaanite woma n. T hese were the clans of Simeon. 16 These were the n ames of the sons of Levi according to t heir records: Ger shon, Kohath and Merari. Levi lived 137 years. 17 The sons of Gershon, by c lans, were Libni and Shimei. 18 The sons of Kohath were Amr am, Izhar, Hebron and Uzziel. Kohath lived 133 years. 19 The sons of Merar i were Mahl i and Mushi. These were the c lans of Levi accord ing to their records. 20 Am r am mar r ied his fat her’s sister Jochebed, who bore him Aaron and Mo ses. Amram lived 137 years. 28 Now when the Lord spoke to Moses in gypt, 29 he said to him, “I am the Lord. Tell E Pharaoh king of Egypt everything I tell you.” 30 But Mo ses said to the Lord, “Since I speak with faltering lips, why would Pharaoh listen to multi ply my s igns and wonders in Egypt, 4 he will not listen to you. Then I will lay my hand on Egypt and with m ighty acts of judgment I will bring out my div isions, my people the Israel ites. 5 And the Egyptians will know that I am the Lord when I stretch out my hand against Egypt and bring the Israelites out of it.” 6 Mo ses and Aaron did just as the Lord commanded them. 7 Moses was eighty years old and Aaron e ighty-three when they s poke to Pharaoh. 7 a 14 The Hebrew for families here and in verse 25 refers to units larger than clans. DAY 28 97 Aaron’s Staff Becomes a Snake 8 The Lord said to Moses and Aaron, 9 “When Pharaoh says to you, ‘Perform a mir acle,’ then say to Aaron, ‘Take your staff and throw it down before Pharaoh,’ and it will be come a snake.” 10 So Mo ses and Aaron went to Pharaoh and did just as the Lord commanded. Aaron t hrew his staff down in f ront of Pharaoh and his off ic ials, and it became a snake. 11 Phar aoh then summoned wise men and sorcer ers, and the Egyptian mag icians also did the same t hings by t heir sec ret arts: 12 Each one threw down his staff and it bec ame a snake. But Aaron’s s taff swallowed up t heir staffs.13 Yet Pharaoh’s heart became hard and he would not listen to them, just as the Lord had said. The Plague of Blood 14 Then the Lord said to Mo ses, “Phar aoh’s heart is uny ielding; he ref uses brews, has sent me to say to you: Let my peo ple go, so that they may worship me in the wilderness. But until now you have not lis tened. s tink; the Egyptians will not be able to drink its water.’ ” 19 The Lord said to Mo ses, “Tell Aaron, ‘Take your staff and stretch out your hand over the waters of E gypt — over the streams and canals, over the ponds and all the reser voirs — and they will turn to blood.’ Blood will be everywhere in Egypt, even in vessels a of wood and stone.” 20 Mo ses and Aaron did just as the Lord had commanded. He raised his staff in the presence of Pharaoh and his officials and struck the water of the Nile, and all the wa ter was changed into blood. 21 The fish in the Nile died, and the river s melled so bad that the Egyptians c ould not d rink its water. Blood was everywhere in Egypt. 22 But the Egypt ian mag ic ians did the same things by their secret arts, and Pharaoh’s heart bec ame hard; he w ould not listen to Moses and Aaron, just as the Lord had said. 23 Instead, he t urned and went into his palace, and did not take even this to heart. 24 And all the Egyptians dug a long the Nile to get drinking water, because they c ould not drink the water of the river. The Plague of Frogs 25 Seven days passed after the Lord struck the Nile. 1 Then the Lord said to Moses, “Go to Pharaoh and say to him, ‘This is what the Lord says: Let my people go, so that they may worship me. 2 If you refuse to let them go, I will send a p lague of frogs on your whole country. 3 The Nile will teem with frogs. They will come up into your palace and your bedroom and onto your bed, into the houses of your off icials and on your people, and into your ovens and kneading troughs. 4 The f rogs will come up on you and your peo ple and all your off icials.’ ” 5 Then the Lord said to Moses, “Tell Aar on, sec ret arts; they also made frogs come up on the land of Egypt. 8 Phara oh summoned Mos es and Aaron and said, “Pray to the Lord to take the frogs away from me and my people, and I will let your people go to offer sacrif ices to the Lord.” 9 Moses said to Pharaoh, “I leave to you the honor of setting the time for me to pray for you and your offic ials and your people that you and your houses may be rid of the frogs, except for those that remain in the Nile.” 10 “Tomorrow,” Pharaoh said. Moses replied, “It will be as you say, so that you may know t here is no one like the Lord our God. 11 The frogs will leave you and your 8 b a 19 Or even on their idols b In Hebrew texts 8:1-4 is numbered 7:26-29, and 8:5-32 is numbered 8:1-28. DAY 28 98 houses, your off ic ials and your people; they will remain only in the Nile.” 12 Af ter Moses and Aaron left Pharaoh, Moses cried out to the Lord about the frogs he had b roughtar on, ‘Stretch out your staff and strike the dust of the ground,’ and throughout the land of Egypt the dust will become gnats.” 17 They did this, and when Aaron stretched out his hand with the staff and struck the dust of the g round, g nats came on people and animals. All the dust throughout the land of Egypt became gnats. 18 But when the magicians tried to pro duce gnats by their secret arts, they could not. Since the gnats were on people and animals every where, f lies on you and your off icials, on your people and into your houses. The houses of the Egyptians will be full of f lies; even the g round will be cov ered with them. 22 “ ‘But on that day I will deal differently with the land of Goshen, where my people live; no s warms of f lies will be there, so that you will know that I, the Lord, am in this land. 23 I will make a distinction a bet ween my people and your people. This sign will occur tomorrow.’ ” 24 And the Lord did this. Dense s warms of f lies poured into Pharaoh’s palace and into the houses of his off icials; throughout Egypt the land was ruined by the flies. 25 Then Phar aoh summoned Moses and Aaron and said, “Go, sacr if ice to your God here in the land.” 26 But Mo s es said, “That would not be r ight. The sacr if ices we offer the Lord our God would be detestable to the Egyptians. And if we offer sacrif ices that are detestable in their eyes, will they not s tone us? 27 We must take a t hree-day journey into the wilderness to offer sacrif ices to the Lord our God, as he commands us.” 28 Pharaoh said, “I will let you go to offer sacr if ices to the Lord your God in the wil derness, but you must not go very far. Now pray for me.” 29 Moses ans wered, “As soon as I leave you, I will pray to the Lord, and tomorrow the f lies will leave Pharaoh and his off icials and his people. Only let Pharaoh be sure that he does not act deceitfully again by not letting the people go to offer sacrif ices to the Lord.” 30 Then Moses left Pharaoh and prayed to the Lord, 31 and the Lord did what Moses asked. The f lies left Pharaoh and his off icials and his people; not a fly remained. 32 But this time also Pharaoh hardened his heart and would not let the people go. MATTHEW 19:16 — 19:30 The Rich and the Kingdom of God 16 Just then a man came up to Jesus and a sked, “Teacher, what good thing must I do to get eternal life?” 17 “Why do you ask me about what is good?” Jesus replied. “There is only One who is good. If you want to enter life, keep the command ments.” 18 “Which ones?” he inquired. Jesus replied, “ ‘You shall not murder, you shall not commit adultery, you shall not s teal, you shall not give false test imony, 19 hon or your father and mother,’ b and ‘love your neighbor as yourself.’ c ” a 23 Septuagint and Vulgate; Hebrew will put a deliverance b 19 Exodus 20:12-16; Deut. 5:16-20 c 19 Lev. 19:18 DAY 28 99 20 “All t hese I have kept,” the young man said. “What do I still lack?” 21 Jesus an s wered, “If you want to be per fect, go, sell your possessions and give to the poor, and you will have treasure in heaven. Then come, follow me.” 22 When the young man heard this, he went away sad, because he had great wealth. 23 Then J esus said to his disc iples, “Truly I tell you, it is hard for someone who is rich to enter the kingdom of heaven. 24 Again I tell you, it is easier for a camel to go through the eye of a need le than for someone who is rich to enter the kingdom of God.” 25 When the disc iples heard this, they were greatly astonished and asked, “Who then can be saved?” 26 Jesus l ooked at them and said, “With man this is impossible, but with God all things are possible.” 27 Peter ans wered him, “We have left every thing to follow you! What then will there be for us?” 28 Jesus said to them, “Truly I tell you, at the renewa l of all things, when the Son of Man sits on his glorious throne, you who have fol lowed me will also sit on t welve thrones, judg ing the t welve tribes of Israel. 29 And everyone who has left houses or brothers or sisters or father or mother or wife a or children or f ields for my sake will receive a hund red times as much and will inherit eternal life. 30 But many who are f irst will be last, and many who are last will be first.”. REWIND Exodus 6:13 – 8:32; Matthew 19:16 – 30; Proverbs 3:11 – 20 GET REAL RICHES. In Exodus 6 – 8 the Lord sends plagues of blood, frogs, gnats, and flies to force the Egyptians to free his enslaved p eople. Then, in Matthew 19 Jesus helps a rich man understand true wealth, telling him to rid himself of things he’s made more important than God. And Proverbs 3 argues that wisdom is more profitable than silver and yields better returns than gold. You can’t get real riches in a store. You get them from God. D PROVERBS 3:11 — 3:20. a 29 Some manuscripts do not have or wife. b 12 Hebrew; Septuagint loves, / and he chastens everyone he accepts as his child DAY 29 100 day29 EXODUS 9:1 — 10:29 contin ue to hold them back, 3 the hand of the Lord will b ring a terr ible plague on your livestock in the field — on your horses, donkeys and camels and on your cattle, sheep and goats. 4 But the Lord will make a dis t inction be tween the livestock of Israel and that of Egypt, so that no animal belonging to the Is raelites will die.’ ” 5 The Lord set a time and said, “Tomor row the Lord will do this in the land.” 6 And the next day the Lord did it: All the livestock of the Egyptians died, but not one animal belong i ng to the Isr ael ites died. 7 Pharaoh investigated and found that not even one of the animals of the Israelites had died. Yet his heart was uny ielding and he would not let the people go. The Plague of Boils 8 Then the Lord said to Mo ses and Aar on, “Take handf uls fur nace and stood before Pharaoh. Moses tossed it into the air, and festering b oils b roke out on peo ple and animals. 11 The mag . a 16 Or have spared you p lagues against you and against your off icials and your peo ple, so you may know that there is no one like me in all the earth. 15 For by now I could have stretched out my hand and struck you and your people with a p lague that w ould have w iped you off the earth. 16 But I have r aised you up a for this very purpose, that I m ight show you my power and that my name might be proclaimed in all the earth. 17 You still set yourself against my people and will not let them go. 18 Therefore, at this time tomorrow I will send the worst hailstorm that has ever fallen on E gypt, from the day it was founded till now. 19 Give an order now to bring your livestock and everything you have in the f ield to a p lace of shelter, because the hail will fall on every person and animal that has not been brought in and is still out in the f ield, and they will die.’ ” 20 Those of f ic ials of Pharaoh who feared the word of the Lord hurr ied to bring t heir slaves and t heir livestock inside. 21 But t hose who ignored the word of the Lord left t heir slaves and livestock in the field. 22 Then the Lord said to Moses, “Stretch out your hand tow ard the sky so that hail will fall all over E gypt — on people and ani mals and on everything growing in the f ields of Egypt.” 23 When Moses s tretched out his staff toward the sky, the Lord sent thunder and hail, and lightn ing f lashed down to the ground. So the Lord rained hail on the land of Egypt; 24 hail fell and lightn ing flashed back and forth. It was the w orst s torm in all the land of Egypt s ince it had become a na tion. 25 Throughout Egypt hail struck every thing in the f ields — both people and animals; it beat down everything growing in the f ields and stripped every tree. 26 The only place it did not hail was the land of Goshen, where the Israelites were. 27 Then Phar aoh summoned Moses and 101 Aaron. “This time I have sinned,” he said to them. “The Lord is in the right, and I and my people are in the w rong. 28 Pray to the Lord, for we have had enough thunder and hail. I will let you go; you don’t have to stay any longer.” 29 Moses replied, “When I have gone out of the city, I will s pread out my h ands in prayer to the Lord. The thunder will stop and there will be no more hail, so you may know that the earth is the Lord’s. 30 But I know that you and your off icials still do not fear the Lord God.” 31 (The f lax and bar ley were destroyed, since the barley had headed and the flax was in bloom. 32 The wheat and spelt, howe ver, were not destroyed, because they ripen later.) 33 Then Mos es off icials hardened t heir hearts. 35 So Pharaoh’s heart was hard and he would not let the Israelites go, just as the Lord had said through Moses. The Plague of Locusts 10 Then the Lord said to Moses, “Go to Pharaoh, for I have hardened his heart and the hearts of his off icials so that I may perform these signs of mine among them 2 that you may tell your child ren and grand child ren how I dealt harshly with the Egyp tians and how I performed my signs a mong them, and that you may know that I am the Lord.” 3 So Mo ses cov er the face of the g round so that it cannot be seen. They will devour what little you have left after the hail, inc luding every tree that is growing in your f ields. 6 They will fill your houses and t hose of all your off icials and all a 10 Or Be careful, trouble is in store for you! DAY 29 the Egyptians — something neither your par ents nor your ancestors have ever seen from the day they settled in this land till now.’ ” Then Moses t urned and left Pharaoh. 7 Pharaoh’s off ic ials said to him, “How long will this man be a snare to us? Let the people go, so that they may worship the Lord their God. Do you not yet rea lize that Egypt is ru ined?” 8 Then Mo s es and Aaron were b rought back to Pharaoh. “Go, worship the Lord your God,” he said. “But tell me who will be going.” 9 Mo ses answered, “We will go with our young and our old, with our sons and our daughters, and with our flocks and herds, because we are to celebrate a festival to the Lord.” 10 Pharaoh said, “The Lord be with you — if I let you go, a long Mo ses, “Stretch out your hand over E gypt so that locusts s warm over the land and devour everything growing in the f ields, everything left by the hail.” 13 So Mo s es stretched out his staff over Egypt, and the Lord made an east wind blow across the land all that day and all that night. By morning the wind had brought the locusts; 14 they invaded all E gypt and sett led down in every area of the country in g reat numbers. Never before had there been such a plague of locusts, nor will there ever be again. 15 They covered all the ground until it was black. They devoured all that was left after the hail — ev erything growing in the f ields and the f ruit on the trees. Nothing green remained on tree or plant in all the land of Egypt. 16 Pharaoh quick ly sum moned Mos es and Aaron and said, “I have sinned a gainst the Lord your God and against you. 17 Now for give my sin once more and pray to the Lord your God to take this deadly plague away from me.” DAY 29 102 18 Mo ses then left Pharaoh and prayed to the Lord. 19 And the Lord changed the wind to a very s trong west wind, which c aught up the loc usts and carried them into the Red Sea. a Not a locust was left anywhere in Egypt. 20 But the Lord hardened Pharaoh’s heart, and he would not let the Israelites go. The Plague of Darkness 21 Then the Lord said to Moses, “Stretch out your hand toward the sky so that dark ness spreads over Egypt — darkness that can be felt.” 22 So Moses stretched out his hand tow ard the sky, and total darkness covered all Egypt for t hree days. 23 No one could see anyone else or move about for three days. Yet all the Israelites had light in the places where they lived. 24 Then Phar aoh summoned Moses and said, “Go, worship the Lord. Even your women and child ren may go with you; only leave your f locks and herds behind.” 25 But Mo ses said, “You must allow us to have sacrif ices and burnt offerings to present to the Lord our God. 26 Our livestock too must go with us; not a hoof is to be left be hind. We have to use some of them in wor shiping the Lord our God, and until we get there we will not know what we are to use to worship the Lord.” 27 But the Lord hardened Pharaoh’s heart, and he was not willing to let them go. 28 Phar aoh said to Moses, “Get out of my sight! Make sure you do not appear before me again! The day you see my face you will die.” 29 “Just as you say,” Mo ses replied. “I will never appear before you again.” MATTHEW 20:1 — 20:19 The Parable of the Workers in the Vineyard 20 “For the kingdom of heaven is like a landowner who went out early in the morning to hire workers for his vineyard. 2 He agreed to pay them a denarius a gain about noon and about three in the afternoon and did the same thing. 6 About five in the afternoon he went out and found still others standing a round. He asked them, ‘Why have you been standing here all day long doing nothing?’ 7 “ ‘Be cause no one has h ired us,’ they an swered. “He said to them, ‘You also go and work in my vineyard.’ 8 “When eve n ing came, the owner of the vineyard said to his foreman, ‘Call the work ers and pay them their wages, beginning with the last ones hired and going on to the first.’ 9 “The workers who were h ired a bout five in the afternoon came and each received a denarius. 10 So when those came who were hired f irst, they expected to receive more. But each one of them also received a denarius. 11 When they received it, they began to grum ble against the landowner. 12 ‘These who were h ired last worked only one hour,’ they said, ‘and you have made them equal to us who have borne the burden of the work and the heat of the day.’ 13 “But he ans wered one of them, ‘I am not bei ng unfair to you, friend. Didn’t you a gree to work for a denarius? 14 Take your pay and go. I want to give the one who was h ired last the same as I gave you. 15 Don’t I have the right to do what I want with my own mone y? Or are you env io us bec ause I am generous?’ 16 “So the last will be f irst, and the f irst will be last.” Jesus Predicts His Death a Third Time 17 Now J esus was going up to Jer usalem. On the way, he took the Twelve aside and said to them, 18 “We are going up to Jer usalem, and the Son of Man will be delivered over to the chief priests and the teachers of the law. They will condemn him to death 19 and will hand him over to the Gentiles to be mocked and f logged and cruc ified. On the third day he will be raised to life!” a 19 Or the Sea of Reeds b 2 A denarius was the usual daily wage of a day laborer. 103 PSALM 17:6 — 17:12. REWIND Exodus 9 – 10; Matthew 20:1 – 19; Psalm 17:6 – 12 GOD DOES WHAT’S FAIR. The plagues God sends on Egypt in Exodus 9 – 10 look like cruel and unusual punishment, but they’re divine payback for Egypt’s harsh treatment of God’s people. Jesus offers another look at fairness in Matthew 20, telling a story of workers all getting the same wage. And in Psalm 17 David pleads for help against fierce enemies. Even when God acts in ways you don’t understand, you can always count on him to be impartial and just. D DAY 30 day30 EXODUS 11:1 — 12:51 The Plague on the Firstborn 11 Now the Lord had said to Moses, “I will b ring one more plague on Phar aoh and on Egypt. After that, he will let you go from here, and when he does, he will drive you out completely. 2 Tell the people that men and women a like are to ask their neighbors for articles of silver and gold.” 3 (The Lord made the Egyptians favorably disposed toward the people, and Moses himself was highly regard ed in Egypt by Pharaoh’s off icials and by the people.) 4 So Mo ses said, “This is what the Lord says: ‘About midn ight I will go throughout Egypt. 5 Every firstborn son in Egypt will die, from the firstborn son of Pharaoh, who sits on the throne, to the firstborn son of the fe male slave, who is at her hand mill, and all the firstborn of the catt le bet ween Egypt and Israel. 8 All these off ic ials of yours will come to me, bowing down before me and say ing, ‘Go, you and all the people who follow you!’ After that I will leave.” Then Moses, hot with anger, left Pharaoh. 9 The Lord had said to Mo ses, “Pharaoh will refuse to listen to you — so that my won ders may be multiplied in E gypt.” 10 Moses and Aaron performed all these wonders before Pharaoh, but the Lord hardened Pharaoh’s heart, and he would not let the Israelites go out of his country. The Passover and the Festival of Unleavened Bread 12 The Lord said to Moses and Aaron in Egypt, 2 “This m onth is to be for you the f irst m onth, the f irst month of your year. 3 Tell the whole communit y of Israel that DAY 30 104 on the tenth day of this m onth each man is to take a lamb a for his family, one for each household. 4 If any household is too s mall for a whole lamb, they must share one with their nearest neighbor, hav ing taken into account the number of people there are. You are to de termine the amount of lamb needed in accor dance with what each person will eat. 5 The animals you c hoose must be year-old males without defect, and you may take them from the sheep or the goats. 6 Take care of them unt il the fourteenth day of the m onth, when all the members of the commun it y, a long with bitter herbs, and bread made without yeast. 9 Do not eat the meat raw or boiled in water, but roast it over a fire — w ith the head, legs and internal organs. 10 Do not leave any of it till morning; if some is left till morning, you must burn it. 11 This is how you are to eat it: with your cloak t ucked into your belt, your sandals on your feet and your staff in your hand. Eat it in haste; it is the Lord’s Passover. 12 “On that same n ight I will pass t hrough Egypt and strike down every firstb orn of both people and animals, and I will b ring judgment on all the gods of Egypt. I am the Lord. 13 The blood will be a sign for you on the houses w ord i nance. 15 For seven days you are to eat bread made without yeast. On the f irst day remove the yeast from your houses, for whoever eats anything with y east in it from the f irst day through the seventh must be cut off from Is rael. 16 On the f irst day hold a sacred assembly, and another one on the seventh day. Do no work at all on these days, except to prepare food for everyone to eat; that is all you may do. 17 “Celebrate the Fest iv al of Un l eave ned read, because it was on this very day that I B brought your div isions out of Egypt. Cele brate this day as a lasting ord inance for the generations to come. 18 In the f irst month you are to eat b read made without yeast, from the even ing of the fourteenth day until the eve ning of the twent y-f irst day. 19 For seven days no yeast is to be found in your houses. And anyone, whether foreigner or nat ive-born, who eats anything with y east in it must be cut off from the communit y of Israel. 20 Eat noth ing s ides t hese instructions as a lasting or d i n ance for you and your de s cen d ants. 25 When you enter the land that the Lord will give you as he promised, observe this ceremo ny. 26 And when your children ask you, ‘What does this ceremony mean to you?’ 27 then tell them, ‘It is the Passover sacrif ice to the Lord, who p assed over the houses of the Israelites in Egypt and spared our homes when he struck down the Egyp t ians.’ ” Then the peo ple bowed down and worshiped. 28 The Israelites did just what the Lord commanded Moses and Aaron. 29 At mid n ight the Lord struck down all the firstborn in Egypt, from the firstborn of Pharaoh, who sat on the throne, to the first born of the prisoner, who was in the dungeon, and the firstborn of all the livestock as well. 30 Phar aoh and all his offic ials and all the Egyptians got up during the night, and there was loud wailing in Egypt, for there was not a house without someone dead. a 3 The Hebrew word can mean lamb or kid ; also in verse 4. 105 The Exodus 31 Dur i ng the n ight Pharaoh summoned Moses and Aaron and said, “Up! L eave my people, you and the Israelites! Go, worship the Lord as you have requested. 32 Take your f locks and herds, as you have said, and go. And also bless me.” 33 The Egypt ians u rged the people to hur ry and leave the country. “For otherw ise,” they said, “we will all die!” 34 So the people took their d ough before the yeast was added, and carried it on t heir shoulders in kneading troughs w rapped in clothing. 35 The Israelites did as Moses instructed and asked the Egyp tians for artic les of silver and gold and for clothing. 36 The Lord had made the Egyp tians favorably disposed toward the people, and they gave them what they asked for; so they plundered the Egyptians. 37 The Isr ae l ites jour neyed from Rames es to Sukkoth. T here were about six hund red thousand men on foot, besides women and child ren. 38 Many other people went up with them, and also large d roves of livestock, both f locks and herds. 39 With the dough the Is raelites had brought from Egypt, they baked loaves of unleavened bread. The dough was without yeast because they had been driven out of Egypt and did not have time to prepare food for themselves. 40 Now the length of time the Israelite peo ple lived in Egypt a was 430 years. 41 At the end of the 430 y ears, to the very day, all the Lord’s div is ions left E gypt. 42 Bec ause the Lord kept vigil that night to bring them out of Egypt, on this n ight all the Israelites are to keep vigil to honor the Lord for the generations to come. Passover Restrictions 43 The Lord said to Moses and Aaron, “These are the regu lations for the Passover meal: “No foreigner may eat it. 44 Any s lave you have bought may eat it after you have circum cised him, 45 but a temporary resident or a hired worker may not eat it. 46 “It must be eaten inside the house; take none of the meat outside the h ouse. Do not DAY 30 reak any of the bones. 47 The whole commu b nit y of Israel must celebrate it. 48 “A fore igne r res id i ng a mong you who wants to celebrate the Lord’s Passover must have all the males in his household circum cised; then he may take part like one born in the land. No uncircumcised male may eat it. 49 The same law ap plies both to the nativeborn and to the foreigner residing among you.” 50 All the Israelites did just what the Lord had commanded Moses and Aaron. 51 And on that very day the Lord brought the Israelites out of Egypt by their div isions. MATTHEW 20:20 — 20:34 d rink the cup I am going to drink?” “We can,” they answered. 23 Jesus said to them, “You will in deed d rink from my cup, but to sit at my r ight or left is not for me to grant. These places belong to t hose for whom they have been prepared by my Father.” 24 When the ten heard about this, they were indignant with the two brothers. 25 Jesus called them together and said, “You know that the rulers of the Gentiles lord it over them, and their high off icials exercise authorit y over them. 26 Not so with you. Instead, whoe ver wants to become g reat a mong you must be your servant, 27 and whoever wants to be f irst must be your slave — 28 just as the Son of Man did not come to be served, but to serve, and to give his life as a ransom for many.” Two Blind Men Receive Sight 29 As Jesus and his disc iples were leaving Jeric ho, a large c rowd fol lowed him. 30 Two a 40 Masoretic Text; Samaritan Pentateuch and Septuagint Egypt and Canaan DAY 31 106 lind men were sitting by the roadside, and b when they heard that Jesus was going by, they shouted, “Lord, Son of Dav id, have merc y on us!” 31 The c rowd rebuked them and told them to be quiet, but they shouted all the louder, “Lord, Son of Dav id, have merc y on us!” 32 Jesus stopped and called them. “What do you want me to do for you?” he asked. 33 “Lord,” they an s wered, “we want our sight.” 34 Jesus had com p as s ion on them and touched their eyes. Immediately they received their sight and followed him. PSALM 17:13 — 17. Whatever kind of rescue you need, the Lord is your mighty Savior. D day31 EXODUS 13:1 — 14:31 Consecration of the Firstborn 13 The Lord said to Moses, 2 “Con sec rate to me every firstborn male. The f irst offspring of every womb among the Israel ites belongs to me, whether human or animal.” 3 Then Mo ses said to the people, “Com memorate this day, the day you came out of Egypt, out of the land of slavery, because the Lord brought you out of it with a m ighty hand. Eat nothing containing yeast. 4 Today, in the month of Aviv, you are leaving. 5 When the Lord brings you into the land of the Ca naanites, Hittites, Amorites, Hiv ites and Jeb 15 As for me, I will be vindicated and will see usites — the land he s wore to your ancestors your face; to give you, a land f lowing with milk and when I awake, I will be satisfied with honey — you are to observe this ceremony in seeing your likeness. this month: 6 For seven days eat bread made without yeast and on the seventh day hold a fest ival to the Lord. 7 Eat un leavened bread REWIND during t hose seven days; nothing with yeast in it is to be seen a mong you, nor shall any Exodus 11 – 12; Matthew 20:20 – 34; yeast be seen anywhere within your borders. Psalm 17:13 – 15 8 On that day tell your son, ‘I do this because GOD SAVES. of what the Lord did for me when I came out Exodus 11 – 12 records one of the Bible’s most of Egypt.’ 9 This observance will be for you momentous scenes. The exodus — the Lord’s like a sign on your hand and a reminder on rescue of his p eople from slavery in Egypt — your forehead that this law of the Lord is to is a stunning example of how God saves. It’s be on your lips. For the Lord brought you out also a foreshadowing of how J esus will deliver of E gypt with his mighty hand. 10 You must people from sin. In Matthew 20 Jesus rescues keep this ordinance at the appointed time year two men from blindness. And Psalm 17 shows after year. 11 “After the Lord brings you into the land David asking to be saved from wicked p eople.
https://www.scribd.com/document/113805689/Once-A-Day-Bible-for-Teens
CC-MAIN-2017-09
refinedweb
63,187
85.52
"Failure: Trying to Control Java GC" I recently had the brilliant idea that I could control the Java garbage collector, in an attempt to avoid it from interrupting some time-critical code. My plan was to do this by using native code, but it failed... brilliantly. The theory behind this is that GC will not begin until all running threads have entered a safe-point (more on this later). One thing that will delay this is a Java thread that is currently waiting to return from a native call (i.e., via JNI), among other things. I began by creating a simple API with the methods pauseGC() and resumeGC(). The JNI implementation would have matching methods called nPauseGC() and nResumeGC(), where the "n" stands for "native." The theory of operation goes like this: - pauseGC(): 1 - Create a Java thread that calls the JNI code, nPauseGC() 2 - nPauseGC() will: 2.a - Increment a counter 2.b - Block by entering spin loop until the value of the counter goes back to 0 3 - Return to the Java calling thread - resumeGC(): 1 - Call nResumeGC(), which will decrement the value of the counter in step 2.b for pauseGC above To call native code from Java, you first need to define the calls in your Java code like this: public class GCController { // ... // Native calls: native public void nPauseGC(); native public void nResumeGC(); } Next, you need to generate the JNI stub code by using the javah utility found in the bin directory of your JDK installation. For this implementation, I ran the following from the command line: javah -jni -d . -cp ./build/classes gccontroller.GCController This tells javah to generate a JNI header, place it in the current directory, for the class GCController in the package gccontroller. The output was the C++ header file called gccontroller_GCController.h. Next, I implemented the API, with the methods pauseGC() and resumeGC(). The implementation of pauseGC() looks like this: public void pauseGC() { // Create a thread that calls into the native code and blocks // until signaled to return via the resumeGC method if ( paused ) { // already paused return; } new Thread() { public void run() { paused = true; nPauseGC(); // Will block until signaled paused = false; } }.start(); } The implementation of resumeGC() is very simple: public void resumeGC() { // Signal the native code to unblock and return from the pauseGC call nResumeGC(); paused = false; } The native C++ code implementation is as follows, with explanation afterwards: #include <jni.h> #include <thread> #include <unistd.h> #include "gccontroller_GCController.h" int calls = 0; void waitWhile() { while ( calls > 0 ) { usleep(1); } } /* * Class: gccontroller_GCController * Method: nPauseGC * Signature: ()V */ JNIEXPORT void JNICALL Java_gccontroller_GCController_nPauseGC(JNIEnv* penv, jobject obj) { // Start a native thread, and wait on an object printf("nPauseGC call counter=%d \n", ++calls); std::thread r (waitWhile); r.join(); } /* * Class: gccontroller_GCController * Method: nResumeGC * Signature: ()V */ JNIEXPORT void JNICALL Java_gccontroller_GCController_nResumeGC(JNIEnv* env, jobject obj) { // Signal the native thread to resume printf("nResumeGC call counter=%d \n", --calls); } This is very simple really. The method Java_gccontroller_GCController_nPauseGC() — I know, JNI creates long-winded method names — increments a counter and creates a native thread that spins until the counter reaches zero. The call to join() ensures the method will not return until the thread spin-loop terminates via a call to Java_gccontroller_GCController_nResumeGC(). Testing It: Safe Points My intention was to use this implementation to try to halt the garbage collector while my code executed something time-critical to avoid it getting interrupted. To test it, I created a method that called pauseGC(), went into a loop allocating memory until it was basically all used, and then called resumeGC(). When I ran it with the -XX:+PrintGC java command-line parameter, I didn't expect to see garbage collection events between my calls to pause and resume the GC, but I did. Why? Because the Java VM is smarter than I am. My theory was based on the fact that the JVM pauses Java threads when they enter what's called a "safe point", which occurs on method returns, loop iterations, returns from native calls, and so on. Java threads pass through safe points all the time without delay. The JVM only uses these safe points to pause application threads when it needs to do something special, such as invoking the garbage collector or the just-in-time (JIT) compiler. I thought that by delaying a native call from returning back to the calling Java code, I could halt the GC. While it's true that it might delay the start of GC, it doesn't stop GC. The JVM just delays the return of your native call instead. On top of that, it can actually create what appears to your application as an even longer GC pause. This is because while all other application threads are paused at their safe points waiting for your native-calling Java thread to enter its safe point, none of your threads get any work done, and neither does the GC. To see all of this in action for yourself, download the code, and run the test application with the following java command-line parameters: > java -XX:+PrintGCApplicationStoppedTime -XX:+PrintSafepointStatistics -Xms10m -Xmx128m -verbose:gc -XX:+PrintGCTimeStamps -XX:+PrintGC -XX:+PrintGCDetails -Djava.library.path=<path to your native library code> gccontroller.GCController Lesson Learned: Don't Help, Control, or Avoid GC Long ago I wrote here and in other places that you should never try to help the GC, try to avoid GC, or otherwise attempt to control GC because these attempts usually work against you. For instance, people that avoid "creating garbage" by pooling and reusing objects, thus trying to avoid the allocation of memory in the process, usually hurt the collector. This is because "garbage collection" is a misnomer, as the bulk of typical GC work is tracing and moving live objects. Creating large pools of objects creates more work for the GC, which can result in longer pauses. I should have heeded my own advice, but learning from failure is what programming is all about. In the next blog, I'll go over other poor Java coding practices that can delay Java safe point entry, hence making it appear that GC is taking longer than expected, and how JVM implementations attempt to avoid this. Happy Coding! -EJB
http://www.drdobbs.com/jvm/failure-trying-to-control-java-gc/240165505?cid=SBX_ddj_related_mostpopular_default_cpp&itc=SBX_ddj_related_mostpopular_default_cpp
CC-MAIN-2018-26
refinedweb
1,036
57.1
In this article, I will show how to make a Status Strip control that acts as your progress bar as well as keep all existing functionality for your Windows form. My first attempt at doing this was to override the ToolStatusStripLabel control, which was successful, however, it had a few flaws; firstly on loading the form, you had to manually resize the ToolStatusStripLabel to match the size of the Status Strip if you wanted it to cover the whole width of the form. Secondly, if you wanted to have multiple labels (or other controls on your Status Strip), this would limit the size of the progress bar. ToolStatusStripLabel I then looked at overriding the Status Strip control and it turned out to actually be easier than I initially thought. And this allowed me to have a progress bar that covered the whole Status Strip as well as add multiple controls. I also use a progressive colour painting of the progress bar using two colours and a LinearGradientBrush. You would be able to replace this section of code to implement your own style of painting a progress bar, or use some of the other progress bar examples found on CodeProject. LinearGradientBrush The code is pretty simple. You first need to crate a new control class that is based on the standard StatusStrip control. We don’t want to reinvent the wheel and are really only interested in enhancing the existing control, so it’s a good base class. StatusStrip public class ProgressStatusStrip : StatusStrip { } Next, we add some new local variables which are used for the control enhancements. Two variables to store the colours of the progress bar, three variables to store the progress bar state. Note: You will notice I use FLOATs for these, the main reason is that the world is not whole, very rarely do you even need to complete a nice round number of tasks, so your progress incremented would normally be a float (example, 6 tasks, 100/6 = 16.66…67). As standard progress bars use an INT for the Value properties, you lose precision when incrementing your progress (unless you keep a separate variable in your code for the progress and just assign that to the progress bar in each iteration). So by using FLOATs, it takes some of the load of your main code to keep an accurate track of its progress. FLOAT INT Value #region ProgressStatusStrip Definitions private Color _barColor = Color.ForestGreen; private Color _barShade = Color.LightGreen; private float _progressMin = 0.0F; private float _progressMax = 100.0F; private float _progressVal = 0.0F; #endregion Next, we add the public properties that we expose to the user, allowing them to configure the progress bar portion of the class at design and run time. It’s always nice to add descriptions for each property and categorise them so they don’t just get lost with the other control properties. We have five properties, two to control the colours of the progress bar, and three which control the progress bar state (these are a match to the properties you get with a standard progress bar). Note: It’s always best when a user changes a property value to do some data validation to ensure you don’t have any code issues elsewhere, hence the checking inside the Set functions. #region ProgressStatusStrip Properties [Description("The color of the Progress Bar"), Category("Progress Bar"), DefaultValue(typeof(Color), "Color.ForestGreen")] public Color ProgressColor { get { return _barColor; } set { _barColor = value; this.Invalidate(); } } [Description("The shade color of the Progress Bar"), Category("Progress Bar"), DefaultValue(typeof(Color), "Color.LightGreen")] public Color ProgressShade { get { return _barShade; } set { _barShade = value; this.Invalidate(); } } [Description("The lower bound of the range the Progress Bar is working with"), Category("Progress Bar"), DefaultValue(0.0F)] public float Minimum { get { return _progressMin; } set { _progressMin = value; if (_progressMin > _progressMax) _progressMax = _progressMin; if (_progressMin > _progressVal) _progressVal = _progressMin; this.Invalidate(); } } [Description("The upper bound of the range the Progress Bar is working with"), Category("Progress Bar"), DefaultValue(100.0F)] public float Maximum { get { return _progressMax; } set { _progressMax = value; if (_progressMax < _progressMin) _progressMin = _progressMax; if (_progressMax < _progressVal) _progressVal = _progressMax; this.Invalidate(); } } [Description("The current value for the Progress Bar, " + "in the range specified by the minimum and maximum properties"), Category("Progress Bar"), DefaultValue(0.0F)] public float Value { get { return _progressVal; } set { _progressVal = value; if (_progressVal < _progressMin) _progressVal = _progressMin; if (_progressVal > _progressMax) _progressVal = _progressMax; this.Invalidate(); } } #endregion The last stage is to override the OnPaint method; this is where we handle the actual drawing of the progress bar. We calculate the actual progress as a percentage; if we’ve made no progress, there is nothing for us to do except call the base class' OnPaint method which handles the drawing of the standard Status Strip parts. If we have made some progress, we need to draw the progress bar, we get the visible bounds of the Status Strip, and adjust this rectangle's width to match the amount of progress we need to show. Now we create a LinearGradientBrush with the colours selected and then paint the progress area with this brush. OnPaint #region ProgressStatusStrip Methods public ProgressStatusStrip() { } protected override void OnPaint(PaintEventArgs pe) { float progPercent = (float)(_progressVal / (_progressMax - _progressMin)); if (progPercent > 0) { RectangleF progRectangle = pe.Graphics.VisibleClipBounds; progRectangle.Width *= progPercent; LinearGradientBrush progBrush = new LinearGradientBrush( progRectangle, _barColor, _barShade, LinearGradientMode.Horizontal); pe.Graphics.FillRectangle(progBrush, progRectangle); progBrush.Dispose(); } base.OnPaint(pe); } #endregion Once you’ve compiled this code, you will be able to select the new control from the Toolbox to add to any form. Then just adjust the progress bar properties and update the Value property of the ProgressStatusStrip from your tasks. ProgressStatusStrip The most important thing you have to remember is that any controls added to your ProgressStatusStrip must have their BackColor set to Transparent; otherwise they partially block the progress bar from being seen (as shown in the example code demo). BackColor Transparent This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) Dim progRectangle As RectangleF = Nothing ' Make a rect progRectangle.Width = MyBase.Width ' Get control's width and assign that value to the drawing rectangle progRectangle.Height = MyBase.Height ' Get control's height and assign that value to the drawing rectangle progRectangle.Width = progRectangle.Width * progPercent ' Set the width to match the specified percentage Dim progBrush As New LinearGradientBrush(progRectangle, _barColor, _barShade, LinearGradientMode.Horizontal) ' Setup a brush to paint with e.Graphics.FillRectangle(progBrush, progRectangle) ' And paint progBrush.Dispose() General News Suggestion Question Bug Answer Joke Praise Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
http://www.codeproject.com/Articles/225519/Make-your-Status-Strip-the-Progress-Bar-ProgressSt
CC-MAIN-2016-30
refinedweb
1,108
50.97
! If you would like to receive an email when updates are made to this post, please register here RSS Thanks what looks like a great library. Where can I get DRA::SCALEX from? Thanks Error 2 error C2653: 'DRA' : is not a class or namespace name c:\Dev\Projects\Words2\Words2\ScreenLib.cpp 243 Error 3 error C3861: 'SCALEX': identifier not found c:\Dev\Projects\Words2\Words2\ScreenLib.cpp 243 Mark: DRA is part of the SDKs that ship with Visual Studio 2005. Are you compiling with VS2005 or some other IDE? FYI, ScreenLib is not supported on eVC or anything other than VS2005. MelSam: I'm trying to use ScreenLib in a WTL CE project using VS2005. The deafult WTL project doesn't seem to include the DeviceResolutionAware.h which was causing the above problems. Btw, are you familiar with WTL's CDialogResize? If so when would you choose one or the other? Thanks for your help. Where EXACTLY is DRA and SCALEX defined? I'm building with Visual Studio 2005 Pro and I'm getting the same error messages Mark mentioned. I've also grepped the headers and SDKs and not seen DRA defined. Ah, nevermind it's DeviceResolutionAware.h. I've been using ScreenLib, there are a couple of issues. [1] If you use it to position a combo box, you loose the combo box hieght used for the drop down. I've fixed this by adding in some code that checks for combos, and times it by 5. int controlHeight = rcCurrent.bottom - rcCurrent.top; TCHAR buffer[256] ={0}; GetClassName(hwndIDCurrent,buffer,256); if (lstrcmpi(buffer,L"combobox")==0) controlHeight*=5; ::MoveWindow(hwndIDCurrent, nMargin, ptMoveTo.y, nNewCtlWidth, controlHeight, TRUE); [2] If you use it position a listbox with a buddy control, you loose the buddy controls position. I fixed this by reattaching the buddy after screenlib has sized the list box. I couldn't think of how to get screen lib to recognize a listbox has a buddy control and get it to do the work. Otherwise it a useful lib. Very useful lib, one issue with DockControl() I found: The size and positions of the ctrl is incorrect for: dtLeft, dtRight, dtTop, and dtBottom, they are mistakenly using the screen width/height for the width/height of the control, and docking in the top left corner for both dtLeft and dtTop. My fix: case dtLeft: nLeft = 0; nTop = rcCtl.top; nWidth = rcCtl.right - rcCtl.left; nHeight = rcCtl.bottom - rcCtl.top; break; case dtRight: nLeft = (rcClient.right - rcClient.left) - (rcCtl.right - rcCtl.left); case dtTop: nLeft = rcCtl.left; nTop = 0; case dtBottom: nTop = rcClient.bottom - (rcCtl.bottom - rcCtl.top); i need to chege my win mo os ,defat laguage is italy ,ineed to change it to english The ScreenLib has very serious design limitations both in the controls layout management and in the code design. I failed to get the my design properly aligned and sized - ScreenLib provides only top/bottom/left/right management, I cannot describe the exact controls layout. The code is also not always good. What is the reason to have '...' parameters avoiding liker checks, when we can use things like UINT NumberOfControls, UINT *ControlsArray? What if I have array of controls, should I list the whole array elements in a single function call and have a function call with 20 parameters? What's the reason to use ASSERTS for error management instead of regular error checking? What a con :) You use the listbox on your video demo to evenly fill the vacant vertical space as you have no OptimizeHeight(). Why didn't you write one? Never mind i'll do it myself ;) That is no OptimizeHeight() for multiple controls. - GPS Signal Quality - Error Reduction - Avoid problems with localizations - Data Layer: do NOT use XML
http://blogs.msdn.com/windowsmobile/archive/2006/09/11/749467.aspx
crawl-002
refinedweb
631
66.74
The SCL duty cycle looks very weird. #include <Wire.h>#define LED_PIN 13byte x = 0;void setup(){ Wire.begin(); // Start I2C Bus as Master pinMode(LED_PIN, OUTPUT); digitalWrite(LED_PIN, LOW);}void loop(){ Wire.beginTransmission(9); // transmit to device #9 Wire.send(x); // sends x Wire.endTransmission(); // stop transmitting x++; if (x > 5) x=0; delay(450);} #include <Wire.h>#define LED_PIN 13#define LED_1 12#define LED_2 11int x;void setup() { Wire.begin(9); // Start I2C Bus as a Slave (Device Number 9) Wire.onReceive(receiveEvent); // register event pinMode(LED_PIN, OUTPUT); pinMode(LED_1, OUTPUT); pinMode(LED_2, OUTPUT); digitalWrite(LED_PIN, LOW); digitalWrite(LED_1, LOW); digitalWrite(LED_2, LOW); x = 0;}void loop() { //If value received is 0 blink LED 1 if (x == 0) { digitalWrite(LED_1, HIGH); delay(200); digitalWrite(LED_1, LOW); delay(200); } //If value received is 1 blink LED 2 if (x == 1) { digitalWrite(LED_2, HIGH); delay(200); digitalWrite(LED_2, LOW); delay(200); }}void receiveEvent(int howMany) { x = Wire.receive(); // receive byte as an integer} The communication does not work. void loop() { //If value received is 0 blink LED 1 if (x == 0) { digitalWrite(LED_1, HIGH); delay(200); digitalWrite(LED_1, LOW); delay(200); }... // Wire Master Reader// by Nicholas Zambetti <>// Demonstrates use of the Wire library// Reads data from an I2C/TWI slave device// Refer to the "Wire Slave Sender" example for use with this// Created 29 March 2006// This example code is in the public domain.#include <Wire.h>void setup(){} In my case none of the leds blinks. The master should output "hello " to serial monitor, but it does not.
http://forum.arduino.cc/index.php?topic=90738.0
CC-MAIN-2014-42
refinedweb
260
56.15
Devel::Declare - Adding keywords to perl, in perl use Method::Signatures; # or ... use MooseX::Declare; # etc. # Use some new and exciting syntax like: method hello (Str :$who, Int :$age where { $_ > 0 }) { $self->say("Hello ${who}, I am ${age} years old!"); } Devel::Declare can install subroutines called declarators which locally take over Perl's parser, allowing the creation of new syntax. This document describes how to create a simple declarator. We'll demonstrate the usage of Devel::Declare with a motivating example: a new method keyword, which acts like the builtin sub, but automatically unpacks $self and the other arguments. package My::Methods; use Devel::Declare; setup_for You will typically create sub import { my $class = shift; my $caller = caller; Devel::Declare->setup_for( $caller, { method => { const => \&parser } } ); no strict 'refs'; *{$caller.'::method'} = sub (&) {}; } Starting from the end of this import routine, you'll see that we're creating a subroutine called method in the caller's namespace. Yes, that's just a normal subroutine, and it does nothing at all (yet!) Note the prototype (&) which means that the caller would call it like so: method { my ($self, $arg1, $arg2) = @_; ... } However we want to be able to call it like this method foo ($arg1, $arg2) { ... } That's why we call setup_for above, to register the declarator 'method' with a custom parser, as per the next section. It acts on an optype, usually 'const' as above. (Other valid values are 'check' and 'rv2cv'). For a simpler way to install new methods, see also Devel::Declare::MethodInstaller::Simple This subroutine is called at compilation time, and allows you to read the custom syntaxes that we want (in a syntax that may or may not be valid core Perl 5) and munge it so that the result will be parsed by the perl compiler. For this example, we're defining some globals for convenience: our ($Declarator, $Offset); Then we define a parser subroutine to handle our declarator. We'll look at this in a few chunks. sub parser { local ($Declarator, $Offset) = @_; Devel::Declare provides some very low level utility methods to parse character strings. We'll define some useful higher level routines below for convenience, and we can use these to parse the various elements in our new syntax. Notice how our parser subroutine is invoked at compile time, when the perl parser is pointed just before the declarator name. skip_declarator; # step past 'method' my $name = strip_name; # strip out the name 'foo', if present my $proto = strip_proto; # strip out the prototype '($arg1, $arg2)', if present Now we can prepare some code to 'inject' into the new subroutine. For example we might want the method as above to have my ($self, $arg1, $arg2) = @_ injected at the beginning of it. We also do some clever stuff with scopes that we'll look at shortly. my $inject = make_proto_unwrap($proto); if (defined $name) { $inject = scope_injector_call().$inject; } inject_if_block($inject); We've now managed to change method ($arg1, $arg2) { ... } into method { injected_code; ... }. This will compile... but we've lost the name of the method! In a cute (or horrifying, depending on your perspective) trick, we temporarily change the definition of the subroutine method itself, to specialise it with the $name we stripped, so that it assigns the code block to that name. Even though the next time method is compiled, it will be redefined again, perl caches these definitions in its parse tree, so we'll always get the right one! Note that we also handle the case where there was no name, allowing an anonymous method analogous to an anonymous subroutine. if (defined $name) { $name = join('::', Devel::Declare::get_curstash_name(), $name) unless ($name =~ /::/); shadow(sub (&) { no strict 'refs'; *{$name} = shift; }); } else { shadow(sub (&) { shift }); } } For simplicity, we're using global variables like $Offset in these examples. You may prefer to look at Devel::Declare::Context::Simple, which encapsulates the context much more cleanly. skip_declarator This simple parser just moves across a 'token'. The common case is to skip the declarator, i.e. to move to the end of the string 'method' and before the prototype and code block. sub skip_declarator { $Offset += Devel::Declare::toke_move_past_token($Offset); } toke_move_past_token This builtin parser simply moves past a 'token' (matching /[a-zA-Z_]\w*/) It takes an offset into the source document, and skips past the token. It returns the number of characters skipped. strip_name This parser skips any whitespace, then scans the next word (again matching a 'token'). We can then analyse the current line, and manipulate it (using pure Perl). In this case we take the name of the method out, and return it. sub strip_name { skipspace; if (my $len = Devel::Declare::toke_scan_word($Offset, 1)) { my $linestr = Devel::Declare::get_linestr(); my $name = substr($linestr, $Offset, $len); substr($linestr, $Offset, $len) = ''; Devel::Declare::set_linestr($linestr); return $name; } return; } toke_scan_word This builtin parser, given an offset into the source document, matches a 'token' as above but does not skip. It returns the length of the token matched, if any. get_linestr This builtin returns the full text of the current line of the source document. set_linestr This builtin sets the full text of the current line of the source document. Beware that injecting a newline into the middle of the line is likely to fail in surprising ways. Generally, Perl's parser can rely on the `current line' actually being only a single line. Use other kinds of whitespace instead, in the code that you inject. skipspace This parser skips whitsepace. sub skipspace { $Offset += Devel::Declare::toke_skipspace($Offset); } toke_skipspace This builtin parser, given an offset into the source document, skips over any whitespace, and returns the number of characters skipped. strip_proto This is a more complex parser that checks if it's found something that starts with '(' and returns everything till the matching ')'. sub strip_proto { skipspace; my $linestr = Devel::Declare::get_linestr(); if (substr($linestr, $Offset, 1) eq '(') { my $length = Devel::Declare::toke_scan_str($Offset); my $proto = Devel::Declare::get_lex_stuff(); Devel::Declare::clear_lex_stuff(); $linestr = Devel::Declare::get_linestr(); substr($linestr, $Offset, $length) = ''; Devel::Declare::set_linestr($linestr); return $proto; } return; } toke_scan_str This builtin parser uses Perl's own parsing routines to match a "stringlike" expression. Handily, this includes bracketed expressions (just think about things like q(this is a quote)). Also it Does The Right Thing with nested delimiters (like q(this (is (a) quote))). It returns the effective length of the expression matched. Really, what it returns is the difference in position between where the string started, within the buffer, and where it finished. If the string extended across multiple lines then the contents of the buffer may have been completely replaced by the new lines, so this position difference is not the same thing as the actual length of the expression matched. However, because moving backward in the buffer causes problems, the function arranges for the effective length to always be positive, padding the start of the buffer if necessary. Use get_lex_stuff to get the actual matched text, the content of the string. Because of the behaviour around multiline strings, you can't reliably get this from the buffer. In fact, after the function returns, you can't rely on any content of the buffer preceding the end of the string. If the string being scanned is not well formed (has no closing delimiter), toke_scan_str returns undef. In this case you cannot rely on the contents of the buffer. get_lex_stuff This builtin returns what was matched by toke_scan_str. To avoid segfaults, you should call clear_lex_stuff immediately afterwards. Let's look at what we need to do in detail. make_proto_unwrap We may have defined our method in different ways, which will result in a different value for our prototype, as parsed above. For example: method foo { # undefined method foo () { # '' method foo ($arg1) { # '$arg1' We deal with them as follows, and return the appropriate my ($self, ...) = @_; string. sub make_proto_unwrap { my ($proto) = @_; my $inject = 'my ($self'; if (defined $proto) { $inject .= ", $proto" if length($proto); $inject .= ') = @_; '; } else { $inject .= ') = shift;'; } return $inject; } inject_if_block Now we need to inject it after the opening '{' of the method body. We can do this with the building blocks we defined above like skipspace and get_linestr. sub inject_if_block { my $inject = shift; skipspace; my $linestr = Devel::Declare::get_linestr; if (substr($linestr, $Offset, 1) eq '{') { substr($linestr, $Offset+1, 0) = $inject; Devel::Declare::set_linestr($linestr); } } scope_injector_call We want to be able to handle both named and anonymous methods. i.e. method foo () { ... } my $meth = method () { ... }; These will then get rewritten as method { ... } my $meth = method { ... }; where 'method' is a subroutine that takes a code block. Spot the problem? The first one doesn't have a semicolon at the end of it! Unlike 'sub' which is a builtin, this is just a normal statement, so we need to terminate it. Luckily, using B::Hooks::EndOfScope, we can do this! use B::Hooks::EndOfScope; We'll add this to what gets 'injected' at the beginning of the method source. sub scope_injector_call { return ' BEGIN { MethodHandlers::inject_scope }; '; } So at the beginning of every method, we are passing a callback that will get invoked at the end of the method's compilation... i.e. exactly then the closing '}' is compiled. sub inject_scope { on_scope_end { my $linestr = Devel::Declare::get_linestr; my $offset = Devel::Declare::get_linestr_offset; substr($linestr, $offset, 0) = ';'; Devel::Declare::set_linestr($linestr); }; } shadow We override the current definition of 'method' using shadow. sub shadow { my $pack = Devel::Declare::get_curstash_name; Devel::Declare::shadow_sub("${pack}::${Declarator}", $_[0]); } For a named method we invoked like this: shadow(sub (&) { no strict 'refs'; *{$name} = shift; }); So in the case of a method foo { ... }, this call would redefine method to be a subroutine that exports 'sub foo' as the (munged) contents of {...}. The case of an anonymous method is also cute: shadow(sub (&) { shift }); This means that my $meth = method () { ... }; is rewritten with method taking the codeblock, and returning it as is to become the value of $meth. get_curstash_name This returns the package name currently being compiled. shadow_sub Handles the details of redefining the subroutine. One of the best ways to learn Devel::Declare is still to look at modules that use it:. Matt S Trout - <mst@shadowcat.co.uk> - original author Company: Blog: Florian Ragwitz <rafl@debian.org> - maintainer osfameron <osfameron@cpan.org> - first draft of documentation This library is free software under the same terms as perl itself stolen_chunk_of_toke.c based on toke.c from the perl core, which is Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, by Larry Wall and others
http://search.cpan.org/~ether/Devel-Declare-0.006018/lib/Devel/Declare.pm
CC-MAIN-2016-30
refinedweb
1,749
63.39
ListUtility Functions count count all all max max is_equal is_equal concat is_equal sub sub splice splice Art students intentionally reproduce great works of art to develop their own skills and techniques. The purpose isn’t to become an imitator, but to deepen an understanding of important work and styles that came before you. Reverse engineering algorithms and abstractions in computer science is of the same spirit! In this exercise you will implement algorithms to practice computational thinking. You will gain familiarity with the names and behaviors of commonly useful functions. Since the work you do is reproducing tried and true abstractions of the past, in the future you can and should use your language’s preferred functions and idioms instead. In this exercise we will show you how to achieve the same functionality using idiomatic Python in the future. Your function implementations may only make use of the built-in len function, and a List object’s methods append and pop. Specifically off-limits in this exercise are the following. Making use of any of the following will result in no credit for the function you use them in: len- specifically not max, min, slice Listclass’s +or ==operators nor built-in methods beyond append Lists. count Given a List of int values, and an int to search for, count should return the number of times the number you are searching for appears in the List. Here is an example use case of your function once completed: >>> count([1, 0, 1], 1) 2 >>> count([1, 1, 0], 0) 1 >>> count([110, 110, 110], 1) 0 Your implementation should not involve the creation of another List. exercisesdirectory create a directory named ex05 exercises/ex05directory create a file named utils.py __author__variable containing your PID as a str. from typing import List. This will allow you to make use of the Listtype in Python. count countfunction as described above. exercises/ex05directory, create a file named utils_test.py _test.pyindicating to the PyTest framework this file should be searched for test functions. __author__variable containing your PID as a str. countfunction: from exercises.ex05.utils import count def test_count_one() -> None: """Test counting a single instance of the needle in the haystack.""" assert count([1, 1, 0, 1, 20, 100], 0) == 1 test_. Can you think of other examples that are particularly interesting? You probably want to test what happens when the search value isn’t found at all and when it is found more than once. Your goal with testing is to prove the correctness of your implementation. count Your count function is a reproduction of a Python’s List’s built-in count method. Since it’s a method, rather than a function, notice the list it is counting comes before the dot and the search value is the sole argument to the method call. >>> [1, 1, 0].count(1) 2 >>> [1, 1, 0].count(0) 1 all In this exercise you will write a function named all. Given a List of ints and an int, all should return a bool indicating whether or not all the ints in the list are the same as the given int. Example usage: >>> all([1, 2, 3], 1) False >>> all([1, 1, 1], 2) False >>> all([1, 1, 1], 1) True Continue by defining a skeleton function with the following signature: all bool, Trueif all numbers match the indicated number, Falseotherwise or if the list is empty. This algorithm should work for a list of any length. Hint: remember you can return from inside of a loop to short-circuit its behavior and return immediately. You will be responsible for writing tests for this function on your own. Just be sure to remember to add the all function to your import list at the top of your utils_test.py file. Note that the assert keyword expects a boolean expression following it. You do not need to compare the return value of all with True or False. Consider these example assertions: assert all([1, 1, 1], 1) assert not all([1, 2, 3], 1) all There is not a directly equivalent built-in function or method for all in Python, but there are some idiomatic ways to achieve this. They involve the use of some concepts we have not arrived at yet (namely either sets or slice subscripts) so we will leave this as a future exercise. max Next, you will write a function named max. The max function is given a List of ints, max should return the largest in the List. If the List is empty, max should result in a ValueError. We’ll show you how! Examples: >>> max([1, 3, 2]) 3 >>> max([100, 99, 98]) 100 >>> max([]) ValueError: max() arg is an empty List Define a skeleton function with the following signature: max int, the largest number in the List. If the List is empty, raises a ValueError. The body of your skeleton function can begin as such, which demonstrates how to raise an error: def max(input: List[int]) -> int: if len(input) == 0: raise ValueError("max() arg is an empty List") We will discuss errors and error handling in more detail in lecture soon. To give you a working test for the case where the input list is empty, here is one you can use in your utils_test.py file. First, add the following imports to the top of your test file (notice, max was added to the list of functions imported from the utils module – don’t forget to do this!): Then, define this test function: def test_max_of_empty() -> None: """Calling the `max` function with an empty List should raise a Value Error.""" with pytest.raises(ValueError): empty_list: List[int] = [] max(empty_list) You can safely ignore the type-checking error this test will give you. The grader will not take off for it. Rediscover tests to find this test and then it should pass based on the skeleton implementation. How exactly this test works is beyond our current place in the course but the idea is this is a pytest idiom for ensuring that this test passes if a ValueError results in the with block and fails otherwise. Add additional tests to find the max value of the list. Note, you cannot use the built-in max function Python provides in your implementation. max Your max function is a reproduction of a Python’s built-in max function:. Python’s version works on collections of many types more broadly, while yours is specifically typed to work with a list of integers. The following exercises are extensions of those in the previous set. These utility functions continue to emphasize practice algorithmic thinking. In this exercise you will also continue testing the functions you write by writing tests which demonstrate their correctness in a variety of cases. is_equal Given two Lists of int values, return True if every element at every index is equal in both Lists. >>> is_equal([1, 0, 1], [1, 0, 1]) True >>> is_equal([1, 1, 0], [1, 0, 1])) False Your implementation should not assume the lengths of each List are equal. This concept is called deep equality. Two separate List objects on the heap may be distinct objects, such that if you changed one the other would remain the same. However, two distinct objects can be deeply equal to one another if what they are made of is equal to each other in essence. Define a function with the following signature: 1. Name: is_equal 2. Parameters: Two lists of integers. 3. Returns: True if lists are equal, False otherwise. Implement the is_equal function as described above. is_equalfunction. is_equal Your is_equal function is a reproduction of a Python’s List’s built-in == operator when used on two List objects. Compound types, such as List and even custom ones such as those we will write soon, can define their own algorithms for operators such as == through what is called operator overloading. >>> [1, 1, 0] == [1, 1, 0] True >>> [1, 1, 0] == [1, 0, 1] False concat In this exercise you will write a function named concat. Given two Lists of ints, concat should generate a new List which contains all of the elements of the first list followed by all of the elements of the second list. Define your function with the following signature. concat Listcontaining all elements of the first list, followed by all elements of the second list. concat should NOT mutate (modify) either of the arguments passed to it. Add tests to the ex05/utils_test.py file which demonstrate the correctness of your concat function. Be sure to consider edge cases which include empty lists on either side. is_equal Python’s List objects use operator overloading to appropriate the + operator for concatenation, just like with str values: >>> [1, 1, 0] + [1, 1, 0] [1, 1, 0, 1, 1, 0] Note that a new List, with the elements copied from each of the operands, results from the evaluation of concatenating two lists, just like your function implements. sub In this exercise you will write a function named sub. Given a List of ints, a start index, and an end index (not inclusive), sub should generate a List which is a subset of the given list, between the specified start index and the end index - 1. This function should not mutate its input list. Example usage: >>> a_list = [10, 20, 30, 40] >>> sub(a_list, 1, 3) [20, 30] Next, define a skeleton function with the following signature in ex05/utils.py: sub If the start index is negative, start from the beginning of the list. If the end index is greater than the length of the list, end with the end of the list. If the length of the list is 0, start > len of the list or end <= 0, return the empty list. Add tests to assert the correctness of your implementation. sub Python has a special subscription notation called slice notation related to the built-in slice function. Typically, in Python, you would achieve the results of sub with the following, an example of slice indexing: >>> a_list = [10, 20, 30, 40] >>> a_list[1:3] [20, 30] splice In this exercise you will write a function named splice. Given a List of ints, an index, and another List of ints, splice should generate a new List. The new List should contain the Elements of the first list, with the Elements of the second list spliced in at (inserted at) the specified index. For example: >>> splice([1, 1, 1, 1], 2, [0, 0, 0, 0]) [1, 1, 0, 0, 0, 0, 1, 1] Define a skeleton function with the following signature: splice intlist, an intindex, and another intlist, where the index will be used to know where to insert the second list into the first list. Listcontaining elements of the second list “spliced” into those of the first. Neither input list should be mutated in the above. If the index is negative, insert the second list before the first list. If the index is greater than the length of the first list, append the second list directly following the fist list. Hint: You can implement splice in terms of two functions you previously implemented in this exercse rather than from scratch. You are encouraged to make use of the functions implemented earlier. Imagine how you can break down the splice process in terms of other functions written, rather than not making use of any. There are a number of edge cases you will want to carefully test for the splice function. Think about tests for empty lists and different locations of the index in the first list. splice Python developers would likely combine the use of the overloaded + operator and the slice subscription notation to pull off splice in a simple, single line of code. See if you can figure out how, based on the examples of these concepts in earlier idioms above, after you’ve implemented your version of splice. Go ahead and delete any submission zips lingering around in your workspace from the previous exercise. When you are ready to submit for grading, close out any open Python Debug Console terminals using the Trash Can and then open up a clean, new terminal. python -m tools.submission exercises/ex05 This should produce a submission timestamped with the current date/time for uploading on Gradescope. Submissions on Gradescope will open as soon as it is ready and an email will be sent out.
https://20f.comp110.com/students/exercises/ex05-list-utils.html
CC-MAIN-2021-10
refinedweb
2,074
70.23
- Problem with Ext.XTemplate escaping javascript functions - Cannot run the application in IE8 - Adjusting column width based on content of the first row - MultiSelect rendering issue (screenshots provided) - Missing required class: Messages - viewport scrolls up when opening multiple windows if "Y" exceed browser height - ExtJS component similar to Flex ViewStack. - Complex layout calculation - Refresh Tree Store - Unable to change the Line Chart color dynamically - body is null when launching app from local iframe. - passing parameters between window extjs - Hidden Grid with fit layout not rendering rows properly until doLayout - Grid, no paging ... - preparedata event on Ext.view.View ExtJs 4.1 - Cannot get REST store / infinite scrolling / remote sorting to work - form getValues & submit sends data from elements which should have been destroyed - Ext 4.1 Showing Blank Page - Problem with Grid&Toolbar in tabPanel - Lazy Tree building - Problems Rendering Second Form with Identical Configurations, Caching Problem ? - Any news on this problem? - success function - for succes:false response - How to find Combobox object within Store? - Problems with store filter function - Looping through the fields in store to find Max lenght of content for each column - A good reference to learn the basics of ext js - Model association with an extra condition - Paging problem - ExtJS 4.1 Problem with Ext.view.View - Ext.picker.Date with no prev and next buttons - EXT JS 4.1 NEWBIE asking for help - panel cancelling the mousemove event on the toolbar - Panel collapsed at afterrender is not expandable anymore - How to do query in JSON Store - struggling with simple form interaction - FireBug not showing error Ext4.1 only - Problem in field mapping? - extjs grid column text wrap around/auto expand - Ext JS 4.1.1 RC1 Now Available - Showing button in the mask - Cancelling an Ajax request - [Ext 4.1.0] childItems is undefined - [Ext 4.1.x] Proposal for listeners enhancement - Grid with Drag and Drop + Grouping + Summary: Getting duplicated summary Row. - [Ext 4.1.1 RC1] Dynamically adding sprites to draw surface not working - Ajax.request and arrayBuffer - [4.1.1 RC1] Combo field was not selected with form.loadRecord() method - [4.1.1 RC1] Bug slated for fix? EXTJSIV-5807 - [4.1.1 RC1] Bug slated for fix? EXTJSIV-3034 - [4.1.1 RC1] Bug slated for fix? EXTJSIV-5273 - [4.1.1 RC1] Bug slated for fix? EXTJSIV-5102 - How to put a field in column? - Date format syntax - Window hide method sets position to -10000 - [4.1/4.1.1 BUG] Grouped Grid scrolls to first row when value of a field changed - FieldContainer Background - 4.1.1 loadRecords fails at refresh. - Neptune - is it really going to work? - ExtJS 4.1 and new Neptune theme - Hide a message box after a certain time duration - Ext.Base:initConfig problem - Extjs grid transform html - So Many Many problem with new code... - 4.1.1-rc1 bug - Why is my store not saving ??? - When the tree refresh, select the first row of the issue is resolved - Issue with Ext.util.JSON.encode() - Ext.chart.axis.Radial problems - issue with the GeoExt Build while migrating from 3.X to 4.X - Handle 'click' event with action column - Issue with non-running code - 4.1.1 RC1 Grid State Bug - Ext.load.setConfig doesn't seem to work - [4.1] After selecting a tab, window no longer moveable - Problem with component loading with renderer of type "component" - Pre selected value in a combobox - Border layout: Dynamic splitter - Ext JS 4.1.1 RC2 Now Available - 4.1.1 RC 2: Theme / Layout broken - Get TreeNode of TreePanel by mouse coordinates or HTML element - [4.1.1rc2] wrong version? - [Answered] ExtJS 4.1 layout problem - 4.1.1RC2 Gauge Chart Step Labels Broken - Ext.Updater: Extjs3.4 migration to extjs 4.1 - This's bug of Store? - create and destory grid and store.load to fill will get slower at each iteration - Combo box submits display field instead of value field - Store does update on insert - [4.1.1 RC2] Sprite's el getHeight() returns 0 - Ext.layout.ContextItem:init failing in simple test scenario - preserveScrollOnRefresh problem, randomly going to top - 4.1.1 RC2 keyup event locks text field input - Column-Header moves when resizing Column-Width - removeAt for selected row fails if filters are used - EXTJS 4.1 Model idProperty issue - Ext.decode seems to not work properly - Migration problem from 4.0 to 4.1 - Problems with button size in Firefox - infinite grid editing - Editing Grid in TabPanel - Ext JS 4.1.1 (GA) Now Available - Planned Areas for Performance Improvements in 4.next - Ext JS 4.2 Beta is Now Available - Neptune Theme - 4.2.0 grid Loading and Grouping - ReferenceError inAbstractCalendar - Little typo in the desktop example - What are the -ent files? - RTL Support: Is There A Right Way Left? - [4.2.0] Ext.data.Store.getById() error - Any Idea on when Ext: 4.2 GA will be available? - Ext: 4.2.0 Beta: Object [object Object] has no method 'filterBy' - 4.2.0Beta: Ext.data.Model, id management consistency - Bug: Tooltip + RTL + Chrome show the shadow in the wrong place - What about Ext.Draw in 4.2? - After upgrade to 4.2 beta window with tree store didnt open again - Ajax Request posts null params - ExtJS 4.2 beta - Buffered tree plugin - [4.2Beta] columnWidth in fieldsets is needed - [4.2.0beta] Ext.view.Table.refreshSize() error - [4.2.0beta] Ext.grid.plugin.BufferedRenderer && layout - [4.2.0beta] Ext.util.CSS.getRule() error - Ext.layout.container.Table: renderChildren OR getRenderTree - LIveSearchGrid not positioning on result - [4.2] [Feature] Need add property 'defaultMargins' in 'auto' layout - [4.2][Bug] Layout 'table' not valid working in window for 'input' components - grid.Panel + forceFit show/hide problem - Buffered store.findExact() throw Object [object Object] has no method 'findIndexBy' - Row Body Feature No Longer Working With Buffered Stores - Problem when grouping by a column with a ComboBox editor and render - Ext JS 4.2.0 Beta 2 Now Available - Handle Associated Data in Grid, DataView and Form - Error raised when opening a new window in ExtTop - Store and MixedCollection Remove event out of order - this.$namespace not handling deep namespaces in Ext.app.Application - Ext.rtl.util.Floating is included in built all-classes.js - but no other RTL support - Grid emptyText isn't shown after a first refresh - [4.2.0.265] Store "add" event firing contract changed - [4.2.0.265] beginBulkUpdate missing on locking view - RTL scheduler - Infinite Scrolling: PageMap asked for range which it does not have - searchfield - onPageMapClear: Uncaught TypeError: Cannot convert null to object - [4.2.0 RC 1] class loading behavior changed? - explorer dump in portal demo with Extjs4.2 - [4.2.0 beta 2] a very simple/small remoter grid: performance compare to 3.4.x - [Ext:4.2.0 Beta] Weird things happen after clicking headers of grid in IE8 - [Ext: 4.2.0 Beta] Tree panel bug - [Ext: 4.2.0 Beta 2] Any ideas how to improve tree panel performance in IE? - [4.2.0 beta 2] ComponentLoader: should not disableCaching be overridden? - Store.findExact throws error in an Infinite grid in Ext4.2 beta - small request about loading scripts - [4.2.0.265] NodeInterface - Now Available - Ext JS 4.2 RC - Hello Neptune! - New Neptune Theme - Looks Awesome - IE8 big Memory Leak? - how to: debug Layout run failed - [4.2.0 RC] [SenchaCmd 3.1.0] Quicker CSS compiling - [Ext-4.2.0.489] Why use ext.js file must with bootstrap.js,but ext-debug.js does not. - [4.2.0.489] bufferedrenderer grids on same store, store reload breaks row selection - 4.2 RC Scheduler - [4.2.0-489] Upgrading from 4.2.0-265 and Sencha Cmd 3.0.2.288 - 4.2.0 RC1 Buffered Scrolling does not release memory - 4.2.0 RC Record set method take more time than 4.1 - [4.2.0.489] Small changes to the classic theme - Problems building themes - [4.2] Ext.window.Window not use property 'focusOnToFront' - Card Layout with animation - How to get value from json response to store particular node in combo box in extjs4.1 - [4.2 RC] Missing reset CSS rules for Chrome - [4.2 RC] suggested locationfor sass for extended (custom) components - [4.2 RC] custom theme compiles before parent theme - vbox layout for a nested tabpanel fails to render grid - 4.2 Beta Link not working - [4.2 RC] Theme resources don't copy to build/resources - [4.2.0.514] Grid features not attaching events. - [4.2.0-489] Putitng generated Javascript at the bottom of the page. - [BUG] Ext-4.2.0.489 Locking Column Row Editing Example - Extreme Frustration with 4.2, Sencha CMD 3.1.0.130 - [4.2.0.489] Ext.view.TableChunker - Ext.grid.plugin.DivRenderer plugin with Grouping feature - afterSubTpl in ComboBox - Please do something to better explain "Layout run failed" errors. - IE9 not displaying sprites by default - Are there ever going to be useful events on Ext.data.Model ? - Maximum Width For Resizing Locked Column - [4.2.0.489] loadMask:false doesn't affect locked grids during store reload - [4.2.0-489] Unit testing controllers - specifically event handlers - Parsing Nested array value in json response problem i - [cmd 3.1.0.130] Ate my tag - CellEditing plugin with Locked Grid and adding a new record fails - Where can I get link for EXTJS download? - Ext.String.trim has bug? - Sencha app build for sass folder does not carry over paths specified in app.js - Customer Support 4.2.0 download link - Sencha Cmd for ExtJS 4.2.0 release? - quick tip stuck after mousing off of tree panel - Is there a jsb file available in ext 4.2 - Extjs blank theme? - Bug with Ext.ux.dataView.DragSelector - missing images? - Outdated documentation - App.scss path problem in ExtJS 4.2 - Section 508 Compliance / ARIA - Sencha CMD - Theme Creation/Editing - whether extjs4.1 application will support in iPad Browser and Android Tablet Browser - Icons - Difference between store created with Ext.Create or using this.getStoreNameStore() ? - Sencha CMD - compiling app - Tab styling variance from 4.1.1 to 4.2 - checkboxgroup lost the name property? - Missing all.scss files? - [BUG] htmleditor search for the font selector although enableFont is set to false - Usage of new ExtJS 4.2 bufferedrenderer Grid - Failed to upgrade to extjs 4.2.0 from 4.1.1a - EXTJS 4.2 gpl link broken - Window not rendering properly in viewport in exts 4.2 - Window layout difference between 4.1.1 and 4.2 - [EXTJSIV-9216 OPEN] Buffered Renderer and FiltersFeature UX - Testing Jsonp - Error in onMouseEnter on Sprites - Worked in 4.0.7, not in 4.2 - Overwriting panel body prevents adding items - Locking Grid in IE is shifting to the left on cell click. - Difference between sencha provided and generated themes - Is it possible to have multiple columns in grid group - Issues with data displaying on grid after migrating from 4.1 to 4.2 - Migration Guide 4.1 -> 4.2 - Invalid Forum specified. If you followed a valid link, please notify the administrato - Is Ext 4.2 released? - Problem with panel witdh on Fit layout - loadData gives error - [4.2] Missing method removeRange in Ext.util.LruCache class - qtips in IE10 - Button text size in Neptune - [4.2] IE 10 grouped column headers - MessageBox doesn't size properly in 4.2 - [BUG] Ext 4.2.0 datefield does not respect format when jsonSubmit set to true - What is difference between extjs and sencha - 4.2 grid with cell checkcolumn no work - Why the white spaces between items in a accordion panel are different? - Clarification on SASS and Theming in 4.2.0 - can anybody give idea best way to develop hybrid app using extjs and sencha - Grid Editor not working - ComboBox forces Store with remote filtering to load on render - Performance hit when loading nodes in a tree - Error on submitting a form - Is Sencha Cmd necessary to create a custom theme in Ext 4.2? - Creating Drag and Drop from a tree view - 4.2 Grouped grid sends empty records to convert function in model
https://www.sencha.com/forum/archive/index.php/f-93-p-3.html
CC-MAIN-2017-30
refinedweb
2,026
61.22
Carsten Ziegeler said the following on 24/5/07 15:57: > hepabolu schrieb: >>>> So you can't rely that you get the namespace attributes in the dom >>>> builder. >> >> I think this is where things go wrong. >> >> Note that both binding file and source are generated with a pipeline >> and pipelineUtil.toDOM. >> >> I've done some debugging into pipelineUtil.toDOM and this is what I >> found: >> - binding file has all the namespaces in pipeline. This is confirmed >> because I can save the output of the pipeline and see the namespaces >> in the root element: >> >> <fb:context xmlns:> xmlns:> xmlns:> xmlns: >> >> - After returning from SourceUtil.toDOM (which uses the default >> DOMBuilder()), the only namespace left is >> fb="". >> Attributes of this node only holds 'path=/oe:version'. >> >> - This is true for the source=pipeline situation as well: only the >> oe="openEHR/v1/Version" is left. >> >> - The source=file situation has all namespaces in the attributes. >> >> I can understand that in the situation of source=pipeline there cannot >> be any matching because the oe namespace is not known in the binding >> file. However, this is also true for the situation of source=file and >> there matching happens on various fb:context until it fails on a >> difference in datatype. >> >> What I also don't understand is the fact that putting the >> source=pipeline through the savedocument function as I did this >> morning, gives me all the namespaces back. >> >> I'm not sure if this helps in the discussion and I have no clue on how >> to solve this. >> >> Anyone? >> > I must say that this is all a little bit strange to me as well. Now, are > you using the prefix oe somewhere in the xml? The prefix fb is definitly > used, so it might be that there is some optimization filtering unused > prefixes? Just a wild guess. Yes. Source is: <oe:version xmlns:oe="openEHR/v1/Version" xmlns:xsi="" xsi: So in fact I want the first line of the binding file to bind to /oe:version I don't think there are unused prefixes in both binding and source. Bye, Helma
http://mail-archives.apache.org/mod_mbox/cocoon-dev/200705.mbox/%3C46559B9E.5000209@gmail.com%3E
CC-MAIN-2016-22
refinedweb
348
71.44
Step 4: Run code in the debugger Previous step: Use the Interactive REPL window In addition to managing projects, providing a rich editing experience, and the Interactive window, Visual Studio provides full-featured debugging for Python code. In the debugger, you can run your code step by step, including every iteration of a loop. You can also pause the program whenever certain conditions are true. At any point when the program is paused in the debugger, you can examine the entire program state and change the value of variables. Such actions are essential for tracking down program bugs, and also provide very helpful aids for carefully following the exact program flow. Replace the code in the PythonApplication1.py file with the following. This variation of the code expands make_dot_stringso that you can examine its discrete steps in the debugger. It also places the forloop into a mainfunction and runs it explicitly by calling that function: from math import cos, radians # Create a string with spaces proportional to a cosine of x in degrees def make_dot_string(x): rad = radians(x) # cos works with radians numspaces = int(20 * cos(radians(x)) + 20) # scale to 0-40 spaces st = ' ' * numspaces + 'o' # place 'o' after the spaces return st def main(): for i in range(0, 1800, 12): s = make_dot_string(i) print(s) main() Check that the code works properly by pressing F5 or selecting the Debug > Start Debugging menu command. This command runs the code in the debugger, but because you haven't done anything to pause the program while it's running, it just prints a wave pattern for a few iterations. Press any key to close the output window. Tip To close the output window automatically when the program completes, select the Tools > Options menu command, expand the Python node, select Debugging, and then clear the option Wait for input when process exits normally: Set a breakpoint on the forstatement by clicking once in the gray margin by that line, or by placing the caret in that line and using the Debug > Toggle Breakpoint command (F9). A red dot appears in the gray margin to indicate the breakpoint (as noted by the arrow below): Start the debugger again (F5) and see that running the code stops on the line with that breakpoint. Here you can inspect the call stack and examine variables. Variables that are in-scope appear in the Autos window when they're defined; you can also switch to the Locals view at the bottom of that window to show all variables that Visual Studio finds in the current scope (including functions), even before they're defined: Observe the debugging toolbar (shown below) along the top of the Visual Studio window. This toolbar provides quick access to the most common debugging commands (which can also be found on the Debug menu): The buttons from left to right as follows: - Continue (F5) runs the program until the next breakpoint or until program completion. - Break All (Ctrl+Alt+Break) pauses a long-running program. - Stop Debugging (Shift+F5) stops the program wherever it is, and exits the debugger. - Restart (Ctrl+Shift+F5) stops the program wherever it is, and restarts it from the beginning in the debugger. - Show Next Statement (Alt+Num *) switches to the next line of code to run. This is most helpful when you navigate around within your code during a debugging session and want to quickly return to the point where the debugger is paused. - Step Into (F11) runs the next line of code, entering into called functions. - Step Over (F10) runs the next line of code without entering into called functions. - Step Out (Shift+F11) runs the remainder of the current function and pauses in the calling code. Step over the forstatement using Step Over. Stepping means that the debugger runs the current line of code, including any function calls, and then immediately pauses again. Notice how the variable iis now defined in the Locals and Autos windows. Step over the next line of code, which calls make_dot_stringand pauses. Step Over here specifically means that the debugger runs the whole of make_dot_stringand pauses when it returns. The debugger does not stop inside that function unless a separate breakpoint exists there. Continue stepping over the code a few more times and observe how the values in the Locals or Autos window change. In the Locals or Autos window, double-click in the Value column for either the ior svariables to edit the value. Press Enter or click outside that value to apply any changes. Continue stepping through the code using Step Into. Step Into means that the debugger enters inside any function call for which it has debugging information, such as make_dot_string. Once inside make_dot_stringyou can examine its local variables and step through its code specifically. Continue stepping with Step Into and notice that when you reach the end of the make_dot_string, the next step returns to the forloop with the new return value in the svariable. As you step again to the Continue using Step Into until you're again partway into make_dot_string. Then use Step Out and notice that you return to the forloop. With Step Out, the debugger runs the remainder of the function and then automatically pauses in the calling code. This is very helpful when you've stepped through some portion of a lengthy function that you wish to debug, but don't need to step through the rest and don't want to set an explicit breakpoint in the calling code. To continue running the program until the next breakpoint is reached, use Continue (F5). Because you have a breakpoint in the forloop, you break on the next iteration. Stepping through hundreds of iterations of a loop can be tedious, so Visual Studio lets you add a condition to a breakpoint. The debugger then pauses the program at the breakpoint only when the condition is met. For example, you can use a condition with the breakpoint on the forstatement so that it pauses only when the value of iexceeds 1600. To set this condition, right-click the red breakpoint dot and select Conditions (Alt+F9 > C). In the Breakpoint Settings popup that appears, enter i > 1600as the expression and select Close. Press F5 to continue and observe that the program runs many iterations before the next break. To run the program to completion, disable the breakpoint by right-clicking and selecting Disable breakpoint (Ctrl+F9). Then select Continue (or press F5) to run the program. When the program ends, Visual Studio stops its debugging session and returns to its editing mode. Note that you can also delete the breakpoint by clicking its dot, but this also deletes any condition you've set. Tip In some situations, such as a failure to launch the Python interpreter itself, the output window may appear only briefly and then close automatically without giving you a chance to see any errors messages. If this happens, right-click the project in Solution Explorer, select Properties, select the Debug tab, then add -i to the Interpreter Arguments field. This argument causes the interpreter to go into interactive mode after a program completes, thereby keeping the window open until you enter Ctrl+Z > Enter to exit. Next step Go deeper - Debugging - Debugging in Visual Studio provides full documentation of Visual Studio's debugging features. Feedback Send feedback about:
https://docs.microsoft.com/en-us/visualstudio/python/tutorial-working-with-python-in-visual-studio-step-04-debugging?view=vs-2019
CC-MAIN-2019-26
refinedweb
1,229
59.03
Closed Bug 1438308 Opened 3 years ago Closed 3 years ago Pressing Alt Gr+R on Windows enters Reader View (Ctrl+Alt+R) Categories (Toolkit :: Reader Mode, defect) Tracking () mozilla60 People (Reporter: henrik.pauli, Assigned: Gijs) References Details (Keywords: user-doc-needed) Attachments (1 file) User Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:58.0) Gecko/20100101 Firefox/58.0 Build ID: 20180206200532 Steps to reproduce: I was typing on my international keyboard (a layout that contains an AltGr key), and accidentally hit R instead of E which would have produced the character I wanted (é in my case, but it does not matter). This is due to Windows having a weird legacy treatment of the AltGr key, which makes it emit not a Right Alt, nor a specific, separate AltGr key down event, but a Left Ctrl and Right Alt keydown event. Pressing AltGr+R on X11 for example does not result in a misinterpretation of the keypress as a control shortcut. Actual results: Firefox entered (and later when AltGr+R was pressed again, exited) Reader View. Sadly, this also resulted in losing whatever I had in the forms of the website. Expected results: Firefox and websites should not ever trigger Ctrl+Alt shortcuts when AltGr is pressed. Any character associated with the AltGr+key combination — or none if there is no character on third level — should be entered (into the text entry or wherever). Additionally, Firefox should not lose data from (accidental) triggering of a view mode change. Component: Untriaged → Keyboard Navigation If it seems similar to #900750, it might be because it's the same issue somewhere deep in Firefox — but this is not about what the rendered websites (and DOM and JS and whatever) should get exposed to, but more about a mishandling outside of the web view, in the browser chrome. So it may or may not be related. The shortcut should be changed. Ctrl+Alt+<character> shortcuts should never be used on Windows. Component: Keyboard Navigation → Reader Mode Product: Firefox → Toolkit (In reply to Neil Deakin from comment #2) > The shortcut should be changed. Ctrl+Alt+<character> shortcuts should never > be used on Windows. Are there alternative shortcuts that are available? Ctrl-R and Ctrl-Shift-R are both taken... Flags: needinfo?(enndeakin) I don't think I'm the right person to have an answer to that. You shouldn't use Ctrl+Alt on Windows because that can map to a printable character. Flags: needinfo?(enndeakin) The F9 shortcut seems to have been the other main suggestion in bug 1144749, and that doesn't work well on mac (which also doesn't have Windows's AltGr problem) so keeping the old shortcut there. Assignee: nobody → gijskruitbosch+bugs Status: UNCONFIRMED → ASSIGNED Ever confirmed: true Comment on attachment 8952396 [details] Bug 1438308 - switch reader mode shortcut to F9 on Windows, Attachment #8952396 - Flags: review?(markh) → review+ Comment on attachment 8952396 [details] Bug 1438308 - switch reader mode shortcut to F9 on Windows, Apologies for not understanding you hadn't tested this - I tested it and as you suspected, it doesn't work. Using keycode instead of key works though. It might also make sense to change the string name from `.win.key` to `win.keycode`. I'll leave r+ as I don't think it's necessary to see it again with those tweaks :) ::: browser/base/content/browser-sets.inc:289 (Diff revision 1) > <key keycode="VK_F11" command="View:FullScreen"/> > #endif > +#ifndef XP_WIN > <key id="key_toggleReaderMode" key="&toggleReaderMode.key;" command="View:ReaderView" modifiers="accel,alt" disabled="true"/> > +#else > + <key id="key_toggleReaderMode" key="&toggleReaderMode.win.key;" command="View:ReaderView" disabled="true"/> This must use keycode (In reply to Mark Hammond [:markh] from comment #8) > Comment on attachment 8952396 [details] > Bug 1438308 - switch reader mode shortcut to F9 on Windows, > > > > Apologies for not understanding you hadn't tested this - I tested it and as > you suspected, it doesn't work. Using keycode instead of key works though. No worries, I really ought to have tested the patch. Thanks for the quick reviews! Pushed by gijskruitbosch@gmail.com: switch reader mode shortcut to F9 on Windows, r=markh Status: ASSIGNED → RESOLVED Closed: 3 years ago status-firefox60: --- → fixed Resolution: --- → FIXED Target Milestone: --- → mozilla60 (In reply to :Gijs from comment #12) > Added to Firefox Nightly 60 release notes. (In reply to Pascal Chevrel:pascalc from comment #14) > Added to Firefox Nightly 60 release notes. The support article should also be updated. (In reply to Gingerbread Man from comment #15) > (In reply to Pascal Chevrel:pascalc from comment #14) > > Added to Firefox Nightly 60 release notes. > > The support article should also be updated. >- > quickly Submitted a revision to this. I already needinfo'd Joni to approve another one I made for the quit shortcut for an older change. comment 12 relnote-firefox: --- → ?
https://bugzilla.mozilla.org/show_bug.cgi?id=1438308
CC-MAIN-2020-40
refinedweb
805
55.03
#include <algorithm> #include <assert.h> #include <iostream> #include <math.h> #include <Eigen/Core> #include <Eigen/Geometry> Go to the source code of this file. Assert that the given transform is an isometry. Definition at line 109 of file check_isometry.h. This file provides functions and macros that can be used to verify that an Eigen::Isometry3d is really an isometry. Eigen itself doesn't do the checks because they're expensive. If the isometry object is constructed in a wrong way (e.g. from an AngleAxisd with non-unit axis), it can represent a non-isometry. But some methods in the Isometry3d class perform isometry-specific operations which return wrong results when called on a non-isometry. E.g. for isometries, .linear() and .rotation() should be the same, but for non-isometries, the result of .linear() contains also the scaling factor, whether .rotation() is only the rotation part. These checks are primarily meant to be performed only in debug mode (via the ASSERT_ISOMETRY macro), but you can call checkIsometry() even in release mode. This check should be mainly performed on transforms input by the user. The default precision to which the transform has to correspond to an isometry. Definition at line 60 of file check_isometry.h. Check whether the given transform is really (mathematically) an isometry. Definition at line 70 of file check_isometry.h.
http://docs.ros.org/en/noetic/api/geometric_shapes/html/check__isometry_8h.html
CC-MAIN-2021-43
refinedweb
224
51.95
0 comments Amazon0 comments A0 comments1 comments Less3 comments Microsoft So everything's going mobile. We'll all hook into the cloud. Now it's touch-happy Windows 8 and an emphasis on Windows Store apps built with JavaScript and HTML5. It's inevitable, and I get that. But what's a hobbyist programmer like myself going to do, after spending a lot of time trying to learn the Microsoft .NET Framework and finally getting to the point where I can create interesting desktop applications? Start over. I don't like JavaScript. Never have. I don't get it--all those functions within functions and spaghetti code I can't figure out. C#/.NET seems a lot more organized and understandable. But that's just me. More important, what about you, the professional developer making a living in the Microsoft ecosystem? Well, the company is trying to smooth the transition. Take, for example, the new Windows Azure Mobile Services (WAMS) preview, which I've been playing around with. To recap, this is a Microsoft effort to simplify back-end development for your mobile cloud apps, targeting developers who want to focus on the client side of things and not worry about the nitty-gritty details of interacting with a database and such. I found a couple things interesting about this initiative. First of all, it's yet another indication of Microsoft's attempt to be part of the transition from a world of PC desktops to mobile devices hooked into the cloud, obviously, along with becoming a good open source citizen. Second, it's yet another indication of Microsoft's goal to simplify programming, making it more accessible to the not-professionally-trained masses. It kind of feeds into the whole "can anyone be a programmer" debate, which recently garnered more than 760 comments on Slashdot in response to an ArsTechnica.com article. I decided to see if WAMS delivers, because, of course, if I can do it, anyone can do it. Well, I can do it; it's that easy. I started with some beginner tutorials available at the WAMS developer site, complete with a link to a free Windows Azure trial account to get you started. You also have to enable the WAMS preview in the account management portal. And you need to download the WAMS SDK, which, though clearly targeted at the mobile arena, could only build Windows 8 apps at the time I started playing around with it--though Windows Phone, Android and iOS support was promised soon. (Update: Microsoft partner Xamarin announced an open source SDK for MonoTouch for iOS and Mono for Android, available on GitHub, which also hosts the open source WAMS SDKs and samples.) The first tutorial, "Get started with Mobile Services," is a simple "TodoList" app, letting you view, add and check-off/delete items from a list of things to be done. First you have to create a service. You need to fill in specific things such as the URL of your Windows Store app, database to use and region (though, curiously, the "Northwest US" region illustrated in the tutorial isn't available yet--you can only use "East US"). In this tutorial you create a new database server and table, instead of use an existing one. After setting up the service, you create a new app to use it. The management portal includes a quickstart to do this. The quickstart can also guide you through the process of connecting an existing app, which basically just requires adding some references and a few lines of code to connect to your database table, which you make via the portal. There are also tutorials available for getting started with data, validating and modifying data using server-side scripts, adding paging to queries, adding authentication, adding push notifications and more. These include downloadable projects for C# or JavaScript apps. (Yes, C# and .NET aren't going away; I exaggerated a little bit earlier, but you know what I mean.) These beginner tutorials all involved setting up a super-simple new database or using a built-in data source such as a collection for your data. I usually check out a bunch of different tutorials when investigating a new technology, mixing and matching and trying different things until I usually get it to work right through sheer brute force, trial-and-error. I wondered about the use of an existing database. I couldn't find nearly as much guidance for that scenario, so I thought I'd explore it further. I turned to the trusty AdventureWorks example database. WAMS uses ordinary Windows Azure SQL Databases, so I used the SQL Database Migration Wizard to generate a script to build the database in the cloud. You just need the info to connect to the server you set up via WAMS. Once the wizard is done and your database is visible from the WAMS portal--you can't use it. You have to do a few different things to get it working. That process is described by Microsoft's Paul Batum in response to a Sept. 6 reader query in the WAMS forum. Basically you have to connect to the database management portal, reached from the regular Windows Azure management portal, to alter the schema so WAMS can use it. I wanted to use the AdventureWorks HumanResources.Employee table, and the WAMS service I set up was called "ram," so I ran this "query" from the database management portal: That changed the schema of just that one table, of course, as you can see in Figure 1. That would be quite tedious to do for every table, but there's probably some batch command or something that can change them all. I also had to change the existing primary key "EmployeeID" column to a lowercase "id," which WAMS requires for everything to work correctly, such as the browse database functionality (I'm not sure if anything else is broken). But WAMS still didn't know about the database, so I had to use the portal to "create" a table named "Employee," exactly as demonstrated in the tutorials where you set up a new database from the portal. After a few seconds, WAMS recognized the database and populated the new table with records. If your primary key column is "id," you can browse the database, as shown in Figure 2. Having an existing database at the ready, I used the portal "Get Started" page to grab the information I needed to connect to WAMS from an existing app (it also shows you how to create a brand-new app, which involves creating a database table and downloading a prebuilt Visual Studio solution all set up to use it). This was fairly straightforward. Figure 3 shows the steps and code for C# apps, while Figure 4 shows the process for JavaScript apps. Heeding the winds of change, I took the JavaScript route. With the MobileServiceClient variable "client" obtained from the WAMS portal as shown in Figure 4, I simply had to grab the table, read it and bind the results, assigned to the dataSource property of a WinJS.Binding.List, to the ListView's itemDataSource: The read function uses one of four server-side scripts (JavaScript) that WAMS provides for insert, read, update and delete operations (because there's no System.Data namespace to use). You can customize the scripts as you wish. For a contrived, impractical example, to query the AdventureWorks Employee table and return only three "Production Technician – WC10" employees who are female and single, I changed the read script to this: Note that a mssql object is also available for situations where a more complex SQL query might be needed. With that object, the read script above could be written as: Normally, of course, the server-side scripts would be used for validation, custom authorization and so on. Such query customization as in my contrived example would be handled from the client. For example, the functionality of my contrived example would be duplicated in the MobileServices.MobileServiceClient's getTable function from the client, like this: WAMS uses a REST API, so the above function call emits the following GET request header to the server, as reported by Fiddler, the free Web debugging tool: That returns the JSON objects shown in Figure 5, as reported (and decrypted) by Fiddler. The resulting ListView display when I hit F5 in Visual Studio is shown in Figure 6. I didn't explore the tutorials much beyond the basics because I was primarily interested in the new aspect of connecting to an existing database, and this proved the concept. But for mobile apps, obviously, push notifications are important and, as mentioned, some tutorials are available through the portal to cover that functionality and user authentication. The push tutorial, however, uses C#, not JavaScript. One reader commented on the push notification tutorial, "Where is the JS version of this documentation? I am a HTML developer." There was no reply. Not to be outdone, other readers in the .NET camp complained about the lack of C# code, specifically for server-side scripting, in the WAMS support forums. In reply to the question of whether or not C# or another .NET language would be supported for scripting, WAMS guru Josh Twist replied: "we have no firm plans right now but certainly haven't ruled this out. Again, we're listening to customer feedback and demand on this (you're not the first person to ask) so thanks for posting." Several other readers also weighed in on the subject, with one saying: "I agree. This seems kinda mismatched. The client allows script or C#. But the server side is JavaScript only. Seems the server side would be even a better fit with C#." There were also some requests for Visual Basic tutorials. In fact, that was the post with the most total views in the support forum. Twist replied, "This is on our list of things to do." (Hmm, I wonder if that "to do" pun--all the tutorials are "to do" lists--was intended.) Microsoft's Glenn Gailey replied with links to the Visual Basic versions of the "Get started with data" tutorial and the WAMS quickstart project. I'm sure such issues will get ironed out as the WAMS preview continues and user feedback is collected, so give it a try and let Microsoft know what you think. As a hobbyist, I'm certainly giving it the thumbs up. In fact, I was gratified that Twist mentioned the hobbyist as one of three distinct personas to whom WAMS is relevant. Twist listed these three roles in his introduction to WAMS on his The Joy of Code site. He said Microsoft research found that about two-thirds of developers were interested in the cloud but suffered from "cloudphobia," in that "they wanted backend capabilities like authentication, structured storage and push notifications for their app, but they were reluctant to add them" for lack of time, expertise and so on. In addition to the hobbyist, the other two developer types he mentioned were the "client-focused developer," targeted by WAMS, and the "backend developer," who is already experienced in writing server code. So I'm looking forward to seeing how WAMS matures (hopefully before my 3-month trial Windows Azure subscription expires). As Twist said in a Joy of Code post, "we're working on making it even easier to build any API you like in Mobile Services. Stay tuned!" What do you think about WAMS? Share your thoughts by commenting here or dropping me a line. Posted by David Ramel on 10/03/2012 at 9:03 AM 29 percent. "Microsoft was very aggressive with its introduction of Azure to the development community a few years ago and that has paid off," said Evans Data CEO Janel Garvin. "Additionally, the large established MSDN community and the fact that Visual Studio is still the most used development environment are huge assets to Microsoft in getting developers to adopt the Azure platform," > More TechLibrary I agree to this site's Privacy Policy. > More Webcasts
https://visualstudiomagazine.com/Blogs/Data-Driver/List/Blog-List.aspx?Page=7
CC-MAIN-2016-18
refinedweb
2,019
60.55
xlsx-write-stream0.0.19 • Public • Published XLSX Write Stream is a streaming writer for XLSX spreadsheets. Its purpose is to replace CSV for large exports, because using CSV in Excel is very buggy and error prone. It's very efficient and can quickly write hundreds of thousands of rows with low memory usage. XLSX Write Stream does not support formatting, charts, comments and a myriad of other OOXML features. It's strictly an CSV replacement. InstallationInstallation npm i 'xlsx-write-stream' Example UsageExample Usage import XLSXWriteStream from 'xlsx-write-stream';// Initialize the writerconst xlsxWriter = new XLSXWriteStream();// Set input stream. Input stream needs to implement Stream.Readable interface// and each chunk should be an array of values (only string, date and number are supported value types)xlsxWriter.setInputStream(inputStream);// Get output stream. This will return a stream of XLSX file data.const xlsxStream = xlsxWriter.getOutputStream();// do something with the output, like write it into file or send it as HTTP responseconst writeStream = fs.createWriteStream('file.xlsx');xlsxStream.pipe(writeStream); LicenseLicense This package is available as open source under the terms of the MIT License. install npm i xlsx-write-stream weekly downloads 290 version 0.0.19 license Apache-2.0
https://www.npmjs.com/package/xlsx-write-stream
CC-MAIN-2019-22
refinedweb
201
51.34
Hi Guenter,On Mon, 14 Nov 2011 22:27:42 -0800, Guenter Roeck wrote:> Add support for SMBUS_READ_BLOCK_DATA to the i2c-mpc bus driver.> Required to support the PMBus zl6100 driver with i2c-mpc.> > Reported-by: Tang Yuantian <B29983@freescale.com>> Cc: Tang Yuantian <B29983@freescale.com>> Signed-off-by: Guenter Roeck <guenter.roeck@ericsson.com>> ---> drivers/i2c/busses/i2c-mpc.c | 33 +++++++++++++++++++++++++--------> 1 files changed, 25 insertions(+), 8 deletions(-)> > diff --git a/drivers/i2c/busses/i2c-mpc.c b/drivers/i2c/busses/i2c-mpc.c> index 107397a..77aade7 100644> --- a/drivers/i2c/busses/i2c-mpc.c> +++ b/drivers/i2c/busses/i2c-mpc.c> @@ -454,7 +454,7 @@ static int mpc_write(struct mpc_i2c *i2c, int target,> }> > static int mpc_read(struct mpc_i2c *i2c, int target,> - u8 *data, int length, int restart)> + u8 *data, int length, int restart, bool block)bool block would be better named bool recv_len IMHO. It will be set to0 for I2C block reads, which is confusing.> {> unsigned timeout = i2c->adap.timeout;> int i, result;> @@ -470,7 +470,7 @@ static int mpc_read(struct mpc_i2c *i2c, int target,> return result;> > if (length) {> - if (length == 1)> + if (length == 1 && !block)> writeccr(i2c, CCR_MIEN | CCR_MEN | CCR_MSTA | CCR_TXAK);> else> writeccr(i2c, CCR_MIEN | CCR_MEN | CCR_MSTA);> @@ -479,17 +479,28 @@ static int mpc_read(struct mpc_i2c *i2c, int target,> }> > for (i = 0; i < length; i++) {> + u8 byte;> +> result = i2c_wait(i2c, timeout, 0);> if (result < 0)> return result;> > + byte = readb(i2c->base + MPC_I2C_DR);> + /*> + * Adjust length if first received byte is length> + */> + if (i == 0 && block) {> + if (byte == 0 || byte > I2C_SMBUS_BLOCK_MAX)> + return -EPROTO;> + length += byte;> + }> + data[i] = byte;> /* Generate txack on next to last byte */> if (i == length - 2)> writeccr(i2c, CCR_MIEN | CCR_MEN | CCR_MSTA | CCR_TXAK);> /* Do not generate stop on last byte */> if (i == length - 1)> writeccr(i2c, CCR_MIEN | CCR_MEN | CCR_MSTA | CCR_MTX);> - data[i] = readb(i2c->base + MPC_I2C_DR);> }This needs careful testing (which I can't do.) There may have been areason why the read was done after the writes. Swapping the commandsmay be the wrong thing to do. The dummy read earlier in this functionsuggests that maybe changes to CCR do not take effect until you readfrom (or write to) the DR register.Can't the above be rewritten to keep the order of the commands as itwas before? AFAICS it would only take one or two extra tests.Note that the hardware implementation may make it difficult or evenimpossible to properly support SMBus block reads of 1 byte. Not surewhat should be done when this can be supported and still happens...Returning -EOPNOTSUPP I guess, and then probably the I2C engine needssome form of reset.> > return length;> @@ -532,12 +543,17 @@ static int mpc_xfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)> "Doing %s %d bytes to 0x%02x - %d of %d messages\n",> pmsg->flags & I2C_M_RD ? "read" : "write",> pmsg->len, pmsg->addr, i + 1, num);> - if (pmsg->flags & I2C_M_RD)> - ret => - mpc_read(i2c, pmsg->addr, pmsg->buf, pmsg->len, i);> - else> + if (pmsg->flags & I2C_M_RD) {> + bool block = pmsg->flags & I2C_M_RECV_LEN;Here again I'd rather name it bool recv_len for clarity.> +> + ret = mpc_read(i2c, pmsg->addr, pmsg->buf, pmsg->len, i,> + block);That's a lot of parameters, most coming from pmsg. It would be moreefficient to pass pmsg itself. Not directly related to your patch,admittedly, but it makes the problem more obvious. Maybe a cleanup forlater.> + if (block && ret > 0)> + pmsg->len = ret;> + } else {> ret => mpc_write(i2c, pmsg->addr, pmsg->buf, pmsg->len, i);> + }> }> mpc_i2c_stop(i2c);> return (ret < 0) ? ret : num;> @@ -545,7 +561,8 @@ static int mpc_xfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)> > static u32 mpc_functionality(struct i2c_adapter *adap)> {> - return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL;> + return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL> + | I2C_FUNC_SMBUS_READ_BLOCK_DATA;You could add I2C_FUNC_SMBUS_BLOCK_PROC_CALL too, even though Idon't know of any slave driver using it.> }> > static const struct i2c_algorithm mpc_algo = {-- Jean Delvare
http://lkml.org/lkml/2011/11/15/76
CC-MAIN-2014-52
refinedweb
629
62.38
/* * memfile.h * * WAV file I/O channel class. * * Portable Windows Library * * Copyright (c) * * All Rights Reserved. * * Contributor(s): ______________________________________. * * $Log: memfile 2002/08/05 05:40:45 robertj * Fixed missing pragma interface/implementation * * Revision 1.2 2002/06/27 03:53:35 robertj * Cleaned up documentation and added Compare() function. * * Revision 1.1 2002/06/26 09:01:19 craigs * Initial version * */ #ifndef _PMEMFILE #define _PMEMFILE #ifdef P_USE_PRAGMA #pragma interface #endif #include <ptlib.h> /**This class is used to allow a block of memory to substitute for a disk file. */ 00062 class PMemoryFile : public PFile { PCLASSINFO(PMemoryFile, PFile); public: /**@name Construction */ //@{ /**Create a new, empty, memory file. */ PMemoryFile(); /**Create a new memory file initialising to the specified content. */ PMemoryFile( const PBYTEArray & data ///< New content filr memory file. ); //@} /**@name Overrides from class PObject */ //@{ /**Determine the relative rank of the two objects. This is essentially the string comparison of the #PFilePath# names of the files. @return relative rank of the file paths. */ Comparison Compare( const PObject & obj ///< Other file to compare against. ) const; //@} /**@name Overrides from class PChannel */ //@{ /**Low level read from the memory file channel. The read timeout is ignored. memory file channel. The write timeout is ignored. PFile */ //@{ /**Get the current size of the file. The size of the file corresponds to the size of the data array. @return length of file in bytes. */ off_t GetLength() const; /**Set the size of the file, padding with 0 bytes if it would require expanding the file, or truncating it if being made shorter. @return TRUE if the file size was changed to the length specified. */ BOOL SetLength( off_t len ///< New length of file. ); /*. @return TRUE if the new file position was set. */ BOOL SetPosition( off_t pos, ///< New position to set. FilePositionOrigin origin = Start ///< Origin for position change. ); /**Get the current active position in the file for the next read or write operation. @return current file position relative to start of file. */ off_t GetPosition() const; //@} /**@name Overrides from class PFile */ //@{ /**Get the memory data the file has operated with. */ 00177 const PBYTEArray & GetData() const { return data; } //@} protected: PBYTEArray data; off_t position; }; #endif // _PMEMFILE // End of File ///////////////////////////////////////////////////////////////
http://pwlib.sourcearchive.com/documentation/1.10.10-1ubuntu6/memfile_8h-source.html
CC-MAIN-2017-17
refinedweb
353
60.21
Windows Phone to Windows 8 If you are currently working on a Windows 8 app that you’d like reviewed for possible early entry into the marketplace, please contact - It must feel natural to use in each of the supported languages - It must provide equal capabilities across all of the supported languages Those are some pretty lofty goals, especially when you consider that the languages Microsoft wanted to support included C#, VB, C++ and JavaScript. To my knowledge no framework has ever been created that provides equal capabilities and feels natural to use across so many languages. But that’s exactly what the product team did when it created the Windows Runtime (WinRT). To C++ developers WinRT looks a lot like a C++ library that’s been linked to the project. To JavaScript developers WinRT looks a lot like an external .js file that’s been referenced. To C# and VB developers WinRT feels a lot like the .NET framework. In fact it feels and looks so much like .NET that if you don’t know exactly what to look for you might just assume it is. This caused some confusion at our //build conference and is still a point of confusion for many developers today, so I’d like to try and demystify it a little for those of you coming from Windows Phone. The truth is that WinRT is actually closest to what the C++ developer sees. WinRT is a runtime, created by the Windows team, written in C++ and exposed to all four languages in a natural way. This is probably easiest to understand by looking at a code sample (or three). ImageEncodingProperties^ imageProperties = ref new ImageEncodingProperties(); imageProperties->Subtype = "JPEG"; imageProperties->Width = 320; imageProperties->Height = 240; auto opCapturePhoto = m_mediaCaptureMgr->CapturePhotoToStorageFileAsync(imageProperties, this->m_photoStorageFile); ImageEncodingProperties imageProperties = new ImageEncodingProperties(); imageProperties.Subtype = "JPEG"; imageProperties.Width = 320; imageProperties.Height = 240; await mediaCaptureMgr.CapturePhotoToStorageFileAsync(imageProperties, photoStorageFile); var photoProperties = new Windows.Media.MediaProperties.ImageEncodingProperties(); photoProperties.subtype = "JPEG"; photoProperties.width = 320; photoProperties.height = 240; mediaCaptureMgr.capturePhotoToStorageFileAsync(photoProperties, photoStorage).then(… he code snippets above are from the MSDN Sample Media capture using webcam. These 5 lines of code turn on the web cam, capture an image, resize it to 320 x 240 and save it as a file in JPEG format. (Yes, you really can use the webcam and save local files using JavaScript – assuming the user has given your app permission to of course.) Notice that the 5 lines of code use the same object names and property names whether you’re using C++, C# or JavaScript. And notice that the name casing changes from Title Case for C++ and C# to camel Case for JavaScript. This ability of the WinRT to “morph” into your language of choice is called Projection and it’s pretty amazing. The WinRT is written in C++ to be as fast as possible, but its objects and capabilities can be used in all supported languages just as if the WinRT were written natively in that language. As you can see from the graphic above, the surface area of WinRT is immense. All four languages are provided with unified APIs for storage, media capture, sensors, GPS and more. With the sheer size of the WinRT and how transparently it’s projected, no wonder developers are mistaking it for the “New .NET”. So is the .NET framework dead? Not at all. In fact it’s still alive and well with version 4.5 in desktop mode. And though WinRT provides most of the things C# developers need to build Metro style apps, a good chunk of the .NET framework is available in Metro mode too. This can blur the lines between what’s .NET and what’s WinRT, but a good rule of thumb is that WinRT components come from Windows.* namespaces and .NET components come from System.*. For an in-depth look at leveraging the .NET framework inside Metro style apps, see .NET for Metro style apps overview. WinRT Components (and WinMD) Now that you know what the WinRT is and how projection works, you might be thinking “Wouldn’t it be cool if I could create my own WinRT libraries and sell them or share them with other developers?” Well you can, and they can be written using C++, C# or Visual Basic. Though you can’t author WinRT components using JavaScript today, components created in any of the other languages are automatically projected and are usable by all of the languages - including JavaScript. Creating a WinRT component is a lot like creating a class library. In fact, class library projects can be converted to WinRT libraries by simply changing the project output from “Class Library” to “WinMD File” (MD stands for MetaData). There are rules that must be followed when creating WinRT components because of the automatic projection system. For example, public methods and properties must only return native WinRT types or basic .NET types like string and int. Private methods and variables, however, can be any .NET type supported in Metro style programs. There are other rules to be aware of, such as how collections are mapped and how to implement asynchronous methods. Luckily, Visual Studio enforces these rules at compile time and even offers instructions on how to correct mistakes if they’re made. You can read all of the rules and requirements in the article Creating Windows Runtime Components in C# and Visual Basic. Keep in mind that .NET class libraries are still supported, so if you aren’t looking to interop with C++ or JavaScript you may not need to create a WinRT component at all. If WinRT is what you need, be sure to check out Creating a simple component in C# or Visual Basic and calling it from JavaScript. Async and Await You may have noticed the new await keyword in front of the call to CapturePhotoToStorageFileAsync in the sample above. When you hear the Windows team say ‘Fast and Fluid’ they mean it. And to stand behind that statement they’ve made every single WinRT call that could possibly take longer than 50 milliseconds asynchronous. But asynchronous programming is hard right? I mean, one can just do a search for “Silverlight asynchronous” and find a long list of developers who were upset coming from the desktop world to find they couldn’t do blocking calls to online services anymore. But developers weren’t upset that they couldn’t block the UI thread, they were upset at how much uglier their code looked and how much harder it was to maintain. To illustrate this problem, consider the following Silverlight code to download a page from a URL: private void DownloadPage() { WebClient client = new WebClient(); client.DownloadStringCompleted += DownloadStringCompleted; client.DownloadStringAsync(new Uri("")); } private void DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { // Only proceed if there wasn't an error if (e.Error == null) { … } } In this example control flow actually leaves the DownloadPage method and moves to an entirely new method called DownloadStringCompleted. Any data (or state) that existed in the DownloadPage method is not available in DownloadStringCompleted. If a choice needs to be made in the callback based on variables defined in DownloadPage, they have to be promoted to class level variables or somehow passed to the handler. Anonymous methods and lambdas help this pattern tremendously. For example, we could rewrite our sample above to look like this: private void DownloadPage() { WebClient client = new WebClient(); client.DownloadStringCompleted += (o, e) => { // Only proceed if there wasn't an error if (e.Error == null) { … } }; client.DownloadStringAsync(new Uri("")); } Now the handler is actually inside the DownloadPage method and has access to all its local variables. (This works, by the way, because of a lesser-known feature of modern programming languages called closures.) The problem with this approach is that it leads to what I like to call “Death by Indention”. For example, if the handler now needs to call something else async, another lambda is required. private void DownloadPage() { WebClient client = new WebClient(); client.DownloadStringCompleted += (o, e) => { // Only proceed if there wasn't an error if (e.Error == null) { WebClient client2 = new WebClient(); client2.DownloadStringCompleted += (o, e) => { // Only proceed if there wasn't an error if (e.Error == null) { … } }; client2.DownloadStringAsync(new Uri("")); } }; client.DownloadStringAsync(new Uri("")); } And if that handler needs to call another async method, well I think you see the problem. The code is messy and it doesn’t feel natural. We’re even writing what we want to do with the results before we write the lines of code that fetches them! It feels “upside down”. All this work is necessary because we’re asking developers to compensate for the fact that asynchronous methods complete using callbacks. But what if we could write code that looks like it’s blocking but is actually yielding time while the asynchronous call completes? That’s what the await keyword does and with it our sample can be written like this in Windows 8: private async void DownloadPage() { HttpClient client = new HttpClient(); string bing = await client.GetStringAsync(""); string ms = await client.GetStringAsync(""); } Which one would you rather maintain? To learn more about why asynchronous programming is so important on Windows 8 see Keeping apps fast and fluid with asynchrony in the Windows Runtime. To dive deep on how the async keyword works and to learn advanced topics like receiving progress reports, check out the awesome post Diving deep with WinRT and await. In the next article I’ll start diving into API differences between Silverlight for Windows Phone and the Windows Runtime for Metro style apps. (Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)
http://mobile.dzone.com/articles/windows-phone-windows-8
CC-MAIN-2014-15
refinedweb
1,610
55.74
C# Corner No unread comment. View All Comments No unread message. View All Messages No unread notification. View All Notifications * * Login using C# Corner TECHNOLOGIES Request a new Category | View All ANSWERS BLOGS VIDEOS INTERVIEWS BOOKS NEWS CHAPTERS CAREER Jobs IDEAS About DataTable twitter google + Reddit Topics No topic found Content Filter Articles Videos Blogs News Complexity Level Beginner Intermediate Advanced Refine by Author [Clear] Vithal Wadje (6) N Vinodh (5) Emiliano Musso (5) El Mahdi Archane (4) Sathish Kumar (4) Devesh Omar (4) Saineshwar Bageri (3) Asma Khalid (3) Shreesh Raj (3) Thiruppathi R (3) Manas Mohapatra (3) Sibeesh Venu (3) Kailash Chandra Behera (3) Ehsan Sajjad (2) Ananth G (2) Jasbeer Singh (2) Vipul Malhotra (2) Sarwar Hussain (2) Praveen Kumar (1) Mahipal Reddy (1) Midhun T P (1) Delpin Susai Raj (1) Santosh Kumar (1) Manav Pandya (1) Kirtiranjan Moharana (1) Sivaraman Dhamodaran (1) Bikesh Srivastava (1) Harsh D (1) Pradeep Sahoo (1) Ankit Bansal (1) Mohammed Zaid Meraj (1) Donald Green (1) Muhammad Aqib Shehzad (1) Durgaprasad Yadav (1) Maruthi Palllamalli (1) Nitin (1) Rakesh (1) Satinder Singh (1) Rajeev Punhani (1) Debendra Dash (1) Vijay Prativadi (1) Manoj Kumar Mandal (1) Abrar Ahmad Ansari (1) Sushil Singh (1) Dinesh Vijayakumar (1) Pramod Thakur (1) Bhanu Pratap Singh (1) Anil Kumar (1) Ajay Yadav (1) Rahul Singh (1) Manish Kumar Choudhary (1) Puran Mehra (1) Akhil Garg (1) Nitesh Luharuka (1) Akshay Patel (1) Sara Silva (1) Keyur Patel (1) Samir Bhogayta (1) Hemant Carpenter (1) Related resources for DataTable No resource found How To Read CSV Or Text File In C# (DataSet/DataTable) 1/9/2018 10:18:23 AM. Learn how to read CSV or TEXT file in C# (DataSet/DataTable). JQuery DataTable Client Side Processing 11/3/2017 12:55:15 PM. In this blog I am going to share with you how to use Jquery DataTable with Jquery Ajax . jQuery DataTable With A Delete button 11/2/2017 8:35:52 PM. In this blog, I am going to share with you how to use jQuery DataTable with the Delete button. How To Use jQuery Datatable In Angular 10/25/2017 5:24:27 PM. In this article I am going to explain how to use and integrate the jQuery datatable with AngularJS. DataTables is a prebuild functionality and a plug-in for the jQuery JavaScript library. It is a high. Responsive GridView Using DataTables Plug-in 8/24/2017 11:42:53 AM. In this article, we will learn how to make an ASP GridView responsive using jQuery based DataTables plug-in. Learn MVC Using Angular Datatable 7/28/2017 11:18:31 PM. In this article, you will learn MVC, using Angular DataTable. DataTable In Xamarin iOS 7/27/2017 1:36:37 PM. In this article, you will learn how to Store Values Using DataTable in Xamarin iOS, using Xamarin Studio. Learn MVC Using Angular Dynamic Control In DataTable 7/26/2017 3:57:41 PM. In this article, we will learn MVC using Angular data binding for dynamic control in datatable from server side Web API using visual studio 2017. Learn MVC Using Angular Wizard 7/3/2017 12:45:05 AM. In this article, you will learn MVC, using Angular DataTable.& Angular Wizard AJAX CRUD Operation With jQuery DataTables In ASP.NET MVC 5 For Beginners 6/14/2017 12:45:55 AM. AJAX CRUD Operation With jQuery DataTables In ASP.NET MVC 5 For Beginners. Difference Between DataReader, DataSet, DataAdapter and DataTable in C# 5/22/2017 9:02:37 AM. what is the difference between DataReader, DataSet, DataAdapter and DataTable in C#. Table With Sorting Using AngularJS 5/8/2017 5:54:32 PM. This is a simple demo that shows how to create a datatable using AngularJs Using Datatable JS For Showing List/ Table Data With Action (Edit/ Delete) Buttons 4/12/2017 5:53:11 PM. Using Datatable JS for showing list/table data with action (Edit/Delete) buttons. AngularJS DataTable With Web API 3/30/2017 11:52:05 AM. In this article, you will get to know about AngularJS DataTable with Web API. Bind SharePoint List Data Into JQuery Datatable Using Content Search Web Part (CSWP) In SharePoint Server 2013 3/7/2017 1:41:07 PM. 2/10/2017 11:18:49 PM. In this article, you will learn about Grid View with Server Side Advanced Search using jQuery DataTables in ASP.NET MVC 5. Using DataAdapter, DataTable and DataGridControl 1/22/2017 11:59:32 PM. This video explains how to display data on the DataGridControl by making use Ado.net DataAdapter and DataTable. Bootstrap DataTable Gridview 12/26/2016 7:13:38 PM. This blog explains how to use DataTable in Bootstrap. Exporting Data From DataTable To PDF 12/20/2016 6:32:53 PM. This blog will explain the method of exporting data from DataTable to PDF. Convert HTML To DataTable 12/17/2016 12:50:06 PM. This blog is about converting HTML to DataTable. How To Convert a List Into a DataTable 12/15/2016 5:36:38 PM. This blog explains how to convert a list into a DataTable. More On C# DataTable 11/30/2016 12:48:16 PM. This article describes what DataTable is, and its uses. Create Pagination, Sorting, Filter With HTML Table Using DataTable.JS 10/29/2016 5:02:20 PM. In this blog, I am going to explain a basic example of how to use DataTable.js to generate a grid. Data Binding To JSON Data In AngularJS Datatable 9/23/2016 5:19:03 PM. In this article, you will learn about Data Binding to JSON Data in AngularJS Datatable. Data Grouping In AngularJS Datatable Using ASP.NET MVC 5 9/16/2016 5:52:16 PM. In this article you will learn about Data Grouping in AngularJS datatable, using ASP.NET MVC 5. ASP.NET Webform - Datatables JQuery plugin Server Side Integration 9/6/2016 5:28:31 PM. In this article you will learn about Datatables Jquery plugin Server Side Integration using ASP.NET Webform. Grouping Data In jqxDataTable Using ASP.NET MVC 4 7/31/2016 6:59:39 PM. In this article, you will see how to display data in jqxDataTable plugin, using MVC 4 application. jQuery Datatable With Server Side Data 7/11/2016 4:30:51 AM. In this article we will learn how to work with jQuery Datatables with server side data. Read Data Using Client Side JavaScript Object Model and Apply Search Using jQuery DataTable 6/29/2016 5:00:08 PM. In this blog you will learn how to read data using client side JavaScript Object Model and Apply Search Using jQuery DataTable. Converting Generic List into DataTable 5/29/2016 3:32:51 PM. In this blog we will see how we can convert generic list into datatable and insert those into database. Display Data In ASP.NET Using jQuery DataTables Plugin 4/3/2016 5:26:10 PM. This article gives a walk-through of jQuery DataTables plugin to display the data stored in the database using ASP.NET web services. ASP.NET MVC 5: Datatables Plugin Server Side Integration 3/15/2016 3:52:46 AM. In this article you will learn about Datatables Plugin Server Side Integration in ASP.NET MVC 5. Read and Import Excel File into DataSet or DataTable using C# in ASP.NET 3/12/2016 12:57:51 PM. In this article you will learn how to read and import Excel Files into DataSet or DataTable using C# in ASP.NET. Convert DataTable to Excel in .NET 2/21/2016 9:02:36 AM. Improved interaction between Excel and DataTable with Elerium Excel .NET 2.1. Bind GridView Using DataTable 1/25/2016 4:12:59 AM. In this article we will see how to bind GridView Control from DataTable. JQuery DataTable - Paging, Sorting, Searching In ASP.NET from Code Behind 1/25/2016 1:12:20 AM. In this article you will learn about Paging, Sorting, Searching with JQuery DataTable in ASP.NET. DataTableAdapter Design Technique Using DataSet 1/6/2016 11:39:59 AM. In this article you will learn DataTableAdapter Design Technique using DataSet. Inner Join and Outer Join In DataTable using LINQ 12/31/2015 6:56:46 AM. This blog describes how to implement Inner Join and Outer Join in DataTable Using Linq. Paging Sorting Searching In ASP.NET MVC 5 12/25/2015 6:57:23 AM. In this article we will learn how to do Sorting, Paging and Searching In ASP.NET MVC 5. Using JQuery DataTable 12/6/2015 12:07:51 PM. In this article I will explain how to use JQuery DataTable. How to Use JQuery Datatable 12/5/2015 7:19:03 AM. In this blog, I have explain how to use JQuery datatable. Convert Datatable to XML String using LINQ 11/27/2015 2:04:11 AM. In this blog we will see how to convert a datatable to XML string using LINQ. Convert DataReader To DataTable 11/18/2015 6:03:56 AM. In this article we will learn how we can convert Microsoft ADOMD DataReader to DataTable. Using jQuery DataTable In SharePoint 2013 11/1/2015 1:18:43 AM. Here you will see how can we use jQuery DataTable in SharePoint 2013. ADO.NET Technique With ASP.NET 10/13/2015 1:35:56 PM. In this article, I will explain ADO.NET concepts that include DataTable, DataSet, DataReader and DataAdapter. Filter DateTime From DataTable In C# 9/26/2015 8:48:22 AM. This blog helps you how to filter datetime from DataTable object in C#. 3 Ways to Convert DataTable to JSON String in ASP.NET C# 8/19/2015 7:16:39 PM. This article explains how to convert a DataTable to JSON in ASP.NET C#. Merging DataTables by Primary Key 8/13/2015 7:44:19 AM. In this blog we will learn how to provide Primary Key to C# DataTables and then merge them. Joining DataTables using LINQ in C# 8/5/2015 4:58:20 AM. In this blog we will learn how to merge two DataTable using LINQ.. jQuery DataTables in ASP.NET MVC 7/10/2015 1:38:10 AM. This article explains jQuery DataTables.. Convert Gridview rows to column 7/3/2015 11:22:55 AM. In this blog, I will show you how to convert Gridview rows to column in C#. Dynamically Creating DataTable and Binding To GridView Without Database 6/22/2015 4:19:31 AM. In this blog you will learn how to dynamically create DataTable and binding to GridView without database in ASP.NET. Sort and Filter CSV Files With DataTable and DataView 5/22/2015 12:58:48 PM. In this article we will learn how to Sort and Filter CSV files with a DataTable and DataView.). Convert LINQ Query to DataTable 5/3/2015 3:43:50 PM. This article shows how a LINQ query result can be converted to a datatable and later how the datatable can be consumed depending on the requirements. Passing DataTable as Input Parameter in C# 4/28/2015 2:55:33 PM. This article illustrates an alternate way of sending a datatable to a database procedure using a list container. Data Manipulation From SQL Server Source Through Controls and LINQ 4/23/2015 12:37:22 PM. In this article we'll see how to make a SQL Server resident table available to our application. Convert CSV File to XML With DataTable 4/22/2015 2:50:05 AM. In this short article, we'll see how to convert a common CSV file into its XML representation, using Visual Basic .NET and the powerful functionalities of DataTable objects. Insert(Bulk) DataTable Data in Database 4/15/2015 7:43:01 AM. In this blog we will Insert(Bulk) Entire DataTable Data in Database. Passing DataTable to StoredProcedure as Parameter in C# 4/5/2015 5:54:48 AM. This article describes how to pass a DataTable to a Stored Procedure as a parameter using ADO.NET in C#. Creating Stored Procedure That Accepts Table as Parameter in C# 3/31/2015 12:26:16 PM. This article explains how to create a Stored Procedure in SQL that accepts a data table as parameter. Difference between DataReader, Dataset, DataTable and DataAdapter in ASP.NET 3/4/2015 3:21:18 AM. In this blog you will learn difference between DataReader, Dataset, DataTable and DataAdapter in ASP.NET. Convert JSON String to DataTable in ASP.Net 2/26/2015 7:51:45 AM. Such as, you are read my previous article Convert DataTable To JSON String in ASP.Net. Here I will explain how to convert a JOSN String to DataTable using a written helper function (in C#) and Newtonsoft DLL. Convert DataTable To JSON String in ASP.Net 2/21/2015 2:23:10 AM. Here I will explain how to convert a DataTable to JSON string using a written helper function (in C#) and Newtonsoft DLL. How to Read Records from Excel to Datatable in C# 1/7/2015 6:36:18 PM. In this blog you will learn How to Read Records from Excel to Datatable in C#. How To Merge Two DataTables Into One Using C# 12/27/2014 8:20:00 PM. In this article we learn how to merge two DataTables in C#. Get a List/DataTable of Months/Years between two Dates 12/20/2014 2:12:39 PM. In this blog you will learn how to get a List/DataTable of Months/Years between two dates. Delete all Empty or Blank Rows from DataTable 12/19/2014 8:14:42 AM. In this blog you will learn how to Delete all empty or blank rows from DataTable in vb.net (none of columns of that row holds any value).#. Convert LINQ Query Result to Datatable 12/10/2014 11:25:43 PM. In this article we will learn how to convert Linq query result into the Datatable. ADO.NET Overview 12/9/2014 3:09:17 PM. In this article we examine the connected layer and learn about the significant role of data providers that are essentially concrete implementations of several namespaces, interfaces and base classes. Convert a DataTable to Generic List Collection 11/25/2014 4:06:22 PM. In this article, I am sharing a generic method I have developed while solving a question here on C# Corner. Various Ways to Convert DataTable to List 11/25/2014 2:45:49 PM. This article shows 3 ways to convert a DataTable to a List in C#. Export GridView Records to XML Using ASP.Net C# 11/12/2014 4:06:36 AM. In this article we will learn how to export GridView records or data table to XML using ASP.Net C#. Passing a DataTable to a Stored Procedure 10/29/2014 5:59:04 AM. This blog will explain how can you pass a data table to a stored procedure in C#. Save DataTable Into ViewState and Bind Gridview Without DataBase Using ASP.Net 10/12/2014 4:01:54 PM. In this article we will learn how to save a DataTable in Viewstate and display those records in a GridView without saving in the database. ADO.NET Objects: Part II 9/19/2014 2:07:37 AM. In this article I will explain about ADO.NET objects. This will help you in understanding them in an easy manner. Sorting and Filtering in Data Table 9/16/2014 2:54:11 PM. This article explains sorting and filtering in a Data Table. How To Merge Records From One DataTable Into Another Datatable 9/14/2014 12:24:45 PM. In this article, we will see how to merge records from one DataTable into another. Datatable in ViewData Sample in MVC - Day 3 7/29/2014 6:29:37 AM. This article describes how to pass an entire datatable from controller to view. Establishing Relation and Constraints in a DataTable Using C# 7/22/2014 4:49:32 PM. This article explains how to create a relationship between two DataTables and constraints in ADO.Net using C#. DataTable Design View For Azure SQL Database 7/19/2014 3:40:38 PM. This article has the goal to show a way to explore an Azure SQL Database, especially the datatable design view. Export Datatable to CSV Using Extension Method 7/11/2014 1:16:58 AM. I would like to share how to export a DataTable to Comma Separated File (CSV) format using an Extension method and how to use Extension methods to make code more manageable. How to Add Excel Data in DataTable 6/23/2014 4:26:07 AM. In this blog, we will learn how to add excel data in Datatable. We will make Range To DataTable method to add data in data table. How to Convert List to Datatable in VB.Net 6/16/2014 5:24:36 AM. Convert list to Datatable in VB.Net. Read CSV file and Get Record in DataTable using TextFieldParser in C# 6/16/2014 5:01:31 AM. By using TextFieldParser you have to import one reference using Microsoft.VisualBasic.FileIO; Send DataSet and DataTable From Webservice and Consume in Application 6/14/2014 1:08:51 PM. In this article we will see how to send a DataSet and DataTable from an ASP.NET web serivce and consume them in an application. Export DataTable to Excel Using HTML Text in C# 6/12/2014 1:09:17 PM. This article explains how to export a DataTable to Excel using HTML text in C#. Export DataTable to HTML in C# 6/10/2014 1:34:42 PM. In this article you will learn how to export a DataTable to HTML in C# .NET. Exporting DataTable to Excel in C# Using Interop 3/26/2014 12:01:42 PM. Here in this article we will use a sample datatable and learn how to export data to an Excel file.
http://www.c-sharpcorner.com/topics/datatable
CC-MAIN-2018-05
refinedweb
3,033
67.55
Add new standard definitions and mixins for working with boxes. Review Request #10659 — Created Aug. 15, 2019 and submitted — Latest diff uploaded Boxes are one of our earliest components in our CSS library. We've had it since early in the 1.0 timeframe. They were used more for presentation, and over time, we've reduced usage of the actual classes and moved to repeated definitions within other CSS files. This change makes this a bit easier. We now have a namespaced set of variables that can be used instead of the older global ones (which are now marked deprecated, but still widely used). There's also a few functions for adding box styles to an element. #rb-ns-ui.boxes.make-box()will add the standard rules. .make-box-at-screen-gte()will add them only at certain screen sizes (useful for desktop-only views). .unmake-box()will zero out the styles used for a box, which is going to be useful for some admin UI work (which isn't namespaced in super consistent and useful ways). These will be used in upcoming admin UI changes. Used these new mixins and variable in upcoming changes.
https://reviews.reviewboard.org/r/10659/diff/1-2/
CC-MAIN-2020-24
refinedweb
196
66.13
[Data Points] CQRS and EF Data Models By Julie Lerman | November 2016 | Get the Code: C# VB Command Query Responsibility Segregation (CQRS) is a pattern that essentially provides guidance around separating the responsibility of reading data and causing a change in a system’s state (for example, sending a confirmation message or writing to a database), and designing objects and architecture accordingly. It was initially devised to help with highly transactional systems such as banking. Greg Young evolved CQRS from Bertrand Meyer’s command-query separation (CQS) strategy, whose most valuable idea, according to Martin Fowler, “is that it’s extremely handy if you can clearly separate methods that change state from those that don’t” (bit.ly/2cuoVeX). What CQRS adds is the idea of creating entirely separate models for commands and queries. CQRS has often been put into buckets incorrectly, as a particular type of architecture, or as part of Domain-Driven Design, or as messaging or eventing. In a 2010 blog post, “CQRS, Task-Based UIs, Event Sourcing, Agh!” (bit.ly/1fZwJ0L), Young explains that CQRS is none of those things, but just a pattern that can help with architecture decisions. CQRS is really about “having two objects where there was previously only one.” It’s not specific to data models or service boundaries, though it can certainly be applied to those parts of your software. In fact, he states that “the largest possible benefit though is that it recognizes that their (sic) are different architectural properties when dealing with commands and queries. When defining data models (most often with Entity Framework [EF]), I’ve become a fan of leveraging this pattern—in particular scenarios. As always, my ideas are meant as guidance, not rules, and just as I’ve chosen to apply CQRS in a way that helps me achieve my architecture, I hope you’ll take them and shape them to suit your own particular needs. Benefits of Relationship Handling with EF Entity Framework makes working with relationships at design time so easy. When querying, this is a huge benefit. Relationships that exist between entities allow you to navigate those relationships when expressing queries. Retrieving related data from the database is easy and efficient. You can choose from eager loading with the Include method or with projections, after-the-fact lazy loading or after-the-fact explicit loading. These features haven’t changed much since the original version of EF, nor since I wrote about them back in June 2011, “Demystifying Entity Framework Strategies: Loading Related Data” (msdn.com/magazine/hh205756). The canonical example in the model in Figure 1 makes querying easy to display the details of a customer’s order, the line items and the product names on a page. You can write an efficient query like this: Figure 1 Entity Framework Data Model with Tightly Coupled Relationships EF will transform this into SQL that will retrieve all of the relevant data in one database command. Then, from the results, EF will materialize the full graphs of customers, their orders, the line items for the orders and even the product details for each line item. It certainly makes populating a page like the Window Presentation Foundation (WPF) window in Figure 2 easy. I can do it in a single line of code: Figure 2 Data Controls Bound to a Single Object Graph Here’s another benefit that developers love: When creating graphs, EF will work out the back and forth to the database to insert the parent, return the new primary key value, and then apply that as the foreign key value to the children before building and executing their insert commands. It’s all quite magical. But magic has its downsides, and in the case of EF data models, the magic that comes from having tightly bound relationships can result in side effects when it’s time to perform updates, and sometimes even with queries. A notable side effect can happen when you attach reference data to a new record using a navigation property and then call SaveChanges. As an example, you might create a new line item and set its Product property to an instance of an existing product that came from the database. In a connected app, such as a WPF app, where EF may be tracking every change to its objects, EF will get that the product was pre-existing. But in disconnected scenarios where EF begins tracking the objects only after the changes have been made, EF will assume that the product, like the line item, is new and will insert it into the database again. There are workarounds for these problems, of course. For this problem, I always recommend setting the foreign key value (ProductId) instead of the instance. There are also ways to track the state and sort things out with EF prior to saving the data. In fact, my recent column, “Handling the State of Disconnected Entities in EF” (msdn.com/magazine/mt694083), shows a pattern for doing that. Here’s another common pitfall: navigation properties that are required. Depending on how you’re interacting with an object, you may not care about the navigation property—but EF will certainly notice if it’s missing. I wrote about this type of problem in another column, “Making Do with Absent Foreign Keys” (msdn.com/magazine/hh708747). So, yes, there are workarounds. But you can also leverage the CQRS pattern to create cleaner and more explicit APIs that don’t require workarounds. This also means that they will be more maintainable and less prone to additional side effects. Applying CQRS Pattern for DbContext and Domain Classes I’ve often used the CQRS pattern to help me get around this problem. Granted that it does mean that whatever models you’re breaking up will result in twice as many classes (although not necessarily twice as much code). Not only do I create two separate DbContexts, but quite often I’ll end up with pairs of domain classes, each focused on the relevant tasks around reading or writing. I’ll use as my example a model that’s slightly different form the simpler one I already presented. This example comes from a sizable solution I built for a recent Pluralsight course. In the model, there’s a SalesOrder class that acts as the aggregate root in the domain. In other words, the SalesOrder type controls what happens to any of the other related types in the aggregate—it controls how LineItems are created, how discounts are calculated, how a shipping address is derived and so forth. If you think about the tasks I just mentioned, they’re focused more on order creation. You don’t really need to worry about the rules around creating a new line item for an order when you’re simply reading the order information from the database. On the other hand, when viewing data, there may be a lot more interesting information to see than I care about when I’m just pushing data into the database. A Model for Queried Data Figure 3 shows the SalesOrder type in the Order.Read.Domain project of my solution. There are a lot of properties here and only a single method for creating better display data. You don’t see business rules in here because I don’t have to worry about data validation. namespace Order.Read.Domain { public class SalesOrder : Entity { protected SalesOrder() { LineItems = new List<LineItem>(); } public DateTime OrderDate { get; set; } public DateTime? DueDate { get; set; } public bool OnlineOrder { get; set; } public string PurchaseOrderNumber { get; set; } public string Comment { get; set; } public int PromotionId { get; set; } public Address ShippingAddress { get; set; } public CustomerStatus CurrentCustomerStatus { get; set; } public double Discount { get { return CustomerDiscount + PromoDiscount; } } public double CustomerDiscount { get; set; } public double PromoDiscount { get; set; } public string SalesOrderNumber { get; set; } public int CustomerId { get; set; } public double SubTotal { get; set; } public ICollection<LineItem> LineItems { get; set; } public decimal CalculateShippingCost() { // Items, quantity, price, discounts, total weight of item // This is the job of a microservice we can call out to throw new NotImplementedException(); } } Compare this to the SalesOrder in Figure 4, which I’ve defined for scenarios where I’ll store SalesOrder data to the database—whether it’s a new order or one that I’m editing. There’s a lot more business logic in this version. There’s a factory method along with a private and protected constructor that ensure that an order can’t be created without particular data being available. There are methods with logic and rules for how a new line item can be created for an order, as well as how to apply a shipping address. There’s a method to control how and when a particular set of order details can be modified. namespace Order.Write.Domain { public class SalesOrder : Entity { private readonly Customer _customer; private readonly List<LineItem> _lineItems; public static SalesOrder Create(IEnumerable<CartItem> cartItems, Customer customer) { var order = new SalesOrder(cartItems, customer); return order; } private SalesOrder(IEnumerable<CartItem> cartItems, Customer customer) : this(){ Id = Guid.NewGuid(); _customer = customer; CustomerId = customer.CustomerId; SetShippingAddress(customer.PrimaryAddress); ApplyCustomerStatusDiscount(); foreach (var item in cartItems) { CreateLineItem(item.ProductId, (double) item.Price, item.Quantity); } _customer = customer; } protected SalesOrder() { _lineItems = new List<LineItem>(); Id = Guid.NewGuid(); OrderDate = DateTime.Now; } public DateTime OrderDate { get; private set; } public DateTime? DueDate { get; private set; } public bool OnlineOrder { get; private set; } public string PurchaseOrderNumber { get; private set; } public string Comment { get; private set; } public int PromotionId { get; private set; } public Address ShippingAddress { get; private set; } public CustomerStatus CurrentCustomerStatus { get; private set; } public double Discount{ get { return CustomerDiscount + PromoDiscount; } } public double CustomerDiscount { get; private set; } public double PromoDiscount { get; private set; } public string SalesOrderNumber { get; private set; } public int CustomerId { get; private set; } public double SubTotal { get; private set; } public ICollection<LineItem> LineItems { get { return _lineItems; } } public void CreateLineItem(int productId, double listPrice, int quantity) { // NOTE: more rules to be implemented here var item = LineItem.Create(Id, productId, quantity, listPrice, CustomerDiscount + PromoDiscount); _lineItems.Add(item); } public void SetShippingAddress(Address address) { ShippingAddress = Address.Create(address.Street, address.City, address.StateProvince, address.PostalCode); } public bool HasLineItems(){ return LineItems.Any(); } public decimal CalculateShippingCost() { // Items, quantity, price, discounts, total weight of item // This is the job of a microservice we can call out to throw new NotImplementedException(); } public void ApplyCustomerStatusDiscount() { // The guts of this method are in the sample } public void SetOrderDetails(bool onLineOrder, string PONumber, string comment, int promotionId, double promoDiscount){ OnlineOrder = onLineOrder; PurchaseOrderNumber = PONumber; Comment = comment; PromotionId = promotionId; PromoDiscount = promoDiscount; } } } The write version of SalesOrder is more complex. But if I ever need to work on the read version, I won't have all of that extraneous write logic in my way. If you’re a fan of the guidance that readable code is code that’s less prone to errors, you may, like me, have yet another reason to prefer this separation. And surely someone like Young would think even this class has way too much logic in it. But for our purposes, this will do. The CQRS pattern lets me focus on the problems of populating a SalesOrder (which, in this case, are few) and the problems of building a SalesOrder separately when defining the classes. These classes do have some things in common. For example, both versions of the SalesOrder class define a relationship to the LineItem type with an ICollection<List> property. Now let’s take a look at their data models; that is, the DbContext classes I use for data access. The OrderReadContext defines a single DbSet, which is for the SalesOrder entity: EF discovers the related LineItem type and builds the model shown in Figure 5. However, as EF requires the DbSet to be exposed, it also makes it possible for anyone to call OrderReadContext.SaveChanges. This is where layers are your friend. Andrea Saltarello provides a great way to encapsulate the DbContext so that only the DbSet is exposed and developers (or future you) using this class don’t have direct access to the OrderReadContext. This can help to avoid accidentally calling SaveChanges on the read model. Figure 5 The Data Model Based on the OrderReadContext A simple example of such a class is: Another protection you can add to this implementation is to take advantage of the fact that SaveChanges is virtual. You can override SaveChanges so that it never calls the internal DbContext.SaveChanges method. The OrderWriteContext defines two DbSets: not just one for SalesOrder, but another for the LineItem entity: Already that’s interesting, as I didn’t bother exposing a DbSet for LineItems in the other DbContext. In the OrderReadContext, I’ll query only through the SalesOrders. I won’t ever query directly against the LineItems, so there’s no need to expose a DbSet for that type. Remember in the query to populate the WPF window as in Figure 2. I eager-loaded the LineItems via the Orders DbSet. The other important logic in the OrderWriteContext is that I’ve explicitly told EF to ignore the relationship between SalesOrder and LineItem using the fluent API: The resulting model looks like Figure 6. Figure 6 The Data Model Based on the OrderWriteContext That means I can’t use EF to navigate from SalesOrder to LineItem. It doesn’t prevent me from doing that in my business logic; as you’ve seen, I have lots of code in the SalesOrder class that interacts with LineItems. But I won’t be able to write a query that navigates through to LineItems, like context.SalesOrders.Include(s=>s.LineItems). That may raise a moment of panic until I remind you that this is the model for writing data, not for reading it. EF can retrieve related data with no problem using the OrderReadContext. Pros and Cons of a Relationship-Free DbContext for Writes So what have I gained by separating the writing responsibilities from the querying responsibilities? It’s easy for me to see the downsides. I have more code to maintain. More important, EF won’t magically update graphs for me. I’ll have to do more work manually to ensure that when I’m inserting, updating or deleting data, the relationships are handled properly. For example, if you have code that adds a new LineItem into a SalesOrder, simply writing myOrder.LineItems.Add(someItem) won’t trigger EF to push the orderId into the LineItem when it’s time to persist the LineItem into the database. You’ll have to explicitly set that orderId value. If you look back at the CreateLineItem method of the SalesOrder in Figure 4, you’ll see I’ve got that covered. In my system, the only way to create a new line item for an order is through that very method, which means I can’t write code elsewhere that misses that critical step of applying the orderId. Another question you may ask is: “What if I want to change the orderId of a particular line item?” In my system, that’s an action that doesn’t make a lot of sense. I can see removing line items from orders. I can see adding line items to orders. But there’s no business rule that allows for changing the orderId. However, I can’t help thinking of these “what ifs” because I’m so used to just building these capabilities into my data model. In addition to the explicit control I have over the relationships, breaking up the read and write logic also gets me thinking about all the logic I add to my data models by default, when some of that logic will never be used. And that extraneous logic may be forcing me to write workarounds to avoid its side effects. The problems I brought up earlier about reference data being re-added to the database accidentally or null values being introduced when you’re reading data you don’t intend to update—these problems will also disappear. A class defined for reading may include values that you want to see but not update. My SalesOrder example doesn’t have this particular problem. But a write class could avoid including properties you may want to view but not update and, therefore, avoid overwriting ignored properties with null values. Make Sure It’s Worth the Effort. My particular use of this pattern isn’t what you might think of as full-blown CQRS, but being given “permission” to split up the reads and writes by CQRS has helped me reduce the complexity of solutions where an overreaching data model had been getting in the way. Finding a balance between writing extra code to get around side effects or writing extra code to provide cleaner, more direct paths to solving the problem takes some experience and confidence. But sometimes your instinct is the best guide. technical expert for reviewing this article: Andrea Saltarello (Managed Designs) (andrea.saltarello@manageddesigns.it) Andrea Saltarello is an entrepreneur and software architect from Milan, Italy, who still loves writing code for real projects to get feedback about his design decisions. As a trainer and speaker, he has had several speaking engagements for courses and conferences across Europe, such as TechEd Europe, DevWeek and Software Architect. He has been a Microsoft MVP since 2003 and was recently been appointed a Microsoft Regional Director. He is passionate about music, and is devoted to Depeche Mode, with whom he has been in love ever since listening to “Everything Counts” for the first time. Receive the MSDN Flash e-mail newsletter every other week, with news and information personalized to your interests and areas of focus. Data Points - CQRS and EF Data Models One thing that wasn't mentioned in this article, that I've used with success is to disable change tracking on your reader classes. You can do that easily like so: public ParticipantsReader() { Conf... Jul 27, 2017 Data Points - CQRS and EF Data Models public IQueryable<SalesOrder> Orders { set { return readContext.Orders; }"set" should be "get" Jul 13, 2017 Data Points - CQRS and EF Data Models Command Query Responsibility Segregation (CQRS) is a pattern that has a lot of benefits—and some drawbacks—when you’re defining data models with Entity Framework. Julie Lerman explains why it’s worth considering. Read this article in the November is... Oct 31, 2016
https://msdn.microsoft.com/magazine/mt788619
CC-MAIN-2019-35
refinedweb
3,048
50.16
hello, I am reading in a file and storing it into an array, and i am trying to find which letter appears most frequently in the array. how can this be accomplished? this is what i have so far. oh ya, and the file has spaces , but when i read contents of array there are no spaces. Code:#include <iostream> #include <fstream> #include <string> #include <iomanip> using namespace std; int main() { string line; // also tried char line[200]; int count = 0; char reply; ifstream infile; string myfile; ifstream inputFile; inputFile.open ("encrypted.txt"); if(!inputFile) { cerr << "Can't open input file " << myfile << endl; cout << "Press enter to continue..."; exit(1); } while (inputFile.peek() != EOF) { inputFile >> line; cout << line; } cin >> reply; return 0; }
https://cboard.cprogramming.com/cplusplus-programming/111771-array-problem.html
CC-MAIN-2017-09
refinedweb
122
73.88
Michele Simionato wrote: > On Aug 5, 4:38 am, "Gabriel Genellina": >> So the namespace that the metaclass receives when the class is created, >> will be some kind of ordered dictionary? >> Metaclasses are available for a long time ago, but the definition order is >> lost right at the start, when the class body is executed. Will this step >> be improved in Python 3.0 then? >> > > Yep. See > (I am working on an English translation these days, > but for the moment you can use Google Translator). Bfiefly, as I understood the discussion some months ago: In 2.x, the class body is executed in a local namespace implemented as a normal dict and *then* passed to the metaclass. In 3.0, the metaclass gets brief control *before* execution so, among other possibilities, it can substitute an (insertion) ordered dict for the local namespace. I will leave the details to Michele's article and its eventual translation. tjr
https://mail.python.org/pipermail/python-list/2008-August/469398.html
CC-MAIN-2014-15
refinedweb
155
60.85
I understand there are more simplified ways of doing what I am making now, but for the time being I am just using my current knowledge of Java to expand on what I already know. So right now I am making a script to convert between binary and text and vice versa. One issue I am having is that the decimal answer is coming out all wrong when I test the binary to text (decimal for now) part. I keep getting this 4-5 digit answer whenever I enter a 8-bit binary number. I've rechecked my code and broke it down to parts, printed each value through the loop but for some reason I get these bizarre numbers. Here's what I have, but keep in mind that THIS IS INCOMPLETE: Code : import java.lang.*; import java.io.*; import java.util.Scanner; public class BinaryOrText { public static void main(String[] args) throws IOException { int method; int iter = 0; int binary; int power = 0; int decimal; char binaryDigit = 0; String strBinary; String text = ""; Scanner in = new Scanner(System.in); System.out.print("Pick a Conversion Method; Enter [1] to Binary | [2] to Text: "); method = in.nextInt(); //text to binary if (method == 1){ System.out.print("Enter text: "); text = in.next(); char charT = text.charAt(0); System.out.println((int)charT); // ...Incomplete } //binary to text else if (method == 2){ decimal = 0; //declare System.out.print("Enter Binary: "); //prompt binary = in.nextInt(); //assign original input strBinary = Integer.toString(binary); //make a string version power = strBinary.length() - 1; //sets the starting power by length of binary code for (int i = 0; i < strBinary.length(); i++){ binaryDigit = strBinary.charAt(iter); //Takes binary digit from char position. decimal += binaryDigit*Math.pow(2,power); // digit * 2^pow. System.out.println(decimal); iter++; //Goes to next binary digit. power--; //Goes to power on next digit } } } }
http://www.javaprogrammingforums.com/%20whats-wrong-my-code/12304-making-binary-converter-script-scratch-running-into-math-issue-printingthethread.html
CC-MAIN-2017-30
refinedweb
309
58.58