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 |
|---|---|---|---|---|---|
NPS accumulates savings into a subscriber’s personal retirement accounts (PRA) while he is working. On retirement, 60% of the accumulated corpus is paid out as lump sum to the subscriber.
Having a secular cash flow at all times is what every individual investors looks for, especially after retirement. With this in mind, National Pension Scheme (NPS) which is a defined contribution scheme, was started for government employees in 2004 and was extended to all in 2009.
NPS accumulates savings into a subscriber’s personal retirement accounts (PRA) while he is working. On retirement, 60% of the accumulated corpus is paid out as lump sum to the subscriber. The rest is used to pay pension for the rest of his life. In Tier I structure, the asset allocation is determined on the basis of age of the subscriber and is divided into equity, corporate bonds and government securities. As the subscriber ages, allocation in equity gradually comes down to 10%. This strategy helps in managing volatility in the portfolio as the age progresses and investor approaches retirement.
Returns generated
Let’s take the case of a 40-year-old investor in 2009 (current age 49), who invests `25,000 every July and January (starting July 2009), in NPS Tier 1 option, managed by one of the biggest pension fund managers in India, with moderate (auto) asset allocation mode. The period considered in this exercise is July 1, 2009 to June 25, 2018. It was observed, in the period 2009 –18, total investment of `4.5 lakh in NPS had grown to `7.14 lakh (touching a high of `7.23 lakh) and registering an internal rate of return (IRR) of 9.6%. We also observed that the investor did go through a drawdown of 10.23% in the portfolio as on August 28, 2013. The overall volatility, however, has remained quite benign; a total of four drawdowns greater than 5% and only one instance of drawdown greater than 10%.
Asset allocation in mutual fund
Another dimension of this analysis was to replicate the asset allocation of NPS in mutual fund portfolio. The same strategy of rebalancing the asset allocation, being dependent on the age of the investor, was then replicated using one large-cap, one credit opportunity fund and one gilt fund (instead of equity, corporate and government allocation of NPS).
We observed the following trends after the exercise: The invested amount of `4.5 lakh has grown to `7.75 lakh in the span of 9 years (2009–18) with an IRR of 10.88% (as compared to 9.6% in the case of NPS). One interesting observation is that, even though this MF allocation is more volatile (in terms of number of drawdowns), the extent of drawdown is more limited than that of NPS. For example, the maximum drawdown in MF allocation is 7.51% as on August 28, 2013 (as compared to a drawdown of 10.23% in NPS). But the instances of drawdown greater than 5% has climbed up to 12, as compared to just four in case of NPS.
We continued this exercise with a half-yearly SIP of `25,000 into large-cap, mid-cap and ELSS category and the results are:
Each of the investments in large, mid and ELSS category funds have registered progressively higher returns than NPS or MF asset allocation, but these returns have come with added volatility as well. We observed that ELSS, large-cap and mid-cap have an IRR of 11.97%, 13.6% and 18.73%, respectively. Also, the maximum drawdowns in the same are 21.2%, 15.58% and 19.79%, respectively. In all three investments, there are 25 instances of drawdowns that are greater than 5%, while only ELSS has recorded instances of drawdowns of 20% and greater (two instances of drawdowns >20%). From above, we can conclude the following: NPS is the least volatile among all options. MF asset allocation has higher volatility, compared with that of NPS. Pure equity MF investment generates higher return and supports wealth creation, but is accompanied by much higher volatility.. | https://www.financialexpress.com/money/investment-in-nps-less-volatile-than-mutual-funds-here-is-why/1263910/ | CC-MAIN-2019-47 | refinedweb | 683 | 63.39 |
What is the exact difference between Sage and Cocalc?
Could anyone tell me, what is the difference between Sage and Cocalc?
Any answers would be accepted.
Thank you!: 372 times
Last updated: Aug 18 '18
share not working in sage cell
Approximate real numbers by rationals
import sage packages in python
JSON and basic sage types
Public interactive not working
Sage binary system requirements
save gp object to sage readable sobj
Problems with Var in Cloud.Sagemath
I am using Cocalc recently, but I would also like to try SageMath. Could anyone give me any idea what kind of function is in SageMath but not in Cocalc? | https://ask.sagemath.org/question/43409/what-is-the-exact-difference-between-sage-and-cocalc/?sort=oldest | CC-MAIN-2019-09 | refinedweb | 107 | 61.97 |
Equations and namespaces¶
Equation parsing¶
Parsing is done via pyparsing, for now find the grammar at the top of the brian2.equations.equations file.
Variables¶
Each Brian object that saves state variables (e.g. NeuronGroup, Synapses, StateMonitor) has a variables attribute, a dictionary mapping variable names to Variable objects (in fact a Variables object, not a simple dictionary). Variable objects contain information about the variable (name, dtype, units) as well as access to the variable’s value via a get_value method. Some will also allow setting the values via a corresponding set_value method. These objects can therefore act as proxies to the variables’ “contents”.
Variable objects provide the “abstract namespace” corresponding to a chunk of “abstract code”, they are all that is needed to check for syntactic correctness, unit consistency, etc.
Namespaces¶
The namespace attribute of a group can contain information about the external (variable or function) names used in the equations. It specifies a group-specific namespace used for resolving names in that group. At run time, this namespace is combined with a “run namespace”. This namespace is either explicitly provided to the Network.run() method, or the implicit namespace consisting of the locals and globals around the point where the run function is called.
Internally, this is realized via the before_run function. At the start of a run, Network.before_run() calls BrianObject.before_run() of every object in the network with a namespace argument and a level. If the namespace argument is given (even if it is an empty dictionary), it will be used together with any group-specific namespaces for resolving names. If it is not specified or None, the given level will be used to go up in the call frame and determine the respective locals and globals. | http://brian2.readthedocs.io/en/2.0a8/developer/equations_namespaces.html | CC-MAIN-2017-39 | refinedweb | 291 | 55.54 |
ElementTree: Working with Qualified Names
Updated December 8, 2005 | July 27, 2002 | Fredrik Lundh
The elementtree module supports qualified names (QNames) for element tags and attribute names. A qualified name consists of a (uri, local name) pair.
Qualified names was introduced with the XML Namespace specification.
Storing Qualified Names in Element Trees
The element tree represents a qualified name pair as a string of the form “{uri}local“.
The following example creates an element where the tag is the qualified name pair (, egg).
elem = Element("{}egg"}
To check if a name is a qualified name, you can do:
if elem.tag[0] == "{": ...
(you can also use startswith, but the method call overhead makes that a lot slower in current Python versions.)
Storing Qualified Names in XML Files
In theory, we could store qualified names right away in XML files. For example, let’s use the {uri}local notation in the file itself:
<{}egg> some content </{}egg>
There are two problems with this approach. One is the according to the XML base specification, { and } cannot be used in element tags and attribute names. Another, more important problem is bloat; even with a short uri like the one used in the example above, we’ll end up adding nearly 50 bytes to each element. Put a couple of thousand elements in a file, and use longer URIs, and you’ll quickly end up with hundreds of kilobytes of extra data.
To get around this, the XML namespace authors came up with a simple encoding scheme. In an XML file, a qualified name is written as a namespace prefix and a local part, separated by a colon: e.g. “prefix:local“.
Special xmlns:prefix attributes are used to provide a mapping from prefixes to URIs. Our example now looks like this:
<spam:egg xmlns: some content </spam:egg>
For a single element, this doesn’t save us that much. But the trick is that once a prefix is defined, it can be used in hundreds of thousands of places. If you really want to minimize the overhead, you can pick one-character prefixes, and get away with four bytes extra per element.
However, it should be noted that xmlns attributes only affect the element they belong to, and any subelements to that element. But an element can define a prefix even if it doesn’t use it itself, so you can simply put all namespace attributes on the toplevel (document) element, and be done with it.
Qualified Attribute Values
XML-languages like WSDL and SOAP uses qualified names both as names and as attribute values.The standard parser does this for element tags and attribute names, but it cannot do this to attribute values; an attribute value with a colon in it may be a qualified name, or it may be some arbitrary string that just happens to have a colon in it.
And once the element tree has been created, it’s too late to map prefixes to namespace uris; we need to know the prefix mapping that applied to the element where the attribute appears.
To work around this, the recommended approach is to use the iterparse function, and do necessary conversions on the fly. In the following example, the namespaces variable will contain a list of (prefix, uri) pairs for all active namespaces.
events = ("end", "start-ns", "end-ns") namespaces = [] for event, elem in iterparse(source, events=events): if event == "start-ns": namespaces.append(elem) elif event == "end-ns": namespaces.pop() else: ...
Note that the most recent namespace declaration is added to the end of the list; to find the URI for a given prefix, you have to search backwards:
def geturi(prefix, namespaces): for p, uri in reversed(namespaces): if p == prefix: return uri return None # not found | http://effbot.org/zone/element-qnames.htm | crawl-001 | refinedweb | 629 | 58.21 |
run or spawn in pexpect
Pexpect is a Python module for spawning child applications and controlling
them automatically.. Other Expect-like modules for Python
require TCL and Expect or require C extensions to be compiled. Pexpect does not
use C, Expect, or TCL extensions. It should work on any platform that supports
the standard Python pty module. The Pexpect interface focuses on ease of use so
that simple tasks are easy.
There are two main interfaces to Pexpect — the function, run() and the class,
spawn. You can call the run() function to execute a command and return the
output. This is a handy replacement for os.system().
I was failed when using spawn() to get output of remote ssh command,
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# filename: pexpect_2hei_spawn.py
import pexpect
if __name__ == ‘__main__’:
child = pexpect.spawn(‘ssh -oStrictHostKeyChecking=no myname@host.example.com’)
child.expect (‘Password:’)
child.sendline (mypassword)
child.expect (‘$’)
child.sendline (‘hostname’)
print child.before
print child.after
Function run() worked for me,that’s great!
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# filename: pexpect_2hei.py
from pexpect import *
if __name__ == ‘__main__’:
User = ‘myuser’
Host = ‘’
Pwd = ‘mypwd’
print run (“ssh -oStrictHostKeyChecking=no ” +User+”@”+Host+” ‘hostname;uptime'”, events={‘(?i)password’:Pwd+’\n’})
本文固定链接: | 2hei's site
最活跃的读者 | https://2hei.net/run-or-spawn-in-pexpect.html | CC-MAIN-2022-21 | refinedweb | 210 | 53.98 |
lp:~tux-style/eflxx/eetxx
Created by Andreas Volz on 2011-12-04 and last modified on 2013-01-04
Branch merges
This import branch has no branches proposed for merge into it.
Related bugs
Related blueprints
Branch information
- Owner:
- Andreas Volz
- Status:
- Development
Import details
Import Status: Failed
This branch is an import of the Subversion branch from.
Last successful import was on 2014-08-28.
Recent revisions
- 7. By cedric on 2013-01-04
trunk: remove use of AM_PROG_CC_STDC as AC_PROG_CC does it.
Patch by Doug Newgard <email address hidden>
- 2. By andreas on 2009-11-29
*** EFLXX API change!!!!!!!! ***
=> more usage of namespaces instead of direct class names
(some libs are in work and not yet possible to compile with the new API)
Branch metadata
- Branch format:
- Branch format 7
- Repository format:
- Bazaar repository format 2a (needs bzr 1.16 or later) | https://code.launchpad.net/~tux-style/eflxx/eetxx | CC-MAIN-2019-39 | refinedweb | 145 | 65.32 |
Domain Modeling with OWL - Part 2
Why Description Logic Matters?
In this second installment of the OWL introductory series, we will be doing a little bit of math. If you ever plan to create a moderately complex OWL 2 model, understanding the mathematical foundations will give you the right intuitions and spare you unpleasant surprises. The math is especially relevant to the reasoning portion of the OWL toolset and tightly integrated reasoning services are one of the main distinguishing features of OWL as opposed to many other knowledge representation languages.
Last time, I gave you a bit of a historical context on OWL and I mentioned that it is a fragment of first-order logic. This is strictly speaking correct, but a bit misleading as far as the original motivation of the formalism. OWL 2.0 is based on Description Logic (henceforth DL) which was developed in order to put semantic networks (or "conceptual graphs") and frames on a firm foundation. Several variants of these conceptual networks were proposed in the 70s, but the ideas at the core of DL first appeared as something called structured inheritance networks . Specifically, those ideas are the use of classes, instances and properties combined with means to create complex logical expressions and, most importantly, the ability to make inferences about sub-classing and class membership. And this last aspect, the fact that non-trivial IS-A relationships between two classes or between a class and an instance can be inferred, is the crucial contribution of that work and the reason it eventually got a comprehensive mathematical treatment gaining the name Description Logic.
When you create a domain model in OWL, you can state various constraints between classes and properties and those constraints have logical consequences. You are actually able to create a rather rich logical model of your domain and then ask interesting questions about it. Part of the knowledge that you would have represented is explicit. That's simply the collection of statements that you make to describe the domain. You can retrieve that knowledge by using the standard semantic web query language SPARQL or by direct API calls. No reasoning involved here, just plain data querying. But another portion of your knowedge base is the implicit knowledge that can be derived as a consequence of your statements. Accessing that implicit knowledge requires a precise logical interpretation, reasoning services and an appropriate expression language to formulate queries. That is what DL is about.
In what follows, I will introduce the actual mathematical formalism and show you side-by-side how it maps to OWL 2.0. Then we will discuss a few uncommon assumptions that OWL reasoners make and what their consequences are. One of the goals of this introduction is to give you a head start should you want to read more about the subject of Description Logic.
For more information and an extensive literature review, please consult The Description Logic Handbook.
Let's Get Formal
Formal languages, mathematical logic languages just list programming languages, are specified in two parts: syntax and semantics. Logic languages in particular are traditionally specified through what is known as Tarski-style semantics, where the meaning of an expression in the language is ascribed via a correspondence with set theoretical constructs. This allows the whole aparatus of model theory to be applied and classical proof techniques can be used to show whether a language is decideable and, if so, to what complexity class it belongs.Here is a summary of the DL language elements:
- Atomic concepts, usually written in capital letters from the beginning of the alphabet:
A, B, C, Detc. Those correspond to OWL classes.
- The special concepts top and bottom, denoted by
and
respectively. In OWL, those are referred to as
owl:Thingand
owl:Nothing.
- Roles, also in capital but from another part of the alphabet:
R,S etc.DL roles are equivalent to OWL properties.
- Individuals usually written in lower case:
a, b, cetc. In OWL we call them individuals as well.
- Logical operators like
(intersection),
(union), ∀ (every), ∃ (there exists), ¬ (complement) as well as number comparison ≤, ≥ etc. In OWL, all those operators are represented differently depending on the OWL syntax used, XML or functional or the very concise Manchester syntax.
The difference in terminology between OWL and DL shouldn't lead to confusion. Knowing the original DL terms and history should help understand the meaning adopted by OWL of what are otherwise standard OO notions. For example, knowing that OWL properties come from DL roles hints at the idea of a connection between two entities rather than having one "belong" to the other. I will be using both DL and OWL terms freely, and they should be considered synonymous. The single letter naming conventions are used only when doing the math. In modeling, both DL and OWL use more descriptive names, usually camel case, starting with capital letter for concepts and individuals, and starting with lower case for roles.
So the core elements in the language are concepts, roles and individuals. The interpretation of those elements is based on a universal set of things that are being talked about, a domain, and a mapping that assigns individual names to elements of that domain, concepts to subsets of the domain and roles to relations over the domain. Thinking about concepts as sets is not far from seeing them as classes, both in the mathematical and in the programming sense.
More formally, the meaning of the language elements is defined by an
interpretation function ℑ that assigns a set to each named DL concept.
We write
xℑ instead
ℑ(x) for the element that the interpretations maps
x to. The domain of interpretation, or application domain in software engineering terms, is denoted by Δℑ.
One may use just Δ for the namespace of individuals, the domain of
discourse. This is an important distinction in mathematical logic as one
is moving from formulas to what they are denoting and back. As an
example, top and bottom are formally interpreted as the whole domain and
the empty set respectively:
ℑ = ∅
ℑ=Δℑ
When proving theorems about a logic language, one frequently reasons
about different possible interpretations and each interpretation is
called a model, not to be confused with our domain models in
software. A model may offer a different mapping of individuals, concepts
and roles, but it may not change the meaning of the logical operators.
For example, the intersection operation
is analogous to what would be logical conjunction ∧ and is always interpreted as set intersection:
(C
D)ℑ = Cℑ∩Dℑ
Intuitively, half of what DL allows you to do is express concept descriptions, i.e. descriptions of sets of individuals. The atomic concepts and the roles are elementary descriptions and then you have operators in the syntax to make up more complex ones. The other half is description of individuals in terms of how they are classified and how they are related to other individuals.
In logical terms, concepts can be seen as one-place predicates while roles as two-place predicates. In fact, the claim that DL is a fragment of first-order logic (FOL) starts with that correspondence. Then it is easy to see how the formulas and statements below can be translated into FOL. So one can state in DL that a given individual belongs to a concept:
C(a) - a belongs C, akin to OWL's ClassAssertion axiom.
or that two individuals are related by a role:
R(a,b) -
b is a filler of the role R (or an
R-filler) for
a. This is akin to OWL's
ObjectPropertyAssertion that we saw last time.
Note the phrasing here: b is "a" filler, not "the" filler as there may be many. But the more interesting part are the complex concept description that one is allowed to form.
Describing Concepts
The power of DL as a language lies in its ability to describe classes of entities via complex logical formulas. That is what makes it into a useful logic language. In the table below you can see the list of available constructors for building those complex descriptions.The 3d column shows the equivalent OWL syntax in the standard OWL Functional Syntax and the Manchester Syntax. I won't be covering the bloated and ugly XML syntax. IMHO, pushing XML as the default serialization mechanism for RDF/OWL is probably an important reason for the slowish adoption of the technology. The functional syntax is both complete and user-friendly. The Manchester syntax is incomplete but even better looking than DL's own and used in Protege whenever class expressions are needed. So I'm showing both of those.
Each and every construct listed above has a precise formal, set-theoretic interpretation. For example, universal value restriction is interpreted thus:
(∀R.C)ℑ = {a∈Δℑ | ∀b:(a,b)∈Rℑ → b∈Cℑ }
As a little exercise, you could spell out the formal semantics of some of the other forms. This list of constructors constitutes a powerful means of expressing all sorts of concepts. Description Logic as a formalism has several variants with different computational characteristics. A particular variant is defined by the set of constructors that are allowed in it. Suffice it to say that all of them are available in OWL. So let's see a few concrete examples of what can be expressed in this language so far, staying on our automobile theme from last time:
In the constructor table, I showed the OWL Manchester syntax right below the OWL functional syntax. To get a feel, here's what the last expression above looks like in the Manchester syntax:
Person and owns only (Hybrid or Biodiesel)
If you are familiar with mathematical logic, you probably noticed the absence of variables. If this makes you uncomfortable, just think of concept expressions in DL as implicitly containing one free variable ranging over the domain of discourse. In other words, concept expressions are what you get as logical formulas in DL.
Making Statements - the TBox and the ABox
So far so good. We have seen how to make complex class descriptions in terms of simpler ones. Let's see how we can state facts (a.k.a. axioms). There are two fundamental kinds of axioms in DL: axioms expressing constraints purely within the conceptual model and axioms talking about individuals in the world being described. The former comprise the so called TBox (Terminological box) while the latter comprise the ABox (Assertion box). OWL itself doesn't make that distinction, but reasoning algorithms use it and you will come across those terms in the literature and discussion groups. I already showed you the two main types of ABox axioms, concept and role assertions with the following semantics:
C(a) is true in ℑ if aℑ ∈ Cℑ
R(a,b) is true in ℑ if (aℑ,bℑ)∈Rℑ
Another way to say the above is that the interpretation ℑ satisfies C(a) and that ℑ satisfies R(a,b). The concept and individual assignments that ℑ makes are consistent with those assertions. If an interpretation satisfies all axioms in an ABox, it is a model for that ABox. Concept and role assertions are not the only possible kinds of statements in an ABox, but they are the most important ones. Other assertions allow you to say when different names should be interpreted as the same individual and when not. More on them below.
In the TBox, the axioms establish a priori facts about concepts and roles. Two main types of axioms are used, inclusions and equalities:
C
D (inclusion or subsumption) is true in ℑ if Cℑ⊆Dℑ
C ≡ D (equality or definition) is true in ℑ if Cℑ=Dℑ
R
S (role subsumption) is true in ℑ if Rℑ=Sℑ
And similarly, an interpretation ℑ satisfies a TBox whenever it satisfies all axioms in it. Note that we can also define property inheritence in Description Logic, not only class inheritence. An example would be hasSon that is a sub-role of hasChild - if somebody has a son, one can infer that they definitely have a child. Even though we've just used atomic names here, a full concept expression can appear on either side of an inclusion or an equality axiom. For example we can define a Pedestrian as somebody who doesn't own a car:
Pedestrian ≡ Person
∀owns.(not Car)
From this, a reasoner can already trivially infer that a Pedestrian is a Person. As another example, we can say that true sports cars must have no more than two doors:
SportsCar
Car
≤ 2 hasPart.Door
The above axiom states that whenever something is known to be a sports car, it
is definitely a car (so if somebody owns it, they can't be a pedestrian) and
it can't have more than 2 doors. If you declare an individual as a
SportsCar and then proceed to assign 4 different doors to it:
hasPart(MyCar, FrontLeftDoor)
hasPart(MyCar, FrontRightDoor)
hasPart(MyCar, BackLeftDoor)
hasPart(MyCar, BackRightDoor)
a reasoner would complain about an inconsistency in your knowledge base, it will enforce a constraint.
Even though operators like intersection and union could be defined for
roles, this is not done in OWL. There are other ways to specify role
constraints at the conceptual level though. Besides role subsumption,
one can constrain the source and target of roles, or domain and range of
a property in OWL terms. Talking about "domains" and "ranges" is more
familiar than "roles" and "fillers", and consistent with the view of OWL
properties as binary relations. OWL provides the special axioms
ObjectPropertyDomain and
ObjectPropertyRange.
However, one should keep in mind that such constraints can be specified
using the existing DL tools and are in fact interpreted in exactly that
way by OWL reasoners:
≥ 1 R.T
C(domain of R is C)
∀ R. C(range of R is C)
In English, the first axiom above says that anything with at least 1
role R
filled by whatever also belongs to the concept C. So in other words,
whenever you have R(x, ?), you can infer the x ∈ C. Similarly, the
second axiom
says that any individual can only be a filler of role R if it belongs to
the
concept C. Therefore, a statement of the form R(?, x) would allow a DL
inference engine to conclude that x belong to C. Notice the pattern here
that allows you to introduce a constraint that applies to everything.
Saying that the universe (
) is subsumed by a concept
C is the same as saying that all individuals belong to
C.
Moreoever, just like binary relations in classical set theory, roles in Description Logic can be classified semantically into symmetric, asymmetric etc. One can directly make such declarations about OWL properties as TBox axioms and enrich the conceptual model this way. And this is again where the beauty of DL and OWL shines. The logical aparatus that you learn in basic discrete math, something that you might use for documentation purposes, is available in a simple declarative software modeling language. Here are the options and a refresher on what they mean:
Some of those role semantics can be expressed using available machinery. For example, the fact that a role
R is functional can be expressed as
≤ 1 R. But transitivity can't. Another such "irreducible" construction available in OWL is
ObjectPropertyChain
which allows you to express role composition. You can say that a chain
of roles that indirectly connects two individuals establishes a
relationship between them. A common example of this is the uncle
relationship which would be defined in OWL like this:
SubObjectPropertyOf(ObjectPropertyChain(hasFather hasBrother) hasUncle)
To sum up, it is common for DL systems to separate the knowledge into a purely conceptual model, sort of like a schema definition, the TBox and actual data which associates individuals to concepts and assigns them roles, the ABox. Reasoning tools tend to use different algorithms and optimization techniques dependending on whether they are dealing exclusively with a TBox or an ABox or a mix of both. The gist of the formalism is the ability to describe complex concepts in terms of simpler ones and the describe individuals in terms of how they are classified and how they relate to other individuals. It is a logic language with no variables all right, but not a propositional one. I've advertised the ability to make non-trivial inferences about the accumulated knowedge, so let's take a look at those now.
Reasoning with Concepts and Roles
There are a few core reasoning problems about the conceptual portion (TBox) of a DL knowledge base stemming from natural questions that one might ask. For example, is a given concept satisfiable (remember, when we say concept here, we may mean a possibly complex logical formula, a full description) in the sense that it is possible to find a model where that concept describes a non-empty set. Another question is whether one concept subsumes another (in OWL terms if a class is a sub-class of another), which can be reduced to satisfiability because:
C
Dif and only if
C
¬Dis not satisfiable.
Another question is if two concepts (or concept formulas) describe the same set
of individuals. And again, this can be reduced to satisfiability by first
observing that two concepts are equivalent if and only if both
C
D
and
D
C
are true. Finally, note that two concepts C and D are disjoint if
C
D
is unsatisfiable. If you think about it a bit, you'd find that all of those
reasoning tasks are reducible to one another. For example, suppose you have an
algorithm for subsumption. You can then determine if C a unsatisfiable by checking if it is subsumed by
.
The satisfiability question is more interesting to tool builders because that's
how tableau algorithms
tend to operate - they try to obtain a contradiction when building a model for
a formula. And it is also sometimes a necessary condition for a whole ontology
to be consistent. But to people, the subsumption question is often the more
interesting one because it can be viewed as implication. If you think of
a concept expressions as logical formulas with one free variable, then concept
subsumption is logical implication in the sense that whenever the sub-concept formula
is true of an individual, the super-concept formula is true as well.
Another reason the subsumption question is interesting in practice is the ability of inference engines to list all named concepts subsumed by a given concept description, thus automatically constructing a conceptual hierarchy out of TBox constraints.
Reasoning with Individuals
Unlike TBox reasoning where we are dealing purely with conceptual
constraints, in the ABox we are stating facts about objects. Something
may be
wrong with a TBox if a concept is unsatisfiable, which simply means that
no
individual can belong to it, which simply means that it's equivalent to
the
bottom concept
.
And there's nothing special about that, there aren't any other
consequences. Usually, when a contradiction is found in a logic
language, it is devastating for the language because it allows one to
prove anything as a consequence. An unsatisfiable concept is a sort of a
contradiction, but it doesn't make an ontology useless because it
doesn't prevent one from creating a model of the set of axioms. That is,
it doesn't prevent one from coming up with a sensible interpretation.
It's just that the sets corresponding to the unsatisfiable concepts will
be empty.
When a TBox has an unsatisfiable concept, it is simply called incoherent. That's an undesirable property, and a knowledge engineer should strive to maintain coherent ontologies. In fact, studying the consequences of incoherence is a topic on its own.
A contradiction involving the ABox however is a different story. It means that it's impossible to find a model for the axioms, i.e. there is no way to interpret them! And this is what defines an inconsistency in DL: an ontology (TBox+ABox) is called inconsistent if there's no model for it. Interestingly, concept satisfiability and consistency have been proven to be equivalent problems! An example of an inconsistency would be asserting that an individual belongs to two disjoint concepts:
Pedestrian(Tom)
Car(H1)
owns(Tom, H1)
Here we've stated that Tom is a
Pedestrian and that he owns the
individual
H1 which we've asserted to be a
Car. According
to our definition of a
Pedestrian above, Tom can only own things that are not
cars. Therefore, a reasoner would infer that
H1∈¬Car and
that's an inconsistency. Note that the inference engine can't tell you
exaclty what you did wrong. If this were a real world example, perhaps the
statement
Pedestrian(Tom) is at fault. But a reasoner won't
complain about it because there's no problem with declaring Tom a pedestrian per se.
While consistency is a natural question to ask, a more practical question is
instance checking which asks if a given individual belongs to a given
concept. Since a concept can be a complex logical formula, this essentially
allows you to ask a logical question about an object. And to check whether
C(a) is true, one needs to prove that if you add it to the
ontology
as an axiom, it leads to an inconsistency. For example to find if a
given car model is an all American green energy car we could ask if it
is an instance of the concept:
∀hasPart.American
(Hybrid
BioDiesel)
Even more fun is the ability to ask for all individuals that belong to a concept. This is known as the retrieval problem. It is akin to querying a database by specifying the desired data's characteristics via a logical expression. Conversely, given an individual one may query for all the named concepts the individual belongs to. That is, we can ask for all the types that individual has been classified under.
What About Data Values
Last time you learned that there are two kinds of OWL properties that an
individual can have: object properties and data properties. In
Description Logic, data properties are introduced by extending the
formalism with concrete domains and further allowing standard
logical predicates (i.e. n-ary boolean functions) over those domains. An
example of a concrete domain is the set of natural numbers with binary
predicates for the comparison operators <, ≥ To make the formalism
work, certain restrictions are imposed on the available set of
predicates for a given domain. However, we won't go into details here
because OWL doesn't allow use of concrete datatype predicates in class
definitions. Thus, it is not possible to say that somebody is allowed to
drink if their
age > 21. So data values in OWL are used
more or less like individuals except they can only appear as role
fillers. When we cover rules later, we will see how to get around this
OWL limitation by using the SWRL (Semantic Web Rule Language).
Reasoning in an Open-Ended World
The economist John Keynes is famously quoted as saying "When the facts change, I change my mind. What do you do, sir?" So it goes for much of (sound) human reasoning. We are quick to draw conclusions, taking shortcuts, making assumptions and faced with new information we rapidly retract our deductions and change our reasoning. The alternative would be to very rarely commit ourselves to a conclusion, say "I'm not sure" most of the time, only infer things that are certain so we don't have the embarassment of being wrong. What's the right attitude? That's the debate between monotonic and non-monotonic reasoning.
In monotonic reasoning, when new axioms are added to the knowledge base, all existing inferences remain unchanged. In other words, knowledge can only grow, deductions are never retracted. If one never makes assumptions that are not explicitly stated, the reasoning will be monotonic. In non-monotonic reasoning, it is possible for new information to cause retraction of previously drawn conclusions. This happens if extra assumptions are made during inference.
Now, one can argue that non-monotonic reasoning is more practical, that's how humans do it after all. Or one can argue that you don't want software to deliberatery make mistakes by making the wrong assumptions. In software one cares about things like reusability, long-term maintenance, safety and context-independence. When you draw conclusions from a set of facts, you don't want to have to do bookkeeping in what context they were arrived at (did we know A at the time or no?). So the pioneers of the semantic web had the debate and went for monotonicity. Since the global semantic web is an open-ended knowledge source, constantly growing and being refined, monotonicity is the way to go. Good. However, that leads to what's argubly the most counter-intuitive aspect of working with OWL DL, especially if you're coming from a software background.
We've seen above the various logical statements that can be made in OWL
2.0. Now, it seems natural to assume that if you don't know whether a
statement
S is true, then you don't know, you can't simply
decide that it's false, right? Well, that's what open-world semantics
say as well. And that's what DL systems generally do: they make the
open-world assumption (OWA): lack of knowledge that
S does not automatically mean
¬S. Assuming otherwise is known as the closed-world assumption (CWA) which enables a reasoning style called negation-as-failure
where failing to deduce something entails its converse. Using
negation-as-failure obviously leads to non-monotonic reasoning because
new facts will invalidate the "failure" part.
Explained like this, the OWA doesn't seem like such a large pill to swallow, it feels fairly natural. It turns out there are surprises and sometimes frustrations when you have spent all your life in a technical environment that operates under the CWA, namely conventional database systems, in particular SQL as well as more traditional logical languages like Prolog. It turns out, adopting the OWA is nothing short of a paradigm shift for the practicing programmer. Let me give you at least one example why and I promise we'll see more later on.
Say you have in the knowledge base
AllAmerican ≡ ∀hasPart.American
American(Engine123)
hasPart(F100, Engine123)
Is
AllAmerican(F100) true? Since the only part that
F100 has is American and since something is
AllAmerican whenver all its parts are made in America, then we'd expect
AllAmerican(F100)
to be true. But this inference can't be made because according to the
open-world assumption nothing prevents a new piece of information to
assert
hasPart(F100, MichelinTires), some time in the
future, i.e. that French-made tires are used on the car. In other words,
information about the entity in question is incomplete. This is unlike
in the classic database world where you'd do a query to list all parts
of the entity, join that with the "MadeIn" table listing where parts
were made and you get the answer. The constraint that we've stated in
the first axiom above will help detect an inconsistency if you assert
both:
AllAmerican(F100)
hasPart(F100, MichelinTires)
But the concept definition itself doesn't provide a sure way to retrieve all its instances. On the other hand, if you define:
American ≡ ∃hasPart.American
madeIn:America
madeIn(Engine123, America)
hasPart(F100, Engine123)
this is a much more constructive definition. It only defines something that is at least part American. Note how DL is capable of dealing with cyclic definitions. Now, if you ask for everything American, you will get both
Engine123 and
F100 in the result set.
In general, problems with OWA arise when a query or an expected
inference rely on the knowledge base somehow having exhaustive
information about how entities related to all other possible entities.
There are a few tricks that one can use to "close" the world by
explicitly adding information or additional constraints to an ontology
with the purpose of forcing certain inferences:
- Listing all individuals explicitly with the enumeration constructor
{...}. That's a way to tell the reasoner that it has complete information about the members of a class.
- Imposing precise cardinality constraints. For example, one could state that a product has no more than, say, 3 parts. Then if all those 3 parts are explicitly listed, a reasoner knows no extra parts are possible and can decide if the product is
AllAmericanor not.
- Stating explicitly that something doesn't have a certain kind of property. For example, one could state that
(¬∃hasPart.¬American)(F100).
- Stating explicitly that something doesn't have a certain property. OWL allows negative property assertions with the
NegativeObjectPropertyAssertionor the
NegativeDataPropertyAssertion. Note that those are syntactic sugar. You can say the same thing using concept complement: {a}
¬ (∃P{b})
All those are valid means to "close the world" and they are used in practice. But one must also keep in mind that the reasoning algorithm is separate from the modeling language. Nothing prevents you from applying non-monotic reasoning with negation-as-failure to DL models in limited and controlled contexts.
UNA - The Unique Name Assumption
To complete our short account of the mathematical foundation of OWL, we will have to take a look at another consequential open-world aspect of DL reasoners - the unique name assumption (UNA) which OWL does not make. The UNA states that distinct names necessarily refer to distinct entities. Recall that names in OWL are URIs, that is identifiers unique within the global namespace of all names in the semantic web. So we are saying here that several different identifiers, unique as they are, may actually identify the same thing. This is again something that we're not used to in classic logic systems or databases where distinct identifiers refer to distinct entities.
Unlike the OWA, the UNA actually makes good sense in the context of Description Logic and it is a natural expectation that a knowledge engineer may rely on. However, OWL does not make that assumption and this is in part due to the global nature of naming in OWL. Everybody can come up with a vocabulary and it would be nice to be able to state post factum when we are talking about the same thing even when we were using a different name for it. In fact there's an axiom for that, called an agreement axiom:
x
y
The agreement says that x and y refer to the same entity so that all facts about x are also true about y and vice-versa. Before you conclude that this is akin to variable assignment and the URIs of OWL individuals are like variables in a programming language, note that this statement is symmetric, it goes in both directions! Agreement is also something that can be automatically inferred by a reasoner as well as a question that a user may ask of a knowledge base. To repeat: a reasoner is free to conclude that two different names, two different URIs are actually refering to the same real world entity. This sort of inference that dabbles with the sacred notion of identity can lead to some rather unexpected inference results. Consider the sensible constraint that every car has exactly one owner:
Car
= 1 isOwnedBy.Person
Now, suppose also that at a certain point in time it is known, asserted in the knowledge base, that
isOwnedBy(H1, Tom). Later, the car identified with
H1 is acquired by Betty so you assert
isOwnedBy(H1, Betty)
as well, yet you forget to remove the assertion about Tom's ownership.
Or, maybe Tom and Betty got married and she became a co-owner of the
car. That should violate our sole ownership constraint, right? Wrong!
For the
reasoner, Tom and Betty are just names referring to an entity and
because names are not assumed to be unique, it happily concludes that
Tom
Becky. Married or not, they may very well object.
Fortunately, getting around that behavior is much easier than with the OWA. There are a few direct ways to dissociate individuals and here are some OWL axioms available (standard accounts for DL don't have shorthand notations for these, but there are ways to encode the knowledge):
owl:DifferentIndividuals(I1, I2, ..., In)states that the listed individuals are all distinct.
owl:DisjointClasses(C1, C2, ..., Cn)states that each pair of classes
Ci, Cj, i≠j, is disjoint, i.e.
Ci
Cj =
.
owl:DisjointUnionOf(C, C1, C2, ..., Cn)states the class
Cis the union of
C1, C2, ..., Cnand furthermore that each pair
Ci, Cjis disjoint, i.e.
Ci
Cj =
. In other words
Cbeing the disjoint union of
C1, C2, ...Cnis the same thing as saying that
C1, C2, ..forms a partition of
C.
Being an exhaustive list of the sub-classes, the
DisjointUnionOf
axiom is a bit like an enumeration but for classes rather than for the
individuals in a classes. So in case you were wondering, when a concept
is
defined through an enumeration of its individuals, say
C = {a,b,c}, that doesn't imply that the individuals in question,
a,b and
c, are different. If they are, you'd have to state it separately with
owl:DifferentIndividuals(a,b,c).
So in the Tom and Betty situation described above, we have several means
to avoid the undesirable inference. Of course we could just declare
that they are different. But we can also have Tom belong to the concept
Male declared as disjoint from the concept
Female.
There may be other indirect ways to refine a model once you discover
such an unwanted inference. Inference engines are often capable of
giving an explanation of a certain inference so you can figure out the
logical steps
that led to it and break the chain somewhere else. In our example, we
may have a relationship
isMarriedTo(Tom,Betty) which may be declared in the TBox to be symmetric, which would
imply
isMarriedTo(Betty, Tom). To fix the problem, we could declare the
isMarriedTo property as irreflexive which would imply
Tom != Betty.
Finally, note that some tools may allow you to set a global parameter to force the UNA, which has the same effect as declaring all individuals to be different. So check your documentation.
Conclusion
Ok, if you've read and understand the above then you know almost all of OWL already. I deliberately stuck with the Description Logic terminology and syntax because I believe it forces one to stay in "math land" and think about OWL from a mathematical logic viewpoint, rather than through the prism of the OO programmer with all the bagage that this entails.
OWL DL is a formalism that merges object-oriented modeling ideas into a mathematical logic that allows you to encode highly-structured knowledge and to make non-trivial inferences from it. One of the skills that you'd need to develop while working with OWL is the ability to formulate questions in terms of logical concept descriptions. And get comfortable with the idea that class constraints are expressed as logical formulas and that sub-classing is logical implication. Don't forget that knowledge is open-ended. And by the way, OWL DL is sound, complete and decidable. This means it only makes true inferences, it makes all inferences and you can't make it loop forever.
Coming Up
In the next and following installments, we'll dive into actual modeling and coding. As a piece of homework, I'd suggest you go through the very detailed Protege tutorial. We will be building an application based on an OWL model and using the standard OWLAPI.
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.) | http://css.dzone.com/articles/domain-modeling-owl-part-2 | CC-MAIN-2014-10 | refinedweb | 5,997 | 51.78 |
Do you want to learn how to develop your very own macOS app that you can be proud of and use it on your personal MacBook? Or maybe you have a stirring passion to start developing on Mac? Then you are at the right place! Here, I will walk you through the steps in developing what could be your first very macOS app with one of the most modern languages, Swift!
Pre-requisites
- Have some interest in programming
- Have some basic understanding of Swift-programming (advantage)
- Xcode 9 installed
- Passion to build a macOS app
What will you learn?
- Basic concepts of macOS development
- How to integrate Alamofire with macOS app to perform network calls
- How to create a drag and drop mechanic
- Some Swift 3.2 syntax
What will we build?
I’m sure you are excited to know what good stuff we will be building! In this tutorial, we will be working on Mac’s main application layer, Cocoa. This layer is responsible for the appearance and user actions’ responsiveness of the app which is also where we will be introducing all our visual elements, networking, and app logics. We will upload our images to uploads.im as it provides an open API for us to use. This will be the end product after going through this entire tutorial,
The user will first be presented with a home screen with instruction saying “Drag and Drop your image here”. Then the user can drag any jpg format image into the app, then the app will present a loading spinner to inform the user that it is uploading the image to server. Once the server respond with success, the user will get a pop-up alert window where he/she can copy URL to clipboard, then he/she can paste the URL anywhere, like on a internet browser to view his/her image from the server.
Enough of talking, let’s get started!
Creating your macOS project
First, let’s launch our Xcode 9 and create your macOS app project call
PushImage. Choose
macOS and
Cocoa App under
Application.
You can follow the settings I put in the next page as follow, then choose a directory of your choice for your project files.
Now that you have your project all setup, I want to take this chance to introduce one of my favourite new feature in Xcode 9, Refactor! If you have used the past versions of Xcode, refactoring of Swift code is not possible. Let’s give it a shot. Highlight
ViewController and go to
Editor->Refactor.
I don’t want to use the default name
ViewController. Let’s change it to
HomeViewController and click
Rename. This will perform a global change to your
filename,
class name and
Storyboard viewcontroller class name, how cool is that!
Going back to our
HomeViewController class, you would have noticed that this controller is a subclass of
NSViewController. If you come from developing iOS apps, you would have straight away notice the difference that we are using
NS and not
UI here. That’s because we are using
Cocoa (AppKit) and not
Cocoa Touch (UIKit). I believe Apple made these 2 distinct frameworks mainly to separate the technologies behind
mobile and
OS. In short,
UIKit is a slimmed down version of
AppKit.
Creating our Home Page
You can download a cloud image icon from this link. Once you have the asset, drag it into
Assets.xcassets and lets rename is to
uploadCloud and move the asset to
2x.
Next, let’s move to our Main.Storyboard to create our view which user will interact with. We will be using Xcode’s beautiful interface builder to design the looks of our home page. In the bottom right container, go to the third item which is an
object library and search for
NSImageView, then drag in into the center of the
HomeViewController view.
Now, click the
NSImageView you just dragged in once, and go to the fourth item, which is the
Attributes Inspector to set the
Image to
uploadCloud. Because in our last step, we have renamed it to
uploadCloud, Xcode automatically registers the name and we can use it directly by inserting the name here without the need to specify its file extensions. One of the wonders of Xcode!
Let’s also increase the width and height a little so that it will look nicer as a whole. Click the fifth item in the right (Utilities) panel. which is the
Size Inspector and increase its width and height to
150x150.
We will also need a text to tell user what they need to do, so now go ahead and search for
label and put in below the
imageView. Again, go to the
Utilities panel, under
Attributes Inspector, set the
Title as
Drag and Drop a .jpg image file here. You can see that the text is totally truncated, let’s increase the width to
300 in
Size Inspector and set the
Text Alignment to be
Center-aligned.
Let’s now align both the
imageView and the
label to the center of the window by first clicking on the
imageView, then hold
CMD and click on the
label. This should let you highlight both, then drag them till you see a cross, which the the guiding lines for you to accurately guage if the components are centered.
The second last UI component we want to add is the
Indicator. Go ahead and search for it and drag it into the window, place it at the center of your label.
The final component we need is our most important piece, the
DragView! We need a
View that act as a droppable area in our app. So following the same ritual of searching for components, search for
NSView and drag it in, then extend it such that it fills the entire window. The
Storyboard ordered the layers from bottom up or
LastInFirstOut concept. So now, our view covers all the other view components. Later on, we will set the view such that it has a transparent background, and it won’t block any view underneath it.
Way to go! That is all the components we needed to add into our
Storyboard, let’s now connect Outlets, which are references the Interface Builder used to connect to a property declared in its
ViewController.
With our
Storyboard as our active window, we can open a separate window showing our
HomeViewController class by activating
Assistant Editor located at the top right.
Holding
ctrl, click on
ImageView and drag it just below our class declaration and let’s call it
imageView. Great! Now your outlet for the
imageView is connected to a property in our class, we can now programmatically adjust its propertise and work with it.
Challenge Time
Now, try doing the same for the
view,
label and the
indicator, let’s call them
dragView,
staticLabel and
loadingSpinner respectively. Your code should look like this at the end.
To get back some space in our window, let’s go back to Standard Editor by clicking the first item at the top right and we will move to our next mission.
Creating our Drag View
Our next mission is really to make our
DragView a proper “drop-off” point for our
.jpg image files. Go ahead and right-click on your root folder and choose
New File. Choose
Cocoa Class and create a new
DragView subclass of
NSView. We will also need to go back to our Storyboard and set our DragView’s class as
DragView.
Then go back to our
HomeViewController and change
NSView! to
DragView!:
If we look closely at NSView, we found out that it actually automatically conforms to NSDraggingDestination protocol which is exactly what we need to make our “drop-off” space.
Before we can use all the draggable methods, we first need to
register our view. Replace the code in the view class with this:
This line of code registers the view for any dragged item thrown inside the app with the file extension of “.jpg”. All we did is registering, our view is not ready to accept files just yet.
Following the NSDraggingDestination documentation, we can conclude that we need these functions to achieve what we want:
So let’s go ahead and add these chunk of code. I will explain what they do :
1 – Firstly, we need to create a
boolean flag call
fileTypeIsOk, defaulted to
false to help us push forward only the right file format of our images. We also create a
acceptedFileExtensions which is an array of acceptable file format in
string.
2 –
draggingEntered function will be called when the file first enter the “drop area”. Here, we will call a function
checkExtension which we will discuss later, to set our
fileTypeIsOk boolean to
true if the file type is of
.jpg or
false if it is not.
3 –
draggingUpdated function is implemented here to get the details of the image. In this case, if the
fileTypeIsOk, we will return the
copy of the image, else it will return an
empty data represented by
[].
4 –
performDragOperation function is called once the user releases his mouse, we will make use of this function to pass the url to our
HomeViewController later.
5 –
checkExtension is our “home-made” function where we check our
drag object, grab the
url of the file coming in, and check if it complies with our
acceptedFileExtensions.
6 – Here, we extend our
NSDraggingInfo which is actually all the senders we see in our
draggingEntered and
draggingUpdated. We added a variable call
draggedFileURL here to reference the url of our image file.
If you run the app now, you should be able to drag in an image file with
.jpg and see a green + sign at your cursor, but not for other file types. Great! Now that we know our app only accepts a specific file type correctly, let’s move on to establishing a communication between the
view and our
controller.
Creating our Delegate
Delegation Pattern is one of the most commonly seen patterns in Cocoa programming. It is like creating a command center to broadcast what
A has done, so now
B should do this. In short, we will be creating these:
- Our command center (DragViewDelegate)
- Function call
didDragFileWith
- View to hold a reference to
DragViewDelegate‘s subscribers and call
didDragFileWith
- ViewController to subscribe to
DragViewDelegateto do something when
didDragFileWithis called in the
View.
So, let’s head back to our
DragView and input this code on top of our class declaration just below
import Cocoa:
We create a delegate protocol here which defines the responsibilities that the delegate wants to command. And here the sole responsibility is when the dragView receive an event call
dragViewdidDragFileWith, the delegate will be called, and subscribers will react. So let’s also create a variable reference for subscribers and put this just after the opening bracket of our class declaration:
We want to immediately inform our
HomeViewController that a correct file is placed, so the best place for our delegate to broadcast will be in the
performDragOperation after the user releases his drag event, and when all the checks are done. So go ahead and add this line of code:
Now let’s head back to our
HomeViewController and extend our class to implement our
delegate method. Go ahead and add these lines of code:
If we run the app now, we will expect to see our file URL being printed in our console, let’s try it!
Hmmm… nothing happens when we drag our
.jpg files in, did we miss out anything? Yes! We need our
HomeViewController to subscribe to our
View‘s delegate. This is a common omissions where developers forgot to add the subscriber, so lets go ahead and fix that. Add this in
viewDidLoad():
After you done that, run the app again and you will see the URL printed. Great Job! You deserved a big pat on your back for coming this far. We are almost there, we can now push our files up to the server!
Integrating Alamofire
Alamofire is a powerful networking library written in Swift. Formerly known as
AFNetworking, it is the most well maintained networking library to date.
Installing Alamofire using CocoaPods
Cocoapods helps to define our project’s dependencies all in one file and it automatically links them to our Xcode project by generating a workspace file. If you have no prior experience with Cocoapods, please check out this tutorial.
We first need to create a
PodFile. You can open up Terminal and navigate to the project directory (
{ROOT}/PushImage). Then run
pod init. Now that our Podfile is created, go ahead and open PodFile and fill them with this code:
Next run
pod install. This will clone the dependencies and you should get Alamofire framework linked to a newly created workspace file. You should see this screen at the end:
Close your current project and from now on we will work on Cocoapod’s newly created
PushImage.xcworkspace.
Way to go! You now have your networking library all set up!
Making our network call to uploads.im
Following the
api document written by Uploads.im, we will be making use the following API to do our
POST just like the example given in the document as well.
upload– URL or image sent by POST method. The system automatically detects that you upload.
So let’s go ahead and import the library:
And then, add these lines of codes in
dragView function:
That’s a lot of codes!!! Don’t be frightened, special thanks to Alamofire, the library provided us with a single
upload function call that allows us to
POST file with multipartFormData, which is a networking method we normally use to upload files. Here, we appended the url of our file, which is the given location of where our file is in string, passed in as a
URL object with parameter name
upload.
The endpoint is appended with
query parameter
format=json to also specify the format response we want. When the server response with
upload success, we grab the
img_url by parsing the JSON response, and print it out. Let’s try it!
Oops! There will be another common error message we may see when we make the first networking call in our apps. It goes something like:
Apple has recently introduced this new ruling where all apps have to communicate through
https protocols. Since we are just experimenting this and making this for personal use, we can perform a workaround.
Head over to
Info.plist at your project directory panel, right click on it and select open as
source code.
Then add these code:
This will bypass the
ATS and allow us to communicate with non-https protocols. Run the app and try to upload another image file! After a few seconds, you should see your file URL uploaded printed in the console! Go ahead and paste it in your browser to see the image on your local machine now loaded from uploads.im server!
Polishing up
We know that our Image Loader is almost done, but we need some additional UX (User Experience) added so that it is more complete.
Previously we talked about our loading spinner, so lets go ahead and implement the logic of our loading spinner to:
- Hide when app starts
- Show and animated when uploading
- Hide and stop animation when uploading finishes or failed
Hide when app starts
Add this in our
viewDidLoad():
Upload Animation
Add them in our
dragView function. Run the app and drag in an image file, when the uploading starts, you should see the loading spinner in action!
Show/Hide Label
We can see that sometimes the
label is obstructing our
- Show when loading spinner is inactive
- Hide when loading spinner is active
Add
staticLabel.isHidden = true after
self?.staticLabel.isHidden = false after
self?.loadingSpinner.stopAnimation(self?.view) after
Run the app again and you should see a beautiful loading spinner non-obstructed!
Pop-up Alert
The last piece of UI component we want to add is our
Alert Box. We will be making use of
NSAlert which is a built-in alert sheet that comes with simple settings that allow us to tweak and present a nice pop-up alert box.
Go ahead and add this function which will present our
NSAlert pop-up box:
Then, go ahead and add it right after
self?.staticLabel.isHidden = false with this line of code:
Run the app now and drag an image in, you should see a nice native pop-up alert box with a button which when you click, it will copy the URL to the clipboard, and you can paste it anywhere for your personal usage!
Recap
So what have we achieved?
- We learnt how to build a macOS app entirely from scratch using Cocoa.
- We learnt how to use Xcode IB to design our UI elements.
- We learnt how to create our custom view class.
- We learnt how to design delegate pattern.
- We learnt how to install external library with Carthage.
- We learnt how to use Alamofire to upload image.
- We learnt how to use open source API of uploads.im.
- We learnt how to use NSAlert.
This is generally how creating a macOS app is like. There are a lot more that I did not cover, and it is up to you to further explore and make meaningful and useful products for people all around the world to use!
Wrapping Up.
If you have any questions about the tutorial, please leave your comment below and let me know.
For the sample project, you can download the full source code on GitHub. | https://www.appcoda.com/macos-image-uploader-app/ | CC-MAIN-2021-17 | refinedweb | 2,945 | 70.43 |
9 780954 703516 SAAD WA ZIKR
SAADAND THE REMINDER
Published by K. M. Malik
Meem Connection
The information presented on this book may be copied and distributed free of charge,provided the contents of the material are not altered in any way and a copy of thisnotice is included to show the owner of the copyright.
km0040@hotmail.com
ISBN 0-9547035-1-0 FOREWORDThis book is dedicated to Allah, Ar Rahman, Ar Raheem the Compassionate, the Mercifuland His Rasool, Muhammad Sal Allahu Alaihi Wa Sallam.
This book follows the previous one, which was Ayn Al Miftah – The Visual Key. The name forthis book Saad Wa Zikr – Saad and the Reminder, has been chosen from the Quraan. Everytime the Arabic letter Saad is used as Haroof Muqattaat (abbreviated letter used in theopening verse of some of the chapters in the Quraan), the word Zikr – Reminder follows inthat sentence. Similarly the ‘learning of the knowledge’ is associated with the human chest,which in Arabic is called Sadr. The chest is the place where all the mysteries unfold. Theword Sadr also starts with the Arabic letter Saad.
The 99 Sifaat - Attributes of Allah also known as Asma ul Husna – the Beautiful Names, havebeen described here. May Allah accept this work in His service and remove the veils ofignorance from us all, and may Allah unfold the mysteries in our Sadr with Zikr Allah, which isbased on the 99 Sifaat - Attributes of Allah. Aameen.
Ya Allah! Bless Nazanin Montazemi for all her time and effort in getting this book ready andfor the contribution of the typed Surat Ta Haa Dua (prayer). Aameen.
Ya Allah! Bless Mohammed Latif for all his time and effort in getting this book ready.
Ya Allah! Bless Prof. Ashiq Hussain Ghouri for all the handwritten Duas in this book.Aameen.
Ya Allah! Bless my parents and all the believers and accept this work. Aameen. BISMILLAH HIR RAHMAN NIR RAHEEM
ALIF 1
Allahumma Salli Ala Muhammadin Wa Ala Alay Muhammadin Kama Sallaita Ala Ibraheema Wa Ala Alay Ibraheema Innaka Hameedum MajeedAllahumma Barik Ala Muhammadin Wa Ala Alay Muhammadin Kama Barakta Ala Ibraheema Wa Ala Alay Ibraheema Innaka Hameedum Majeed
INTRODUCTION
This book has been written in such a way that it will guide the seeker to Allah. Normally the99 Attributes of Allah start with the personal Name, Allah, which is the Ism Zaat, and finish onthe ninety-ninth Attribute As Saboor.In this book we are trying to get back to Allah, therefore the book starts from Allah’s Attribute,As Saboor, and finishes at the Ism Zaat, personal Name, Allah.For those who already ‘know’ Allah, they can read this book from the right as in Arabic, Urduor Persian. That is they can start with the Ism Zaat, Allah, and finish on Allah’s Attribute AsSaboor. Those who are seeking Allah can start from the left as in the Latin languages fromAllah’s Attribute As Saboor and finish at the Ism Zaat, Allah.No matter which direction the reader approaches this book, each one shall find something ofinterest to him or her, Inshaa Allah.
Allah has ninety-nine Names, that is, one hundred minus one, and whoever believes in theirmeanings and acts accordingly, will enter paradise; and Allah is Witr (One) and loves the‘Witr' (odd numbers). [Sahih Al Bukhari]
8 Allah! There is no god only He! To Him belong the Most Beautiful Names. Allahu La ilaha illa Huwa Lahul Asmaa Ul Husna [Quraan: Ta Haa, Chapter 20]
May Allah enlighten all the Muslims and may Allah forgive all of us our sins. Aameen.
1 99 – AS SABOOR
67 (Khidhr) said: "You will not be able to have patience with me! [Quraan: Al Kahf, Chapter 18]
This incidence took place, when Prophet Musa met Hadhrat Khidhr . Even after havingspoken to Allah, Musa was still in need of a lesson in patience. If Hadhrat Musa , evenwith the honour of being Allah’s Messenger, needed a lesson in patience, then we, theordinary people, are in an even greater need of learning patience.In nature, Allah has given us another example. We have all heard the expression that: A dogis a man’s best friend. If we do not feed the dog for a day or more, the dog will still respect itsmaster. The dog will not bite its master because of starvation. The dog will not turn againstits master. If we admonish the dog for a wrong action, the dog will still respect its master. Itwill not bark at the master.If we are deprived of a single meal, we turn against our Master who is our Rabb (Lord). Webecome impatient. We can learn a lesson from the dog. If a dog is faithful to its master, thenwhat is wrong with the human beings that we become unfaithful to our Master?The first lesson we all need to learn is Patience – Sabr! Why? Because Allah is As Saboor –The Patient One and we also have to emulate the quality of being patient.There are many instances in which patience is required. We need to be patient when we arehungry. We need to be patient when we are in pain. We need to be patient when we are ill.We need to be patient when we suffer a loss. Whatever the reason for distress, we need tobe patient. Patience is a noble quality.When we transgress against Allah, Allah is patient with us. Perhaps we might turn back andask for forgiveness. Allah gives us plenty of chances to repent or turn back to the right pathso that we can ask Allah for forgiveness. Allah does not like haste. Haste is a quality ofShaytaan (Satan). Shaytaan makes us act in haste.
2 99 – AS SABOOR
45 Seek help in patience and prayer; and truly it is hard except for the humble-minded,46 Who know that they will have to meet their Rabb (Lord), and that to Him they arereturning. [Quraan: Al Baqara, Chapter 2]
From the above reference, in verse 45 we learn that patience can only be achieved byhumbling ourselves. And the verse that follows clearly states that: Who know that they willhave to meet their Rabb and to Him they are returning. This is what we are trying to achievewith this book, we know we have to meet our Rabb and we have to return to Him.There are two ways of returning to our Rabb. One way is through death when we leave theworld physically. The other way is to die before death. That is to kill the worldly desires.
Abu Bakr came from his house at As-Sunh on a horse. He dismounted and entered themasjid, but did not speak to the people till he entered at Aisha’s and went straight to Allah'sRasool who was covered with Hibra cloth. He then uncovered the Prophet's face and bowedover him and kissed him and wept, saying, "Let my father and mother be sacrificed for you.By Allah, Allah will never cause you to die twice. As for the death which was written for you,has come upon you." [Sahih Al Bukhari]
There is something very interesting in the above Hadees. The last two sentences are veryimportant. By Allah, Allah will never cause you to die twice. As for the death which waswritten for you, has come upon you.…never cause you to die twice. Why did Hadhrat Abu Bakr As-Siddiq say those words?What he meant was that no person can experience death twice. What he indicated was thatAllah’s Rasool, Muhammad had already given up worldly desires while he was walkingon this earth in a physical form. What he indicated was that Prophet Muhammad hadalready experienced death before death came. What Abu Bakr As-Siddiq indicated wasthat Muhammad , the Beloved of Allah, had already met Allah while he was still walkingon this earth.Nobody can meet Allah before death, unless of course we die (or kill our worldly desires)before death comes to us. Only then can we meet Allah while we are still walking on thisearth. The last sentence in the above Hadees clarifies the normal death, which is decreed byAllah even while we were in our mother’s womb.To clarify the two deaths, the first death is to die before dying, that is when we leave alonethe worldly desires and we are not attracted to them while we live amongst the people ofearth. The second death is where we physically depart from the earthly community and livewith the community of Burzakh, the spirit world.How do we achieve the death before death? By practicing and achieving patience. When wehave patience! Then we are not bothered by hunger. Then we are not bothered by insults.Then we are not bothered by possessions. Then we are effectively dead to this world ofillusions and we are alive in Allah. That is when Shaytaan can longer influence us.Hadhrat Adam was driven out of heaven for one mistake and he had to learn to be patientfor 330 years. Then, and only then, was Prophet Adam admitted back to heaven into thepresence of Allah. The average human life span is much shorter in the present age. Eventhen we are impatient. Therefore we should start with the lesson on patience and work ourway back to Allah. That is, let us start by learning the most difficult lesson in patience firstand work our way back to Allah. Let us die before death comes to us. Let us kill our desires
3 99 – AS SABOOR
for this world of illusions. When we achieve that, we can return to Allah even while we walkon this earth in a physical form.
The difference between Sabr Patience and Saboor Patient is just oneletter Waw . Therefore to practice patience, to become patient we need to have and showlots of love and kindness towards Allah’s creatures and creation. Allah treats every humanbeing whether Muslim or non-Muslim equally. Therefore we must learn from that.What is Sabr? Sabr is whatever happens in the Sadr chest to keep it within ourselves and be thankful to our Rabb in all conditions. When we add love and kindness toSabr then maybe we can reflect some of the qualities of As Saboor.Since we started this article by mentioning one of Allah’s Messengers, namely, Musa , thenlet us finish with another reference pertaining to Prophet Musa which is quite apt:
I also ask Allah, my Rabb to expand my chest, ease my task for me and remove theimpediment from my writing and speech so that the readers and the listeners mayunderstand. Aameen. May Allah give us all patience in each and every condition. Aameen.
MEDITATION
The person who reads Ya Sabooru 101 times everyday, will be saved from every hardshipand Allah will hold back the tongues of the enemies and the envious people, Inshaa Allah. Ifa troubled person reads Ya Sabooru 1111 times, Allah will relieve that person and give him /her peace of mind, Inshaa Allah. Furthermore, meditation on Ya Sabooru will make the
4 99 – AS SABOOR
person patient in times of difficulty. Any task that is taken on by the one who meditates on YaSabooru, Allah will ensure that the person completes that task
5 98 – AR RASHEED
10 When the young men fled for refuge to the cave and said: Our Rabb (Lord)! Give usmercy from Your presence and shape for us the right way in our plight [Quraan: Al Kahf, Chapter 18]
The men mentioned in the above reference are also known as the Companions of the Cave.They asked Allah for mercy and the right way or the right path. The paths are many. In everysituation we are presented with different choices. Out of those choices we have to seekAllah’s help in being guided to the right path or choice. Then Allah will make the decision forus. In the above reference, Allah made the decision for the companions of the cave to sleepfor 309 years. Allah is capable of whatever He pleases. Allah can do whatever He wishes.Therefore the companions of the cave are among those who are rightly guided.There is one very important lesson to be learnt here. Therefore pay close attention. Do youknow what that lesson is? Your answer can be either “Yes!” or “No!”We have to ask the question: “When do we need to be guided?” The answer is: “When we donot know!” And, when do we not know?To answer that, we have to consider two examples. The first example can be somethingsimple like: Where is the city of Madinah? Either we know the answer or we do not know. Noargument. No ‘ifs’ and ‘buts’. There is a clear concise answer to this question.The other example can be more difficult, for instance: Will the Day of Judgment take placetomorrow? The reason for choosing this question has a purpose. The purpose will be madeclear right here, Inshaa Allah. Today, in this day and age of technological advancement the“Muslims” can neither determine nor decide amongst themselves the day of Eid celebration.Usually there are two or three different days of Eid being celebrated in the same city. Why isthat? Is it because we are not being guided to the right path?Here is an example of a truly guided person whom we should try to emulate:
6 98 – AR RASHEED
Rasool Allah took an oath that he would not visit his wives for one month. But when twenty-nine days had elapsed, he went to them in the morning or evening. It was said to him, "YaRasool Allah! You had taken an oath that you would not visit them for one month." Hereplied, "The month can be of twenty nine days." [Sahih Al Bukhari]
“The month can be of twenty nine days.” In that, there is a great lesson for us. Allah madethat month last for just 29 days instead of 30.Let us come back to the lesson that we were learning…Even the answer to the simple question like: ‘Where is the city of Madinah?’ will be spoken inthe next moment, or in other words, the answer will be spoken in the future. The future hasnot yet come into existence. Therefore, when Allah’s Rasool said: “The month can be oftwenty nine days”, Allah loved His Beloved so much that Allah made that month last foronly 29 days! Since Prophet Muhammad was rightly guided.Since tomorrow has not come into existence, we have to learn a lesson from what we havealready covered here. The lesson here is Allah our Rabb can make a ‘thing’ or Shay
come into existence with His knowledge and make that ‘thing’ fall into the constraints of aDairah or circle.The ‘thing’ does not necessarily have to be an object. The ‘thing’ can be anything. Forexample, the ‘thing’ can be a path that does not yet exist, or a day that has not yet come intoexistence.And finally here is a reference from the Quraan confirming that:
May Allah guide all the Muslims to the right path. Aameen.
7 98 – AR RASHEED
MEDITATIONThe person who cannot make up his or her mind about something, should read YaRasheedu 1111 times. Inshaa Allah, the answer will come either in a dream or the person’sheart and mind will incline towards what is better for that person. The person who keepsreciting Ya Rasheedu everyday, will find all the obstacles and difficulties removed from thatperson’s path and all his or her tasks will be made easy, Inshaa Allah.It is also stated that the person who keeps meditating on Ya Rasheedu, whomever he ‘looks’at, Allah will guide the latter
8 97 – AL WAARIS
89 And Zakariya, when he cried to his Rabb (Lord): “My Rabb (Lord)! Do not leave mechildless, though You are the best Inheritor.” [Quraan: Al Anbiyaa, Chapter 21]
Prophet Zakariya asked Allah, his Rabb for an heir. He asked his Rabb for a child. AndAllah granted Hadhrat Zakariya his prayer and gave him a son who was named Yahya .Why did Prophet Zakariya cry to his Rabb for an offspring? Why do we need children? Theanswer is given here:
6 "(One that) will represent me and represent the posterity of Yaqoob (Jacob); and make himmy Rabb (Lord) one with whom You are well pleased!"…12 (To his son came the command): "Yahya! Take hold of the Book with might": and Wegave him wisdom even as a youth.13 And pity (for all creatures) as from Us and purity: he was devout14 And kind to his parents and he was not arrogant or rebellious.15 So Peace on him the day he was born the day that he dies and the day that he will beraised up to life! [Quraan: Maryam, Chapter 19]
The lesson here is to ask Allah for our children to be good. A child is a blessing from Allah,whether the child is a boy or a girl. Allah sends every newborn child, with his or hersustenance. Then it becomes the duty of the parents to look after that child under Allah’sguidance. If we teach our child the right path and good manners, that child becomes ablessing for us. If we do not care about our child and the child turns to evil actions, that childbecomes an embarrassment for us. In other words our children are our representatives andthey will represent us in either a good way or a bad way. We, with Allah’s help, have to teachour children wisdom. And what is this wisdom? The answer is already given in verses 13 and14 in the above reference.
9 97 – AL WAARIS
Allah created everything to serve Him. When we serve Allah, our Rabb will reward us for ourservice. There are two types of reward. Allah gives us one kind of reward in this world. AndAllah also gives us another kind of reward in the next world. The reward of this world is goodchildren. For every good deed a child does, others will speak well of the child and mentionthe parents of that child with respect. Allah hears these words and rewards the child as wellas the parents. For every evil deed a child does, others will speak of the child with contemptand the names of parents will be dragged through dirt.A good child will pray to Allah for his / her parents. A good child will ask Allah for forgivenessfor his / her parents. When we die we leave whatever we have as inheritance to our childrenaccording to what is stated in the Quraan. And they in turn will leave that to their children andso on. Ultimately, everything will be given up, and given back to Allah, the ultimate Inheritor.
23 And it is We who give life and who give death. It is We who remain the inheritors. [Quraan: Al Hijr, Chapter 15]
Allah is Al Waaris the Inheritor who inherits everything. The moral here is to leave behindgood mannered children who are caring towards the creatures. They should learn that fromtheir parents, who in turn learnt it from their parents and so on. Provided we leave behindgood children they in turn will endeavour to do the same for their children and eventually allof us, together with our good deeds will return to Allah . For every good child or deed thatwe leave behind, our Rabb will give us the Samar fruit, reward, goodness of ourchildren, our prayers and our good deeds, Inshaa Allah.And finally what is this reward? This reward is what has been written in the Quraan, Chapter19 verse 15:Peace on him the day he was born the day that he dies and the day that he will be raised upto life (again)!May Allah make our children wise, caring towards others, firm in purity and devout Muslims.Aameen.
10 97 – AL WAARIS
MEDITATIONThe person who keeps reciting Ya Waarisu 1111 times everyday, will find all his / her taskswill come to .
11 96 – AL BAAQEE
76 "And Allah does advance in guidance those who seek guidance; and the things thatendure. Good deeds are best in the sight of your Rabb (Lord) as rewards and best in respectof eventual returns." [Quraan: Maryam, Chapter 19]
Allah tells us in the above reference what this enduring thing may be. Good deeds are theenduring or lasting thing! Good deeds are sometimes tangible and at other times they arenot. Tangible things can be Masjids where people will pray. Those who have contributedtowards the building of the Masjid will be rewarded long after their death. Non-tangible thingscan be prayer, fasting, charity in the Name of Allah, or even a smile, a kind word that wouldcheer up someone who is unhappy. Even a glass of water for a thirsty person can beconsidered non-tangible. All these non-tangible good deeds are recorded and these will bepaid back on the Day of Judgment. These latter deeds are those that last.
Allah's Rasool said, "While a man was walking he felt thirsty and went down a well and drankwater from it. On coming out of it, he saw a dog panting and eating mud because ofexcessive thirst. The man said, 'It is suffering from the same problem as mine. So he filledhis shoe with water, caught hold of it with his teeth and climbed up and watered the dog.Allah thanked him for his (good) deed and forgave him." The people asked, "Ya RasoolAllah! Is there a reward for us in serving animals?" He replied, "Yes, there is a reward forserving any living thing." [Sahih Al Bukhari]
Allah’s Rasool said: “Yes, there is a reward for serving any living thing.”
12 96 – AL BAAQEE
Any living thing is not necessarily just our own family. Any living thing is not necessarily justan animal. Any living thing is not necessarily just trees and plants. In fact any living thing isdefinitely not just the Muslims. Is it? There is a lesson in that last statement in the aboveHadees. When we take off our blinkers and look at the wider picture, we realise that it isAllah who has created every living thing. In serving Allah’s creation, we are basicallyreceiving reward from Allah. That reward may not be tangible in this world of illusion, but itwill definitely remain, endure and last for us to collect in the next world. Let us look at anotherexample from the Quraan about the good deeds that remain, or endure, or last.
26 And Ibraheem said to his father and his people: “I do indeed clear myself of what youworship.”27 “(I worship) only Him who made me and He will certainly guide me.”28 And he left it as a word to endure among those who came after him that they may turnback (to Allah). [Quraan: Az Zukhruf, Chapter 43]
What is it that Prophet Ibraheem left behind that endures to this day? Is it the Kaaba inMakkah that Prophet Ibraheem left behind which endures? No! Because the Kaaba hasbeen rebuilt many times and even Hadhrat Muhammad said that the Kaaba is not builton the same foundation as that of Ibraheem . So what is it that Prophet Ibraheem leftbehind that endures to this day?It is the Kalimaat or word or prayer we say in Salaah after Darood / Salawaat Ibraheem. It isthe prayer of Prophet Ibraheem , which has endured to this day and that prayer will last tillthe Day of Judgment. Every Muslim, in every country, every day, repeats the prayer ofProphet Ibraheem which is shown here:
40 "My Rabb (Lord)! Make me one who establishes regular prayer and also among myoffspring. Our Rabb (Lord)! Accept my prayer.41 "Our Rabb (Lord)! Forgive me, my parents and believers on the day that the Reckoningwill be established!" [Quraan: Ibraheem, Chapter 14]
Here is the beauty of all this, unlike the Kaaba which we cannot build on because we wouldnot be permitted to do so, we can certainly build on the prayer of Prophet Ibraheemstriving to achieve the same foundation or Imaan or faith as that of Ibraheem , individually.And if we can achieve even one-fortieth Imaan or foundation of Prophet Ibraheem , Allahwill guide us to good deeds that will endure long after we are dead and buried, Inshaa Allah.
All the creation has been created by none other than Allah . We can only achieve Qurb
nearness to Allah through knowledge and good deeds that we leave behind. These
13 96 – AL BAAQEE
good deeds will last long after we are gone. And I ask Allah with the Kalimaat left behind byHadhrat Ibraheem :My Rabb (Lord)! Make me one who establishes regular prayer and also among my offspring.Our Rabb (Lord)! Accept my prayer. Our Rabb (Lord)! Forgive me my parents and (all)believers on the day that the Reckoning will be established! Aameen.
MEDITATIONNo person can become everlasting by reciting Ya Baaqee. Only Allah is the Everlasting. Theperson who keeps reciting Ya Baaqee 1111 times everyday, will find that Allah will keep thatperson free from all kinds of loss and Allah will accept all the good deeds of that person andmake them everlasting in the spiritual .
14 95 – AL BADEE
117 The Originator of the heavens and the earth! When He decrees a thing, He says to itonly: “Be!” And it is. [Quraan: Al Baqara, Chapter 2]
Why bother with creation? The answer is in the preceding verse for the above reference:
116 They say: "Allah has begotten a son"; Glory be to Him. To Him belongs all that is in theheavens and on earth; everything renders worship to Him.117 The Originator of the heavens and the earth! When He decrees a thing, He says to itonly: "Be!" And it is.118 And those without knowledge say: "Why does Allah not speak to us, or a sign come tous?" So said the people before them words of similar sort. Their hearts are alike. We haveindeed made clear the signs to any people who have firm faith. [Quraan: Al Baqara, Chapter 2]
Every creation has been created to worship Allah. Every creation worships Allah in its ownway. Only we do not ‘see’ how these different creations worship Allah.For example, the sun, the moon, the earth and all the planets have been created to worshipAllah. How? The planets have been created to orbit the sun. The sun has been created toprovide sunlight to the planets. The sun does not extinguish of its own free will. The planetsdo not stop in their orbits of their own free will. Each one is obeying the command of Allah.The angels are created out of light. They obey Allah.The jinn are created from smokeless fire. And the humans are created from clay. Both thejinn and human have been created to worship Allah. But we rebel! Why? Because the jinnand the human are susceptible to Shaytaan. We fall into the traps set by Shaytaan.In the above reference from the Quraan we find the mention of the false and baselessassociation of a son to Allah. They say: "Allah has begotten a son"; Glory be to Him. To Himbelongs all that is in the heavens and on earth; everything renders worship to Him.
15 95 – AL BADEE
There is a simple solution to this argument. How can a Creator who is not created bephysically related to a creation? The two cannot be physically related. Then we are told thateverything in the heavens and earth belong to him. In other words everything in the heavensand earth are Allah’s creation. We all belong to him in the sense that Allah is our Creator.Allah is not limited in any way, but all creation is a limitation. Even the heavens and earth arelimited. So are we.There is another form of beauty in the above quote from the Quraan. We cannot observe theheavens and earth without being created. If we did not come into existence we would notexperience the creation. Finally here is another reference from the Quraan:
101 The Originator of the heavens and the earth! How can He have a child, when there is forHim no associate, when He created all things and is Aware of all things? [Quraan: Al Anaam, Chapter 6]
Allah brings the creation into existence within the constraints of Dairah a circle or
limitation with His Knowledge . Why are we here? Believe it or not, we are here to seekknowledge. Only by being created can we gather knowledge that will be useful for us in the
next world. From a thought form the creation becomes Ayn visible when Allahcommands, “Be!” In our case we have to associate the knowledge we gather with what wesee in this world. As it was stated in Ayn al Miftah, for every visible thing in this world, there isa hidden or spiritual meaning. We can only understand the spiritual side if we use ourknowledge to discern or observe what we see. Seeing without knowledge is of no use.Knowledge without seeing is also of no use. We have to associate the knowledge with whatwe see.A good example is when we go to school we are taught to conduct experiments in physics,chemistry or biology. We observe the outcome and then we make conclusions on what wehave observed. Similarly, we must be observant every waking hour and minute. We must tryand understand whatever we see. We must try and understand what is the reality behindwhat we are observing. With observation we will understand something about the creationand hopefully advance in knowledge, Inshaa Allah.There is another subtle point that needs to be mentioned here. If Allah did not create us wewould not be here. If we were not here, then we would not have the opportunity to observeeither the heavens or the earth. Neither would we be able to gain knowledge. As far asassociating knowledge with observation or observation with knowledge is concerned thatwould also be nonexistent. It is a sad fact that the majority of the people having been giventhe chance to exist by Allah, fail to observe and gain knowledge. May Allah, the Originator ofthe heavens and earth teach us some of the knowledge of whatever we observe. Aameen.
16 95 – AL BADEE
TOTAL 86 TOTAL
MEDITATIONThe person who keeps reciting Ya Badeeu 1111 times everyday, will find that all difficultiesand / or worries will be overcome, Inshaa Allah. The person who reads Iftahu Aftahu YaBadee ul Aajaaibi Bil Khairi Ya Badeeu 1200 times for 12 days will achieve whatever thatperson has made the intention for or set out to do, within 12 days, Inshaa Allah. However,this Zikr must be continued for 12 consecutive .
17 94 – AL HAADEE
52 And thus have We inspired in you (Muhammad) a Spirit of Our command. You did notknow what the Scripture was, or the Faith. But We have made it a light whereby We guidewhom We will of Our servants. And you do guide to the right path.53 The path of Allah, to Whom belongs whatever is in the heavens and whatever is in theearth. Do not all things reach Allah at last? [Quraan: Ash Shura, Chapter 42]
The example here is like that of one candle being lit. That original candle in turn lit tens,hundreds, thousands, millions of other candles. Each candle giving light. Each candle lightingother candles. Yet the original candle is still lit for eternity like a beacon guiding others. Inother words, Prophet Muhammad is that original candle. Allah was Al Haadee – theGuide for Muhammad . Prophet Muhammad became Haadee - Guide for all theMuslims, since we have been left the Quraan – The Path of Allah and the Sunnat – The Wayof Muhammad . But why do we need a Guide?The answer is in the above reference. We all need to know the right path to Allah. Why?It is because everything in the heavens and on earth belongs to Allah. Because our end isalso a return to Allah and as it is stated in the above reference: Do not all things reach Allah?Whether a person believes in Allah or not, in the end we will all reach Allah where we will bequestioned. Just as we guide our children how to behave in front of people, so must we learnhow to behave before Allah. However, there is a subtle point here, which we mustunderstand. We only need to behave in front of people in their presence. But Allah is aware
18 94 – AL HAADEE
of every move, our every action, our every thought, so we must learn guidance so that webehave ourselves all the time whether we are in the company of people, or all alone.Because Allah is forever present. What is this Guidance?For Muslims the Guidance is what has been revealed in the Quraan and the Sunnat. Thereare five pillars in Islaam. These are:
There are five prayer times in a day. There are five sensory systems in the human being.These are the avenues that lead to guidance.
…So they will come to me and say, 'Ya Muhammad! You are Allah's Rasool and the last ofthe Prophets, and Allah forgave your early and late sins. Intercede for us with your Rabb(Lord). Don't you see in what state we are?' "Rasool Allah added, "Then I will go beneathAllah's Throne and fall in prostration before my Rabb (Lord). And then Allah will guide me tosuch praises and glorification to Him as He has never guided anybody else before me. [Sahih Al Bukhari]Even in the above Hadees it is mentioned that Allah will guide Muhammad to suchpraises and glorification to Him as He has never guided anybody else before him. With thatguidance Prophet Muhammad will intercede for us on the Day of Judgment. And finallylet us finish with another quote or two from the Quraan:
36 Is Allah not enough for His servant? But they try to frighten you with others besides Him!For such as Allah leaves to stray there can be no guide.37 And such as Allah guides there can be none to lead astray. Is Allah not exalted in power,Rabb (Lord) of Retribution? [Quraan: Az Zumar, Chapter 39]
Allah is Al Haadee the Guide and we have to seek Hidayat –Guidance from Him as to howto behave in this world. Whatever Hidayat we learn in this world will be beneficial in the next
world. When we return to Allah , and we are standing before Allah we can expect HisMercy. Allah is Daeim the Everlasting. He will always exist. Therefore we cannot avoid our
meeting with Him on the day of reckoning. Allah has full knowledge of how we behavedin this world. Therefore we must also learn knowledge as how to behave in the proper way inthis world so that we may be forgiven. The secret is to ask Allah for guidance. Only thendoes Allah guide. May Allah guide all the Muslims. Aameen.
19 94 – AL HAADEE
MEDITATIONThe person who keeps reciting Ya Haadee 1111 times everyday, will find complete guidanceand that person will also receive understanding of lsla .
20 93 – AN NOOR
35 Allah is the Light of the heavens and the earth. The similitude of His light is as a nichewherein is a lamp. The lamp is in a glass. The glass is as a shining star. Kindled from ablessed tree, an olive neither of the east nor of the west, whose oil would almost glow forththough no fire touched it. Light upon light, Allah guides to His light whom He will. And Allahspeaks to mankind in allegories, for Allah is knower of all things. [Quraan: An Noor, Chapter 24]
Light is not light without the darkness. The visible is not visible without the invisible. Manifestis not manifest without the hidden. Good is not good without the evil. Heaven is not heavenwithout the earth. East is not east without the west.The point we are making here is that everything has an opposite. If there were no opposites,there would be nothing but Allah. Neither you nor I would be here! Allah has createdeverything in pairs.Allah is the Light of the heavens and the earth. In both the heavens and earth the Light isfromcontaining oil. A lamp has a wick that is lit to burn that oil contained within it. A lamp supplieslight.The lamp is in a glass. Glass is a fragile material. Glass is translucent. Glass is transparent.We can see through glass! That is glass does not get in the way of the vision. We ignore the
21 93 – AN NOOR
presence of glass when we look through a window. Therefore we can see the lamp throughthe glass.The glass is as a shining star. In this verse we are told that the glass is like a shining star.The glass surrounding the lamp usually shines when the lamp is lit. Here the opposite to thelast paragraph is also true. Just as vision can see through the glass unhindered, likewise thelight can shine through the glass unhindered.Kindled from a blessed tree, an olive neither of the east nor of the west. A tree takes years togrow. It begins from a seed. It grows into a plant. Then it becomes a strong tree. Then thetree produces fruit. In this example the fruit is the olive. But this tree is neither of the east orwest. If we observe a tree, it is planted in a particular place. It does not move. But thisparticular tree is neither of the east nor of the west. Therefore this tree is either a heavenlytree or it moves!Whose oil would almost glow forth though no fire touched it. The oil in the lamp is lit. Yet firehas not touched it. It generates light.Light upon light, Allah guides to His light whom He will. And Allah speaks to mankind inallegories, for Allah is knower of all things.A man of knowledge once said: “The heavens and earth cannot contain Allah, and yet Allahlives in the heart of a true believer.” Now if we look at the entire verse, we find that the Lightreferred to in the above verse is Knowledge. The tree neither of the east or west is thehuman. The heavens and earth cannot contain knowledge, yet the human being can containknowledge of heavens and earth. Where is this light referred to in the above verse? It is as aniche (a recess) where there is a lamp. The human heart is in a niche in the human body.The heart is lit from a blessed tree neither of the east or west. The red Indians call the treesthe standing people. The human being is not rooted in one place. The heart pumps withoutbeing lit and no batteries are required!The heart is the place of revelation of the mysteries, if the Light of Allah shines in there. Theheart is the place of Zikr Allah, if the Light of Allah shines in there. And as Mawlana AbulNoor Mohammad Bashir so beautifully wrote: “In this day and age we keep hearing of peoplehaving heart attacks. If there is no Zikr Allah in a heart, what do you expect? It is bound tostop!”The heart or the lamp needs fuel. The fuel or oil is the Zikr Allah. With Zikr Allah, the lamp islit without being touched by fire. The human body becomes a blessed tree neither of the eastnor of the west. Light upon light, is achieved by that tree in the form of knowledge uponknowledge. Every branch of knowledge is based on certain principles or foundation. And theknowledge is built on that principle or foundation. Our foundation is Islaam and theknowledge is the Quraan and Sunnat of Prophet Muhammad . Allah guides to His lightwhom He will. Finally a reference from the Quraan:
1 Alif Laam Ra. A Book which We have revealed to you in order that you may lead mankindout of the depths of darkness into the light by the leave of their Rabb (Lord) to the way of(Him) the Mighty in Power, the Praiseworthy! [Quraan: Ibraheem, Chapter 14]
If we look at the opening of the above verse we find we have Alif Laam Ra . What is
missing from that? It is the letters Noon and Waw to make the Name AnNoor (the Light). How? Because we are told further in the above reference …that you maylead mankind out of the depths of darkness into the Light by the leave of their Rabb…
22 93 – AN NOOR
Light or En-lighten-ment only comes if we leave alone the hatred. It is only through loveand kindness that we can attain enlightenment. But after that we need the leave orpermission of our Rabb to be truly enlightened. May Allah enlighten all the Muslims.Aameen.
MEDITATION
The person who keeps reciting Ya Nooru 1111 times everyday, that person’s heart will lightup with the Light .
23 92 – AN NAAFEE
96 Those against whom the word of your Rabb (Lord) has been verified will not believe,97 Even if every sign was brought to them until they see the grievous penalty.98 If only there had been a community (of all those that were destroyed of old) that believedand profited by its belief as did the people of Yunus (Jonah). When they believed Weremoved from them the torment of disgrace in the life of the world and gave them comfort fora while. [Quraan: Yunus, Chapter 10]
In this example, the profit is used in connection with belief. Belief in what? Belief in Allah, HisAngels, His Books, His Messengers! What is the profit of believing in Allah? Allah removesfrom the believers disgrace in the life of this world. Allah gives us comfort for a while in thisworld. What is the penalty or loss in disbelief? The loss in disbelief is destruction.In order to gain profit, we need favourable conditions. Profit and favourable conditions gohand in hand. If the conditions are unfavourable, we will be at a loss. Allah is the one whocreates the favourable conditions for a profit. It is also Allah who creates the unfavourableconditions for a loss. We must believe in Allah and acknowledge that all profit and losscomes from Him.Now if we look at the wider picture, Allah has created all the conditions that are favourablefor human existence on this earth. If we abuse these favourable conditions, we suffer fromthe wrath of Allah. Or in the words of the above reference verse 97, the disbelievers will seea grievous penalty.Since we have mentioned the ‘favourable conditions’ on the earth, let us step back evenfurther and consider everything in existence. We are told further in the Quraan:
24 92 – AN NAAFEE
101 Say: "Behold all that is in the heavens and on earth"; but neither signs nor warners profitthose who do not believe.102 Do they then expect (anything) but (what happened in) the days of the men who passedaway before them? Say: "Expect then! I too will expect."103 In the end We save Our Messengers and the believers, thus it is fitting on Our part thatWe should save the believers. [Quraan: Yunus, Chapter 10]
In the above reference we are told, Behold all that is in the heavens and on earth. What doesit mean to behold?To behold is to consider. To behold is to contemplate. To behold is to discern. To behold is toobserve. To behold is to witness. What do we need to consider, to contemplate, to discern, toobserve or to witness? Observe everything that is in the heavens and earth.Allah has created all that which is in the heavens and the earth as a favour for us, to profitfrom, with the exception of what has been forbidden for the believers in the Quraan. Since itis Allah the One who has created everything in the heavens and the earth. Thereforeeverything in the heavens and the earth are under the command of Allah. Allah is more thancapable of making the heavens and the earth either favourable or unfavourable. If and whenAllah makes the conditions unfavourable, there is one guarantee. What is this guarantee?This guarantee is stated in the above reference verse 103. That is, no matter howunfavourable the conditions become in the heavens and the earth, Allah will save all the truebelievers.Finally, let us finish with another example from the Quraan:
16 Say: "Who is the Rabb (Lord) of the heavens and the earth?" Say: "Allah!" Say: "Do youthen take protectors other than Him which have no power either for Nafaa (good) or for harmto themselves?" Say: "Are the blind equal with those who see? Or is the darkness equal tolight?" Or do they assign to Allah partners who have created (anything) as He has created sothat the creation seemed to them similar? Say: "Allah is the Creator of all things. He is theOne the who subdues." [Quraan: Ar Raad, Chapter 13]
We hear people say, he / she was in the right place at the right time when something goodhappens! Or, he / she was in the wrong place at the wrong time when something badhappens! Who creates the favourable conditions for the right place and the right time? Orwho creates the conditions for the wrong place and the wrong time? Allah creates favourableconditions for profit and it is Allah who creates unfavourable conditions for a loss.Allah An Naafee the Favourable creates the favourable conditions for the believers. Thisworld and the next world, the heavens and earth and everything within are the creations ofAllah . Everything in the heavens and earth, are created for our Faidah Profit with the
exception of what is forbidden by Allah in the Quraan. Allah has given us eyes to see.
25 92 – AN NAAFEE
Therefore the blind are not equal to the seeing. Neither is darkness equal to light. So howcan we associate partners to Allah? Only Allah is the Creator of everything.
MEDITATION
The person who keeps reciting Ya Naafeeu after boarding a ship or an aircraft will be safefrom all kinds of disaster or unfavourable conditions, Inshaa Allah.The person who reads Ya Naafeeu 1111 times everyday, Allah will create favourableconditions for success for any permissible venture, Inshaa Allah. A married man who readsYa Naafeeu will have good children who will be good Muslims, Inshaa Allah. .
26 91 – ADH DHAAR
52 To Him belongs whatever is in the heavens and on earth and religion is His forever. Willyou then fear any other than Allah?53 And whatever goodness you have is from Allah. When you are touched by distress, youcry to Him for help.54 When He removes the distress from you behold, some of you attribute partners to theirRabb (Lord) [Quraan: An Nahl, Chapter 16]
Why does Allah the most Merciful cause distress to His creation? Allah causes us distress inorder to test our faith. Allah causes us distress in order to test our patience. Allah causes usdistress in order to separate the true believer from the one who just performs lip service.Allah causes us distress in order to make us strong so that no matter what happens, we willnot leave His religion. If we leave His religion then we are the ones that will be at a loss andin distress.However, there is a very subtle lesson to be learnt. If we do not suffer distress, we cannotappreciate comfort. If we do not suffer distress, we will become weak. If we become weak,we will perish at the slightest distress or infliction.It is better to bear the distress in this world. The distress that will be caused to thedisbelievers in the next world will be unbearable. At least in this world we have theopportunity to turn towards our Rabb and ask Him to remove our distress. In the next world,there is no such avenue open to us for relief from distress.
27 91 – ADH DHAAR
But as we are told, in the above reference: When He removes the distress from you behold,some of you attribute partners to their Rabb. How do we associate partners to our Rabb?As it was stated in the section An Naafee, it is Allah who creates favourable conditions forprofit and it is Allah who creates unfavourable conditions for a loss. Likewise, no person, nojinn, no angel, no star, no planet can cause distress. Each of the latter acts according to thewillby this medicine. Al Hamdu Lillah, Allah sent such a person for my assistance.There is another side to being inflicted by distress. That is shown here in the followingHadees:
Rasool Allah said, "No fatigue, nor disease, nor sorrow, nor sadness, nor hurt, nor distressbefalls a Muslim, even if it were the sting he receives from a thorn, but that Allah expiatessome of his sins for that." [Sahih Al Bukhari]
From this Hadees we learn that whenever a believer is inflicted with distress or hurt orsadness or sorrow or disease or fatigue, Allah removes some of the sins of a believer. Allahis so generous that He is looking for an excuse to forgive us our sins. For that we have topay a small price. That small price is in the form of distress or hurt etc. But, if Allah is sogenerous, why does He not forgive our sins without causing us distress?The answer is quite simple. It is human nature to devalue anything that is given for free. It ishuman nature not to appreciate something until it is lost. For example, good health is a giftfrom Allah. We cannot appreciate good health unless we have experienced illness. However,we must be patient under such circumstances in order to be forgiven some of our sins and atthe same time we must be thankful to Allah in all conditions. We must praise Allah in healthas well as in sickness. It is Allah who brings about the distress and it is only Allah who canrelieve us from that distress. How do we ask Allah to relieve us from distress? One of thebest Dua or prayer in times of distress is that of Prophet Ayub :
83 And Ayub (Job) when he cried to his Rabb (Lord) "Truly distress has seized me and Youare the Most Merciful of those that are merciful." [Quraan: Al Anbiyaa, Chapter 21]
From the above reference we can see and appreciate how Allah relieves a person fromdistress. First we must call upon Allah, our Rabb. And then we must praise Him. In thisexample Prophet Ayub called his Rabb and said to his Rabb, “Truly distress has seizedme and You are the Most Merciful of those that are merciful."Allah is Adh Dhaar the Distresser. All forms of distress are from Allah. And only Allahour Rabb - Arham ur Rahimeen can relieve us from that distress.
28 91 – ADH DHAAR
MEDITATIONThe person who reads Ya Dhaaru 1111 times everyday, Allah will protect that person fromvisible and invisible forms of distress, and that person will achieve nearness to his / herRabb, .
29 90 – AL MAANEE
55 And what is there to prevent mankind from believing now that guidance has come to themand from praying for forgiveness from their Rabb (Lord), unless (they wish) the ways of theancients are repeated with them or they should be confronted with the doom. [Quraan: Al Kahf, Chapter 18]
In the above reference we are told: What is there to prevent mankind from believing…The answer is not that obvious at first glance, it is very subtle! We have to look at the versesthat follow and deduce the answer from there. The verses that follow the above referenceare:
56 We only send the Messengers to give good news and to warn. But the unbelieversdispute with false argument in order to refute the truth and they treat our signs as a jest asalso the fact that they are warned!57 And who does more wrong than one who is reminded of the signs of his Rabb (Lord), thenturns away from them forgetting the (deeds) which his hands have sent forth? We have setveils over their hearts so that they should not understand this and over their ears deafness.And though you call them to guidance, even then will they never accept guidance. [Quraan: Al Kahf, Chapter 18]
From verses 56 and 57 we can deduce that Allah in His infinite Mercy sent Messengers towarn the people. Therefore the choice for belief of disbelief is given to the individual. If therewas no such choice, then there is no point in sending any Messengers! Here is the subtlety,as soon as we start to argue in order to refute the truth, or if we mock the truth, Allahprevents us from understanding the truth. The truth can only be ‘seen’ or understood if weapproach it with an open mind. If we approach the truth with an open mind, then Allah willgive us the understanding required to analyse the truth. We must not be hasty in drawing ourconclusions or in refuting the truth immediately. Remember the first lesson we learnt was As
30 90 – AL MAANEE
Saboor. Therefore we must be patient with the process of understanding. Inshaa Allah thenAllah will not prevent us from believing the truth.Which reminds me of numerous occasions when someone in difficulty, approached mybrotherthen. This is the state of the Muslims! May Allah forgive us from such utterances and mayAllah prevent us in future from such utterances.Allah is very forgiving therefore we must hasten towards repentance. Then, there have beennon alsoguides them to the right path. Allah removes the veils from their hearts and ears so that theybegin to understand. Islaam is not just for the Muslims. It is for all beings.Then there is another category of Muslims who prevent non-believers from doing Zikr Allah.Who or what gives them that right? How can any Muslim not give Zikr Allah to a disbelieverin distress so that they too can benefit from it and come to Islaam after receiving guidancefrom Allah!Now if we continue from the above reference verses 56 and 57, we are told:
58 But your Rabb (Lord) is the Forgiving, Full of Mercy. If He were to call them (at once) toaccount for what they have earned then He would have hastened their punishment. But theyhave their appointed time beyond which they will find no refuge.59 Such were the populations We destroyed when they did wrong, but We fixed anappointed time for their destruction. [Quraan: Al Kahf, Chapter 18]
Allah, our Rabb is the Forgiving, Full of Mercy. Allah gives everyone an opportunity to turntowards the truth so that He may remove the veils that prevent the non-believers fromunderstanding the truth. If they still do not believe, then the punishment awaits at theappointed time and not a moment before.Let us finish with one more example from the Quraan:
75 (Allah) said: "Iblees! What prevents you from prostrating yourself to one whom I havecreated with My hands? Are you proud, or are you one of the high (and mighty) ones?"76 (Iblees) said: "I am better than him. You created me from fire and You created him fromclay." [Quraan: Saad, Chapter 38]
In this example Iblees or Satan was asked what prevented him from bowing down to HadhratAdam . In reality it was Allah who prevented him from bowing down! How? The answer isin the next verse, where Iblees did not even try to understand the creation of Prophet Adam . He just looked at the visible form and decided that he was more superior to Adam . Hadhe thought out the creation of Adam and realised that Allah had created Adam with Hishands. And Allah had breathed into Adam His breath then he would have complied. Ibleeson the other hand had neither of these qualities. Iblees would have realised the superiority ofAdam over him. Since Iblees did not have an open mind, Allah prevented him fromunderstanding the superiority of Adam over Iblees. Iblees was hasty. No patience!
31 90 – AL MAANEE
We have come back to where we started this article. We must have an open mind when itcomes to learning Islaam. We must not be hasty in making quick decisions over what is thetruth and what is not.Allah is Al Maanee the Preventer. The Preventer is none other than Allah . Allahprevents those who are hasty and lack patience and those who mock His signs andrevelations from seeing the Noor the light. That light is the real vision and that vision is ilm
or knowledge. Behind every visible thing, there is a hidden meaning. May Allah preventus all from being hasty and keep us all on true guidance. Aameen.
MEDITATIONThe person who reads Ya Maaneeu 1111 times everyday, Allah will prevent any hatred orquarrel between married couples, and Allah will create love and understanding betweenthem, Inshaa Allah. The person who reads Ya Maaneeu for any permissible need orrequirement, that person will achieve that .
32 89 – AL MUGHNEE
28 You, the believers! The idol worshippers are unclean. So do not let them, after this year oftheirs, approach the Sacred Masjid. And if you fear poverty, Allah will soon enrich you if Hewills out of his bounty. Allah is knower, wise. [Quraan: At Tawba, Chapter 9]
From the above reference we can see that Allah has the means to enrich anyone in anywaythat He may wish. However, there are two forms of enrichment. Firstly there is theenrichment in the financial form. Most people only understand the financial form ofenrichment. Allah enriches financially whomever He wills.Prophet Muhammad explained the second form of enrichment: “Enrichment is not fromwealth but from heart.” Since a wealthy person can be a miser, that person might not spendthe money. Therefore a wealthy person may not necessarily be an enriched person!Whereas the person who is generous, bountiful, charitable, hospitable, open-handed is theone who is really enriched by Allah the Enricher. There is one other quality which should bementioned that is explained in the Quraan in the verses preceding the above reference:
25 Allah helped you to victory in many places and on the day of Hunayn when you werepleased with your large number but they availed you nothing. The earth for all that it is widedid constrain you and you turned back in retreat.26 But Allah did pour His calm on the Rasool and on the believers and sent down forces thatyou could not see. He punished the disbelievers. Such is the reward of disbelievers.27 Then afterward Allah will relent toward whom He will; Allah is Forgiving, Merciful. [Quraan: At Tawba, Chapter 9]
33 89 – AL MUGHNEE
When the people were pleased with their large number, it was of no use because theybelieved that they will win the battle by overpowering the enemy. They were relying on thewealth in numbers rather than on wealth of belief in the heart.How did Allah enrich them? Allah poured His calm on the Rasool and the believers andsent down forces that they could not see. Basically, Allah enriched them with belief in Allahand not in their large numbers. Allah enriched them with calmness, by giving them peace ofmind. Peace of mind is also a form of enrichment. This second form of enrichment is the onethat should be understood by most people because this is the true form of enrichment. And inverse 27 in the above reference we find that Allah will turn toward whom He will, because Heis Forgiving and Merciful.
32 Marry those among you who are single or the virtuous ones among your slaves male orfemale, if they are in poverty Allah will enrich them of His bounty. Allah is All Embracing,Knower. [Quraan: An Noor, Chapter 24]
Looking at the above reference, how will Allah enrich them? Allah will provide the marriedcouples with children. Each child born will bring his or her own sustenance which Allah willhave written for the child. Through the blessing of the child the parents will be enrichedwhere the whole family will be sharing the food, shelter and most importantly love for eachother. Whereas the slaves mentioned in the above verse will be further enriched by gainingtheir freedom and being treated with respect as a member of the family. That is how Allah willenrich them.Every form of enrichment is from Allah, Al Mughnee the Enricher. A Mu_min is a firmbeliever in Allah. Allah, Al Mughnee - the Enricher will bless the Mu_min by pouring his calm
to give the believer peace of mind and send Ghayb unseen, hidden forces. These hiddenforces are angelic created from the Noor light. When the light shines in the heart of a true
believer, the knowledge descends, that the only true Enricher is none other than Allah.
Noon 50 Ya 10 TOTAL 1100 TOTAL
34 89 – AL MUGHNEE
MEDITATIONThe person who reads Ya Mughnee 1111 times everyday, Allah will enrich that personmaterially and spiritually, from the visible and the invisible, .
35 88 – AL GHANEE
5 For those whose look forward to the meeting with Allah the term (appointed) by Allah issurely coming, and He is the Hearer, the Knower.6 And if any strive they do so for their own souls, truly Allah is free of all needs from allcreation. [Quraan: Al Ankabut, Chapter 29]
Allah is free of all needs from all creation. Allah is Self Sufficient. Whatever good we do it isfor our own souls. It is not because Allah needs us, or our good deeds! The lesson here isthat Allah is the Self Sufficient and we are not. We have to strive to do good deeds for ourown souls. If Allah does not need our good deeds then why do we need to do good deeds?The answer is simple. If we do not do any good deeds, after death our souls will be incontinuous turmoil. If we do not do any good deeds, we will suffer eternal pain and torture. Itwill be extremely difficult to escape from that eternal torture. We will be weighed down withthe ‘heaviness’ of our evil deeds. Now let us look at the reason for doing good deeds. Againwe need to look at the verses following the above reference:
7 Those who believe and do good deeds from them We shall blot out all evil in them and Weshall reward them according to the best of their deeds.8 We have enjoined on man kindness to parents, but if they force you to join with Me (inworship) anything of which you have no knowledge, then do not obey them. You have toreturn to Me and I will tell you all that you did.9 And those who believe and do good deeds We shall admit them to the company of therighteous.
36 88 – AL GHANEE
Referring to verse 7 above, if we do good deeds, Allah will blot out all evil in us. What doesthat mean? As stated above, evil deeds will cause ‘heaviness’ or ‘darkness’ on our souls.That is what will be weighed on the Day of Judgment. For every good deed, Allah will removesome of that weight from our souls, so that the soul becomes light. Now if we look at the nextverse Allah tells us to be kind to parents. Why?When we were born, we were helpless. Allah placed love and kindness in the hearts of ourparents so that they looked after us. Our parents taught us how to look after ourselves, thatis to clean ourselves, dress ourselves, help ourselves to food when we are hungry. One ofthe reasons Allah tells us to be kind to our parents is because our parents did their best tomake us self sufficient in looking after ourselves to the best of our ability, all with Allah’spermission. And finally another example from the Quraan:
64 To Him belongs all that is in the heavens and on earth, for truly Allah, He is the SelfSufficient, the Praiseworthy.65 Have you not seen how Allah has made subject to you all that is on the earth and theships that sail through the sea by His command? He withholds the sky from falling on theearth except by His leave: Allah is Kind Merciful to humans. [Quraan: Al Hajj, Chapter 22]
In the above reference we are told that everything in heavens and earth belongs to Allah whois Self Sufficient. Then in verse 65 there is a message for us the creation. What is thatmessage?Allah has created everything on earth for us. Allah has made everything on earth for ourservice. In this example, the ship that sails through the sea and the sea are all obeyingAllah’s command. However Allah is giving us a hint. What is that hint?Allah is not going to send us the ship from heaven! It is not because Allah is not able to dothat. Allah can do whatever He wills as we are told in the Quraan, Al Maaida Chapter 5 verse114.
114 Jesus the son of Mary said: "Allah our Rabb (Lord)! Send us from heaven a table set(with food) that there may be for us for the first and the last a feast and a sign from You. Giveus sustenance for You are the best Sustainer.115 Allah said: "I will send it down for you. And if any of you disbelieves after that I willpunish him with a penalty such as I have not inflicted on anyone among all the peoples. [Quraan: Al Maaida, Chapter 5]
That is when Prophet Isa (Jesus) asked Allah to send down a table with food from heavenso that everyone can have their fill. And Allah did send that. But look at the condition thatwas imposed for sending a table! There is no room for disbelief after Allah provides. Ifanyone disbelieves after that, the punishment will be such that which has not been inflictedon anyone.But in the case of Prophet Nuh (Noah) Allah guided him to build a ship for himself andthose that Allah wanted to save from the flood. We have to learn to be a little self-sufficient,
37 88 – AL GHANEE
and build ‘the ship’ ourselves with the knowledge that Allah has given us. Allah, the Kind, theMerciful has created everything on earth so that we may become self sufficient to a certainextent. We should praise Allah for being so generous. We should praise Allah for giving usthe chance to utilise His gifts on earth to our advantage. We should praise Allah for makingus a little self-sufficient. Instead we abuse the gifts given to us by Allah on the earth. And wecomplain about insignificant things. And this is confirmed in the following verse from theprevious reference:
66 It is He who gave you life will cause you to die and will again give you life. Truly man is amost ungrateful creature! [Quraan: Al Hajj, Chapter 22]
In reality, Allah, Al Ghanee the Self Sufficient wants us to become self-sufficient. Allahwants us to see the Light of his creation. Allah wants us to utilise that Light to seek
knowledge so that we become self-sufficient. May Allah enlighten us all and make us allself-sufficient to the best of our ability. Aameen.
Noon 50 Ya 10 TOTAL 1060 TOTAL
MEDITATIONThe person who reads Ya Ghaneeyu 1111 times everyday, Allah will bless that person’swealth and that person will become self-sufficient to a certain extent, Inshaa Allah. Aphysically or spiritually sick person who reads Ya Ghaneeyu and blows on his / her entirebody will be cured, .
38 87 – AL JAAMEE
8 "Our Rabb (Lord)! Do not let our hearts deviate after You have guided us but grant usmercy from Your presence. You are the Bestower.”9 "Our Rabb (Lord)! You are the one that will gather mankind together on a day about whichthere is no doubt. Allah never fails in His promise." [Quraan: Al Imraan, Chapter 3]
Let us first look at verse 8 in the above reference and try and see the connection betweenthat verse and the verse that follows it. Would you believe that both the verses are connectedwith gathering?When a person’s heart deviates from anything the person will say: “I am not sure,” or “I am intwo minds!” What that means is that the person’s thoughts are not gathered. That person’sthoughts are wandering. To make a firm decision we need to gather all our thoughts togetherand make the decision. Similarly once we have been guided, we have to gather all ourthoughts and stand firm on our belief in Allah. Mental concentration can only be achieved ifour thoughts are not wandering but gathered together on the subject at hand.Moving on to the next verse, Allah will gather mankind on the Day of Judgment. That is notdifficult for Allah. Whatever Allah intends, Allah makes the intention and says: “Be!” And it is.And remember that the same Allah announced the following:
39 87 – AL JAAMEE
Notice the name of the chapter! The analogy here is that the Quraan was revealed over aperiod of twenty-three years. Yet we have the same Quraan that was recited by HadhratJibraeel to Hadhrat Muhammad who in turn recited the same Quraan to his followersduring his time. Allah collected the Quraan over a period of twenty-three years without losinga single letter from the verses. This was proven in the article on the Letter Noon in the bookAyn Al Miftah. There are 6,236 verses in the Quraan. Collecting all the letters of 6,236 versesis not an easy task for us mere mortals. And even after more than 1400 years we still havethe same Quraan in our possession. Only Allah could do that, and He did! Allah has shownus practically that He is capable of gathering every letter in the Quraan over a long period oftime from 23 years to 1421 years. The other interesting point is that the Attribute Jaameeequates to 114. That is the exact number of chapters in the Quraan. Allah said that He willgather the Quraan. And He equated the number of chapters in the Quraan to the numericalvalue of His Attribute Al Jaamee. Then how can there be any doubt that Allah will gathermankind on the Day of Judgment! Let us finally look at another example from the Quraan:
87 Allah! There is no god only He. He will gather you together on the Day of Judgment aboutwhich there is no doubt. And whose word can be truer than Allah's? [Quraan: An Nisaa, Chapter 4]
First let us consider the last sentence in the above verse: And whose word can be truer thanAllah's? Now let us refer to the first reference in this article where we find in Chapter 3 Verse9: Allah never fails in His promise.There is a lesson for us in these two references. Since Allah will gather us on the Day ofwhich there is no doubt, Allah will also gather every word that we spoke. What did we speak?We spoke sentences! We spoke words! We spoke letters! If Allah has proven to us beforeour very own eyes, that He has gathered the Quraan over 23 years. And then Allah haspreserved those letters of the Quraan collected over 23 years even after 1424 years, thenhow can it be difficult for Allah to collect our words spoken over an average life of 70 yearsfor thousands of years? It is easy for Allah to gather us, and also our words on the Day ofJudgment. The Quraan did not come down from heaven in paper form did it? The Quraancame as spoken words! The Quraan has only been recorded on paper for our benefit! Thelesson is that if we make a promise, we must endeavour to fulfil it. Otherwise we will bequestioned about those unfulfilled promises.Now let us go back to the above reference Chapter 4 Verse 87. Again we are told that Allahwill gather us together on the Day of Judgment. The interesting point here is that the chapteris called An Nisaa or The Women.We were first non-existent. Then Allah, Al Jaamee the Gatherer created us in the womb
of our mother. Allah gathered all the necessary building blocks required to create a humanbeing. And that human being was created from Maa water. When we were born or when
we arrived into this world we took on a visible shape or a visible form. Not only that, butAllah keeps our entire body gathered together so it does not fall apart. Therefore, if Allah cando all that, if Allah can gather us out of nothing, if Allah can keep the components of our bodygathered together during our physical life, then what is so difficult about gathering us asecond time? It is easy for Allah to gather us together whenever He wills!
40 87 – AL JAAMEE
MEDITATIONThe person who reads Ya Jaameeu 1111 everyday, will start to understand the hiddenmeanings behind the visible forms, because Allah will make that person gather the hiddenmeanings behind the visible, Inshaa Allah. The person who has been separated from hisfamily or friends should also read Ya Jaameeu, that person will be reunited with them, InshaaAllah. If a person has lost something then he / she should recite Ya Jaameeu, the lost thingwill turn .
Updated
41 86 – AL MUQSIT
9 If two parties of believers fall into a quarrel, then make peace between them. But if one ofthem transgresses against the other then fight against the one that transgresses until itcomplies with the command of Allah. If it complies then make peace between them withjustice and be equitable. Allah loves the equitable.10 The believers are brothers. So make peace between your two brothers. And fear Allah sothat you may receive mercy. [Quraan: Al Hujurat, Chapter 49]
Allah wants us to make peace between believers who quarrel. Allah wants us to fight anyone of the believers who transgresses the limits set by Allah. Allah wants us to be just,equitable and fair.Allah is the one who is Al Muqsit, the equitable and fair. Allah wants us to emulate this qualityof fairness. Allah wants us to be even handed. We should not bring personal feelings intosettling a dispute between two parties of believers. Allah does not want us to take sidesbetween two believers. The only side we should take is that of Allah and His RasoolMuhammad . If one party transgresses the limits set by Allah, we should fight them untilthey comply with the command of Allah. Then we should endeavour to settle the disputebetween the quarrelling parties. Why?The answer is in the next verse. All the believers are brothers. In reality, all of humanity isone family! Are we not all descendants of Hadhrat Adam and Hadhrat Hawwa (Eve)?But as far as the above reference is concerned, Allah is telling us how to deal with thebelievers. Therefore we must be fair and impartial because if we are inclined towards either
42 86 – AL MUQSIT
party due to personal preference or personal reasons then Allah will hold that against us. Wemust fear Allah.Since we mentioned that even the disbelievers are really part of the one and same humanfamily, from the same ancestors, how do we deal with them? Do we then bring personalfeelings into settling their dispute? Can we incline towards the one party or the other? Theanswer is: No! Allah tells us about the disbelievers and how to deal with them in thisreference from the Quraan:
42 They are listeners of falsehood, devouring anything forbidden. If they do come to you,either judge between them or decline. If you decline they cannot harm you in the least. If youjudge, judge in equity between them. Allah loves the equitable. [Quraan: Al Maaida, Chapter 5]
Even with the disbelievers we have to be impartial. We must not incline towards either party.We must not bring personal feelings into settling their disputes. We can however decline tosettle their disputes without any harm from them or from Allah.The irony is that the Muslim nations and their so-called believing leaders when they fall intodispute amongst themselves they seek the help of non-Muslims in settling their disputes.When was the last time that any leaders of quarrelling nations whether believers ordisbelievers asked the leader of a believing nation to settle their disputes?The task of being equitable, impartial and fair is not an easy one. Most of us start to makejudgments on people at first glance or meeting. We make judgments on a person’s looks. Wemake judgments on a person’s appearance. As the saying goes: Never judge a book by itscover. Unfortunately, we do judge a book (person) by its cover (looks).So coming back to being impartial and equitable, we must remember that we are dealing withour own brothers and we must not take sides with either party whether believers ordisbelievers. The only side we are allowed to take is that with Allah and His RasoolMuhammad . Allah is Al Muqsit the Equitable. Therefore when we have to assume therole of settling a dispute between two parties we have to be a Mu_min (believer). We mustnot take sides, because the analogy is like that of Qiyamat the Day of Judgment. Our ownlimbs and organs will give evidence on our behalf before Allah. We must listen withattention to both sides without making preconceived judgments, just as we will hear our limbsand organs on the Day of Judgment. Our intentions must be pure without seeking anypersonal or worldly gain. We must be mindful that Allah is present and aware. May Allahguide us all to be impartial and fair in dealing with everyone. Aameen.
43 86 – AL MUQSIT
MEDITATIONThe person who reads Ya Muqsitu 1111 times everyday will be protected from thewhispering of Shaytaan, and Allah will enable that person to deal equitably with .
44 85 – ZUL JALAALI WAL IKRAAM
45 85 – ZUL JALAALI WAL IKRAAM
Bounty. Even the disbelievers will agree that life exists on this earth because of the climaticconditions, oxygen, water, air, etc. Although they will not attribute the existence of theseconditions to a Supreme Being! They will set up these ‘climatic conditions’ as the solecontributors to the existence of life. Whereas we the believers, say that these conditions existbecause of Allah’s Bounty and not because they just happened to be there.Therefore we exist in order to experience Allah’s Jalaal (Majesty) and at the same time thankAllah for His Karam (Bounty). Allah the Majestic provides us with numerous bountifulconditions for our existence on this earth.
77 Then which of the favours of your Rabb (Lord) will you deny? [Quraan: Ar Rahman, Chapter 55]
We cannot deny any of the favours of our Rabb! Therefore we must thank Allah our Rabb,and call upon Him with His Beautiful Names often.
78 Blessed be the Name of your Rabb (Lord) possessor of Majesty and Bounty. [Quraan: Ar Rahman, Chapter 55]
Allah the Possessor of everything in heavens and earth and all that is in between createdthe heavens and earth out of love for the creation so that we should praise Allah ourCreator. La ilaha illa Hu There is no god only He. Allah is Al Jalaal the Majestic like ahidden treasure waiting to be known. There was La Shay nothing before Him, only Allahand there will be La Shay nothing afterwards when everything will perish. Only the Wajuh Aspect of Allah will abide. Therefore we must not waste any time hesitating. We musttestify: La ilaha ill Allah There is no god only Allah, while we have the chance. We mustthank Allah, Al Ikraam the Bounteous for His Karam Generosity towards His creation.After all Allah is the Rabbil Alameen Lord of the worlds. And Allah sent His BelovedMuhammad to show us the way to thank Allah and attain nearness to Him.
46 85 – ZUL JALAALI WAL IKRAAM
LETTER
VALUE 30 1 30 3 30 1 6 700 LETTER Laam Alif Laam Jeem Laam Alif Waw Zal
LETTER VALUE 40 1 200 20 1 30 1 6 LETTER Meem Alif Ra Kaaf Alif Laam Alif Waw
TOTAL = 1100
MEDITATIONThe person who reads Ya Zul Jalaali Wal Ikraam 1100 times everyday, Allah will bestowhonour and respect on that person and Allah will be even more generous towards that .
47 84 – MAALIK UL MULK
113 Thus have we sent this down an Arabic Quraan and explained in there in detail some ofthe warnings in order that they may fear Allah or that it may cause them to remember.114 Then exalted be Allah the real King! Do not hasten with the Quraan before its revelationto you is completed but say "My Rabb (Lord)! Advance me in knowledge." [Quraan: Ta Haa, Chapter 20]
In the previous chapter we were told that Allah is the Majestic. Now we come to the King – AlMaalik. A king is only a king if there is kingdom. Allah is the King and everything in existence,visible and invisible is His Kingdom. Since everything is in Allah’s Kingdom, He is the ownerof everything and therefore Allah is able to do whatever He likes in His Kingdom.Therefore, even the Quraan belongs in His Kingdom. Allah sent the Quraan in Arabicbecause that was His decision. We must learn to recite the Quraan in Arabic because that isthe language chosen by Allah, and that is the language that Allah preferred over all otherlanguages. Then we are told: Do not hasten with the Quraan before its revelation to you iscompleted but say: "My Rabb (Lord)! Advance me in knowledge."
48 84 – MAALIK UL MULK
The Quraan belongs to Allah. We belong to Allah. Therefore, Allah took the responsibility ofcompleting the revelation of the Quraan to His Beloved, Muhammad . That is what itmeans to be a True King. Allah the True King takes on the responsibility of everything in HisKingdom. Allah the True King takes the responsibility of everything for all His creation. Someof the responsibilities are of feeding, watering, physical growth and intellectual development.No one besides Allah is capable of providing all that. The other side of this is that Allah doesthat without expecting anything in return! In the case of an ordinary king, the king expectssome sort of taxes and loyalty for looking after his subjects. Disloyalty to a human king iscrime punishable by banishment from the kingdom, or imprisonment or worse. But Allah, theTrue King, looks after all creation regardless of their loyalty to Him and He is aware that thecreation cannot leave His Kingdom and go anywhere else! The loyalty will only bequestioned on the Day of Judgment. But while we are in this life, Allah provides for us withoutquestioning our faith, regardless of our colour, race or creed. Therefore the only True King isAllah and none other.It is short sightedness on the part of disbelievers that they do not believe in Allah. Since Allahis fair towards all His creation in this world, the disbelievers find no reason to believe in Allah.All their needs are provided for even when they disbelieve. They do not realise that Allah ispatient and fair to His subjects. But Allah did send His Messengers to warn the people ofwhat awaits them in the next world if they do not believe in Allah. And Allah states clearly inthe Quraan:
115 "Did you then think that We had created you in jest and that you would not return back toUs (for account)?"116 Therefore exalted be Allah the Real King! There is no god only He the Rabb (Lord) ofthe throne of honour. [Quraan: Al Muminoon, Chapter 23]
When we deal with each other we are polite to each other and say: “Thank you!” for everylittle thing. Good manners do not cost anything. Then why is it so difficult to say thanks toAllah the True King who has given us countless blessings? We only have to move ourtongue and say: Al Hamdu Lillah – All praise is for Allah. It does not cost us anything to saythat. Just by moving the tongue, Allah will be lenient on us on the Day of Judgment, InshaaAllah.When people approach an ordinary king, they are courteous. But when it comes to showinggood manners before Allah, they are insolent. Even in the animals created by Allah there areexamples for us to follow. Every animal, when it comes to drinking water, bows its headbefore Allah. We should learn from that. There is nothing wrong in bowing our head to Allahespecially when He is the Real King who does not need us, yet we need Him.Only Allah is the True Maalik ul Mulk Zul Jalaali wal Ikraam – Allah is the Owner ofSovereignty, possessor of Majesty and Bounty.Once Prophet Muhammad heard someone praying with the following words: AllahummaInni Asaluka Bismik al Azeem il Azam il Hannaan il Mannaani Maalik ul Mulki Zul Jalaali walIkraam. Prophet Muhammad said, that person had prayed to Allah with Ism Azam – theGreatest Name. The person who prays to Allah, calling upon Allah with that Name, hisprayers will be accepted. Whatever that person asks for from Allah, he will receive.The Real True Maalik King is none other than Allah who provides for all the creation forall the needs. The only requirement for this provision from the True King is that we move our
49 84 – MAALIK UL MULK
Lisaan tongue and thank and praise Him for all His Karam Generosity which He
bestows on every living thing. Al Hamdu Lillah All praise is for Allah who guided us through
the blessed Lisaan tongue of His Beloved Muhammad . The words that wererepeated by Muhammad were recorded in the in the form of the Quraan which has beengiven to us as a gift from Allah. And that Book starts with the letters Alif Laam Meem.Al Hamdu Lillah – All praise is for Allah. La ilaha illa Huwa Rabb ul Arshil Kareem There isno god only He the Rabb (Lord) of the throne of honour, the One who sent Rasool al Kareemwho left us the miracle of Quraan al Kareem. Wal Hamdu Lillahi Rabbil Alameen.
LETTER VALUE 20 30 1 40 LETTER Kaaf Laam Alif Meem LETTER VALUE 20 30 40 30 1 LETTER Kaaf Laam Meem Laam Alif
TOTAL = 212
MEDITATION
The person who reads Ya Maalik ul Mulk 1111 times everyday, Allah will make that personself-sufficient, Inshaa Allah.The person who reads Ya Maalik ul Mulk Zul Jalaali Wal Ikraam 1312 times every night willattain spiritual knowledge, Inshaa Allah. Furthermore that person will be protected from thecruelty and injustice of others towards him / her, since Allah will take the responsibility oflooking after that person .
50 83 – AR RAUF
8 What is the matter with you that you should not believe in Allah? And the messengerinvites you to believe in your Rabb (Lord) and has already made a pact with you, if you arebelievers?9 He is the One who sends to His servant manifest signs that He may lead you from thedepths of darkness into the light. Allah is indeed Kind and Merciful towards you. [Quraan: Al Hadeed, Chapter 57]
In the previous chapter it was mentioned: It is short sightedness on the part of disbelieversthat they do not believe in Allah. In fact Allah says in the above reference: What is the matterwith you that you should not believe in Allah?One of the reasons is that Allah is fair towards all His creation in this world. There is nopreferential treatment of Muslims over non-Muslims in this world by Allah, so the disbelieverscannot find any reason to believe in Allah. The disbelievers fail to comprehend that Allah ispatient and fair with everyone in this world. The disbelievers fail to comprehend that thisworld is in fact an illusion. The disbelievers fail to comprehend that this world is a place togain knowledge so that we can pass the examination at the end. Those who pass theexamination will be in bliss in the next world. Those who fail will be in turmoil.Allah wants to lead the people from darkness into light. Hence Allah treats each one of uswith kindness in this world so that no one has an unfair advantage over another. In otherwords, the disbelievers cannot claim that they had been treated unfairly in this world. Thedoor is always open in this world for disbelievers to come to the right path. And on the Day ofJudgment the disbelievers will not have any excuse for disbelieving in Allah after they hadbeen treated fairly in this world.
51 83 – AR RAUF
Had Allah given the Muslims preferential treatment in this world, then, the disbelievers wouldonly believe for the sake of a better life in this world and for no other reason. Had Allah giventhe Muslims preferential treatment in this world, then, the disbelievers would only believe forthe sake of riches of this world and for no other reason. We can go on and on and everyreason would be for the sake of this world and not for the next world. Why?The next world is invisible. Therefore all ‘goodness’ of this world would be equated to riches.In reality, riches of this world only count as goodness if they are used to help others in theName of Allah. Riches of this world should be the last reason for a disbeliever to become abeliever. The goodness of the next world is invisible. In the next world the believers will begiven ‘preferential’ treatment over the disbelievers. Some people want visible proofs of thenext world in order to believe. If everyone was given visible proofs of the next world, thenthere would be no reason to send Messengers. If everyone was given visible proofs of thenext world, then everyone would be a believer! Unfortunately, not everyone uses his or herintellectual capacity to discern the truth! Hence Allah sent Messengers to remind us of Allahand the truth. Therefore the reward in the next life is directly proportional to faith and gooddeeds in this world and not to the riches of this world! So Allah is Kind to all His creation inthis world regardless. Everyone is welcome to the path that leads to Allah. Once we passaway, that path is closed for a disbeliever.Allah is full of Kindness towards His creation. Now let us look at another example of thatkindness from the Quraan:
128 There has come to you a messenger from amongst yourselves. It grieves him that youshould perish, (he is) concerned for you, for the believers he is kind and merciful.129 But if they turn away say: "Allah is sufficient for me. There is no god only He. In Him ismy trust, and He is the Rabb (Lord) of the supreme throne. [Quraan: At Tawba, Chapter 9]
Allah sent His Beloved to guide mankind from darkness into light. We find Allah’s Attribute ofKindness emulated by His Beloved Muhammad . It grieves Muhammad that weshould perish. So he called the people to the path of Allah. Prophet Muhammadcalled the disbelievers to the path of Allah. The disbelievers became believers.Allah, Ar Rauf the Kind, loves His creation. He did not create us so that He could punishus. On the contrary! He created us so that we would recognise our Creator in order that Hemay reward us. And to show His fairness, Allah is Kind to His entire creation. Kindnessaffects the heart. Kindness is the key to Fattah to open the heart and mind of someone toaccept the truth, not harshness. May Allah make all the Muslims kind towards each other.Aameen.
52 83 – AR RAUF
The person who reads Ya Raufu 1111 times everyday, will find that the person will be kind toothers and others will be kind to him / her. The person who reads Ya Raufu will also find thathe / she will become calm and their temper will be brought under control. If the person whodoes this Zikr blows on an enraged person, the enraged person will calm .
53 82 – AL AFUW
98 Except those who are weak and oppressed men, women and children who are unable todevise a plan and are not shown a way.99 For them there is hope that Allah will pardon them. Allah is Pardoning, Forgiving. [Quraan: An Nisaa, Chapter 4]
Allah will pardon those who are weak and oppressed, unable to devise a plan and who havenot been shown a way. First let us look at what is meant by oppression. Oppression isinjustice, tyranny and cruelty. In every age, there have been people who have been unjustand cruel towards others. In every age, there have been the oppressors and the oppressed.We have been told how the pharaohs were the oppressors and the Israelis were theoppressed. Allah in His infinite mercy sent Hadhrat Musa as His Messenger to lead hiscommunity, the Israelis, from oppression to freedom. Then we look at just 60 years ago, theIsraelis were oppressed again during the second world war. The lesson to be learnt here isthat the descendants of these oppressed people have now become the oppressors ofanother community.Which reminds me of a story about a saint who saw a blind boy sitting all by himself near theedge of a river while other children were playing in the water. The saint felt sorry for the blindboy and prayed to Allah to restore the sight of the blind boy. Allah replied that it was betterfor the boy to be blind. But the saint insisted. Allah restored the sight of the blind boy. Assoon as the sight of the blind boy was restored, he jumped into the water where the otherchildren were playing and he tried to hold the heads of the other children under water inorder to drown them. The saint saw what this boy was doing and asked Allah for forgiveness,and he prayed to Allah to change the condition of the boy back to the way he was. That is,make the boy blind again. Allah once more took away the sight of that boy. The blind boy
54 82 – AL AFUW
came back to the same spot where he was originally sitting and he once again sat calmly.There is a lesson in this story for all of us regardless of race or religion.Allah does not like the oppressors. Allah is on the side of the oppressed. The oppressorsthink they are gods who can do whatever they like to others. Allah does not have partners!Ultimately both the oppressors and the oppressed return to Allah for judgment.It is never too late to repent. Allah accepts repentance and pardons, provided we are sincere.Allah accepts repentance and pardons, provided we mend our ways.Finally let us look at one other example from the Quraan:
148 Allah does not like evil to be uttered in speech except by one who has been wronged.Allah is Hearer, Knower.149 Whether you do good deeds openly or in secret, or forgive evil. Allah is Pardoning,Powerful. [Quraan: An Nisaa, Chapter 4]
Allah does not like evil to be uttered in speech… Why does Allah not like evil to be uttered inspeech? Speech is a gift from Allah to be used for repentance. Speech is a gift from Allah tocall upon Him by His most Beautiful Names. Speech is a gift from Allah to speak kindly toothers. And speech is the gift from Allah, which we can use to pardon and forgive otherswhen they wrong us or oppress us! However, in desperation the tongue slips and utters whatshould not be uttered. If that wrong utterance is from the tongue of an oppressed person,Allah will forgive, Inshaa Allah.
Allah is Al Afuw the one who Pardons. Allah is Al Aleem, the one who has full knowledgeof every act, major or minor, good or evil. Nothing is hidden from Allah’s knowledge. Eventhen Allah keeps the door open to pardon and forgive us provided we ask for Allah’sforgiveness and pardon with sincerity. Allah created His creatures out of love and kindnessnot out of hatred. Therefore Allah is the one who forgives us our mistakes and sins. SinceAllah loves to forgive our sins and pardons us, we must try and emulate this quality offorgiving and pardoning others who have done wrong to us. May Allah forgive and pardon allthe Muslims for their mistakes and may the Muslims forgive and pardon each other for thesake of Allah. Aameen.
Fa 80 Waw 6 TOTAL 156 TOTAL
55 82 – AL AFUW
MEDITATIONThe person who reads Ya Afuwu 1111 times everyday, will find that Allah will forgive thatperson's sins, Inshaa Allah. And likewise the person should also forgive others .
56 81 – AL MUNTAQIM
22 And who does more wrong than one who is reminded of the signs of his Rabb (Lord), thenturns away from them? Surely the transgressors We shall requite. [Quraan: As Sajda, Chapter 32]
Allah will take revenge on those who when they are reminded of the signs of their Rabb, theyturn away. Allah will take revenge on those who are rebellious and wicked. Why?Neither rebellion nor wickedness can be associated with Allah’s Attributes. Both thesequalities are unacceptable to Allah. In fact Allah is very Patient and most Kind. Thereforethose who are rebellious or wicked are acting in opposition to the noble qualities of theirRabb. Those who are rebellious and wicked are acting against the laws of nature as setdown by Allah in the Quraan. Those who are rebellious and wicked are acting against theSunnat and noble character of Allah’s Rasool Muhammad .Therefore Allah will take revenge on those who are rebellious and wicked, those that actagainst the noble qualities of Allah, those that act against the laws of nature laid out in theQuraan and those that act against the noble character of Prophet Muhammad . If wewant to avoid the punishment of Allah, or the revenge of Allah, then we should repent andfollow the example of the greatest human being, Allah’s Rasool, Muhammad . As Allahclearly confirms in the Quraan:
57 81 – AL MUNTAQIM
21 You have a beautiful example in the Messenger of Allah for anyone whose hope is inAllah and the Last Day and who remembers Allah always. [Quraan: Al Ahzaab, Chapter 33]
The moral here is to remember Allah always especially before we speak or act. The advancethought of Allah will refrain us from any rebellious or wicked deed or word. The advancethought of Allah will ensure that we do not do anything by which Allah will be displeased withus and take revenge on us.There is another side to rebellion that we should also mention. This is the rebellion of thesoul. The soul, which is the Nafs also rebels at times when it comes to prayer time or ZikrAllah. We should take revenge on the Nafs by ignoring the negative thoughts and actingagainst them. The Nafs has an animal quality. It should not be allowed to take control overthe person. If it does take control, it corrupts the person, and that person becomes wickedand rebellious. Therefore, before the wickedness goes too far, the person should learn tocontrol the cause of that wickedness and rebellion. That is the Nafs should be brought underthe control of that person. Only then does the Nafs become subdued and obedient.Let us look at one more example from the Quraan:
15 We shall indeed remove the penalty for a while. Surely you will revert (to your ways).16 One day We shall seize you with a mighty onslaught, We will indeed avenge! [Quraan: Ad Dukhan, Chapter 44]
In this example Allah tells us that He shall remove the penalty for a while from the wickedpeople. Why does Allah remove the penalty from the wicked for a while?It was stated earlier in this article that Allah is Patient. Allah gives the wicked ones a chanceto repent. But if they miss this opportunity of asking Allah for forgiveness, then Allah will takerevenge and deal with them as He wishes.There is one more point that should be mentioned here. Those who have no intention ofrepenting their hearts become hard as stones if they are given respite. Those who can thinkhave to realise that Allah has given them ease for reflection on their condition. Allah hasgiven them ease so that they have time to repent. Allah has given them ease so that theymay thank Allah for His Patience. If the latter realise this and repent, Allah will forgive them,Inshaa Allah. The former however become even more wicked and rebellious.A true believer is never hard-hearted. A true believer is not wicked. A true believer is notrebellious. In other words a true believer has a soft heart. An example of a true believer otherthan Allah’s Rasool is Abu Bakr As-Siddiq . It is related that: Abu Bakr As-Siddiqwas a man who used to weep too much, and he could not help weeping on reciting theQuraan.Allah is Al Muntaqim the Avenger. Allah will take revenge on the disbelievers, the wickedand the rebellious by throwing them in the Naar fire. Because they neither controlled theirNafs nor did they see the light. Hence they failed to do Tawba repent to Allah. Allah willtake revenge on Qiyamat the Day of Judgment when the deeds will be weighed on theMeezan balance.May Allah guide us all and make us obedient towards Him and kind towards His creation.Aameen.
58 81 – AL MUNTAQIM
The person who reads Ya Muntaqimu 1111 times everyday, will find that Allah will make thatperson’s Nafs (soul) obedient, Inshaa Allah. If the person who has been wronged by anotherreads Ya Muntaqimu, Allah will take revenge on the oppressor only if the oppressed is .
59 80 – AT TAWWAAB
1 Ha Meem.2 The revelation of this book is from Allah the Mighty, the Knower3 Who forgives sin, the Acceptor of Repentance, the strict in punishment with a long reach.There is no god only He. To Him is the final goal. [Quraan: Al Mu_min (or Al Ghaafir), Chapter 40]
To Him is the final goal! That is what we are trying to do, to return to Him before deathovertakes us. Tawba is the returning of the creature towards the Creator. We have to takethe initiative of repenting, for Allah to turn towards us with His mercy. Allah is prepared toaccept our repentance until the last breath. If we do not repent then the punishment will bevery strict. Whether we commit a major sin or a minor one, a sin is a sin. Whether we committhe sin knowingly or unknowingly, a sin is a sin. There are two ways to pay for the sin. Eitherwe can pay for the sin here in this world or we can pay for it later in the next world. It is betterto pay now than later. Allah in His infinite mercy has warned us in the Quraan that it is betterto pay now than later.If we truly repent and ask Allah for forgiveness, Allah will accept our repentance and forgivethe sin, Inshaa Allah. If on the other hand we do not repent or ask Allah for forgiveness, thenwe will be charged for the sin in the next world. And the payment of sin in the next world issevere punishment. Allah will accept a few sincere words of repentance from the heart in thisworld as full payment for the sin. Sincere words of repentance do not cost anything neitherdo they inflict pain on our self. But they carry a lot of weight as far as forgiveness isconcerned. However if we do not seek repentance, then punishment of our self is the price topay in the next world. Why?
60 80 – AT TAWWAAB
Allah has created everything to abide by certain rules. For instance, the planets have beencreated to abide by the rules or laws that Allah has intended for them. If the planets actedagainst the laws that Allah has subjected them to, then they would be destroyed. Similarly,committing a sin is an act that is contrary to the rules. Committing a sin is an act againstnature. Committing a sin is destruction or punishment of our own self. Committing a sin doesnot harm Allah in any way. Neither does repentance of an individual have any benefit forAllah. Both harm and benefit are for the individual and no one else. However, becauseAllah’s mercy far outweighs His wrath, Allah does not want us to suffer or perish. Allah wantsto reward us and show us His generosity. Allah wants us to correct our wrong actions byrepenting and asking for forgiveness. And as it was stated earlier on, sincere words ofrepentance do not cost anything. And the rewards for repentance will be beyond anyone’simagination.Looking at another example from the Quraan:
104 Do they not know that Allah is He who accepts repentance from His devotees andreceives their gifts of charity and that Allah is He who is the Acceptor of Repentance, theMerciful? [Quraan: At Tawba, Chapter 9]
Allah accepts repentance and receives gifts of charity. What do gifts of charity have to dowith repentance?Since repentance is turning back to Allah, gifts of charity are also the return of a token backto Allah for all the gifts that He bestows on us. The gifts from Allah to us are numerous andbeyond accountability. He gave us life. He made us grow. He made us self-sufficient. Hefeeds us everyday by making the crops grow. We can go on and on and still not account forall the gifts that Allah bestows on us. We cannot repay Allah for even a mouthful of food. Ourgifts of charity in the Name of Allah are negligible. But Allah is the one who accepts theseinsignificant gestures and tokens as gifts of charity that we give in His Name. If we have nomoney or food to give, Allah even accepts a smile from the poor as a gift of charity in HisName. Allah has no need for food or money. The gifts that are given in His Name are ameans to help the less fortunate and to teach us that there is nothing but Oneness. Theentire human race is one big family. Therefore, with repentance, or turning back to Allah, wemust also return some of the gifts that He has given us, to those who are less fortunate thanus because they are also His creation. We cannot just take and take, but we must returnsomething in the Name of Allah as a gift of charity.Allah is At Tawwaab the Acceptor of Repentance from His devotees because He createdeverything out of love and not hatred. Allah wants us to turn to Him so that He may turntowards us. Allah wants us to give some of the gifts that He has bestowed on us to thosewho are less fortunate. We are all His creation .
61 80 – AT TAWWAAB
The person who reads Ya Tawwaabu 1111 times everyday, Allah will accept the repentanceof that person, Inshaa Allah. The person who keeps reading Ya Tawwaabu will find that his /her tasks will become easier. If a person reads Ya Tawwaabu 10 times and blows on awicked person, Allah will relieve the reader from that wicked .
62 79 – AL BARR
27 "But Allah has been good to us and has delivered us from the penalty of the scorchingwind.28 "Truly we did call Him from of old. Truly it is He the Beneficent, the Merciful" [Quraan: At Toor, Chapter 52]
The above words will be of those who will be in heaven. Allah will deliver from the fire andthe scorching wind those who do good deeds in this world and remember Allah always.Towards them, Allah will be the Beneficent and Merciful. There is the Attribute Rabb andthere is the Attribute Barr. The Attribute Barr is connected with everything within. What ismeant by within?Within here means that Allah has placed goodness within everything. For example, thegoodness within the earth is its treasures. What makes the plants grow? It is the chemicalsthat Allah has placed within the earth. The sea is full of treasures. And all the treasuresplaced within the sea and the goodness placed within the soil is by none other than Allah, AlBarr, the Beneficent. Allah’s Beneficence is without prejudice. There is equality in thegoodness as far as when any one plants a seed in good soil it will grow into a plant withoutprejudice as to who placed the seed in the soil. Allah does not discriminate!The lesson here is that Allah delivers without prejudice from the fire and the scorching windthose who do good and call Him. Therefore we have to remove all forms of prejudice fromour own selves when dealing with others. We must not discriminate when dealing withothers. Just as the goodness is placed within the soil or within the sea, so are the prejudicesplaced within us. If the prejudices are placed within us, then the ‘room’ for goodness is takenover by the prejudices. We must remove the prejudices within and make room for thegoodness within that was originally there before our prejudices replaced that goodness.Another example of the quality of Barr, Beneficent or Goodness is that of a teacher. Ateacher teaches all the students the same lesson. That is, the teacher teaches withoutprejudice. The lecture is the same for all the students in the same class. It is the
63 79 – AL BARR
responsibility of the individual students to grasp what is being taught according to their ownindividual understanding. Similarly, goodness has to come from within us in order for us toreceive goodness from outside. There is an example in the Quraan about this:
12 "Yahya! Take hold of the Book with might." And We gave him wisdom even as a youth.13 And compassion as from Us and purity and he was devout,14 And beneficent to his parents. And he was not arrogant or rebellious. [Quraan: Maryam, Chapter 19]
Allah tells Prophet Yahya to take the Book with might. Why ‘with might’? Here might is inconnection to the feelings. Just as people have strong prejudices within them, similarly, toovercome these prejudices we have to be strong and conquer these prejudices and drivethem out. Therefore in the above reference we are being told to hold the Book of Allah withstrength over our prejudices. That is read the Quraan without prejudice or preconceivedideas. When we empty our selves of the prejudices and the literal meaning of the Quraan, wemake room for a real understanding to descend in our hearts with Allah’s permission. Then atotally different dimension, a new way of understanding the Quraan opens up for us.And then we are told in the above reference: And We gave him wisdom even as a youth. Theliteral meaning is obvious without any explanation. The spiritual meaning is that just as ayouth is strong, fresh and ‘new’, the stronger, fresher and newer meaning or the spiritualdimension of the Book is taught and understood. The condition for this wisdom iscompassion, purity, devotion, beneficence to parents and humbleness. That is inhumbleness, there is no room for prejudice.To emulate the quality of beneficence we have to humble ourselves before others. The onlyway we can humble ourselves is to remove all forms of prejudices from within us. It tookyears to form those prejudices, and it is not easy to remove them overnight. However if wemake the intention, Inshaa Allah we will overcome them.Therefore Allah, Al Barr the Beneficient is the one who has placed all kinds of goodnesswithin the creation for our benefit. We must thank our Rabb for His Beneficence which iswithout prejudice.May Allah make us humble towards His creation so that He may purify us and placegoodness within all of us. Aameen.
MEDITATIONThe person who reads Ya Barru 1111 times everyday, will overcome all kinds of evil and badhabits within, including the love for this temporary world, Inshaa Allah. A person who wantsto give up alcohol and other addictive substances should read Ya Barru 7 times everyday.Eventually, the addiction will be overcome, Inshaa Allah.
64 79 – AL BARR .
65 78 – AL MUTA_AALI
8 Allah does know what every female bears by how much the wombs fall short of completionand that of which they exceed. And there is measure with Him of everything.9 He knows the unseen and the seen, the Great the Exalted. [Quraan: Ar Raad, Chapter 13]
We are told that Allah knows what every female bears and the time taken for the completionof the offspring. Everything is measured and known to Allah. Allah also knows the unseenand the seen. That is Allah knows everything hidden and everything manifest. Since it isAllah who created both the hidden and the visible worlds and everything in them, then howcan He not know everything! Therefore Allah has measured our lifespan as to how manyyears we are to live. Allah has measured our breaths as to how many breaths we are goingto breathe. Allah has measured our sustenance as to how much food we are going to eat onthis earthly life. Allah knows how many other lives are going to affect our life and likewisehow many other lives we as individuals are going to affect. All that knowledge is with Allahbecause He knows the invisible and the visible.Therefore Allah is the Exalted in the sense that He knows everything about everything.Allah’s knowledge encompasses everything. Our knowledge is defective in relation to Allah’sknowledge. Our knowledge is insignificant where as Allah’s knowledge knows no limits. IfAllah’s knowledge knew its limits, then it would be limited! Therefore, Allah’s knowledge isunlimited, without limitations, so it knows no limits. Allah’s knowledge is without boundariesencompassing everything. Therefore Allah is the Exalted in terms of knowledge. We are alsotold in the above reference that: There is measure with Him of everything. Allah’s knowledgeis such that:
66 78 – AL MUTA_AALI
59 With Him are the keys of the unseen. None knows them but He. He knows whateverthere is on the earth and in the sea. Not a leaf falls but He knows it, there is not a grain in thedarkness of the earth nor anything fresh or dry but is (inscribed) in a clear record.60 It is He who takes your souls by night and has knowledge of all that you have done byday. By day He raises you up again, that a term appointed be fulfilled. In the end to Him willbe your return then will He show you the truth of all that you did. [Quraan: Al Anaam, Chapter 6]
There is not a leaf that falls without Allah’s knowledge. If we look at the number of trees inthe world we would not be able count them. Then how can we count the number of leaves onthem? But Allah’s knowledge is limitless without bounds and aware of every leaf on everytree. Then the next example given in the above reference says it all, that Allah is aware ofevery grain. The grain can be a grain of sand. Who can count the grains of sand other thanAllah? Therefore Allah’s knowledge also knows what each one of us does and we will beshown the truth of what we did. May Allah guide us all so that we refrain from what isforbidden and remain on the right path all the time. Aameen.
Allah Al Muta_aali the Exalted created us from Turaab dust and gave us Aqlsense to seek Him the One whose Name is Allah . We cannot see Allah but we certainly
can know Allah. The way to know Allah is with the Kalimaat: La ilaha ill Allah There is no
god only Allah, not just with the tongue but with the Knowledge that He has given us tounderstand what we ourselves are saying when we say La ilaha ill Allah. May Allah enlightenthe Muslims so that we the Muslims may exalt the community of Prophet Muhammadabove all other communities by our deeds and actions. In so doing may Allah exalt ourMaster Sayyidina Muhammad to an even higher rank than now. Aameen.
Alif 1 Laam 30 Ya 10 TOTAL 551 TOTAL
67 78 – AL MUTA_AALI
The person who reads Ya Muta_aali 1111 times everyday, will overcome all kinds ofdifficult .
68 77 – AL WAALI
10 It is the same whether any of you conceal his speech or declare it openly; whether he lieshidden by night or walks freely by day.11 For each there are (angels) in succession before and behind him who guard him byAllah’s command. Truly never will Allah change the condition of a people until they changewhat is in their own souls. But when Allah wills a punishment for some people there can beno turning it back nor will they find besides Him any to govern. [Quraan: Ar Raad, Chapter 13]
In the section Al Muta_aali, the Exalted we found that everything is already encompassed byAllah’s knowledge. Similarly in this section we find that Allah is aware of every thought.Whether we speak out the thought in speech form or keep it hidden, Allah knows even ourmost secret thoughts. We can neither run nor hide ourselves from Allah. Then there areangels who are before and behind each one of us. They are under the command of Allah.Allah is the one who governs those angels. Similarly, Allah governs our existence.
Notice that the difference between the spellings of Waali Governor and Walee
Friend (Section 55) is that there is an extra Alif in the Name Al Waali. That one Alifis what distinguishes Al Waali from Al Walee. In friendship there are no formalities. Butbefore a Waali proper protocol has to be observed. In worldly ways there can be many
69 77 – AL WAALI
friends. In other words, one person can have a lot of friends. But there can only be onegovernor. Still continuing with the example of worldly matters, if there was more than onegovernor, then there would be a conflict at some time or other between the governors.In heavenly terms there is only one Governor and that is Allah. Allah alone is the Governor,without partners in His governing affairs. Everything renders service to Him and Him alone.Therefore the angels assigned to each one of us are under the command of Allah. Hencewhen Allah wishes to punish anyone, no one can interfere in His decision because He is theGovernor who decides the course of action. But to avert a punishment we must first changeour selves and believe in Allah and His angels and His Books and His Messengers, andfollow the guidance laid down by Him for us. May Allah guide us all to the right path that willavert His punishment and earn His mercy. Aameen.
Allah is a loving Al Waali Governor, up to a certain point. Then there is a ‘line’ which
must not be crossed. To avert the punishment we must believe in the Kalimaat La ilaha illAllah Muhammadur Rasool Allah. But we must also understand that Allah has Knowledge
of our inner, most secret thoughts. Therefore lip service is of little or no use without belief.
MEDITATIONThe person who reads Ya Waali 1111 times everyday, will be saved from all kinds of harm,Inshaa Allah. Similarly if a person who reads Al Waali 11 times and blows on a container ofwater and sprinkles that water on his dwelling, Inshaa Allah the house will be safe from allkinds of harm. If a person wishes to make a family member obedient, he / she should read AlWaali 11 times, Inshaa Allah the disobedient person will become obedient. .
70 76 – AL BAATIN and the Manifest and the Hidden and He has knowledge of allthings. [Quraan: Al Hadeed, Chapter 57]
In this example we are told that Allah is the First, the Last, the Manifest and the Hidden. Weshall look at the first three Attributes in their relevant sections. It is the last Attribute that weshall look at in this section. Everyone knows that Allah is the Hidden. To believe in somethingthat is visible is easy for everyone. For example, when someone shows us the sun and says:“That is the sun!” Everyone can believe that without a question. To take this argument to thenext stage, if someone says “The sun is many times larger than the earth”, then we have toeither use our knowledge and come to the same conclusion or alternatively we can justbelieve the other person because we can see the sun is very far from us, therefore it must behuge. Or if our mind cannot function properly, we can totally reject the last statement of thatperson.Now if someone says “Allah Exists and He is Hidden, you cannot see Him and you have tobelieve that Allah Exists”, that is where all the trouble starts!If Allah was Visible, there would be no arguments. If Allah was Visible, then everyone wouldbe a believer. If Allah was Visible, there would be no need for Allah to send His Messengers.However, if Allah was Visible, it would be impossible for this world to exist! Likewise, neithercould we exist. Therefore Allah had to keep Himself hidden. But why is Allah Hidden and whywould it not be possible for the world to exist?The answer is in the Quraan:
71 76 – AL BAATIN
143 And when Musa (Moses) came to Our appointed place and his Rabb (Lord) had spokento him, he said: “My Rabb (Lord)! Show me, that I may look upon You”. He said: “You will notsee Me, but look upon the mountain! If it stands still in its place, then you will see Me”. Andwhen his Rabb (Lord) revealed (His) glory to the mountain He sent it crashing down. AndMusa fell down senseless. And when he woke he said: “Glory to You! I turn to You repentant,and I am the first of believers.” [Quraan: Al Aaraaf, Chapter 7]
If Musa a very noble Messenger of Allah had difficulty in seeing Allah and he fainted, whatwill be the state of ordinary people like us? If the mountain crashed just because of the gloryof Allah, what would be the state of the rest of the creation if Allah revealed His Glory toeverything, would it be standing or would it be destroyed?Allah’s Tajalli (Glory) is unbearable. Even on the Night of Miraaj - Ascension of the HolyProphet, Muhammad , all the angels stopped at their relevant posts, which they wouldnot dare to cross because they would be destroyed. But Muhammad crossed thoseboundaries and met Allah!And finally let us finish with one more example from the Quraan:
13 On the day when the hypocritical men and the hypocritical women will say to thebelievers: “Look at us so that we may borrow from your light!” It will be said: “Go back andseek for light!” Then a wall will separate them in which is a gate, the hidden (inner) sidecontains mercy, while the visible (outer) side is toward the punishment. [Quraan: Al Hadeed, Chapter 57]
In this example we are told that the disbelievers will say to the believers “Look at us so thatwe may borrow from your light!” The sun, although it gives light, is of no use to a physicallyblind person! Therefore the ‘light to see’ is within the creature and not in the sun! The sight ofa believer is the light. That is the believer believes in Allah without seeing Him since Allah isthe Hidden, the believers ‘vision’ ‘sees’ Allah through His works. Then how can the sight of abeliever not be the light! The believers will say to the disbelievers, go back and seek for light.That is, go back and believe in Allah. Then a wall will separate them (the believers and thedisbelievers). The hidden side contains mercy. That is Allah being the Hidden is a mercy forus because we would not be able to look at the Tajalli and those on the outside of the wallwill start crashing down like the mountain in the previous example.Allah is Al Baatin the Hidden. The creation cannot see Allah directly because of whathappened on the Mount Toor . But with inner purity we can ‘know’ Allah by His works andHis creation by the Noor light that Allah has placed within all of us. May Allah show Hismercy on all of us. Aameen.
72 76 – AL BAATIN
The person who reads Ya Baatinu 1111 times everyday, Allah will reveal the hiddenmeanings behind the visible and the love for Allah will start to flourish in the heart of thatperson, Inshaa Allah. The person who reads two Rakaat Nawafil Salaah and then at the endrecites Huwal Awwalu Wal Akhiru Waz Zaahiru Wal Baatinu Wa Huwa Ala Kulli ShayyinQadeer(u) 11 times will achieve his / her lawful .
73 75 – AZ ZAAH]
Allah is Az Zaahir the Manifest. But we have just seen in the previous section that Allah is notvisible! So how can Allah be the Invisible and Manifest at the same time?Allah is Manifest in the sense that when we look at everything around us, Allah has placedsigns in them for us to know that all this creation is by none other than Allah. Allah isManifest in the sense that Allah has placed clear, distinct, evident, obvious, plain andunmistakable signs in the creation of heavens and earth and everything in between. And ineverything the signs point to the Oneness of Allah. And Allah alone is the Creator.That is, in every created thing we find the same basic structure of an atom. That is, everycreated thing has a ‘circular’ construction. That is, every created thing also follows a circularpattern of existence.In the Al Baatin Attribute we have to believe in the existence of Allah as stated in thebeginning of the Quraan: Who believe in the unseen, and establish worship, and spend ofthat We have bestowed upon them.The Quraan is guidance for them. With believing in the unseen, we now have to believe inthe Visible in the sense we have to perform certain rituals such as Salaah (prayer) which is aManifest sign of Allah. Just as the recitation is audible and the prayer is Zaahir (visual), the
74 75 – AZ ZAAHIR
reward is inaudible and Baatin (hidden). Zaahir compliments Baatin and vice versa. Everyphysical Zaahir – visual action is recorded in the Baatin – unseen, and again vice versa.For example, whether we have a pleasant or unpleasant thought, our body language willreflect that unseen thought into the visible world through our body! Likewise when we seesomething in the visible, our body and our invisible thoughts will respond to that sight.Therefore Zaahir and Baatin, Manifest and Hidden compliment each other.But we look at physical forms and forget that the eyes can deceive us. Therefore as ImaamAbu Hameed Al Ghazzali has stated in one of his books: Beyond intellect there is anotherstage. At this stage another eye is opened, by which a person beholds the unseen, what is tobe in the future, and other things which are beyond the ken of intellect in the same way asobjects of intellect are beyond the ken of the faculty of discernment and the objects ofdiscernment are beyond the ken of sense.In other words, the senses, including sight, are just the avenues of taking in information.Then discernment takes over where what the senses perceive is put into perspective.Intellect takes over after that and the intellect analyses what is discerned. But beyond thesenses, beyond the discernment, beyond the intellect is a ‘third eye’, which sees the reality ofthings. It is this ‘third eye’, which beholds the unseen. And that is how Allah is Az Zaahir theManifest – the Visible. We have to know Allah from the signs in the creation and then discernthem. Then use our intellect to understand what we have observed or discerned. Then it isup to Allah to open up our ‘third eye’ so that we may ‘behold’ Him through His works. Takinganother example from the Quraan to show the existence of this ‘third eye’:
20 Do you not see that Allah has subjected to you all things in the skies and on earth andhas made His bounties flow to you in exceeding measure both seen and unseen? Yet thereare among men those who dispute about Allah without knowledge and without guidance andwithout a Book to enlighten them! [Quraan: Luqmaan, Chapter 31]
In the above reference, we are asked: Do you not see… We can either try and look at thingsin the skies and earth with the physical eyes or we can try and really see or in other words tryand understand what is in the skies and the earth and realise it is all there for us to master.We can master in the sense that we must try to understand what we ‘see’. That is use the‘third eye’.Therefore Allah is Az Zaahir in the sense that Allah wants to guide us, give us Hidayat so that we may come out of the darkness to the understanding that Ar Rahman theCompassionate, has bestowed numerous favours upon us. Then which of the favours of ourRabb (Lord) will we deny?May Allah open up our understanding so that we may really know Him. Aameen.
75 75 – AZ ZAAHIR
MEDITATION
The person who reads Ya Zaahiru 1111 times everyday, Allah will ‘pour the light’ into theeyes and heart of that person, Inshaa Allah. The person who also reads two Rakaat NawafilSalaah and then at the end recites Huwal Awwalu Wal Akhiru Waz Zaahiru Wal Baatinu WaHuwa Ala Kulli Shayyin Qadeer(u) 11 times will achieve all his / her lawful desires, .
76 74 – AL AKH]
Everything will perish apart from Allah. At last there will be nothing but Allah. When doeseverything perish?Almost every time the words “Believe in Allah” or “Belief in Allah” is mentioned we find thewords “Last Day” mentioned almost next to them in the Quraan. For example:
59 You who believe! Obey Allah and obey the Messenger and those charged with authorityamong you. If you differ in anything among yourselves refer it to Allah and His Messenger ifyou do believe in Allah and the Last Day. That is better and most suitable for finaldetermination. [Quraan: An Nisaa, Chapter 4]
What is the significance of the Last Day? One of my Muslim brothers mentioned that all thesaints of the past have written in their teachings that the world will end very soon. And someof these teachings date back to 1100AD and some even before that time. But the world is stillin existence. What happened? The answer is very simple. For each one of us there is alimited period on this earth. Then there will come a day when our days will end. When wedie, the world as we know it will cease to exist for us. What have the dead got to do with the
77 74 – AL AKHIR
earth? The earth or this world ceases to exist for the dead. The Last Day arrives on the daywe depart from this world. When we die, others say: “Such and such has departed or died.”Similarly belief in Allah is a requirement for those who are presently living in this world. Afterdeath, the reality becomes plain to see. Therefore belief in Allah and the Last Day is toremind us that we need to believe in Allah before the Last Day. Every time in the Quraan,“Belief in Allah” precedes the mention of the “Last Day”. Therefore belief in Allah takesprecedence over the last day. The world does end on the last day at the last breath. Afterdeath, no amount of pleading or excuses will be accepted for disbelief in Allah. Let us look atanother example from the Quraan:
5 "Our Rabb (Lord)! Make us not a trial for the disbelievers but forgive us our Rabb (Lord)!You are the Mighty, the Wise."6 There was indeed in them an excellent example for you to follow for those whose hope is inAllah and the Last Day. But if any turn away truly Allah is the Self Sufficient, thePraiseworthy. [Quraan: Al Mumtahana, Chapter 60]
Whether someone believes in Allah or not the last day arrives without a doubt. The last dayarrives for a Muslim, it arrives for a Christian, it arrives for a Jew, it arrives for an idolworshipper and it also arrives for an atheist. The moral of the story is that belief in Allah isimperative in this world. Why? So that on the Last Day we may have a chance to be savedfrom punishment and doom by Allah’s generosity. On the other hand, one who does notbelieve in Allah will be lost and doomed. As the above reference clearly states the excellentexample for us to follow is to seek forgiveness for heedlessness and Praise our Rabb (Lord),because we need Him. Allah on the other hand is free from all needs or wants and worthy ofall praise.
Allah is Al Akhir the Last to whom we have to return. Allah Al Khaaliq the Creator is theOne who created us in the first place, so that we may truly know our Rabb (Lord) bypraising Him, who will save us on the Last Day by His generosity, Inshaa Allah.May Allah guide us all to strong belief in Him so that we may be forgiven on the Last Day.Aameen.
Ra 200 TOTAL 801 TOTAL
78 74 – AL AKHIR
MEDITATIONThe person who reads Ya Akhiru 1111 times everyday, Allah will remove all desires from theseeker other than Allah. And the person who keeps reciting Al Akhiru will be forgiven all thesins and that person will die with his / her faith in Allah, Inshaa Allah. The person who alsoreads two Rakaat Nawafil Salaah and then at the end recites Huwal Awwalu Wal Akhiru WazZaahiru Wal Baatinu Wa Huwa Ala Kulli Shayyin Qadeer(u) 11 times will achieve all his / herlawful desires, .
79 73 – AL AWWAL
We exist because Allah exists. Our existence is borrowed from the First existence. The Firstexistence is Eternal. The first human creation was that of a male namely Hadhrat Adam .This first human creation is a secondary existence. This secondary existence, that is ourexistence is temporary in the sense that we are on this earth for only a limited time. Thesecondary existence is given eternal life in the sense that Allah will recreate us and rewardus for our belief and works and give us gardens of bliss. Or alternatively Allah will punish useternally for our disbelief and evil deeds.It is because of the First that everything exists and the Last will exist when everything elseother than Allah will perish, because Allah is the First and Allah is the Last.Allah is the Patient One who will accept our belief from the first to the last day of ourexistence. Allah will accept our belief from the first breath to the last. Even on the deathbed ifa disbeliever utters the testimony of belief La ilaha ill Allah Muhammadur Rasool Allah –There is no god only Allah, Muhammad is the Messenger of Allah, Allah will accept thatperson as a believer. That does not mean we can be disbelievers until the last breath. Wemay not get the chance to testify at our last breath. Therefore the earlier we believe in Allah
80 73 – AL AWWAL
the better it is for us. The earlier we believe in Allah the more time we have to know Him. Theearlier we believe in Allah the more loving the relationship we can have with Allah.Therefore we must believe in the First Messenger of Allah to the Last Messenger. We mustbelieve in the First Book from Allah to the Last Book from Allah. We must pray to Allah in theFirst part of the day and we must also pray to Allah in the Last part of the day. Just like Allahcreated us on the First day (the day we were born), Allah will recreate us on the Last day.
47 And they used to say “What! When we die and become dust and bones shall we thenindeed be raised up again?”48 “And our forefathers?”49 Say: “Yes those of old and those of later times,”50 “All will certainly be gathered together for the meeting appointed for a day well-known.” [Quraan: Al Waaqia, Chapter 56]
Although we will die and become dust we will all have left our impression on this earth. Wewill have left our children on this earth. Similarly our parents will leave, or have left us behind.We will have left our works on this earth. There is no way that our existence will be erased.Therefore we will be raised up again. Therefore the imprint of our parents has been left in us.We came about because our parents came about. Similarly we can keep going back right upto Hadhrat Adam and Hadhrat Hawwa (Eve). On the last day each human being fromthe first to the last will be gathered. On the last day, each Messenger of Allah from the firstto the last will be gathered. On the last day, the last community, the community of ProphetMuhammad will be the first to be admitted to the heavens.And before anyone was created there was no one other than Allah Al Awwal the First,Eternal existence. Allah the First Existence is Waahid One, He created everything bycreating pairs. In each pair Allah placed an attraction or love so that another creation iscreated out of each pair. And after all that Allah always was, and always will be La Shareek
without a partner.May Allah Al Awwal, the First, shower His blessings on Muhammad the first Light thatwas created and the last Messenger to be sent. Aameen.
81 73 – AL AWWAL
MEDITATIONFor a couple that desires a male child, the husband should read Al Awwalu 40 times for 40days, Inshaa Allah they will have a male child. A traveller who reads Al Awwalu 1111 timeseveryday will return home safe and sound, Inshaa Allah. The person who also reads twoRakaat Nawafil Salaah and then at the end recites Huwal Awwalu Wal Akhiru Waz ZaahiruWal Baatinu Wa Huwa Ala Kulli Shayyin Qadeer(u) 11 times will achieve all his / her lawfuldes .
82 72 – AL MUAKHIR
Allah is delaying the Day of Judgment until the appointed time arrives. If Allah wants to bringthat day forward, Allah can. If Allah wants to delay that day, Allah can. Everything is underthe command of Allah. Allah can do whatever He wills. If we look all around us in this dayand age, there is corruption all around. We have become Muslims by name and not bydeeds. We practice Islaam because it is a ‘reflex action’ and not because of our faith. Ourwords are empty promises. Allah is warning us in the above reference: The day it arrives nosoul shall speak except by His leave. Allah is giving us all a chance to repent. Allah is givingus all a chance to relearn the true Islaam. Allah is giving us all a chance to be true to ourwords. On the Day of Judgment no one will be able to speak except by His leave. Thereforewe must not say one thing and do the opposite. We must stand firm on our words. Once welearn to stand firm on our words we will learn to stand firm on Islaam. Once we learn to standfirm on our promises then we will stand firm on faith in Allah. Since to become a Muslim wehave to testify the Kalimaat: La ilaha ill Allah Muhammadur Rasool Allah. And how do wetestify? We testify with words or speech. Unless we ourselves become true to the words weutter, how else can we become Muslims!Therefore Allah is the Delayer who is delaying the Day of Judgment in order that we have achance to speak now and stand firm on our own words, because on that day we will not beable to speak unless we have Allah’s permission. On that Day, Allah will divide us into twogroups. One group will be wretched and the other group will be blessed. The fate of thesetwo groups is stated further along in the chapter:
83 72 – AL MUAKHIR
106 Those who are wretched shall be in the fire. There will be for them in there the heavingof sighs and sobs.107 They will dwell in there for all the time that the heavens and the earth endure except asyour Rabb (Lord) wills. Your Rabb (Lord) is the doer of what He wills.108 And those who are blessed shall be in the garden. They will dwell in there for all the timethat the heavens and the earth endure except as your Rabb (Lord) wills. An unfailing gift!…112 Therefore stand firm as you are commanded, you and those who with you turn (to Allah),and do not transgress. He sees all that you do. [Quraan: Hud, Chapter 11]In Muhammad , Allah gave us an excellent example to follow. If we now look at anotherexample from the Quraan:
3 "That you should worship Allah fear Him and obey me.”4 "So He may forgive you your sins and give you respite for a stated term. For when the termgiven by Allah is accomplished it cannot be delayed, if you only knew." [Quraan: Nuh, Chapter 71]
We find in the above reference similarity from which we can learn. The people during thetime of Prophet Nuh (Noah) became corrupt. Prophet Nuh warned them to worshipAllah and to obey his warning. He warned them that there will not be any delay when theterm given by Allah is accomplished. Allah, the Delayer, delayed the punishment untilHadhrat Nuh had built the ark. And after that Allah did not delay the punishment anylonger. That takes us back to where we started this article. Allah the Delayer delays theappointed time as He in His Majesty sees fit. And since the delay is on the command ofAllah, Allah changes the command to delay no further. We the Muslims are on borrowedtime. We must worship Allah and obey His Rasool, Muhammad so that when theinevitable Day arrives, Allah in His mercy may include us in the blessed group. Aameen.Allah is Al Muakhir the Delayer who is delaying the Day of Judgment because He createdus from Adam whom He fashioned with His own hands out of love. Allah can destroy us
anytime He wants to. But He is giving us all a chance to mend our ways and ask for Khairwhat is better from Him so that we can serve our True Rabb Lord.
Ra 200 TOTAL 846 TOTAL
MEDITATIONThe person who reads Ya Muakhiru 1111 times everyday, Allah will accept the repentance ofthat person, Inshaa Allah. The person who reads Ya Muakhiru 100 times everyday willreceive ‘nearness’ to Allah, Inshaa Allah. Without the Zikr the person will feel no peace.
84 72 – AL MUAKHIR
85 71 – AL MUQADDIM
28 He will say: “Do not dispute with each other in My presence, I had already in advancesent you warning.”29 "The word does not change before Me and I do not the least injustice to My servants." [Quraan: Qaf, Chapter 50]
Allah hastened the warning to all the people in every community by sending each communitya Messenger from Him. Allah told all the communities how to conduct their lives in thisworld if they wanted a better life in the next world. Each Messenger of Allah was sent asone who warns their communities. Allah hastened to send the warning that we must hastento do good deeds and abstain from that which is forbidden. As Al Muakhir, the Delayer, Allahdelays the punishment so that we may repent. As Al Muqaddim, the Expediter, Allah sendsus advance warnings to correct our wrong actions. The wrong actions cannot be erasedwithout good actions. What is in the past cannot be changed unless we do some good now.We cannot change the past. The only thing we can do something about is now and thefuture, whatever future Allah may have written for us. If we mend our ways and seekrepentance, then the action of seeking repentance from Allah will outweigh the evil deeds,Inshaa Allah. The word does not change before Allah and similarly Allah has already said onthe night of Ascension that His Mercy has far exceeded His Wrath. So Allah will keep Hisword and we must keep our trust in Allah along with good deeds. What must we do?
13 That day man will be told (all) that he put forward and all that he put back.
86 71 – AL MUQADDIM
Since Allah sent us warnings in advance, we must do good deeds in advance. We must notwait for tomorrow because ‘Tomorrow never comes!’ We must hasten to do good deeds now.There is no time like now! Once this moment is gone, it cannot be brought back. It is onemore moment that has been lost forever That is one less moment we have to live. That isone less moment we have for goodness. Therefore every moment that is passing us by iseither written as goodness or as evil for us.In the above reference Allah will tell us: All that we put forward and all that we put back. Or toput it in another way, we will be told of all the goodness that we put forward and all thebadness we put behind. Or to look at it in yet another way, we will be told about all the evilthat we hastened to and all the goodness we delayed or put aside for tomorrow and wenever got round to doing it. It is the latter meaning that is understood from the abovereference because the verse that follows clarifies that Man will be evidence against himself.Since evidence is either for or against. And in this case the evidence will be for or against ourselves.How will the evidence be given? Our mouths shall be sealed. Our bodies, that is our limbs,our skin our eyes, our ears shall give evidence for or against us. This is explained furtheralong in Chapter 75:
Just as the verses applied to the revelation of the Quraan when Allah first revealed theQuraan to Muhammad . Similarly the above verses also mean that Allah will commandeach one of us not to stir our tongue on the Day of Judgment. Allah will collect our deeds anddeclare what we did. When the deeds will be declared, we shall be following their recitals.And Allah will explain to us everything we did. Hence as stated in the previous verses:
May Allah save us from evil and guide us to the straight path. May Allah have mercy on us,so that when our deeds are recited to us we do not have to put up any excuses. Aameen.Allah is Al Muqaddim the Expediter who has already sent us advance warnings ofQiyamat the Day of Judgment. We must hasten to put aside some good for that day. Theonly Deen religion acceptable to Allah is the religion perfected by Allah for Muhammad . Since Muhammad is the final Messenger of Allah to all the communities, all ofcreation, unlike the previous Messengers who were only sent to warn their own communities.In order to attain nearness to Allah we must all expedite some goodness before it is too late.
87 71 – AL MUQADDIM
The person who reads Ya Muqaddimu 1111 times everyday, will become obedient to Allah,Inshaa Allah. The person who reads Al Muqaddimu while fighting his enemy, he will receivestrength and domination over his .
88 70 – AL MUQTADIR
In the previous section, Al Muqaddim, we learnt that: Man will be evidence against himselfand that the evidence will be collected and then declared. [Quraan: Al Qiyamat, Chapter 75,verses 14 - 17].Now we find where that evidence will be collected and stored and eventually recited from.The evidence is recorded in the Zubbur – the book of deeds. Allah has the power to do thatwithout a doubt. On the Day of Judgment contents of Zubbur will be declared openly and noexcuse will be acceptable. But those whose book of deeds is acceptable to Allah will dwellamong the gardens and rivers, in an assembly of truth in the presence of a SovereignPowerful. How is Allah the Powerful?Allah is the Powerful in numerous ways. Allah has the power to punish just as He has thepower to reward. In the Quraan from where the above reference was taken [Chapter 54] weare given plenty of examples of Allah’s power to punish those who reject His signs.The lesson here is that if Allah the Powerful sends a punishment on certain people, thepunishment itself is also powerful. How can a punishment not be powerful if the commanderof the punishment is the Powerful - Al Muqtadir? Therefore the punishment from Allah is sopowerful that there is no way of averting it.Let us look at another example from the Quraan:
89 70 – AL MUQTADIR
45 Set forth to them the similitude of the life of this world, it is like the rain which We senddown from the skies, the earth's vegetation absorbs it but soon it becomes dry stubble whichthe winds do scatter, it is (only) Allah who prevails over all things.46 Wealth and sons are allurements of the life of this world. But the good deeds that endureare best in the sight of your Rabb (Lord) for reward and best in respect of hope. [Quraan: Al Kahf, Chapter 18]
People forget Allah’s Power and they start relying on their wealth and sons as a form ofpower in this world. People forget that both wealth and sons are gifts from Allah. Allah caneasily take away either or both of these gifts just as easily as He gave them in the first place.If we look around us in this day and age, people more or less idolise those with wealth.Good deeds are better in the sight of Allah because they last. Whereas wealth and sons arelike the rain sent by Allah. It is momentary. However the rain can be a blessing, which feedsthe vegetation. Or the rain can disappear and the vegetation becomes dry stubble.If we think about it, on the Day of Judgment, neither wealth nor sons will be of any use.However, the good deeds will be a means of salvation. In the Zubbur – the book of deeds,only the deeds will be written. What else? After all, Zubbur is a book of deeds and not a bookof bank balances and number of sons!Going back to the first reference from the Quraan in this section we are told:
Allah, Al Muqtadir the Powerful, has the Power to do whatever He wills. On Qiyamatthe Day of Judgment, Allah can punish us with a powerful punishment or forgive us if we hadtruly did Tawba turned towards Him in repentance before we departed from Dunya theworldly life and performed good deeds in the service of our Rabb (Lord). May Allah giveeach one of us the determination to do good deeds so that we experience the assembly oftruth where there is the presence of the Sovereign Powerful. Aameen.
90 70 – AL MUQTADIR
MEDITATIONThe person who reads Ya Muqtadiru 1111 times everyday, will find all tasks become easyand whatever lawful that person wants, he / she gets, lnshaa Allah. This Name can be readin conjunction with the next Name as Al Qaadir ul Muqtadir. Inshaa Allah we shall see theadvantages of reading the two names together in the next section .
91 69 – AL QAADIR
3 ("And to preach thus) ‘Seek forgiveness of your Rabb (Lord) and turn to Him repentant thatHe may grant you to enjoy good until a time appointed and bestow His abounding grace onall who abound in merit! But if you turn away then I fear for you the penalty of a great day.’”4 "`To Allah is your return and He has power over all things.'" [Quraan: Hud, Chapter 11]
The objective of this book is to try and return to Allah before our natural death overtakes us.In other words, we want to ‘die before dying’. We want to meet our Rabb (Lord) before wephysically disappear off the face of the earth. In the above reference we are informed thatAllah has the power to return us to Him. That is Allah can make that happen for us to meetHim before we physically die. The Miraaj (Ascension) of the Holy Prophet, Muhammad ,is proof of this meeting with Allah. The forty days fast of Prophet Musa on mount Toor isproof of this meeting with Allah. The three days imprisonment of Prophet Yunus in the fishis proof of this meeting with Allah.However in the above three examples there are different merits. Starting with the lastexample first, Prophet Yunus ran away from the presence of Allah and he was imprisonedfor three days. Then Allah showed mercy towards him. Prophet Musa spent thirty daysfasting and Allah said that it was not enough, he had to fast another ten days to make up
92 69 – AL QAADIR
forty days in total. Prophet Muhammad resting after he had been Praising Allah for mostof the night, eyes closed, and Allah could not wait to meet him. Allah sent Hadhrat Jibraeelto bring His Beloved to Him.The moral is that Allah is Able to meet whomever He wishes in whatever time He chooses.There is no compulsion for Allah to fix a time for meeting. Similarly, Allah is Able to dowhatever He wishes whenever He wants and there is no compulsion for Him to do so. Justlike we are told in the above reference: Seek forgiveness of your Rabb (Lord) and turn to Himrepentant that He may grant you to enjoy good until a time appointed and bestow Hisabounding grace on all who abound in merit!Everything is based on merit. That is what the above examples show us. Everyone receivesAllah’s grace based on their merit. That is, Allah’s grace is based on the merit of the receiver.Now let us look at another example from the Quraan:
70 It is Allah who creates you and takes your souls at death. And of you there are some whoare sent back to a feeble age so that they know nothing after having known (much), andAllah is Knower, Able. [Quraan: An Nahl, Chapter 16]
Allah first creates us because He is Able to do so. Our soul is taken back at death becauseAllah is Able to do so. Similarly Allah gives each one of us a different life span. Some Hetakes back in early, middle or late age in life. However there are some who live to be over100 years old. If you have ever seen a person who has attained 100 or more years of lifespan, you will find that their hair starts to grow black again. Their teeth start to appear again.If Allah can do that, and show us His Power to do that, then we should not doubt that Allah isAble to do anything He wishes. Allah gives us visual proofs. As Allah says in the abovereference:And of you there are some who are sent back to a feeble age so that they know nothing afterhaving known (much), and Allah is Knower, Able.May Allah make us understand His finest mysteries since He is Able to make us understand.Aameen.Allah is Al Qaadir the Able, who can do anything, if He wills, without any difficulty. Allahalone created the Dunya world without any assistance, by Himself, because He is Able todo so. Why did He create all this? Because Allah wanted to show us His Rahmat Mercysince He is the Rabb il Aalameen. And that Rahmat is Muhammad , Rahmat ul lilAalameen.
93 69 – AL QAADIR
MEDITATIONThe person who reads Al Qaadir ul Muqtadir 1111 times everyday, will find that Allah is Ableto do whatever He wills and with the joining of the Name Al Muqtadir, Allah will also makewhatever lawful that is desired to happen, Inshaa Allah.The person who performs two Rakaat Nawafil Salaah and reads Al Qaadiru 100 times, his /her enemies will be degraded provided the person who reads is truthful, Inshaa Allah. If aperson feels like taking revenge on someone, that person should read Ya Qaadiru 41 timesand the feeling for revenge will sub .
94 68 – AS SAMAD
Since Allah is the One and Only there can be nothing that brought Him into being. Allah didnot come into being from any event or condition. Allah always existed and will always exist.Allah is independent of conditions. In fact, Allah creates the conditions for existence for Hiscreation. As Samad means awake, never asleep nor with any need to sleep. As Samadmeans alive, living without any need for food. In other words, As Samad means, without anyneed for anything whatsoever. In Islaam we believe that Allah does not beget nor is Hebegotten, unlike the Christian belief. That means Allah Was, Allah Is, Allah Will Be, withnothing beside Him. That is Allah is Samad, Eternal without beginning, without middle,without end.As Samad means that nothing can enter or leave. As Samad means indivisible, the One whois not and cannot be divided. As Samad means infinite, that is One who has no boundariesand is limitless. Therefore it follows that since Allah is without limits then how can He beget?Begetting can only take place if a boundary is drawn to distinguish one entity from another,from the begetter to the begotten. Therefore Allah does not beget. Similarly, it follows thatsince Allah is without limits then how can He be begotten? Begotten can only come intoexistence from another entity. Then who would this other entity be? Likewise, again aboundary is needed to distinguish the begotten from the begetter. To say it again, in both the
95 68 – AS SAMAD
above cases of ‘begetting’ and ‘begotten’ a boundary needs to be drawn to distinguish oneentity from the other. That is totally against the concept of limitless or infinite.This is why idol worshipping is forbidden! How can Allah who is without boundaries berepresented by the sun, moon or stars? How can Allah, who is infinite be represented by atree, an animal or a statue? All the symbols mentioned are finite. That is they all haveboundaries. That is they can all be differentiated by their size and appearance. The idolworshippers place limitations on Allah! May Allah save us from such ignorance!All the symbols mentioned above have all come into existence. Therefore they are noteternal. Neither did they exist by themselves. All the symbols mentioned above willeventually cease to exist. Therefore they are not eternal. If we think about it, all the symbolsmentioned above are perishable like ourselves. Then what is the point of worshipping somesymbol or idol which can neither harm nor benefit us in any way? Then why not worship theOne Real Creator who created these symbols and who is also our Creator? Everything willperish except Allah.
74 Ibraheem (Abraham) said to his father Azar: "Do you take idols for gods? I see you andyour people in manifest error."75 So did We show Ibraheem the power and the laws of the heavens and the earth that hemight (with understanding) have certainty.76 When the night covered him over he saw a star. He said: "This is my Rabb (Lord)." Butwhen it set he said: "I do not love those that set."77 When he saw the moon rising in splendour, he said: "This is my Rabb (Lord)." But whenthe moon set he said: "Unless my Rabb (Lord) guides me I shall surely be among those whogo astray."78 When he saw the sun rising in splendour, he said: "This is my Rabb (Lord). This is thegreatest." But when the sun set he said: "My people! I am free from your (guilt) ofassociating partners to Allah.”79 "I have set my face firmly and truly toward Him who created the heavens and the earth,and never shall I associate partners to Allah." [Quraan: Al Anaam, Chapter 6]
May Allah save us all from ignorance and grant us all an understanding which leads tocertainty. Aameen.
Allah is As Samad the Eternal. Without beginning or end. Allah does not beget neither isHe begotten. And yet Allah Al Muheet encompasses everything in His knowledge. Theentire creation is by nature perishable. That is how Allah created everything to show us thedifference between Him and us. Only Allah is Daiem the One who Exists forever.
96 68 – AS SAMAD
The person who reads Allahu Samad 1111 times everyday, will become free of any needsfrom others, Inshaa Allah. To achieve spiritual enlightenment, Allahu Samad should berecited 3125 times under the guidance of a spiritual master .
97 67 – AL AHAD
Chapter Al Ikhlaas starts with the verse: Say: He is Allah the One and Only. Everything isunder the command of Allah. If there were many gods, then there is bound to be thepossibility of a disagreement between the gods. It would be impossible for existence to servemany gods just as one person cannot serve many masters at the same time. On the otherhand, one master can have many servants. Just as Allah the One and only has many angelswho serve and obey Him. The angels follow the command of One Master in whose ordersthere cannot be any conflict or disagreement.Let us take a crude example to prove our point. We all have one brain. The brain commandsthe limbs. The brain commands the legs to walk in a particular direction. Both legs will followeach other, assisting each other, to get to the destination. Now let us suppose that we hadmore than one brain functioning independently. Then if one brain commands one leg tofollow a particular direction, and the other brain commands the other leg to follow an oppositedirection, it would be impossible to walk or to get anywhere.Taking this example, one stage further, when we find a person whose behaviour is notnormal, we say that that person is mad or possessed. That is, the brain of that person is notfunctioning normally. Someone or something is manipulating the brain of that person in adifferent direction.
98 67 – AL AHAD
We only have one body which functions as one single unit. The body is under the commandof one single brain. Therefore our body, brain, spirit and soul must also function as one unitto serve only One Master. That One Master is Allah. Like the saying goes: “You can’t pleaseeveryone!” If one person cannot please every person, how can one person please manygods?Now if we can all accept that what has been stated above is true, then how can any normalthinking human being come to the conclusion of many gods? Appearances deceive! Inappearance we find multiplicity. In reality there is only Oneness. And that Oneness of Allah issuch that there is nothing like Him.When we believe in the Oneness of Allah then none of us is different from each other. Weare all supposed to respect each other just like we are to look after our one body.
12 You who believe! Avoid suspicion as much (as possible). For suspicion in some cases isa sin, and do not spy on each other nor speak ill of each other behind their backs. Wouldany of you like to eat the flesh of his dead brother? You would abhor it...but fear Allah. ForAllah is often Returning, Merciful. [Quraan: Al Hujuraat, Chapter 49]
Just as brothers are from one family, so are the Muslims as one family. And the Muslims canonly be one if they all truly believe in Allah’s Oneness. May Allah, Al Ahad, the One, make allthe Muslims as one community. AameenThere is only Allah Al Ahad the One Master whom we, the Muslims, need to serve andplease. To serve Him is Hamd to Praise Him, unlike the idol worshippers who have toserve and please numerous gods and idols, which are perishable and did not exist bythemselves. Only Allah is Daiem who is Everlasting.
99 67 – AL AHAD
MEDITATIONThe .
Al Hamdu Lillah, All Praise is for Allah, 33 Names out of the 99 Names of Allah have been completed here.
100 66 – AL WAAHID
73 They do blaspheme who say: “Allah is one of three in a trinity”, for there is no god exceptOne God. If they do not desist from their word, a grievous penalty will fall on the disbelieversamong them.74 Why do they not turn to Allah and seek His forgiveness? For Allah is Forgiving, Merciful. [Quraan: Al Maaida, Chapter 5]
The Attribute Waahid is sometimes used in association with the word god to emphasise OneGod in the Quraan. The above reference is one such example. However Ahad is an Attributeof Allah which is used to describe that Allah is Ahad or One. There is a very subtledifference. Whenever the message or verses of the Quraan are a warning for thedisbelievers to avoid blasphemy the Attribute Waahid is used. What is this subtle difference?This subtle difference is that when spreading the message of Islaam or instructing thedisbelievers, show kindness towards them, so that they may be guided. Love and kindness issomething every living creature yearns for. It is through love and kindness that we canexplain that ilaha is Waahid. And Allah is willing to forgive the past sins of a disbeliever whoenters Islaam. If we look at the examples set by Prophet Muhammad , the examples setby the Companions of Prophet Muhammad and the Awliyaa Allah (Saints), we findthat they had to have six qualities combined in the one person. This is stated in the bookAarif ul Maarif by Hadhrat Shahab ud Deen Suhrawardi . It is stated in Aarif ul Maarif in thechapter on Initiation of the Seeker:
101 66 – AL WAAHID
Our Shaykh – Abdul Qadir al Jilani has said: “It is improper for the shaykh to sit in theposition of pillage, or to sneer at the sword of benevolence until he becomes qualified withthe following six qualities:
Name QualityAllah - To cover up sins and to forgive.Muhammad - To intercede and to accompany.Abu Bakr - Truthfulness and benevolence.Umar - To command and forbid.Usman - To feed the poor and to pray when others sleep.Ali - To be knowing and brave.
If these qualities are not possessed by the Shaykh, he is unworthy of the initiation of theMurshid. If he possesses these qualities then follow under his banner. If he does not possessthese qualities, Shaytaan has made him his friend and he will not participate in the benefitsof this life or the next.” [Aarif ul Maarif]
Initiation of a seeker requires the above six qualities in one teacher. Similarly the initiation ofthe disbelievers to Islaam also requires the above six qualities in the one who calls thedisbelievers to Islaam.Unfortunately, today’s ‘Shaykhs’ are more interested in how much money they can raise fromtheir ‘Mureeds’.Hence the difference between the Attributes Al Waahid and Al Ahad is just the one letterWaw with a numerical value equal to 6. Both the Attributes of Allah mean - the One. Thedifference in spelling these two Attributes is to show us what is required of us the Muslimswhen we call the non-Muslims to Islaam.The word god or gods is what the disbelievers understand. Therefore Allah explains to us inthe Quraan to tell them that there is only ‘One God’. For the Muslims, There is no god onlyAllah. There is a very subtle difference here. When we can understand this differencebetween ilaha and Allah then we can understand that Allah is not a god. Between ilaha and
Allah there is also a difference of one letter Laam . Once we understand that ilaha isWaahid, then and only then will we understand Allah is Ahad.
163 And your god is One God; there is no god only He the Compassionate, the Merciful. [Quraan: Al Baqara, Chapter 2]
Call the disbelievers with love and kindness with the six qualities mentioned in this section.Tell them that there is only One ilaha God. The Muslims praise One Allah unlike theidol worshippers who have to serve and please numerous gods and idols, which areperishable and did not exist by themselves. Only Allah is Daiem who exists forever.
102 66 – AL WAAHID
The .
103 65 – AL MAAJID
73 They (the angels) said: "Do you wonder at Allah's command? The mercy and blessings ofAllah be upon you, people of the house! He is indeed worthy of all praise, full of all glory!"74 When fear had passed from Ibraheem and the good news had reached him he began toplead with Us for Lut's people.75 Ibraheem is mild, imploring, penitent. [Quraan: Hud, Chapter 11]
Noble qualities are praiseworthy. Nobility is the opposite of common. Nobility is consideredas lordly, aristocratic, majestic. In the case of Allah, Allah is Al Maajid - the Noble becausethere is nothing like Him. Allah is Al Maajid because He is Majestic. There are certain rulesand etiquette that must be observed in this world. For example, when we are in the presenceof our parents we have to be courteous. We have to observe our manners. Similarly whenwe are before Allah, Al Maajid, we must also observe the proper rules and manners.When are we in the presence of Allah? All the time! Allah is aware of our every movement ofevery part of our body. That includes every atom of our body.Therefore, in the presence of Allah Al Maajid, we must observe noble qualities. We must tryand emulate noble qualities. Since Allah is aware of us every moment, we must keep thenoble qualities within ourselves and act accordingly every moment of our life. If we practicethese noble qualities long enough, we will behave in a noble manner in front of everyone,Inshaa Allah.The example given to us in the above verse is that of Prophet Ibraheem . In fact, all ofAllah’s Messengers displayed noble qualities. They all possessed superiority over their
104 65 – AL MAAJID
communities as Allah’s Messengers . And coming back to the example we have at hand,Prophet Ibraheem started to plead with Allah for Prophet Lut’s people. That is a noblequality. Just as Prophet Muhammad has taught us to ask Allah for our brothers what wewould ask Allah for ourselves. That is a noble quality. Caring for others is a noble quality.Prophet Muhammad used to pray throughout the night asking Allah for forgiveness forhis community, that is a noble quality, because he cared for his community.It is because of their noble qualities that Allah chose them as His Messengers. Allah blessedeach one of His noble Messenger with certain noble titles. For example:
is the difference between Jalaal and Jamaal ? The first Laam in Jalaalis changed into a Meem to arrive at Jamaal. And that Meem is the first letter of Maajid
which is Nobilty. And the same Meem can be found at the end of Daiem the Onewho lives forever.
105 65 – AL MAAJID
The person who reads Ya Maajidu endlessly everyday, will become enlightened, InshaaAllah. Alternatively, read Ya Maajidu 1111 times everyday .
106 64 – AL WAAJID
39 As for those who disbelieve, their deeds are as a mirage in a desert. The thirsty onesupposes it to be water till he comes to it and finds it to be nothing. Instead he finds Allahthere, so He pays him his due; and Allah is swift in reckoning. [Quraan: An Noor, Chapter 24]
Either we can find Allah or Allah can find us! There is nothing hidden from Allah, yet Allah ishidden from us! We will all find Allah one day, and Allah will pay us our dues. If we arebelievers in Allah and His Books, and His Angels, and His Rasools (Messengers), and theLast Day, we will be paid what we will be pleased with, Inshaa Allah. Otherwise whatevergood we do, it will be worthless. That is what the above reference tells us. Whatever gooddeeds that a disbeliever does in this world, he will be paid back by Allah in this world. Thereis nothing left for the disbeliever in the next world. For a believer, some of the good deedsare paid back in this world and the next, while other good deeds will be paid back in the nextworld.For us to find Allah is not easy. How can we find the One who cannot be seen? It is veryeasy for Allah to find us, whether we are visible or invisible. Since the jinn and angels areinvisible, Allah can find them too, because nothing is hidden from Allah.We have already come across Allah’s Attribute Al Waahid, the One. Now we are looking at
Allah’s Attribute, Al Waajid, the Finder. The difference between Al Waahid the One,
and Al Waajid the Finder, is just one Nukhtah or dot. Al Waahid has the letter Hainstead of the letter Jeem in Al Waajid. The Finder is capable of finding anything Hewants to. Since all creation is from Nukhtah, it is easy for Him to find whatever or whoeverHe wants to find.
107 64 – AL WAAJID
There is subtle difference between Al Waahid and Al Waajid. Allah cannot be contained inthe entire universe, yet Allah can be found in the heart of a true believer. The Mount Toorwas crushed by the revelation of Allah’s Glory. Yet Prophet Musa , a true believer, justfainted. Prophet Musa could just about bear Allah’s Glory and Majesty. Therefore no harmcame to him.Since the difference between Al Waahid and Al Waajid are the letters Ha and Jeem, we go
for Hajj pilgrimage to find Allah. There is oneness in the pilgrims, in their dress, in theirprayers, in their aim to be forgiven by Allah. And the person who taught us all the rites of Hajjis none other than Prophet Muhammad . Therefore let us now find one more examplefrom the Quraan in relation to Al Waajid, the Finder:
Prophet Muhammad had not received any new revelation from Allah for quite some time.Allah addressed His Beloved, Muhammad , and reassured him that Allah had neitherforsaken His Beloved, nor was Allah displeased with him. Where did Allah find Muhammad ?Wajood is the manifestation of that which was not there before. Allah, Al Waajid findswhatever is required to give us a Wajood. Similarly, Allah, Al Waajid, found His Belovedas an orphan and Allah found for him shelter. Similarly, Allah, Al Waajid, found His Beloved wandering, and Allah found for him guidance. Similarly, Allah, Al Waajid, found HisBeloved in need, and Allah found for him a means to make him independent. For everyneed, Allah can find a solution for us. For every difficulty, Allah can find a solution for us.Similarly, for every question that was posed to Prophet Muhammad about living by therules of Islaam by the community, Hadhrat Muhammad received the answer from Allah.Allah is Al Waajid the Finder who can find every little thing, even an atom’s worth of good
or evil. Allah Knows the mysteries of the unseen. Nothing is hidden from Him. OnlyAllah is Daiem the One who exists forever.
108 64 – AL WAAJID
MEDITATIONThe person who reads Ya Waajidu while eating, that food in the stomach of that person willbecome a form of energy and light, Inshaa Allah. The person who reads Ya Waajidu onceand blows it on a glass of water, the person who drinks the water will become loving towardsthe one who read Ya Waajidu, the Name of Allah on the water, Inshaa Allah. This will onlywork where it is lawful .
109 63 – AL QAIYY.
From the above example we find that Allah is Self-Subsisting Eternal. In other words, Allahhas always existed, Allah still exists, and Allah will always exist. To say it in yet another way,Allah did not come into existence and neither is Allah’s existence timed. On the other handevery living thing comes into existence or being at a certain ordained time. Every living thingexists on this earth for a defined period. It comes into existence because Allah exists! ButAllah is not dependent on anything. Allah does not feel any fatigue of any kind. Neither doesAllah sleep. There is a lesson in the last sentence for the Muslims. Allah does not sleep but
110 63 – AL QAIYYUM
the majority of the Muslims of this day and age are asleep even while they are awake! Whenit comes to Islaam they stop thinking.To continue, His are all things in the heavens and earth, meaning that everything in theheavens and earth is dependent on Allah. Yet Allah is Self-Subsistent. Even intercession forsomeone is dependent on Allah’s permission. Allah’s permission for intercession is notdependent on anyone or anything. Allah knows what is before and after. In other words Allahknows what awaits for us in the next moment, the next day, the next year, the next life just asHe knows what we have done this instance, yesterday, last year and all our life up to thismoment. Each moment of our life is dependent on Allah. Each life depends on every momentor to explain it in a different way, each life is made up of every moment!Every moment makes a day. The day depends or subsists on the moment. Every week ismade of 7 days. The week depends or subsists on the 7 days. Every month is made up ofweeks. Every month depends or subsists on weeks. Every year is made up of months. Everyyear depends or subsists on the months. Yet Allah is independent of all this because He is AlQaiyyum, the Self-Subsisting.We mentioned intercession above. On the Day of Judgment or Qiyamat, intercession will bewith Allah’s permission. The Day of Qiyamat is dependent on Allah. Heaven and hell aredependent on Allah. How, when, where is all dependent on Allah. Our reward or punishmentis dependent on Allah. Yet Allah is independent of the Day of Qiyamat, because Allah is AlQaiyyum, the Self-Subsisting.Let us look at another example from the Quraan:
61 Is he whom We have made a fair promise which he will find (true) like him whom We havegiven to enjoy the comfort of the life of the world, then on the Day of Judgment he will be ofthose brought up?62 That day He will call to them and say: "Where are My partners whom you imagined?" [Quraan: Al Qasas, Chapter 28]
Since we mentioned Qiyamat the above example is about Qiyamat and the reason willbecome clear Inshaa Allah.We start in the above reference with a promise from Allah on which the fortunate will subsist.And the opposite is shown to us of the unfortunate who subsist on the comfort of this lifewhich again is provided by Allah. On the Day of Judgment the second group will be askedabout the partners that they set up with Allah.The reason for choosing the above verse was to show the connection between Al Qaiyyum
Allah is Al Qaiyyum the Self-Subsisting who will preside over the Yaum Day ofJudgment. If we are true Muslims we are relying on Wasilah the intercession of Allah’sBeloved, our Nabee, Muhammad for Allah’s mercy and forgiveness and Allah doesnot break His promises.
111 63 – AL QAIYYUM
The person who reads Ya Qaiyyumu 1111 times everyday, will gain respect from the people,Inshaa Allah. The person who reads Ya Hayyu Ya Qaiyyumu after the Fajr (morning) prayerwill overcome laziness, Inshaa Allah .
112 62 – AL HAYY
Allah is the Living and Self-Subsisting. Our life is borrowed from Allah’s Attribute of Al Hayy.Allah has created 18,000 worlds. To say it in another way, Allah has brought to life 18,000worlds. Allah is Living and Self-Subsisting without any cause. The life of the 18,000 worldsincluding our own, have all been caused by Allah. The cause of life and the subsistence ofthese worlds are dependent on Allah. Allah’s existence is independent of a cause and HisSubsistence is not dependent on anything or anyone. But why did Allah give us life in the firstplace?
3 He has revealed the Book to you in truth, confirming what came before it, and He revealedthe Torah and the Injeel4 As a guidance to mankind and He has revealed the Criterion. Then those who disbelieve inthe signs of Allah a terrible punishment awaits them and Allah is Mighty, stern in retribution. [Quraan: Al Imraan, Chapter 3]
Allah gave us life so that we could come to this world. Allah gave us life so that we can learnfrom the Book. Learn what? Learn the guidance that will be useful for us in the next world. IfAllah has trusted us to be His Khalifah in this world, then it is up to us to learn the guidancefor the next world. As it has been mentioned in Ayn al Miftah numerous times, that this worldis the school of learning for the life in the next world. Allah has no use for heaven for Himself!Allah has no use for hell for Himself! Heaven and hell have been created, as reward orpunishment respectively, for our deeds. Since our life is temporary in this world, as we knowit, life is for eternity in the next world. Therefore Allah has revealed the Book in truth asguidance for mankind. Allah has no need for our good deeds because Allah is the Living,Self-Subsisting. Allah has no need for our bad deeds because Allah is the Living, Self-Subsisting. Therefore, Allah in His infinite mercy has sent us guidance for our own benefit
113 62 – AL HAYY
and not His. If we do good deeds, there is life for us in heaven for eternity. If we do evildeeds, there is life for us in hell for eternity. As a certain person said: “In this world, theultimate end of life is death. In the next world, eternal life begins from death.” Here is anexample of that from the Quraan:
27 "You cause the night to pass in to the day and You cause the day to pass in to the night.You bring the living out of the dead and You bring the dead out of the living. And You givesustenance to whom You please without measure." [Quraan: Al Imraan, Chapter 3]
In this reference we have the obvious meaning of the alternation of night to day and day tonight. The spiritual meaning is that we knew nothing of the scripture, we were in darknessand Allah enlightens us with guidance contained in the Quraan. Similarly, there are thosewho after being enlightened slip into darkness or ignorance.Allah, Al Hayy, the Living brings the living out of the dead and He brings the dead out of theliving. Bringing the living out of the dead has many meanings. One meaning is related to thedead earth and Allah pours rain over the dead earth and makes it sprout with vegetation.Another meaning is that those who abstained from the comforts of this life for the sake ofAllah are like the dead. At death these people are given life without end. They are freed fromthe shackles and bonds of the earthly life to enjoy real life in the presence of Allah the Living,Al Hayy.Bringing the dead out of the living are those that thought this earthly life was the only life andthere is no other life. They enjoy their earthly life but they are in reality dead, because theyhave ignored the real life of eternity for the sake of a temporary life. In worldly terms theseare the dead who are brought out of the ‘living’. In the next life these will be the ones who willwish for death to escape their torment. But there will be no death in the next life! There willbe no escape from life in the next world!May Allah guide us all so that we use our lives on this earth sensibly in order to gain life inthe next world. Aameen.Allah is Al Hayy the Living who has given us a temporary life in this world to seek
MEDITATIONThe person who reads Ya Hayyu 1111 times everyday, will never become ill, Inshaa Allah.An ill person should read Ya Hayyu 11 times or someone else should read it for that personand blow the breath on the patient, the latter will regain health, Inshaa Allah.The person who reads Ya Hayyu 70 times everyday, Allah will give that person a long life.
114 62 – AL HAYY .
115 61 – AL MUMEET
78 It is He who has created for you ears, eyes and hearts. How little thanks you give!79 And He has created and multiplied you in the land, to Him you will be returned.80 It is He who gives life and causes death, and His is the alternation of night and day. Doyou understand? [Quraan: Al Muminoon, Chapter 23]
In the above reference we find that Allah has given us ears, eyes and heart. We should bethankful for these gifts.Multiplication in the land is the granting of life by Allah. The end for each earthly life is death.If death had not been created this earth would run out of space. Allah had to create death inorder to regulate the life on earth. If death had not been created then multiplication would nothave been allowed.Everything created by Allah has an equal and opposite. With the creation of life, Allahcreated death to keep the balance. Yet there is nothing and no one like Allah. Allah breathedthe Ruh (Spirit) into Adam when He created him. ‘To Him you will be returned.’ So the Ruhhas to return to Allah. The body is created from the earth. So the body has to be returned toearth. Everything has to be balanced out. Without the creation of death, the balance wouldnot be maintained. Hence we are given the analogy: ‘His is the alternation of night and day.Do you understand?’Just as there is night, there has to be the opposite, which is the day. Just as there is life,there has to be the opposite, which is death. After death, just as there is heaven, there has tobe hell.If Allah did not create death, the soul would not be able to separate from the body. The soulhas the Word of Allah that it will be released from the body after a certain period. The body is
116 61 – AL MUMEET
like the night. The body is the darkness. The soul was like the day and it becomes dark likethe night after attaching itself to the body for years. The soul needs to be kept bright as theday. And Zikr Allah is its food which keeps it healthy. There is no escape from death for anycreation.
35 Every soul must taste death, and We test you with evil and with good as a trial. To Us youmust return. [Quraan: Al Anbiyaa, Chapter 21]
For a Muslim, death is not death but it is the door to eternal life. For a Muslim, death is notdeath but it is the door which makes one realise the reality. Therefore, death has beencreated as means to free the spirit from the body. The only snag with life is that we will betried with evil and good. It is a means devised by Allah to weed out the true Muslims from thepretenders. And death is the means to realise our sincerity as Muslims. Just as Allah says inthe Quraan:94 Say (to the Jews): "If the abode of the hereafter with Allah is only for you alone and not foranyone else then long for death if you are truthful.95 But they will never long for death on account of that which their hands have sent onbefore them. And Allah is well acquainted with the wrongdoers. [Quraan: Al Baqara, Chapter 2]
For a good person, death is a means of preserving his or her good deeds and freedom fromthe trial of evil and good. For a bad person, death is something disliked, because of his orher bad deeds and fear of the unknown. So how do we prepare for death?
158 Say: "Mankind! I (Muhammad) am sent to you all as the Rasool (Messenger) of Allah towhom belongs the dominion of the heavens and the earth. There is no god only He, thatgives life and death. So believe in Allah and His Rasool, the unlettered Nabee (Prophet) whobelieves in Allah and His words and follow him so that you may be guided." [Quraan: Al Aaraaf, Chapter 7]
We must follow Allah’s guidance in the Quraan. We must follow His Rasool Muhammadso that we may be guided.Allah is Al Mumeet the Creator of Death who created Mawt death as the end of our
worldly life in which we must seek Knowledge of Allah. And if we fall short, and we will allfall short without a doubt, we must say Tawba ask for repentance, because Allah is theAcceptor of Repentance. May Allah forgive our sins and guide us on the right path. Aameen.
117 61 – AL MUMEET
MEDITATIONThe person who cannot control his / her Nafs (soul - desires) should place his / her hands onthe chest during bedtime and keep reading Ya Mumeetu every night until he / she fallsasleep. Allah will give that person control over his / her desires, and make the Nafs (soul .
118 60 – AL MUHYEE
158 Say: "Mankind! I (Muhammad) am sent to you all as the Rasool (Messenger) of Allah towhom belongs the dominion of the heavens and the earth. There is no god only He that giveslife and death. So believe in Allah and His Rasool, the unlettered Nabee (Prophet) whobelieves in Allah and His words and follow him so that you may be guided." [Quraan: Al Aaraaf, Chapter 7]
Life is an Attribute of Allah. Allah loans us this quality of life so that we may experience Hiscreation and we may know Him who created us. In the section on Al Mumeet, we came toknow about death. So in this section we must now know something about life. Life on thisearth is like a loan which has its repayments. Life is not about taking whatever we can getbut it is about give and take. The reason that Allah creates us is so that we can know Himand follow His guidance. The reason Allah gave us life is so that we can contribute somegoodness to creation, however little it may be.There are those that are living on this earth yet they are dead. They are dead because theyhave failed to understand the reason for attaining life. They are dead in the sense that theychase after the worldly things. Worldly things are physical things. On death the Ruh or spiritis separated from the physical body and the worldly things are all left behind. Allah hasshown us this by example. The pharaohs had their worldly possessions buried with them.They did not manage to take their worldly possessions away from this earth with them.Nobody can! Those who have woken up to this fact and realised this, they are the ones whopossess life. The latter have realised that we can only take with us whatever goodness wedid in the Name of Allah. We can only take with us whatever Zikr Allah we did while on thisplanet. Since Zikr Allah cannot be seen in the physical world, it is related to the spiritualworld. Goodness of action is only for a limited time but it is recorded in the invisible.Allah has given us life to prepare us for the next world. We are a spirit that must prepare for alife in the spiritual world. How do we prepare for the next life?
119 60 – AL MUHYEE
So believe in Allah and His Rasool, the unlettered Nabee (Prophet) who believes in Allah andHis words and follow him so that you may be guided."If we are a spirit then why must we come to the physical world in the first place?The spirit needs a physical body to experience life. For example we need a physical body totouch, taste and smell. Just as a certain scent or taste triggers memories of years gone by.The spirit remembers the experiences. How can that be? Remember when Allah taughtHadhrat Adam all the names? Allah first created Adam in the physical form and thentaught him knowledge of all things. Whereas the angels who are in spiritual form were askedby Allah to name the things and they replied: “We have no knowledge except what You havetaught us.” So we come back to the fact that life is given to us by Allah so that we may learnfor the life yet to come after physical death.Let us look at one more example from the Quraan:
67 He it is who created you from dust, then from a drop then from a clot, then brings youforth as a child, then lets you attain full strength and then lets you become old though someamong you die before and that you reach an appointed term, so that you may understand.68 It is He who gives life and death; and when He decides upon an affair He says to it "Be!"And it is. [Quraan: Al Mu_min (or Al Ghaafir), Chapter 40]
Allah the Al Muhyee Giver of Life has chosen to give us life and created us from dust etc,so that when we reach our appointed term (death) we should have understood the meaningof life. The only way we can understand the meaning of life is by saying Allah’s Hamd His
Knowledge which will be beneficial to us in the next world. Allah’s decision is just “Be!”That is Knowledge! May Allah enlighten everyone so that we do not waste our lives in thisworld. May Allah enlighten us all so that we may use our life for gaining knowledge of ourCreator, Allah.
120 60 – AL MUHYEE
A sick person who reads Ya Muhyee 1111 times everyday, will regain health, Inshaa Allah.Alternatively someone else can read it for a sick person and should blow the breath on thesick person. The sick person will recover and regain health, Inshaa Allah.The person who reads Al Muhyee 89 times everyday and blows the breath on himself orherself will remain free from all kinds of imprisonment, .
121 59 – AL MUEED
11 It is Allah who begins creation; then repeats it. Then you shall return to Him.12 On the day that the hour will be established the guilty will be struck dumb with despair. [Quraan: Ar Room, Chapter 30]
Repetition or restoration in this reference firstly applies to the Day of Judgment. Allah willrecreate or repeat or restore the creation of humans for Judgment. That is what isunderstood from the verse that follows in the above example. But the disbelievers do notbelieve in resurrection. There is a very simple answer to prove that Allah can recreate orrestore us after death. Our body has the ability to heal cuts and wounds. New skin forms toreplace the damaged tissue. The dead tissue eventually falls off. Similarly our skin is beingrenewed everyday while we are awake or asleep, yet we do not notice it. If we can believethis fact about our skin, why is it so difficult to believe that Allah will recreate us? Yet thescientists are trying to recreate extinct life forms from DNA samples. Similarly, when we aretold that in hell the skin will be burned to char and then new skin will grow and the processwill be repeated forever, why is that so difficult to believe?However, this only occurs while the soul is ‘attached’ to the body. This can be observed fromthe body of a dead creature. As soon as the soul is ‘separated’ from the body, the body startsto decay. The skin is no longer renewed or regenerated. To recreate the body, the soul willbe ‘re-attached’ to the body. And if we read further along the same chapter in the Quraan, wefind:
19 It is He who brings out the living from the dead and brings out the dead from the living andwho gives life to the earth after it is dead: and thus shall you be brought out (from the dead).20 Among His signs is this that He created you from dust and then behold you are menscattered (far and wide)! [Quraan: Ar Room, Chapter 30]
122 59 – AL MUEED
Just as our skin dies and scatters wherever we may be sitting, or standing, or walking,similarly we find that the human race is scattered all over the land. We have been createdfrom the same dust that this planet has been created from. So we will return our bodies tothis very earth. The dust of our bodies is a ‘loan’ from the earth by the command of Allah.Therefore we must return it to the earth and bury the dead to repay that loan. It is notpermissible to cremate or burn the human body because the loan from the earth will not berepaid! Even the so-called ‘people of the Book’, the Christians, have started to cremate thebodies of the dead. But Allah can and Allah will recreate those who have been crematedwhether they are Christians or atheists or idol worshippers. Then the ‘cremation’ that willfollow on the Day of Judgment will be endless, because the soul will be attached to the body.Therefore the skin will keep regenerating even after it has been burnt. The torment will beendless.Let us take one more example from the Quraan:
34 Say: "Of your 'partners', can any originate creation and repeat it?" Say: "It is Allah whooriginates creation and repeats it. Then how are you misled (from the truth)?" [Quraan: Yunus, Chapter 10]
Al Mueed , the Restorer has given us two Eid celebration days in Islaam inthe twelve months of the lunar calendar. The first Eid is at the end of the ninth month which isthe month of fasting - Ramadhan. It is the month of abstaining from all food and drink duringthe daylight. The first Eid celebration is on the first day after the completion of the ninthmonth. It takes nine months to complete the creation of a human baby. And the birthday isthe first day the baby arrives in this world. That is the origination. The second Eid day is inthe twelfth month, the month of pilgrimage – Hajj, after performing the rites of Hajj. The Hajjis on the ninth day of the twelfth month and the Eid day is the tenth day.
Allah’s Rasool said, "Whoever performs Hajj for Allah's pleasure and does not have relationswith his wife, and does not do evil or commit sin then he will return (after Hajj free from allsins) as if he were born anew." [Sahih Al Bukhari]
Performing the Hajj is similar to being regenerated or restored! Allah Al Mueed theRestorer continually restores us as mentioned in the example of the skin, and Allah willrestore us on the Day of Judgment. When Allah creates us, or restores us in the physical
world, we become Ayn visible. The real restoration will take place on Yaum the Dayof Deen Judgment. May Allah cover us all with His Mercy. Aameen.
123 59 – AL MUEED
Ya 10 Dal 4 TOTAL 124 TOTAL
If a person has gone missing or runaway, then read Ya Mueedu 70 times in each corner ofthe house at night and say Ya Mueedu bring back the missing person. Inshaa Allah, themissing or runaway person will return within 7 days or news about that person will arrive,Inshaa Allah. (See the section on Al Mubd .
124 58 – AL MUBDEE
We have already come across Al Badee, the Originator and now we come across
Al Mubdee, the Originator. Both these Attributes of Allah mean the Originator. Sowhat is the difference between Al Mubdee and Al Badee?The major difference between Al Badee and Al Mubdee is the Arabic letter Meem ! AlBadee is connected with the creation of the heavens and earth. That is the creation of theheavens is a single act. The creation of the earth is a single act. In reality everything in theheavens and the earth is a living thing. That includes the heavens and earth. The heavensand earth are living things, if only people would realise that! Al Mubdee is connected with theorigination of living things. Every living thing is created from water (Maa with a Meem inArabic) as it is clearly stated in the following reference:
30 Do the disbelievers not see that the heavens and the earth were joined together (as oneunit of creation) then We parted them? We made from water every living thing. Will they notthen believe? [Quraan: Al Anbiyaa, Chapter 21]
The heavens and earth were joined together as one. Then they became many when Allahseparated them. That is, even the heavens and the earth are living things. The ironic part isthat the scientists are looking for water on the planet Mars. Yet the planets are also createdfrom water!There is another reference that we must also look at here:
125 58 – AL MUBDEE
44 It is Allah who alternates the night and the day. Truly in these things is an instructiveexample for those who have vision!45 And Allah has created every animal from water. Of them there are some that creep ontheir bellies; some that walk on two legs; and some that walk on four. Allah creates what Hewills. Truly Allah is Able to do all things.46 We have indeed sent down signs that make things clear. Allah guides whom He wills tothe straight path. [Quraan: An Noor, Chapter 24]
By mentioning alternation of night and day, Allah then instructs us that there is an examplehere for those with vision. Then again we are told that Allah has created every animal fromwater. The next sentence in verse 45 is the example for those who have vision! Of somethere are those that creep on their bellies… seems fairly straightforward at first glance. Weimmediately start thinking of snakes and worms. But Allah is telling us more than that. Allahis telling us look at the planets! Even they are living things and they too ‘creep on theirbellies’! To an observer on the earth, the planets take months or years to move once aroundthe sun. As far as the observer on the earth is concerned, the planets are creeping very, veryslowly.Let us finish with another example from the Quraan:
If we take the example of Hadhrat Adam , Allah originated him from clay and then repeatedthe process with Hadhrat Hawwa (Eve) by creating her from Adam , without a mother.Similarly the example of Prophet Isa is like that of Prophet Adam that Allah originatedhim from the Spirit and created him from Hadhrat Maryam , without a father.Allah is Al Mubdee the Originator who created every living thing from water. The creation is brought into existence under the rules of a Dairah circular or cyclic pattern. Each
living thing has been given a certain kind of knowledge for survival, but the human beinghas been sent to learn further knowledge. Our Rabb (Lord), increase our knowledge so thatwe may know You even better. Aameen.
126 58 – AL MUBDEE
The person who reads Al Mubdee ul Mueedu 1111 times everyday will find the doors ofknowledge open up and attain Sirat al Mustaqeem - the right path, Inshaa Allah.If a person wants to find a lost thing, then he / she should read Al Mubdee ul Mueedu 180times and the lost thing will be found, Inshaa Allah.The person who is about to tackle a difficult task should read Al Mubdeeu and Inshaa Allah,the task will come to a successful conclusion .
127 57 – AL MUHSEE
93 There is none in the heavens and the earth but must come to the Compassionate as aservant.94 He does take account of them and has numbered them exactly.95 And every one of them will come to Him alone, on the Day of Judgment. [Quraan: Maryam, Chapter 19]
Everything in the heavens and earth has been accounted for and numbered so that the totalmatches. For example, all the stars in the sky, all the planets, all the trees on earth, all theleaves on each and every tree have been accounted. You name it, Allah has accounted andnumbered it! And there are ‘learned scholars’ in Islaam who say that numbers have nothingto do with Islaam. If numbers had nothing to do with Islaam, then Allah is One would bemeaningless! Similarly, there would be no need to keep account of prayers, or fasts, or evenmonths. Allah is Al Muhsee, the Appraiser and He wants us to believe in His Oneness. Allahwants us to count our prayers, count our fasts and count the months so that we know theforbidden months from the rest. The only way we can do that is to emulate the Attribute ofAllah and keep accounts. Then Allah Appraises our good actions. Allah either accepts ourprayers, fast, charity or any other good deed, or He rejects it if the intention was not valid.Similarly, our every action physical and verbal is going to be accounted on the Day ofJudgment and it will be appraised. Hence on the Day of Judgment we go to Allah alone. Andwe will have to ‘balance’ the book of deeds with Him. Either Allah will call us to account forour actions, or He will overlook them.
Allah's Rasool said, "None will be called to account on the day of Resurrection, but will beruined." Hadhrat Aisha said "Ya Rasool Allah! Hasn't Allah said: 'Then as for him who will begiven his record in his right hand, he surely will receive an easy reckoning?'" (84:7-8) Allah'sRasool said, "That (Verse) means only the presentation of the accounts, but anybody whoseaccount (record) is questioned on the day of Resurrection, will surely be punished."
128 57 – AL MUHSEE
[Sahih Al Bukhari]Let us take another example from the Quraan:
6 On the day when Allah will raise them all together and inform them of what they did. Allahhas kept account of it while they forgot it. And Allah is Witness over all things. [Quraan: Al Mujaadila, Chapter 58]
Just as Allah has sent us here for a purpose, He has kept an account of it even before wecame to the world. But most of us have forgotten our promise with Allah, when He asked us:“Am I not your Rabb (Lord)?” We all answered: “Yes!” Similarly when we return to Allah,Allah will show us the account of our actions, while we will have forgotten again what we didin this short life. Since Allah is a Witness over everything, He is the one who encompasseseverything. Nothing escapes Allah’s knowledge. Therefore we must learn to keep account ofour own actions and appraise them immediately or at least once per day. If there is anyaction that we feel guilty about, we should endeavour to correct that action so that we do notkeep repeating the same wrong deed.Allah is Al Muhsee the Appraiser who appraises our every Harkat action. When Allahcreated Hadhrat Adam and gave him the title Safee Allah the preferred of Allah, it was
because Allah taught him the knowledge of everything. Since that knowledge is inheritedby each one of us we should know what is good and what is bad. We should know that everygood action has a good reward. We should also know that every bad action has apunishment associated with it. May Allah give us all the opportunity to correct our wrongactions and take our life while we stand firm on faith. Aameen.
129 57 – AL MUHSEE
MEDITATIONThe person who reads Ya Muhsee 1111 times everyday, will achieve enlightenment, .
130 56 – AL HAMEED
1 Alif Laam Ra. A book which We have revealed to you in order that you may lead mankindout of the depths of darkness into light by the leave of their Rabb (Lord) to the way of theMighty, the Praiseworthy! [Quraan: Ibraheem, Chapter 14]
Ignorance is darkness. Knowledge is light. In order to step out of the depths of darkness intolight, or to say it in another way, in order to come out of ignorance and learn knowledge, wemust praise our Rabb. Here, we are not referring to worldly knowledge. Both, a believer anda disbeliever can attain worldly knowledge. But the knowledge being referred to is that whichwill help us in the next world and it is the real knowledge. This is where a believer is requiredto praise his Rabb in order to be let into the light from the depths of darkness. As Allah hasmentioned in the Quraan numerous times, That He does not turn to a person, unless theperson first turns towards His Rabb. Therefore, we must praise our Rabb so that He may turntowards us in Mercy and open the doors of knowledge. Praise is the calling of the one inneed to the One who has no needs. Praise is the thanking of the one who has receivednumerous gifts to the One who bestows the gifts. Praise is a ‘kind of payment’ for the life wehave been given, to the One who gave us life and asks for no payment.Praise takes on many forms. There is praise in Salaah -prayer. There is praise in Zakaat -charity. There is praise in Hajj - pilgrimage. There is praise in Sawm - fast. And above allthere is praise in believing La ilaha ill Allah Muhammadur Rasool Allah - There is no god onlyAllah Muhammad is the Messenger of Allah. It is a mistake to think that we do the abovedeeds as a favour to Allah. We do the above deeds for ourselves because Allah is above anyneed, free of all wants.If Allah has no needs and He is free of any requirements then what is the point of praisingHim? When we praise Allah we ask for His Mercy. When we praise Allah, He teaches uswhat is required for our salvation in the next world. When we praise Allah we attain‘nearness’ to Him. To attain nearness to Allah is the ultimate goal of every human being.
131 56 – AL HAMEED
Unfortunately, the majority of the Muslims only praise Allah because they feel threatened bythe punishment of the next world or they just want heaven. They will get what they deservesince Allah does not let even an atoms worth of good deeds go to waste. But these peoplewill have missed the opportunity to know Allah.The ultimate act of praising Allah is Zikr Allah. Zikr Allah is to remember Allah with thetongue. Allah assigns angels as the helpers of those who do Zikr Allah. Remember ProphetIbraheem ? The angels came to give him the good news of a son. Remember ProphetZakariya ? The angels came to give him the good news of a son. Remember HadhratMaryam ? The angel Hadhrat Jibreel came to give her the good news of a son.Remember Prophet Muhammad ? Hadhrat Jibraeel used to come and say Salaam toHadhrat Muhammad after the birth of each son. Why? Because they all praised theirRabb as He deserves to be praised.One more example from the Quraan:
131 To Allah belong all things in the heavens and on earth. And We have directed the peopleof the Book before you, and you, to fear Allah. But if you disbelieve, to Allah belong all thingsin the heavens and on earth and Allah is free of all wants worthy of all praise. [Quraan: An Nisaa, Chapter 4]
Everything in the heavens and earth belongs to Allah. It has all been created because of Hisgreatest creation, Ahmad, who is better known as Prophet Muhammad . Ahmad wascreated for Hamd – Praise. With Hamd – praising Allah, we become part of the community ofProphet Muhammad . Allah is not in need of our praise for Him, in fact we are in need ofHim to guide us and keep us on the right path so that we may know Him like He deserves tobe known. Prophet Muhammad said: “I have not known You to the extent to which Iought to have known You.” Therefore we, the community of Prophet Muhammad , canonly but try to know Allah to the best of our limited ability, as much as Allah allows us.
Allah is Al Hameed the Praiseworthy. The Miftah key to Knowledge in this Dunya(world) is praise of Allah in order to attain Al Daeim the One who Lives Forever.
132 56 – AL HAMEED
The person who reads Ya Hameedu 1111 times everyday, will receive spiritual knowledge,Inshaa Allah.The person who reads Ya Hameedu 93 times for 45 consecutive days will become free of allbad habits, Inshaa Allah.The person who reads Ya Hameedu for any difficulty will overcome .
133 55 – AL WALEE
62 Behold! Truly on the friends of Allah there is no fear nor shall they grieve.63 Those who believe and guard against evil,64 For them are good tidings in the life of the world and in the hereafter. No change canthere be in the words of Allah. This is indeed the supreme triumph. [Quraan: Yunus, Chapter 10]
Are Muslims, in general, friends of Allah? If they are, then why are they suffering all over theworld? In the above example Allah clearly states: Truly on the friends of Allah there is no fearnor shall they grieve… For them are good tidings in the life of the world and in the hereafter.The friends of Allah that are mentioned in this reference are certain individuals who believeand guard against evil. These individuals have spent their lives attaining nearness to Allah.Allah is Al Walee, the protecting Friend. These individuals are Walee Allah, the friends ofAllah. If every Muslim was a Walee Allah, they would not grieve. If every Muslim was aWalee Allah, they would believe and guard against evil. If every Muslim was a Walee Allah,they would have good in this world and the next.Unfortunately the majority of Muslims are not Walee Allah. They practice Islaam in order toattain paradise and here is a classic example from Hadees:
A Bedouin came to Muhammad, Rasool Allah and said, "Tell me of such a deed as willpermit me to enter paradise, if I do it?" Allah’s Rasool said, "Worship Allah, and worship nonealong with Him, offer the (five) prescribed compulsory prayers perfectly, pay the compulsoryZakaat, and fast the month of Ramadhan." The Bedouin said, "By Him, in whose hands mylife is, I will not do more than this." When he (the Bedouin) left, Allah’s Rasool said, "Whoeverlikes to see a man of paradise, then he may look at this man." [Sahih Al Bukhari]
134 55 – AL WALEE
Notice the last sentence. …a man of paradise… The Bedouin in the above example isneither a friend of Allah, nor a servant of Allah. The teachings of Prophet Muhammadare very subtle. That is what the majority of Muslims of today are, people of paradise. Theyare like the questioner in the above Hadees: "Tell me of such a deed as will permit me toenter paradise, if I do it?" They do not want to know such a deed as to attain nearness toAllah. They do not want to know such a deed as to know the Creator of paradise. They wantto know such a deed which will permit them to enter paradise. Therefore, the majority of theMuslims are not friends of Allah. The above reference from the Quraan is directed at certainindividuals. So when Allah tests the Muslims, they are made to suffer.
155 Be sure We shall test you with something of fear and hunger some loss in goods or livesor the fruits but give glad tidings to those who patiently persevere.156 Who say when afflicted with calamity: "We belong to Allah and to Him is our return."157 They are those on whom (descend) blessings and mercy from Allah and they are theones that receive guidance. [Quraan: Al Baqara, Chapter 2]
Those who pass this test from Allah as quoted in the above reference from the Quraan areWalee Allah, and Allah becomes their Protecting Friend. Walee Allah are also known asAwliyaa Allah.How does a person attain nearness to Allah? Do more than the Bedouin in the aboveHadees settled for. Follow the example set by Prophet Muhammad .Let us conclude with one more example from the Quraan:
196 "My protecting Friend is Allah who revealed the Book and He will choose and befriendthe righteous. [Quraan: Al Aaraaf, Chapter 7]
There are two kinds of friendship. There is friendship of those who are good and there isfriendship of those who are evil. The friendship of the good is based on complete trust. Thefriendship of the evil is based on mistrust, as the saying goes, ‘Better the devil you know!’ Infriendship of the good, one can trust a friend with his / her life. While in the friendship of theevil the opposite is true and it is based on preserving ones life from the other.The friendship of Allah is such that He becomes the Protector of His friends. And thisfriendship is formed with the righteous. To Prophet Muhammad , Allah revealed the Bookand its mysteries. To the righteous from the community of Prophet Muhammad , Allahreveals the mysteries of that very same Book. May Allah guide the Muslims so that theysincerely seek His Friendship, rather than just perform acts for the sake of paradise.Aameen.Allah is Al Walee the Protecting Friend. Allah’s Friendship is based on love. Friendship
should be such that La Shay nothing comes between friends. All friendships are based on
135 55 – AL WALEE
The person who reads Ya Waleeyu 1111 times everyday, will be given spiritual knowledge,overcome difficulties and be free of all kinds of .
136 54 – AL MATEEN
56 I have only created jinn and human that they may serve Me.57 I seek no livelihood from them, nor do I ask that they should feed Me.58 Allah is He who gives sustenance, Lord of Power, the Firm. [Quraan: Az Zaariyaat, Chapter 51]
Allah is Powerful and Firm or Strong. Allah has created jinn and human to serve Him. Allahdoes not need food. Yet Allah is Powerful and Firm. The reality of Allah is that Allah does notneed any food for strength and Allah does not need sleep for rest. Allah’s Firmness is fromHimself and not due to any ‘outside’ interaction. On the other hand, human beings derivetheir strength by Allah’s leave, from their diet or sustenance and rest. Allah provides thesustenance for His creation. Allah feeds His creation and yet Allah is free of needingsustenance. Allah feeds His creation so that they may become firm and praise the One whoprovides for them. By praising Allah we serve Him. By serving Allah, we acknowledge HisMajesty and Strength over us. By acknowledging Allah’s Majesty and Strength Allah providesfor us.The human being starts as a weak baby. Over the years the child grows into an adult andattains firmness by the provision from Allah. As more years pass, the person becomes weakin old age even though the provision is the same. Therefore we go from weakness to firmstrength and then to infirmity. That is the physical meaning of firmness.
137 54 – AL MATEEN
182 And those who deny Our revelations, step by step We lead them on from where they donot know.183 I give them respite, for My scheme is firm.184 Do they not reflect? Their companion is not seized with madness, he is only a clearwarner. [Quraan: Al Aaraaf, Chapter 7]
Allah gives respite to the disbelievers. It is not because Allah is ‘soft’. It is because Allahknows the weaknesses of the human beings. Perhaps they will turn towards Him fromdisbelief to belief. His scheme is firm. He sent Messengers to warn people. He sent booksthat are with us to this day so that we may reflect. Unlike the human being, Allah did not startweak. Neither does Allah grow weak. Allah was Firm. Allah is Firm. Allah will remain Firm.There will be no change in Allah’s Firmness. What does Allah tell us in the above verses?Prophet Muhammad has been sent as a clear, plain, warner by Allah. The differencebetween Mateen and Mubeen is just one Arabic letter. Allah, the Firm sent aClear Warner. The clear warner is one who does not give in to opposition because he is senton a mission by Allah to warn and to remind. The one who warns has to be firm in deliveringthe message. The one who warns is not allowed to alter the message of Allah to please thepeople. The message contains what is beneficial for the present life. Following the guidancein the message needs firmness on our part in this life. The conduct in this life is what leadstowards endless bliss or endless torment in the everlasting life. That is the spiritual side offirmness.Allah is Al Mateen the Firm. Allah is firm against the disbelievers but ready to forgivethose who say Tawba and turn towards Him in repentance. He then opens up their
hearts and minds with knowledge and gives them a light by which He leads them fromdarkness into Noor Light.
138 54 – AL MATEEN
MEDITATIONThe person who reads Ya Mateenu 1111 times everyday, will have firm belief and strength tocarry out his / her duties with ease, .
139 53 – AL QAWEE
51 “This is for that which your own hands have sent forth, and that Allah is never unjust toHis servants.52 “After the manner of the people of Pharaoh and of those before them; they rejected thesigns of Allah and Allah punished them for their crimes. Allah is Strong and strict inpunishment. [Quraan: Al Anfaal, Chapter 8]
Allah is never unjust. Each person in every community gets what they deserve. The examplegiven in the above reference is the people of the Pharaoh. What did the Pharaoh and hispeople do? They rejected the signs of Allah. They oppressed another race. Today we seeexactly the same situation across the world, where one race is oppressing another. Theoppression is based on greed and power over others because of the strength of one raceover another. Allah’s Strength cannot be overcome by anyone. Sooner or later theoppressors pay or will pay for their actions. Allah is Strong and strict in punishment.In the case of Pharaoh and his people, Allah caused a drought, shortness of crop, floods,sent locusts, lice and frogs. Allah killed the first born son of the Pharaoh and his community,just like the Pharaoh had killed the sons of Bani Israeel. Similarly when Abraha came todestroy the First House in Makkah, Allah sent tiny birds to destroy Abraha and his army.Moving to the present day, America and Britain bombed Iraq so that they could show theirstrength, Allah sent ‘foot and mouth’ disease and infected the livestock in Britain, wherenumerous livestock was destroyed. America and Canada started suffering from “powerfailures”! The people, that is, the scientists or analysts can look at all kinds of excuses for theabove ‘misfortune’. But Allah tells us plainly “This is for that which your own hands have sentforth, and that Allah is never unjust to His servants.”
140 53 – AL QAWEE
But why are the people of Iraq suffering? The Iraqis first started fighting with Iranians. Thenafter that did not get them very far, they picked on Kuwaitis. “This is for that which your ownhands have sent forth, and that Allah is never unjust to His servants.”There is a lesson in this for each one of us. We must constantly check ourselves. Each oneof us must realise, that we human beings are weak creatures. It is Allah who is the StrongOne. The strength given to us by Allah is for our own self-defence. Allah gives us physicalstrength for our physical protection. Allah gives us spiritual strength for our spiritualprotection. We must not and should not oppress anyone with injustice, because Allah is Just,Allah is Strong and Allah is Strict in punishment.Let us look at one more example of Al Qawee from the Quraan:
64 "And my people! This she-camel of Allah is a symbol for you, leave her to feed on Allah'searth and inflict no harm on her or a swift penalty will seize you!65 But they did slew her. So he said: "Enjoy yourselves in your homes for three days! Thepromise cannot be disproved!"66 When Our commandment came, We saved Saleh, and those who believed with him, by amercy from Us, from the ignominy of that day. Your Rabb (Lord)! He is the Strong, theMighty. [Quraan: Hud, Chapter 11]
How many days were the community of Prophet Saleh allowed to enjoy themselves?Three! There are three letters in Allah’s Name Al Qawee the Strong. The community ofProphet Saleh did not love the creation of Allah and they killed it. The third Yaum
day was all they were allowed to enjoy. Allah dealt with them on the fourth day. ProphetSaleh and those who believed with him were saved by mercy from Allah. While the rest ofthe community were destroyed. Why?Because the mercy and the destruction were from their own works as Allah says in theearlier reference:
51 “This is for that which your own hands have sent forth, and that Allah is never unjust toHis servants. [Quraan: Al Anfaal, Chapter 8]
May Allah have mercy on all of us and save us from destruction from our own hands.Aameen.
141 53 – AL QAWEE
MEDITATIONThe person who reads Ya Qaweeyu 1111 times everyday will become strong physically,mentally and spiritually, .
142 52 – AL WAKEEL
80 He who obeys the Rasool (Apostle) obeys Allah, but if any turn away We have not sentyou to watch over them.81 They promise to obey you; but when they leave you, a section of them plot in secret,things very different from what you tell them but Allah records their plots. So keep clear ofthem and put your trust in Allah, and Allah is sufficient as Trustee. [Quraan: An Nisaa, Chapter 4]
To obey the Rasool, Muhammad , is to obey Allah. To trust the Rasool is to trustAllah. Since the guidance from Allah came through His Messengers . Therefore, the firstpoint of knowledge of Allah was the one chosen by Allah as His Messenger. The first point oftrust in Allah is the trust placed in His Messengers . In the above reference there weresome people who promised to obey Allah’s Rasool but in secret they planned otherwise.Since they did not trust Prophet Muhammad , it follows that they did not trust Allah. SoAllah informed His Rasool to keep clear of such people and place his trust in Allah. Wecan only place our trust in Allah if we place our trust in Prophet Muhammad . This is avery fine point therefore ponder over it, since the Quraan was revealed through HadhratMuhammad . Whoever believed Prophet Muhammad , believed Allah. WheneverProphet Muhammad said anything concerning Islam, Hadhrat Abu Bakr used to reply
143 52 – AL WAKEEL
“Saddaqta Ya Rasool Allah” – “You have spoken the truth Ya Rasool Allah ”. SinceHadhrat Abu Bakr trusted Allah and His Rasool without hesitation or reservation, he wasgiven the title As Siddiq, the Truthful.In contrast we find in the above reference, certain people promised to obey ProphetMuhammad , but in secret they were against him. On the one hand, we have thecompanions of Prophet Muhammad who were ready to obey Prophet Muhammad byword and deed. The companions trusted Allah and His Rasool completely. So Allahbecame the Trustee of Prophet Muhammad and his companions . The proof is with ustoday. Even after 1400 years, Islaam is the fastest growing religion. Sayyidina Muhammad , his family and his companions’ names are still mentioned today by the Muslimswith great respect and honour. The family and the companions trusted Allah and His RasoolMuhammad , Sayyidina Muhammad trusted Allah, and Allah is sufficient as aTrustee. So what is wrong with the Muslims of today that they do not place their trust in Allahand His Rasool ?
45 Ya Ayyuhan Nabee (Prophet)! Truly We have sent you as a witness and a bringer of goodnews and a warner.46 And as one who invites to Allah by His leave and as a lamp spreading light.47 Then give the good news to the believers that they will have great bounty from Allah.48 And do not incline towards the disbelievers and the hypocrites. Disregard theirannoyances and put your trust in Allah. Allah is sufficient as Trustee. [Quraan: Al Ahzaab, Chapter 33]
When Allah clearly states that Prophet Muhammad has been sent as a witness, one whobrings good news, one who warns, one who invites to Allah by Allah’s permission. A lampspreading light, then what is wrong with the Muslims that they do not place their trust in Allahand His Rasool, Muhammad ? For those who do place their trust in Allah and His Rasool they will have great bounty. What is this great bounty? This bounty is great honour andrespect for years after the person is physically no longer with us.Allah is Al Wakeel the Trustee whose great bounty of Kalimaat Words and Knowledge
was given from Lawh Mahfuz the Preserved Tablet to His Messengers so that theymay lead mankind from darkness to light. May Allah guide all of us. Aameen.
144 52 – AL WAKEEL
The person who reads Ya Wakeelu 1111 times everyday, will always be under the protectionof Allah from all kinds of misfortune, Inshaa Allah.The person who reads Ya Wakeelu during times of distress and places his / her trust in thisTrusting Name of Allah, Allah will protect / relieve the person of all kinds of distress, InshaaAllah. Remember to recite any Darood / Salawaat of your choice 11 times before and afterthe above Zikr and send the Hadiya (reward) for the Darood / Salawaat to Allah’s Rasool, ourMaster, Sayyidina Muhammad .
145 51 – AL HAQQ
29 Have you not seen how Allah causes the night to pass into the day and causes the day topass into the night, and has subdued the sun and the moon, each running to an appointedterm; and that Allah is acquainted with all that you do?30 That is because Allah, He is the Truth, and that which they invoke beside Him is the false,and because Allah, He is the High, the Great. [Quraan: Luqmaan, Chapter 31]
There is a set of books called Tafseer-e-Naeemi, by Al Mufti Ahmad Yaar Khan Naeemi,(from Gujrat) may Allah bless him for his contribution to Islaam. The books contain anexcellent explanation of the Holy Quraan. It is mentioned in Tafseer-e-Naeemi, that thegreatest sin is to tell a lie. Since what the Christians say about Prophet Isa is a lie. Whatthe Christians say about Allah is a lie. To attribute partners to Allah is a lie:
23 He is Allah, there is no god only He, the Sovereign, the Holy the Peace, the Guardian ofFaith, the Protector, the Mighty, the Compeller, the Supreme. Glorified be Allah from all thatthey ascribe as partner (to Him). [Quraan Al Hashr. Chapter 59]
146 51 – AL HAQQ
Therefore the act of attributing partners to Allah is to speak a lie which is the greatest sin!Allah is the Truth, the Real. That is because Allah, He is the True, and that which they invokebeside Him is the false.To reiterate, speaking a lie is one of the greatest sins. One lie leads to another. Then thereare lies to cover lies. The person gets dragged deeper and deeper into a life full of lies,where it becomes a habit to speak lies and think nothing of it.Just look at the spellings of LIFE and LIE. That life becomes a False existence! That lifebecomes Fruitless! That life becomes a Fantasy! So what do the people do? They elect suchpeople for presidents and leaders! Instead of the president being a pure resident, he / shebecomes a false, fruitless, fantasy resident! In Arabic there is no such letter which soundslike the letter ‘P’.Allah is the Truth, the Real, and He created everything in the heavens and the earth with theTruth, including human beings and jinn. Then why do people speak lies? If the answer isbecause they have been led astray by jinn and Shaytaan, then the cure is in the Quraanwhich is the Truth from Allah, provided we put our Trust in Allah, and His Kalaam. If theanswer is for self-preservation, then the answer is that silence is better than a lie. It is betternot to say anything rather than to speak a lie.Let us look at one more example from the Quraan:
24 On the day when their tongues and their hands and their feet testify against them as towhat they used to do,25 On that day Allah will pay them their just due, and they will know that Allah, He is theTruth, the Manifest. [Quraan : An Noor, Chapter 24]
The tongue is created to testify the truth. The hands are created to testify the truth. The feetare created to testify the truth. We use the tongue to speak the truth, and then we shakehands as confirmation of what the tongue has just said. And we say: “Let us shake hands onthat.” That is let us agree on what the tongue has spoken. Alternatively we can put theagreement in writing with the hands. The feet are placed firmly on the ground as witnesses.The feet are Arjul, a foot is Rijl and men are Rijal. People say about liars: "He does not havea leg to stand on!" Yet they do not know why they say it.We are told in the Quraan that whenever we have dealings in loans and trusting property tosomeone we must take two male witnesses. So that the witnesses ensure that the Truth isupheld. If we have followed the above, for a truthful person, the feet are enough aswitnesses, because they will be called as witnesses. If only people knew, they would fearAllah and speak the truth always. But these feet of ours will be called as witnesses in thepresence of Allah. Hence we must take two men as witnesses in this world as stated in theQuraan. Since the men can be called up and made to give evidence in this world.My uncle once wrote for me: ‘The tongue being in a wet a place is apt to slip. Always use itcarefully.’ Those words of wisdom from him stuck in my mind since my teens. I am indebtedto him for those two small but truthful sentences. May Allah repay him with good in this worldand the next because he needs it now more than ever. Aameen.Allah is Al Haqq the Truth, the Real One, and He created everything with Truth, since heis Al Qawee the Strong beyond measure and Al Qaadir the One Able to do that. May Allahguide us all to the Truth, the whole Truth and nothing but the Truth, so help us Allah!Aameen.
147 51 – AL HAQQ
For the return of a lost thing or to call back a missing person, write Al Haqq as shown belowon piece of paper. At night stand under the sky with the head uncovered. Place the paper inthe palms of the hands facing upwards, raise the hands so that they are higher than the headand say three times, “Ya Haqq return my lost ‘item (mention the item)’ to me” or “Ya Haqqreturn ‘such and such’ to me” (mention the name of the missing person and his / her mother’sname). Inshaa Allah the result will speak for itself within 24 hours. If not then repeat the samefor two more nights to make it a total of three nights.
Remember to recite any Darood / Salawaat of your choice 11 times when you achieve theresult and send the Hadiya (reward) for the Darood / Salawaat to Allah’s Rasool, our Master,Sayyidina Muhammad .
148 50 – ASH SHAHEED
117 (Isa replied to Allah) "I spoke to them only that which You commanded me. `Serve Allahmy Rabb (Lord) and your Rabb (Lord)'; and I was a witness over them while I dwelt amongstthem; when You took me You were the Watcher over them and You are a Witness to allthings.”118 "If You punish them they are Your servants, and if You forgive them You are the Mightythe Wise.” [Quraan: Al Maaida, Chapter 5]
In the previous section we came across what the Christians say about Prophet Isa . In thisexample from the Quraan we find that Allah questions Hadhrat Isa about what theChristians believe and whether he told them to do so. Allah sent a Messenger to eachcommunity whose duty was to deliver the Message of Allah and also to be a witness overtheir community. This is confirmed in the reply given by Prophet Isa who was the witnessover his community, during his time on earth and furthermore, he also confirms that Allah is aWitness to all things. That is Allah is a Witness over the witness. If Allah is a Witness overthe witness then why does He ask that question? What is the wisdom in the question sinceProphet Isa says: You are the Mighty, the Wise?Imaam Ibn Al Arabi has explained the wisdom of this verse beautifully:
‘The question from Muhammad and his supplication to his Rabb (Lord) in which herepeated the phrase (verse 118 above) for the entire night until dawn was a request for theanswer. If he had heard the answer in the first questioning, he would not have repeated it.
149 50 – ASH SHAHEED
Allah showed him the judgments in detail by which they deserved punishment. As eachinstance was presented to him and specified, Muhammad said to Him, "If You punishthem, they are Your servants, and if You forgive them, You are the Mighty, the Wise." If hehad seen in what was presented to him anything which would make it necessary that Allahhad already decided and that His preference must be preferred, he would have invoked Allahagainst them rather than for them. So what they deserved is changed by what this ayataccords of submission to Allah and exposing themselves to His pardon’. [Fusus al Hikam]
Therefore, Allah is really giving Prophet Isa a chance to ask on behalf of his community,and Prophet Isa understood that, and he says: "If You punish them they are Yourservants, and if You forgive them You are the Mighty the Wise.” That is Wisdom!A Hadees comes to mind where a man committed an illegal sexual sin and came to Allah’sRasool and confessed what he had done. That man was his own witness againsthimself. Prophet Muhammad turned his face away from the man. The man did notunderstand! He went over to the side where Prophet Muhammad turned his face andconfessed again. This happened four times. The man did not understand the wisdom in theturning of the blessed face. Each time he was being given a chance to ask Allah forforgiveness instead of being a witness against himself. The reason he was given four
chances is that there are four letters in the Name Shaheed - Sheen, Haa, Ya andDal. Having been a witness against himself four times, he was asked whether he was mad,to make sure that an innocent man is not punished. The moral here is that Allah is theWitness and He is Wise. Allah chose Messengers who were given wisdom to bewitnesses over their communities as Prophet Isa and Prophet Muhammad haveshown us by example in the above references. When we take people for witnesses we mustalso make sure they are not mad and that they are wise.Let us look at one more example from the Quraan:
45 Ya Ayyuhan Nabee (Prophet)! Truly We have sent you as a witness and a bringer of goodnews and a warner.46 And as one who invites to Allah by His leave and as a lamp spreading light. [Quraan: Al Ahzaab, Chapter 33]
In this example from the Quraan we are told that Prophet Muhammad has been sent asa witness first, then a bringer of good news and then as one who warns. Being a witnesstakes precedence over the other two duties. Why is that? A witness will be called to giveevidence. And from the first example we have seen that when the witness is asked about theconduct of his community, Allah will give the witness a chance to say: "If You punish themthey are Your servants, and if You forgive them You are the Mighty the Wise.” In other wordsthe witness will be able to ask Allah to forgive his community, who are Allah’s servants.Allah is Ash Shaheed the Witness who sent a Messenger as a witness to all thecommunities. For Muslims, Allah sent Sayyidina Muhammad as Haadee the guide
with Knowledge of how to live our life in Dunya the world. May Allah guide us all.Aameen.
150 50 – ASH SHAHEED
MEDITATIONThe person who reads Ya Shaheedu 1111 times everyday, will witness the answers to his /her questions, Inshaa Allah.The person whose child is disobedient, should read Ya Shaheedu 21 times while placing hisright hand on the forehead of the child, the child will become .
151 49 – AL BAAIS
6 This is because Allah is the Reality: it is He who gives life to the dead and He is Able to doall things.7 And truly the hour will come, there can be no doubt about it, and Allah will raise those whoare in the graves.8 And among mankind is one who disputes about Allah without knowledge and withoutguidance and without a book giving light. [Quraan: Al Hajj, Chapter 22]
It is important to realise that Allah is Al Qaadir, Able to do all things. Therefore Allah can, andAllah will, raise those who are in the graves. Those who dispute about this fact are withoutknowledge, without guidance and without a book giving light. Knowledge is a basicrequirement, followed by guidance. With knowledge and guidance comes a book. ProphetMuhammad had knowledge from Allah, he had guidance from Allah, and he received abook giving light, which is the Quraan. We are told in the above book of light, And truly thehour will come, there can be no doubt about it… Whether a person is a believer or adisbeliever, there is no doubt that we all have to die one day. Therefore, everyone canaccept the part of the book which mentions the hour will come and that hour is one in whichwe will die. For the disbeliever it is difficult to believe Allah will raise those who are in thegraves.Allah created us for the first time from out of nothing. Allah gave us a physical body. Afterdeath the body decays. Yet the bones remain. And we are told in the Quraan:
152 49 – AL BAAIS
259 Or the similarity of one who passed by a town in ruins, said: "How shall Allah bring thistown to life after its death?" And Allah made him die for a hundred years then raised him up.He said: "How long did you stay (thus)?" He said: "A day or part of a day." He said: "No, youhave stayed away a hundred years. Just look at your food and drink; they show no signs ofage, and look at your donkey. With this We make of you a sign for the people, look at thebones how We bring them together and clothe them with flesh!” When this was shown clearlyto him he said: "I know that Allah is Able to do all things." [Quraan: Al Baqara, Chapter 2]
Allah is Able to do all things. Allah can raise a dead person, just as Allah is able to raise aperson out of non-existence simply by the command ‘Be!’ In the above example we have aperson who is made to die and he is raised up again after 100 years, that is an example forhim and us. Then there are further two examples for that man who has been raised. The firstexample is the food which has not shown any sign of ageing even after 100 years. Just incase he thought that he had really been away for a day and not 100 years, the remains of thedonkey are shown to him as a second example. All that remained of the donkey were thebones that had become detached from each other. And before his very own eyes, Allahshowed him how he brought the broken skeleton together and clothed the bones with fleshand skin. In this is a sign for those who believe.Al Baais is the forty-ninth Attribute of Allah, which is about half way between 1 and 99. Sothere is a term appointed for us in this world and there is a term appointed for us in the nextworld. However, the time references are different.Let us look at another example from the Quraan where Allah is asked to raise for the firsttime:
129 "Our Rabb (Lord)! And raise among them a messenger of their own who shall recite tothem Your revelations, and teach them the Book and the wisdom and shall make them grow.You are the Mighty, the Wise.” [Quraan: Al Baqara, Chapter 2]
Prophet Ibraheem and Prophet Ismaeel prayed to Allah as in the above reference. Allahaccepted the prayer, and when the time was right, Allah sent Prophet Muhammad as ananswer to the prayer. Muhammad was a Messenger raised from among the people ofMakkah, who recited to his people, revelations from Allah, and taught them the Book and thewisdom and made them grow. The wisdom of the Book is such that it is never ending. Yetpeople limit the wisdom to the obvious meaning and fail to understand the deeper meaning ofthe Quraan. The Quraan is such a book that sheds new light in every age. Allah has alsoresurrected the wisdom of the Quraan for all ages and time.Allah is Al Baais the one who Resurrects. Just as Allah created us the first time, Allah isable to raise us again. All that is required from Allah is one command: “Be!” And it is! The
result is visible before our very eyes . As stated at the start of this section that the hourwill come and surely it will come, on every believer and every disbeliever, without a doubt.We must prepare for it now. The Samar reward for belief in Allah will be beyond ourwildest imagination. May Allah have mercy on us all. Aameen.
153 49 – AL BAAIS
Sa 500 TOTAL 573 TOTAL
MEDITATIONThe person who reads Ya Baaisu 1111 times everyday, will have firm belief and strength tocarry out his / her duties with ease, Inshaa Allah.The person who reads Ya Baaisu 101 times everyday with the hands placed over the heart,just before falling asleep, his / her heart will be revived with knowledge and wisdom, .
154 48 – AL MAJEED
The word Majeed – Glorious is used as an Attribute to describe Allah. He is indeed worthy ofall praise full of glory. Majeed is also used to describe the Quraan. It is from the Quraan weknow He is indeed worthy of all praise full of glory. And finally it is used to describe theThrone - Arsh. Allah is the Possessor of the Glorious Throne. He is indeed worthy of allpraise full of glory.Since Prophet Ibraheem praised Allah as only Allah is worthy of praise, Allah sent angelsto give him the news of a son. And the angels conveyed the mercy and blessings upon himand his household. That is the mercy and blessings were also for his wife who had grown oldand past the age of childbearing. But Allah is Able to do whatever He wills. The same angelswere sent to Prophet Lut . Only there, they were sent to protect Prophet Lut and thosethat believed in Allah, but his wife was one of those that would be punished. Allah favouredand honoured both Prophet Ibraheem and Prophet Lut .There is another reference in the Quraan where Al Majeed is used in connection with Arsh orThrone:
155 48 – AL MAJEED
There are 7 Thrones. Arsh Majeed is the third. It is related in by Shaykh Abu ul AbbasAhmad bin Ali Booni :Arsh Majeed is unlimited and exalted. All the spirits show great respect for this Throne. Thefirst Arsh - Throne is neither hidden nor veiled. Allah has granted degrees of respect to theMessengers and the Awliyaa with that. And in this station the heavenly world has beenshown. This is also the place of the spirit. Arsh Majeed has given the physical form to thespirits and made the effects of the spirit to act on the physical form… So the visible is fromthe power of Allah and the invisible is from the command of Allah. [Shams ul Maarif]
And finally let us look at a third reference which is applied to the Quraan itself:
The Quraan is also Al Majeed, the Glorious. Why? The Quraan is our link to knowledge ofAllah. The Quraan is our link to the Arsh Majeed. Therefore, the Quraan is our link to Allah.How? When we recite the Quraan, Allah and the inhabitants of Arsh Majeed hear it. Theblessing of the recitation rises up to Arsh Majeed and the blessings from Allah descend onthe one who recites below. Good deeds always ascend upwards towards Allah’s Throne.Blessings from Allah always descend downwards towards His creation. The similarity of theblessings coming down from Allah are as rainfall from the clouds.Allah Al Majeed the Glorious created the third Arsh and named it Arsh Majeed. The
knowledge of Arsh Majeed is mentioned in the Quraan, which is from the guarded tablet.Whatever good we do, it is recorded and sent up towards the Arsh (throne) and blessingsfrom Allah descend down on Dunya the world of forms. May Allah guide all of us toperform good deeds that will be acceptable to Him. Aameen.
156 48 – AL MAJEED
The person who reads Ya Majeedu 1111 times everyday, will receive honour and blessingsfrom .
157 47 – AL WADOOD
90 “And ask forgiveness of your Rabb (Lord) and turn to Him (repentant), for my Rabb (Lord)is Merciful, Loving.”91 They said: "Shuayb! Much of what you say we do not understand! Among us we see youas weak! Were it not for your family we should have stoned you! For you are not strongagainst us" [Quraan: Hud, Chapter 11]
There is a sharp contrast in the above reference. There is Prophet Shuayb telling hiscommunity to turn to Allah because He is Merciful and Loving. The community on the otherhand replies with hatred that they would have stoned him for telling them to repent. Theywere not interested in the Message. They were more concerned about who was physicallystrong. That is a sickness of the mind. Just as love is the opposite of hatred, similarly humilityis the opposite of arrogance. When Allah told the angels to bow down to Hadhrat Adam ,the angels complied with humility. Shaytaan refused because of arrogance. What doesShaytaan do? Shaytaan puts hatred in the hearts of people, so they hate others. If we look atthe life of the Awliyaa (Saints), all of them humbled themselves and loved others for thesake of Allah. Shaykh Abdul Qadir al Jilani has said: “My enemy and the one who lovesme are both equal in my sight. No friend or foe of mine is left on the face of the earth. This issomething that comes about only after loving Allah, cultivating sound belief in His Onenessand seeing creatures as being powerless.”This is the true emulation of Allah’s Attribute Al Wadood. Allah does not discriminate inproviding for his creatures, whether one believes in Allah or not. Therefore we have no rightto discriminate against our personal enemies. This is something that comes about only afterloving Allah. How does one begin to love Allah?
158 47 – AL WADOOD
One starts by serving His creation without expectation of any kind of reward from the creationor the Creator, and one ends up still serving His creation but Allah bestows love on thatperson.
96 Those who believe and do good works, the Compassionate will bestow love.97 So We make (this Quraan) easy in your own tongue, that with it you may give good newsto the righteous, and warnings to people given to contention. [Quraan: Maryam, Chapter 19]
31 Say: "If you love Allah, follow me; Allah will love you and forgive you your sins. Allah isForgiving, Merciful.” [Quraan: Al Imraan, Chapter 3]
So we must endeavour to follow the example of Allah’s best creation, Hadhrat Muhammad . Allah also commanded: “Dawood (David)! Make My creatures love Me!” Why did Allahcommand Hadhrat Dawood such? If we look at the name Dawood along withWadood we find that the name Dawood contains love. That was the quality ofProphet Dawood , which he had to share with others, so that they would love Allah theCreator of Hadhrat Dawood . Love is a quality which can only be shared. Love cannot behoarded.There is a subtle lesson in all this. All created things perish. The Creator of these perishablethings, Allah is Everlasting. If we love Allah, Allah knows that. If Allah knows that we loveHim, then even after we disappear from the face of the earth, Allah will still remember us withlove. The moral of the story is that love between two people is remembered only as long oneoutlives the other. Whereas love for Allah is everlasting since Allah is Everlasting.Allah is Al Wadood the Loving. Allah is Daiem the One who will Exist Forever. Thereforewe must learn to love Allah and our love for Allah will last forever because Allah is the Onewho Exists Forever and He will remember us with love forever.May Allah fill our hearts with love for Him and give us all the ability to serve Him as Hedeserves to be served. Aameen.
159 47 – AL WADOOD
The person who reads Ya Wadoodu 1111 times everyday, will be loved by Allah and thepeople will love that person, Inshaa Allah.The person who reads Ya Wadoodu 1111 times over food, and eats that food with his / herspouse, the arguments between them will stop and they will start to love each other, .
160 46 – AL HAKEEM
1 All that is in the heavens and all that is in the earth glorifies Allah, the Sovereign, the Holy,the Mighty, the Wise.2 It is He who has sentah is Al Hakeem, the Wise. He has sent a Messenger of their own, to recite to them Hisrevelations and to make them grow, and to teach them the Book and wisdom.Knowledge and Wisdom go hand in hand just as ignorance and foolishness go hand in hand.If you have knowledge, attain wisdom. If you are ignorant, attain knowledge so that you mayattain wisdom. Knowledge without wisdom is of little use. Knowledge and wisdom combinedis the ideal. The Quraan states that Allah is Knowledgeable and Wise. And Allah gavewisdom to all His Messengers . But in this day and age, almost every Muslim seems to beknowledgeable yet most of them lack wisdom. This is also true of the Imaams of today in themosques. Therefore the knowledge is of little use if the wisdom of application is notunderstood. With wisdom, comes clarification of the knowledge. The truth is separated fromthe false. Misconceptions are eradicated. May Allah give wisdom to all the Muslims.Allah also tells us in the Quraan:
161 46 – AL HAKEEM
1 Ya Seen.2 By the wise Quraan, [Quraan: Ya Seen, Chapter 36]
There is truth in the above statements. This has been verified time and time again. Whenpeople come seeking guidance, they have been given the same Ayats of the Quraan for thesame purpose. For one person, Allah answers the prayer immediately. For another person,there is a delay. The person guiding is the same. The Ayats from the Quraan are the same.Only the receivers of the Ayats are different. Why is there an immediate relief for one personand a delay for another person? It is based on our belief and sincerity which Allah knows andthe wise Quraan is informed to act upon.Therefore the Quraan is indeed wise. Even the Ayats of the Quraan know who is sincere andwho is not. And Allah also informs us in the same wise Quraan:
82 And We reveal of the Quraan that which is a healing and a mercy for believers, to theunjust it causes nothing but loss after loss. [Quraan: Al Israa, Chapter 17]
And finally let us take one more example from the wise Quraan about wisdom:
The similarity in the creation of Prophet Adam and Prophet Isa is the Wisdom of Allah.He created them both from dust. Prophet Adam was created without any parents, andProphet Isa was created without a father. They were both created by Allah’s Command:“Be!” In this, there is great wisdom if people realise. Right at the beginning it was stated thatthere is also a Command that is wise.
Allah is Al Hakeem the Wise. Allah’s Kitaab Book and Allah’s Kalaam, Word is also
wise and knowledgeable which teaches it’s wisdom to the Muttakeen those whobelieve in the unseen. May Allah teach the Muslims of today wisdom of the knowledge.Aameen.
162 46 – AL HAKEEM
The person who reads Ya Hakeemu always, whatever he / she intends will be achieved,Inshaa Allah.The person who read Ya Hakeemu 1111 times everyday, will find the doors of knowledgeand wisdom will be opened for him / .
163 45 – AL WAASI
261 The likeness of those who spend their wealth in the way of Allah is as the likeness of agrain that grows seven ears and in every ear a hundred grains. Allah gives increase manifoldto whomever He wills. Allah is All Embracing, All Knowing. [Quraan: Al Baqara, Chapter 2]
Here we are given an example of wealth that is spent for the sake of Allah. One grain of corngrows seven ears of corn. Each ear of corn has 100 grains. The potential is 700 ears of cornfrom that one grain. We can take this equation further and find that it becomes limitless.Therefore the reward for spending wealth for the sake of Allah is unlimited. Wealth here doesnot mean just monetary. Wealth embraces money, food, clothing, kind words, a smile,guidance and also sharing knowledge. However, guidance to good, knowledge of good isrewarded with better guidance and more knowledge. Spreading good, sound knowledge isnot the same as spreading misconceptions. With sound knowledge more people will be led tothe straight path whereas with unsound knowledge, more people will be misled. The rewardfor spreading good sound knowledge is without measure. The punishment for spreadingunsound knowledge is also without measure. The moral of the story is that unless a personhas had a worthy teacher from whom he has learnt knowledge and wisdom, he should notendeavour to write about Islaam because the one who has no guide, Shaytaan is his guide.By worthy teacher it is not meant an Islaamic school lecturer. The worthy teacher is aspiritual master who knows the state of his students both mentally and spiritually. That is theteacher must be knowledgeable and wise, Aleem and Hakeem. As it was stated in AlHakeem, knowledge without wisdom is of little use.
164 45 – AL WAASI
98 Your God is only Allah, there is no god only He, embracing all things in His knowledge.99 Thus do We relate to you some stories of what happened before, and We have given youfrom Our presence a reminder. [Quraan: Ta Haa, Chapter 20]
Just as Allah embraces all things in His knowledge, and His Rasool, Muhammademulated this quality of Allah and embraced all things in his knowledge, so must the spiritualteacher embrace all things in his knowledge so that he emulates Muhammad Rasool Allah . The reminder then comes from Allah’s presence. How else could one know whathappened before, unless Allah reminded from His own presence.Comprehending or Embracing is very important for Wisdom. Wisdom comes from embracingknowledge, understanding, comprehending. Allah has knowledge. Allah comprehends theentire knowledge. Allah is the Wise.There is the example of Prophet Ibraheem , when he saw a star and he said that was hisRabb (Lord). When it set, he turned away from it. Then he saw the moon, he said that washis Rabb. When it set he turned away from it. Then he saw the sun rising and said that washis Rabb. When the sun also set, he turned away from the sun and all created things andturned towards the One who created these things. In each stage we can see the similarity oflight. The star shines a light. The moon is brighter than the star. The sun is so dazzling thatwe cannot even look at it. But that too sets. Each of these can be considered as stages incomprehension. First there is a little understanding. Then a little more, then a lot, and finally it‘dawns’! Once we have understood, the ‘light’ is there with us which does not set.
80 His people disputed with him. He said: "Do you dispute with me about Allah when He hasguided me? I do not fear those you associate with Him unless my Rabb (Lord) wills. My Rabbcomprehends in His knowledge all things. Will you not remember?” [Quraan: Al Aanaam, Chapter 6]
Allah Embraces, Understands, Comprehends, all knowledge and He bestows this quality toembrace, understand, comprehend, to those whom He chooses.Allah is Al Waasi the All Embracing and to emulate this quality of Allah, we must not set uppartners with Him. Allah is Ahad One and we can only comprehend His works when webelieve in His Oneness. As in the example stated, that from one grain given in the way ofAllah, has the potential of Sabaa seven ears of corn. Similarly, comprehending one thing
leads to the clarification and comprehension of another. Then we can ‘see’ the meaningbehind the visible, if Allah wills. May Allah make us all embrace Islaam with comprehensionthat is required instead of just empty actions. Aameen.
165 45 – AL WAASI
The person who reads Ya Waasiu 1111 times everyday, will be granted visible and invisiblemeanings of true Islaam, Inshaa Allah. With this Zikr Allah, difficulties are overcome, andexpansion and increase is achieved from the little that is given for the sake of Allah. .
166 44 – AL MUJEEB
61 And to Samood (We sent) their brother Saleh. He said: My people! Serve Allah, you haveno other god only Him. He brought you forth from the earth and has made you inhabit it. Soask His forgiveness and repent to Him. My Rabb (Lord) is close, Responsive. [Quraan: Hud, Chapter 11]
Allah brought us forth from the earth. That is the spirit has been given a body to experiencelife on earth. And Allah has made us inhabit it. That is Allah has made us inhabit the earthand He has made us inhabit the body made of earth. To ask for forgiveness is from the bodyand soul. The body is there to serve Allah. It is the vehicle of the spirit to learn and to serveAllah. Allah asked the angels to name the things. They said they had no knowledge otherthan what Allah had taught them. Allah asked Hadhrat Adam after he had been createdfrom clay and the spirit was breathed into him to name the things. And he named them!So Allah has made us inhabit the body, the earth for a time appointed. In that time we mustserve Allah. We must turn to Him. Allah is close, and He Hears, He Responds to our prayer.
186 And when my servants ask you concerning Me I am indeed close. I respond to theprayer of the suppliant when he calls Me. Let them also respond to My call and believe inMe, so that they may be led the right way. [Quraan: Al Baqara, Chapter 2]
167 44 – AL MUJEEB
How does one respond to Allah’s call? Allah sent Messengers who called the people asAllah’s representatives. In this day and age, since there are no more Messengers to come,Allah’s call has been recorded in the Quraan and Ahadees. The only people that will comeare those who will revive Islaam and teach it as it should be taught. Following the teachingsof the Quraan and Ahadees is responding to Allah’s call. Supplicating to Allah, AllahResponds. The supplication rises towards Arsh Majeed and Allah Al Majeed, help is receivedfrom Allah with His Attribute Al Mujeeb, the One who Responds. Allah is closer to us than ourjugular vein. This is in the sense that before the affectations of the heart reach the brain,Allah already knows beforehand what we are going to experience. There are many ways thatAllah responds. Sometimes the responses are clear-cut. For example, when people pray forrain, Allah responds by sending rain. At other times the response is not so clear. In the lattercase, we have to be aware in order to realise that Allah has responded. For example: Whenthe Companions of the Cave asked Allah for His mercy from the persecution of theircommunity, Allah put them to sleep in the cave for 309 years. When they woke up, theythought that maybe they had just been asleep for a day or so. Yet when they found out, allthose who rejected them had already been dead and gone for three centuries. Allahresponded to the prayers of the Companions of the Cave, but the response was understoodby them 309 years later. Although from their viewpoint it was a day may be less because thatis how long they felt they had been asleep.
31 "Our people respond to the one who invites to Allah and believe in Him. He will forgiveyou your faults and deliver you from a painful doom.” [Quraan: Al Ahqaaf, Chapter 46]
There is an important message in the above reference. As it was stated previously that therewill be no more Messengers from Allah but there will be those who revive Islaam. ShaykhAbdul Qadir al Jilani was one such person who revived Islaam. Imaam Mahdi will beanother such an enlightened person who will also revive Islaam. The corruption that hasbefallen the Muslims today, Islaam needs revival. May Allah revive Islaam and cleanse it ofall crookedness that has been added to it. Aameen.Allah Al Mujeeb the Responsive responds to those who respond to His call. Jannat andJahannam heaven and hell are the destinations. Heaven is the reward for those whorespond to Allah’s call. Hell is the punishment of those who do not respond. Allah has
168 44 – AL MUJEEB
The person who reads Ya Mujeebu 1111 times everyday, will have his / her prayersaccepted and answered .
169 43 – AR RAQEEB
1 Mankind! Fear your Rabb (Lord) who created you from a single soul and from it created itsmate and from them He has scattered abroad many men and women. And fear Allah inwhom you claim one another, and toward the wombs (that bore you). Allah is a Watcher overyou. [Quraan: An Nisaa, Chapter 4]
Allah is One. He has created us from a single soul. Whether we look at this physically orspiritually the answer is still the same. Physically, from a single creation of Prophet Adam ,Allah created the rest of humanity. Spiritually we are told that Allah created all of us from asingle soul. Yet there is animosity and hatred between people. Sometimes, it is based on noother reason other than the other person ‘looks’ different. It is a race ‘thing’. It is a culture‘thing’. It is a language ‘thing’. Allah is watching our every action. To watch is also to witness.The watching is not just over the visible body, it is also over the hidden body, the soul. Thewatching is not just over the spoken word; it is also over the unspoken word. The watching isnot just over the physical actions, it is also over the hidden emotions. Allah watches over ourlives from the visible aspect as well as the hidden aspect.What is the difference between watching and witnessing?
170 43 – AR RAQEEB
In the above reference, Prophet Isa was a witness over his community. Prophet Isareplied: “You were the Watcher over them and You are a Witness to all things.” Therefore towatch also means to guard. It follows that Ar Raqeeb also means the Guardian. ThereforeAllah is the Guardian as well as the Witness. A Guardian is a defender, protector, custodian,trustee, keeper, preserver. So when Prophet Isa says: “If You punish them they are Yourservants, and if You forgive them You are the Mighty the Wise”, he praises Allah with thecorrect Sifaat or Attributes or Names of Allah for that particular situation. That is the subtletywhich we lack. Prophet Isa knows how to call upon his Rabb with the right words for agiven situation. We do not know how to call our Rabb in times of need so we must learn.In the case of Prophet Muhammad , on the Day of Judgment:
“…Allah will say, 'Muhammad, lift up your head and speak, you will be heard, intercede, yourintercession will be accepted, ask, it will be granted.’ Then I will raise my head and glorify myRabb with certain praises which He has taught me. Allah will put a limit for me I will takethem out and make them enter Paradise…” [Sahih Al Bukhari]
That is the secret of the Names of Allah. We must use the correct Names of Allah to callupon Him for a given situation.We will need that intercession on the Day of Judgment because:
17 When the two receivers receive (him), seated on the right and on the left,18 Not a word does he utter but there is a watcher by him ready19 And the agony of death will bring truth: "This is that which you wanted to escape.” [Quraan: Qaf, Chapter 50]
Allah is Ar Raqeeb the Watcher, the Guardian, the Defender, the Protector, the Custodian,the Trustee, the Keeper, the Preserver who is Qareeb close. He is closer to us than our
own jugular vein. Allah has complete knowledge of His creation and what each onehas done. Ya Allah, if You punish us we are Your servants, and if You forgive us You are theMighty the Wise. May Allah watch over all of us, guard us, from all kinds of evil, Aameen.
171 43 – AR RAQEEB
MEDITATIONThe person who reads Ya Raqeebu 1111 times everyday, will be guarded and protectedfrom all kinds of visible and invisible .
172 42 – AL KAREEM
40 Said one who had knowledge of the Book: "I will bring it to you within the blinking of aneye!" Then when (Sulaiman) saw it placed firmly before him he said: "This is by the grace ofmy Rabb (Lord)! To test me whether I am grateful or ungrateful! And if anyone is gratefultruly his gratitude is for his own soul; but if anyone is ungrateful truly my Rabb (Lord) is Self-Sufficient, Generous!"41 He said: "Transform her throne out of all recognition by her. Let us see whether she isguided or is one of those who receive no guidance." [Quraan: An Naml, Chapter 27]
Here Prophet Sulaiman (Solomon) had the throne of queen Sabaa (Sheeba) broughtbefore him in the blink of an eye. The jinn had the knowledge of the Book, so he knew how todo it. Prophet Sulaiman had knowledge of the jinn, so he knew how to control them. Allahin His Generosity gave Hadhrat Sulaiman knowledge, control and power over jinn. And thejinn obeyed Prophet Sulaiman . Allah’s Generosity is immense. Allah the Generous gaveus a body to experience life on this earth. Allah the Generous gave us emotions toexperience the difference between happiness and sadness. Allah the Generous gave usfruits and spices to experience the difference between sweetness and bitterness. Allah theGenerous made fasting compulsory to give us experience of the difference between hungerand to have a full stomach. Everything that Allah has created and commanded is out of HisGenerosity for His ultimate creation the human being, it is for our benefit. There is no gain orloss for Allah. In the words of Prophet Sulaiman :"This is by the grace of my Rabb (Lord)!To test me whether I am grateful or ungrateful! And if anyone is grateful truly his gratitude is
173 42 – AL KAREEM
for his own soul; but if anyone is ungrateful truly my Rabb (Lord) is Self-Sufficient,Generous!" For every good deed the reward is ten times, because Allah is Generous. Allah’s Messenger taught us the right path for our benefit and not because there was something in it for himor Allah, because Allah’s Messengers are generous. Similarly, from the Quraan we canderive all kinds of knowledge for our benefit because the Quraan is generous. Therefore theone who had the knowledge of the book brought the throne before his master in the blink ofan eye. As stated above, Prophet Sulaiman said: “And if anyone is grateful truly hisgratitude is for his own soul; but if any is ungrateful truly my Rabb (Lord) is Self-Sufficient,Generous!"Generosity is based on the heart of a person. A rich person does not necessarily becomegenerous. Similarly a generous person is not necessarily rich in the financial sense but he isrich in the spiritual sense. Allah is both Rich and Generous.It was mentioned that Prophet Sulaiman had power over the jinn. Allah has power over allHis creation. But Allah’s generosity is such that despite His power over His creation to punishwhom He wills, Allah forgives with His generosity whom He wills, because Allah is theGenerous.
6 Mankind! What has seduced you from your Rabb (Lord) the Generous?7 Who created you, then fashioned, then proportioned you;8 In whatever form He wills, He puts you together. [Quraan: Al Infitaar, Chapter 82]
Allah the Generous fashions the body for the spirit because of His generosity. When we areseduced from our Rabb by worldly things, Allah does not punish us instantaneously, becauseHe is Generous, giving us a chance to repent. Allah is embarrassed in punishing His creatureimmediately because of His generosity, yet the creature is not embarrassed in committing sinand takes advantage of Allah’s generosity. And yet, none of us know when we will die.Therefore we must endeavour to keep away from sin and remember Allah always. We mightnot get a chance to repent. May Allah Al Kareem the Generous give us all a chance to repentbefore He takes our soul. Aameen.Allah Al Kareem the Generous created the body for the Ruh spirit so that the Ruh can
learn knowledge . Having attained the knowledge, Allah wants us to return as Mu_mina believer in Him. May Allah give us that chance to return as a Mu_min. Aameen.
174 42 – AL KAREEM
MEDITATIONThe person who reads Ya Kareemu 1111 times everyday, will be blessed with goodness,honour and generosity, .
175 41 – AL JALEEL
There is Jalaal and there is Jaleel. The difference between Jalaal and Jaleel is that Jalaal is
spelt with Alif as shown here Jeem Laam Alif Laam while Jaleel is spelt with Ya
, which is also shown here Jeem Laam Ya Laam. The entire Arabic letter setstarts with the letter Alif and finishes on the letter Ya. In the beginning (Alif) there was Allahand nothing existed beside Him. And In the end (Ya) there will be Allah, everything willperish, nothing will exist beside Him. Like it is stated in the above reference from the Quraan.Everything on earth is perishable, except the aspect of our Rabb the Possessor of Majesty.Why will everything perish except the aspect of our Rabb? The Majesty of Allah is such that itis unbearable. Mountains humble themselves and crumble into dust. The incident withProphet Musa comes to mind:
143 And when Musa (Moses) came to our appointed place and his Rabb (Lord) had spokento him, he said: “My Rabb (Lord)! Show me, that I may gaze upon You.” He said: “You willnot see Me, but gaze upon the mountain! If it stands still in its place, then you will see Me.”And when his Rabb (Lord) revealed (His) Majesty to the mountain He sent it crashing down.And Musa fell down senseless. And when he recovered he said: “Glory to You! I turnrepentant to You, and I am the first of the believers.” [Quraan: Al Aaraaf, Chapter 7]
176 41 – AL JALEEL
Prophet Muhammad went past all these stations until he reached the presence of Allah.Hadhrat Muhammad did not faint!
Allah's Rasool said, "Two gardens, the utensils and the contents of which are of silver, andtwo other gardens, the utensils and contents of which are of gold. And nothing will preventthe people who will be in the Garden of Eden from seeing their Rabb (Lord) except thecurtain of Majesty over His Face." [Sahih Al Bukhari]
From the above Hadees, it is clear that even the inhabitants of paradise will be preventedfrom seeing their Rabb by the curtain of Majesty over His Face. Otherwise the inhabitants ofparadise would also perish. The reference from the Quraan for the above Hadees is
46 But for such who fear standing before their Rabb (Lord) there will be two gardens.…62 And besides these two there are two other gardens. [Quraan: Ar Rahman, Chapter 55]
The utensils and contents of the first two gardens mentioned are silver. And the utensils andcontents of the second two gardens mentioned are gold. What are utensils? Utensils areinstruments or containers. What are contents? Contents are what is contained within avessel. The spiritual meaning of the above Hadees is that some people will be precious assilver. And they are the utensils of the first two gardens. The content or their Zikr will beprecious as silver. Similarly, some people will be more precious than silver and they will beprecious as gold. And their Zikr will be more precious than of the inhabitants of the previoustwo gardens. Yet they will not be able to see their Rabb. Even the inhabitants of the sixthparadise, Jannat Eden, will be prevented from seeing their Rabb by the curtain of Majesty -Jalaal.Therefore, those who are spiritually blind in this world will not see their Rabb in this world orthe next world even though they may attain paradise. Those who know Allah by his works willalso know Him in the next world. Allah’s Jalaal (Majesty) is unbearable just as the eyescannot look at the sun without turning blind.However, on the other hand Allah’s Beauty or Jamaal is easy to see through His works thatis, through the signs in His creation.Allah is Al Jalaal the Majestic like a hidden treasure waiting to be known. Yet Allah’s
Majesty is La Yuhtamal unbearable. Allah has given us all Knowledge of Him through
His Messengers There was La Shay (nothing) before Him, and there will be La Shaynothing afterwards when everything will perish.May Allah give us all true knowledge of Him through His works so that we may know Himbetter. Aameen.
177 41 – AL JALEEL
The person who reads Ya Jaleelu 1111 times everyday, Allah will bestow honour and respect .
178 40 – AL HASEEB
38 There can be no reproach for the Nabee (Prophet) in what Allah has indicated to him as aduty. That was Allah's way with those who passed away before and the commandment ofAllah is certain destiny.39 Who delivered the messages of Allah and feared Him, and feared none except Allah.Enough is Allah to call to account.40 Muhammad is not the father of any man among you, but he is the Rasool - Messenger ofAllah and the Seal of the Prophets; and Allah has full knowledge of all things. [Quraan: Al Ahzaab, Chapter 33]
Allah had already enumerated, counted, numbered the duties for the Muslims. And Allah hasrecorded them in the Quraan. The clarification of the duties has been recorded in theAhadees. Since Allah is Al Haseeb the Reckoner, Allah has given us Muslims the Quraanwhich is a Book of divine revelations. All the chapters in the Quraan have been accountedfor. All the verses have been accounted for. All the letters in all the verses in all the chaptersin the entire Quraan have been accounted for. Finally, Allah has taken the responsibility ofguarding the Quraan from any additions, subtractions or alterations. And there are still somemisguided fools who say that the numbers have nothing to do with Islaam! Allah also tells usin the above reference that He has accounted for all His Messengers and ProphetMuhammad is the final Messenger, the Seal of the Messengers, so there will be no moremessengers after him. The Book of Messengers has been all accounted for.
179 40 – AL HASEEB
13 And every man's fate We have fastened to his own neck, We shall bring forth for him onthe Day of Judgment a book which he will see spread open.14 "Read your book. Your soul is sufficient this day as a reckoner against you." [Quraan: Al Israa, Chapter 17]
There is Hisaab and there is Kitaab. There is accounting and there is a book. The accountedfigures are kept in the book. Each one of us is writing his or her own accounts in his or herown book. Any good deed will be found in that book and any evil deed will be found in thatbook. To do accountancy one has to know the three ‘R’s. That is Reading, Riting andRithmatic. So the soul is able to read, write and add up. The soul also knows about profit andloss accounting. In all forms of accounting, we have to determine whether there is adeficiency or whether there is sufficiency.We all want sufficient money to live on. We all want sufficient space to live in. We all wantsufficient comfort in our lives. Nobody likes deficiency. Everyone wants sufficiency. What weall need is sufficiency. But when it comes to our belief in Allah, not many people considerwhether we have sufficiency. That is, do we have adequate belief in Allah? Do we havesufficient belief in Allah? Do we have sufficient trust in Allah? That is the question each oneof us has to answer for ourselves.When Prophet Ibraheem was about to be thrown into the fire, Hadhrat Jibraeel came ina flash and asked him if he needed any assistance:
“Allah is sufficient for us and He Is the best disposer of affairs”, was said by Ibraheem whenhe was thrown into the fire; and it was said by Muhammad when they (i.e. hypocrites) said,“A great army is gathering against you, therefore, fear them”, but it only increased their faithand they said: "Allah is sufficient for us, and He is the best disposer (of affairs, for us)." [Sahih Al Bukhari]
129 Now, if they turn away say: Allah is sufficient for me. There is no god only He. In Him Iput my trust, and He is Rabb (Lord) of the tremendous throne. [Quraan: At Tawba, Chapter 9]
Allah is Al Haseeb the Reckoner, who will take account of our every action. Allah is As
Samee the Hearer of our every word, Allah has knowledge of our every act, ourevery thought, our every feeling and our every intention. We are His creation so Heknows our every secret. May Allah guide us all and give us all sufficiency in our belief in Himas the disposer of affairs. Aameen.
180 40 – AL HASEEB
The person who writes Ya Haseebu and keeps it with him / her and also keeps repeating YaHaseebu will be safe from his / her enemy, Inshaa Allah.The person who is afraid of someone or something, should read Hasbiy Allahul Haseebu 70times, morning and night for eight days, starting on a Thursday morning. That person will besafe from all kinds of danger from everything, .
181 39 – AL MUQEET
85 Whoever intervenes in a good cause will have a share of it, and whoever intervenes in anevil cause will bear consequence of it. Allah maintains all things.86 And when you are greeted with a greeting, greet back with a better one or return it. Allahkeeps count of all things. [Quraan: An Nisaa, Chapter 4]
182 39 – AL MUQEET
Ultimately, when the spirit is separated from the body on death, it should be strong enough towithstand the change in its existence without the body instead of being weak and helplessand traumatised.A weak spirit will not be able to answer the questions asked in the grave. A strong spirit willbe able to answer those questions, Inshaa Allah.Let us take the above examples one stage further. Since the food nourishes the whole body,similarly, Islaam is the food of the body of the Muslim community. Likewise, since somepeople satisfy the body and neglect the spirit, we find that some Muslims turn against othersto protect their leadership and kingdoms. That is they neglect the spirit of Islaam. Just as ZikrAllah is the nourishment of the spirit, unity is the spirit of Islaam. Since the Muslim communityis divided, we find weaknesses in the Muslim community which are being taken advantageof. I would like to reiterate the words from the Quraan as a reminder:Whoever intervenes in a good cause will have a share of it, and whoever intervenes in anevil cause will bear consequence of it. Allah maintains all things.Once again I would like to ask the question that I asked in the section on Al Muqsit:The Muslim nations and their so-called believing leaders when they fall into dispute amongstthemselves they seek the help of non-Muslims in settling their disputes. When was the lasttime that any leaders of quarrelling nations whether believers or disbelievers asked theleader of a believing nation to settle their disputes?Allah is Al Muqeet the Maintainer, who has the power and He is Qaadir Able to do andcreate what He wills. Allah feeds His creation with different foods so that they may also gain
strength and attain Knowledge of their Creator. When we repent and turn to Allah and callHim, Allah At Tawwab the Acceptor of Repentance returns to His creation time and timeagain. May Allah maintain our affairs for us, give us strength, physically and spiritually, giveus knowledge of how to call upon Him, and turn towards Him in times of health and sickness,happiness and sadness, plenty and less, in all conditions, all the time. Aameen.
MEDITATIONThe person who reads Ya Muqeetu 1111 times everyday, will have all his / her lawful wishesfulfilled, Inshaa Allah. The person who wears a silver ring with this Name of Allah engravedon it will receive strength as .
183 39 – AL MUQEET
Updated
184 38 – AL HAFEEZ
63 So when they went back to their father they said: “Our father! The measure of grain isdenied to us, so send with us our brother that we may obtain the measure, surely we willguard him well.”64 He said: “Can I entrust him to you except as I entrusted his brother to you before? Allah isbetter at guarding, and He is the Most Merciful of those who show mercy.” [Quraan: Yusuf, Chapter 12]
Prophet Yusuf’s brothers asked their father Prophet Yaqub to let their youngest brotheraccompany them to Egypt otherwise they would not get any grain during the years of famine.They wanted to take the responsibility of guarding their youngest brother from any kind ofharm. Yet these were the same brothers who thought ill of their own brother Hadhrat Yusuf and previously plotted to get rid of him so as to divert the love and attention of their father,from Prophet Yusuf , towards them. Previously they had said the same words that theywould guard Yusuf . Yet, secretly they wanted to get rid of Prophet Yusuf .The moral in all this is that, like Prophet Yaqub , we cannot place our trust in any one,other than Allah. It is Allah who guards and preserves us till the appointed time of our death.It is Allah who guards us from all kinds of harm and danger. It is Allah who guards andpreserves our every breath from the first breath on the day we were born to the last breathon the day we die. However, Allah can choose and place His trust on whomever he wishes.Allah chose and placed His trust on Prophet Adam to guard himself and not to approachthe forbidden tree. But Shaytaan made him slip. Then we have the example of Prophet Yusuf :
185 38 – AL HAFEEZ
54 And the king said: “Bring him to me that I may attach him to my person.” And when hehad spoken to him he said: “You are today before our presence established and trusted.”55 (Yusuf) said: "Set me over the storehouses of the land. I will skilfully guard them." [Quraan: Yusuf, Chapter 12]
Here, the king of Egypt placed his trust in Prophet Yusuf to guard the storehouse duringthe famine. And we all know that he lived up to his responsibilities. That is he emulatedAllah’s quality or Attribute of guarding or preserving what he had been trusted with. Similarly,Allah placed His trust in all His Messengers to deliver His Message to one and all of theircommunity. They placed their trust in Allah to guard them long enough to deliver theMessage. That is Allah guarded them so that they could fulfil their responsibility like theexample given for Prophet Yusuf .How does Allah guard or preserve His creation? We need to look at another reference fromthe Quraan:
56 "I place my trust in Allah my Rabb (Lord) and your Rabb! There is not a moving creaturebut He has grasp of its forelock. My Rabb is on a straight path.57 "If you turn away, I have conveyed the message with which I was sent to you and myRabb will make another people to succeed you and you will not harm Him at all. For myRabb is Preserver over all things.” [Quraan: Hud, Chapter 11]
There is not a moving creature that is not in the grasp of Allah. Therefore it is easy for Allahto be the Preserver, the Guardian over everything. Just as Allah is the Preserver, Allah wantsus to preserve and guard our faith in Him. So Shaytaan has been given leave to lead thepeople astray except those who truly believe in Allah and the Last Day. Over them Shaytaanhas no authority. Why does Allah give Shaytaan leave to lead people astray?Allah wants to distinguish between those who believe in Him and the hereafter from thosewho doubt.Allah is Al Hafeez the Preserver, whom we should praise so that Allah Al Fattah the
Opener may open our hearts and minds to the Knowledge of knowing Him. When thedoors of knowledge open, Allah leads His creation out of the shadow, into Zahoor visibilty.May Allah Preserve all those who believe in Him and the last day in this world and the next.Aameen.
186 38 – AL HAFEEZ
MEDITATIONThe person who writes Ya Hafeezu or Ayat ul Kursi (Quraan 2:255) or the last part of Ayat ulKursi and places it round the neck of a child, Allah will guard and preserve the child from theevil eye. If the writing is placed in the property, Allah will protect the property, Inshaa Allah.Last part of Ayat ul Kursi is this:Wa La Yaooduhu Hifzu Humma Wa Huwal Aliyul AzeemAnd their preservation does not burden Him. He is the High, the Magnificent.
The person who reads Ya Hafeezu 1111 times everyday, will be protected from all kinds ofcalamities and disasters, .
187 37 – AL KABEER
22 Say: “Call upon those whom you set up beside Allah! They do not possess an atom'sweight either in the heavens or the earth, nor have they any share either, nor is any of themHis helper.”23 "No intercession can avail in His presence except for those for whom He permits. Yet,when fear is removed from their hearts, they say, ‘What was it that your Rabb (Lord) said?’They say, ‘The Truth. And He is the High, the Great.’” [Quraan: Sabaa, Chapter 34]
Allah gives us an example that the helpers, the idols, that some people set up as gods do nothave an atom’s worth of power in the heavens or earth. The example is like that of an atombefore Allah. An atom is so small that it is invisible to the human eye. In other words, it isfutile to compare a god with the Greatness of Allah. And yet every atom is Allah’s creation.One atom compared to all the atoms in the heavens and earth is not really a comparison. Butin this case these gods do not even possess one atom’s worth. In other words Allah’sGreatness cannot be compared! But Allah is not visible! So how does the Attribute ofGreatness be applied to Allah?In the section Al Hafeez, it was stated that: There is not a moving creature that is not in thegrasp of Allah. So Allah is Great in that He has power over every creature. Allah is Great inthat He created everything yet He is Uncreated. Allah is Great in that He is One, and all ofthe creation together are powerless before Him. Allah is Great in that just a glimpse of His
188 37 – AL KABEER
Majesty made the mountain crumble to dust. Allah’s Greatness cannot be compared in thephysical sense. Which reminds me of a saying: Is intellect greater or a cow? An uninitiatedperson like me who could only think in physical terms replied: A cow is greater! Thecomparison was done on a physical level by comparing the size of the human brain to thesize of a full-grown cow. And of course the cow is physically bigger than the human brain.But the human intellect is capable of putting the cow to use, to serve the human in moreways than one. That is the cow although it is physically bigger than the human being, ismade to serve the human. Hence we cannot compare Allah’s Greatness to anything. Allah’sGreatness is beyond comparison and reason.
30 That is because Allah, He is the True - Real, and that which they invoke beside Him is thefalse, and because Allah, He is the High, the Great. [Quraan: Luqmaan, Chapter 31]
Truth is not the same as false? Existence is not the same as non-existence. So when westand for prayer, we say: “Allahu Akbar – Allah is Great!” When we bow down to Allah, wesay: “Allahu Akbar!” When we prostrate we say: “Allahu Akbar!” When we sit up fromprostration we say “Allahu Akbar!”All this is in order to forget our selves in prayer because the real existence belongs to Allah.Our existence is false on the basis that we exert emphasis on the physical side and forgetthe spiritual side. Our physical existence is on a temporary basis. Even in that temporaryphysical existence, there are signs of aging to show us that we cannot exist forever in thisworld.On the one hand we have Allah who is Living, Hearing, Seeing, Powerful, Creator and Greatand there is no change in Him, and on the other hand we have an idol that is lifeless, deaf,blind, powerless, created and finite that does age with time. How can there be a comparison?Similarly, the human body only has life while the soul is attached to it. Otherwise it is lifeless.Allah is above all kinds of comparisons in His Greatness. Allah’s Greatness is in relation tothat Allah existed before anything else was created. Allah exists while the creation exists.And Allah will exist while everything else will perish yet there will be no change in Allah.Allah’s Greatness is that He can bring into existence all kinds of creation out of nothing.Allah is Al Kabeer the Great, who is beyond comparison because there is nothing likeHim. Allah just has to command and the creation comes into existence from the
Knowledge of Allah, who is the Rabb Lord of all the worlds. May Allah give us all theknowledge about His Greatness, so that we may praise Him as is worthy of His Greatness.Aameen.
189 37 – AL KABEER
MEDITATIONThe person who reads Ya Kabeeru 1111 times everyday, will be protected and receivehon .
190 36 – AL ALI
Just as the Attribute Al Kabeer, the Great cannot be quantified, neither can the Attribute AlAli, as far as Allah’s High-ness is concerned. Allah’s High-ness is not in respect of height.Allah’s High-ness is in respect of honour. Allah’s High-ness is in respect of dignity.In the prayer, when we perform the prostration, we say Subhaana Rabbi Yal Alaa, Glory tomy Rabb (Lord) the High. In the physical we lower our bodies towards the ground so as totouch our forehead on the ground, on the tongue we proclaim, Allah’s High-ness. This isdone to show humility before Allah. This is done to show how insignificant we are comparedto Allah’s High-ness. This is done to show how insignificant we are compared to theuniverse. Yet Allah prefers human beings above all His creations from universes to ants. YetAllah prefers human beings above angels and jinn.But not all human beings are preferred. Allah only prefers those human beings who believein Him and show humility. We have to lower ourselves with humility, out of respect before
191 36 – AL ALI
Allah the High. Therefore, the lowering of our selves, the humbling of our selves, the practiceof humility, is not just in prayer, but all the time, since Allah is always present and Allah isaware of everything all the time. Yet there are people who perform the prayer and as soon asthe prayer is over, they are filled with arrogance! Shaytaan makes them puff up with pride.Here is an observance that has been highlighted by my brother Prof. Ashiq Hussain Ghouri,which is something which we should all reflect upon:The tree that is laden with fruit, lowers itself, it lowers its branches, under the weight of thatfruit. So that people may pluck and eat its fruit with ease. In fact the tree is humbling itselfbefore Allah for being given the gift of plenty.Similarly, a learned scholar humbles himself before Allah all the time, so that others maybenefit from his knowledge. Similarly the scholar is humbling himself under the weight of theknowledge that Allah has bestowed upon him. Only Allah is the High, who chooses Hispeople for this gift. Allah’s Messengers are the perfect examples for us in humblingthemselves before Allah, the High. Prophet Muhammad is the best example for us tofollow on being humble before Allah, the High.
67 And they have not estimated Allah’s might truly. The earth shall be in His grasp on theDay of Judgment, and the heavens shall be rolled up in His right hand. Glorified is He andHigh from all that they ascribe as partners (to Him). [Quraan: Az Zumar, Chapter 39]
Allah’s decision is final! There are no partners to have a say in the matter. There can be nopartners to share in Allah’s High-ness. Allah is Al Ali, the High where partners cannot beascribed to Him. The earth and the heavens shall be in His hand, where is the room for anypartners? That is every creature, every creation, shall be in His hand, where is the room forpartners? Allah is High from all that they ascribe as partners. Allah has no partners!The greatest verse of the Quraan, Ayat ul Kursi (Chapter 2: 255) mentions Allah’s Attribute,Al Ali, the High. And reciting just the last part of Ayat ul Kursi, “Wa La Ya Uduhu HifzuHumma Wa Huwal Ali Yul Azeem” is enough to destroy the jinn.
Allah is Al Ali the High, without any comparison to His High-ness. Allah is One, La
Shareek without any partners, that is partners cannot be ascribed to Him. Allah’s
Knowledge is limitless. That is without boundaries. Allah is Al Ali, the most High in everysense.
Laam 30 Ya 10 TOTAL 110 TOTAL
192 36 – AL ALI
MEDITATIONThe person who reads Ya Aliyu 1111 times everyday, will be elevated in respect, and theperson will find happiness, .
193 35 – ASH SHAKOOR
29 Those who read the Book of Allah, establish prayer and spend (in charity) out of what Wehave provided for them secretly and openly, hope for imperishable gain.30 For He will pay them their due and Increase them of His grace. He is Forgiving,Appreciative. [Quraan: Faatir, Chapter 35]
Allah wants us to read His Book, establish prayer and give charity. To read the Book of Allahis to know Him and to soften the heart. Allah appreciates or recognises us reading His Bookin order to know Him. To establish prayer is to ‘nourish’ the spirit. The spirit is the breath ofAllah. Allah appreciates or recognises the act of prayer. Spending what Allah has providedfor the sake of Allah is appreciated or recognised by Allah, because Allah is the Appreciative.Allah only appreciates or recognises our actions if we appreciate Allah in the first place.Since everything is based on intention. If we read the Book of Allah to show others, howbeautifully we can recite, then it is only recited or read out of ego, Allah does not appreciatethat. If we establish prayer to show others our piety, Allah does not appreciate that. If wespend out of what Allah has provided to show our generosity, Allah does not appreciate that.That is why the word ‘secret’ precedes the word ‘openly’ in the above reference. That is, readthe Book of Allah to know Allah and to attain nearness to Him. Establish prayer in order topractice for the meeting with our Rabb as in the Miraaj (Ascension). As Allah’s Rasool,Muhammad said: “The prayer is the Miraaj of the believer.”Spend in the way of Allah, because we are all His creatures. Allah will give everyone theirdue and increase them as mentioned in the following reference:
194 35 – ASH SHAKOOR
33 Gardens of Eternity! They enter them wearing bracelets of gold and pearls and theirgarments there will be silk.34 And they will say: "Praise be to Allah who has removed grief from us. Our Rabb (Lord) isForgiving, Appreciative. [Quraan: Faatir, Chapter 35]
Gardens of eternity are the reward from Allah the Appreciative, to His servants. Why gardensof eternity? That is because they read and understood the Book of Allah and attainednearness to Allah. Allah, the Appreciative, recognised that. Why bracelets of gold? That isbecause there hearts were generous and they used their hands to spend in the Name ofAllah, secretly and openly. Allah, the Appreciative, recognised that. Why garments of silk?That is because they purified themselves with water and water is a smooth substance likesilk. They purified themselves physically and spiritually and then stood for prayer beforeAllah. Allah, the Appreciative, recognised that.Likewise, we also have to emulate Allah’s Attribute, Ash Shakoor, the Appreciative. Why?We have to appreciate that Allah does not need anything, yet when we recognise Him as ourCreator, He rewards us just for that recognition. We have to appreciate that Allah hasprovided us with all the necessary conditions beneficial for our existence. We must show ourappreciation towards Allah for that. Yet there are people who abuse the gifts given to us byAllah, in order to make a personal gain. Although, Allah tells us to spend what He has givenus in His way secretly and openly.But there are always those who praise Allah for all His gifts that He has bestowed uponthem, in all conditions. The angels are ashamed when Allah reminds them of the time whenthey said: ”Will You place one that will do mischief and shed blood?”Allah is Ash Shakoor the Appreciative, the One who recognises His servants actionswhich are performed for His sake and for no other reason. Allah is Kaafi Allah is Sufficientto reward His servants for their good intentions and actions. Appreciation is only possiblewhen there is Love involved. The servant performs the actions because of Allah’scommandments and the desire for heaven. And Allah appreciates the servants’ actions out ofLove for His servants. Yet there are some servants who perform the commandments outof Love for Allah and not for heaven. These servants are very few in number and theirultimate reward is the meeting with their Rabb Lord. May Allah increase these fewservants to many. Aameen.
195 35 – ASH SHAKOOR
MEDITATIONThe person who reads Ya Shakooru 41 times everyday, will be relieved of all kinds ofconstriction, oppression and sadness, .
196 34 – AL GHAFOOR
31 Say, (Muhammad, to mankind): “If you love Allah, follow me; Allah will love you andforgive you your sins. Allah is Forgiving, Merciful.”32 Say: "Obey Allah and His Rasool (Messenger)"; but if they turn back Allah does not lovedisbelievers. [Quraan: Al Imraan, Chapter 3]
In the section Ash Shakoor we found that forgiveness is based on reading the Book of Allah,establishing prayer and spending in Allah’s way out of what He has provided for us. Belief inAllah and His Rasool is the basic requirement. If we believe in Allah and His Rasool,Muhammad , it follows that we will believe what was revealed to Prophet Muhammad is the Truth. That Truth is the Book of Allah, the Quraan. And in that Book of Allah, it ismentioned in the above reference, Say, (Muhammad, to mankind): “If you love Allah, followme; Allah will love you and forgive you your sins. Allah is Forgiving, Merciful.” ProphetMuhammad is the connection for the Muslims between them and Allah. So, to follow theexample of Allah’s Messenger is a means to attaining Allah’s forgiveness.However if we wrong someone, Allah does not forgive unless the person who has beenwronged, forgives first. Otherwise, the wronged person has claim over the wrongdoer on theDay of Judgment. Likewise, it is better to forgive others who wrong us. The reason behind itis that whoever holds a grudge, dissipates their energy and Shaytaan plays with thatperson’s mind.A man approached Prophet Muhammad and said:"I ask you to ask Allah for forgiveness for me for all the hostility I directed against you and forwhatever insults I expressed in your presence or absence."
197 34 – AL GHAFOOR
Allah originates His creation out of love. Allah restores them in order to reward those who areworthy of reward. Allah forgives those who repent. Allah loves His creation. If only thecreation loved Him as He deserves to be loved. Whether the creation appreciates Allah ornot, Allah still provides for each creation their needs. So, if we spend in His way out of whatHe has provided, secretly or openly, He will keep providing out of love and forgiveness. Thelesson is that we must learn to forgive. We must emulate Allah’s Attribute, Al Ghafoor, theForgiving. If Allah provides for all His creatures regardless of whether they believe in Him ornot, why should we not be ready to forgive those who have wronged us personally?
Allah is Al Ghafoor the Forgiving without any needs from any of His creatures. Allah AlFattah the Opener, opens the gates of forgiveness for His creatures out of Love forthose servants who obey Him and His Rasool . All praise is for Allah, Rabb il Aalameen Lord of the worlds.May Allah, soften our hearts towards others, so that we may find it easy to forgive those whowrong us, because it is Allah who is the Doer of what He wills!
Fa 80 Waw 6 Ra 200 TOTAL 1286 TOTAL
198 34 – AL GHAFOOR
MEDITATIONThe person who reads Ya Ghafooru 1111 times everyday, will forget all his / her troubles andwill receive goodness from Allah in wealth and, 66 Names out of the 99 Names of Allah have been completed here.
199 33 – AL AZE. [Quraan: Al Baqara, Chapter 2]
As it is has already been mentioned, this verse from the Quraan, also known as Ayat ulKursi, is the greatest verse in the Quraan. In fact it can be considered the essence of theQuraan. Prophet Muhammad has said that this verse contains Ism Azam, the greatestName of Allah. Some people consider Al Hayy ul Qayyum which is mentioned in the Ayat ul
Kursi as Ism Azam. The difference between the word Azam and the Name Azeem
is that the letter Alif disappears and the letter Ya appears. Ayat ul Kursi endswith Allah’s Attribute Al Azeem, the Magnificent. Al Azeem is another Attribute, which ismentioned in the Salaah, prayer, like the Attribute Al Ali, the High.
200 33 – AL AZEEM
Just as the Attribute Al Ali, the High, is mentioned three times in prostration during prayer, AlAzeem, the Magnificent, is also mentioned three times while bowing. That is, Al Azeem alsohas a special place in the Salaah just like Al Ali. We say Subhaana Rabbi Yal Azeem - Gloryto my Rabb (Lord) the Magnificent. In the physical we bow ourselves to Allah’s Magnificence.On the tongue we proclaim, Allah’s Magnificence. This is done to show that no one dares tolook at Allah’s Magnificence. We have not got the eyes to see His Magnificence. There arethings which draw the attention of the eyes. And there is that which the eyes cannot see.Allah’s Magnificence is beyond the realms of sight. Allah’s Magnificence is beyond therealms of intellect. Allah’s Magnificence has no bounds or limits. So we bow instead toAllah’s Magnificence.Allah is Al Azeem and He has also named a throne with that Name. It is one of the seventhrones and it is Arsh Azeem. So let us take an example from the Quraan about themagnificent throne:
128 There has come to you a messenger from amongst yourselves, it grieves him that youshould perish, full of concern for you, for the believers he is kind, merciful.129 But if they turn away, say: "Allah is Sufficient for me. There is no god only He. In Him Iplace my trust and He is the Rabb (Lord) of the magnificent throne!” [Quraan: At Tawba, Chapter 9]
Prophet Muhammad , is concerned for the believers. He is kind and merciful. He wouldnot like to see us perish. Therefore he has shown us how to present ourselves before Allah,Al Azeem, the Rabb of Arsh Al Azeem. Bow down to Allah the Magnificent. HadhratMuhammad has been sent as the last Messenger of Allah. Therefore the teaching thathe passed on is for everyone. The teaching is there for everyone. But if some of humanityturns away from that teaching, then the message is clear: Allah is Sufficient for a believer.There is no god only He. In Him we place our trust and He is the Rabb (Lord) of themagnificent throne.Arsh Al Azeem, the magnificent throne is the fifth throne. It is the throne where all the gooddeeds of the heart reach. It is the throne where all the Zikr Allah, remembrance of Allah,reaches. That is where Allah’s will is being sought.
Allah is Al Azeem the Magnificent. Allah’s Magnificence is beyond the realms of visibilityor Zill shadow. Allah’s Magnificence cannot be arrived at by knowledge. Knowledge
201 33 – AL AZEEM
Zoin 900 Ya 10 Meem 40 TOTAL 1020 TOTAL
MEDITATIONThe person who reads Ya Azeemu 1111 times everyday, will be granted respect andgreatness and he / she will be protected from the evil of the jinn, .
202 32 – AL HALEEM
Allah is Exalted and High, therefore, Allah does not become angry or enraged by “what theysay!” That is, Allah does not take to account those who associate partners with Him becauseAllah is Forbearing. If Allah took swift account of everyone for their wrongdoing, hardlyanyone would exist. Each person would be destroyed there and then on their first wrongaction. Allah is Forbearing, giving us plenty of chances to repent. Since Allah is Forgiving, Heis Forbearing. Hence, good Muslims exist, bad Muslims exist, and so do those who ascribepartners to Him also exist, for an appointed term. All the heavens and earth and thecreatures within praise Him in their own way. And as Allah says: But you do not understandtheir praise.It was the custom of the city people during the birth of Hadhrat Muhammad to send theiryoung to the desert, with foster parents, during the initial years of their life in order to makethem strong and aware. It was the custom of the city people to pay the foster parents for theirkindness and looking after the child. When Hadhrat Muhammad was presented to thefoster parents, everyone refused to take him in their care because he was an orphan. Thedesert people wanted to be rewarded, and what could they expect from a child’s motherwhose husband had passed away! Every woman had taken a child and Allah, Al Haleem,made sure that a lady called Haleemah did not get any child from the well-to-do families. All
203 32 – AL HALEEM
the children were allocated a foster mother except Muhammad . All the foster motherswere allocated a child except lady Haleemah. And in the words of lady Haleema: “Everywoman who came with me got a suckling except me, and when we decided to depart I saidto my husband: ‘By Allah, I do not like the idea of returning with my friends without asuckling; I will go and take that orphan.’ He replied, ‘Do as you please; perhaps Allah willbless us on his account.’ So I went and took him for the sole reason that I could not findanyone else.” Most women had decided that they wanted payment for looking after the fosterchildren. Lady Haleemah having been left without a foster child, decided she would look afterthe orphan even if she was not going to be compensated by the child’s mother.Miracles started happening from that moment onwards. Allah, Al Haleem, had placed thequality of forbearance in lady Haleemah and hence Allah chose her because of that quality.Now do you see: The seven heavens and the earth and all that is in there praise Him, andthere is not a thing but celebrates His praise; but you do not understand their praise. He isForbearing, Forgiving.
16 So fear Allah as much as you can, and listen and obey, and spend for the benefit of yourown souls. And those saved from the greed of their own souls they are the successful.17 If you lend to Allah a beautiful loan He will double it to for you and He will forgive, for Allahis Appreciative, Forbearing,18 Knower of the invisible and the visible, the Mighty, the Wise. [Quraan: At Taghaabun, Chapter 64]
To be saved from greed is for the benefit of our own soul. To be saved from greed is tospend in the Name of Allah for the benefit of our own soul. In lady Haleemah we have a fineexample of one who spent in the Name of Allah for the benefit of her own soul. In ladyHaleemah we have a fine example of one who was saved from the greed of her own soul bylending Allah a beautiful loan. She took the orphan, Muhammad for the benefit of herown soul and not for any payment in return. That was the beautiful loan. Allah wasAppreciative towards her and Allah, Al Haleem, rewarded lady Haleemah many times over.Allah has given us examples openly, or visibly, to follow, yet we do not take heed. May Allahguide us to be forbearing like lady Haleemah so that we can come to know a little bit abouthow Allah is the Forbearing. Aameen.
Allah is Al Haleem the Forbearing. We turn towards Him when all the avenues are closed
and there is nothing or nobody left to turn to. Even if we have nothing to spend, there is
always something that we can give in the Name of Allah. That is knowledge is to be usedso that we can say a kind word or perform a good deed in the Name of Allah. Even that act ofkindness is a beautiful loan to Allah. Those who give a beautiful loan to Allah are AlMuflihoon the successful.
204 32 – AL HALEEM
The person who reads Ya Haleemu 1111 times everyday, will overlook the faults of othersand it is also beneficial for the cure of visible and invisible illnesses, .
205 31 – AL KHABEER
1 Alif Laam Ra. A Book with basic verses, further explained in detail from One Wise, Aware.2 Serve none but Allah. For, I am to you from Him a warner and a bringer of good tidings. [Quraan: Hud, Chapter 11]
We are living in a time where information is available instantly from east to west, north tosouth. We are informed of what is happening anywhere in the world through satellitecommunications. So we rely on these inventions to keep us informed as to what is happeningaround the world. Allah, on the other hand, does not need these gadgets in order to beinformed and aware of what is happening in His creation. With all these gadgets andinformation, mankind have still not understood the Quraan like it is supposed to beunderstood, except a few who learned directly from Allah’s Rasool, Muhammad . Theyattained the status of Radhi Allah. Allah was pleased with them while they were walking onthis earth. And that teaching has been passed from person to person in the spiritual learningand development. We are told in the above reference: Alif Laam Ra. A Book with basicverses, further explained in detail from One Wise, Aware. Wisdom precedes Awareness.Allah is Wise and Allah is Aware. Allah taught wisdom to Hadhrat Adam directly. Allahtaught wisdom to Hadhrat Khidhr directly. And Allah taught wisdom to HadhratMuhammad directly. Jibraeel came with the verses of Haroof Muqattaat (abbreviatedletters) and recited them. Prophet Muhammad replied: “Understood!” Jibraeelenquired about their meaning. Prophet Muhammad replied: “The message of the Kingcannot be disclosed to the servant.” The servant being referred to in this case was Jibraeel . So, awareness comes from wisdom.Allah is Aware of everything in both the physical and spiritual worlds. Nothing is hidden fromAllah’s Awareness.
206 31 – AL KHABEER
28 "Those who believe and whose hearts find satisfaction in the remembrance of Allah.Without doubt, in the remembrance of Allah do hearts find satisfaction. [Quraan: Ar Raad, Chapter 13]
Now let us a look at another example from the Quraan about Allah, Al Khabeer, the Aware.
102 Such is Allah, your Rabb (Lord). There is no god only He, the Creator of all things, soworship Him. And He takes care of all things.103 No vision can grasp Him but His grasp is over all vision. He is the Subtle, the Aware. [Quraan: Al Anaam, Chapter 6]
Since Allah is the Creator of all things, it follows that Allah is Khabeer, Aware about them.Since Allah is Aware about all things, Allah takes care of all things as He deems appropriate.Vision is defective and it cannot grasp Allah. Just as Prophet Musa said: “Show me (Yourself), that I may gaze upon You” and the answer was: “You cannot see me!”So the moral of the story is that Allah cannot be seen but He can be known from His works.Just as the mountain crumbled, that was a sign from Allah, that we too should be aware ofHim who created us. Since whatever we see, whatever we do, Allah is Aware of all that.Allah’s grasp is over all vision. Allah’s grasp is over all action. In fact, Allah is Aware of themost subtle detail about all His creation.
Allah is Al Khabeer the Aware, because He is the Al Badee the Originator of all
creation. Nothing is outside the Knowledge of Allah from the cosmos to the single cellamoeba. Why? Because Allah is the Rabb Lord of all the worlds. All praise is for Allah inas many different ways as the number of His creations, which only Allah is Aware of. MayAllah accept our insignificant praise of Him, Aameen.
207 31 – AL KHABEER
Ba 2 Ya 10 Ra 200 TOTAL 812 TOTAL
The person who reads Ya Khabeeru 1111 times everyday, will receive knowledge of theunknown, Inshaa Allah. The person who is under the spell of worldly desires should alsoread Ya Khabeeru, Inshaa Allah, he / she will be freed from those desires .
208 30 – AL LATEEF
Subtlety means, to be tactful. To know and make available the finer points about something.Allah is Al Lateef, the Subtle in that He teaches us by the Quraan by giving us examples. Theexamples need to be studied and the finer or subtle points should be understood. Imaam IbnAl Arabi wrote:The one who receives the manifestation (Tajalli) will only see his own form in the mirror ofthe Real. He will not see the Real, for it is not possible to see Him. At the same time, heknows that he sees only his own form. It is the same as a mirror in the visible world inasmuchas you see forms in it or your own form but do not see the mirror. At the same time, however,you know that you see the forms, or your own form, only by virtue of the mirror. Allahmanifests that as a model appropriate to the Tajalli of His Essence, so that the one receivingthe Tajalli knows that he does not see Him. There is no model nearer or more appropriate tovision and Tajalli than this. When you see a form in a mirror, try to see the body of the mirroras well - you will never see it. It is true that some people who perceive this say that thereflected form is imposed between the vision of the seer and the mirror. This is the most thatit is possible to say, and the matter is as we have mentioned. [Fusus al Hikam]
No vision can grasp Him but His grasp is over all vision. He is the Subtle, the Aware. It is likethe explanation given above. We see our own reflection in the mirror and yet we do not seethe mirror. Without the mirror or the quality of reflection, it is not possible to see the
209 30 – AL LATEEF
manifestation. Therefore, to take the crude example, Allah is ‘like’ the mirror which we do notsee. So, vision cannot grasp Him. We need Allah to see. Hence, His grasp is over all vision.There is subtlety in vision and there is subtlety in speech. Every vision has a visible andhidden meaning. Every word has an obvious and a hidden meaning to it. Therefore,Lateefah, subtlety is something that can be understood but cannot be expressed in words.For example, there is the Lateefah associated with the Nafs, the soul. And there is theLateefah associated with the Ruh, the spirit. These examples mentioned can only beunderstood, and yet they cannot be expressed in words. It follows, that Allah can only beknown through subtleties and cannot be expressed in words. Hence Allah is Al Lateef, theSubtle.
62 That is because Allah, He is the Real, and those they call besides Him, it is false,because Allah, He is the High the Great.63 Do you not see how Allah sends down rain from the sky and then the earth becomesgreen? Allah is Subtle, Aware. [Quraan: Al Hajj, Chapter 22]
In this example from the Quraan, we are told: Do you not see how Allah sends down rainfrom the sky and then the earth becomes green? Allah is Subtle, Aware.Here the subtlety is that rain descends from the sky and the earth becomes green. Even adisbeliever would agree with the fact that where there is rain, greenery will follow. Themessage for the believers is obvious as well as the subtle. What is the subtle message?The subtle message is that we must do Zikr Allah. We must remember Allah often. The ZikrAllah ascends from the earth towards heaven just as rain descends from heaven towards theearth. The rain is considered a blessing from Allah. It washes away the dirt. It causes thegrass to grow from the darkness of the earth into the light and it points towards heaven. ZikrAllah, is like a light that comes out of the darkness of our bodies, out of the darkness of themouth of a person and ascends towards heaven. What is heaven? A garden! The watering ofthat garden is Zikr Allah. Since Allah sends down the rain, we must send up the light of ZikrAllah. May Allah give us the ability to remember Him always. Aameen.
Allah is Al Lateef the Subtle. It is Allah that sends the rain from the skies to wash theearth, so we must do Tahhara purify ourselves in like manner with water that Allah has
provided us. The knowledge of Allah is subtle so He teaches us with similitude. When weFattah open ourselves, that is, approach the Quraan with an open mind, then Allahallows us to understand His finest mysteries. May Allah teach us His finest mysteries.Aameen.
210 30 – AL LATEEF
MEDITATION
The person who reads Ya Lateefu 1111 times everyday, for whatever difficulty, it will beovercome, Inshaa Allah. The person who reads Ya Lateefu 129 times will blessed in his / herearn .
211 29 – AL ADL
89 One day We shall raise from all communities a witness against them from amongstthemselves, and We shall bring you as a witness against these. And We reveal the Book toyou explaining all things, a guide a mercy and good news to Muslims.90 Allah commands justice and kindness and liberality to kin and He forbids all shamefuldeeds and injustice and rebellion. He instructs you that you may take heed. [Quraan: An Nahl, Chapter 16]
Allah commands justice and kindness and liberality. So we set up human courts of law.Allah’s justice is infallible. The justice in the law courts of the communities is prone to error.Hence there are times when there is a miscarriage of justice. Sometimes the innocent arelocked up, and sometimes the guilty walk away free. In Allah’s court, there is no miscarriageof justice. Allah knows the guilty from the innocent. Therefore it follows that each one of uswill get what we deserve. That will be then. How about now?There is a saying: What goes round comes round. Not many people realise this but it is thelaw of Allah, others call it the law of nature. The moral is to treat others like you yourselfwould like to be treated. If we show kindness towards others, others will show kindnesstowards us. If we are liberal with others, others will be liberal towards us. Kindness andliberality towards others is only possible if we are just. How do we practice liberality, kindnessand justice?
212 29 – AL ADL
When we stop loving the life of this world, then we can realise that one day, all this will be leftbehind. We can then learn and practice liberality. When we realise that in reality we are allone family, we can learn and practice kindness as towards our own family. When we realisethat our hands, and our feet, all belong to our body, then we can realise further that each oneof us is just like the different members of the same family, only then can we learn andpractice justice. Unfortunately, in this day and age, it is just, Me! Me! Me! Not Meem! We justremember the first Meem and not Meem, Meem Ya Meem which is MEEM!If we practice justice, kindness and liberality in this world, then justice kindness and liberalitywill come round to us in this world and the next, from Allah.And We reveal the Book to you explaining all things, a guide a mercy and good news toMuslims.The explanations are in the Book (the Quraan). If we take heed, it is for our own benefit. If wedo not, then we will be unjust to our own souls.
58 Allah commands you that you restore deposits to their owners, and, if you judge betweenmankind, that you judge justly. How excellent is this which Allah gives. Allah is He whohears, sees. [Quraan: An Nisaa, Chapter 4]
see in the section Al Hakam, Inshaa Allah. Allah is Al Adl the Just and He wants us toemulate that quality in Dunya this world without prejudice because whatever goes roundcomes round, just as Allah will be Just to each one of us on the Day of Judgment. There will
be La Raiyba Fee doubt or ambiguity in the facts or the decision from Allah. May Allahtreat all of us with kindness and be liberal. Aameen.
213 29 – AL ADL
Dal 4 Laam 30 TOTAL 104 TOTAL
The person who reads Ya Adlu 1111 times everyday, will be treated justly and he / she willalso learn how to be just .
214 28 – AL HAKAM
61 He is the Irresistible (watching) from above over His worshippers and He sets guardiansover you. At length when death approaches one of you, Our messengers take his soul andthey never fail in their duty.62 Then they are returned to Allah their Protector the True. Surely, His is the judgment. AndHe is the most swift of the Reckoner. [Quraan: Al Anaam, Chapter 6]
There is a saying: Never judge a book by its cover. How many of us stick to that rule? Notmany! If Allah, Al Hakam, the Judge, judged us by our looks, would that be fair?Fortunately for us, Allah does not judge us by our looks, or by our colour, or by our race.Allah Judges us by our actions and the intentions that preceded those actions. Hence to be a
. Al Hakeem, the Wise has one extra letter than Al Hakam. And that letter is the
letter Ya which represents knowledge, and wisdom. Hence Allah only judges us becauseHe has knowledge of our actions and intentions. Therefore Allah’s judgment is based onwisdom of the visible and invisible, actions and intentions. Then they are returned to Allahtheir Protector the True. Surely, His is the judgment. And He is the most swift of theReckoner. Therefore, whatever evil thought comes to our mind, we should resist to act uponit. Whatever good action we carry out, we should precede that action with a good intentionand not to score points.
215 28 – AL HAKAM
43 But why do they come to you for judgment when they have Torah, wherein Allah hasdelivered judgment (for them)? Yet even after that they turn away. Such are not believers. [Quraan: Al Maaida, Chapter 5]During the time of Prophet Muhammad and the rightly guided Khalifahs, the Jews usedto go to them for judgment. Because they knew, that those rightly guided people feared Allahand they would Judge with justice according to the Quraan and Sunnat. Imaam Ibn Al Arabi has reinforced this. He wrote:
Allah said, "We gave Sulaiman understanding of it” (in spite of his opposite judgment tothat of Dawood ), and Allah "gave each of them judgment and knowledge." (21:79)Dawood's knowledge was knowledge given by Allah, and Sulaiman's knowledge was theknowledge of Allah in the matter inasmuch as He is the Judge without intermediary. SoSulaiman is the interpreter of Allah in the seat of sincerity …The community of Muhammad was given the rank of Sulaiman in judgment and the rank of Dawood in wisdom, sothere is no better community than it. [Fusus al Hikam]
Who comes for judgment from the Muslims in this day and age especially from the non-Muslims? No one! Who do the Muslim leaders approach for judgment? Non-Muslims!Allah is Al Hakam the Judge. Allah’s decision or judgement is based on what is written inour Kitaab book, of thoughts and actions. And even after that, Allah has permitted HisBeloved Muhammad to intercede on our behalf.Allah! Give our Master, Sayyidina Muhammad the privilege of intercession andexcellence and high rank. And raise him to the highest station Makaam-e-Mahmood whichYou have promised him.
216 28 – AL HAKAM
MEDITATIONThe person who reads Ya Hakamu 1111 times everyday, will receive spiritual enlightenment .
217 27 – AL BASEERa, Chapter 42]
There is nothing like Allah, so whatever we see is nothing like Allah. Allah sees His creation,but His creation cannot see Him. And yet, Allah has given us a pair of eyes to see with.Allah’s Seeing is not like our seeing, because there is nothing like Him. Allah sees our everyaction. Allah even sees our every thought. Nothing is hidden from Allah’s seeing, not even anatom. Allah sees all His creation, everywhere, at the same time. That includes all the creationin the heavens and on earth and even within the earth.Prophet Musa said: “Let me gaze upon You” and Allah replied: “You cannot see Me!”Another incident comes to mind, where a student asked his Shaykh to show him Allah. TheShaykh pointed to the sun and said: “Look at that with your eyes open.” The student couldnot bear to see the intensity of the sun’s light. So the Shaykh said: “If you cannot bear to lookat the sun, then how can you bear to see the One who created it? His intensity is far, fargreater than that of the sun.”As stated in the above reference, Allah has created things in pairs. Hence Allah gave us apair of eyes. Yet the right eye cannot see the left eye and the left eye cannot see the righteye without the aid of a mirror. The amazing thing is that our eyes are placed next to each
218 27 – AL BASEER
other. But when we look at any object whether it is near like our hand, or it is far like themoon, sun or star, we see them in an instant. As Imaam Ibn Al Arabi said:
The moment in which the eye moves is the same moment in which it connects to the object,in spite of the distance between the viewer and the object. The moment that the eyes open isthe moment in which they are connected to the heaven of the fixed stars. The moment whenits glance returns is the same moment that its perception is absent. [Fusus al Hikam]
So what is the point of having eyes when we cannot see Allah? The reason Allah has givenus eyes is to observe the creation. The reason for having eyes is to see the beauty of Allah’screation. The reason for having eyes is to know Allah through His works. The form ofcommunication in this world is by speech and vision. The form of communication in the nextworld is also by speech and vision. Hence when we dream we see things and hear words.Yet the physical eyes do not see nor do the physical ears hear. So how is it possible to seeand hear while dreaming?Allah breathed into Prophet Adam His spirit. The spirit therefore has the capacity to seewithout physical eyes and it has the capacity to hear without physical ears. Whatever is seenin a dream needs interpretation. It is not WYSIWYG. What You See Is not What You Get! Forexample, the dream of the king of Egypt and Prophet Yusuf’s interpretation:
43 And the king said: Surely I see seven fat cows which seven lean ones devoured; andseven green ears (of corn) and (seven) others dry: You chiefs! Explain to me my dream, ifyou can interpret the dream.…47 (Yusuf) He said: You shall sow for seven years continuously, then what you reap leave itin its ear except a little of which you eat.48 Then there shall come after that seven years of hardship which shall eat away all that youhave beforehand laid up in store for them, except a little of what you shall have preserved.49 Then there will come after that a year in which people shall have rain and in which theyshall press (grapes). [Quraan: Yusuf, Chapter 12]
Hence, never judge a book by its cover! People have preconceived fixed images of whatlooks nice and what does not. For example when people speak of a Shaykh, the listener whohas never seen the person, automatically conjures up an image of an old man with a beard,a turban and a robe. Even the Sikhs can meet that criteria in appearance! The moral here isthat Allah has given us eyes to see, so we must use them carefully, and not judge a personjust by looks. We should really ‘look’. Sometimes the greatest Shaykhs disguise themselves,so that their spirituality cannot be recognised by the common people.And finally let us look at one more example from the Quraan:
19 Have they not seen the birds above them spreading out their wings and closing them?None can uphold them except the Compassionate. He is Seer of all things. [Quraan: Al Mulk, Chapter 67]
At first glance the above verse is fairly straightforward it is WYSIWYG. What you see is whatyou get! But when we really ‘see’, the question comes to mind: What have birds spreadingwings got to do with Allah the Seer? The answer is, that it is an analogy. Birds spreading outtheir wings and closing them is the similarity of the eyes that Allah has given us. The eyelids
219 27 – AL BASEER
spread out and the eyes see. When the eyelids close the eyes stop seeing. None can upholdthem except the Compassionate. He is Seer of all things. When we see through ourselves,we misinterpret. When we see ‘through Allah’ we really see. When our eyes are open,whatever we see we connect with that. When our eyes are closed, whatever place or personwe think of, we connect with that. That is what Imaam Ibn Al Arabi meant in that quotefrom Fusus al Hikam.Allah is Al Baseer the Seer. Allah can see all the secrets that we hide in our Sadr
chest, because Allah has knowledge of everything in the heavens and earth. That is whyAllah is Rabb Lord of all the worlds. May Allah give us insight to know Him better throughHis works. Aameen.
MEDITATIONThe person who reads Ya Baseeru 1111 times everyday, will receive enlightenment throughthe eyes and .
220 26 – AS SAMEE, Chapter 42]
Allah hears the prayers of everyone that calls His Name. Just imagine how many creaturesthere are out there. They all call upon Allah and Allah hears each and everyone and Heanswers them all. Allah also gave us a pair of ears. Yet, there is no comparison betweenAllah’s hearing and our hearing, since there is nothing like Him. And in whatever you differ,the decision in there belongs to Allah. How do people differ? The differences arise becauseof what people see or hear. Allah created our eyes as a pair and also our ears as a pair. Yetwe cannot differentiate between what one eye sees from the other and we cannotdifferentiate what one ear hears from the other. So how can two people understand to thesame level? Hence differences arise according to the understanding of people. Thereforebelief in Allah is based on what we hear and understand, since we cannot see Allah.Just as in the above example, heaven and earth have been created as pairs, so has Allahcreated our eyes and ears as pairs. Then sight and hearing can also be considered asanother pair just like heaven and earth.Allah’s hearing is such that it hears even an ant. This is stated in the Quraan and Allah alsotaught Hadhrat Sulaiman their speech.
221 26 – AS SAMEE
18 Until when they came to the valley of the ants, an ant said: You ants! Enter your houses,so that Sulaiman and his hosts do not crush you while they do not know. [Quraan: An Naml, Chapter 27]
In the case of Hadhrat Muhammad , Allah gave His Beloved the capability of hearingeven stones and trees, since he heard their greetings to him.
There is Samea to hear, and there is Ism which is name. In Ism there is
an Alif at the start and in Samea there is an Ayn at the end. Everything has a name.Each one of us recognises our own name when we hear it. Allah taught Hadhrat Adam allthe names! We learn names of things from our parents as we grow up. That is all through thefaculty of hearing. When someone mentions the name of a thing, the brain immediately putstogether a picture. Initially when we were learning, the object or the image of an object wasplaced before our eyes so that we could associate the name with that object. However, thereis nothing like Allah. So we are taught that Allah is the One who hears our prayers. So wecall Him with His Asma (Names) and the prayer rises towards the heaven from earth. Allahhears our prayer. Allah hears His Names, and mercy descends from heaven towards theearth, since Allah is the Creator of heavens and earth. Even in the word Samaa(un) heaven,
60 And your Rabb (Lord) says: "Call on Me, I will answer you. But those who are too arrogantto serve Me will surely find themselves humiliated in Hell!" [Quraan: Al Mu_min (or Al Ghaafir), Chapter 40]
Allah, our Rabb says: “Call on Me, I will answer you!” That is, call on Allah while we are onearth. To speak, we need a physical body. Therefore, we must call on our Rabb, now!Tomorrow may be too late. Once the spirit departs from the body, the earth of our bodycannot make any sound. It becomes silent. There will be no prayer rising towards the heavenfrom the silent earth. There will be no mention of Allah’s Asma from the silent earth.And finally one more example from the Quraan:
64 And we have revealed the Book to you so that you may explain clearly to them the thingsin which they differ, and a guidance and a mercy for a people who believe.
222 26 – AS SAMEE
65 Allah sends down water from the skies and gives life to the earth with it after its death!Truly in this is a sign for those who hear. [Quraan: An Nahl, Chapter 16]
The Book too has been sent down from heaven to earth, to explain things, which is aguidance and mercy for the believers. Allah sends water from the sky to revive the earth. Sowe must perform Wudu to revive our bodies. Even the deceased is washed to revive thebody ready for the questioning in the grave. In that is a sign for those who hear! May Allahexplain the signs so that we may hear.Allah is As Samee the Hearer, or the One who hears our prayers. Allah sends down
Maa water which revives the earth after its death! Water is symbolic of knowledge .
Knowledge is ilm and Allah is Aleem Knower, Wallahu Sameeun Aleem - and Allah isHearer, Knower. Allah hears our call to Him and He answers our prayers.
The person who reads Ya Sameeu 1111 times everyday, will have the prayer heard andfulfilled .
223 25 – AL MUZILL
26 Say: "Allahumma! Owner of Sovereignty! You give sovereignty to whom You please, andYou withdraw sovereignty from whom You please. You honour whom You please and Youdishonour whom You please. In Your hand is the goodness. You are Able to do all things. [Quraan: Al Imraan, Chapter 3]
There is honour and there is dishonour. Everyone would like to be honoured. Nobody wantsto be dishonoured or disgraced. In dishonour, people feel humiliated. However, when aperson is digraced by one, it does not follow that others will cut off all ties with that person.For example, although Allah has disgraced Shaytaan, there are those that follow and obeyShaytaan. In the long run, the followers of Shaytaan will also be disgraced and Shaytaan willclear himself of their actions on the day of Judgment. Allah has disgraced Shaytaan, andAllah has also warned mankind not to follow him. Allah has warned mankind not to obeyShaytaan. The consequence of following or obeying Shaytaan is the fire of hell. Theconsequence of following or obeying Shaytaan is disgrace and dishonour from Allah. Okay!What is the point of creating Shaytaan in the first place? Did Allah not know that Shaytaanwould become disgraced and also lead others to disgrace?Of course Allah knew that Shaytaan would become disgraced! Hence the whole point ofcreating him in the first place was to test him. Then it would follow to disgrace Shaytaanwhen he refused to obey Allah. In this way the Sifaat, the Attribute, Al Muzill took form, andShaytaan became dishonoured. Otherwise everyone of mankind would be on the straightpath. Then there would be no point in guidance, or heaven and hell. There would be nothingto judge, or to reward. Shaytaan was created to separate the bad from the good. The entirecreation is based on opposites. Hence Allah’s Attributes of Al Muizz - the Honourer and AlMuzill - the Dishonourer are opposites. Al Awwal - the First and Al Akhir - the Last are alsoopposites. So are Az Zaahir - the Manifest and Al Baatin - the Hidden. Likewise, Allah has
224 25 – AL MUZILL
created the forces between the sun and the planets as equal and opposite, to keep theplanets in their orbits. Hence, Allah created Shaytaan with full knowledge and purpose toserve Him. Therefore although Shaytaan believes in Allah and nothing else, he is disgraced.Since Allah tells the believers to say:I have believed in Allah, and His angels, and His Books, and His Messengers, and the LastDay and the decree of its good and evil from Allah-ta_ala, and in the rising after death.Shaytaan only believes in the above Kalimaat as far as I have believed in Allah, and nofurther, so Allah has disgraced him. What is wrong with just believing in Allah and nothingelse? Why is that disgraceful?A person who believes in Allah and does not believe in His angels, and His Books, and HisMessengers, and the Last Day and the decree of its good and evil from Allah-ta_ala, and inthe rising after death, goes astray. To receive guidance and then to know Allah, can only beachieved by believing in the entire Kalimaat. Since the guidance was sent to Messengersin the form of Books by Allah. Allah revealed the writing of His Books to the Messengersas words repeated by the angels, under the command of Allah.Therefore in order to believe in Allah and to know Him, we also have to believe in all ofAllah’s Messengers . The Messengers have left us Books, which are the words of Allah,so we also have to believe in all of Allah’s Books. The angels repeated the words from HisBooks to the Messengers , so we also have to believe in His angels. Therefore, there is achain of truthfulness that we have to believe in, in order to believe in Allah and to know Allah,who is the ultimate Truth.There will be the rising after death for the Judgment. If the good deeds outweigh the baddeeds, then there is hope. If the bad deeds outweigh any good deeds, then the disgrace thatwill follow will be eternal, or alternatively until such a time that Allah wishes, when the personwho has paid the price for the bad deeds, is released from hell. So we also have to believe inthe Last Day and the rising after death.Shaytaan also believes in Allah, but he does not know Allah, because he refuses to believein the rest of the above Kalimaat. Hence Allah, Al Muzill the Dishonourer, has dishonouredShaytaan.Allah is Al Muzill the Dishonourer. Allah will disgrace all those who refused to believe in
Zaalik al Kitaab that Book, La Raiyba Fee in which there is no doubt, guidance to thosewho ward off (evil). Since the Quraan is Umm al Kitaab, it contains all the revealed Booksfrom Allah. May Allah have mercy on us all and save us from disgrace on the Last Day.Aameen.
225 25 – AL MUZILL
MEDITATIONThe person who reads Ya Muzillu 75 times will be protected from oppressors and enviouspeople, .
226 24 – AL MUIZZ
11…There is nothing like Him and He is the Hearer and the Seer [Quraan: Ash Shuraa, Chapter 42].
Since there is nothing like Him it follows that we cannot know Allah by His Essence. There isnothing like His likeness. On the other hand, Allah tells us that He is the Hearer and theSeer, we can know Allah by His Attributes, since we have been blessed by Allah who gaveus the likeness of some of these Attributes, however, our attributes of hearing and seeing areinsignificant compared to Allah’s Attributes.Honour and respect has to be earned. We must strive to earn or to achieve honour by gooddeeds and kind words. To achieve honour from Allah is to do good deeds for His sake so thatwe can achieve ‘closeness’ to Allah. To achieve ‘closeness’ to Allah is through the teachingsand example of His Rasool, Muhammad .
227 24 – AL MUIZZ
157 Those who follow the messenger, the Nabee (Prophet) who is unlettered, whom they willfind described in the Torah and the Gospel with them. He will enjoin on them that which isright and forbid them that which is wrong. He will make lawful for them all good things andprohibit for them only the foul; and he will relieve them of their burden and the fetters thatthey used to wear. Then those who believe in him, and honour him and help him, and followthe light which is sent down with him, they are the successful. [Quraan: Al Araaf, Chapter 7]
Allah is Al Muizz the Honourer. Allah has sent clear, manifest, visual guidance in theform of the Quraan and in the form of Muhammad who is Zaeem Al Anbiyaa,the Chief of the Messengers. As a mark of honour, Allah is called Zakee and He alsonamed His Beloved with the name Zakee - Sinless and Pure.
228 24 – AL MUIZZ
Za 7 TOTAL 117 TOTAL
The person who reads Ya Muizzu 40 times after Maghrib prayer, on Mondays or Fridays,Allah will honour that person amongst others, Inshaa Allah. The person who reads 1111times everyday, will overcome his / her enemies, .
229 23 – AR RAAFEE
14 Call upon Allah with sincere devotion to Him even though the unbelievers may detest it.15 Exalter of ranks the Possessor of the Throne. He casts the spirit of His command to anyof His servants He pleases so that He may warn of the Day of Meeting. [Quraan: Al Mu_min (or Al Ghaafir), Chapter 40]
Allah is the Exalter of ranks the Possessor of the Throne. There is Ar Raafaa the
Exalter and there is the Al Aarif the Knowing, the Acquainted. Know that thedifference between the Raafaa and Aarif is just the re-arrangement of letters. To be exalted,one must be knowledgeable. Nobody chooses the village idiot to be exalted! If we humanswould choose a worthy person for exaltation, Allah in His wisdom also chose worthy peoplewith upright characters for exaltation. Allah chose the Messengers because of theirexalted characters for His Message to be proclaimed through them.He casts the spirit of His command to any of His servants He pleases so that He may warn ofthe Day of Meeting.Likewise, Allah chooses an Aarif, a knower to warn the people of the Day of Meeting. Just asit is stated in the Quraan:
20 And there came running from the furthest part of the city a man saying: “My people!Follow those who have been sent!”21 “Obey those who ask no reward of you and who have themselves received guidance.”22 “It would not be reasonable of me if I did not serve Him who created me and to whom youshall be brought back.” [Quraan: Ya Seen, Chapter 36]
230 23 – AR RAAFEE
Who was that man? He was an Aarif. Just as when Prophet Muhammad received hisfirst revelation and he told his first wife, Hadhrat Khadijah about it. Her uncle who was anAarif, a knowledgeable person, confirmed that Muhammad was none other than the finalMessenger that the world had been waiting for. Allah has exalted Prophet Muhammad tothe position of Maqaam-e-Mahmood, where all of Allah’s Messengers will back away forsome reason or other when it comes to asking Allah for forgiveness for the people on theDay of Meeting, Muhammad will bow down to Allah and Allah will ask him to raise hishead and ask. Allah will listen to his praise and grant whatever Prophet Muhammadasks for his community.Coming back to Aarif… Allah the Exalter has also appointed people other than HisMessengers who are also exalted. Since there will be no more Messengers, these peopleconfirm the teachings of Muhammad, Rasool Allah , the Quraan. They call the people tothe teachings of Rasool Allah .
A man came to Muhammad Rasool Allah and said, "Ya Rasool Allah! Who is more entitled tobe treated with the best companionship by me?" The Prophet said, "Your mother." The mansaid. "Who is next?" The Prophet said, "Your mother." The man further said, "Who is next?"The Prophet said, "Your mother." The man asked for the fourth time, "Who is next?" TheProphet said, "Your father." [Sahih Al Bukhari]
For most of us, it all starts at home. Our parents, especially our mothers, start to teach ushow to start talking when we are young. They keep repeating to their child: La ilaha ill Allah.Hence the rank of the mother is exalted above that of the father as shown by the aboveHadees.Similarly, Allah has exalted the rank of husband above that of the wife in their partnershipwith each other. The rank of one’s mother is exalted by three times and the rank of the fatheris one time. If we look at the name Adam and the name Hawwa (Eve) we have:Adam = Alif + Dal + Meem = 1 + 4 + 40 = 45Hawwa (Eve) = Ha + Waw + Alif = 15The numerical value for Hawwa is one-third the numerical value of Adam.
270 Darajat or degrees respect. That is Ra (= 200) and Ayn (= 70). The father isworthy of 81 Darajat or degrees respect, Fa (= 80) and Alif (= 1) which equals 81degrees. Out of 360 degrees we have:360 – 351 (for Raafaa) = 9 degrees missing. What about the missing 9 degrees? That is the9 months that the mother carries the baby in her womb before she becomes a mother. Thatis, only a woman who gives birth to a child after 9 months pregnancy, is really a mother. A
mother exhibits more kindness, Urf , towards the child than the father. Apart from
231 23 – AR RAAFEE
Adam , every Messenger and every saint, every human being is born from a woman, amother. Hence, Allah exalted one’s mother by three times more than one’s father.Therefore, we must love, respect, honour and exalt our mother, who carried us for ninemonths, gave birth to us, and then nurtured us and protected us only as a mother can. Ofcourse we must also love, respect, honour and exalt our father. This is so that we are notabased but exalted by Allah on the Day of Meeting as stated in the following reference fromthe Quraan:
You will find the Aarifs sitting at those doors of Allah’s mercy. Allah! Save us from beingabased when the event happens. Aameen.
The person who reads Ya Raafeeu 1111 times especially on the 14th night of every lunarmonth, Allah will make that person exalted amongst
232 22 – AL KHAAFIDH
We ended the section Ar Raafee, The Exalter, with this reference, now let us continue,because the opposite of exaltation is abasement.Al Khaafidh is the opposite of Ar Raafee. Abasing cannot mean anything unless we have theopposite which is the exaltation. As we have found in the previous sections, there areopposites in Allah’s Sifaat. Just as Allah the Exalter exalted Hadhrat Adam when Hecreated him, Allah, the Abaser also abased Shaytaan at the same time. Likewise when theevent occurs as in the above reference, Allah will exalt those who followed the correct path,and Allah will abase those who followed the wrong path. There is no denying that the eventwill occur. Neither is there any denying that the exaltation and abasement will occur. Asstated, exaltation will have no meaning unless there is abasement. As a crude example, wefind that most people want something better than others. Therefore when Allah shows usabasement and exaltation, only then can people realise that exaltation is better thanabasement.If everyone was exalted or everyone was abased, there is no comparison to draw upon.There is nothing to show preference for over the other. Just as there are degrees or Darajatin exaltation, likewise, there are degrees or Darajat in abasement. We find that exaltation isin accordance with one’s goodness. Therefore abasement is also relative to one’s baddeeds. We can see the examples in this world too, where the guilty are punished inaccordance with the crime committed. The exaltation in heaven is with respect to the gooddeeds we perform for the sake of Allah, and abasement in hell is with respect to the evil thatwe do for own selves. Hence Allah the Abaser is also Allah the Exalter. Allah has given usthe guidance to follow in order to attain exaltation. To reject the guidance will lead toabasement.
233 22 – AL KHAAFIDH
Unfortunately, we find the opposite of opposites in this world! We find that those who havemoney are exalted by the masses. An incidence comes to mind about the poor, well, onecertain person in particular.There was a Faqeer who was hungry. He went asking for food. Everyone “shooed” himaway, saying that he smelled, and to go away. In other words, the people abased him. Onebutcher felt sorry for him and threw a piece of meat at him saying: “Take this and go away.”He then started looking for someone to cook that piece of meat for him but the people treatedhim with the same contempt. Finally he got fed up and held the piece of meat towards thesun and said to the sun: “You’re Shams and so am I, cook this piece of meat for me.” Thesun came closer and cooked the meat for Shah Shams and in the process, it also“cooked” the people who abased him. Allah could not stand to see his creature whom He hadexalted, to be abased in such a manner.The moral of the story is that we should not judge people by their wealth or poverty orappearance. We do not have the eyes to “see” whom Allah has exalted and whom Allah hasabased. All is not lost though. We know for a fact that Allah, the Exalter, has exalted ProphetMuhammad so we must follow his teachings and his example. Allah, the Abaser, hasabased Shaytaan, therefore we must not follow his suggestions or whispering. We must takerefuge with Allah from Shaytaan. Whenever the whispering of Shaytaan comes to a person,the person should start repeating:
Do not take my word for it! Believe in Allah’s Kalaam and try it for yourself. Inshaa Allah, youwill find nothing works faster than the above formula from the Quraan, the Book of Allah,which will stop the whispering and suggestions of Shaytaan. The above Kalaam of Allah willsave one from being abased.
Allah is Al Khaafidh the Abaser, abasing some and exalting others. Allah is Ahad Onewithout partners. Therefore when Allah abases some, none can exalt. Those who are exaltedby Allah, for them Allah Al Fattah the Opener, opens the doors of His mercy. Thosewhom Allah abases they are stricken with grief when the inevitable event occurs. Allah!Save us from being abased on the eventful day. Aameen.
Alif 1 Fa 80 Dhwad 800 TOTAL 1481 TOTAL
234 22 – AL KHAAFIDH
MEDITATIONThe person who reads Ya Khaafidhu 1111 times everyday will overcome difficulties andrealise his / her ambitions, Inshaa Allah. The person who fasts for three days and on thefourth day, sits in one place and reads Al Khaafidhu 70 times, he / she will win over his / heren .
235 21 – AL BAASIT
245 Who is it that will lend to Allah a beautiful loan, so that He may give it increase manytimes? Allah constricts and expands and to Him you will return. [Quraan: Al Baqara, Chapter 2]
Allah does not need any loans! So why is Allah asking to be lent a loan? The loan in questionis actually to feed the poor in the Name of Allah. The loan in question is to help others in theName of Allah. The loan in question is teaching Islaam in the Name of Allah. Blessed arethose who give in the Name of Allah. They “lend a beautiful loan to Allah“ and Allah repaysthem handsomely. I would like to share an anecdote that my brother, Professor AshiqHussain Ghouri has told us many times.There was a man who decided to follow the spiritual path. He found a worthy Shaykh. Oneday the seeker asked the Shaykh, to ask Allah how long did he (the seeker) have before hisdecreed death. The Shaykh prayed to Allah and he was told that there were only four daysleft. So the seeker asked the Shaykh to ask Allah to provide him with his entire four daysprovision right that moment. Again the Shaykh prayed and Allah provided the remaining fourdays provision for the seeker right away. The seeker took the food, went away anddistributed all the food to the poor while he starved. The seeker returned and then he againasked the Shaykh to ask Allah how long did he have left to live. This time the answer came40 days. The seeker did the same again. He asked for his entire 40 days provision to beprovided there and then. Again he took it away and distributed it to the poor. Now he hadbeen told that he had 400 days left. He did the same again and again. That seeker lived tobe more than 111 years old before he finally passed away.The moral of the story is that life and death is in the hands of Allah. He can expand it or hecan contract it. Likewise, the number of our breaths and our provision are in the hand ofAllah. Also, if we “lend Allah a beautiful loan” we cannot lose! There is tenfold gain on thereturn. Most people do understand this and we do find that generally, human beings, of allreligions believe in giving to the poor. There are very few extreme cases where certain
236 21 – AL BAASIT
individuals are so tight that they would not give a penny without expecting something inreturn in this world. Allah! Save us from being such people. Aameen.Speaking of breaths, we find that our chest expands when we inhale. And the opposite isalso true that our chest contracts when we exhale. Since the breaths are under the commandof Allah, when the breaths have finished for an individual, there is no way that the chest willexpand to catch the incoming breath. So death, as Imaam Ibn Al Arabi has so beautifullystated in his writings, is that the incoming breath is not allowed to enter and the out goingbreath is not allowed to return, or words to that effect.Let us look at one more example from the Quraan:
52 Don't they know that Allah enlarges the provision or restricts it for any He pleases? Trulyin this are signs for people who believe!53 Say: “My servants who have transgressed against their souls! Despair not of the mercy ofAllah, who forgives all sins. He is the Forgiving the Merciful.” [Quraan: Az Zumar, Chapter 39]
Allah enlarges and constricts the provision of an individual. If Allah provided equally for oneand all, there would be no need to share our food with others and there would not be anypoor person to feed. That would ultimately lead to human beings behaving like animalswithout feelings of sympathy for other fellow human beings. We would not be able tounderstand the meaning of kindness or compassion or mercy.Coming back to the above reference, there is a clue as to how to ask Allah the Constrictor toexpand ones provision. The answer is to turn to Allah, and ask for His forgiveness andmercy. Inshaa Allah, Allah will expand ones provision. Which shows us that little story oranecdote that we started with in this section about the seeker is a true fact. The onlycondition is that we should not despair of the mercy of Allah. All too often people in difficulty,start to despair. With desperation they say things about Allah which makes them fall intodisbelief. At times of desperation, patience is a virtue. We started this book with Allah’sAttribute As Saboor, for which there was a reason. We should be patient in all kinds ofcircumstances. We must master patience so that we do not utter anything that is against thepurity of Allah.Whether, Allah enlarges or constricts our provision, we should learn to share it with others.There is forgiveness and mercy in sharing our provision. Likewise, sharing knowledge withothers is forgiveness and mercy, provided, and I emphasise, provided the knowledge is thetruth and beneficial to others. To spread false knowledge is like sharing poisoned food, itharms all those who take part. So there is a fine balance in sharing knowledge. There is alsothe requirement as Allah’s Rasool, Muhammad said: “Speak to the people according tothe level of their understanding.”Knowledge itself is like a provision or food for the spirit. The spirit cannot eat food. It needsknowledge as its sustenance. We find from the life of the Prophet Muhammad that hewas always pleased to see Hadhrat Jibraeel . Every time Jibraeel came to visit Allah’sRasool, Muhammad knew that Jibraeel had come to him, bringing him spiritualsustenance from Allah in the form of Ayat of the Quraan.
237 21 – AL BAASIT
Prophet Muhammad used to constrict his physical sustenance, that is, he used to fastmost of the days of his life, in order to expand his allotment of spiritual sustenance. Spiritualand physical sustenance go hand in hand. Expand one and constrict the other or vice versa.In the above reference we find: Say: “My servants who have transgressed against theirsouls!” That is keep the soul in check. Keep it partly physically hungry, so that it may be fedwith some spiritual knowledge. Truly in this are signs for people who believe!Allah Al Baasit the Expander, expands the physical and spiritual sustenance of any of
His servants as He pleases. Allah is the One who is As Samee the Hearer of prayers.Allah answers the prayer provided we keep calling His Name(s) with Tayyab pure heartsand minds.Allah! Expand our spiritual sustenance so that we may know you better. Aameen.
MEDITATIONThe person who reads Ya Baasitu 1111 times everyday, Allah will make that person selfsufficient, .
238 20 – AL QAABIDH
In the section on Al Baasit we came across the mention of loan to Allah. Let us look onemore time into this loan. The loan is that when we are comfortable, we should look after theless fortunate in the Name of Allah. That is a loan to Allah. Allah in His generosity returnsthat loan to us manifold. Similarly, if Allah brings upon us difficult times, the loan that we mayhave lent to Allah in the easier times is once again repaid by Allah. All we have to do is topray to Him who created us. Allah has taken the responsibility of looking after His creatures.Once again, all we need to do is to call upon Him and pray to Him. It is related:
When Allah intended to create Adam, He commanded Jibraeel “Get a handful of clay fromthe earth!” When Jibraeel reached for the clay, the earth forbid Jibraeel from taking any partof it. Jibraeel returned empty handed. Allah then sent Israfeel . He too came back emptyhanded. Then Allah sent Mikaeel . Same thing happened. Allah then sent Azraeel . Againthe earth refused Azraeel from taking any part of it. Azraeel strongly mentioned, “I have beensent by the One who has the grip on my life. I will not listen to you. I will obey the commandof Allah.” Azraeel took the clay from the earth to present it to Allah. Azraeel’s Zikr is AlQaabidh. Allah said, “You have brought it, from now on you will also be responsible forgrabbing the spirit from the body.” [Shams ul Maarif]
When the time of death comes on any of the children of Adam. It is with this Name of Allah,Al Qaabidh, that Azraeel takes the soul of a person and separates it from the clay. If we
239 20 – AL QAABIDH
analyse the above, the earth gives a loan to Allah when Allah intends to create a creature.Allah repays that loan to the earth at the time of death of that creature. It was mentioned inone of the earlier sections that our body is a loan from the earth. It is the foolish ones whoburn or cremate the bodies of their deceased relatives. Azraeel the angel that takes oursouls at the time of death is in the grip of Allah, and he has his grip on our soul. Overall Allahhas His grip on all His creatures. Azraeel is the servant of Allah, yet he has been assignedwith the duty of taking the souls. That is one aspect of the Name Al Qaabidh.Now we shall look at another aspect of the Name Al Qaabidh. Allah the Constrictor,constrains our provisions as He wills. Likewise, Allah has restricted our spirits so that theyare stopped from knowing the hidden. Allah has restricted our eyes from seeing the hidden.Allah has restricted our ears from listening to the hidden. Except of course, if we rememberAllah often, Allah opens the mysteries of the hidden. Do you know how? With the Name AlBaasit, the Expander! You want to know Allah? ‘Look’ for Him in His opposite Asma –Names. You will come to know Allah to some extent.However, whether Allah expands our provision or constricts it, we are in His grip. Whetherwe know Allah or not, we are still in His grip. So what is the point of knowing Allah? Theanswer is in the previous set of opposite Names of Allah, Ar Raafee - the Exalter and AlKhaafidh - the Abaser. If we know Allah, then Allah will exalt us, if we do not know Allah, thenAllah will abase us.We saw in the previous section that Allah expands or restricts our sustenance. In otherwords, Allah also expands or restricts our spiritual knowledge or spiritual sustenance. Wealso find that as a person gets older and infirm, the amount of sustenance taken by theperson decreases. Most old people tend to become forgetful. Allah makes them forget whatthey used to know. That is Allah constricts their physical sustenance as well as their spiritualsustenance.There is an important point to realise here. The food, or sustenance is taken into our physicalbodies by the mouth. The tongue tastes the food or sustenance. Spiritual knowledge is takenin by the spirit either through the ears when listening to someone, or through the eyes whenreading something, or it comes from Allah through our minds when we are all alone withAllah. Of course the blind people have made progress in this day and age where they usetheir fingertips to identify words when reading in Braille. However, when we impart thatknowledge to others we either use the same mouth and tongue to form the words so that itbecomes speech for others to hear. Or we write it down with our hands or fingers for othersto read. The same hand and fingers that we use to feed ourselves. And we use our eyes tosee what we are writing is correct.And finally let us look at one more example from the Quraan:
The opening and closing of the wings of the birds is like the opening and closing of our eyes.It is like the expansion and contraction of our lungs or chest. It is like the expansion andcontraction of sustenance. It is like the expansion and contraction of our knowledge. Whenwe forget something like an Ayat or Hadees we are supposed to say: “Allah made me forget.”It is wrong to say, “I have forgotten.”
The Prophet said, "Why does anyone of the people say, 'I have forgotten such-and-suchVerses (of the Quraan)?' He, in fact, is caused (by Allah) to forget." [Sahih Al Bukhari]
One day the Prophet said, "Whoever spreads his sheet till I finish this statement of mine andthen gathers it on his chest, will never forget anything of my statement." So, I spread mycovering sheet which was the only garment I had, till the Prophet finished his statement and
240 20 – AL QAABIDH
then I gathered it over my chest. By Him who had sent him with the truth, since then I did notforget even a single word of that statement of his, until this day of mine. By Allah, but for twoverses in Allah's Book, I would never have related any narration (from the Prophet). "Truly!Those who conceal the clear signs and the guidance which we have sent down...(up to) theMerciful." (2.159-160) – Abu Huraira. [Sahih Al Bukhari]
The knowledge or spiritual sustenance was poured from the blessed mouth of ProphetMuhammad onto the sheet spread out and it was sustenance for the spirit of HadhratAbu Hurarira .Allah is Al Qaabidh the Constrictor. Allah provides or restricts the provision of Hiscreation as He pleases. Just as the Earth has sacrificed its earth for Allah’s creationin the Name of Allah, we must also offer our sacrifice in the Name of Allah. Allah! Accept oursacrifices which are made in your Name, like you accepted the sacrifice from ProphetIbraheem and Prophet Ismaeel . And what a great sacrifice that was! Aameen.
MEDITATION
The person who reads Ya Qaabidhu 1111 times everyday for 40 days, will never be hungryor thirsty and any wounds or pain will be healed, .
241 19 – AL ALEEM
31 And He taught Adam all the names, then showed them to the angels, saying: “Inform Meof the names of these, if you are truthful.”32 They said: “Be glorified! We have no knowledge except that which You have taught us.You, only You, are the Knower, the Wise.”33 He said: “Adam! Inform them of their names.” And when he had informed them of theirnames, He said: “Did I not tell you that I know the secrets of the heavens and the earth? AndI know that which you disclose and which you hide.”34 And when We said to the angels: “Bow down to Adam”, they bowed down, except Iblees.He refused through pride, and so became a disbeliever. [Quraan: Al Baqara, Chapter 2]
In the above example, Allah taught Adam all the names. That is Allah taught Adam thenature of things. The angels do not have that knowledge. So the angels had to bow down toAdam in the basic sense, as well as to the superiority of Adam in the spiritual sense.Prophet Muhammad said: “Seek knowledge from the cradle to the grave.” Knowledge isour heritage from Allah. So we must seek it. Seeking knowledge leads us closer to Allah.Allah is the Knower, so we must know also. Of course our knowledge pales intoinsignificance. There is no comparison between Allah’s knowledge and our knowledge.Allah’s knowledge knows no bounds. Our knowledge is limited. Allah’s knowledge coverseverything within the heaven and earth and without. Allah the Knower knows what enters ourhearts and what intentions we have. Allah knows our secret thoughts.Let us ask the question: “What specific knowledge did Allah teach Adam ?”If I say that: “Allah taught Adam the letters!” I am sure there will be lots of people who willdisagree with that. Take any language and you will find that a child is first taught the letters ofthe alphabet of that language. Then the child is taught to join the letters and to make thenames of things. Even today we are quite happy to teach our children that ‘A’ is for Apple.Yet when we say that ‘Alif’ is for Allah, people ridicule the idea. How else would Adamknow the names if Allah had not taught him the letters of whatever language Adam wastaught to speak?
242 19 – AL ALEEM
Letters are the seeds. Words are the plants. Sentences are the gardens. To understand thesentences, we need to understand the words. To understand the words, we need tounderstand the letters. To Know is to appreciate the gardens, the plants and the seeds.But Hadhrat Muhammad is known as Nabiyy al Ummee, the Unlettered Prophet! So howdo we explain that? How could Hadhrat Adam have been taught the letters and HadhratMuhammad be known as the Unlettered Prophet?When Jibraeel came to Muhammad and said: “Read!” Hadhrat Muhammadreplied: “I cannot read!” This happened three times and each time Jibraeel pressedMuhammad , that is Jibraeel embraced Muhammad three times with such forcethat Muhammad could not bear the force with which he was embraced. In those threeembraces knowledge was transmitted from Allah Al Aleem, through Jibraeel toMuhammad .If we look at the first revelation received by Prophet Muhammad which is the first fiveverses of Chapter 96 Al Alaq in the Quraan, we find that these five verses are composed ofexactly 14 letters of the Arabic alphabet!
That is exactly half of the 28 Arabic letters are used in the above five verses of the firstrevelation. The other 14 letters were revealed over time. Please check this for yourself. Thatis how Allah Al Aleem, the Knower, teaches us so that we come to know when we start to dosome research.Looking at the content of the above verses, we see that they are about Allah, our Rabb,teaching man, what man did not know. Why did Allah teach man what man did not know?Allah, Al Aleem, from His ilm created the Aalam. That is, Allah, the Knower, from Hisknowledge created the worlds. Having created the worlds, Allah became the Rabb, Lord ofthose worlds. To create the worlds, Allah had to be the Knower. Being the Knower, Allah hasknowledge. Having the knowledge, Allah creates. How does Allah create? He says: “Kun!“(“Be!”) And the thing comes into existence. That is Allah pronounces words composed ofletters. For the thing to come into existence, it must first be in the form of knowledge. If thething is not in the knowledge of Allah, it cannot come into existence! But why did Allah teachman what man did not know?The Messenger of Allah said, quoting Allah, “I was a hidden treasure, therefore I loved tobe known.” Allah Al Aleem created the Aalameen, the worlds, for the human beings. Allahtaught humans which they did not know, so that Allah the Knower would be known.The one who knows Allah best, is our Master Sayyidina Muhammad . Muhammad isthe Unlettered Prophet in the sense that he did not have any human teacher, he learned fromAllah through Jibraeel initially. And on the night of the Miraaj, the Ascension, Muhammad
243 19 – AL ALEEM
learned directly from Allah where no angel could reach for fear of being annihilated.Allah put the knowledge in the heart of Muhammad directly from the First to the Last.And we also find that Prophet Muhammad has been bestowed with so many titles orattributes. And you know what! Those titles are made up of Arabic letters!The Unlettered Prophet, Nabiyy al Ummee has the most titles or attributes comparedwith any other of Allah’s Messengers or any other human being for that matter. Al HamduLillah, all praise is for Allah! And what do we do these days? We write our name and thenfollow it by letters like BSc or BA or MSc or MA or PhD or DPhil! From where did we learn todo that?Muhammad is the Unlettered Prophet with all the letters. From being an UnletteredProphet, Allah made Muhammad become a knower, Aleem. Allah gave us the Quraanthrough Jibraeel , through Muhammad so that we the community of Muhammadalso become knowers. Prophet Muhammad’s name is followed by all the letters ofArabic, not just from BSc or BA to DPhil! Muhammad’s name is followed with Alif to Ya! FromAhmad to Yateem! From Umee to Yaaseen! Just look at his titles, Asma-e-Muhammadand you will know what I mean! Those names are all his titles! They are his qualifications! Histitles, his qualifications, contain all the letters of the Arabic alphabet. Our universities,whether they are worldly or “Islaamic” can only teach us so much. Allah’s Universitygraduated Muhammad with all kinds of degrees in useful knowledge for this world andthe next. So Muhammad is honoured with all the letters after his blessed name. By theway, ‘unlettered’ can also mean that there is no letter left which has not been used todescribe the titles or qualifications or degrees of Prophet Muhammad !
4 Say: My Rabb (Lord) knows what is spoken in the heaven and the earth. He is the Hearer,the Knower. [Quraan: Al Anbiyaa, Chapter 21]
Allah in His generosity has given each one of us a knowledge which the angels do not have.After all we are the descendents of Adam . What knowledge is this that we have and theangels do not? The angels have only been given knowledge of two or three or four Names ofAllah. That is their Zikr. Adam and his descendants have been given knowledge of all the99 Names of Allah. Hence the superiority of knowledge taught to Adam over theknowledge taught to the angels, by Allah. Of course there is one Ism Azam – Greatest Nameof Allah, which again is received by certain people and not the angels.And finally to round off this section let us look at the last verse in the first reference:
34 And when We said to the angels: “Bow down to Adam”, they bowed down, except Iblees.He refused through pride, and so became a disbeliever. [Quraan: Al Baqara, Chapter 2]
If there is something about Islaam that we do not understand, there is no shame in asking.Do not let pride get in the way of attaining knowledge. Look what happened to Iblees orShaytaan! He had been praising Allah for 70,000 years or more so he thought his knowledgewas superior to Adam’s. The downfall of Iblees was his pride. His knowledge was defective.Iblees thought that fire was more powerful than clay or earth. Since he had been createdfrom fire and Adam had been created from clay. He thought that he was superior to Adam.Disbelief is a very fine line. Iblees knew Allah. Iblees had been worshipping Allah. So howcould he be a disbeliever? Is it not a requirement for belief to believe in only Allah? Not quite!
244 19 – AL ALEEM
The requirement for belief is to believe in Allah, His Books, His Angels and His Messengers . Belief is also a very fine line. We cannot disregard the Books or the Angels or theMessengers and just believe in Allah. If that was the case, then there was no point in theprevious Messengers informing their communities of the future coming of other Messengers.Likewise, it follows that Iblees would not have been cast into disbelief since he alreadybelieved in Allah.It was stated in the section on Al Hakeem: Knowledge and Wisdom go hand in hand just asignorance and foolishness go hand in hand. If you have knowledge, attain wisdom. There area lot of people in this day and age, who have “parrot fashion” knowledge but they lackwisdom. They lead the ignorant ones astray. That is exactly what Shaytaan does! Hence thesaying: “Knowledge (even a little bit of it) in the wrong hands is dangerous!”
114 Exalted is Allah, the King, the Real! And do not hasten with the Quraan before itsrevelation has been completed to you, but say: “Rabbi zidni ilma(n) (My Rabb (Lord)!Increase me in knowledge).” [Quraan: Ta Haa, Chapter 20]
Allah is Al Aleem the Knower. There is La Shay nothing which escapes Allah’s
Laam 30 Ya 10 Meem 40 TOTAL 150 TOTAL
245 19 – AL ALEEM
MEDITATIONThe person who reads Ya Aleemu 1111 times everyday, Allah will open the doors ofknowledge and understanding, after a long absence from writing, Allah has finallypermitted me to complete this section. I seek Allah’s assistance in helping me to write aboutthe rest of the Asma that are yet to follow in this book, Inshaa Allah.
Updated
246 18 – AL FATTAH]
That which Allah opens to mankind of mercy, none can withhold it. Allah has opened themercy to the believers in one form as the Quraan because the Quraan is a healing and amercy for the believers:
82 We sent down in the Quraan that which is a healing and a mercy to those who believe: tothe unjust it causes nothing but loss after loss. [Quraan: Bani Israeel, Chapter 17]
To open is to make accessible or available. Allah has made the Quraan accessible by anopening. Allah has appointed angel messengers with two, three or four wings. What doesthat mean?The wings are the Names of Allah. As long as we do Zikr Allah, the angels fly with thesewings, or these Names of Allah. That which Allah opens to mankind of mercy none can
247 18 – AL FATTAH
withhold it, and that which He withholds none can release thereafter. He is the Mighty, theWise.Allah opens to mankind of mercy none can withhold it. When we do Zikr Allah, none canwithhold the Zikr and Allah opens the doors of mercy. Likewise, when we withhold from doingZikr, Allah withholds the mercy and none can release it. The example is like that of a bird. Ifwe clip the wings of a bird, it cannot fly. Zikr is like a bird or a spirit that soars towardsheaven. If we withhold from doing Zikr, it is like caging or trapping the bird or the spirit andnot letting it fly.The Quraan has many layers of meanings. The meanings of the hidden layers of the Quraanare opened by the mercy of Allah. The surprising thing is that the Quraan is a manifest, openbook, yet we cannot see the hidden meanings unless Allah opens our hearts and minds to it.The Quraan starts with the Opening Chapter, Al Fatihah – the Opening! That is the mercy ofAllah. Everything is contained in the Quraan, yet we fail to see it. The Quraan is a healingand mercy for the believers.Since we mentioned Al Fatihah, the Opening chapter of the Quraan, let us examine thatchapter a bit more closely. We find that Al Fatihah contains seven verses. What we also findis that Al Fatihah contains all the letters of the Arabic except for seven letters. That is,Chapter 1, Al Fatihah has 7 verses. The 7 verses are written with 21 Arabic letters from atotal of 28 letters. In other words 7 letters out of the total 28 letters of Arabic are not used inthe composition of Al Fatihah. Please do not take my word for it, check this for yourself, thisis how Allah Al Fattah, the Opener, opens the door of knowledge, when we start to examine.Here is Surat Al Fatihah from the Quraan for you to check that only 21 letters of the Arabicare used and 7 letters are missing.
What is so special about Al Fatihah? Al Fatihah is special because it is the opening to therest of the Quraan. Al Fatihah is special because it is recited in every Salaah. Al Fatihah isspecial because in every cycle or Rakaat of Salaah, Al Fatihah must be recited. Otherwisethe Salaah is not accepted. Here are two quotations attributed to Hadhrat Abu Huraira :
248 18 – AL FATTAH
The Quraan is recited in every prayer and in those prayers in which Allah's Rasool recitedaloud for us, we recite aloud in the same prayers for you; and the prayers in which theProphet recited quietly, we recite quietly. If you only recite ‘Al-Fatihah’ it is sufficient but if yourecite something else in addition, it is better.Allah’s Rasool said, "Angels keep on descending from and ascending to the Heaven in turn,some at night and some by day, and all of them assemble together at the time of the Fajr andAsr prayers. Then those who have stayed with you overnight ascend to Allah who asks them,and He knows the answer better than they, "How have you left My servants?" They reply,"We have left them praying as we found them praying." If anyone of you says "Aameen"(during the prayer at the end of the recitation of Surat al Fatihah), and the angels in Heavensay the same, and the two sayings coincide, all his past sins will be forgiven." [Sahih Al Bukhari]
Now do you see the connection between the above Ahadees and the opening reference(pardon the pun) that we started with? Here is the opening reference again:]
This reference starts with the words Al Hamdu Lillah… Al Fatihah also starts with Al HamduLillah…Then we have angels with two, three or four wings. How many Rakaat are there in anyprayer? There are either two, or three or four Rakaat in a prayer and no more. The angelssay Aameen at the end of each recitation of Al Fatihah. So Surat Al Fatihah is recited twotimes in two Rakaat prayer, it is recited three times in three Rakaat prayer and four time in afour Rakaat prayer. The angels with the appropriate number of wings are appointed for thesame number of Rakaat.When we pray, Allah opens the door of mercy on the ones who are praying. The angels withtwo or three or four wings reply to Allah’s question: "We have left them praying as we foundthem praying."By the way, there is at least one verse in the Quraan that contains all the seven letters withinit, which are missing in Al Fatihah!Allah is Al Fattah the Opener, who opens the doors of mercy when we start the Tilawat recitation of Surat al Fatihah and we call on Allah testifying His Oneness saying: Weworship only You and we ask only You for help, after first saying His Hamd praise. AlHamdu Lillahi Rabbil Alameen, All praise is for Allah the Rabb of the worlds.
249 18 – AL FATTAH
MEDITATIONThe person who reads Ya Fattahu 70 times with his / her hands on their chest after Fajr –morning prayer, Allah will enlighten that persons heart with the light of belief, Inshaa Allah.The person who reads Ya Fattahu 1111 times every day, Allah will enlighten that personspirit .
250 17 – AR RAZZAAQ
10 And when the prayer is finished then disperse in the land and seek Allah's bounty, andremember Allah often, that you may be successful.11 But when they spot some merchandise or amusement they break away to it and leaveyou standing. Say: "That which Allah has is better than pastime or merchandise, and Allah isthe best Provider. [Quraan: Al Jumaa, Chapter 62]
Speak of provisions and the first thought that comes to mind for the majority of the people isfood! However, there are many kinds of provisions and food is only a small part of it.Somebody said: “There are people who live to eat and there are people who eat to live.”There is food for the physical body and there is food for the spiritual ‘body’. The physicalbody needs to consume food provided by Allah from the earth. The spirit needs foodprovided by Allah from the heavens. The heavenly food is Zikr Allah and reflection on themysteries of life. Why are we here? What is the purpose of life? That is the ‘hunger’ of thespirit. The answers to these questions are the provisions which Allah provides through theQuraan and the Sunnat of the Prophet Muhammad which the spirit digests and thehunger is abated for a while. The spirit feels hungry again for either Zikr Allah or an answerto a spiritual question. Until the next time that a question arises in the mind.Coming back to the above example from the Quraan, we are told to pray first and thendisperse. Satisfy the spirit first then the body. If we satisfy the body first, the spirit will beneglected because the body will want to rest having no hunger pangs. Again an examplecomes to mind, where we have a horse and a rider. If we look after the horse and ignore the
251 17 – AR RAZZAAQ
rider, that would be wrong because the rider is more important than the horse. If the horse isfed and the rider ignored, there will come a time when the rider will fade away with weaknessand the horse will retain its strength. Then the horse will wander wherever it wants and therider will be ‘following’ the horse instead of commanding it or having its reins in his hands.Remember Allah much, so that you may be successful.But when they see some merchandise or pastime they break away to it and leave youstanding. This is the case where the body or Nafs has control over the spirit. As in ourexample, the horse is just carrying the rider wherever it wants to go. The rider has no controlover the horse’s movements.Say: “That which Allah has is better than the pastime or merchandise, and Allah is the best ofproviders”. That is, take control of the body and do not let it wander aimlessly when it is timefor prayer. Likewise, when we are praying the mind should be focused on Allah and weshould not let it wander aimlessly, we should not be thinking about the day’s events or thebargain we are going to pick up later, etc. Since the verse is in the chapter Al Jumaa, theGathering, we must gather our thoughts and direct them towards Allah. That which Allah hasis better than the pastime or merchandise.Allah is the best of providers. How many people believe that? During the invasion of Iraq inthe year 1424 AH (2003), there was an Iraqi shown on the television and his words were:“Welcome British! Welcome American! Where is the food? Where is the water?”I know it is not easy being under attack by bombs falling from the sky and bullets flying onthe earth, and being trapped. If we were in the same situation, like that Iraqi person, we toomight fall into this error unless Allah guides us. Another resident of Iraq, who lived inBaghdad, had the following to say:Do not worry about your provisions. The provisions are working harder to reach you than youseeking them. If you have received your food for today, then do not be concerned abouttomorrow. As yesterday passed without your knowing whether tomorrow will come.Concentrate only on your needs for today.Well if that is the case, that the provisions are working harder to reach us, then why botherasking Allah? (This is our question not of this person who lived in Baghdad). He answers:Allah has commanded us to ask from Him and He has urged us to that end. He says: “Callon Me, I will accept your prayers.” [Quraan: 40:60] and He says: ”Ask Allah for His favour.”[Quraan:4:32]And the Holy Prophet says: “Ask from Allah while you are fully confident of theacceptance of your prayer.” And he says: “Pray to Allah with the palms of your hands.”I think you may have realised that this resident of Baghdad is the light of Baghdad, the well-known Shaykh Muhyuddeen Abdul Qadir al Jilani .The first quote is from Al Fathu Rabbani and the second quote is from Futuh al Ghayb. Bothof these books contain the sermons, discourses of the enlightened Shaykh Abdul Qadir alJilani .Prophet Muhammad said: “Pray to Allah with the palms of your hands.” What is thesignificance of “praying with palms of the hands?” The palms of the hands are used forreceiving. The human beings use their hands to feed themselves. The human beings usetheir hands to clean themselves. The human beings use their hands to cover themselves.The human beings use their hands in earning their living. So pray with the palms of yourhands. So that Allah may provide for our efforts.
252 17 – AR RAZZAAQ
In the previous reference we were told to Remember Allah much. Now we are being told tofear Allah and to put our trust in Allah. To place our trust in Allah is emphasised by ProphetMuhammad : “Ask from Allah while you are fully confident of the acceptance of yourprayer.” And he says: “Pray to Allah with the palms of your hands.” The palms of thehands are for praying. The palms of the hands are for working. The palms of the hands arenot for begging from others. And finally the palms of the hands are definitely not for stealing.As my brother Professor Ashiq Hussain Ghouri has pointed out on numerous occasions: “Afarmer plants the seeds in the field with complete trust that it will germinate and the crop willgrow.” Otherwise, why would he plant the seeds? That is how our trust in Allah should be.We should pray with the complete confidence that the prayer will be accepted, which is like aseed being planted and that seed turns into a crop. Again the prayer and planting the seed iswith the palms of the hands.Allah is Ar Razzaaq the Provider, the same Provider who provided the Zam-Zam waterin an inhospitable place. And that place is now visited by millions of Muslims and they stilldrink from that water which was rediscovered just before the arrival of Muhammad intothis world. That provision from Allah has been flowing for more than 1400 years and it isstill flowing today. Allah is Al Qaadir the Able, and Allah is able to provide a measure forall things.
MEDITATIONThe person who reads Ya Razzaaqu 1111 times everyday, Allah will provide sustenance forthat person, and remove all kinds of illnesses, Inshaa Allah.The person who recites 11 times after every prayer, the verses as shown in the lastreference from the Quraan (Chapter 65) Allah will provide sustenance for that person, InshaaAllah:
253 17 – AR RAZZAAQ
Wa manyat taq illaha yaj al lahu makhrajan wa yarzuq hu min haisu la yahtasib(u) wa manyatawakkal ala allahu fa huwa hasbuhu inn allaha balighu amrih(i) qad ja ala allahu likulli shaiyin qadra .
254 16 – AL WAHHAAB
34 And We did try Sulaiman (Solomon). We placed on his chair a body. Then he did repent.35 He said: “My Rabb (Lord)! Forgive me and grant me a kingdom such shall not belong toany after me. You are the Bestower.” [Quraan: Saad, Chapter 38]
Allah tried Prophet Sulaiman . In fact, Allah tried every one of His Messengers . Similarly,every Muslim is tried, is being tried or will be tried by Allah. As Allah says clearly in theQuraan:1 Blessed is He in whose hand is the Sovereignty, and He is Able to do all things.2 He who has created death and life so that He may try you, which of you is best in conduct;and He is the Mighty, Forgiving. [Quraan: Al Mulk, Chapter 67]
Whenever Allah tries the people, there is always someone who will say: “Why me!” If Allahtried those that were near and dear to Him, namely the Messengers , then we are nothing.If they, the Messengers were patient in adversity, then we must learn from them and we tooshould learn patience and practice it. Allah the Bestower, bestows the reward that follows,without any strings. But why does Allah try those who are near and dear to Him in the firstplace? Why can Allah not just bestow the rewards?The human being is a weak creature in the physical sense. At the same time the human soulor Nafs or animal self is strong and the human spirit or Ruh is weak. In order to strengthenthe spirit, the soul has to take a battering. If the soul is not checked, it overpowers the spirit.If the soul takes a battering, the spirit grows stronger and makes the soul, the animal self,subservient. When the soul becomes obedient to the spirit, the soul attains complete rest andit becomes Nafs ul Mutmainna, Hence Allah tries those who are near and dear to Him tomake their spirits stronger and their souls restful.
255 16 – AL WAHHAAB
The similarity is like that of iron. Iron by itself is strong but it rusts. To make the iron strongerand to remove the rust from it, it is put into fire and turned into steel which does not rust.Once the soul becomes obedient, it is always kept in check.In the first reference above from the Quraan, the trial of Prophet Sulaiman was: “Weplaced on his chair a body.” What happened was that Hadhrat Sulaiman was removedfrom his kingdom and it was taken over by another.His trial was poverty from riches. The trial of Prophet Ibraheem was the sacrifice of his sonProphet Ismaeel . The trial of Prophet Ayub was infection of his body. The trial ofProphet Yunus was imprisonment in the fish. These are just a few examples of the teststhat Allah placed on His Messengers . After having tried His Messengers or should wesay that after Allah ‘strengthened’ His Messengers , Allah bestowed His gifts on all of them.As we are told in the Quraan:
If we remember these two verses during any affliction, we will never say: “Why did Allah dothis to me?” Allah has given us the antidote for trials and affliction. Therefore we should keeprepeating the above two verses and Allah, Al Wahhaab, the Bestower, will remove thedifficulty and relieve us of our trials and burdens. So we come out of the trial with a strongercharacter, with our faith intact, instead of losing our faith by saying: “Why me?” And talking offaith, it leads us nicely to the next reference from the Quraan:
8 “Our Lord! Do not let our hearts deviate after You have guided us, and grant us mercy fromYour presence. You, only You are the Bestower”. [Quraan: Al Imraan, Chapter 3]
Having been guided by Allah, by having faith in him, if we are tried, we must ask Allah not tolet our hearts deviate. We must ask Allah to keep our faith intact. We must ask Allah to grantus mercy from His presence. Since Allah is the Bestower, Allah will bestow the mercy fromHis presence and keep us on a firm footing as far as our belief or faith is concerned. All ofAllah’s Messengers asked Allah for different gifts like a son or blessings for theirdescendants, or relief from an affliction. Our Master, Sayyidina Muhammad taught hiscommunity how to ask Allah for gifts: “Rabbana atina fid dunya hasanataw wal fil akhiratihasanataw waqina azaaban naar.” Our Rabb (Lord) give us good in this world and give usgood in the next world and save us from the torment of the fire.The above prayer is so complete that ‘nothing specific’ is asked for from Allah other than therefuge from the fire of hell, and yet it includes everything good in this world and the next.That is, the prayer includes health, wealth and happiness. Health, wealth and happiness arein the hands of Allah, and He is the one who can bestow those on His servants. There arecertain things that are given without asking for them specifically. There are certain things thatare given when asked for them specifically. With the above prayer all the things are asked forwithout asking for them specifically and yet they are being asked for specifically.Allah in His infinite wisdom gives His servants what is good for them in this world as well asthe next world. Allah! Accept the above prayer from us. Aameen.Allah is Al Wahhaab the Bestower who bestows numerous gifts on His creation. The giftscome from Hu Him through the different avenues that He chooses. The gifts that are
bestowed by Allah have their origin from Allah and their destination is His creation .
256 16 – AL WAHHAAB
Remember to read Darood / Salawaat of your choice at least 11 times per day and send theHadiya (reward) for the Darood / Salawaat to Allah’s Rasool, our Master, SayyidinaMuhammad .
257 15 – AL QAHHAAR
17 "If Allah touches you with affliction none can remove it but He, and if He touches you withgood fortune, He is Able to do all things.18 “He is the Subduer over His slaves, and He is the Wise, the Knower.” [Quraan: Al Anaam, Chapter 6]
In the section Al Wahhaab we came across the prayer that contains everything good for thisworld and the next. As it was mentioned, health, wealth and happiness are the requirementsfor a good life. The meanings of health and happiness can be applied fairly consistently overall the people. However, the reasons for happiness are many. Just as wealth means differentthings to different people. To the majority of the people, wealth means possessions like gold,silver, money, land, etc. To some people it means pious children, and or serving others. Thelatter are happy when they can help someone else just for the sake of Allah.Since health, wealth and happiness are in the hands of Allah, it is up to Allah to bestow themor to hold them back. When Allah the Subduer touches us with affliction, we becomesubdued, broken, crushed and overpowered. Allah is Able to do what He wills. When illnesscomes, it comes from Allah. None can remove it unless Allah wants to restore us to health.It is stated in Al Fathu Rabbani:The Prophet said: “Allah does not make His beloved suffer but He may make himexperience adversities.”The Shaykh said: “A true believer is convinced that Allah Almighty will not put him throughany adversity unless there are benefits to follow either in this world or the next. With suchfaith, he consents to any trial, practices patience, and has no hidden blame towards his Rabb(Lord). A state of absorption in his Rabb keeps him thinking about His glory and unconcernedabout adversities.” [Al Fathu Rabbani – Shaykh Abdul Qadir al Jilani]
258 15 – AL QAHHAAR
The Shaykh is reminding us that with every difficulty there is relief as stated in the Quraan.That every difficulty, trial, affliction is for a reason and there are rewards to follow. Thereforewe must consent to trial with total faith in Allah that it is or it was for our own benefit. The endresult is that patience is a noble quality. Patience is achieved by subduing the Nafs Thetongue is subdued in Zikr, remembering Allah. The mind is subdued with absorption in ourRabb. The limbs are subdued in prayer. The hunger is subdued by fasting.When Allah the Subduer subdues us with affliction we have to subdue ourselves so that wedo not say anything that would be detrimental to our own selves. This does not mean we puton a miserable face and keep quiet. It means we must put on the same face and smile as wewould in times of ease.Referring again to the Quraan we find the following verses:
48 On the day when the earth will be changed to other than the earth, and the heavens (alsowill be changed) and they will come forth before Allah, the One, the Subduer.49 You will see the guilty on that day bound together in chains.50 Their garments of pitch black and their faces covered with fire. [Quraan: Ibraheem, Chapter 14]
On the Judgment Day, Allah the Subduer will subdue the guilty. Allah will chain and bindthem and their faces will be covered with fire. There is a lesson here for us. If Allah tries usand we walk around subdued with a miserable face, then what is the difference between thatand example given to us by Allah? Looking miserable is like having a face covered with fire.Looking miserable because of an adversity from Allah, is like showing displeasure and blametowards Allah. As the Shaykh says, we should practice patience and have no hidden blametowards our Rabb. The only way to practice patience is to subdue the soul so that it does notbecome an accusing soul - Nafs Lawwamah. When Allah the Subduer sends an adversityour way, we are supposed to subdue the soul and not allow it to have its way of accusations.This way, we can wear the bright garment, a smile, which Allah would like us to wear to showour consent without blame, instead of the dark garments of pitch black, a miserable look,which the guilty will be made to wear on Judgment Day.Moving on to the next reference from the Quraan:
60 It is He who does take your souls by night and knows all that you have done by day. ThenHe raises you again to life therein, that the term appointed be filled. And in the end to Him isyour return. Then He will show you what you used to do.61 He is the Subduer over His worshippers and He sets guardians over you until when deathapproaches one of you Our angels take his soul and they never fail in their duty. [Quraan: Al Anaam, Chapter 6]
Since we mentioned the soul and how it has to be subdued in adversity, we are now told thatAllah takes our souls by night or when we sleep and knows all that we have done during theday or while awake. Allah knows which soul has been accusing and blaming his Rabb andwhich soul has been subdued with patience. Allah is the Subduer over His worshippers. Thatis worshippers are engaged in their worship where they have subdued their souls and theirlimbs. The soul is subdued by Zikr Allah from accusing and blaming its Rabb. The hands aresubdued from taking anything unlawful. The tongue is subdued by Zikr Allah from uttering
259 15 – AL QAHHAAR
unlawful words. The eyes are subdued by focusing on the ground and not seeing anythingblameworthy. The mind is subdued by concentrating on the words of Zikr Allah. The ears aresubdued from listening to anything other than paying attention to the Zikr Allah. Therefore theworshippers are subdued from worldly participation while they are worshipping Allah.It is better that Allah subdues us in this world and not in the next world as the guilty ones willbe subdued by Allah. Ya Allah! Protect us from being subdued by You in the next world asthe guilty. Aameen.Notice that we keep coming across patience again and again. That is the first lesson welearnt from As Saboor the 99th Name of Allah where this book started. We must not forgetthat lesson, because it is the greatest lesson and the one that we need to keep practicingthroughout our earthly life. Patience is the foundation on which faith in Allah is built. Hencewe started this book from the 99th Name and we are working our way towards Allah.May Allah forgive our sins and keep us all on firm belief in Him. Aameen.Allah is Al Qahhaar the Subduer, who subdues His worshippers in order to test them andto strengthen them. He is Al Haadee the Guide who guides those who are near to Himeven closer and leads astray those who are further from Him. Instead of looking at thecauses we should look at the Causer and there is only One , He is Allah, Rabb Lord of allthe worlds.
The person who is overcome with the love and greed for this world and would like toovercome this, he / she should read Ya Qahhaaru 1111 times everyday. Inshaa Allah thelove and greed for this world will be overcome and the love for Allah will increase, .
260 14 – AL GHAFFAAR
5 He has created the heavens and the earth with truth. He makes night to succeed day, andHe makes day to succeed night, and He has subjected the sun and the moon to give service,each running on for an appointed term. Is He not the Mighty, the Forgiver? [Quraan: Az Zumar, Chapter 39]
The heavens and the earth are created with truth. That is they do not lie. Human beings lie.To lie is to be untruthful. Yet we are created from the same earth that Allah mentions in theQuraan as in the above verse. That earth is created with truth. When human beings tell lies,they are corrupting the earth. When the body is buried at death, or burnt for that matter, theearth of the body, or ashes, will be returned to the earth, which is created with truth. Theearth will overpower the earth of the body that used to lie. When we speak of ‘lies’, we arereferring to that word in the broadest sense. ‘Lies’ here encompasses all evils.The night and the day follow in succession. That is the night takes ‘life’ and it ends its life atthe arrival of the day. The day then takes ‘life’ and it ends its life at the arrival of the followingnight. The sun and moon are giving service for an appointed time. Many generations ofhuman beings have come and gone since the creation of Prophet Adam but the majority ofthe human beings have lived for a predefined time on this earth. They have outlived at leasta night and or a day. Yet the sun and the moon have outlived all those generations and theyare still obedient to Allah in their service, to this day. Even the earth has outlived all theprevious generations and it is still living. The appointed term of the sun, moon and the earthis not over yet. We come into existence for a short term. Our lifespan is nothing but a blink ofthe eye in comparison to the term appointed for the earth, sun and the moon. All the previousgenerations have all disappeared, having reached their appointed term.The lesson to be learned from the above reference from the Quraan is that we have outliveda number of nights and days. How short their term was. Similarly our lives are shortcompared to the life of the sun, moon and the earth. We must live our lives in truth and askforgiveness from Allah the Forgiver before it is too late. Yet when we take on our earthly life,
261 14 – AL GHAFFAAR
we become disobedient to the service of Allah while the sun, moon and the earth have beenobedient to the service of Allah. Even then, Allah loves His human creation more than Hiscreation of sun, moon, earth, and even the angels. Allah is Al Ghaffaar and ready to acceptour prayer and forgive us for our past errors provided we live a life of truth from then on.Allah has given us analogies so that we might reflect, repent and turn towards Allah and askHis forgiveness.
Allah's Messenger said, "When carried to his grave, a dead person is followed by three, twoof which return (after his burial) and one remains with him: his relative, his property, and hisdeeds follow him; relatives and his property go back while his deeds remain with him." [Sahih Al Bukhari]
The above Hadees is a testimony, that we have to live a truthful life because forgiveness willbe based on our deeds and not on our relatives, nor on our property. Allah is not going tolook at our relatives, or our properties. Allah will look at our deeds in order to forgive us.Hence Prophet Muhammad has taught us that every deed is based on intention. If theintention is good, the deed will be good and a means for Allah’s forgiveness. If the intentionis bad, the deed will be bad and a means for Allah’s punishment. As Prophet Nuh (Noah)said:
10 And I have said: ‘Seek pardon from your Rabb (Lord)! He is ever forgiving.’11 ‘He will open the sky for you with plenty of rain,’12 ‘And will help you with wealth and sons, and will assign to you gardens and will assign toyou rivers.’ [Quraan: Nuh, Chapter 71]
Just as it is mentioned in the Quraan, we must seek pardon from our Rabb. He is AlGhaffaar, the Forgiver and He will open the sky for us with plenty of rain. Whenever we thehumans seek inspiration, we look upwards towards the sky. We look up for inspiration. Weare looking up for “plenty of rain”. We are looking for an answer. Since Allah placed the brainat the top of the human being. That is where inspiration descends from above, not frombelow. Rain falling down is like inspiration descending in the mind. The rain sprouting thevegetation is like the inspiration or idea taking form.The wealth and the sons are goodness of this world. The wealth of the next world is the gooddeeds that we will take with us which will be a means for our forgiveness from Allah. Thesons of this world are to carry on the family name. The sons of the next world are the oneswho learn from a good teacher and emulate his character, so that they too can teach theproper way of Islaam and good manners to others.Gardens and rivers will be assigned for those who seek pardon from their Rabb, Allah theForgiver. We have been told in the Hadees that the property follows the deceased to thegrave, but it returns after burial. Therefore the gardens and rivers of this world will bereturned after burial. The gardens and rivers of the next world, will be assigned to those whoseek forgiveness of their Rabb in this world. Ya Allah! Accept our repentance and forgive usour visible and invisible sins which we have committed knowingly or unknowingly, You are AlGhaffaar, the Forgiver. Aameen.
Allah is Al Ghaffaar the Forgiver of sins, the Acceptor of Repentance. Allah Al Fattahthe Opener, always keeps the doors of His mercy open. Since He knows that we have no
262 14 – AL GHAFFAAR
other besides Allah who can forgive our sins. We must ask pardon of our Rabb so thatwe may be forgiven our sins.
Fa 80 Alif 1 Ra 200 TOTAL 1281 TOTAL
MEDITATIONThe person who reads Ya Ghaffaaru 1111 times everyday, Allah will forgive that person’spast sins, and make the person, refrain from future .
263 13 – AL MUSAWWIR
Nothing is hidden from Allah, whether it is on earth or in the heavens, or in the wombs. Toput it in simple terms, how can anything be hidden from Allah when He is the Creator ofeverything that is in the heavens and the earth! It is Allah that shaped us in the wombs. Wehave been fashioned by Him. Allah has given us a form so that we may experience Hiscreation and then return back to Him. The spirit is formless. The spirit has no form. The bodyis given a form and the spirit is ‘attached’ to it. The spirit forgets its reality and only startsthinking of the body.Allah knows what is in the earth and in the heavens and nothing is hidden from Him. Our ownspirit forgets its own reality and it cannot see beyond its ‘own nose’. Whereas we havealready been told Allah has taught Adam all the names.Allah shapes us in the wombs as He pleases. That is, Allah imagines our form, He paints ourform, He fashions our form and we come into existence. There is no god only He the Mightythe Wise. We can see the beauty of the painting all around us. The world is a painting. Allahhas painted the world with all kinds of colours. However, the world is constantly changing.Wherever we turn, we see the painting but we do not realise it. Any face we see, it has beengiven form by Allah. Every face has been formed and painted by Allah. Every tree has beengiven form and painted in different colours by Allah. The painting keeps changing everymoment.
22 And of His signs are the creation of the heavens and the earth, and the difference of yourlanguages and colours. Truly in that are signs for those who know. [Quraan: Ar Room, Chapter 30]
264 13 – AL MUSAWWIR
27 Have you not seen that Allah causes water to fall from the sky, and We produce therewithfruit of various colours; and among the hills are streaks white and red, of various shades ofcolour, and raven black.28 And of men and beasts and cattle, in like manner, various colours. The knowledgeableamong His servants fear Allah alone. Truly Allah is Mighty, Forgiving. [Quraan: Faatir, Chapter 35]
Allah not only formed the heavens and the earth and everything within, but He also made thecreation colourful. When we take a photograph we try and capture a moment which will notbe repeated, even though that moment is limited to the angle of camera view. We try andcapture the colours in the photograph. Whereas Allah’s ‘painting’ of heavens and earthcannot be captured in its entirety by any camera. Similarly, making a film of nature iscapturing a part of that great painting by Allah. Again only those moments and only thosecolours and only those parts of the great painting that have been captured can be replayed,and yet that does not play the whole picture. Or should that be, it does not paint the wholepicture!The water falling from the sky, the rain, in the above reference is colourless. The earth ismostly brown. Same water, same earth, yet the fruits are of various colours and so are theflowers. Same water, same earth, same fruits and vegetables, same green grass and yet thepeople who eat those fruits, vegetables and animals are of different colours. The beasts thateat different beasts are of different colour. The cattle that eat the green grass are of differentcolours.If we take this reasoning further, we find that each creature is different. No two creatures arealike. There may be similarities amongst people, amongst beasts and amongst cattle. But wecannot say that this one is that one. We can only say, this one is like that one. Even twins arenot truly identical. There is always something different about them. So Allah, Al Musawwirhas painted each one of us differently. Going back to the example of the twins, no matterhow similar they appear, it does not follow the good deeds of one will be mistakenly awardedto the other and vice versa. Just as each one of us is responsible for our actions, each one ofus has been formed by Allah individually. Therefore each one of us is responsible andanswerable for our own actions.
24 He is Allah, the Creator, the Shaper out of nothing, the Fashioner. His are the mostbeautiful Names. All that is in the heavens and the earth glorifies Him, and He is the Mighty,the Wise. [Quraan: Al Hashr, Chapter 59]
We have all heard the expression, “That person is two-faced!” We all have a physical faceand we all have a hidden face. That is we portray one image or personality in front of others,and we have another personality when alone. We cannot hide that from Allah. The idea is tomerge the two faces into one so that we behave the same whether we are with someone oralone. If we realise that even when we are alone we are not alone, Allah is always watchingus!Allah Al Musawwir the Fashioner has fashioned each one of us and then painted usin His wisdom. It is all out of love for His creatures and made Adam and his descendantsin the image of Rahman . From Allah’s imagination He formed us and then He saw Hiscreation, from Tasawwur to Masawwir to Baseer.
265 13 – AL MUSAWWIR
The person who reads Ya Musawwiru 1111 times everyday, will be able to understand thegreat painting of the heavens and earth, and merge the visible and invisible personalities intoone for the .
266 12 – AL BAAREE
54 And when Musa (Moses) said to his people: “My people! You have wronged yourselvesby choosing of the calf (for worship) so turn in repentance to your Maker, and kill (the guilty)yourselves. That will be best for you with your Maker.” Then He turned toward you. He is theAcceptor of repentance, the Merciful.55 And when you said: “Ya Musa! We will not believe in you till we see Allah plainly.” Andeven while you looked the lightning seized you. [Quraan: Al Baqara, Chapter 2]
Samiri melted the jewellery of Israelis. From the melted gold he made a calf. The Israelisstarted worshipping the calf. Rather than worshipping the Maker of all the heavens and earthand everything, the Israelis worshipped a golden calf made by a man, which could not benefitthem in fact it only worsened their state. Prophet Musa seeing this after coming down fromthe mountain ordered the Israelis to kill the guilty ones. That was the expiation of the sin ofworshipping an object, an idol, instead of worshipping their Maker.Shapes are made out of nothing. Allah, Al Baaree, the Maker of shapes made the heavensand earth out of nothing. Likewise Allah, the Maker made everything in the heavens andearth out of nothing. That is also the way Allah the Maker made Adam . Let us look at howthat is done.If Samiri could take little pieces of gold and add them all together to make a calf, then howcan it be difficult for Allah to add earth, water, air and fire and create a human being? Samiritook the gold from the Israelis to make the calf. Allah, who owns everything in the heavensand earth can take the elements to create what He wills. That was the case in the creation ofProphet Adam . At first Prophet Adam did not physically exist. Then Allah, Al Baaree,the Maker, made Hadhrat Adam out of not being into a physical being. Allah has made usout of nothing. However, each one of is physically based on the physical aspects of ourparents. At first we did not exist. Then Allah created us little by little. Allah gives us forms.Allah has made our shapes from different atoms and compounds all joined together. Ourphysical appearance is based on the likeness of our parents. In one sense we are like ourparents and in another “we think” we are different from our parents.What Allah Al Baaree does is gather the dots, the atoms and gives us shapes. Allah gives uslife. Samiri was unable to give life to the calf. He took the dust from the feet of the Messenger
267 12 – AL BAAREE
and he threw that dust in the gold and the calf made a sound. Samiri could shape the calf buthe did not have the power or ability to give life. Just like the idols are shaped but they arelifeless. Gold comes from earth, and earth is the important ingredient to make human beings.Samiri took the earth from the feet of the Messenger and he threw that dust in the gold.The punishment for the crime of making and worshipping the calf was to slay the guilty ones.Because the idol was made from gold which comes from earth, and handful of dust which isearth, the punishment for those who were guilty was to compensate the earth with their ownearthly bodies. They were not worthy of having a physical body. They had to destroy theirown forms. Their punishment was to go back into a void of nothingness from which they firstcame. Only this time it was accompanied by punishment.We too will be returning into not-physically-being and returning the earth to earth. We will allbe returning with compensation from Allah of reward or punishment depending on whetherAllah is pleased with us or displeased with us respectively. May Allah guide us and have pityon us and keep us on the Siraat al Mustaqeem. Aameen.
24 He is Allah, the Creator, the Maker out of nothing, the Fashioner. His are the mostbeautiful Names. All that is in the heavens and the earth glorifies Him, and He is the Mighty,the Wise. [Quraan: Al Hashr, Chapter 59]
Allah Al Baaree the Maker made us out of nothing and gave us forms. Allah based us allon the same design of Adam whom He made first. Then Allah asked all of us: “Am I not
your Rabb Lord?” We all agreed: “Yes!” Then Allah sent us to earth to gain knowledgeand return to Him as true believers in Him. May Allah take away our forms as true believersin Him. Aameen.
268 12 – AL BAAREE
MEDITATION
The person who reads Ya Baareeu 1111 times everyday, will forget the forms and ‘look’towards the Maker of the forms,
269 11 – AL KHAALIQ
59 The likeness of Isa (Jesus) with Allah is as the likeness of Adam. He created him fromdust, then He said to him: “Be!” And he is.60 The truth from your Rabb (Lord), so do not be of those who doubt. [Quraan: Al Imraan, Chapter 3]
Imaam Ibn Al Arabi has made a very interesting statement about Allah’s creation of thehuman beings. He has said that Allah has created the human beings in four different ways,namely: 1 The creation of Adam . 2 The creation of Hawwa (Eve) . 3 The creation of the rest of the human beings (which includes you and me). 4 The creation of Isa (Jesus) .
Allah created Adam , without a father or a mother. Allah created Adam with His own twohands. Allah created his body from dust or clay and then breathed into the body His ownbreath. Here we have the creation of the first human being. A creation which had nopredecessor, nothing to base the design on except the way Allah preferred him to take form.So Hadhrat Adam was created out of nothing. That was the first human creation.Then Allah took Adam’s rib and He fashioned it and created Hawwa . Allah createdHawwa from Adam . That was the second form of creation. The creation of a womanfrom a man.Then from Hadhrat Adam and Hadhrat Hawwa , Allah created the third creation. Allahcreates the third form of creation from a father and mother. The descendants of Adam andHawwa multiplied. That is where we all fit in.
270 11 – AL KHAALIQ
1 Mankind! Be careful of your duty to your Rabb (Lord) who created you from a single souland from it created its mate and from those two, has spread abroad a multitude of men andwomen. Be careful of your duty toward Allah in whom you claim (your rights) of one another,and toward the wombs (that bore you). For Allah has been a Watcher over you. [Quraan: An Nisaa, Chapter 4]
And finally, when the time was right, Allah created Isa . Hadhrat Isa was created fromHadhrat Maryam (Mary) , without a father. Allah sent Jibraeel to blow the Holy Breath.That was Allah’s fourth creation of a human being.The likeness of Isa (Jesus) with Allah is as the likeness of Adam. He created him from dust,then He said to him: “Be!” And he is.Allah is also the Creator of the heavens and the earth in which we abide. In all the creationsthere are four main basic elements. These four elements are, earth, water, air and fire.Whether it is heaven, earth cosmos or micro-organisms, Allah has created all these thingsout of the four basic elements. Allah has created the heavens as gardens and the existencein there is blissful. The creation of hell is a place of fire or extreme cold and existence inthere is extremely difficult. Allah has given us examples of that here on earth. But the bliss ofheaven is beyond imagination. Likewise the difficulty or torment of hell is beyond imagination.The interesting thing to note is that Allah, Al Khaaliq, creates everything in pairs. Allah hascreated Adam then Hawwa , that is, man and woman. Allah has created heaven andhell. Allah has created good and evil. Allah has created day and night. Allah has created,right and left. Allah has created mountains and valleys. Allah has created earth and water.Allah has created air and fire. Allah has created the visible worlds and the invisible worlds.Yet Allah, Al Khaaliq is One, He is Single and there is nothing like Him.
36 Glory to Allah Who created in pairs all things that the earth produces as well as their ownkind and things of which they have no knowledge. [Quraan: Ya Seen, Chapter 36]
49 And all things We have created by pairs, so that you may reflect. [Quraan: Az Zariyaat, Chapter 51]
Why has Allah created the creation in pairs? For creation to exist, there has to be oppositesor pairs. Even in the creation of every human being, Allah has created the spirit – Ruh andthe soul – Nafs. The Ruh is weak at the start, and the soul is strong. The soul is the animaltendencies in the human being. The soul has the survival instinct. As the human being growsolder the soul gets stronger. The spirit gets even weaker. In remembering Allah, the soul isimprisoned and the spirit is allowed to grow and be free. Allah has created the soul withnegative qualities, and the spirit with positive qualities.We can take the example of a battery. Unless the positive and the negative terminals areconnected to the circuit it will not be active. If we connect the positive terminal to a car andleave the negative terminal disconnected, the car engine does not turn with the ignition, andvice versa. Where did mankind learn about having positive and negative terminals to make abattery? We can say through scientific experimentation or we can say: “Allah taught Adam allthe names”.Because of the opposite qualities of the soul and the spirit created by Allah, there is always aconflict between them. The greatest Jihaad – Holy War, is the fight against the Nafs – soul.The fight is the suppression of the negative qualities of the soul. When the soul becomessubdued, the soul and the spirit exist in harmony. Initially the survival instinct of the soul isrequired to keep alive. Eventually, it must be subdued, hence the term “Spirituality”.Spirituality is to strengthen the spirit which has angelic qualities and subdue the soul whichhas the animal and satanic tendencies.
271 11 – AL KHAALIQ
Abu Huraira said, “The Prophet said, 'No child is born but that, Satan touches it when it isborn where upon it starts crying loudly because of being touched by Satan, except Mary andher son.'” [Sahih Al Bukhari]
So Allah in His Wisdom has created everything in pairs for creation to exist. If there is no evil,there is no reason for good to exist. There is nothing left for the good to conquer. You andme would not be here. I would not be writing this and you would not be reading this! Thewhole idea of creation according to a Hadees Qudsi, Allah said, “I was hidden treasure and Iloved to be known.”And then there was Muhammad , Allah’s greatest creation. Allah sent him as an examplefor the whole of mankind to follow. Someone asked Hadhrat Aisha to describe MuhammadRasool Allah . She answered, “Have you not read the Quraan? He is the living Quraan!”Let us go back to the beginning of the revelation of the Quraan to Muhammad . Jibraeel appeared at the cave and said:
Allah created the letters. From the letters, Allah created words. From the words, Allahcreated the worlds! Allah commanded: “Kun! (Be!)”, and things came into existence.The likeness of Isa (Jesus) with Allah is as the likeness of Adam. He created him from dust,then He said to him: “Be!” And he is.Muhammad is the letters! Muhammad is the words! Muhammad is the worlds!Muhammad asked Jibraeel , “How old are you?” He replied, “I do not know, I onlyknow that there is this polar star that appears once every 70,000 years. I have seen it 72,000times.” Hadhrat Muhammad revealed his forehead by moving his turban backwards andasked Jibraeel , “What do you see?” He replied, “It is the same star that I have seen72,000 times.”There is another Hadees where Muhammad stated: “I was a Messenger while Adamwas between clay and water.”And there is yet another Hadees Qudsi: “If it was not for you, I would not have created theheavens and manifested the Sovereignty.”
Allah is Al Khaaliq the Creator, who created everything visible and invisible. Allah is
One, La Shareek without partners, Al Qaadir Able to create whatever He wills by Hiscommand: “Be!”
272 11 – AL KHAALIQ
Alif 1 Laam 30 Qaf 100 TOTAL 731 TOTAL
MEDITATIONThe person who reads Ya Khaaliqu 1111 times everyday, Allah will teach that personeverything about the earth and the heavens, .
273 10 – AL MUTAKABBIR
74 Except Iblees. He was filled with pride and became one of the disbelievers.75 (Allah) said: “Iblees! What prevents you from prostrating before that which I have createdwith both My hands? Are you too proud or are you one of the high exalted?”76 (Iblees) said: “I am better than him. You created me from fire, while You created him fromclay.”77 (Allah) said: "Then get out from here, for you are outcast,”78 "And My curse is on you till the Day of Judgment." [Quraan: Saad, Chapter 38]
Pride is something that we all have. We have to suppress that quality, since pride is onlyreserved for Allah, Al Mutakabbir. Iblees showed his pride and Allah cursed him. Prideprevents one from bowing down. If we look at Salaah the prayer, we are required to bow andprostrate. Only a servant can bow down to the master. In our case, Allah is the Master. Weare His servants. So we have to bow down and prostrate to Allah. In bowing down, there ishumility. Humility is based on our smallness in relation to Allah’s creation of the heavens andearth. We are insignificant in comparison to the entirety of creation. Yet Allah loves Hishuman creation above all other creations.Allah is Akbar, Allah is Great, we are nothing. Therefore we must practice humility and refrainfrom pride. Pride belongs to Allah alone and no one else. Hence the question posed by Allahto Iblees: “Are you too proud or are you one of the high exalted?”Allah alone is Proud and He alone is the Exalted. Allah does not share His Attribute of Pridewith anyone. In this day and age we find that there are some leaders of certain countries whoare proud and arrogant. Either these leaders have risen to power by force or they have beenelected to govern the country. Election is based on the people voting for a party or leader toserve them in office. When the party leader gets into office, he forgets that the people haveelected him or her to serve them. Instead of serving the people, these leaders start to behavelike kings. They are puffed up with pride. Allah has reserved the Attribute of pride for Himself,He does not like to share that.We can also look back in history and find that the Pharaoh was filled with pride. Heconsidered everyone else as less than him. In fact he started claiming lordship for himself.Prophet Musa reasoned with him but when someone is filled with pride, that person
274 10 – AL MUTAKABBIR
becomes unreasonable. Even to the point of losing his own first born, the Pharaoh did notcome to his senses. And finally when, Allah decided enough was enough, Allah drowned himin the Red Sea.The spiritual side of this is that a proud person is senseless. The pride drowns that personinto a tormenting sea, from which it is impossible to come out alive. Allah in His Wisdom haskept the Attribute of Pride for Himself and Allah knows how to control that pride. Humanbeings become proud because Shaytaan pushes them in that direction, until they drown intheir own pride, since they do not know how to control pride. Let us look at another examplefrom the Quraan on humility which is the opposite of pride:
18 Till, when they reached the valley of the ants, an ant exclaimed: “Ants! Enter yourdwellings lest Sulaiman (Solomon) and his armies crush you, without knowing it.”19 And he smiled, amused at her speech, and said: “My Rabb (Lord)! Arouse me to bethankful for Your favours which You have favoured me and my parents, and to do good thatshall be pleasing to You, and include me in (the number of) Your righteous servants.” [Quraan: An Naml, Chapter 27]
First of all, the ant knew who Prophet Sulaiman was because the ant mentioned him byname, Sulaiman, that is one of Allah’s Messengers! Next, the ant did not accuse him of anywrong, so it said: “…without knowing it.” And finally, Prophet Sulaiman instead of beingfilled with pride, overcame with humility and said: “My Rabb (Lord)! Arouse me to be thankfulfor Your favours which You have favoured me and my parents, and to do good that shall bepleasing to You, and include me in (the number of) Your righteous servants.”Here we have two opposite examples, the humble Prophet Sulaiman asking to be includedin Allah’s righteous servants and the proud Pharaoh claiming lordship. What was the end ofHadhrat Sulaiman and what was the end of Pharaoh? What will be the end of the leadersof nations who are puffed up with pride?
Pride is my cloak and Greatness My robe, and he who competes with Me in respect of eitherof them, I shall cast into Hell fire. [Hadees Qudsi]
Allah is Al Mutakabbir the Proud. Allah does not like to share His Attribute of Pride withanyone, since everything is created by Him alone. Allah knows how to control His pride whenwe seek forgiveness since He is At Tawwaab the Acceptor of Repentance. Allah is AlKabeer the Great, His Greatness cannot be compared with anything since none of thecreation is anything like Him. So we must turn towards Allah our Rabb Lord and askHim: “My Rabb (Lord)! Arouse me to be thankful for Your favours which You have favouredme and my parents, and to do good that shall be pleasing to You, and include me in (thenumber of) Your righteous servants.” Aameen.
275 10 – AL MUTAKABBIR
The person who reads Ya Mutakabbiru 1111 times everyday, Allah will bestow respect onthat person .
276 9 – AL JABBAAR]
31 "And He has made me blessed wherever I am and has enjoined on me prayer and charityas long as I live,”32 “And dutiful to my mother, and not arrogant or miserable.”33 "Peace is on me the day I was born the day that I die and the day that I shall be raisedalive!” [Quraan: Maryam, Chapter 19]
When we apply the Attribute Al Jabbaar to Allah, it means the Compeller, the One whoforces His Will on His creatures. Jabbaar applied to ceratin people means arrogant or tyrant.It can also be applied as meaning to enforce one’s will upon another.Allah, Al Jabbaar is the One who has made certain laws and He forces those laws on thecreation. For example,
11 Then He turned to the sky when it was smoke and said to it and to the earth: "Come bothtogether willingly or unwillingly." They said: "We come obediently." [Quraan: Ha Meem, Chapter 41]
The sky and the earth are compelled by Allah to come together, whether they like it or not,that is willingly or unwillingly. Since Allah has created the sky and earth in truth, they cametogether willingly. Since Allah has created heavens and the earth in truth, Allah has forcedcertain laws upon them, like the earth orbiting the sun for as long as Allah wills. So Allah has
277 9 – AL JABBAAR
forced His will on the earth, the sun and all the things in heavens and earth. Likewise Allahhas forced certain laws on human beings. But human beings fall into two categories, thosewho believe in Him, and those who deny Him. Those who believe in Allah are compelled tolive their lives within certain limits or boundaries. Hence we have the commandments andlaw in the Books of Allah. Those who do not believe in Allah and break the commandmentsare not punished immediately. Because Allah is the Forgiver and the Merciful allowing themtime to reflect and come to the right path.When Jabbaar is applied to certain human beings, sometimes the meaning takes on the formof a tyrant or arrogance. We do not have to look very far to find tyrants ruling over others inthis day and age. Here the tyrant forces his will upon others. If anyone goes against thetyrant, that person is immediately “dealt with”. The person is not allowed any time to reflect orshow remorse for ones actions or utterances, the punishment is dished out straight away.Hence the application of Jabbaar to certain people is in the sense of tyrant.Arrogance can also be applied to certain people, who are known as Jabbaar. Arrogance andpride go hand in hand. Such people do not care for anyone else.In the example from Quraan, Chapter Maryam, Allah has recorded the words of Prophet Isa for our benefit. His life example was one of humility. His life example was one of servinghis Rabb (Lord). So we can say that Hadhrat Isa was not arrogant. Hadhrat Isa wasdutiful and kind to his mother Hadhrat Maryam .Let us go back to the Hadees which was quoted in the section Al Mutakabbir:
Pride is my cloak and Greatness My robe, and he who competes with Me in respect of eitherof them, I shall cast into Hell fire. [Hadees Qudsi]
What is the word for cloak in Arabic? Is it Jubbah? What does a Jubbah do? A Jubbahconceals or covers ones body and dress. Allah does not wear Jubbah because Allah is purefrom any physical body. The implication in the above Hadees is Allah does not want us towear pride or arrogance. These two qualities in a human being will lead that person to thefire of hell. We must learn to cover our pride so it is not visible. We must learn to hide orsuppress our arrogance so that it does not come to the surface. When we wear our Jubbah,we must cover our pride and arrogance. We must learn to practice humility. Islaam meanspeace. Peace cannot be attained by pride or arrogance. May Allah cover our faults and makeus humble towards Him and His creation, and save us all from the fire of hell. Aameen.Allah is Al Jabbaar the Compeller. Allah forces His Will on everything in creation .Allah does not permit any creature a share of His Oneness in His Pride or Jabarut - Might.All praise is for Allah, Rabbil Aalameen Lord of worlds.
278 9 – AL JABBAAR
MEDITATIONThe person who reads Ya Jabbaaru 1111 times everyday, will be protected from tyrants andtheir .
279 8 – AL AZEEZ
1 Ha Meem.2 Ayn Seen Qaf.3 Thus does (He) send inspiration to you as to those before you, Allah the Mighty the Wise. [Quraan: Ash Shuraa, Chapter 42]
Allah Al Azeez bestowed respect and honour on certain individuals from Hadhrat Adam toHadhrat Muhammad and chose them to be His Messengers. Allah the All Mighty sentinspiration to Muhammad as He did to those Messengers before him. In other words,Allah the Mighty exalted the status of His Messengers above those of their communitiesand gave them the might and power over the disbelievers.Here is an interesting fact. To receive the inspiration from Allah, all the Messengers of Allahfasted. Fasting is an integral part of receiving inspiration. Prophet Musa fasted for 30 days,that was not enough, Allah made him fast a further 10 days, making 40 days in total. AndAllah then sent inspiration to Hadhrat Musa . Prophet Muhammad used to fast whilestaying in the Cave Hira, and he received inspiration when Allah willed. We have an examplefrom Hadees how the inspiration affected Prophet Muhammad :
Al-Hariss bin Hisham asked Allah's Rasool "Ya Rasool Allah! How is the divine inspirationrevealed to you?" Allah's Rasool replied, "Sometimes it is (revealed) like the ringing of a bell,this form of inspiration is the hardest of all and then this state passes off after I have graspedwhat is inspired. Sometimes the Angel comes in the form of a man and talks to me and Igrasp whatever he says." 'Aisha added: “Truly I saw the Prophet being inspired divinely on avery cold day and noticed the sweat dropping from his forehead (as the Inspiration wasover).”’
280 8 – AL AZEEZ
[Sahih Al Bukhari]
Since the inspiration comes from the Mighty, the receiver is in awe of Allah’s Might. As wehave been told in the above Hadees. But fasting makes the body weak, so how does that tieup with might?We are not speaking of physical might or strength. Fasting chains Shaytaan. Fasting withZikr Allah, makes the spirit stronger. The spirit is purified and strengthened by remembranceof Allah. The nourishment of the spirit is the Zikr Allah. When the spirit gets strong it realisesits true nature and it is ready to receive inspiration from Allah.To receive inspiration, the receiver must be strong spiritually. Just as a house needs to bebuilt on a firm foundation, so does the inspiration need a strong foundation. The strongfoundation is the spirit.The spirit which has been strengthened by fasting and Zikr Allah is honoured to receive theinspiration. There are two kinds of inspirations. One kind comes from Allah and it is allgoodness. The other kind comes from Shaytaan, which is evil. The person receiving theinspiration must have a firm, strong, mighty foundation otherwise Shaytaan will lead thatperson astray. The Messengers of Allah had the Shaytaan bound and tied, and it could notlead them astray.
The Prophet offered a prayer, and (after finishing) he said, "Shaytaan came in front of metrying persistently to divert my attention from the prayer, but Allah gave me the strength toover-power him." [Sahih Al Bukhari]
281 8 – AL AZEEZ
Nothing is hidden from Allah, whether it is on the earth or the heavens. Allah is the Mightywho shakes the earth and reveals what is hidden for our sakes. Allah already has knowledgeof what is hidden in there. Similarly, Allah the Mighty knows what is in the wombs since He isthe Creator and the Shaper of what is in the wombs.
Allah is Al Azeez the Mighty, and there is not an atom that is hidden from Allah inside the
earth, that He reveals by making the Zilzala earthquake. Allah in His knowledgeshapes, and gives form as He pleases to a seed that is planted in the soil.
Za 7 Ya 10 Za 7 TOTAL 94 TOTAL
MEDITATIONThe person who reads Ya Azeezu 1111 times everyday, will be honoured in this world andthe .
282 7 – AL MUHAYMIN
48 And to you We have revealed the Scripture with the truth, confirming whatever Scripturewas before it, and a guardian over it. So judge between them by that which Allah hasrevealed, and do not follow their desires away from the truth which has come to you. Foreach We have appointed a divine law and a traced out way. Had Allah willed He could havemade you one community. But that He may try you by that which He has given you. So striveone with another in good works. To Allah you will all return, and He will then inform you ofthat wherein you differ. [Quraan: Al Maaida, Chapter 5]
Allah has appointed a guardian over the Scripture that has been revealed with the truth. Thatis, the Quraan confirms whatever Scripture was revealed before it. And there is a guardianover the Quraan, who guards the Quraan. Allah has taken the responsibility of guarding andprotecting the Quraan from corruption. Similarly, we have to guard and protect the words ofthe Quraan. Our faith and trust in Allah has been derived from the words of the Quraan. Wehave to guard and protect our faith in Allah, His angels, His Books and His Messengers.We must judge with that which Allah has revealed. To judge with that which Allah hasrevealed, is to guard and protect the faith. To guard the faith is to guard and protect therevelation received from Allah, which is the Holy Quraan. It is not permissible to follow thedesires away from the truth that has come to us. Yet, you will find the “Muslims” themselveshave become corrupt and they follow the desires away from the truth. In some countries wefind that there are different rules for different races of Muslims!Allah is the Guardian! As Allah says in the above reference: Had Allah willed He could havemade you one community. But that He may try you by that which He has given you.
283 7 – AL MUHAYMIN
The communities mentioned in the above verse does not necessarily mean Muslims,Christians, Jews, etc. We can also apply it to the “Muslim Communities”. That is, Muslimcommunities within the Muslim community! There is no limit to the depth of the wisdom of theQuraan. How do we guard our faith? By treating others, the same way we would like to betreated ourselves. As just mentioned earlier, there are different rules and laws within theMuslims for different races.
As we mentioned earlier, Allah has assigned a guardian over the Quraan. Each word of theQuraan is guarded. For example, if we look at the Name Muhaymin, we have the letters:
. The letter Meem is the guarding letter over the letter Haa and the
remaining letters. And likewise, the letter Haa is the guardian over the letter Ya and theremaining letters. The letter Ya is the guarding letter over the letter Meem and Noon. Andfinally the second letter Meem is the guarding letter over the letter Noon .Similarly the Name Muhaymin is the guardian over the Name Azeez and the Name Azeez isthe guardian or Muhaymin over the Name Jabbaar and so on. Hence we can say the NameALLAH is Muhaymin over all the 99 Names or Attributes of Allah.Allah is Al Muhaymin the Guardian who guards over His creation. There is nothingwhatever as His likeness and Hu He is the Hearer, the Seer. Nothing escapes His
284 7 – AL MUHAYMIN
MEDITATIONThe person who reads Ya Muhayminu 145 times everyday, will be guarded and receiveenlightenment .
285 6 – AL MU_MIN
1 All that is in the heavens and all that is in the earth glorifies Allah; to Him belongs dominionand to Him belongs praise, and He is Able to do all things.2 It is He who has created you; and of you are some that are disbelievers and some that arebelievers: and Allah sees what you do.3 He created the heavens and the earth with truth, and He shaped you and made yourshapes beautiful, and to Him is the journey. [Quraan: At Taghaabun, Chapter 64]
Al Hamdu Lillah, all praise is for Allah the Doer of what He wills. We are told that He createdus and some are disbelievers – unfaithful, and some are believers – faithful. The ones whohave Allah have Imaan and they are referred to as the faithful. Those who do not have Allahhave no Imaan and we say in Urdu Bay_imaan, which means unfaithful, crooked, bent orcorrupt.Hadhrat Muhammad was known as Al Ameen, the faithful, everyone trusted him as anupright and honest person. The thing to notice here is that before Muhammadproclaimed his mission as Allah’s Messenger, even the people of Makkah called him AlAmeen – the one who is trustworthy, or we could say the one who has Faith! Allah chose awoman named Aaminah to be the mother for His last Messenger . And what doesAaminah mean? Does it not mean the same as the one who has Faith? And Allah chose aman named Abdullah to be the father of His last Messenger. What does Abdullah mean?
286 6 – AL MU_MIN
Does it not mean Allah’s servant? Hadhrat Muhammad took form in this world fromHadhrat Abdullah and Hadhrat Aaminah and the people of Makkah called him AlAmeen. Allah the Faithful sent His servant as the faithful, to this world to teach us what faithis.Allah is the Faithful. Faith in Allah makes a person faithful. And Allah uses that attribute todescribe His servants who believe in Him. There are different categories of Muslims. Thecategories are from those that profess belief with words and there are those that professbelief not only with words but also with deeds.There are those that say: “Yes brother. I will do this for you.” or “I will do that for you.” Whenthe time comes to put the words in action, the “brother” is nowhere to be found. When he isfound, there are all kinds of excuses that follow. Then there are those that say: “Yes I will dothis for you, Inshaa Allah.” When the time comes to put words into action, they are there toback up their words. It is these latter ones who are Mu_minoon, their faith is in Allah, andAllah the Loyal, Allah the Dependable, Allah the Reliable, Allah the Truthful and Allah theFaithful guards their faith.]
Whoever praises Allah is faithful, and a believer. Whoever rejects Allah is unfaithful, and adisbeliever. To be faithful to Allah we need to learn from the above reference, and purifyourselves first, since Allah is the Holy One. We have to find peace in ourselves or be atpeace with ourselves so that Allah the Peaceful will send tranquillity to our hearts. That is wehave to believe and have faith in Allah, and Allah the Faithful will keep our faith intact. MayAllah give us all faith in Him so that we may all find peace of mind. Aameen.Allah is Al Mu_min the Faithful. Allah is Al Wadood the Loving who loves the Mu_min believer who believes in Allah, His Angels, His Books, His Messengers, the Day ofJudgment, and that Muhammad is the last and final Messenger. Allah loves thosebelievers more than the Angels and Jinn that He created from Noor – Light and Naar –Fire respectively.
287 6 – AL MU_MIN
MEDITATIONThe person who reads Ya Mu_minu 1111 times everyday, will be given strong faith and alldoubts and whispering of Shaytaan will be removed .
288 5 – AS SALAAM
“Salaam – Peace!” is the word from a Rabb Merciful. “As Salaamu Alaikum – The Peace beupon you!” is the greeting of a Muslim to another Muslim. “Wa Alaikum As Salaam – Andupon you also be the Peace!” is the response from the other Muslim on the one who wishedhim peace first. Therefore a Muslim wishing peace on someone should bring peace fromAllah on the one wished upon. Yet it does not! Why? That is because the words of peace areempty of any feelings. The words of peace are empty of sincerity. The words of peace aresaid as an impulse. The words of peace are said without understanding that this is thegreeting of heaven, so how can the people living in “hell” understand these words, or meanthem sincerely! Is it surprising that the one wished peace by another does not feel peaceful?So the greeting of heaven is ”Peace!” and the greeting of the earth is also “Peace!” Allah isthe Source of Peace. When we wish peace upon someone, we greet that person with thegreeting of heaven on earth. Allah says in the above reference: They and their partners, inpleasant shade, on reclining thrones. Theirs the fruit (of their good deeds) and theirs all theyask.How ironic that it is the partners (husband / wife) that make life hell for each other on thisearth. Instead of being in pleasant shade, they are in a burning inferno with flaring tempers.Instead of reclining on thrones, they are at each other’s throats. Instead of receiving their fruitand what they ask, they receive curses from each other and their wishes are refused. Howdoes one get out of this situation to attain peace? There are two options available. First
289 5 – AS SALAAM
option is to divorce and get out of that hell. Of all the permissible things in Islaam, the thingmost hated by Allah and His Rasool, Muhammad , is divorce!The whole idea of life on earth is to seek Allah, perfect our patience and find peace. If we donot find peace in ourselves on earth, we will not find peace after death. Therefore, thesecond option is to be busy in the remembrance of Allah and sending messages of peaceand blessings on Allah’s Beloved.
103 When you have performed the act of worship, remember Allah, standing, sitting andreclining. And when you are in safety, observe proper worship. Worship at fixed hours hasbeen enjoined on the believers. [Quraan: An Nisaa, Chapter 4]
28 Who have believed and whose hearts have rest in the remembrance of Allah. Truly in theremembrance of Allah do hearts find rest! [Quraan: Ar Raad, Chapter 13]
To attain peace on earth within ourselves we must remember Allah standing, sitting andreclining. Only then do the hearts of the believers find rest. Since the Nafs – soul is one ofthree states, that is, Ammarah – Reckless, Lawwamah – Restless or Mutmainnah –Peaceful. Standing, sitting and reclining are also three states. Allah tells us in the Quraan, inall three states, standing – Ammarah, sitting – Lawwamah and reclining – Mutmainnah wemust remember Allah. Only then do the hearts find rest. When the heart finds rest, itbecomes peaceful. When that heart finds peace, it can transmit peace to other hearts. So apeaceful person, saying Salaam to another means the words with his heart. And the hearerof the words feels it in his heart.Therefore, wishing Peace or saying Salaam to someone is also an act of worship providedwe remember Allah at the time we say Salaam. Like it has been made compulsory in Salaahprayer, “As Salaamu Alaika Ayyuhan Nabiyyu Wa Rahmat Ullahi Wa Barakatuhu.” We say:“Peace be upon you Nabee (Muhammad) and Mercy of Allah and His Blessings”, in everySalaah. And we also wish peace on every righteous servant of Allah in Salaah. Salaah issupposed to bring Peace to the one praying, yet we find some people want to read theSalaah like it is a competition as to who can finish it first!We started with finding peace in the womb of our mother. Allah gives us life. We are born.We come into motion and find it restless, seeking for a way to peace as we were before. Ondeath the body comes to rest and the soul and the spirit either attain peace or they remainrestless. To attain peace in this world, patience with remembrance of Allah is the answer.That is why we started this book with As Saboor, the Patient. Patience is the most difficultlesson to master in life. Allah loves those who are patient.May Allah, As Salaam the Source of Peace give us peace whether we are Nafs
Lawwamah the restless soul or Nafs Ammarah the reckless soul and change ourcondition to Nafs Mutmainnah the peaceful soul, which is pleased with its Rabb andpleasing to its Rabb. Aameen.
290 5 – AS SALAAM
The person who reads Ya Salaamu 1111 times everyday, will find peace and tranquillitywithin him / her, Inshaa Allah.A person wishing to calm an angry person should read Salaamun Qawlam Mir RabbihRaheem 11 times and either blow the breath at the agitated person or just look at thatperson, Inshaa Allah the agitated person will calm .
291 4 – AL QUDDUS
1 All that is in the heavens and all that is in the earth glorifies Allah, the Sovereign, the Holy,the Mighty, the Wise.2 It is He who has raised praise is for Allah. All that is in the heavens and earth praises Allah. Allah is Holy in thesense that He is Pure of any faults and pure of any forms. While human beings who havebeen created from a despised fluid, they can never attain purity as such. It is the intentionthat precedes the action of washing that follows to purify ourselves which is acceptable toAllah.Allah is Al Quddus the Holy One and He named Jibraeel as Ruh ul Quddus – the HolySpirit. Everytime Allah sent a Messenger, He sent Jibraeel to reveal the Message to theMessengers so that they could warn their communities. In the case of Prophet Isa Allahinforms us in the Quraan:
110 When Allah said: “Isa (Jesus), son of Maryam (Mary)! Remember My favour to youand on your mother; how I strengthened you with the Holy Spirit, so that you spoke tomankind in the cradle as in maturity; and how I taught you the Scripture and wisdom and theTorah and the Gospel; and how you shaped from clay the likeness of a bird by My
292 4 – AL QUDDUS
permission, and did blow upon it and it was a bird by My permission, and you did heal himwho was born blind and the leper by My permission; and how you did raise the dead, by Mypermission and how I restrained the Children of Israel from (harming) you when you came tothem with clear proofs, and those of them who disbelieved exclaimed: This is nothing butmagic;” [Quraan: Al Maaida, Chapter 5]
Allah is pure of any faults. Allah does not beget nor is He begotten. Allah has chosen theexample of Prophet Isa to inform us that the Christian idea of Trinity is an invention and alie. The example states that Hadhrat Isa shaped the clay in the form of a bird and breathedlife into it by Allah’s permission. Hadhrat Isa healed the blind and the lepers with Allah’spermission, and so did he raise the dead by Allah’s permission. Prior to all this, it was Allahwho taught Prophet Isa the Scripture and wisdom, Torah and the Gospel. Allahstrengthened Hadhrat Isa with the Holy Spirit, that is, Hadhrat Jibraeel . We find asimilar example of life giving:
96 He (Samiri) said: I perceived what they perceive not, so I seized a handful from thefootsteps of the messenger, and then threw it in. Thus my soul commended to me. [Quraan: Ta Haa, Chapter 20]
Samiri took a handful of dust from the footsteps where Jibraeel had passed, and even thatdust left behind, had attributes of life, which made the golden calf make a sound.In the case of Prophet Isa , Allah has created him from His own Breath, so we refer toHadhrat Isa as Ruh Allah, the Spirit of Allah. Hence Allah gave Prophet Isa permissionto give life, heal the sick and cure the blind. Now if we go back to the creation of ProphetAdam we find the same thing, Allah breathed into Hadhrat Adam His spirit andcommanded the angels to prostrate to him.
59 The likeness of Isa with Allah is as the likeness of Adam. He created him of dust, then Hesaid to him: Be! And he is. [Quraan: Al Imraan, Chapter 3]
So we come back to what we said. Allah is the Holy One without partners. There is no Trinity.If there was, then how can Prophet Adam be left out? In the case of Prophet Isa therewas a human mother, whereas in the case of Prophet Adam there was no human motheror father. The case of Trinity falls apart! The likeness of Isa is like that of Adam! They bothhad the Holy Spirit blown into them.Now we come back to the first reference from the Quraan in this section: Allah raised amongthe unlettered ones a Messenger of their own. This Messenger, Muhammad could alsomake a dried stem of date palm come to life with Allah’s permission, he could make waterflow from his fingers by Allah’s permission, he could make the moon split in two halves bypointing at it with Allah’s permission. Prophet Muhammad recited to them His revelationsand to make them grow, and to teach them the Book and wisdom, though before they werein manifest error.Allah’s revelations were brought by Jibraeel the Holy Spirit, to Muhammad . Now if wetake this one stage further, and realise that Allah’s revelations are the Ayats – signs, versesof the Quraan. Since these verses have been brought down by Jibraeel , the same onefrom whose dust the Samiri could make the golden calf exhibit signs of life, then we mustrealise that verses of the Quraan in our hands are more powerful and life giving than thatdust! When we recite the verses of the Quraan, we are reciting the same words that HadhratJibraeel recited to Hadhrat Muhammad . The verses of the Quraan should awaken or
293 4 – AL QUDDUS
strengthen the Holy Spirit within us! That is the greatest Miracle of Prophet Muhammadfor his community through Jibraeel , from Allah.If we go back to the references from the Quraan, we find Prophet Isa was strengthenedand he ‘spoke’ in infancy. We find Prophet Muhammad ‘recited, spoke’, the revelations.Zikr Allah is the answer.
The person who reads Ya Quddusu 1111 times everyday, will receive wisdom from Allah,and the one who reads Subbuh Quddus Rabb ul Malaaikati Wa Ruh 300 times will bepurified and receive enlightenment from world of angels,
294 3 – AL MALIK
113 Thus We have revealed it as an Arabic Quraan and have displayed therein certainwarnings, so that they may keep from evil or that it may cause them to remember.114 Then exalted is Allah, the King, the Real! Be not in haste with the Quraan before itsrevelation to you is completed but say "My Rabb (Lord)! Increase me in knowledge." [Quraan: Ta Haa, Chapter 20]
The Quraan has been revealed in Arabic. So we must recite the Quraan in Arabic, so that weare kept away from evil. The Arabic language of the Quraan is also a reminder for us! A letteris formed from a dot. We connect the dots and give a shape to whatever we are writing andform a letter. The Quraan starts with the letter Ba which has one dot. There are signs in thatand a reminder! The Quraan has been revealed in stages. Be not in haste with the Quraanbefore its revelation to you is completed! But say: “My Rabb! Increase me in knowledge.” Thehuman being is created from a drop and it takes form in stages. The human form takes ninemonths to complete. After birth, the baby learns little by little and grows into a full grownadult. Over the years the human being keeps learning, increasing in knowledge. “My Rabb!Increase me in knowledge.”Allah is Al Malik, the King, and He appointed certain individuals as kings on this earth. Forexample Allah the King appointed Prophet Sulaiman as a king. In fact Allah appointedHadhrat Adam as a vicegerent to represent Him on earth. We find that all the earthly kingsare in need of Allah. Like we are told in the example of the king of Egypt. Where the king ofEgypt had a dream and although he was a king, he was in need of someone to interpret hisdream. Allah gave that knowledge of interpreting dreams to Prophet Yusuf and not to theking of Egypt.Allah is the only True King over everything in the heavens and earth. Just as Allah hasservants to serve Him, the earthly kings appoint servants to serve them. Allah assigned theduty of revelation and message to Hadhrat Jibraeel . Allah assigned the duty of rainfall and
295 3 – AL MALIK
provisions to Hadhrat Mikaeel . Allah assigned the duty of taking life to Hadhrat Azraeel .Allah assigned the duty of blowing the trumpet to Hadhrat Israfeel .Allah appointed two kinds of earthly kings. There are those that Allah appoints on earth, whohave servants serving them on earth. They have palaces, riches and servitude on earth.Anyone speaking against them used to be beheaded or imprisoned in the old days.Then there are those kings that Allah appoints on earth that have no visible servants servingthem. The latter have derelict houses, poverty and insults on earth. Anyone insulting them isnot beheaded or imprisoned on earth for any personal insults. These latter types of kings weknow them as the Messengers of Allah. Prophet Musa is good example of such a king.Prophet Isa is good example of such a king. Prophet Muhammad is a good exampleof such a king. All of them served their communities. Their kingdom is not of the earthly type.Their kingdom is of the heavenly type. They served Allah, and His creation. Allahcommanded the angels to serve them. We find the Awliyaa Allah are the heirs, the inheritorsof the Messengers of Allah, hence they are also inheritors of the heavenly kingdoms.We find that the earthly kings with their riches are surrounded and followed by the richpeople. The heavenly kings with their poverty are surrounded and followed by the poor. Allthe earthly kings, all the heavenly kings and all those who follow either sort of king are inneed of Allah the Real King. Allah the Real King is not in need of anyone.
116 Therefore exalted be Allah the King, the Real. There is no god only He the Rabb (Lord)of the throne of generosity! [Quraan: Al Muminoon, Chapter 23]
Whether someone believes or disbelieves that Allah is Malikin Naas – the Master of thehumans, one thing is certain. Allah Al Malik is also Maliki Yaumid Deen – Master of the Dayof Judgment and every human being must taste death. After death each one of us will meetour Maker.
Allah is Al Malik the Sovereign, the Real. La ilaha illa Hu there is no god only He, Rabbof Arsh il Kareem Throne of Generosity.
296 3 – AL MALIK
MEDITATIONThe person who reads Ya Maliku 1111 times everyday, will be be honoured on earth and inheaven, and the person will become self-sufficient, .
297 2 – AR RAHEEM
31 Say, (Muhammad): “If you love Allah, follow me; Allah will love you and forgive you yoursins. Allah is Forgiving, Merciful.”32 Say: "Obey Allah and His Rasool (Messenger)"; but if they turn back Allah does not lovedisbelievers. [Quraan: Al Imraan, Chapter 3]
The message from Allah to Muhammad is to tell mankind: “If you love Allah, follow me.”There are numerous reasons for mankind to follow Muhammad . Allah Ar Raheem theMerciful sent His Rahmat – Mercy as Muhammad Rahmat al Lil Aalameen – Mercy tothe worlds. Allah said, “My Mercy has exceeded My Wrath.”Allah’s Attribute Ar Raheem is repeated again and again at the beginning of ever chapter inthe Quraan, except one. Ar Raheem is also found in the Quraan in the verses of thechapters. We recite Bismillah Hir Rahman Nir Raheem whenever we perform an action thatis good and permissible. We seek Allah’s Mercy in that action. We seek Allah’s blessings inthat action. We want Allah to make that action successful and fruitful in this world and thenext, since Mercy is divided between this world and the next world. Allah showers us with HisMercy in this world by providing for our needs, and Allah will show His Mercy in the nextworld to forgive us our sins. All praise is for Allah, who has given to us His Beloved,Muhammad , the Mercy to the worlds. Prophet Muhammad left for us the Quraan tofollow. Someone asked Hadhrat Aisha about the character of Prophet Muhammad ,and she replied: “Have you not read the Quraan?” The person asking replied: “Yes!” ThenHadhrat Aisha replied: “He is the Quraan!”
298 2 – AR RAHEEM
Therefore, if we love Allah, we must follow him who is the Quraan. We must followMuhammad Rasool Allah , and Allah will forgive us our sins, Allah is Forgiving, Merciful.We must obey Allah, and how do we obey Allah? As Allah says, “Obey Allah, obey theRasool!”
51 It is not fitting for a man that Allah should speak to him except by revelation or frombehind a veil or by the sending of a Messenger to reveal with Allah's permission what Allahwills. He is Exalted, Wise. [Quraan: Ash Shuraa, Chapter 42]
Muhammad , the Mercy to the worlds is that veil between Allah and us. Allah speaks tous from behind that veil, by the Quraan, since the words of the Quraan are from Allah.Therefore, those who believe in Allah and His Rasool, Muhammad , for them the Quraanis a Mercy and a Healing, for the disbelievers, it causes them loss after loss.Rahman is connected with creation, therefore Raheem is connected with after being created.
Raheem is connected with life and living. Allah , Ar Raheem the Merciful, Al Hayy
the Living gives us life so that we may experience His Mercy. If Allah is so Mercifulthen why do we see so many people suffer?To answer that question, let us start with an example. Since we are speaking of creation thenthe example we shall take is that of a mother and baby. If a mother does not allow her babyto crawl, because the baby will become dirty, then the baby will never learn to crawl. Then ifthe baby cannot crawl, it will never know how to stand. If the baby does not know how tostand, then it will never learn to walk. The legs will become deficient. The baby will grow intoa child and never be able to walk. Therefore, the mother being over protective, will harm thebaby’s growth rather than assist. The mother not allowing the baby to crawl will hinder thedevelopment of the baby rather than being merciful.Likewise, if Allah gave us everything on a plate, that we did not have to make any effort, thatwould hinder our development. Therefore, when we see others suffer, Allah wants to awakenthe mercy that he placed in our hearts. If everyone had all they wanted from Allah, then thefeeling of mercy in our hearts would die, because we would never experience that emotion. Itis Allah that placed the feeling of mercy in our hearts so that we may feel and share theburden of another human being and bring a smile on another person’s face.
Allah's Messenger said: There are one hundred (parts of) mercy of Allah and He has sentdown out of these one part of mercy upon the jinn and human beings and the insects and it isbecause of this (one part) that they love one another, show kindness to one another andeven the beast treats its young one with affection, and Allah has reserved ninety-nine partsof mercy with which He would treat His servants on the Day of Resurrection. [Muslim]
Just as we need Allah’s Mercy in this world after being created, we will need His Mercy whilewe are in the grave, and we will need His Mercy again when we are raised or created asecond time. Allah’s Mercy is an essential part of existence. Without Allah’s Mercy, existencewould be difficult.
83 And Ayub (Job) when he cried to his Rabb (Lord) "Truly distress has seized me and Youare Most Merciful of those that are merciful." [Quraan: Al Anbiyaa, Chapter 21]
299 2 – AR RAHEEM
Allah tried Prophet Ayub with distress and Hadhrat Ayub cried to his Rabb. The tears of ahuman being are like the mercy which descends from heavens. Allah heard the cry of Hisservant and showered His Mercy on Prophet Ayub and relieved him of the distress. That ishow Allah’s Mercy is sought by crying to our Rabb and asking Him to relieve us of ourdistress. May Allah, Ar Raheem shower His mercy on each one of us. Aameen.
Allah is Ar Raheem the Merciful, who gave us Hayaat Life so that we may seek
knowledge of Him because to Him is our final destination. The way to that knowledge isHadhrat Muhammad who is the final Messenger of Allah, and his gift to us is the Quraan,which is the gift from Allah.
MEDITATIONThe person who reads Ya Raheemu 1111 times everyday, will repay his debt even if it isequivalent to the size of a mountain, Inshaa Allah. Allah’s Mercy will also descend on theperson that recites Ya Raheemu .
300 1 – AR RAHMAN
This is the point where we have been created and fashioned in the image of Rahman. Sincewe have been formed in the Rahm, which is the womb, we have been created in the imageof Rahman. The womb takes its form from the Attribute, Ar Rahman. A mother’s womb is aplace of security.We have an entire chapter called Ar Rahman, which is Chapter 55 in the Quraan. ArRahman is the first point of contact for us. Everything in this world is created for the benefit ofhumans. As Allah clearly states again and again in the Quraan in the Chapter Ar Rahman,"Then which of the favours of your Rabb will you deny?"The umbilical cord of a baby is cut after birth. The baby cries on arrival into this world. That isa physical reality. Although in the physical world it is the separation of a baby from themother, the spiritual aspect is the separation of the spirit from the Reality. A physical bodycannot cry! The cry comes from the spirit which uses the body as a vessel to make thesound. The spirit cries at the separation from the Reality.Just as it was hinted in the section Ar Raheem that Raheem is a description of living or beingalive, we find that Rahman is a description of creation. We have the word Ar Rahman
and we find that after the letter Meem there is a tiny Alif. Meem and Alif is Maa -water.
45 Allah has created every animal from water. Of them there are some that creep on theirbellies; some that walk on two legs; and some that walk on four. Allah creates what He wills.Truly Allah is Able to do all things. [Quraan: An Noor, Chapter 24]
54 And it is He who has created man from water, and has established relationships oflineage and marriage; for your Rabb (Lord) is Able. [Quraan: Al Furqaan, Chapter 25]
301 1 – AR RAHMAN
From the above two examples we find the relationship of water in creation explained further.The lineage and marriage, and these two are also based on the water. The examples aregiven visibly on the earth. We have oceans, rivers, streams and tributaries, and how Allahhas linked them. We must follow that rule by having links to our families, and relatives.
30 Do not the unbelievers see that the heavens and the earth were joined together beforeWe clove them asunder? We made from water every living thing. Will they not then believe? [Quraan: Al Anbiyaa, Chapter 21]
Then we are given yet another example in the Quraan as shown above. Heaven and earthwere joined together. The scientists have established that to be true in this day and age. Yetwe had already been told that was the case more than 14 centuries ago. ProphetMuhammad explained that even further by example but how many people understood?Do we not know that mother and baby are joined together at the beginning of creation? Thenthe baby is separated from the mother just as Allah tells us in the above example. ThenProphet Muhammad said: "Heaven is at the feet of one's mother!"An incidence comes to mind where two women were fighting over a child. Each claiming thatthe child belonged to her. They came to Prophet Sulaiman and presented their case sothat he might judge with fairness. Hadhrat Sulaiman asked the first woman whether thechild was hers, she replied, “Yes.” He then asked the second woman if the child was hers,and she too answered, “Yes.” Prophet Sulaiman then spoke the judgment on the case.“Since each woman is claiming the child is hers, the proper judgment in this case is to cut thechild in two with the sword, and let each one have half of the child!” The real mother of thechild quickly spoke up and said, “Spare the child’s life and give it to the other woman.”Prophet Sulaiman replied: “Only a real mother would love her child and would not wantany harm to come to it.” So he gave the child to its rightful mother. There is no harm inheaven!A mother is a sign of heaven. The child is a sign of the earth. The heavens and earth werejoined together once upon a time, before they were separated. Therefore, we must respectour parents especially our mother. Heaven is under the feet of our mother. If she says aprayer for us, Allah accepts, since we are a product of her Rahm. And Allah is Ar Rahmanthe Compassionate. Allah will be Compassionate towards those who show respect towardstheir parents especially the mother. Allah is more Compassionate than a mother towards itschild.Therefore, it is natural that the first Attribute of Allah that Prophet Muhammad taught usis Ar Rahman, the Compassionate, the point of creation and the Attribute that follows ArRahman is Ar Raheem, the Merciful who gives life to us after we reach our appointed termand it is time to separate the earth from heaven!Similarly, Allah sends a heavenly spirit to earth. The transition point of the heavenly spirit tolife on earth is the womb of the mother. The people on earth cut the earthly umbilical cord toseparate the child from the mother. Allah cuts the heavenly umbilical cord of the spirit toseparate it from Ruh al Azam, the Greatest Spirit. The 'separated' spirit cries in heaven andthe child cries on earth. Both the spirit and child cry at the separation from their heavenlyhome.Just as Allah sent Hadhrat Adam to earth and told him that this would be his temporaryabode, Adam cried to Allah. Just as Prophet Ibraheem left Hadhrat Hajara andHadhrat Ismaeel in Makkah and told them that the valley of Makkah would be theirtemporary abode, they cried to Allah. Allah looked upon them with Compassion. And Hemade Makkah a holy city for His first house of worship.
302 1 – AR RAHMAN
While on the arrival of Muhammad , Allah decided, that Makkah is not a place for HisBeloved to stay. So Prophet Muhammad left Makkah for Madinah, leaving behind hishome, and that will be our case when we have to leave our earthly homes where we havebeen living for a while and return to Allah. Inna Lillahi Wa inna ilaihih Rajioon - We are fromAllah and to Him is our return.Allah Ar Rahman is our Rabb who gave us Hayaat life after creating us from Maawater so that we may experience this world temporarily and gain Noor enlightenmentbefore we return to Him.May Allah forgive all of us our sins and overlook our faults and take us back to Him with faithand the testimony La ilaha ill Allah Muhammadur Rasool Allah – There is no god only AllahMuhammad is the Messenger of Allah on our tongues at the time of our departure from earth.Aameen.
Al Hamdu Lillah – All praise is for Allah. Allah has given me the opportunity to write about His99 Asma ul Husna – Beautiful Names, His Sifaat – Attributes. May Allah accept this humbleeffort in His service and send His blessings on our Master Sayyidina Muhammad , hisfamily, his descendants, his companions, and all the believers in this world and the next.Aameen.
MEDITATIONThe person who reads Ya Rahmanu 1111 times everyday, will become compassionatetowards others and Allah will show His Compassion on that person by providing for theneeds
303 ALLAH
ALLAHAllah is Allah. Allah is the proper Name of our Creator. The Name Allah encompasses all theother Attributes, Sifaat of Allah. There is no substitute for the Name Allah. Therefore, everychapter (except one) in the Quraan starts with the words Bismillah Hir Rahman Nir Raheem– In the Name of ALLAH the Compassionate the Merciful. The proper Name Allah takesprecedence over all other Names or Attributes since the Name Allah encompasses all otherAttributes of Allah.
Just as we can visually see from the Name Allah, we can derive the Name Lillah .
From Lillah we can derive the Name Lahu . From Lahu we can derive the Name Hu .Even the Chapter of the Quraan which does not start with Bismillah Hir Rahman Nir Raheem,has the Name Allah mentioned as the first Name rather than God or the other Sifaat,Attributes:
1 A (declaration) of immunity from Allah and His Rasool to those of the pagans with whomyou have made a treaty. [Quraan: At Tawba, Chapter 9]
304 ALLAH
It all started when one day, 50 days before the birth of the Holy Prophet, Muhammad ,when the invaders came from Abyssinia (Ethiopia) to spread Christianity in Arabia and todestroy the Kaaba in Makkah. The residents of Makkah departed from the town and wentinto the hills. Abdul Muttalib , Muhammad’s grandfather, called Allah with the Name‘Allah’ and asked Him to protect His House."Allahumma, a man protects his house, so protect Your House. Let not their cross and theircraft tomorrow overcome Your craft. If You will to leave them and our qiblah to themselves,You may do as You please."The people of Makkah, were no match for the invaders. And Allah responded by destroyingthe army that had come to destroy His House, the Kaaba, as related in the Quraan, Surat AlFeel, Chapter 105.This does not mean that Allah ‘lives’ in the Kaaba. No! His House, the Kaaba is the firsthouse that was built as a place for His worship and the glorification of His Name.So the Name Allah was mentioned in Makkah for the first time 50 days before the birth of theHoly Messenger . The Name Allah is special because there is no comparison or likenessof Him.
11 The Creator of the heavens and the earth. He has made for you pairs of yourselves, andof the cattle also pairs, whereby He multiplies you. Nothing is as His likeness, and He isthe Hearer, the Seer. [Quraan: Ash Shuraa, Chapter 42]
The Name Allah is used to trap one's spirit. That is, when we meditate, when we do ZikrAllah, when we remember Allah, we should endeavour to visualise the Name Allah in ourmind so that everything else is removed from our thoughts.That is, all the spiritual energy should be concentrated at one point. And that point of
concentration is the Name Allah . Since all the 99 Attributes, Sifaat of Allah arecontained in the Name Allah. Therefore we need to get back to the source from which all theother Names of Allah have become manifest. And that source is ALLAH!As Prophet Muhammad said, when we read the Salaah, we must perform it like we cansee Allah. Of course, it is impossible to see Allah. What Prophet Muhammad meant wasthat all our thoughts must be gathered towards Allah. That is we must visualise the NameAllah while performing Salaah, and Inshaa Allah, we will attain a concentration in our Salaahsuch that we forget about everything else, and only 'see' Allah.La ilaha ill Allah Muhammadur Rasool Allah - There is no god only Allah, Muhammad is theRasool (Messenger) of Allah - is also known as Kalimaat Tayyab. Kalimaat Tayyab is thetestification of faith in Islaam. A person cannot be considered to be a Muslim if he / she doesnot believe in the words of this Kalimaat. To become a Muslim, a person must say thisKalimaat with total belief. Another point about this Kalimaat is the name given to it, which isTayyab. Tayyab means Purity. By uttering this Kalimaat a person is purified from disbelief.An impure person becomes pure. This purification is spiritual.
The Messenger of Allah added, "There will come out of Hell everyone who says: 'La ilaha illAllah,' and has in his heart good equal to the weight of a barley grain. Then there will comeout of Hell everyone who says: ' La ilaha ill Allah,' and has in his heart good equal to theweight of a wheat grain. Then there will come out of Hell everyone who says: 'La ilaha illAllah,' Al Bukhari]
305 ALLAH
And finally, another interesting fact that I would like to share with you, my dear friends, is thatduring the farewell pilgrimage of Prophet Muhammad , he gave a last sermon. In the lastsermon, Prophet Muhammad called upon Allah to witness that he had delivered HisMessage.
"People! No Prophet or Apostle will come after me and no new faith will be born. Reasonwell, therefore, you people, and understand words which I convey to you. I leave behind metwo things, the Quraan and my Sunnah and if you follow these you will never go astray.All those who listen to me shall pass on my words to others and those to others again; andmay the last ones understand my words better than those who listen to me directly. Be mywitness ALLAH, that I have conveyed Your message to Your people." [Arafaat, 9th Zul Hijjah 10 A.H.]
And finally let us go back to the Quraan from where we have received tremendous benefit,blessings, and mercy from Allah.
22 He is Allah, other than whom there is no other god, the Knower of the invisible and thevisible. He is the Compassionate, the Merciful.Hu Wallahul Lazee La ilaha illa Huwa Aalimul Ghaybi Wa Shahaadati Huwar Rahman urRaheem
23 He is Allah, other than whom there is no other god, the Sovereign, the Holy One, theSource of Peace, the Keeper of Faith, the Guardian of Faith, the Mighty, the Compeller, theProud. Glory to Allah from all that they ascribe as partner (to Him).Hu Wallahul Lazee La ilaha illa Huwal Malik ul Quddus us Salaam ul Mu_min ul Muhaiyminul Azeez ul Jabbaar ul Mutakabbir Subhaan Allahi Amma Yushrikoon
24 He is Allah, the Creator, the Shaper out of nothing, the Fashioner. His are the mostbeautiful names. All that is in the heavens and the earth glorifies Him, and He is the Mighty,the Wise.Hu Wallahul Khaaliq ul Baari ul Musawwiru Lahul Asma ul Husna Yu Sabbihu Lahu Ma FisSamawati Wal Ardhi Wa Huwal Azeez ul Hakeem [Quraan: Al Hashr, Chapter 59]
306 ALLAH
ALLAH ALLAH
The person who regularly visualises and keeps repeating the Name ALLAH , will beblessed by Allah to receive wonderful knowledge about His .
307 ALLAH
0 3 8 3
0 9 1
0 0 8
2 26 1 2
2 1 6 2
1 2 7 6
1 3 0
3 1 1
308 ALLAH
In the 99 Names of Allah, the frequency of the usage of the letters is as follows. Below is atable with the Arabic Letters and below the box with the letter there is a number signifyinghow many times that letter has been used across the 99 Names of Allah. And the winner is… the Letter Meem!
20 8 20 41
4 26 6
43 4 15
11 47 23 11
5 10 17 7
9 3 30 16
2 5 2
4 3 3
Al Hamdu Lillah, All praise is for Allah, we have reached Allah or we have reached the NameAllah..
With which Name was Allah known, before He was known as Allah? See the next section inthis book.
309 -1 – AL MUDABBIR
Al Hamdu Lillah, Allah has given me the opportunity to write about His Beautiful Names. Wehave looked at the 99 Names of Allah in this book from As Saboor to Ar Rahman or from ArRahman to As Saboor whichever you prefer. We have looked at 100 Names of Allah if wecount the Name Allah. Now let us look at the ‘Minus One’ Name of Allah in this book. In otherwords, let us look at the above Hadees from every angle! One is Witr, odd number and so isMinus One (-1), which is still an odd number!Allah is Al Mudabbir, the Arranger or the Manager or the Director. To manage is toaccomplish, administer, conduct, direct, effect, govern, rule, supervise and control.Let us start with a reference about Allah, the Arranger, from the Quraan:
2 Allah is He who raised the heavens without any visible pillars; is firmly established on thethrone; subjected the sun and the moon, each one runs for an appointed term. He arrangesaffairs explaining the signs in detail that you may believe with certainty in the meeting withyour Rabb (Lord). [Quraan: Ar Raad, Chapter 13]
Allah was and there was nothing with Him! It is related in Muwahib Ludniya Muhammadinformed Jaabir: “Inn Allaha Khalaqa Qablal Ashya_e Noora Nabiyyika – Allah created theLight of your Nabee before any other creation.” That is Allah created the Light of Muhammad before any other creation. Mawlana Abul Noor Mohammad Bashir writes in his book:
310 -1 – AL MUDABBIR
Muhammad is the first creation of Allah. The reason being that Muhammad isRahmat ul Lil Aalameen – Mercy to the worlds. For the worlds to come into existence, it wasnecessary to create the object for the Lordship. For Allah’s Lordship to be manifested, it wasnecessary for the Mercy to be brought into existence first. If anything had been createdbefore the Mercy, then some existence would be outside the Mercy and so it would not betrue to say ‘Mercy to the worlds’. Hence the Mercy had to precede all the worlds of creation.Mercy had to be created before the creation of anything else.In another place there is mention of Hadhrat Jibraeel’s age:
Jibraeel said: “There is a star that appears and shines every 70,000 years, and I have seenthat star 72,000 times.”Muhammad replied: “Wa Izzati Rabbi, Ana Zaalikal Kawakab.” – I swear by the Might ofmy Rabb (Lord), I am that star! [Jibraeel Ki Hikayat – Stories about Jibraeel]
It is also related in other Ahadees, “I was a Messenger while Adam was between clay andwater.”So the Noor-e-Muhammadi, the Light of Muhammad was created first out of the Noor ofAllah.
Allah, Al Mudabbir the Arranger, planned, arranged and directed the creation such
that everything began with the creation of the Light of Muhammad , and the rest of
creation came after that. Allah Al Mudabbir created Ahmad for His praise. AndAllah, Barr became Rabb having created the object for His Rabbubiyat -Lordship. Then Allah created the heavens and the throne from the Light of Muhammad, andestablished Himself firmly on the throne. Allah created the sun and the moon from the Lightof Muhammad and subjected them to run their course.When it was time to create a Khalifah (Vicegerent), Allah put the Damm in Alif and breathed
into it His Breath, and created Adam for Hamd to praise his Creator, Allah! AgainAdam is created from the Light of Muhammad. Then Allah commanded all the angels to bowdown to Hadhrat Adam and they all bowed down, except Iblees who was arrogant. Allahtaught Adam all the names.
33 (Allah) He said: “Adam! Tell them their natures.” When he had told them Allah said: “Did Inot tell you that I know the secrets of heaven and earth and I know what you disclose andwhat you hide?” [Quraan: Al Baqara, Chapter 2]
Allah Al Mudabbir sent Hadhrat Adam to earth to prepare, arrange for the arrival of Hisgreatest creation, the model for humanity to follow.Hadhrat Muhammad arrived on this earth in the year 570AD in Makkah. Makkah wasalready established as place where the House of Allah, the first house of worship was built.Then Allah the Arranger, wanted to show us physically the separation of Noor-e-Muhammadifrom the Noor of Allah by arranging the circumstances such that Prophet Muhammad ,had to separate from Makkah and the First House of worship and move to Madinah. So
Hadhrat Muhammad moved from one Meem (Makkah) to Ya (Yasrib) and havinggot there, Yasrib became the final Meem (Madinah). From Mudabbir to Muhammad there
311 -1 – AL MUDABBIR
is Knowledge. From Makkah to Madinah there is Knowledge. From one Meem to the other
Meem there is Knowledge. Allah sent us a great Muallim – Teacher to teach us Hisways. Salawaat - Blessings and Salaam - Peace on that Great Teacher from Allah, whonever went to any school, Allah taught him all the names and nature of things!Inna Lillahi Wa inna ilaihih Rajioon - We are from Allah and to Him is our return.
Allah has ninety-nine Names, that is, one hundred minus one, and whoever believes in theirmeanings and acts accordingly, will enter Paradise; and Allah is Witr (One) and loves the‘Witr' (odd numbers). [Sahih Al Bukhari]
May Allah enlighten all the Muslims and May Allah forgive all of us our sins. Aameen.Allah is Al Mudabbir the Arranger, the Director, the Manager, who manages directs andarranges the affairs according to His Wisdom. Only Allah is Al Daiem the One who existsand will exist forever. All the creation will perish except the aspect of our Rabb Lord,Possessor Majesty and Honour.
MEDITATIONThe person who reads Ya Mudabbiru 1111 times everyday, whatever good that person plansto do, Allah will assist that plan to a fruitful .
312 -1 – AL MUDABBIR
Al Hamdu Lillah, All praise is for Allah who enabled me to complete this book after more thanthree and half years. I pray to Allah, “Ya Allah! Bless our Master Sayyidina Muhammad ,His Family and His Companions. Ya Allah, bless all the Anbiyaa Alaihi Salaam, all theAwliyaa Ikraam , especially Shaykh Muhayyuddeen Abdul Qadir al Jilani , all myteachers, especially Professor Ashiq Hussain Ghouri, all the believers, our parents, and ourchildren in this world and the next. Ya Allah! Keep us all on Siraat al Mustaqeem the straightpath. Ya Allah! You love to forgive, therefore forgive us our sins for the sake of Your Beloved,Muhammad , our Master, after all, we are his followers.”
8 Allah! There is no god only He! To Him belong the Most Beautiful Names. Allahu La ilaha illa Huwa Lahul Asmaa ul Husna [Quraan: Ta Haa, Chapter 20]
313Name Meaning-1 Al Mudabbir The Arranger ALLAH ALLAH 1 Ar Rahman The Compassionate 2 Ar Raheem The Merciful 3 Al Malik The Sovereign 4 Al Quddus The Holy 5 As Salaam The Source of Peace 6 Al Mu_min The Faithful 7 Al Muhaymin The Guardian 8 Al Azeez The Mighty 9 Al Jabbaar The Compeller10 Al Mutakabbir The Proud11 Al Khaaliq The Creator12 Al Baaree The Maker13 Al Musawwir The Fashioner14 Al Ghaffaar The Forgiver15 Al Qahhaar The Subduer16 Al Wahhaab The Bestower17 Al Razzaaq The Provider18 Al Fattah The Opener19 Al Aleem The Knower20 Al Qaabidh The Constrictor21 Al Baasit The Expander22 Al Khaafidh The Abaser23 Ar Raafee The Exalter24 Al-Muizz The Honorer25 Al Muzill The Dishonorer26 As Samee The Hearer27 Al Baseer The Seer28 Al Hakam The Judge29 Al Adl The Just30 Al Lateef The Subtle31 Al Khabeer The Aware32 Al Haleem The Forbearing33 Al Azeem The Magnificent
314Name Meaning34 Al Ghafoor The Forgiving35 Ash Shakoor The Appreciative36 Al Ali The High37 Al Kabeer The Great38 Al Hafeez The Preserver39 Al Muqeet The Maintainer40 Al Haseeb The Reckoner41 Al Jaleel The Majestic42 Al Kareem The Generous43 Ar Raqeeb The Watchful44 Al Mujeeb The Responsive45 Al Waasi The All Embracing46 Al Hakeem The Wise47 Al Wadood The Loving48 Al Majeed The Glorious49 Al Baais The Resurrector50 Ash Shaheed The Witness51 Al Haqq The Truth52 Al Wakeel The Trustee53 Al Qawee The Strong54 Al Mateen The Firm55 Al Walee The Protecting Friend56 Al Hameed The Praisworthy57 Al Muhsee The Appraiser58 Al Mubdee The Originator59 Al Mueed The Restorer60 Al Muhyee The Giver of Life61 Al Mumeet The Creator of Death62 Al Hayy The Living63 Al Qayyum The Self Subsisting64 Al Waajid The Finder65 Al Maajid The Noble66 Al Waahid The One
315Name Meaning The One67 Al Ahad The Eternal68 As Samad The Able69 Al Qaadir The Powerful70 Al Muqtadir The Expediter71 Al Muqaddim The Delayer72 Al Muakhar The First73 Al Awwal The Last74 Al Akhir The Manifest75 Al Zaahir The Hidden76 Al Baatin The Governor77 Al Waali The Exalted78 Al Muta_aali The Beneficient79 Al Barr The Acceptor of Repentance80 At Tawwaab The Avenger81 Al Muntaqim The Pardoner82 Al Afuw The Kind83 Ar Rauf The Owner of Sovereignty84 Maalik ul Mulk The Possessor of Majesty and85 Zul Jalaali wal Ikraam Bounty86 Al Muqsit The Equitable87 Al Jaamee The Gatherer88 Al Ghanee The Self Sufficient89 Al Mughnee The Enricher90 Al Maanee The Preventer91 Adh Dhaar The Distresser92 An Naafee The Favourable93 An Noor The Light94 Al Haadee The Guide95 Al Badee The Originator96 Al Baaqee The Everlasting97 Al Waaris The Inheritor98 Ar Rasheed The Guide to the Right Path99 As Saboor The Patient
316317318 ALLAHUMMA INNI ASALUKA WA TUWAJJAHU ILAYKA BE NABIYYIKA MUHAMMADIN NIBIYYIR RAHMATI YA MUHAMMADU INNI AL WAJJAHU BIKA ILA RABBI FEE HAJATEE HAZIHI LI TUQDHA LEE ALLAHUMMA FASHFEEHU FIYYA
2 Rakaat Salaat Nawafil Hajat then read the above 3 times and mention your desire
319320321 Bismillah Hir Rahman Nir Raheem
322 | https://fr.scribd.com/document/50672737/Allah-s-names | CC-MAIN-2019-43 | refinedweb | 83,750 | 73.37 |
csGLScreenShot Class Reference
[Common Plugin Classes]
OpenGL screen shot. More...
#include <csplugincommon/opengl/glss.h>
Detailed Description
OpenGL screen shot.
Definition at line 48 of file glss.h.
Member Function Documentation
Decrement the number of references to this object.
Thread-safe - it is possible to manipulate the reference count from different threads. If multiple threads simultaneously decrement the reference count and cause the object to be freed it's not defined on which thread the subsequent destruction happens - it may happen in any one of the decrementing thread.
iDataBuffer implementation
Implements iDataBuffer.
Definition at line 97 of file glss.h.).
Definition at line 63 of file glss.h.
Get a string identifying the format of the raw data of the image (or 0 if raw data is not provided).
The format string must be compatible with that supported by iTextureManager::CreateTexture().
- See also:
- Texture format strings
Definition at line 76 of file glss.h.
iDataBuffer implementation
Implements iDataBuffer.
Definition at line 90 of file glss.h.
The documentation for this class was generated from the following file:
Generated for Crystal Space 2.1 by doxygen 1.6.1 | http://www.crystalspace3d.org/docs/online/api/classcsGLScreenShot.html | CC-MAIN-2014-10 | refinedweb | 188 | 51.95 |
Ok, so now I got Windows Vista RC1 installed (You can get it too from MSDN Subscriber Downloads) and I have the Orcas tools installed. I have been playing with Avalon since 2002 and it was announced as a "pillar of Longhorn" to all of you at the 2003 PDC but yet it seems to be a good time to start again for a couple of great reasons:
So, here are the steps. I make no attempt to have this post be "novel" or "definitive"; just an attempt to put information in one place.
You may also want to install, for later, AFTER you learn the basics:
Microsoft® Expression® Interactive Designer September 2006 Community Technology Preview
Microsoft® Expression® Graphic Designer September 2006 Community Technology Preview
Ok, now we're finally ready. I recommend, if you can, that you start with an editor and the command line compilers in the Windows SDK. I am using Notepad++ with its nice free syntax hilighting (I've given up on TextPad). As I said earlier, although VS2005 is very nice with its syntax hilighting, and WILL be what you use after the basics, it's wizards and such get in the way of really learning a new framework and learning with a book like Applications = Code + Markup. Like I said, the five editions of this book got me started programming Windows 2.0 in the mid-1980's and on through Windows 3.0 and 3.1. There was no Visual C++ or Visual Basic then. All we had was Petzold, a C compiler and an editor! In some ways, it was better because you really had to learn what you were doing. Of course, it wasn't very productive writing 175 lines of C code to put up a Window, you sure knew what the heck was going on.
Anyhow, fire up your editor, or use Visual Studio with the Orcas tools.
using System;
using System.Windows;
using System.Windows.Input;
using System.Windows.Controls;
namespace Gentile.Avalon
{
public class DisplayTextBlockToMakeIanHappy : Window
{
[STAThread]
static void Main()
{
Application myApplication = new Application();
myApplication.Run(new DisplayTextBlockToMakeIanHappy());
}
public DisplayTextBlockToMakeIanHappy()
{
TextBlock ianText = new TextBlock();
ianText.FontSize = 32;
ianText.Text = "Hello Ian";
Content = ianText;
}
}
}
It looks like this (Glass and all!):
Now, you're ready for more!
Technorati Tags: Windows Presentation Foundation, | http://codebetter.com/blogs/sam.gentile/archive/2006/09/10/Writing-Your-First-Avalon-Program-on-Windows-Vista-RC1.aspx | crawl-002 | refinedweb | 384 | 65.12 |
Lifecycle of a Python Code - CPython's Execution Model
Batuhan Osman Taşkaya
・11 min read
Motivation
- Learn Python's internals.
- Make cool stuff with understanding of AST
- Write better and memory efficient code
Pre-requirements
- Basic understanding of how interpreters work? (AST/Tokenization...)
- Python knowledge
- Little bit C.
batuhan@arch-pc ~/blogs/cpython/exec_model python --version Python 3.7.0
CPython's Execution Model
Python is a compiled and interpreted language. The Python compiler generates bytecodes and interpreter executes bytecode. We are going to look this sections;
- Parsing & Tokenization
- Transformation To AST
- CFG
- Bytecode
- Execution On CPython's Virtual Machine
Parsing & Tokenization
Grammar
The grammar defines semantics of a python with. It is also useful in specifying how a parser should parse the language.
The grammar of python uses ebnf-like syntax. It has its own grammar to source language translator.
You can find the grammar file in
cpython/Grammar/Grammar
An example of grammar,
batuhan@arch-pc ~/cpython/Grammar master grep "simple_stmt" Grammar | head -n3 | tail -n1 simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
A simple statement contains small statement then it might take semilcon (for oneliners :) ) and it finishes with a new line. A small statement looks like a list of expressions, imports...
Some statements,
small_stmt: (expr_stmt | del_stmt | pass_stmt | flow_stmt | import_stmt | global_stmt | nonlocal_stmt | assert_stmt) ... del_stmt: 'del' exprlist pass_stmt: 'pass' flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt | yield_stmt break_stmt: 'break' continue_stmt: 'continue'
Tokenization ( Lexical Scanning )
Tokenization is the process of getting a stream of text and tokenize it meanful (to interpreter) words with some extra metadata (like where the token started where it ended what is the string value of this token)
Tokens
Tokens is a header file and it contains definition of all tokens. Python currently has 59 types of tokens (
Include/token.h).
Some tokens;
#define NAME 1 #define NUMBER 2 #define STRING 3 #define NEWLINE 4 #define INDENT 5 #define DEDENT 6
You can see this tokens when you tokenize some python code.
Tokenize with CLI
It is our tests.py
def greetings(name: str): print(f"Hello {name}") greetings("Batuhan")
And when we tokenize it with
python -m tokenize, it is the output;
batuhan@arch-pc ~/blogs/cpython/exec_model python -m tokenize tests.py 0,0-0,0: ENCODING 'utf-8' ... 2,0-2,4: INDENT ' ' 2,4-2,9: NAME 'print' ... 4,0-4,0: DEDENT '' ... 5,0-5,0: ENDMARKER ''
The numbers (ex: 1,4-1,13) represents where token started and where it ended up. The
NAME,
OP,
STRING like things it the real tokens. And
def,
greetings,
( like thins it their value.
The encoding token is always the first token we get. It tells encoding of source file and if there is a problem about encoding of source file interpreter raises an exception.
Tokenize with
tokenize.tokenize
If you want to tokenize a file inside your code you can use
tokenize module (in stdlib).
>>> with open('tests.py', 'rb') as f: ... for token in tokenize.tokenize(f.readline): ... print(token) ... TokenInfo(type=57 (ENCODING), string='utf-8', start=(0, 0), end=(0, 0), line='') ... TokenInfo(type=1 (NAME), string='greetings', start=(1, 4), end=(1, 13), line='def greetings(name: str):\n') ... TokenInfo(type=53 (OP), string=':', start=(1, 24), end=(1, 25), line='def greetings(name: str):\n') ...
The type is the token id in the
token.h header file. The string is the value of the token. Start and End represents where token started and where it ended.
In other languages the scopes identified with curly braces or begin/end statements but in python we use indentation for scopes and their levels. The
INDENTand
DEDENTtoken represents indentations. This tokens are really import for constructing relational parse / abstract syntax trees.
Parser Generation
Parser generation is the name of the process that generates parser from given Grammar. Parser generators are known as PGen.
In cpython repository there are 2 parser generators. One is the original one (
Parser/pgen) and one is the rewrited one that writed with python (
/Lib/lib2to3/pgen2).
"The original was actually the first code I wrote for Python".
- Guido
We can understand from the quote that pgen is the one of the most important thing for a programming language.
When you call pgen (in
Parser/pgen) it generates a header file and a c file (the parser itself).
If you look at the generated c code it might not make sense to you (because it is not supposed to do). It just contains alot of static data and structs. I'll try to explain the basic components of it.
DFA
Parser defines one DFA to every non-terminal. Every DFA is defined as an array of states.
static dfa dfas[87] = { {256, "single_input", 0, 3, states_0, "\004\050\340\000\002\000\000\000\012\076\011\007\262\004\020\002\000\300\220\050\037\202\000"}, ... {342, "yield_arg", 0, 3, states_86, "\000\040\200\000\002\000\000\000\000\040\010\000\000\000\020\002\000\300\220\050\037\000\000"}, };
For each DFA we also have the start set which shows which tokens the specific non-terminal can start with.
State
Every state is defined as an array of arcs.
static state states_86[3] = { {2, arcs_86_0}, {1, arcs_86_1}, {1, arcs_86_2}, };
Arc
And every arc has 2 number. The first number is the arc label. It refers to symbol number. The second number is the destination.
static arc arcs_86_0[2] = { {77, 1}, {47, 2}, }; static arc arcs_86_1[1] = { {26, 2}, }; static arc arcs_86_2[1] = { {0, 2}, };
Labels
It is a special table which converts symbol ids into arc labels.
static label labels[177] = { {0, "EMPTY"}, {256, 0}, {4, 0}, ... {1, "async"}, {1, "def"}, ... {1, "yield"}, {342, 0}, };
The number
1 corresponds all identifiers. So that each one of those get a diffrent arc label even though they are all share the same symbol id.
Simple Example
We have a code that prints 'Hi' if 1 is True.
if 1: print('Hi')
According to parser the
code is a
single_input.
single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE
Our parse tree starts with a just root node of single input;
And our DFA (single_input) number is 0;
static dfa dfas[87] = { {256, "single_input", 0, 3, states_0, "\004\050\340\000\002\000\000\000\012\076\011\007\262\004\020\002\000\300\220\050\037\202\000"} ... }
And it looks like this;
static arc arcs_0_0[3] = { {2, 1}, {3, 1}, {4, 2}, }; static arc arcs_0_1[1] = { {0, 1}, }; static arc arcs_0_2[1] = { {2, 1}, }; static state states_0[3] = { {3, arcs_0_0}, {1, arcs_0_1}, {1, arcs_0_2}, };
arcs_0_0 made of 3 elements. First one is
NEWLINE, second one is
simple_stmt and the last one is
compound_stmt.
According to start set of
simple_stmt a
simple_stmt can not starts with
if. Because
if is not an newline but the
compound_stmt might begin with if. So we transition along the last arc (
{4, 2}). And add the
compound_stmt node the parse tree and before we actually transition to number 2 we switch to a new DFA.
The new DFA parses compound statements.
compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | with_stmt | funcdef | classdef | decorated | async_stmt
It loooks like this;
static arc arcs_39_0[9] = { {91, 1}, {92, 1}, {93, 1}, {94, 1}, {95, 1}, {19, 1}, {18, 1}, {17, 1}, {96, 1}, }; static arc arcs_39_1[1] = { {0, 1}, }; static state states_39[2] = { {9, arcs_39_0}, {1, arcs_39_1}, };
Only the first arc can begin with an
if statement.
Updated parse tree with
if
Then we switch our DFA again, the next DFA parses
if statements.
if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
It is a long one. In the inital state we have only one arc with a label 97. That corresponds
if token.
static arc arcs_41_0[1] = { {97, 1}, }; static arc arcs_41_1[1] = { {26, 2}, }; static arc arcs_41_2[1] = { {27, 3}, }; static arc arcs_41_3[1] = { {28, 4}, }; static arc arcs_41_4[3] = { {98, 1}, {99, 5}, {0, 4}, }; static arc arcs_41_5[1] = { {27, 6}, }; static arc arcs_41_6[1] = { {28, 7}, }; ...
When we switch to the next state (with staying in same DFA). Next one (arcs_41_1) has only one arc too. But this one for
test non-terminal. It might begin with a number (like 1).
In
arcs_41_2 there are only 1 arc that consumes Colon token (:).
Then we have a suite. Suite can start with a print statement.
Finally we have a
arcs_41_4. The first arc in suite is the
elif statement, second one is represents
else and the third one stands for final state.
Basically that is it.
Python Interface For Parser
Python offers you to edit parse tree of python expression in pyhon via a module called
parser.
>>> import parser >>> code = "if 1: print('Hi')"
We can generate a CST (Concrete Syntax Tree) with
parser.suite
>>> parser.suite(code).tolist() [257, [269, [295, [297, [1, 'if'], [305, [309, [310, [311, [312, [315, [316, [317, [318, [319, [320, [321, [322, [323, [324, [2, '1']]]]]]]]]]]]]]]], [11, ':'], [304, [270, [271, [272, [274, [305, [309, [310, [311, [312, [315, [316, [317, [318, [319, [320, [321, [322, [323, [324, [1, 'print']], [326, [7, '('], [334, [335, [305, [309, [310, [311, [312, [315, [316, [317, [318, [319, [320, [321, [322, [323, [324, [3, "'Hi'"]]]]]]]]]]]]]]]]]], [8, ')']]]]]]]]]]]]]]]]]]], [4, '']]]]]], [4, ''], [0, '']]
It's output is a nested list. Every list in the structure has two elements. First one is the symbol id (0-256 terminals, 256+ non-terminals) and second one is the token string for terminals.
Documentation of parser module says no one should use it. Use AST module instead of it. But i want to just show there is a bridge module for parser.
Abstract Syntax Tree
Basically AST is a structural representation of you source code in a tree format where every node in tree represents a different type of language construct (e.g: an expression, a statement, a variable, a literal).
What is a Tree?
Tree is a data structure that has a root node as a starting point. The root node can branch down to other nodes. Each node (except root node) has a single, unique parent.
What is difference between AST and Parse Tree
In right there is a parse tree of
2x7+3 expression. It is basically a one-2-one mapping of your source code into a tree form. You can see all expression, terms, factors. But it is a very complicated and complex tree for a basic piece of code. So we can remove all syntactical expressions that we need to define the code and simplify it.
The simplified version is called AST. The left one is the AST for same code. we've left behind all these syntactical expressions.
When you transform your Parse Tree to AST you lose some information
Example
Python offers a built-in AST module for working with AST.
You can use 3rd party modules like Astor.
to generate source code back from the AST
We have the same code. Print Hi if 1 is True.
>>> import ast >>> code = "if 1: print('Hi')"
Lets use
ast.parse method to get our AST.
>>> tree = ast.parse(code) >>> tree <_ast.Module object at 0x7f37651d76d8>
We can see readable AST with
ast.dump method.
>>> ast.dump(tree) "Module(body=[If(test=Num(n=1), body=[Expr(value=Call(func=Name(id='print', ctx=Load()), args=[Str(s='Hi')], keywords=[]))], orelse=[])])"
It is way better than Parse Tree :D
Control Flow Graphs
CFGs are a directed graph that models the flow of a program using basic blocks that contain the intermediate representation within the blocks.
CFGs are usually one step away from final code output. Code is directly generated from the basic blocks (with jump targets adjusted based on the output order) by doing a post-order depth-first search on the CFG following the edges.
Best Part - The Bytecode
Python Bytecode is a intermediate set of instructions that runs on Python's virtual machine implementation.
When you run a source code python creates a directory called
__pycache__ and stores your compiled python code for time saving in rerun situations. That is a python bytecode.
Simple python function in func.py
def say_hello(name: str): print("Hello", name) print(f"How are you {name}?")
When i call it repl it prints;
>>> from func import say_hello >>> say_hello("Batuhan") Hello Batuhan How are you Batuhan?
It is a function type object
>>> type(say_hello) <class 'function'>
And it has
__code__ attribute. It is a python code object
>>> say_hello.__code__ <code object say_hello at 0x7f13777d9150, file "/home/batuhan/blogs/cpython/exec_model/func.py", line 1>
Code Objects
Code objects are immutable data structures that contains instructions / metadata needed for run the code. Simply it is a representation of a python code.
Also you can get python code objects by compiling ASTs via
compile method.
>>> import ast >>>>> tree = ast.parse(code,
Every code object has attributes that holds information (they are prefixed by co_). I'll just mention a few of them.
co_name
First one is name. If it is a function it is going to be name of the function, for a class it is going to be name of the class. In AST example we're using modules so we can't actually tell compiler what we want this to be called so it's just going to be called
<module>.
>>> code.co_name '<module>' >>> say_hello.__code__.co_name 'say_hello'
co_varnames
It is a tuple that contains all your local variables (including arguments).
>>> say_hello.__code__.co_varnames ('name',)
co_consts
A tuple contains all of the literals or constant values that were referenced in the body of our function.
>>> say_hello.__code__.co_consts (None, 'Hello', 'How are you ', '?')
The only weired this is None among the values. We didn't put / include a None into our function body. The python puts it into there because if python is executing our function and it finishes executing without reaching any return statement it is going to return None.
The Bytecode (co_code)
This is the bytecode of the our function.
>>> bytecode = say_hello.__code__.co_code >>> bytecode b't\x00d\x01|\x00\x83\x02\x01\x00t\x00d\x02|\x00\x9b\x00d\x03\x9d\x03\x83\x01\x01\x00d\x00S\x00'
This is not a string, it is a byte object. A sequence of bytes.
>>> type(bytecode) <class 'bytes'>
The first byte printed a 't' char. When i look decimal value of that
>>> ord('t') 116
It is 116 same as bytecode[0]
>>> assert bytecode[0] == ord('t')
The 116 value doesn't mean anything to me. Fortunately python offers a standard library module called dis (comes from disassembly). It might help me with
opname list. It is a list of all bytecode instructions. Each index is the name of the instruction.
>>> dis.opname[ord('t')] 'LOAD_GLOBAL'
Lets create another function that makes more sense.
>>> def multiple_it(a: int): ... if a % 2 == 0: ... return 0 ... return a * 2 ... >>> multiple_it(6) 0 >>> multiple_it(7) 14 >>> bytecode = multiple_it.__code__.co_code
Lets check what is the first instruction of this bytecode.
>>> dis.opname[bytecode[0]] 'LOAD_FAST
The
LOAD_FAST instruction made of 2 elements.
>>> dis.opname[bytecode[0]] + ' ' + dis.opname[bytecode[1]] 'LOAD_FAST <0>'
Loadfast 0 is the instruction for, look up the variable names tuple and push 0 indexed element in tuple into evaluation stack.
>>> multiple_it.__code__.co_varnames[bytecode[1]] 'a'
Lets disassemble our code with
dis.dis and transform bytecode to human readable version.
>>> dis.dis(multiple_it) 2 0 LOAD_FAST 0 (a) 2 LOAD_CONST 1 (2) 4 BINARY_MODULO 6 LOAD_CONST 2 (0) 8 COMPARE_OP 2 (==) 10 POP_JUMP_IF_FALSE 16 3 12 LOAD_CONST 2 (0) 14 RETURN_VALUE 4 >> 16 LOAD_FAST 0 (a) 18 LOAD_CONST 1 (2) 20 BINARY_MULTIPLY 22 RETURN_VALUE
The numbers (2,3,4) stands for line numbers. Each line of python code turned into multiple instructions.
Execution Time
CPython is a stack-oriented virtual machine instead of registers. It means that python code is compiled for an imaginary (virtual) computer with a stack architecture.
Each time you make a function call you are pushing a call frame into call stack in python. When return statement happen that call frame gets popped from stack.
Python uses 2 stacks additionally when a function called. One is evaluation stack and the other one is the block stack. The most of call happens in evaluation stack and the block stack tracks how many active blocks right now and other things related with blocks and scopes._6<<
| https://dev.to/btaskaya/lifecycle-of-a-python-code---cpythons-execution-model-85i | CC-MAIN-2019-35 | refinedweb | 2,720 | 65.93 |
2012-05-25 02:39:51 8 Comments
I know that in C++11 we can now use
using to write type alias, like
typedefs:
typedef int MyInt;
Is, from what I understand, equivalent to:
using MyInt = int;
And that new syntax emerged from the effort to have a way to express "
template typedef":
template< class T > using MyType = AnotherType< T, MyAllocatorType >;
But, with the first two non-template examples, are there any other subtle differences in the standard? For example,
typedefs do aliasing in a "weak" way. That is it does not create a new type but only a new name (conversions are implicit between those names).
Is it the same with
using or does it generate a new type? Are there any differences?
Related Questions
Sponsored Content
28 Answered Questions
[SOLVED] What is the difference between #include <filename> and #include "filename"?
- 2008-08-22 01:40:06
- quest49
- 598233 View
- 2378 Score
- 28 Answer
- Tags: c++ c include header-files c-preprocessor
24 Answered Questions
[SOLVED] What is the "-->" operator in C++?
- 2009-10-29 06:57:45
- GManNickG
- 798974 View
- 8973 Score
- 24 Answer
- Tags: c++ c operators code-formatting standards-compliance
40 Answered Questions
[SOLVED] What are the differences between a pointer variable and a reference variable in C++?
11 Answered Questions
[SOLVED] What does the explicit keyword mean?
- 2008-09-23 13:58:45
- Skizz
- 868821 View
- 2945 Score
- 11 Answer
- Tags: c++ constructor explicit c++-faq explicit-constructor
9 Answered Questions
[SOLVED] What is a lambda expression in C++11?
13 Answered Questions
[SOLVED] What is a smart pointer and when should I use one?
- 2008-09-20 00:09:24
- Alex Reynolds
- 574265 View
- 1835 Score
- 13 Answer
- Tags: c++ pointers c++11 smart-pointers c++-faq
12 Answered Questions
[SOLVED] What is move semantics?
- 2010-06-23 22:46:46
- dicroce
- 425617 View
- 1718 Score
- 12 Answer
- Tags: c++ c++-faq c++11 move-semantics
13 Answered Questions
[SOLVED] What is a typedef enum in Objective-C?
- 2009-04-01 21:59:43
- Craig
- 433281 View
- 1087 Score
- 13 Answer
- Tags: objective-c enums typedef
8 Answered Questions
[SOLVED] Difference between 'struct' and 'typedef struct' in C++?
8 Answered Questions
[SOLVED] C++11 introduced a standardized memory model. What does it mean? And how is it going to affect C++ programming?
- 2011-06-11 23:30:14
- Nawaz
- 226110 View
- 1908 Score
- 8 Answer
- Tags: c++ multithreading c++11 language-lawyer memory-model
@dfri 2020-06-04 13:50:18
All standard references below refers to N4659: March 2017 post-Kona working draft/C++17 DIS.
Typedef declarations can, whereas alias declarations cannot, be used as initialization statements
As governed by [dcl.typedef]/2 [extract, emphasis mine]
a typedef-name introduced by an alias-declaration has the same semantics is if it were introduced by the
typedefdeclaration.
However, this does not imply that the two variations have the same restrictions w.r.t. in which contexts they may be used. And indeed, albeit a corner case, a typedef declaration is an init-statement and may thus be used in contexts which allows initialization statements
whereas an alias-declaration is not an init-statement, and may thus not be used in contexts which allows initialization statements
@Klaim 2020-06-30 22:38:01
Wow, my intuition was right in the end! There is a difference! Thanks for finding that difference, it's the kind of very very narrow detail that can make a difference in the kind of code I work with (unfortunately XD).
@marski 2019-12-02 22:23:42
Both keywords are equivalent, but there are a few caveats. One is that declaring a function pointer with
using T = int (*)(int, int);is clearer than with
typedef int (*T)(int, int);. Second is that template alias form is not possible with
typedef. Third is that exposing C API would require
typedefin public headers.
@RoboticForest 2019-06-12 02:59:59
I know the original poster has a great answer, but for anyone stumbling on this thread like I have there's an important note from the proposal that I think adds something of value to the discussion here, particularly to concerns in the comments about if the
typedefkeyword is going to be marked as deprecated in the future, or removed for being redundant/old:
To me, this implies continued support for the
typedefkeyword in C++ because it can still make code more readable and understandable.
Updating the
usingkeyword was specifically for templates, and (as was pointed out in the accepted answer) when you are working with non-templates
usingand
typedefare mechanically identical, so the choice is totally up to the programmer on the grounds of readability and communication of intent.
@Zhongming Qu 2015-10-05 22:58:29
They are largely the same, except that:
@g24l 2015-11-12 13:34:56
Particularly fond of the simplicity of the answer and pointing out the origin of typeset.
@Marc.2377 2019-09-14 05:23:27
@g24l you mean typedef... probably
@McSinyx 2019-12-16 11:03:24
What is the difference between C and C++ in
typedefif I may ask?
@Klaim 2020-06-30 22:36:32
This is not answering the question though. I already know that difference and pointed at in the original post. I was asking only about the case where you don't use templates, is there differences.
@Validus Oculus 2018-03-31 08:20:30
They are essentially the same but
usingprovides
alias templateswhich is quite useful. One good example I could find is as follows:
So, we can use
std::add_const_t<T>instead of
typename std::add_const<T>::type
@someonewithpc 2019-03-10 16:15:11
As far as I know, it's undefined behavior to add anything inside the std namespace
@Validus Oculus 2019-03-11 02:18:40
@someonewithpc I was not adding anything, it already exists, I was just showing an example of typename usage. Please check en.cppreference.com/w/cpp/types/add_cv
@4xy 2014-04-21 11:39:59
The using syntax has an advantage when used within templates. If you need the type abstraction, but also need to keep template parameter to be possible to be specified in future. You should write something like this.
But using syntax simplifies this use case.
@Klaim 2014-05-02 19:57:40
I already pointed this in the question though. My question is about if you don't use template is there any difference with typedef. As, for example, when you use 'Foo foo{init_value};' instead of 'Foo foo(init_value)' both are supposed to do the same thing but don't foillow exactly the same rules. So I was wondering if there was a similar hidden difference with using/typedef.
@Jesse Good 2012-05-25 03:16:42
They are equivalent, from the standard (emphasis mine) (7.1.3.2):
@iammilind 2012-05-25 04:28:14
From the answer,
usingkeyword seems to be a superset of
typedef. Then, will
typdefbe deprecated in future ?
@Klaim 2012-05-25 05:11:26
@iammilind I don't think so as it is part of C and certainly will not be removed from it. Also, C++11 and future versions will still keep maximum compatibility with our current code...
@Iron Savior 2013-04-20 20:37:40
Deprecation doesn't necessarily indicate intent to remove--It merely stands as a very strong recommendation to prefer another means.
@TemplateRex 2013-05-09 21:59:01
@iammilind
typedefis unlikely to become extinct. For one, the current Standard Library design guidelines have a clause "where C++ 2003 syntax can be used, they are preferred over C++ 2011 features". Of course, in user code no such restrictions apply.
@celtschk 2013-07-21 09:44:23
But then I wonder why they didn't just allow typedef to be templated. I remember having read somewhere that they introduced the
usingsyntax precisely because the
typedefsemantics didn't work well with templates. Which somehow contradicts the fact that
usingis defined to have exactly the same semantics.
@Jesse Good 2013-07-21 22:19:07
@celtschk: The reason is talked about in the proposal
n1489. A template alias is not an alias for a type, but an alias for a group of templates. To make a distinction between
typedefthe felt a need for new syntax. Also, keep in mind the OP's question is about the difference between non-template versions.
@davidA 2014-05-08 02:13:55
What about with template-templates? A typedef for one of the template template parameters doesn't appear to be suitable as the typedef isn't correct unless it itself has template parameters specified. Can the type alias be used here, or is it equivalent to a typedef in this case (and can't be used)? Or is the solution to this a template type alias? That's a difference between a type alias and a typedef then, yes?
@Benoît 2017-04-29 20:31:53
So why this redundancy whas introduced ? 2 syntaxes for the same purpose. And I don't see
typdefbeing deprecated ever.
@amirali 2020-06-01 06:25:43
I have had an experience which
usingwas faster than
typedef. | https://tutel.me/c/programming/questions/10747810/what+is+the+difference+between+39typedef39+and+39using39+in+c11 | CC-MAIN-2020-29 | refinedweb | 1,537 | 61.36 |
Type: Posts; User: vishalon
OK
Now I have this code very simple and plain which is giving fine output. As I am passing the array of object in showAge function.
#include <iostream.h>
#include <conio.h>
class fish
{
...
Hello Everybody
This is my question
Define a class named HOUSING in C++ with the following descriptions:
Private members
REG_NO integer(Ranges...
OK Paul can you give some guidance where I can get good tutorial on the topic I am looking for that is Using MySQL database from C++
Dear Paul McKenzie thank you for considering and reply. I am not friendly with C++, I'm learning C++
While compiling the code,compiler is complaining
Hello
I am trying to connect MySQL database from C++ code given below-
My development environment is -
Window 7
CODE::BLOCKS 10.05 with minGW mingw32-g++.exe
MySQL Connector C++...
Hi
I am learning JDBC with MS SQL Server 2005. I wrote a simple code in Java 1.6
This is my code in MainJdbc1.java
import java.sql.*;
public class MainJdbc1
{
public static void... | http://forums.codeguru.com/search.php?s=a1348f0650e3f5faeaf7729125c980a7&searchid=8422847 | CC-MAIN-2016-07 | refinedweb | 179 | 67.86 |
mandax Posted February 13, 2011 Firstly - I'm a long time Skulltag player, I love ST and I want to continue to play it, therefore I would like to remain anonymous. Consider this post an act of whistleblowing that will hopefully help improve the port in the end. Some of you might remember the csDoom backdoor incident. The creator of csDoom (Fly) added a backdoor to the server binaries which would grant him RCON rights on any server. A similar backdoor was implemented by Carnevil as can be seen in the recently released 0.97c2 source code. sv_admin.cpp: Here we can see Carnevils hardcoded IP address and a function that will return true, if a given address is included in the Adminlist! Note that this code was written with expandability in mind. void SERVER_ADMIN_Construct( void ) { g_AdminList[ADMIN_CARNEVIL].Address.ip[0] = 24; g_AdminList[ADMIN_CARNEVIL].Address.ip[1] = 242; g_AdminList[ADMIN_CARNEVIL].Address.ip[2] = 214; g_AdminList[ADMIN_CARNEVIL].Address.ip[3] = 13; } bool SERVER_ADMIN_IsAdministrator( netadr_t Address ) { ULONG ulIdx; for ( ulIdx = 0; ulIdx < NUM_ADMINS; ulIdx++ ) { if ( NETWORK_CompareAddress( g_AdminList[ulIdx].Address, Address, true )) return ( true ); } return ( false ); } Let us have a look where this function is used and what IP addresses listed in the secret Adminlist can do: all of the following code is from sv_main.cpp: They cannot be banned from the server!if (( sv_enforcebans ) && ( SERVERBAN_IsIPBanned( szAddress[0], szAddress[1], szAddress[2], szAddress[3] )) && ( SERVER_ADMIN_IsAdministrator( clients[lClient].address ) == false )) { // Client has been banned! GET THE FUCK OUT OF HERE! SERVER_ClientError( lClient, NETWORK_ERRORCODE_BANNED ); return; } They can issue "silent" RCON commands that will not be printed.// If they don't have RCON access, and aren't an adminstrator, deny them the ability to do this. if (( clients[parse_cl].bRCONAccess == false ) && ( SERVER_ADMIN_IsAdministrator( clients[parse_cl].address ) == false )) return ( false ); // Admins can operate incognito. if ( SERVER_ADMIN_IsAdministrator( clients[parse_cl].address ) == false ) Printf( "%s RCON (%s)\n", players[parse_cl].userinfo.netname, pszCommand ); They cannot be kicked from the game or server!if ( stricmp( szPlayerName, argv[1] ) == 0 ) { if ( SERVER_ADMIN_IsAdministrator( clients[ulIdx].address )) continue; // If we provided a reason, give it. if ( argv.argc( ) >= 3 ) SERVER_KickPlayer( ulIdx, argv[2] ); else SERVER_KickPlayer( ulIdx, "None given." ); return; } if ( stricmp( szPlayerName, argv[1] ) == 0 ) { if ( SERVER_ADMIN_IsAdministrator( clients[ulIdx].address )) continue; // Already a spectator! if ( PLAYER_IsTrueSpectator( &players[parse_cl] )) continue; // If we provided a reason, give it. if ( argv.argc( ) >= 3 ) SERVER_KickPlayerFromGame( ulIdx, argv[2] ); else SERVER_KickPlayerFromGame( ulIdx, "None given" ); return; } All of the above probably applies to ScoreDoomST, which is based on 0.97c2, as well. Now this backdoor might or might not be present in the current ST source code. What caught my eye though in the recent changelog was the implementation of a server-side whitelist and adminlist, with similar functionality, meant for server hosts only. For more details check out the Wiki. The Skulltag master-server is distributing a global banlist to all servers. As this and this post suggest a global whitelist is distributed as well. Now what if all the server-side lists have been implemented at the global level and the master-server is also distributing a secret adminlist to all servers (maybe the global adminlist IP checks are done directly on the master though)? If a backdoor of any kind is still present it would be a huge security risk and massive breach of trust between server hosts and the ST administration. Someone who is skilled in Reverse Engineering might want to check the current server master communication for a 'third list' or other suspicious queries to confirm my worries. An official statement from the administration confirming or disputing the existence of a "master adminlist" or any other form of backdoor could clear things up. Since Skulltag is closed source we ultimately have to trust the official statement from the administration. Releasing older source code so we can at least see since when the backdoor was present would be a first step. I guess this incident will make the administration cautious to remove incriminating code from future source code releases though. Some viable options to regain trust would be to go fully open source or allow some neutral members from the DooM community to review the code in person by visiting one of the developers IRL. I know that some prominent figures from the doom community, like AlexMax, Ladna, Gez and Graf Zahl, are actively pushing for Skulltag to be open sourced. Ladna said it best in the previously linked altdeath thread:ST keeping a current, open-source version would at least prevent something like the current situation with ZDaemon by allowing us the "fuck you jerks" option. He is absolutely right! The players should have all the power. The programmers should just do their job and write code instead. If the programmers or admins try to deceive the players the project can be forked easily! I would be very pleased if ST became a truly free port like Odamex and they could finally share code and join forces! Maybe this negative incident here can be turned into something positive and accelerate that process. 0 Share this post Link to post | https://www.doomworld.com/forum/topic/54352-skulltag-097c2-server-backdoor/?tab=comments | CC-MAIN-2018-39 | refinedweb | 843 | 57.06 |
I have recently started learning java.I want to make a game like I have made it in c++ once using a simple graphics lib. I have the graphics part down i plan to use small images and use this basic graphics lib.I can't figure out keyboard input i want it so if you press an arrow the picture adds a small green square(I have a green.png).I can't figure out to use keyboard listeners.I get all these errors.I just need a simple lib that i can say getKey() or something and i can use if() to figure out the action.this is the code I have.I was messing with the key event but don't understand it.
import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.*; public class game implements KeyListener { public void keyReleased(KeyEvent e){} public void keyTyped(KeyEvent e){} public game()//snake like game { } public void test() { int x=30,y=30;//middle total 60x60 tile[] map=new tile[3600];//tile is a class i made that is a picture and some int and bool using the simple lib i linked 60 by 60 tiles for(int i=0;i<3600;i++) { map[i]=new tile(); } } public void keyPressed(KeyEvent e)//this does not work i want it to work when a key is clicked { while(x>0)//this part works when it is not in the keypressed function { map[(y*60)+x].load(4);//4 refrences a green rectangle image map[(y*60)+x].draw(x,y,10);//draw it based on x and y 10 pixels sized tiles x--;//make a line going left } } }
I know this may be messy.I have tested my code it works it just breaks when i try to implement keyboard events.If you can point me to a much more beginner friendly lib that would be great.
You simply have to add the listener to something (e.g. the window where the game is being played).
I will give you an example, where we will simply display the code of the key being stroked.
This is the class where you produce the interface:
import java.awt.Dimension; import javax.swing.JFrame; public class Game { public static void main(String[] args) { /* Creating a window (300x400) */ JFrame frame = new JFrame("Add your own title"); frame.setPreferredSize(new Dimension(300, 400)); /* This is the part where we add the keyListener (notice that I am also sending * this window as a parameter so that the listener can modify it)*/ frame.addKeyListener(new ArrowListener(frame)); /* Making the window visible */ frame.pack(); frame.setVisible(true); } }
And this is the class where we have the listener:
import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JLabel; public class ArrowListener implements KeyListener { /* We keep the window as an instance variable so we can modify it once the event is triggered */ JFrame frame; /* This is the constructor */ public ArrowListener(JFrame j) { frame = j; } /* This is where the magic happens */ public void keyPressed(KeyEvent e) { /* Modify this with what you actually want it to do */ /* We clear the panel so we can add new text without any other text behind it */ frame.getContentPane().removeAll(); /* We add some text that actually shows the keyCode (left arrow = 37, top = 38, right = 39, bottom = 40) */ frame.add(new JLabel("Key Code #" + String.valueOf(e.getKeyCode()))); /* Redrawing the window */ frame.revalidate(); } /* These two are part of the contract we made when we decided to * implement the KeyListener */ public void keyTyped(KeyEvent e) { /* Do nothing */ } public void keyReleased(KeyEvent e) { /* Do nothing */ } }
Note: when running the program press the keys to see the text appearing on the window.
I didn't get around the library you were using, but I used the most popular one called swing (tutorial) | http://databasefaq.com/index.php/answer/68668/java-computer-science-keylistener-keyevent-keyboard-events-java | CC-MAIN-2018-51 | refinedweb | 647 | 72.46 |
Core.
"Kroah-Hartman says he’s been wanting to build something like CoreOS for over half a decade," writes Cade Metz in a recent Wired article featuring CoreOS.
At the heart of this functionality is cgroup -- the Linux kernel subsystem that allows process containers for resource partitioning. CoreOS CTO Brandon Philips will speak at LinuxCon and CloudOpen in New Orleans next week about cgroup.
"Until recently the only true way to isolate Linux apps from each other was with a hypervisor like KVM," Philips said. "With containers we get that isolation and ability to programmatically turn on and off virtual machines. But, they come online faster and use far fewer resources."
Here he previews his talk and discusses the benefits of CoreOS for sysadmins and developers; how CoreOS uses cgroups and systemd; how the cgroup redesign might affect CoreOS; and poses his questions for Linux kernel developers in advance of their panel discussion at LinuxCon and CloudOpen.
What is CoreOS in a nutshell, for those who are unfamiliar (or didn’t read the Wired article)?
It’s a new Linux operating system focused on creating a Linux that’s more tuned for people with up to hundreds of thousands of servers. A lot of the problems they encounter are those that Facebook or Google have already solved. They have lots of machines and developers and need to be really efficient and automate tasks. CoreOS does things a lot differently than other Linux distros.
For example: /etc is where configuration files are stored on a Linux machine. We have created etcd, a dameon that runs across all machines to share configuration data. It’s a simple API and operationally simple.
What are the benefits of CoreOS for a sysadmin? For an application developer?
For a lot of teams already doing distributed systems, this isn’t new to them. But having a dynamic registry running across your machines instead of running a bunch of static config files means you can just write into the service registry and all the machines in the cluster have access to that.
How does CoreOS utilize cgroups and systemd?
Really the fundamental difference between CoreOS and what people are used to, is that we don’t have a package manager. Instead we use containers. What makes it possible are cgroups and namespaces. Cgroups has the ability to meter and isolate the amount of hardware resources the individual container is able to use. And with cgroups we can run production and development software at the same time because dev can have a lot lower priority. We can safely deploy containers across machines that aren’t necessarily production.
How will the cgroup redesign affect what you’re trying to accomplish with CoreOS?
In the long run it will probably help us. CoreOS is built on top of systemd, and essentially the big change in cgroups is moving away from a file system where anybody can manipulate that file system from having a gateway API. The current implementation that exists is systemd and we’ve bought into systemd. We had no intentions of using anything other than systemd.
Why do you need a new operating system to accomplish this for application servers? Why not build within another distro?
A big piece that caused us to take pause and create our own distro is we wanted to do updates quite a bit differently. Taking inspiration from Chrome OS, we have two file systems A and B. While a Linux system is running on A you can make offline changes in the B system. As soon as you’re ready to upgrade you reboot the machine. This double buffered update gives you a couple of advantages. Things are completely atomic, you don’t want a server to ever be in a state where things are unknown. A classic package manager will modify files all over your system while you’re doing your upgrade, this means many daemons could be in any unstable state at any point.
You want to make sure code is up to date and control rollouts so they don’t happen during some critical time for the application. It shouldn’t be something a sysadmin should worry about every day. We wanted to make that a core piece of the distro.
If you could ask the kernel developers on stage at LinuxCon anything, what would it be?
I really think dbus is an interesting thing happening within both kernel and user space. Cgroups started as a file system and you realized a file system isn’t going to cut it. A lot of the new cgroups functionality is exposed to dbus in its first implementation. There’s talk of adding dbus into the kernel. I’m interested to hear where people think file systems today aren’t cutting it and where userspace dbus enabled daemons might be useful for future APIs.
Also, now that we are having to invent new APIs and syscalls that haven't existed in other unix-like systems how do you feel about versioning APIs/ABIs or providing API previews to application/library developers to make sure we are on the right path with a given design?
Can you give us a preview of your talk at LinuxCon?
My talk won’t be about CoreOS at all, it’s just the product I’m working on. It’s familiarizing people and giving an overview of technologies that have made it possible to think of Linux and Linux servers as a hypervisor for containers and what functionality that gives you.
Until recently the only true way to isolate Linux apps from each other was with a hypervisor like KVM. With containers we get that isolation and ability to programmatically turn on and off virtual machines. But, they come online faster and use far fewer resources. I’ll give people practical examples of how to use cgroups to monitor apps or isolate them or use namespaces to increase security and isolate things from the network and the file system. It’s more of a practical guide to these newer APIs and functionality. | https://www.linux.com/news/featured-blogs/200-libby-clark/737364-brandon-philips-how-the-coreos-linux-distro-uses-cgroups/ | CC-MAIN-2014-15 | refinedweb | 1,015 | 62.68 |
. It has operators that modify graphics states, which, from a high-level look something like:
This explains a few things:
In this guide, we'll be using borb - a Python library dedicated to reading, manipulating and generating PDF documents, to create a PDF document. It offers both a low-level model (allowing you access to the exact coordinates and layout if you choose to use those) and a high-level model (where you can delegate the precise calculations of margins, positions, etc to a layout manager).
We'll take a look at how to create and inspect a PDF document in Python, using borb, as well as how to use some of the
LayoutElements to add barcodes and tables.
borb can be downloaded from source on GitHub, or installed via
pip:
$ pip install borb
borb has two intuitive key classes -
Document and
Page, which represent a document and the pages within it. These are the main framework for creating PDF documents.
Additionally, the
Documents we create.
With that in mind, let's create an empty PDF file:
from borb.pdf.document import Document from borb.pdf.page.page import Page from borb.pdf.pdf import PDF # Create an empty Document document = Document() # Create an empty page page = Page() # Add the Page to the Document document.append_page(page) # Write the Document to a file with open("output.pdf", "wb") as pdf_file_handle: PDF.dumps(pdf_file_handle, document)
Most of the code speaks for itself here. We start by creating an empty
Document, then add an empty
Page to the
Document with the
append() function, and finally store the file through
PDF.dumps().
It's worth noting that we used the
"wb" flag to write in binary mode, since we don't want Python to encode this text.
This results in an empty PDF file, named
output.pdf on your local file system:
Of course, empty PDF documents don't really convey a lot of information. Let's add some content to the
Page , before we add it to the
Document instance.
In a similar vein to the two integral classes from before, to add content to the
Page, we'll add a
PageLayout which specifies the type of layout we'd like to see, and add one or more
Paragraphs to that layout.
To this end, the
Document is the lowest-level instance in the hierarchy of objects, while the
Paragraph is the highest-level instance, stacked on top of the
PageLayout and consequently, the
Page.
Let's add a
Paragraph to our
Page:
from borb.pdf.document import Document from borb.pdf.page.page import Page from borb.pdf.pdf import PDF from borb.pdf.canvas.layout.paragraph import Paragraph from borb.pdf.canvas.layout.page_layout.multi_column_layout import SingleColumnLayout from borb.io.read.types import Decimal document = Document() page = Page() # Setting a layout manager on the Page layout = SingleColumnLayout(page) # Adding a Paragraph to the Page layout.add(Paragraph("Hello World", font_size=Decimal(20), font="Helvetica")) document.append_page(page) with open("output.pdf", "wb") as pdf_file_handle: PDF.dumps(pdf_file_handle, document)
You'll notice we added 2 extra objects:
PageLayout, made more concrete through its subclass
SingleColumnLayout: this class keeps track of where content is being added to a
Page, which area(s) are available for future content, what the
Pagemargins are, and what the leading (the space between
Paragraphobjects) is supposed to be.
Since we're only working with one column here, we're using a
SingleColumnLayout. Alternatively, we can use the
MultiColumnLayout.
Paragraphinstance: this class represents a block of text. You can set properties such as the font, font_size, font_color, and many others. For more examples, you should check out the documentation.
This generates an
output.pdf file that contains our
Paragraph:
Note: This section is completely optional if you are not interested in the inner workings of a PDF document. But it can be very useful to know a bit about the format (such as when you're debugging the classic "why does my content now show up on this page" issue). Typically, a PDF reader will read the document starting at the last bytes:
xref 0 11 0000000000 00000 f 0000000015 00000 n 0000002169 00000 n 0000000048 00000 n 0000000105 00000 n 0000000258 00000 n 0000000413 00000 n 0000000445 00000 n 0000000475 00000 n 0000000653 00000 n 0000001938 00000 n trailer <<61e6d144af4b84e0e0aa52deab87cfe9>]>> startxref 2274 %%EOF
Here we see the end-of-file marker (
%%EOF) and the cross-reference-table (typically abbreviated to
xref).
The
xrefis delimited by the tokens
"startxref"and
"xref".
An
xref (a document can have multiple) acts as a lookup table for the PDF reader.
It contains the byte offset (starting at the top of the file) of each object in a PDF. The first line of the
xref (
0 11) says there are 11 objects in this
xref, and that the first object starts at number 0.
Each subsequent line consists of the byte offset, followed by the so called generation number and the letter
f or
n:
fare free objects, they are not expected to be rendered.
nare "in use".
At the bottom of the
xref, we find the trailer dictionary. Dictionaries, in PDF syntax, are delimited by
<< and
>>.
This dictionary has the following pairs:
/Root 1 0 R
/Info 2 0 R
/Size 11
/ID [<61e6d144af4b84e0e0aa52deab87cfe9> <61e6d144af4b84e0e0aa52deab87cfe9>]
The trailer dictionary is the starting point for the PDF reader and contains references to all other data. In this case:
/Root: this is another dictionary that links to the actual content of the document.
/Info: this is a dictionary containing meta-information of the document (author, title, etc).
Strings like
1 0 R are called "references" in PDF syntax. And this is where the
xref table comes in handy.
To find the object associated with
1 0 R we look at object 1 (generation number 0).
The
xref lookup table tells us we can expect to find this object at byte 15 of the document.
If we check that out, we'll find:
1 0 obj <> endobj
Notice how this object starts with
1 0 obj and ends with
endobj. This is another confirmation that we are in fact dealing with object 1.
This dictionary tells us we can find the pages of the document in object 3:
3 0 obj <> endobj
This is the
/Pages dictionary, and it tells us there is 1 page in this document (the
/Count entry). The entry for
/Kids is typically an array, with one object-reference per page.
We can expect to find the first page in object 4:
4 0 obj <> endobj
This dictionary contains several interesting entries:
/MediaBox: physical dimensions of the page (in this case an A4 sized page).
/Contents: reference to a (typically compressed) stream of PDF content operators.
/Resources: reference to a dictionary containing all the resources (fonts, images, etc) used for rendering this page.
Let's check out object 5 to find what is actually being rendered on this page:
5 0 obj <> stream xÚã[email protected] \È<§®`a¥£šÔw3T0É €!K¡š3Benl7'§9©99ù åùE9) !Y(®!8õÂyšT*î endstream endobj
As mentioned earlier, this (content) stream is compressed. You can tell which compression method was used by the
/Filter entry. If we apply decompression (
unzip) to object 5, we should get the actual content operators:
5 0 obj <> stream q BT 0.000000 0.000000 0.000000 rg /F1 1.000000 Tf 20.000000 0 0 20.000000 60.000000 738.000000 Tm (Hello world) Tj ET Q endstream endobj
Finally, we are at the level where we can decode the content. Each line consists of arguments followed by their operator. Let's quickly go over the operators:
q: preserves the current graphic state (pushing it to a stack).
BT: begin text.
0 0 0 rg: set the current stroke color to (
0,0,0) rgb. This is black.
/F1 1 Tf: set the current font to
/F1(this is an entry in the resources dictionary mentioned earlier) and the font size to
1.
20.000000 0 0 20.000000 60.000000 738.000000 Tm: set the text-matrix. Text matrices warrant a guide of their own. Suffice to say that this matrix regulates font size, and text position. Here we are scaling the font to
font-size 20, and setting the text-drawing cursor to
60,738. The PDF coordinate system starts at the bottom left of a page. So
60,738is somewhere near the left top of the page (considering the page was
842units tall).
(Hello world) Tj: strings in PDF syntax are delimited by
(and
). This command tells the PDF reader to render the string "Hello world" at the position we indicated earlier with the text-matrix, in the font, size and color we specified in the commands before that.
ET: end text.
Q: pop the graphics state from the stack (thus restoring the graphics state).
borb comes with a wide variety of
LayoutElement objects. In the previous example we briefly explored
Paragraph. But there's also other elements such as
UnorderedList,
OrderedList,
Image,
Shape,
Barcode and
Table.
Let's create a slightly more challenging example, with a
Table and
Barcode.
Tables consist of
TableCells, which we add to the
Table instance.
A
Barcode can be one of many
BarcodeTypes - we'll be using a
QR code:
from borb.pdf.document import Document from borb.pdf.page.page import Page from borb.pdf.pdf import PDF from borb.pdf.canvas.layout.paragraph import Paragraph from borb.pdf.canvas.layout.page_layout import SingleColumnLayout from borb.io.read.types import Decimal from borb.pdf.canvas.layout.table import Table, TableCell from borb.pdf.canvas.layout.barcode import Barcode, BarcodeType from borb.pdf.canvas.color.color import X11Color document = Document() page = Page() # Layout layout = SingleColumnLayout(page) # Create and add heading layout.add(Paragraph("DefaultCorp Invoice", font="Helvetica", font_size=Decimal(20))) # Create and add barcode layout.add(Barcode(data="0123456789", type=BarcodeType.QR, width=Decimal(64), height=Decimal(64))) # Create and add table table = Table(number_of_rows=5, number_of_columns=4) # Header row table.add(TableCell(Paragraph("Item", font_color=X11Color("White")), background_color=X11Color("SlateGray"))) table.add(TableCell(Paragraph("Unit Price", font_color=X11Color("White")), background_color=X11Color("SlateGray"))) table.add(TableCell(Paragraph("Amount", font_color=X11Color("White")), background_color=X11Color("SlateGray"))) table.add(TableCell(Paragraph("Price", font_color=X11Color("White")), background_color=X11Color("SlateGray"))) # Data rows for n in [("Lorem", 4.99, 1), ("Ipsum", 9.99, 2), ("Dolor", 1.99, 3), ("Sit", 1.99, 1)]: table.add(Paragraph(n[0])) table.add(Paragraph(str(n[1]))) table.add(Paragraph(str(n[2]))) table.add(Paragraph(str(n[1] * n[2]))) # Set padding table.set_padding_on_all_cells(Decimal(5), Decimal(5), Decimal(5), Decimal(5)) layout.add(table) # Append page document.append_page(page) # Persist PDF to file with open("output4.pdf", "wb") as pdf_file_handle: PDF.dumps(pdf_file_handle, document)
Some implementation details:
borbsupports various color models, including:
RGBColor,
HexColor,
X11Colorand
HSVColor.
LayoutElementobjects directly to a
Tableobject, but you can also wrap them with a
TableCellobject, this gives you some extra options, such as setting
col_spanand
row_spanor in this case,
background_color.
font,
font_sizeor
font_colorare specified,
Paragraphwill assume a default of
Helvetica,
size 12,
black.
This results in:
In this guide, we've taken a look at borb, a library for reading, writing and manipulating PDF files.
We've taken a look at the key classes such as
Document and
Page, as well as some of the elements such as
Paragraph,
Barcode and
PageLayout. Finally, we've created a couple of PDF files with varying contents, as well as inspected how PDFs store data under the hood. | https://www.codevelop.art/creating-a-pdf-document-in-python-with-borb.html | CC-MAIN-2022-40 | refinedweb | 1,920 | 57.57 |
“A direct byte buffer may be created by invoking the allocateDirect factory method of this class. The buffers returned by this method typically have somewhat higher allocation and deallocation costs than non-direct buffers. measureable gain in program performance.”.
I don’t follow this explanation – the Off-heap implementation is calling:
@Override
public byte getByte() {
return unsafe.getByte(pos + byte_offset);
}
the DirectMeomoryBuffer implementation is calling:
public byte More …get() {
return ((unsafe.getByte(ix(nextGetIndex()))));
}
Where is the “bringing memory to heap space” happening in DMB vs off heap objects?.
I have one further question based on the article presented here:
It seems to me you are using the same technique to access Off-heap memory, and yet you experience much better results, clearly unaffected by the JNI calls. Could you explain why that might be the case?
My this article was as part of curiosity from the article you mention above, i have commented on it with my result before writing this blog!
Difference is that i am allocating one big array for all the objects and the blog that you mention allocate memory per object
Allocating one big array has lot of nice benefit
– Predictable memory access
– Most of the data will be prefetched
This type of allocation will be more cpu cache friendly.
It seem that your implementation of HeapAllocatedObject is not apple-to-apple comparison, as you added extra layer HeapValue and caused addition index-lookup and memory fragmentation.
As the Object construct and GC are only happen in HeapAllocatedObject, but not others. it supposed to be slowest.
One of the reason to write this blog is to share the overhead you have with plain java object.
Heapvalue will have all the overhead that is associated with any object due to layout used by java, all the heap allocation will have GC overhead also and direct memory is free from it and that is one of the big reason of write speed you get with direct memory.
Bytebuffer shows interesting result , it has worst write performance although it is just backed by bytearray and most compact way to store data on heap.
Access by index is not adding any significant overhead.
Thanks for your interesting posts. So what is the reason caused ByteBuffer slower than Heap in both read and write performance?
I have to do some more investigation to workout the cause, but some of the factor to consider are
– for ByteBuffer data is stored in bytearray , so every time you ask for long fair bit of shift operation happens for converting byte to Long value because of bigEndian/littleendian on both read & write side.
– Another thing to consider can be bigEndian/littleendian, for littleendian byte array is read in reverse order(8th byte to 1th byte), so there is high chance that CPU prefetchers are not of much use, i have not benchmarked this assumption
The Unsafe is (btw) just like memcpy(&arr, (char*)&integer, 4);
You cannot compare this to manual encoding (like bitshifting…).
I mean the ByteBuffer which located on heap, not the directBuffer, so there is no unsafe usage.
“This is almost same as Direct ByteBuffer but with little different, it can be allocated by unsafe.allocateMemory, as it is direct memory so it creates no GC overhead”
Should’ve explained this properly. You are showing huge differences in results, but describing as “little different”. Shows you also don’t know much about it.
“C/C++ community will not like it”
Shows your immaturity… why on earth they won’t like it.
That sentence was more from API usage point of view not on real result. I not expert in this area, i am just sharing my observation and if you don’t like it then it is fine. It would be nice if you can share your experience with Direct Bytebuffer.
Regarding C/C++ community you missed the whole context
Would you be willing to share the code you used for this test? I performed a similar test, but using 100M int primitives, and found on-heap (via int[]) to be fastest for both read and write. I’d be curious to see where the difference lies. I suspect your more complex data structure might kill on-heap due to additional pointer redirection and loss of locality, but as always, the devil’s in the details.
As for my own version of the test, I’ve just started looking at output from -XX:+PrintAssembly but it seems like the JIT is better able to optimize serialized array access than the other forms. Of course, this has implications for real applications with more random access patterns, but that’s why they always say microbenchmarking is so difficult, especially in Java.
My test environment is:
OS : Ubuntu 14.04
JDK : OpenJDK 1.7.0_91
CPU: Xeon E5-1650
Measured average time per item over 100M integers is as follows…
Writes:
int[] – 0.952ns = 1050 Mops/sec
Unsafe – 1.228ns = 814 Mops/sec
direct ByteBuffer – 1.328ns = 753 Mops/sec
heap ByteBuffer – 1.886ns = 530 Mops/sec
Reads:
int[] – 0.502ns = 1992 Mops/sec
Unsafe – 0.872ns = 1146 Mops/sec
direct ByteBuffer – 0.944ns = 1059 Mops/sec
heap ByteBuffer – 2.175ns = 459 Mops/sec
I’ve posted the source of my test here:
I’ve placed each individual test into a single method and all are static in an effort to maximize compile-time optimizations. The only method calls I make are to the framework classes such as ByteBuffer. Like you, I sum the values while reading (and set that result to a volatile) to ensure the reads aren’t optimized away.
Out of curiosity I downloaded your code and ran it in my environment with 100M objects on a 16GB heap (same as I used for mine)…
Writes:
HEAP – 146 Mops/sec
OFFHEAP – 310 Mops/sec
DBB – 323 Mops/sec
BB – 110 Mops/sec
Reads:
HEAP – 267 Mops/sec
OFFHEAP – 514 Mops/sec
DBB – 293 Mops/sec
BB – 110 Mops/sec
Of note, I never came anywhere near 12000 Mops/sec. Nor would I expect it to be possible: if each object is 13 bytes, as in your example, that would amount to 156 GB/sec, which is far more than any current CPU’s memory bandwidth. You may want to recheck those values.
It does make sense to me that a primitive array would perform far better than a reference array, and it will be similarly interesting to see how these numbers change once Java 9 value types are a thing. With those, the objects themselves can be in the array, avoiding having to dereference two pointers for each access and the corresponding loss of locality. The array will look much more like the packed bytes in the unsafe blob. | https://www.javacodegeeks.com/2013/08/which-memory-is-faster-heap-or-bytebuffer-or-direct.html | CC-MAIN-2017-04 | refinedweb | 1,128 | 60.35 |
XML Namespaces let you place a set of XML elements inside a separate "area" to avoid tag name clashes. This is an important feature because it allows XML documents to be extended and combined. Unfortunately, using XML namespaces is tricky. For something that initially seems very straightforward, there's a surprising amount of explanation required.
Using XML Namespaces, developers can work together to define a common set of markup for different sets of data, such as RSS items, meta-information about pages on the Internet, or books. When programmers everywhere represent related information using the same set of elements in the same namespace, then everyone can create powerful applications based on a large set of shared data.
That's the theory, anyway.
On a more practical side, avoiding tag name clashes is still an issue because it's useful to modify XML documents. Clashes aren't a problem when everyone is working with a fixed set of elements. However, you can run into trouble if you allow others to extend a document by adding their own elements.
For example, you may decide to use <title> to refer to the title of a web page, but your friend used <title> as the title of a person, such as Mister or Doctor. With XML Namespaces, you can keep <html:title> distinct from <person:title>.
Some languages have a similar concept, where functions and objects belonging to a package can be namespaced together. PHP does not support namespaces, which is why you may see PHP function and class names prefixed with a unique string. For example, the PEAR::DB MySQL module is named DB_mysql. The leading DB_ means that this class will not conflict with a class named simply mysql.
Another example of namespaces is the domain name system: columbia.com is the Columbia Sportswear company, while columbia.edu is Columbia University. Both hosts are columbia, but one lives in the .com namespace and the other lives in .edu.
In XML, a namespace name is a string that looks like a URL?for example,. This URL doesn't have to resolve to an actual web page that contains information about the namespace, but it can. A namespace is not a URL, but a string that is formatted the same way as a URL.
This URL-based naming scheme is just a way for people to easily create unique namespaces. Therefore, it's best only to create namespaces that point to a URL that you control. If everyone does this, there won't be any namespace conflicts. Technically, you can create a namespace that points at a location you don't own or use in any way, such as. This is not invalid, but it is confusing.
Unlike domain names, there's no official registration process required before you can use a new XML namespace. All you need to do is define the namespace inside an XML document. That "creates" the namespace. To do this, add an xmlns attribute to an XML element. For instance:
<tag xmlns:
When an attribute name begins with the string xmlns, you're defining a namespace. The namespace's name is the value of that attribute. In this case, it's.
Since URLs are unwieldy, a namespace prefix is used as a substitute for the URL when referring to elements in a namespace (in an XML document or an XPath query, for example). This prefix comes after xmlns and a :. The prefix name in the previous example is example. Therefore, xmlns:example="" not only creates a namespace, but assigns the token example as a shorthand name for the namespace.
Namespace prefixes can contain letters, numbers, periods, underscores, and hyphens. They must begin with a letter or underscore, and they can't begin with the string xml. That sequence is reserved by XML for XML-related prefixes, such as xmlns.
When you create a namespace using xmlns, the element in which you place the attribute and any elements or attributes that live below it in your XML document are eligible to live in the namespace. However, these elements aren't placed there automatically. To actually place an element or attribute in the namespace, put the namespace prefix and a colon in front of the element name. For example, to put the element title inside of the namespace, use an opening tag of <example:title>.
The entire string example:title is called a qualified name, since you're explicitly mentioning which element you want. The element or attribute name without the prefix and colon, in this case title, is called the local name.
Note that while the xmlns:example syntax implies that xmlns is a namespace prefix, this is actually false. The XML specification forbids using any name or prefix that begins with xml, except as detailed in various XML and XML-related specifications. In this case, xmlns is merely a sign that the name following the colon (:) is a namespace prefix, not an indication that xmlns is itself a prefix.
Example A-2 updates the address book from Example A-1 and places all the elements inside the namespace.
<ab:address-book xmlns: <ab:person <ab:firstname>Rasmus</ab:firstname> <ab:lastname>Lerdorf</ab:lastname> <ab:city>Sunnyvale</ab:city> <ab:state>CA</ab:state> <ab:email>rasmus@php.net</ab:email> </ab:person> <!-- more entries here --> </ab:address-book>
If two XML documents map the same namespace to different prefixes, the elements still live inside the same namespace. The URL string defines a namespace, not the prefix. Also, two namespaces are equivalent only if they are identical, including their case. Even if two URLs resolve to the same location, they're different namespaces.
Therefore, this document is considered identical to Example A-2:
<bigbird:address-book xmlns: <bigbird:person <bigbird:firstname>Rasmus</bigbird:firstname> <bigbird:lastname>Lerdorf</bigbird:lastname> <bigbird:city>Sunnyvale</bigbird:city> <bigbird:state>CA</bigbird:state> <bigbird:email>rasmus@php.net</bigbird:email> </bigbird:person> <!-- more entries here --> </bigbird:address-book>
The ab prefix has been changed to bigbird, but the namespace is still. Therefore, an XML parser would treat these documents as if they were the same.
As you can see, prepending a namespace prefix not only becomes tedious, it clutters up your document. Therefore, XML lets you specify a default namespace. Wherever a default namespace is applied, nonprefixed elements and attributes automatically live inside the default namespace.
A default namespace definition is similar to that of other namespaces, but you omit the colon and prefix name:
xmlns=""
This means there's yet another way to rewrite the example:
<address-book <person id="1"> <firstname>Rasmus</firstname> <lastname>Lerdorf</lastname> <city>Sunnyvale</city> <state>CA</state> <email>rasmus@php.net</email> </person> <!-- more entries here --> </address-book>
It is not uncommon to find a document that uses multiple namespaces. One is declared the default namespace, and the others are given prefixes.
For more on XML Namespaces, read Chapter 4 of XML in a Nutshell by Elliotte Rusty Harold and W. Scott Means (O'Reilly) or see the W3 specification at | http://etutorials.org/Server+Administration/upgrading+php+5/Appendix+A.+Introduction+to+XML/A.5+XML+Namespaces/ | CC-MAIN-2018-39 | refinedweb | 1,175 | 55.74 |
[
]
Noah Slater updated COUCHDB-230:
--------------------------------
Fix Version/s: 1.0.2
(was: 1.0.1)
> Add Support for Rewritable URL
> ------------------------------
>
> Key: COUCHDB-230
> URL:
> Project: CouchDB
> Issue Type: New Feature
> Reporter: Patrick Aljord
> Fix For: 1.0.2
>
>
> It would be good if couchdb would allow to rewrite urls so that instead of having to
write that:
>
> I could just write:
>
> It could be done with the web server but having the rewritten rules in the db would make
it a bit easier for replication so we don't have to write the rules on each web server where
a db gets replicated.
> Here are a few propositions from davisp:
> <davisp> alisdair: how so? rewriting urls should be in _design documents, since
they're in _design docs they should be limited to per db namespaces
> <davisp> bobesponja: I don't know that anyone has looked at it seriously, but my
first guess is that we'd just make a _design/doc "urls" member that's a list of regex's and
targets as is fairly standard practice
> <davisp> bobesponja: or perhaps, regex's -> erlang handler
> <davisp> the second might not be as fun
--
This message is automatically generated by JIRA.
-
You can reply to this email to add a comment to the issue online. | http://mail-archives.apache.org/mod_mbox/couchdb-dev/201008.mbox/%3C11888920.392801282049478822.JavaMail.jira@thor%3E | CC-MAIN-2014-23 | refinedweb | 214 | 68.33 |
Last time I discovered that the JVM startup times aren't that bad. Clojure and Leiningen are much slower.
Clojure startup times suck. Let's just be honest. Starting
lein repl in a typical project takes about eight seconds on my machine. Running
lein test takes over twelve seconds. And I don't even have any
tests.
How do Clojure programmers live with this?
Further, Clojure is all about interactive development. It's all about fast feedback, incremental compiling, exploration. How can you have fast feedback when it takes 12 seconds to run tests? How do you do exploration when things take so long?
The startup times are annoying! When I want to start coding, it takes a lot of time before I can even type the first paren. I have to wait and remember all of the stuff that's going on in my head that I just want to type out. It's very stressful. I love fast feedback. I can't stand programming in a system that forces me to type stuff, then takes a while to show me the result of typing that stuff. But let me tell you, Clojure is not one of those systems.
The (Not so) Secret
Here's the key to fast feedback in Clojure: I rarely restart my application. I have REPLs that have been open for days. When I'm actively working on a single application, I will keep it running for weeks sometimes. It's not crazy. So I am willing to wait 20-30 seconds for my application to start. 20-30 seconds is nothing compared to weeks of development with super fast feedback.
Most workflows get it all wrong
Let me tell you a little story that Alan Kay has told about Smalltalk back in the day. People writing C++ would show all of these microbenchmarks showing how C++ way outperforms Smalltalk, especially when doing integer arithmetic. But when they'd write a GUI in C++, they'd waste all of the performance gained. Mouse clicks would take a long time to have their effect. Windows wouldn't update their contents quickly. The actual goal of showing the answer to the user quickly was ignored. Smalltalk let you do the math, see the answer, and change the calculation faster than the C++-based GUIs could.
Smalltalk focused on giving users the whole cycle. C++ focused on fast math, one little piece. When people focus on startup times, they are missing the big picture. It's not about startup times, it's about fast feedback.
What I see in Clojure (and some other communities) is a consistent high-level concern with the speed of feedback. That includes the entire cycle, from thinking of some code, to typing it in, to compiling it and running it and seeing the result.
It's why Figwheel exists. People complain about ClojureScript compile times. In most frontend systems, there's almost no compilation time. But they are not counting the time it takes to refresh their browser and click buttons to test out what they just coded. With Figwheel, you literally type code, save it, and less than a second later see the result in your browser. The compilation time is only a part of the equation.
When people complain about the startup times, I wonder about their workflow. I've even considered offering a consulting service to help people set up their workflow for fast feedback. If you want me to get annoyed and stressed and quit my job, give me long feedback loops. The absolutely most important thing to me in any system is making it fast to make changes and see the results. I'll spend a lot of time speeding up my workflow instead of working on features.
Cider (the Emacs development environment for Clojure), Cursive, and proto-repl (the Atom development environment for Clojure) all focus on this entire feedback loop.
My workflow
With the obligatory caveats that my workflow is certainly not ideal for everyone, let me try to describe how I work in Clojure.
I open up Emacs, browse to a random file in my project, then run
cider-jack-in, which starts a connected REPL. That takes about 20-30
seconds. I twiddle my thumbs.
Now that I'm in, I compile the current namespace with a keystroke
(
C-c-k). Then I code. Then I compile everything. Then I code. Then I
compile everything. Over and over.
If I'm doing TDD, after I compile my code, I run the tests with a
keystroke (
C-c C-t n). All of this stuff is so ingrained in my
muscle memory that I don't think about it. I do it without
realizing it.
Some other resources
Okay, startup times is a very common complaint and people have worked hard on it. There are some interesting resources.
One approach is to keep a JVM around that's already booted up and
ready with the classpath you want. Then when you want to run some
code, you just connect to the JVM and add the new code and run
it. That's the approach of drip and
it should be a drop-in replacement for the
java executable.
The Leiningen wiki has a page about making Leiningen faster.
Alan Dipert wrote a guide to avoid restarting the JVM when developing in Boot. Boot is cool because it totally gets the fast-feedback mindset. Boot lets you add dependencies as you go, instead of having to restart to add a new JAR.
But startup time of Clojure is still bad for shell scripting. Planck and Lumo are ClojureScript REPLs that start up fast and let you code ClojureScript. It's not JVM Clojure, but it's a way to run Clojure for quick scripts. They can handle command line arguments, input/output, and shelling out to other programs, among other things. These are under active development and they get new features all the time.
Conclusions
Startup times are still important for a lot of applications, like running shell scripts. However, when developing applications, the Clojure community focuses on fast feedback more than it focuses on the startup time. Get your workflow set up so that you can see the result of your changes instantly.
If you are coming to Clojure from another language (or it's your first language), I don't want you to get stuck on the intricacies of the JVM. It can be a huge stumbling block. That's why I created a course called JVM Fundamentals for Clojure. It explains all sorts of stuff that will make you more effective when using the JVM, configuring it, doing interop, and understanding what's going on. You can buy that individual course or you can get it as part of a membership.
We're going to take a little turn now and next time we'll be exploring the wide variety of JVM deployment options. | https://purelyfunctional.tv/article/how-do-clojure-programmers-deal-with-long-startup-times/ | CC-MAIN-2018-43 | refinedweb | 1,161 | 75.2 |
Hi, I have an Excel document (region and language is german) with some dates and times. When I save this document as HTML using Aspose.Cells the date and time formats are switched to the english ones. I'm using Aspose.Cells 4.8.2.0. I have attached the Excel document and the corresponding HTML output. Is ther any way that the date and time formats will not be changed when saving the document?
Problem with date and time format in an Excel document (german region and language) saved as HTML
Hi,<?xml:namespace prefix = o
Thank you for sharing the template file.
We have found your mentioned issue after an initial test. We will look into it and get back to you soon. Your issue has been registered in our internal issue tracking system with issue id: CELLSNET-16910.
Thank You & Best Regards,
Hi,
Thank you
Hi, with the attached version the problem has been fixed. Thank and Regards.
Hi, sorry, but there are still some problems remaining. Please find attached a new sample document. The time format of cell B7 is not as aspected in the HTML and also the date format of cell D3.
Hi,
Thank you for sharing the template file.
We have found your mentioned issue after an initial test. We have re-opened your issue. we will further look into it and get back to you soon.
Thank You & Best Regards
Hi,
After further investigation, the number format of “B7” is [$-F400]h:mm:ss AM/PM. The displayed number format in MS is h:mm:ss. The number format of “D3” is [$-F800]TTTT, MMMM TT, JJJJ. The display number format in MS is TTTT,TT. MMMM JJJJ. We ignored the header “[$-Fxxx]” of the number in converting date time to a string value. By the way, we will fix the two issue soon. But we do not know whether there are some other special formats that start with “[$-Fxxx]”. So, could you simply set the number format as actual displayed number format: h:mm:ss, TTTT,TT. MMMM JJJJ?
Thank you.
Hi,
We have fixed your issue, kindly try the attached version.
Thank you.
The issues you have found earlier (filed as 16910) have been fixed in this update.
This message was posted using Notification2Forum from Downloads module by aspose.notifier.
While trying to keep the API as straightforward and clear as possible, we have decided to recognize and honor the common development practices of the platform; we have re-arranged API Structure/ Namespaces.
With this release, we have reorganized the API classes for Aspose.Cells component. This change has some major aspects that we follow. We have added new namespaces. The entire API (classes, interfaces, enumerations, structures etc.) were previously located in the Aspose.Cells namespace. Now, certain sets of API have been moved to their relative namespaces, which make the relationship of classes (with their members) and namespaces clear and simplified. It is to be noted here, we have not renamed existing API (classes, enumerations etc.) but, I am afraid you still need to make certain adjustments in your existing projects accordingly.
For complete reference, please see the product's API Reference. | https://forum.aspose.com/t/problem-with-date-and-time-format-in-an-excel-document-german-region-and-language-saved-as-html/137016 | CC-MAIN-2022-21 | refinedweb | 533 | 67.35 |
Re: webservice.htc, no WSDL
From: Simon (simon_at_nospam.com.au)
Date: 06/16/04
- Previous message: jey: "How do i use onblur event to imitate ModalDialog?"
- In reply to: Martin Honnen: "Re: webservice.htc, no WSDL"
- Messages sorted by: [ date ] [ thread ]
Date: Wed, 16 Jun 2004 12:37:54 +1000 To: Martin.Honnen@gmx.de
Martin Honnen wrote:
>
>
> Simon wrote:
>
>
>> I am using SOAP from IE. However I do not want the round trip of
>> retrieving a WSDL before I can make a SOAP call in the browser, which
>> the IE webservice.htc seems to demand.
>>
>> My services are not independantly exposed, I control the IE JavaScript
>> development and server side development. I am implementing simple
>> lookups - so pulling back the WSDL (when I know the SOAP format)
>> incurs a needless performance hit.
>>
>> So - can I use the web service behaviour to make a SOAP call without
>> needing the WSDL?
>
>
> I think the web service behaviour needs to read the WSDL to be able to
> offer you a simple API to call the methods of the web service and take
> care of marshalling your arguments and the return values.
> However the web service behaviour makes use of MSXML to make SOAP
> requests over HTTP so in principle you can use MSXML yourself to make
> the SOAP requests and receive the SOAP response. And of course for
> simple tasks SOAP is a overhead, maybe you can live with sending and
> receiving some simple XML with MSXML (or even with sending and receiving
> text if needed and properly UTF-8 encoded).
>
Thanks Martin,
After much playing and close review of webservice.htc, I've decided I
don't like it. I like the mozilla approach, which provides a soap api
for making soap calls directly, and also a wsdl api which retrieves the
wsdl and can make the soap call on the coder's behalf.
In my case, what the WSDL provides can be easily plugged directly into
the soap call (ie endpoint URI, namespaces, method name, argument
array), which saves the WSDL retrieval/parse overhead (not to mention
downloading webservice.htc). Unfortunately I can't see that
webservice.htc allows this!
So for IE, I am now replicating the mozilla soap api, using xmlHttp.
I have previously used xmlHttp for other xml documents - but now I am
hitting apache axis directly from the browser, so I need the soap envelope.
Cheers,
Simon
- Previous message: jey: "How do i use onblur event to imitate ModalDialog?"
- In reply to: Martin Honnen: "Re: webservice.htc, no WSDL"
- Messages sorted by: [ date ] [ thread ] | http://www.tech-archive.net/Archive/Scripting/microsoft.public.scripting.jscript/2004-06/0252.html | crawl-002 | refinedweb | 428 | 62.78 |
04 September 2008 16:29 [Source: ICIS news]
By Joe Kamalick?xml:namespace>
WASHINGTON (?xml:namespace>
Indeed, export sales of chemicals and other manufactured goods are fairly credited with saving the
“Exports are vital to the
“Over the past year - second quarter 2007 to second quarter 2008 - the
“Nearly two-thirds of that growth, 61%, came from exports, which increased by 11.2% during that period,” he said.
“Strong growth abroad, which has averaged 3.9% over the past three years (on a trade-weighted basis) and a more competitive dollar have made US manufactured exports more competitive globally,” Huether added.
That strong global growth has helped sustain the
“Exports are very important to American chemistry, accounting for 23% of shipments for overall chemistry - and 25% of chemicals excluding pharmaceuticals,” Swift said.
“According to the Bureau of the Census, exports support 16% of the chemical industry’s jobs, with an additional 8% of industry jobs supported by the exports of other industries that depend on the domestic availability and quality of American chemistry,” Swift said.
That is 207,000 chemical industry jobs tied directly or indirectly to export trade, said Swift.
“Looking at the details of some of the resins,” said Swift, “exports have been very supportive at a time when domestic demand has been soft.”
“The July HDPE [high density polyethylene] figures just came out and indicated that while domestic sales thus far this year were down 6.2% for the first seven months compared with the same period in 2007, exports were up 59.6% during the same time,” he said.
“Similarly, domestic sales of polystyrene [PS] were down 3.7% for the first seven months this year compared with the same period in 2007, with exports up 2.1%.”
“The question is,” Swift said, “how long can this go on?”
The International Monetary Fund (IMF) said that “the slowdown in global growth, which started in mid-2007, is expected to continue through the second half of 2008, with only a gradual recovery during 2009”.
“Global growth decelerated to 4.5% in the first quarter of 2008, measured over four quarters earlier,” the IMF said in its recent world economic outlook, “down from 5% in the third quarter of 2007, with activity slowing in both advanced and emerging economies.”
In addition, “recent indicators suggest a further deceleration of activity in the second half of 2008,” the IMF said.
“Accordingly, global growth is projected to moderate from 5% in 2007 to 4.1% in 2008 and 3.9% in 2009,” according to the fund’s forecast.
“Expansions in emerging and developing economies are expected to lose steam,” the IMF said. “Growth in these economies is projected to ease to around 7% in 2008-2009 from 8% in 2007.”
“In
Growth projections for the euro area and
Consequently, at least some of the strong foreign growth that has sustained US chemical and other manufacturing over the past year and more can be expected to wane this year and into 2009.
As the export market begins to cool, will the
The IMF said that
But the fund also expected the
As August drew to a close, the US Commerce Department revised its estimate of the nation’s GDP in the second quarter to a 3.3% rate of growth, up sharply from the department’s earlier estimate of 1.9% GDP expansion in the quarter.
The question is whether the hoped-for
Joe Acker, president of the Synthetic Organic Chemical Manufacturers Association (SOCMA), said that there is another factor in the balance between domestic and foreign markets - the quality and dependability of
“While there is no question that the weaker US dollar has helped our exports, there are other factors,” Acker said.
“As those developing economies begin to cool and as costs are coming up in
In other words, even if the domestic
“
Bookmark Paul Hodges' Chemicals and the Economy blog | http://www.icis.com/Articles/2008/09/04/9153990/insight-us-producers-face-test-of-export-strength.html | CC-MAIN-2014-15 | refinedweb | 650 | 58.82 |
TL;DR: So you are thinking about developing your next great application with Next.js, huh? Or maybe you already started developing it and now you want to add authentication to your app. Either way, you are in the right place. If you are just starting to build your app with Next.js, now it is a good time to learn how to add authentication to it. If you already have something going on, it is never late to add authentication the right way.
In this article, you will learn how to leverage Passport to secure your Next.js app. What is cool about the approach you will learn here is that it even supports Server-Side Rendering (SSR) of protected routes. That is, with this setup, if an unknown user requests a secured route (those that are only accessible by authenticated users), your app will redirect them to the login page. On the other hand, if an authenticated user tries to load the same route, your Next.js app will recognize them and render the page on the server. Sounds cool? If so, keep reading!
"Securing your Next.js applications with Passport is easy, even when supporting server-side rendered routes that must remain protected. Learn how!"
This GitHub repository was created by the author while writing the article. You can use it as a reference if needed..
Scaffolding Next.js Applications
First thing you will need is a directory to put your project's source code. Also, you will have to transform this directory into an NPM project (if you prefer using Yarn, keep in mind you will have to adjust the commands accordingly). To achieve that, issue the following commands from a terminal:
# create a directory for your application mkdir nextjs-passport # move into it cd nextjs-passport # start it as an NPM project npm init -y
After that, use the following command to add some dependencies to your new project:
npm i body-parser bootstrap dotenv \ dotenv-webpack express isomorphic-fetch \ next react react-bootstrap \ react-dom styled-components
This command, as you can see, is installing a lot of dependencies. Some of them are required; some of then are optional. More specifically, these are the required dependencies:
body-parser: This package lets your Express application parse different types of request bodies (e.g.,
application/json)
dotenv: This package helps you read environment variables from a file.
dotenv-webpack: This package allows you to adjust some of the settings of Next.js.
express: This package will allow you to define a backend app more easily.
isomorphic-fetch: This package adds an isomorphic
fetchfunction that you can use both on the frontend and the backend.
react, and
react-dom: Together, these packages let you build React apps that support server-side rendering.
While these are the optional ones:
bootstrapand
react-bootstrap: These packages allow you to use Bootstrap components without having to use jQuery.
styled-components: This package lets you use CSS in JavaScript.
Note: If you choose not to install the optional dependencies, you will have to refactor the code to your needs. Also, don't worry if the explanation above is vague. Soon, you will learn how the pieces work together.
Configuring Next.js Projects
After installing these dependencies, it's time to configure them. For starters, create a file called
.babelrc inside the project root and add the following code to it:
// ./.babelrc { "presets": ["next/babel"], "plugins": [["styled-components", { "ssr": true }]] }
This file will make
styled-components work with Next.js and let Babel know that you are developing with this package. Configuring Babel with the
next/babel preset is needed to make this package compile your code accordingly.
With that in place, the next thing you will do is to create a file called
.env inside the project root. For now, you will only use this file to define what port your app will listen to:
# ./.env PORT=3000
In a few moments (while setting up authentication), you will add more properties to this file.
Now, you will create a file called
next.config.js inside the project root, and you will add the following code to it:
// ./next.config.js require("dotenv").config(); const path = require("path"); const Dotenv = require("dotenv-webpack"); module.exports = { webpack: config => { config.plugins = config.plugins || []; config.plugins = [ ...config.plugins, // Read the .env file new Dotenv({ path: path.join(__dirname, ".env"), systemvars: true }) ]; return config; } };
The goal here is to help Next.js parse the configuration file you just created (i.e., the
.env).
With that in place, create a directory called
src inside the project root, then create three subdirectories inside it:
components,
pages, and
state. To speed up, you can use the following commands to create these directories:
# the -p flag makes sure src is created first mkdir -p src/components mkdir src/pages mkdir src/state
Next.js will use
src/pages as the main directory to define what routes (pages) are available in your app.
After creating these directories, add a new file called
index.js inside
src/pages and add the following code to it:
// ./src/pages/index.js import styled from "styled-components"; const Rocket = styled.div` text-align: center; img { width: 630px; } `; function Index() { return ( <Rocket> <img src="" /> </Rocket> ); } export default Index;
Next, you will create a file called
_document.js inside
src/pages and add the following code to it:
// ./src/pages/_document.js import Document, { Head, Html, Main, NextScript }(); } } render() { return ( <Html> <Head> <link rel="stylesheet" href="" /> </Head> <body> <Main /> <NextScript /> </body> </Html> ); } }
The code above defines a class with a static function called
getInitialProps that might look confusing. Don't worry about this method. Its purpose is to make Next.js capable of server-side rendering your styled component (i.e., you need this to make
styled-components work properly on the server side). Besides that, this class defines the
render method to be able to inject Bootstrap's stylesheet on the HTML that Next.js generates.
Note: By default, pages in Next.js skip the definition of the surrounding document's markup. That is, you will never include
htmland
bodytags on pages. To override the default structure, you need this
_document.jsfile.
To wrap things in this section, open the
package.json file and replace the
scripts property with this:
// ./package.json "scripts": { "dev": "next ./src" },
Note: By default, Next.js will use the project root to look for your source code (e.g., the
pagesdirectory and its routes). However, this article uses the
srcdirectory to keep things more organized. As such, you need to add
./srcto tell Next.js about this change. Feel free to move things around to better suit your needs.
After defining the
dev script, you can execute
npm run dev from your terminal to run the first version of your Next.js app. If everything works as expected, in a few seconds, you will be able to open in a web browser.
Developing Next.js Applications
In this section, you will develop a Next.js application that will allow users to do two things: share their thoughts (similar to what they do on Twitter) and consume the thoughts others shared. For the moment, these thoughts will have no information about the user who entered them (i.e., no identity management). In the next section though, you will add authentication to your app and will make it link thoughts to users.
Building custom APIs with Next.js
To support this application, you will need an API that serves thoughts when requested and that is capable of persisting new thoughts that users share. To build this API, the first thing you will do is to create a file called
thoughts-api.js inside
src; then you will add the following code to this file:
// ./src/thoughts-api.js const bodyParser = require("body-parser"); const express = require("express"); const router = express.Router(); router.use(bodyParser.json()); const thoughts = [ { _id: 123, message: "I love pepperoni pizza!", author: "unknown" }, { _id: 456, message: "I'm watching Netflix.", author: "unknown" } ]; router.get("/api/thoughts", (req, res) => { const orderedThoughts = thoughts.sort((t1, t2) => t2._id - t1._id); res.send(orderedThoughts); }); router.post("/api/thoughts", (req, res) => { const { message } = req.body; const newThought = { _id: new Date().getTime(), message, author: "unknown" }; thoughts.push(newThought); res.send({ message: "Thanks!" }); }); module.exports = router;
This file is defining two Express endpoints. The first one allows clients to issue HTTP GET requests to get all thoughts. The second one will enable clients to issue HTTP POST requests to insert new thoughts.
After defining the endpoints, create a file called
server.js inside
src and add the following code to it:
// ./src/server.js require("dotenv").config(); const express = require("express"); const http = require("http"); const next = require("next"); const thoughtsAPI = require("./thoughts-api"); const dev = process.env.NODE_ENV !== "production"; const app = next({ dev, dir: "./src" }); const handle = app.getRequestHandler(); app.prepare().then(() => { const server = express(); server.use(thoughtsAPI); // handling everything else with Next.js server.get("*", handle); http.createServer(server).listen(process.env.PORT, () => { console.log(`listening on port ${process.env.PORT}`); }); });
This file is using Express to extend the default functionality that Next.js provides. After Next.js finishes preparing itself to serve requests (
app.prepare().then), this file creates an Express server, adds to it the endpoints that
thoughts-api.js defines, and starts listening to HTTP requests. Note that, apart from adding your custom endpoints to the Express server, this file is also stating that Next.js must handle all the other requests (i.e., the ones that are not seeking your custom endpoints). Without this setting, your Next.js app would end up serving only the custom API endpoints.
To wrap the custom API creation, open the
package.json file and replace the
scripts property with this:
// ./package.json "scripts": { "dev": "node ./src/server.js", "build": "next build ./src", "start": "NODE_ENV=production node ./src/server.js" },
Now, back in your terminal, issue
npm run dev to confirm that everything is working as expected (you might need to stop the previous process first). After running your development server, you must be able to issue HTTP GET requests to to list thoughts.
Consuming custom APIs with Next.js
After adding a custom API to your Next.js application, the next thing you will do is to make your application consume the API. To do so, the first thing you will do is to create a component that will render the details of a single thought. So, create a file called
Thought.js inside
src/components and add the following code to it:
// ./src/components/Thought.js import Card from "react-bootstrap/Card" export default function Thought({ thought }) { const cardStyle = { marginTop: "15px" }; return ( <Card bg="secondary" text="white" style={cardStyle}> <Card.Body> <Card.Title>{thought.message}</Card.Title> <Card.Text>by {thought.author}</Card.Text> </Card.Body> </Card> ); }
This component will use the
Card component that
react-bootstrap provides to show the
message entered by the user. As mentioned, thoughts won't hold information about their author yet. So, for the moment, they will all show "unknown" on the
author property.
After creating this component, you will create a component that will render all thoughts. In this case, create a file called
Thoughts.js inside
src/components and add the following code to it:
// ./src/components/Thoughts.js import Col from "react-bootstrap/Col"; import Row from "react-bootstrap/Row"; import Thought from "./Thought"; export default function Thoughts(props) { return ( <Row> <Col xs={12}> <h2>Latest Thoughts</h2> </Col> {props.thoughts && props.thoughts.map(thought => ( <Col key={thought._id} xs={12} sm={6} md={4} lg={3}> <Thought thought={thought} /> </Col> ))} {!props.thoughts && <Col xs={12}>Loading...</Col>} </Row> ); }
As you can see, this component will get a list of thoughts through
props and will iterate (
thoughts.map) over them to create multiple
Thought (now singular) elements. Just like the other component, this one takes advantage of React Bootstrap to render a nice user interface.
Lastly, you will open the
index.js file and replace its code with this:
// ./src/pages/index.js import Container from "react-bootstrap/Container"; import fetch from "isomorphic-fetch"; import Thoughts from "../components/Thoughts"; function Index(props) { return ( <Container> <Thoughts thoughts={props.thoughts} /> </Container> ); } Index.getInitialProps = async ({ req }) => { const baseURL = req ? `${req.protocol}://${req.get("Host")}` : ""; const res = await fetch(`${baseURL}/api/thoughts`); return { thoughts: await res.json() }; }; export default Index;
The new version of this file uses
getInitialProps (a feature that Next.js provides) to fetch thoughts from the custom API. By using this feature, you make Next.js render thoughts on the server side before issuing an HTML response to a client (usually a browser). Besides that, Next.js will also use this method when users trigger client-side navigation.
After creating these components, if you issue a request to, you will get an HTML response that includes all thoughts that the custom API return. To confirm that this is working, you can use any HTTP client to issue the request; then you can copy the HTML response and paste on a tool like HTML formatter to check the response more easily.
Feeding custom APIs with Next.js
After learning how to consume a custom API, the next thing you will do is to create a route where users will be able to share their thoughts. The idea here is to create a route that is protected and that only authenticated users can access. However, to make the authentication process easier to be digested, you will first create this route publicly; then, in the next section, you will secure the route and the endpoint that supports it.
As your users will have to navigate to this route, you need to enable them to do so. For that, you could simply add a link above the list of thoughts. However, to make this app more realistic, you will create a navigation bar that will include this link.
To create the navigation bar, create a file called
Navbar.js inside
src/components and add the following code to it:
// ./src/components/Navbar.js import Link from "next/link"; import Container from "react-bootstrap/Container"; import Navbar from "react-bootstrap/Navbar"; import Nav from "react-bootstrap/Nav"; export default function AppNavbar() {"> <Link href="/share-thought"> <a className="nav-link">New Thought</a> </Link> </Nav> </Navbar.Collapse> </Container> </Navbar> ); }
The component uses three React Bootstrap components (
Container,
Navbar, and
Nav) to create a good-looking navigation bar. Now, as you don't want to include this bar inside each route manually, you will create a file called
_app.js inside
src/pages and add the following code to { render() { const { Component, pageProps } = this.props; return ( <NextContainer> <Head> <title>Thoughts!</title> </Head> <Navbar /> <Container> <Jumbotron> <Component {...pageProps} /> </Jumbotron> </Container> </NextContainer> ); } } export default MyApp;
By defining this file, you are extending the Next.js default
App component behavior to add your
Navbar on every page. Besides that, you are nesting the contents of your pages inside a
Jumbotron, which will make your app look better.
After creating the navigation bar and extending the
App component, you can finally define your new route. To implement this route, create a new file called
share-thought.js inside
src/pages and insert the following code into it:
// ./src/pages/share-thought.js import Form from "react-bootstrap/Form"; import Router from "next/router"; import Button from "react-bootstrap/Button"; import Container from "react-bootstrap/Container"; const { useState } = require("react"); export default function ShareThought() { const [message, setMessage] = useState(""); async function submit(event) { event.preventDefault(); await fetch("/api/thoughts", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ message }) }); Router.push("/"); } return ( <Container> <Form onSubmit={submit}> <Form.Group> <Form.Label>What is in your mind?</Form.Label> <Form.Control Share </Button> </Form> </Container> ); }
This code might be a bit lengthy, but its behavior is somewhat easy to understand. First, after importing its dependencies, the
ShareThought components starts by using the
useState hook. This feature allows developers to use state inside functional components. After that, the code defines a function called
submit that the component will call when users click on the Share button. For now, this method simply issues a POST AJAX request to the backend API with the message that the user entered. Lastly, this code defines what the route will look like (i.e., defines what components React will use to put the view together).
With that in place, if you refresh your app on the browser (), you will see its new version. This version will show the navigation bar at the top and will allow users to navigate to the route where they will be able to share their thoughts.
Securing Next.js Applications with Passport
All right. After bootstrapping and developing the base application, you are now ready to learn how to secure your Next.js application with Passport. In this section, you will use Passport along with Auth0 to take advantage of the cool benefits we provide (e.g., out-of-the-box features like sign-in, sign-up, password reset, single sign-on, and multifactor authentication). However, if you prefer using another alternative, don't worry. Switching authentication strategies on Passport is easy and there are plenty of options available.
For starters, you will need an Auth0 application. If you don't have one yet, now it is a good time to sign up for a free Auth0 account. If you already have an account, you can reuse it.
After signing into the Auth0 dashboard, head to the Applications section and click on Create Application. Clicking on this button will make Auth0 show a dialog where you will have to fill the following options:
- Name: In this field, you can type something meaningful and easily identifiable. For example: "Next.js and Passport"
- Type: Here, you will have to choose Regular Web Application.
After filling this form, click on Create. Doing so will make Auth0 redirect you to the Quick Start section of your new application. From there, click on Settings and update your Auth0 application as follows:
- Allowed Callback URLs:
- Allowed Logout URLs:
You will need this configuration because Auth0 will only redirect users (after a successful login or logout process) to the URLs whitelisted in these fields. So, scroll to the bottom of the page and click on Save Changes. Don't close this page yet, you will need to copy some values from it soon.
Now, head back to your terminal, stop the development server (
Ctrl + C), and execute the following command:
npm install passport passport-auth0 express-session uid-safe
This will make NPM install four packages that you will need for a proper setup:
passport: This is the main Passport package.
passport-auth0: This is the Auth0 strategy for Passport.
express-session: This is the official Express middleware for session handling.
uid-safe: A package that helps creating safe UIDs for URLs and cookies.
After installing these dependencies, open the
server.js file and replace its contents with this:
// ./src/server.js require("dotenv").config(); const express = require("express"); const http = require("http"); const next = require("next"); const session = require("express-session"); // 1 - importing dependencies const passport = require("passport"); const Auth0Strategy = require("passport-auth0"); const uid = require('uid-safe'); const authRoutes = require("./auth-routes"); const thoughtsAPI = require("./thoughts-api"); const dev = process.env.NODE_ENV !== "production"; const app = next({ dev, dir: "./src" }); const handle = app.getRequestHandler(); app.prepare().then(() => { const server = express(); // 2 - add session management to Express const sessionConfig = { secret: uid.sync(18), cookie: { maxAge: 86400 * 1000 // 24 hours in milliseconds }, resave: false, saveUninitialized: true }; server.use(session(sessionConfig)); // 3 - configuring Auth0Strategy const auth0Strategy = new Auth0Strategy( { domain: process.env.AUTH0_DOMAIN, clientID: process.env.AUTH0_CLIENT_ID, clientSecret: process.env.AUTH0_CLIENT_SECRET, callbackURL: process.env.AUTH0_CALLBACK_URL }, function(accessToken, refreshToken, extraParams, profile, done) { return done(null, profile); } ); // 4 - configuring Passport passport.use(auth0Strategy); passport.serializeUser((user, done) => done(null, user)); passport.deserializeUser((user, done) => done(null, user)); // 5 - adding Passport and authentication routes server.use(passport.initialize()); server.use(passport.session()); server.use(authRoutes); server.use(thoughtsAPI); // 6 - you are restricting access to some routes const restrictAccess = (req, res, next) => { if (!req.isAuthenticated()) return res.redirect("/login"); next(); }; server.use("/profile", restrictAccess); server.use("/share-thought", restrictAccess); // handling everything else with Next.js server.get("*", handle); http.createServer(server).listen(process.env.PORT, () => { console.log(`listening on port ${process.env.PORT}`); }); });
The new version of this file adds six important changes to your custom API. The following list summarizes these changes:
You are importing five new modules. One for each of the four dependencies you just installed, and one for a module called
auth-routes. This module (which you will create soon) will define the authentication routes.
You are making your Express server use the session package (
server.use(session(sessionConfig))) to persist user sessions. Note that, through the
sessionConfigobject, you are defining how this package will behave (e.g., you are using
uid-safeto generate a safe secret to hash your cookies, and you are defining that cookies will stay valid for 24 hours).
You are configuring the
Auth0Strategywith four environment variables. You will learn how to set them later.
You are configuring Passport to use Auth0's strategy, and you are telling this package what data it should keep on users sessions.
ou are making your Express server use Passport, and you are adding the authentication routes to it.
ou are restricting access to the
/profileand the
/share-thoughtroutes.
After refactoring your Express server to use Passport, you will need to create a file called
auth-routes.js inside
src. In this file, you will add the following code to define the authentication routes:
// ./src/auth-routes.js const express = require("express"); const passport = require("passport"); const router = express.Router(); router.get("/login", passport.authenticate("auth0", { scope: "openid email profile" }), (req, res) => res.redirect("/")); router.get("/callback", (req, res, next) => { passport.authenticate("auth0", (err, user) => { if (err) return next(err); if (!user) return res.redirect("/login"); req.logIn(user, (err) => { if (err) return next(err); res.redirect("/"); }); })(req, res, next); }); router.get("/logout", (req, res) => { req.logout(); const {AUTH0_DOMAIN, AUTH0_CLIENT_ID, BASE_URL} = process.env; res.redirect(`{AUTH0_DOMAIN}/logout?client_id=${AUTH0_CLIENT_ID}&returnTo=${BASE_URL}`); }); module.exports = router;
As you can see, your application will have to support three new routes:
/login: When users reach this route, your app will call Passport's authentication method telling it to use Auth0's strategy. This will make your app redirect users to Auth0's Universal Login Page.
/callback: After authenticating, Auth0 will redirect users to this URL. There, your app will get a code back from the authentication process and will use it (along with the
AUTH0_DOMAIN,
AUTH0_CLIENT_ID, and
AUTH0_CLIENT_SECRETenvironment variables) to exchange for user details (a profile, mainly).
/logout: When your users want to log out from the application, they will request this URL. This endpoint will log users out from your app and from Auth0 as well.
Then, you can open the
.env file and update it as follows:
# ./.env # ... keep PORT untouched ... AUTH0_DOMAIN=... AUTH0_CLIENT_ID=... AUTH0_CLIENT_SECRET=... AUTH0_CALLBACK_URL= BASE_URL=
To replace the
AUTH0_DOMAIN,
AUTH0_CLIENT_ID, and
AUTH0_CLIENT_SECRET variables, you can copy the Domain, Client ID, and Client Secret values from the Settings section of your Auth0 Application.
Note: Don't push these values to a version control system like Git (mainly
AUTH0_CLIENT_SECRET, which should be kept private).
.envfiles are designed to keep environment variables that are specific to an environment (in this case, your machine) and should not be shared.
Next, you will open the
thoughts-api.js file and will replace the POST method of the
/api/thoughts endpoint with this:
// ./src/thoughts-api.js function ensureAuthenticated(req, res, next) { if (req.isAuthenticated()) return next(); res.send(401); } router.post("/api/thoughts", ensureAuthenticated, (req, res) => { const { message } = req.body; const newThought = { _id: new Date().getTime(), message, author: req.user.displayName }; thoughts.push(newThought); res.send({ message: "Thanks!" }); });
This will make your endpoint respond with an HTTP
401 unauthorized status to unauthenticated users. Authenticated users will still be able to use this endpoint.
With that in place, you can open the
Navbar.js file and replace its contents with this:
// ./src/components/Navbar.js import Link from "next/link"; import Container from "react-bootstrap/Container"; import Navbar from "react-bootstrap/Navbar"; import Nav from "react-bootstrap/Nav"; export default function AppNavbar({ user }) {"> {user && ( <> <Link href="/share-thought"> <a className="nav-link">New Thought</a> </Link> <Link href="/profile"> <a className="nav-link">Profile</a> </Link> <Link href="/logout"> <a className="nav-link">Log Out</a> </Link> </> )} {!user && ( <Link href="/login"> <a className="nav-link">Log In</a> </Link> )} </Nav> </Navbar.Collapse> </Container> </Navbar> ); }
As you can see, this version of your navigation bar will receive a
user props and will use it to decide if it must show the login button, or if it shows the logout button and a button to redirect users to a profile page.
This profile page is a page where your users will be able to see what your app knows about them. To define it, create a file called
profile.js inside
src/pages and add the following code to it:
// ./src/pages/profile.js import styled from "styled-components"; const Picture = styled.img` border-radius: 50%; border: 3px solid white; width: 100px; `; function Profile({ user }) { return ( <div> <h2> <Picture src={user.picture} alt={user.displayName} /> Hello, {user.displayName} </h2> <p>This is what we know about you:</p> <ul> { Object.keys(user).map(key => ( <li key={key}>{key}: {user[key].toString()}</li> ))} </ul> </div> ); } export default Profile;
As you can see, this page will mainly show users'
displayName and
picture. Then, it will iterate over the properties of the
user object to create an unordered list (
ul) with them and their values.
To complete this section, open the
_app.js file and replace its contents with { static async getInitialProps({ Component, ctx }) { let pageProps = {}; if (Component.getInitialProps) { pageProps = await Component.getInitialProps(ctx); } if (ctx.req && ctx.req.session.passport) { pageProps.user = ctx.req.session.passport.user; } return { pageProps }; } constructor(props) { super(props); this.state = { user: props.pageProps.user }; } render() { const { Component, pageProps } = this.props; const props = { ...pageProps, user: this.state.user, }; return ( <NextContainer> <Head> <title>Thoughts!</title> </Head> <Navbar user={this.state.user} /> <Container> <Jumbotron> <Component {...props} /> </Jumbotron> </Container> </NextContainer> ); } } export default MyApp;
One important change in this file is that you are redefining the
static getInitialProps method of the
MyApp class. You are doing this to add the
user object (if available) to all pages'
props. That is, the
Profile page you just defined will get this props. Also,
ShareThought and
Index will get this data too (the later will still get
thoughts alongside the
userobject).
Besides that, you are making the
MyApp component hold the user that comes from the backend on its internal state. This will make any client-side navigation have access to the user profile.
With the changes that this section introduces, you are ready to take your secure app for a spin. So, in your terminal, run the
npm run dev command. Then, head to and use the login button to test the authentication process.
If everything works as expected, after using the Auth0 login page to sign up (or sign in, in case you already have a user), you will be redirected back to your app. There, you will see the navigation bar showing three links: New Thought, Profile, and Log Out. Clicking on the second link will redirect you to the page where you will see your own information.
What is more interesting is that, at this moment, the view is rendered by the browser (i.e., without the help of the backend). And, if you use your browser to refresh this page, the same view appears, but now rendered with the help of the backend (i.e., the view travels through the wire with your profile data already structure in the HTML DOM).
Recap
In this article, you learned how to secure Next.js applications with Passport properly. You also learned how to use Auth0 as a strategy in your Passport configuration. This strategy speeds up the process because it prevents you from having to invest time in developing features like sign-in, sign-up, password reset, and similar.
As homework, you can try replacing Auth0 strategy with another one. But be aware, if you decide to handle user credentials by yourself, you will have to take care of important things like password hashing and multi-factor authentication manually. Or, if you end up deciding to support social strategies (like Facebook and Google), you will have to install each one separately (while with Auth0 you can add new social provider with a single click).
Have fun!
"I just learned how to use Passport to properly secure Next.js applications. Quite cool!" | https://auth0.com/blog/next-js-authentication-tutorial/ | CC-MAIN-2020-45 | refinedweb | 4,799 | 58.99 |
Find out how to create a reverse proxy on the latest iteration of the Ubuntu Server platform. This tutorial will walk you through the basics.
This comes from the office of "You might not ever need it, but when you do, you'll be glad you know how."
A reverse proxy is a proxy server that accepts HTTP (or HTTPS) requests and automatically feeds them to backend servers. This can be helpful when you have a website that functions with backend applications that need to be fed requests directly from the website. With the help of Apache, you can make this happen with a relative amount of ease. I'm going to walk through the process of setting up a basic reverse proxy on the latest version of Ubuntu Server (18.04).
What you'll need
You'll need a server (or virtual machine) running Ubuntu Server 18.04 with Apache installed. If your server doesn't already have Apache installed, you can accomplish that with the single command sudo apt install lamp-server^.
With that out of the way, let's make this happen.
SEE: Securing Linux policy (Tech Pro Research)
Dependencies
We are going to be working with a tool called Flask, a micro-framework written in Python used for the development of web applications. Open a terminal window and install Flask with the following commands:
sudo apt-get update sudo apt-get -y install python3-pip sudo pip3 install flask
Next we need to enable a few Apache modules. To do this, issue the following commands:
sudo a2enmod proxy sudo a2enmod proxy_http sudo a2enmod proxy_balancer sudo a2enmod lbmethod_byrequests
Apache will now need to be restarted with the command:
sudo systemctl restart apache2
Backend servers
Now we need to create two simple backend servers. We're going to create these with a bare minimum of configuration and options. Create the configuration file for the first backend server with the command:
nano ~/backend_server_1.py
In that file, copy the following content:
from flask import Flask app = Flask(__name__) @app.route('/') def home(): return 'Backend 1!'
Save and close that file. Create another configuration file called backend_server_2.py with the contents:
from flask import Flask app = Flask(__name__) @app.route('/') def home(): return 'Backend 2!'
Save and close that file.
Now we use the Flask tool to start the first background server on port 8080 and redirect the output to /dev/null. The command for this is:
FLASK_APP=~/backend_server_1.py flask run --port=8080 >/dev/null 2>&1 &
Start the second backend server (on port 8081) with the command:
FLASK_APP=~/backend_server_2.py flask run --port=8081 >/dev/null 2>&1 &
SEE: 20 quick tips to make Linux networking easier (free TechRepublic PDF)
Testing the setup
Let's test the process so far. From the terminal window, issue the command:
curl
You should see Backend 1 in the output (Figure A).
Figure A
The Backend 1 server is listening.
Now issue the command:
curl
This time you should see Backend 2 reporting (Figure B).
Figure B
Backend 2 reporting in.
Configuring Apache
At this point, you can reach those backend servers only from the localhost address (127.0.0.1). If you need to access the reverse proxy from your LAN, you need to reconfigure Apache. Before you do this, make a copy of your current Apache configuration file with the command:
sudo cp /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/000-default.conf.bak
Issue the command:
sudo nano /etc/apache2/sites-available/000-default.conf
Replace the entire contents of that file with the following:
<VirtualHost *:80> ProxyPreserveHost On ProxyPass / ProxyPassReverse / </VirtualHost>
Save and close that file. Restart Apache with the command:
sudo systemctl restart apache2
If you still have the original Apache index.html file in /var/www/html/ move it with the command:
sudo mv /var/www/html/index.html /var/www/html/index.html.bak
Now point a web browser to (where SERVER_IP is the IP address of your server). You should now see Backend 1 printed in the browser. The reverse proxy is working.
That's all there is to it
Ladies and gents, you now have a basic reverse proxy up and running on Ubuntu Server 18.04. Depending upon your needs, this should serve as a starting point to get you where you need to go. This will come in handy if you require passing connections from a web server to a backend application server.
Also read...
- How to configure, monitor, and manage Apache with ApacheGUI (TechRepublic)
- How to improve Apache server security by limiting the information it reveals (TechRepublic)
- Apache or NGINX: Which web server is right for you? (TechRepublic Video)
- How to speed up Apache with Varnish HTTP cache (TechRepublic)
- We interrupt this revolution: Apache Spark changes the rules of the game (ZDNet)
Other tips?
Got a favorite open source trick or time-savers? Share it with fellow TechRepublic members in the Comments section below. | https://www.techrepublic.com/article/how-to-setup-a-reverse-proxy-on-ubuntu-server-18-04/ | CC-MAIN-2019-47 | refinedweb | 828 | 63.9 |
JAX-RPC
The Building Web Services With JAX-RPC (JAX-RPC) is the Java API for developing and using Web services.
Overview of JAX-RPC
An RPC-based Web service is a collection of procedures that can be called by a remote client over the Internet. For example, a typical RPC-based Web service is a stock quote service that takes a SOAP (Simple Object Access Protocol) request for the price of a specified stock and returns the price via SOAP.
Note: The SOAP 1.1 specification, available from, defines a framework for the exchange of XML documents. It specifies, among other things, what is required and optional in a SOAP message and how data can be encoded and transmitted. JAX-RPC and JAXM are both based on SOAP.
A Web service, a server application that implements the procedures that are available for clients to call, is deployed on a server-side Web container. The container can be a standalone Web container or part of a J2EE server.
A Web service can make itself available to potential clients by describing itself in a Web Services Description Language (WSDL) document. A WSDL description is an XML document that gives all the pertinent information about a Web service, including its name, the operations that can be called on it, the parameters for those operations, and the location of where to send requests. A consumer (Web client) can use the WSDL document to discover what the service offers and how to access it. How a developer can use a WSDL document in the creation of a Web service is discussed later.
Interoperability
Perhaps the most important requirement for a Web service is that it be interoperable across clients and servers. With JAX-RPC, a client written in a language other than the Java programming language can access a Web service developed and deployed on the Java platform. Conversely, a client written in the Java programming language can communicate with a service that was developed and deployed using some other platform.
What makes this interoperability possible is JAX-RPC's support for SOAP and WSDL. SOAP defines standards for XML messaging and the mapping of data types so that applications adhering to these standards can communicate with each other. JAX-RPC adheres to SOAP standards, and is, in fact, based on SOAP messaging. That is, a JAX-RPC remote procedure call is implemented as a request-response SOAP message.
The other key to interoperability is JAX-RPC's support for WSDL. A WSDL description, being an XML document that describes a Web service in a standard way, makes the description portable. WSDL documents and their uses will be discussed more later.
Ease of Use
Given the fact that JAX-RPC is based on a remote procedure call (RPC) mechanism, it is remarkably developer friendly. RPC involves a lot of complicated infrastructure, or "plumbing," but JAX-RPC mercifully makes the underlying implementation details invisible to both the client and service developer. For example, a Web services client simply makes Java method calls, and all the internal marshalling, unmarshalling, and transmission details are taken care of automatically. On the server side, the Web service simply implements the services it offers and, like the client, does not need to bother with the underlying implementation mechanisms.
Largely because of its ease of use, JAX-RPC is the main Web services API for both client and server applications. JAX-RPC focuses on point-to-point SOAP messaging, the basic mechanism that most clients of Web services use. Although it can provide asynchronous messaging and can be extended to provide higher quality support, JAX-RPC concentrates on being easy to use for the most common tasks. Thus, JAX-RPC is a good choice for applications that wish to avoid the more complex aspects of SOAP messaging and for those that find communication using the RPC model a good fit. The more heavy-duty alternative for SOAP messaging, the Java
API for XML Messaging (JAXM), is discussed later in this introduction.API for XML Messaging (JAXM), is discussed later in this introduction.
Advanced Features
Although JAX-RPC is based on the RPC model, it offers features that go beyond basic RPC. For one thing, it is possible to send complete documents and also document fragments. In addition, JAX-RPC supports SOAP message handlers, which make it possible to send a wide variety of messages. And JAX-RPC can be extended to do one-way messaging in addition to the request-response style of messaging normally done with RPC. Another advanced feature is extensible type mapping, which gives JAX-RPC still more flexibility in what can be sent.
Using JAX-RPC
In a typical scenario, a business might want to order parts or merchandise. It is free to locate potential sources however it wants, but a convenient way is through a business registry and repository service such as a Universal Description, Discovery and Integration (UDDI) registry. Note that the Java API for XML Registries (JAXR), which is discussed later in this introduction, offers an easy way to search for Web services in a business registry and repository. Web services generally register themselves with a business registry and store relevant documents, including their WSDL descriptions, in its repository.
After searching a business registry for potential sources, the business might get several WSDL documents, one for each of the Web services that meets its search criteria. The business client can use these WSDL documents to see what the services offer and how to contact them.
Another important use for a WSDL document is as a basis for creating helper classes, used by a client to communicate with a remote service and by the server to communicate with a remote client.
A JAX-RPC runtime system converts the client's remote method call into a SOAP message and sends it to the service as an HTTP request. On the server side, the JAX-RPC runtime system receives the request, translates the SOAP message into a method call, and invokes it. After the Web service has processed the request, the runtime system goes through a similar set of steps to return the result to the client. The point to remember is that as complex as the implementation details of communication between the client and server may be, they are invisible to both Web services and their clients.
Creating a Web Service
Developing a Web service using JAX-RPC is surprisingly easy. The service itself is basically two files, an interface that declares the service's remote procedures and a class that implements those procedures. There is a little more to it, in that the service needs to be configured and deployed, but first, let's take a look at the two main components of a Web service, the interface definition and its implementation class.
The following interface definition is a simple example showing the methods a wholesale coffee distributor might want to make available to its prospective customers. Note that a service definition interface extends
java.rmi.Remoteand its methods throw a
java.rmi.RemoteExceptionobject.package coffees; import java.rmi.Remote; import java.rmi.RemoteException; public interface CoffeeOrderIF extends Remote { public Coffee [] getPriceList() throws RemoteException; public String orderCoffee(String coffeeName, int quantity) throws RemoteException; }
The method
getPriceListreturns an array of
Coffeeobjects, each of which contains a
namefield and a
pricefield. There is one
Coffeeobject for each of the coffees the distributor currently has for sale. The method
orderCoffeereturns a
Stringthat might confirm the order or state that it is on back order.
The following example shows what the implementation might look like (with implementation details omitted). Presumably, the method
getPriceListwill query the company's database to get the current information and return the result as an array of
Coffeeobjects. The second method,
orderCoffee, will also need to query the database to see if the particular coffee specified is available in the quantity ordered. If so, the implementation will set the internal order process in motion and send a reply informing the customer that the order will be filled. If the quantity ordered is not available, the implementation might place its own order to replenish its supply and notify the customer that the coffee is backordered.package coffees; public class CoffeeOrderImpl implements CoffeeOrderIF { public Coffee [] getPriceList() throws RemoteException; { . . . } public String orderCoffee(String coffeeName, int quantity) throws RemoteException; { . . . } }
After writing the service's interface and implementation class, the developer's next step is to generate the helper classes. The final steps in creating a Web service are packaging and deployment. A Web service definition is packaged in a Web application archive (WAR). For example, the CoffeeOrder service could be packaged in the file
jaxrpc-coffees.war, which makes it easy to distribute and deploy.
Coding a Client
Writing the client application for a Web service entails simply writing code that invokes the desired method. Of course, much more is required to build the remote method call and transmit it to the Web service, but that is all done behind the scenes and is invisible to the client.
The following class definition is an example of a Web services client. It creates an instance of
CoffeeOrderIFand uses it to call the method
getPriceList. Then it accesses the
priceand
namefields of each
Coffeeobject in the array returned by the method
getPriceListin order to print them out.
The class
CoffeeOrderServiceImplis one of the classes generated by the mapping tool. It is a stub factory whose only method is
getCoffeeOrderIF; in other words, its whole purpose is to create instances of
CoffeeOrderIF. The instances of
CoffeeOrderIFthat are created by
CoffeeOrderServiceImplare client side stubs that can be used to invoke methods defined in the interface
CoffeeOrderIF. Thus, the variable
coffeeOrderrepresents a client stub that can be used to call
getPriceList, one of the methods defined in
CoffeeOrderIF.
The method
getPriceListwill block until it has received a response and returned it. Because a WSDL document is being used, the JAX-RPC runtime will get the service endpoint from it. Thus, in this case, the client class does not need to specify the destination for the remote procedure call. When the service endpoint does need to be given, it can be supplied as an argument on the command line. Here is what a client class might look like:package coffees; public class CoffeeClient { public static void main(String[] args) { try { CoffeeOrderIF coffeeOrder = new CoffeeOrderServiceImpl().getCoffeeOrderIF(); Coffee [] priceList = coffeeOrder.getPriceList(): for (int i = 0; i < priceList.length; i++) { System.out.print(priceList[i].getName() + " "); System.out.println(priceList[i].getPrice()); } } catch (Exception ex) { ex.printStackTrace(); } } }
Invoking a Remote Method
Once a client has discovered a Web service, it can invoke one of the service's methods. The following example makes the remote method call
getPriceList, which takes no arguments. As noted previously, the JAX-RPC runtime can determine the endpoint for the CoffeeOrder service (which is its URI) from its WSDL description. If a WSDL document had not been used, you would need to supply the service's URI as a command line argument. After you have compiled the file
CoffeeClient.java, here is all you need to type at the command line to invoke its
getPriceListmethod.
The remote procedure call made by the previous line of code is a static method call. In other words, the RPC was determined at compile time. It should be noted that with JAX-RPC, it is also possible to call a remote method dynamically at run time. This can be done using either the Dynamic Invocation Interface (DII) or a dynamic proxy.
All of the material in The J2EE Tutorial for the Sun ONE Platform is copyright-protected and may not be published in other works without express written permission from Sun Microsystems. | http://docs.oracle.com/javaee/1.3/tutorial/doc/IntroWS5.html | CC-MAIN-2014-15 | refinedweb | 1,954 | 52.6 |
Created on 2013-12-08 05:08 by eric.snow, last changed 2014-01-05 07:12 by eric.snow. This issue is now closed.
(my browser farted the half finished report into existence :P )
The __eq__() implementation of the path-based loaders in importlib is just the stock one that compares object identity. So two that are effectively the same compare unequal. This has a material impact on ModuleSpec. ModuleSpec.__eq__() does a comparision of its various attributes, one of them being the loader. Thus most specs will compare unequal even though they are effectively equal.
I recommend that we provide a better implementation for SourceFileLoader and friends.
Larry: would such a feature addition be okay?
Here's a patch.
There can be some interesting backwards compatibility consequences when adding an __eq__ implementation to a class that was previously using the default ID based __eq__:
- it becomes unhashable (unless you also add a suitable __hash__ definition)
- subclasses with additional significant state may start comparing equal, even though their additional state is not taken into account by the new __eq__ function.
For the latter problem, you can alleviate it by comparing the instance dictionaries rather than specific attributes:
>>> class Example:
... def __eq__(self, other):
... return self.__class__ == other.__class__ and self.__dict__ == other.__dict__
...
>>> a = Example()
>>> b = Example()
>>> a == b
True
>>> a.foo = 1
>>> a == b
False
>>> b.foo = 1
>>> a == b
True
(technically this can still change subclass behaviour if they're messing about with slots, but there *is* such a thing as being *too* paranoid about backwards compatibility)
The hashability problem is easy enough to handle just by mixing together the hashes of the attributes of most interest:
def __hash__(self):
return hash(self.name) ^ hash(self.path)
Brett, could you weigh in please?
I'm fine with the suggestions Nick made. While loaders are not technically immutable (and thus technically probably shouldn't define __hash__), they have not been defined to be mutable and mucked with anyway, so I have no issue if someone breaks the hash of a loader by changing an attribute post-hash.
Good point, Nick. Here's a patch that follows your recommendation on both points.
Unless there are objections, I'll commit this in the next day or two.
That's not how this works, Eric. I have to give you permission to add a new feature, which I remind you I have yet to do.
My bad, Larry. I guess I was reading between the lines too much. :)
That reminds me: I ended up working around this in the runpy tests by only
checking the loader type was correct in the module specs. With an improved
definition of equality for loaders, the runpy tests could be both
simplified *and* made more rigorous at the same time (by simply comparing
specs for equality, the same as the other module level attributes).
Yeah, it was while writing tests that I ran into this.
So can you tell me how this will make users' lives easier? I don't really understand the issues involved. But the only concrete thing I've seen mentioned is making testing easier, and that's not worth breaking feature freeze over.
Yeah, I think we can safely leave this to 3.5.
Right now say you have 2 module specs that are the same. The only difference is that the 2 loaders are not the same instance (they were created separately with the same arguments, ergo equal). The two specs will not compare as equal even though they are equal.
I expect users will find it surprising if they compare module.__spec__ to another spec that is basically the same (as described above) and it resolve to not equal. I can see this as particularly vexing for importer writers that are switching over to the new spec-based APIs.
In my mind, the benefit of removing that unexpected (and aggravating) behavior outweighs the risk that someone is depending on identity-only comparision for the two loader types that are impacted by this change (which were both just added in 3.3).
Importer writers are already used to __loader__ being annoying, and comparting specs for equality is unlikely to be a common thing (and easily worked around by comparing spec.origin instead)
1. Is this patch going to change best practice for working with ModuleSpec?
2. If we delayed it to 3.5, will users have to ignore it to work around the deficiencies of the ModuleSpec implementation in 3.4?
I'm guessing the answer to both of these is "well, no, not really" simply because comparing ModuleSpec objects is not expected to be a regular operation.
Yes, I think it will just make the third party idiom for testing that the
right module was imported to be to check spec.origin rather than comparing
specs directly. It's a nice-to-have, rather than something essential that
justifies breaking feature freeze.
That is, I think the answer to both your questions is actually "Yes, but it
doesn't really matter due to the obscurity of the use case".
I'm fine with this. Thanks, Larry, for your attentiveness and diligence.
So, not to yank your chain, but... I'm okay with checking this in. Yes, we're already in beta, but ModuleSpec is brand new, and the sense I get is that this use case is obscure even for ModuleSpec. The only installed base is beta 1 users, and given that this is new functionality...
Anyway. I expect to tag late tonight, say in twelve hours. Can you check it in before then?
I'll commit it in a little while. Thanks.
New changeset a72a0e4dad20 by Eric Snow in branch 'default':
Issue #19927: Add __eq__ to path-based loaders in importlib.
You broke buildbots. Please fix.
Hmm, hard to see how you caused that with the path loader change. Still please take a quick look.
I fired off another build to see if it was a transient error, but that'll take a while.
I'll take a look. It could be something with #19713 or #19708 that also failed there.
The other failing buildbot for those 3 changesets is.
The windows buildbot failure looks like a race condition in a test unrelated to my changes (see issue #20127). I'm looking at the FreeBSD failure now.
Which passed on the subsequent run...
The FreeBSD failure happened in test_threading (apparently), where it was the last test to "finish". In the passing run it finished 339/388 -- the seed was different (1253928 vs. 5389019).
This does not seem to be related to my 3 changesets. I'm guessing it's one of those lingering race conditions we have sprinkled here and there. | https://bugs.python.org/issue19927 | CC-MAIN-2017-43 | refinedweb | 1,123 | 65.73 |
M5StickC usb driver and Catalina
Hello,
I worked with a M5Stack, Arduino 1.8.x and MacOS Mojave and every thing with USB was fine.
I updated to MacOS Catalina and updated Arduino to version 1.8.10. Every with USB for my M5Stack was fine, too. If I check the USB driver I can see:
$ ls /dev/tty.* /dev/tty.Bluetooth-Incoming-Port /dev/tty.SLAB_USBtoUART /dev/tty.usbserial-017D2264
If I like to flash my M5Stick-C and I connected it, I can see only this:
$ ls /dev/tty.* /dev/tty.Bluetooth-Incoming-Port /dev/tty.usbserial-9D5AE08545
With the old and the new Arduino-version the "tty.usbserial-9D5AE08545"-driver did not work. Arduino needs a "SLAB_USBtoUART"-driver.
What can I do?
Yes, I know today Catalina is a beta-version, but it will released shortly.
What do you mean by does not work the newer gen stick versions only have the number string and work ok but then my OS X is about a year old
There known bugs in Catalina.
Try using the Arduino beta. it "should" work, ...... sometimes. :-(
- lukasmaximus M5Stack last edited by
We don't have a Mac with Catalina on in the office to test, so I think it may take a while before our software supports it.
- o.copleston last edited by
+1 to this issue. I'm unable to flash to any of my M5StickC's at the moment on Catalina, but can flash to my M5 Camera strangely...
- o.copleston last edited by
Ok, here the fix:
- Use the latest CP210x USB to UART driver
- Connect G0 pin to GND
That did the trick for me
Ok sorry I forgot about this until now. If you have an Arduino or an usb to UART adapter you can bypass the inbuilt USB adapter and program M5Stack cores using the UART port
No solution with Catalina did work for me. Only the programming with Windows 10 was working.
Which driver did M5StickC need? A Silicon Labs CP210x-driver?
I installed CP210x Version 5.2.4 and I used Catalina 10.15.3 (19D49f).
- lukasmaximus M5Stack last edited by
As far as I know the esp32 pico, which is inside the stickC does not use the cp210x drivers. Some have reported using standard ftdi drivers to interface with the device. I'm afraid I dont have OS Catalina to test
@lukasmaximus Thank you for your help. In the meantime I tested with Catalina Version 10.15.2 (19C57) and with the drivers from FTDI. I can not program the M5StickC, but the Arduino Monitor did work!
I found the problem: The M5StickC didn't change to upload mode!
I connected a small button between GND and G0 at the 8-ext Pin connector and I pressed the button if Arduino like to upload ("Connecting........_____...."). The workaround worked fine.
Is there any other way to change M5StickC to upload-mode? Ist isn‘t nice to change the connector every time I like to upload a new program. I used a joystick-modul and my upload-modul.
- flippycurb last edited by flippycurb
I can confirm that the workaround "Connect G0 pin to GND" works for me on Catalina 10.15.2. I am now able to write to the m5StickC wheras before it was stuck connecting eventually throwing the error "A fatal error occurred: Failed to connect to ESP32: Timed out waiting for packet header". I am able to reproduce this on two m5StickCs. It's worth noting this is without any 3rd party drivers and after only following the steps given here -
Has there been any progress on resolving the issue?
In the meantime I tested three M5StickC and can not program anyone without "Connect G0 pin to GND". I changed from Arduino to esp-idf and got the same issue.
After some analysis, I separated the problem: I think the esptool.py didn't work correct with the cp210x drivers. The critical part is:
def _connect_attempt(self, mode='default_reset', esp32r0_delay=False): """ A single connection attempt, with esp32r0 workaround options """ # esp32r0_delay is a workaround for bugs with the most common auto reset # circuit and Windows, if the EN pin on the dev board does not have # enough capacitance. # # Newer dev boards shouldn't have this problem (higher value capacitor # on the EN pin), and ESP32 revision 1 can't use this workaround as it # relies on a silicon bug. # # Details: last_error = None # If we're doing no_sync, we're likely communicating as a pass through # with an intermediate device to the ESP32 if mode == "no_reset_no_sync": return last_error # issue reset-to-bootloader: # RTS = either CH_PD/EN or nRESET (both active low = chip in reset # DTR = GPIO0 (active low = boot to flasher) # # DTR & RTS are active low signals, # ie True = pin @ 0V, False = pin @ VCC. if mode != 'no_reset': self._setDTR(False) # IO0=HIGH self._setRTS(True) # EN=LOW, chip in reset time.sleep(0.1) if esp32r0_delay: # Some chips are more likely to trigger the esp32r0 # watchdog reset silicon bug if they're held with EN=LOW # for a longer period time.sleep(1.2) self._setDTR(True) # IO0=LOW self._setRTS(False) # EN=HIGH, chip out of reset if esp32r0_delay: # Sleep longer after reset. # This workaround only works on revision 0 ESP32 chips, # it exploits a silicon bug spurious watchdog reset. time.sleep(0.4) # allow watchdog reset to occur time.sleep(0.05) self._setDTR(False) # IO0=HIGH, done for _ in range(5): try: self.flush_input() self._port.flushOutput() self.sync() return None except FatalError as e: if esp32r0_delay: print('_', end='') else: print('.', end='') sys.stdout.flush() time.sleep(0.05) last_error = e return last_error def connect(self, mode='default_reset'): """ Try connecting repeatedly until successful, or giving up """ print('Connecting...', end='') sys.stdout.flush() last_error = None try: for _ in range(7): last_error = self._connect_attempt(mode=mode, esp32r0_delay=False) if last_error is None: return last_error = self._connect_attempt(mode=mode, esp32r0_delay=True) if last_error is None: return finally: print('') # end 'Connecting...' line raise FatalError('Failed to connect to %s: %s' % (self.CHIP_NAME, last_error))
The esptool.py used reset with DTR and RTS and I suspect this part did not work correct, because any print of '.' or '_' showed a (fatal) error.
My short test for all existing ports showed the error:
$IDF_PATH/components/esptool_py/esptool/esptool.py chip_id
@sheepdog this problem from MAC OS FTDI driver , you can try to use WIN10 OS (like using a virtual machine) to upload program. also M5StickC Upload program don't need CP2104 Driver.
@m5stack Thank you for your quick response. I am sure that Mac OS Catalina need a driver. A few days ago I installed Mac OS 10.15.2 form scratch and M5StickC needs the cp210x-driver (M5Stack needs the FTDI driver!).
You can test it. If you connect a M5StickC you see at the directory /dev a file with this name "cu.usbserial-<number>". With connected M5Stack you see "cu.SLAB_USBtoUART" (<- This is the FTDI driver).
My workaround is "Connect G0 pin to GND". That is not nice. Your solution to start a VM is even more complex because all need all my files there.
Yes, I can program M5StickC, but I am looking for an easy way to program M5StickC with short turn around times and easy handling. Normally I used Atom editor with PlatformIO.
@m5stack could you please advise on the best process for getting M5StickC to work and flash via esptool on Mac OS Catalina ?
Also, advise on which driver is needed for M5StickC. Is it the FTDI driver or is it the CP210X driver ?
@tcruse first , on some Mac PC, M5StickC cannot upload program properly.
the solution: When programming, short the G0 to GND using the DuPont line.
and , all most PC don't need driver with M5StickC. But some old PC System need install FTDI driver.
FTDI driver is for M5StickC, CP2104 driver is for M5Stack Core ( like Fire BASIC M5GO)
@m5stack Yes, I swapped the drivers. You can check it at Apple menu, systemreport and USB.
If I connected a M5Stack I saw:
If I connected a M5StickC I saw:
You can check the loaded drivers and their versions in terminal with "sudo kextstat".
I noticed that sometimes M5Stack didn't not work without "short the G0 to GND". I think that is a timing-problem at Catalina and esptool.py. It is not a problem of M5Stack- or M5StickC-Software.
I formulated an Issue at Github: Link to Issue
Supplement on January 18, 2020: You need an Espressif account to see the issue. | https://forum.m5stack.com/topic/1369/m5stickc-usb-driver-and-catalina | CC-MAIN-2021-39 | refinedweb | 1,429 | 66.03 |
Introduction to Custom Ant Tasks
Example Two: Optional Attributes Support
I will now expand on the previous example by adding an attribute to your task. Consider that you desire to have an optional attribute for your task. The value of this attribute will be a person's name, such as Bob, and you will say "Hello, Bob!" instead of "Hello, World!" if this attribute is set. (If the name attribute is omitted, you'll fall back to the original message.)
You provide attribute support by adding the necessary instance variable in your class and providing a corresponding getter/setter method for it. The name of the attribute should match the name of your instance variable so that Ant can most easily determine which getter/setter method is involved as it is processing your custom task. (Chalk it up to some reflection magic.) In other words, if you decide you want an optional "name" attribute in your custom task, you need to create a "name" instance variable and a standard getName/setName method pair. For a build.xml file that looks like this...
<project name="demo" basedir="." default="demo"> <taskdef resource="MyAntTasks.properties" classpath="mytasks.jar"/> <target name="demo"> <helloworld name="Bob"/> </target> </project>
package org.roblybarger.ant.taskdefs; import org.apache.tools.ant.Task; import org.apache.tools.ant.Project; public class HelloWorld extends Task { private String name=null; public void setName(String name) { this.name = name; } public String getName() { return name; } public void execute() { if (name != null && name.length() > 0) { log("Hello, " + name + "!", Project.MSG_INFO); } else { log("Hello, World!", Project.MSG_INFO); } } }
Recompile and update your jar file. Run Ant both with and without the additional attribute present. For the sample build.xml file I showed at the beginning of this section, you should get:
Buildfile: build.xml demo: <helloworld> Hello, Bob! BUILD SUCCESSFUL Total time: 0 seconds
Property References in Attributes
You may refer to properties defined elsewhere in the build.xml file when you set the value of an attribute for your custom task—Ant automatically will expand the property before it calls the setter method in your code. In other words, name="${first} ${last}" would work fine without your needing to detect, parse, and replace the values on your own.
Case-Insensitivity
The exact case for your attribute name does not need to exactly match that of the instance variable in your Java class. In general, attribute names can also be entirely in lower case. In other words, if your instance variable is called "intValue", it is fine for the attribute to be named "intvalue" in the build.xml file.
Type Conversions to Non-String Variables
Ant does provide some automatic type conversions as necessary, so the instance variables in your Java code can be primitive types such as int or boolean or object types such as File.
To see any of the above comments illustrated, view the downloadable files for this example.
Example Three: Required Attributes and Conditionally Failing the Build
Now, consider the case where you insist the name attribute to be given, meaning it is no longer an optional attribute. Where, in Example Two, you were checking for a null (or zero length) value and emitting the default message, you now will cause the Ant output to say "BUILD FAILED" and halt operation. This is done by throwing an org.apache.tools.ant.BuildException object.
Note: I am showing only an updated execute method here.
public void execute() throws BuildException { if (name != null && name.length() > 0) { log("Hello, " + name + "!", Project.MSG_INFO); } else { throw new BuildException("name attribute is required."); } }
Now, update the build.xml file to use this both with and without the required attribute to see the effect:
<project name="demo" basedir="." default="demo"> <taskdef resource="MyAntTasks.properties" classpath="mytasks.jar"/> <target name="demo"> <helloworld name="Bob"/> <helloworld/> </target> </project>
Running this without the name attribute in the build.xml file should result in this:
Buildfile: build.xml demo: [helloworld] Hello, Bob! BUILD FAILED /Users/rob/Projects/Articles/Article1/ex3_files/build.xml:7: name attribute is required. Total time: 0 seconds
Reasons for you to do this might involve some critical file not being present (or readable), some required property not being set as expected, or whatever else might cause your business logic to go horribly awry. To address some problems ahead of time, you might be able to have some default values; however, I encourage you to emit a "WARNING" level log message that informs the user (which may be you, later, when you forgot how your task works) that a default value is being used.
Page 2 of 3
| http://www.developer.com/java/article.php/10922_3630721_2/Introduction-to-Custom-Ant-Tasks.htm | CC-MAIN-2014-42 | refinedweb | 768 | 57.77 |
Autocache - An automatic caching framework for Perl.
use Autocache; autocache 'my_slow_function'; sub my_slow_function { ... }
This code came about as the result of attempting to refactor, simplify and extend the caching used on a rather large website.
It provides a framework for configuring multiple caches at different levels, process, server, networked and allows you to declaratively configure which functions have their results cached, and how.
Autocache acts a lot like the Memoize module. You tell it what function you would like to have cached and if you say nothing else it will go ahead and cache all calls to that function in-process, you just specify the name of the function.
In addition to this though Autocache allows you to specify in great detail how and where function results get cached.
The module uses IoC/dependency injection from a configuration file to setup a number Strategies. These are the basic building blocks used to determine how things get cached.
Strategies determine how a cached value should be validated, refreshed, and even whether or not the value should be stored at all.
The goal here is to make it stupidly simple to start to cache certain functions, and change where and how those values get cached if you find they're in the wrong place.
There are a number of considerations when using autocache, or any caching mechanism.
Any function that is pure should have no trouble being cached.
A pure function being one;
If your function does depend on external state then you may or may not be able to use some form of caching. For example if your function depends on one of a number of states that may be the current one then you can always create a new function that does depend on all of that information and make the current function simply a driver for it.
For example, the function below depends on the state of a global variable
$mode.
autocache 'authorised'; sub authorised { my ($user,$resource,$action) = @_; if( $mode eq 'normal' ) { ...normal mode code... } elsif( $mode eq 'strict' ) { ...strict mode code... } else { ...all other mode code... } }
If this function is cached then autocache will cache the value generated for whatever the
$mode variable is set to at the time of the first invocation, if this function is invoked again later on it may produce incorrect results since the value of
$mode has changed.
We can still gain a speedup through caching but we have to rewrite it slightly to make sure we're caching a pure function.
autocache '_authorised_by_mode'; sub authorised { my ($user,$resource,$action) = @_; return _authorised_by_mode($user,$resource,$action,$mode); } sub _authorised_by_mode { my ($user,$resource,$action,$mode) = @_; if( $mode eq 'normal' ) { ...normal mode code... } elsif( $mode eq 'strict' ) { ...strict mode code... } else { ...all other mode code... } }
Now even though the
authorised function is still dependant upon the global
$mode variable the new
_authorised_by_mode function is entirely dependant upon it's input parameters and nothing more and it can be cached.
Function results are cached based on the arguments to the function. For functions whose arguments are position dependant and are simple values autocache should simply do the right thing.
Two cases where autocache will require help are when the arguments to a function are provided through a hash, or more complex data structure and when objects/references are passed around that are equivalent but where the identities of the references are not.
For example, if a function 'fn' accepts a hash containing one or more parameters named 'a', 'b', 'c' and 'd' then the following calls are equivalent but autocache can't tell that.
fn( 'a', 3, 'd', 4 ); fn( 'd', 4, 'a', 3 )
To overcome this you can provide a normalisation function that takes the parameters that are passed to the function and provides a canonical string version that ensures equivalent calls appear to be the same to autocache. Obviously care should be taken when designing a normalisation function where the inputs may be large. (TODO - cookbook for normalisation)
To allow autocache to automatically pick up your normalisation function it should be named the same as the function it provides normalisation for but prefixed with '_normalise_'.
For the above function we could use something like this;
sub _normalise_fn { my (%hash) = @_; return join ':', map { "$_=$hash{$_}" } sort keys %hash; }
Perl functions are called in one of three contexts.
Autocache automatically maintains seperate caches for each of the first two contexts that functions may be called in. Since it expects functions to be pure it understands when a function is called in void context and does nothing at all since the value will not be used.
TODO - add option to merge all contexts into one if the author knows that the same value is returned in either scalr or list context.
Autocache initially split up the process of caching into generating the values and storing the values. This has since been unified under the banner of 'strategies'. There is a 'Store' namespace in 'Strategy', intended to represent strategies that involve storage.
Strategies may be chained. Some examples of Strategies are CostBased, Refresh, Store::Memory and Store::Memcached.
The API for Strategies is not yet completely fixed but you should be able to quite easily take one of those that already exists and modify it to suit your needs. The configuration syntax allows you to use any custom classes you like as long as they can accept the way we perform IoC (sub-optimal right now).
Test, test, test.
Loads, and adding more all the time. This code is yet to become stable.
This module is Copyright (c) 2010 Nigel Rantor. England. All rights reserved.
You may distribute under the terms of either the GNU General Public License or the Artistic License, as specified in the Perl README file.
This module is free software. IT COMES WITHOUT WARRANTY OF ANY KIND.
Nigel A Rantor - <wiggly@wiggly.org>
Rajit B Singh - <rajit.b.singh@gmail.com> | http://search.cpan.org/~wiggly/Autocache-0.004/lib/Autocache.pm | CC-MAIN-2014-35 | refinedweb | 992 | 62.78 |
curs_addstr(3x) curs_addstr(3x)
addstr, addnstr, waddstr, waddnstr, mvaddstr, mvaddnstr, mvwaddstr, mvwaddnstr - add a string of characters to a curses window and advance cursor
#include <curses.h> int addstr(const char *str); int addnstr(const char *str, int n); int waddstr(WINDOW *win, const char *str); int waddnstr(WINDOW *win, const char *str, int n); int mvaddstr(int y, int x, const char *str); int mvaddnstr(int y, int x, const char *str, int n); int mvwaddstr(WINDOW *win, int y, int x, const char *str); int mvwaddnstr(WINDOW *win, int y, int x, const char *str, int n);
These functions write the (null-terminated) character string str on the given window. It is similar to calling waddch once for each byte in the string. The mv functions perform cursor movement once, before writing any char- acters. Thereafter, the cursor is advanced as a side-effect of writing to the window. The four functions with n as the last argument write at most n bytes, or until a terminating null is reached. If n is -1, then the entire string will be added.
All functions return the integer ERR upon failure and OK on success. X/Open does not define any error conditions. This implementation re- turns an error o if the window pointer is null or o if the string pointer is null or o if the corresponding calls to waddch return an error. Functions with a "mv" prefix first perform a cursor movement using wmove, and return an error if the position is outside the window, or if the window pointer is null. If an error is returned by the wmove, no characters are added to the window. If an error is returned by waddch (e.g., because the window is not large enough, or an illegal byte sequence was detected) only part of the string may be added. Aside from that, there is a special case in waddch where an error may be returned after successfully writing a character to the lower-right corner of a window when scrollok is dis- abled.
All of these functions except waddnstr may be macros.
These functions are described in the XSI Curses standard, Issue 4.
curses(3x), curs_addch(3x). curs_addstr(3x) | http://ncurses.scripts.mit.edu/?p=ncurses.git;a=blob_plain;f=doc/html/man/curs_addstr.3x.html;hb=89730563d0a660d4ddd83d28660dc23c6d3f0bed | CC-MAIN-2020-50 | refinedweb | 371 | 67.38 |
This article covers features introduced in SpiderMonkey 31
Initializes the JS engine so that further operations can be performed.
Syntax
#include "js/Initialization.h" // previously "jsapi.h" bool JS_Init(void);
Description
Initialize SpiderMonkey, returning true only if initialization succeeded. Once this method has succeeded, it is safe to call
JS_NewRuntime and other JSAPI methods.
This method must be called before any other JSAPI method is used on any thread. Once it has been used, it is safe to call any JSAPI method, and it remains safe to do so until
JS_ShutDown is correctly called.
It is currently not possible to initialize SpiderMonkey multiple times (that is, calling
JS_Init, JSAPI methods, then
JS_ShutDown in that order, then doing so again). This restriction may eventually be lifted.
In the past
JS_Init once had the signature
and was used to create new
JSRuntime * JS_Init(uint32_t maxbytes)
JSRuntime instances. This meaning has been removed; use
JS_NewRuntime instead. | https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/JSAPI_Reference/JS_Init | CC-MAIN-2017-43 | refinedweb | 153 | 57.77 |
Details
- Type:
Bug
- Status: Closed
- Priority:
Major
- Resolution: Fixed
- Affects Version/s: 2.0-beta2
-
- Component/s: Configurators
- Labels:None
- Environment:
Environment:
JDeveloper 11.1.1.6.0
logj42 (apache-log4j-2.0-beta2-bin)
Windows 7 64bits
Description
This issue was incorrectly opened in bugzilla as by Evgeny.
Steps to Reproduce:
//config file presents or not - does not meter.
Run / Debug simple application:
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class test_log {
public test_log()
static Logger logger = LogManager.getLogger(test_log.class.getName());
public static void main(String[] args){ test_log test_log = new test_log(); logger.entry(); logger.debug("test"); logger.error("test Err"); logger.exit(); }
...
}
Actual Results:
Failed with error
java.lang.ExceptionInInitializerError
at view.test_log.<clinit>(test_log.java:13).logging.log4j.LogManager.<clinit>(LogManager.java:77)
Additional Info:
When xmlparserv2.jar is deleted - application run fine.
But - it have to be presents - when deleted, JDeveloper failed to start.
Activity
- All
- Work Log
- History
- Activity
- Transitions
Ralph, from my reading of the JDK bug report, Oracle has fixed the bug in various versions of Java.
They appear to have fixed it in 6u29 and backported the fix to various places.
Unfortunately I don't see a easy work-around, short of cut and pasting a fair chunk of code from java.util.Properties and java.util.XMLUtils into LogManager.
Ralph, Noel
Thanks for your quick replay.
Is it some way to skip LogManager configuration loading? If i'll configure it in the code instead of config file - file it allow me to bypass this issue?
By the way - if I'll use stable (not beta) release of log4j (1.x) - will it also use same way to load configuration?
We just need to decide about logging framework for our new project, and this issue is look like blocker for us.
Thanks!
I am looking at addressing this in at least two ways.
1. I'm going to switch from using loadFromXML to load and convert the properties file from XML to a "normal" properties format.
2. I'm planning on creating a combined jar where the api and core are merged together. There will still be some binding but it will use a (hopefully) simpler method.
Log4j 1.x does not use this mechanism because there is no separation between the API and implementation.
I attempted to verify the problem by running the above program in JDeveloper on both my Mac and Windows 7, but neither experienced the problem. I was running JDeveloper 11.1.2.3.0 on Windows 7 64 bit with JDK 1.6.0_24. This is going to make it difficult for me to verify that the change I'm implementing actually fixes the problem.
Ralph,
Do you have xmlparserv2.jar in your classpath? It is the root of my issue.
I did nothing special. My understanding was that simply trying to test under JDeveloper caused the problem. Your report says removing xmlparserv2 causes JDeveloper not to start. Is there something else I need to do to cause the problem?
FYI - I created a Maven project with the code above as the only application. I then imported the application, which was a bit frustrating as it didn't seem to accomplish much. I then had to manually add the log4j 2 jars into the classpath along with target/classes and had to make a couple of other changes so that it knew how things were laid out in the project. I then ran the application from JDeveloper and it ran fine.
I was able to manually add the xmlparserv2 jar to the classpath and duplicate the error. I'm still not sure why this jar is required but I have changed LogManager to use a regular properties file and verified it works even with Oracle's jar present.
Please verify the fix and close this.
Ralph,
Sorry, but I am new in Jira and Bugzilla. Where can I obtain the fixed version (beta-3) - I want verify it on my environment? On the log4j download page it is only beta2 available.
Thank you!
beta-3 has not been released yet so right now you can only test against 2.0-beta3-SNAPSHOT. You have to check it out from subversion and build it yourself or I could deploy the artifacts to the Apache snapshot repository but you would need to add that to your list of repositories.
See for information on how to check out the source. To build just run mvn clean install in the root directory of the checked out project.
If its possible - i'll prefer you to build it and i'll download the artifacts.
Thank you
By the way - do you have approximation for the final release of log4j2?
Ralph,
I think I did not explain myself right - I just switched to java from dot net, so I still not so comfortable with java environment. This is the reason I prefer to download ready build - i want to verify the fix but avoid invalid builds and other issues as well as my svn invalid work errors.
Thank you!
Ralph, hello
I several times tried to check out via svn the sources to compile them.
I was not able to find snapshot 2.0-beta3-SNAPSHOT.
When are you planing to release next version of log4j2? I cannot use it now in my code, it is blocking me now... I also cannot verify the fix.
Thank you!
I had planned to start the release yesterday but my day job got in the way. I just deployed the snapshots so you can give it a try.
Hi Ralph
I was out of office, so I was able to test the fix only now.
It is working as expected.
Thank you!
Need I change the status of this issue?
The reporter of this problem also has asked on Oracle's forum for a solution -. In addition, I see at least one other similar report -. A bug was also opened against the JDK - - which was closed as being a bug in XMLUtils. It appears Oracle is simply ignoring this bug. | https://issues.apache.org/jira/browse/LOG4J2-104 | CC-MAIN-2016-50 | refinedweb | 1,020 | 67.04 |
Provided by: lxc1_2.0.0-0ubuntu2_amd64
. List options, like capabilities and cgroups options, can be used with no value to clear any previously defined values of that REBOOT SIGNAL Allows one to specify signal name or number, sent by lxc-stop to reboot the container. This option allows signal to be specified in kill(1) fashion, e.g. SIGTERM, SIGRTMIN+14, SIGRTMAX-10 or plain number. The default signal is SIGINT. lxc.rebootsignal specify the signal used to reboot INIT COMMAND Sets the command to use as the init system for the containers. This option is ignored when using lxc-execute. Defaults to: /sbin/init lxc.init_cmd Absolute path from container rootfs to the binary to use as init. INIT ID Sets the UID/GID to use for the init system, and subsequent command, executed by lxc- execute. These options are only used when lxc-execute is started in a private user namespace. Defaults to: UID(0), GID(0) lxc.init_uid UID to use within a private user namesapce for init. lxc.init_gid GID to use within a private user namesapce for init. EPHEMERAL Allows one to specify whether a container will be destroyed on shutdown. lxc.ephemeral The only allowed values are 0 and 1. Set this to 1 to destroy a container on shutdown. may be used without a value to clear all previous network options. virtual ethernet pair device is created with one side assigned to the container and the other side attached to a bridge specified by the lxc.network.network.veth.pair option (except for unprivileged containers where this option is ignored for security reasons)..logfile Specify a path to a file where the console output will be written. lxc.console Specify a path to a device to which the console will be attached.. ENABLE KMSG SYMLINK Enable creating /dev/kmsg as symlink to /dev/console. This defaults to 0. lxc.kmsg Set this to 1 to enable his home directory at just the right time. lxc.mount specify a file location in the fstab format, containing the mount information. The mount target location can and in most cases should be a relative path, which will become relative to the mounted container root. For instance, proc proc proc nodev,noexec,nosuid 0 0 .fi add two options to mount. optional don't fail if mount does not work. create=dir or create=file to create dir (or file) when the point will be mounted.:mixed (or sys): mount /sys as read-only but with /sys/devices/virtual/net writable. · sys:ro: mount /sys as read-only for security / container isolation purposes. · sys:rw: mount /sys as read-write · cgroup:mixed: (without specifier): defaults to cgroup:rw if the container retains the CAP_SYS_ADMIN capability, cgroup:mixed otherwise. ·.) ·. aufs:/lower:/upper does the same using aufs in place of overlayfs. For both overlayfs and aufs multiple /lower directories can be specified. loop:/file tells lxc to attach /file to a loop device and mount the loop device..rootfs.backend specify the rootfs backend type to use, for instance 'dir' or 'zfs'. While this can be guessed by lxc at container startup, doing so takes time. Specifying it here avoids extra processing.. APPARMOR PROFILE othewise. lxc.aa_profile Specify the apparmor profile under which the container should be run. To specify that the container should be unconfined, use lxc.aa_profile = unconfined If the apparmor profile should remain unchanged (i.e. if you are nesting containers and are already confined), then use lxc.aa_profile = unchanged lxc.aa_context Specify the SELinux context under which the container should be run or unconfined_t. For example lxc.se_context = system_u:system_r:lxc_t:s0:c. In the case of the stop hook, paths to filedescriptors for each of the container's namespaces along with their types are passed..container.conf(5) | http://manpages.ubuntu.com/manpages/xenial/man5/lxc.container.conf.5.html | CC-MAIN-2019-43 | refinedweb | 635 | 59.7 |
Keywords or entities are condensed form of the content are widely used to define queries within information Retrieval (IR).
Keyword extraction or key phrase extraction can be done by using various methods like TF-IDF of word, TF-IDF of n-grams, Rule based POS tagging etc.
But all of those need manual effort to find proper logic.
In this topic I will show you how to do (automatically) keyword extraction or key phrase extraction using package called Pytextrank in Python which is based on Text Rank algorithm of Google.
Also Read:
- AUTOMATIC KEYWORD EXTRACTION USING RAKE IN PYTHON
- AUTOMATIC KEYWORD EXTRACTION USING TOPICA IN PYTHON
After reading this post you will know:
- Why to do keyword extraction
- Keyword extraction using TextRank in Python
- What is happening at background?
Why to do keyword extraction:
- You can judge a comment or sentence within a second just by looking at keyword of a sentence.
- You can make decision whether the comment or sentence is worth reading or not.
- Further you can categorize the sentence to any category. For example whether a certain comment is about mobile or hotel etc.
- You can also use keywords or entity or key phrase as a feature for your supervised model to train.
Setting up PyTextRank in python:
Type python –m pip install pytextrank in cmd
Download SmartStoplist.txt from
Keep SmartStoplist.txt inside your working directory(the folder where you are saving your python directory)
Keyword extraction using PyTextRank in Python:
While doing key phrase extraction, Pytextrank process text into two stages to do keyword extraction.
Stage 1:
In stage 1 it do some text cleaning and processing stuff like below:
- Index each word of text.
- Lemmatize each word
Stage2:
Stage 2 based on some logic it come up with important keywords or entity or key phrase with their ranks.
First let’s try to extract key phrases from sample text in python then will move on to understand how pytextrank algorithm works.
Note: If you are getting error saying:
TypeError Traceback (most recent call last)
<ipython-input-6-7dbb39972cd2> in <module>()
13
14 with open(path_stage1, 'w') as f:
---> 15 for graf in pytextrank.parse_doc(pytextrank.json_iter(path_stage0)):
16 f.write("%s\n" % pytextrank.pretty_print(graf._asdict()))
17 print(pytextrank.pretty_print(graf._asdict()))
C:\Users\anindya\Anaconda2\lib\site-packages\pytextrank\pytextrank.pyc in parse_doc(json_iter)
259 print("graf_text:", graf_text)
260
--> 261 grafs, new_base_idx = parse_graf(meta["id"], graf_text, base_idx)
262 base_idx = new_base_idx
263
C:\Users\anindya\Anaconda2\lib\site-packages\pytextrank\pytextrank.pyc in parse_graf(doc_id, graf_text, base_idx, spacy_nlp)
191 markup = []
192 new_base_idx = base_idx
--> 193 doc = spacy_nlp(graf_text, parse=True)
194
195 for span in doc.sents:
TypeError: __call__() got an unexpected keyword argument 'parse'
Go to your Anaconda directory and then Lib->site-packages->pytextrank
(For me full path was C:\Users\anindya\Anaconda2\Lib\site-packages\pytextrank)
Open pytextrank.py, search for “parse=True”. You should find this term twice in whole script.
Remove “parse=True” from those line.
For example:
Previously:
doc = spacy_nlp(graf_text, parse=True)
After Removing:doc = spacy_nlp(graf_text)
Stage1:
# Pytextrank import pytextrank import json # Sample text" # Extract keyword using pytextrank with open(path_stage1, 'w') as f: for graf in pytextrank.parse_doc(pytextrank.json_iter(path_stage0)): f.write("%s\n" % pytextrank.pretty_print(graf._asdict())) print(pytextrank.pretty_print(graf._asdict()))
Output:
{"graf": [[0, "I", "i", "PRP", 0, 0], [1, "Like", "like", "VBP", 1, 1], [2, "Flipkart", "flipkart", "NNP", 1, 2], [0, ".", ".", ".", 0, 3]], "id": 0, "sha1": "c09f142dabeb8465f5c30d1c4ef7a0d842ffb99c"} {"graf": [[0, "He", "he", "PRP", 0, 4], [1, "likes", "like", "VBZ", 1, 5], [3, "Amazone", "amazone", "NNP", 1, 6], [0, ".", ".", ".", 0, 7]], "id": 0, "sha1": "307041869f5cba8a798708d64ee83f290098e00a"} {"graf": [[0, "she", "she", "PRP", 0, 8], [1, "likes", "like", "VBZ", 1, 9], [4, "Snapdeal", "snapdeal", "NNP", 1, 10], [0, ".", ".", ".", 0, 11]], "id": 0, "sha1": "cfd16187a0ddb43d4e412ae83acc9312fc0da922"} {"graf": [[2, "Flipkart", "flipkart", "NN", 1, 12], [0, "and", "and", "CC", 0, 13], [3, "amazone", "amazone", "JJ", 1, 14], [5, "is", "be", "VBZ", 1, 15], [0, "on", "on", "IN", 0, 16], [6, "top", "top", "NN", 1, 17], [0, "of", "of", "IN", 0, 18], [7, "google", "google", "NNP", 1, 19], [8, "search", "search", "NN", 1, 20], [0, ".", ".", ".", 0, 21]], "id": 0, "sha1": "f70b4cb49e04ac5586a4b07898212a7bbb673649"}
Stage2:))
Output:
["google search", 0.32500626838725255, [7, 8], "np", 1] ["search", 0.16250313419362628, [8], "nn", 1] ["top", 0.12701509697944047, [6], "nn", 1] ["amazone", 0.12383387876447217, [3], "np", 1] ["google", 0.08783938094837528, [7], "nnp", 1] ["snapdeal", 0.08690112036341668, [4], "np", 2] ["flipkart", 0.08690112036341668, [2], "np", 3]
How Pytextrank Algorithm Works?
Stage1:
Let’s recall what happened at stage 1.
Input:
“I like flipkart.”
Output:
[[0, "I", "i", "PRP", 0, 0], [1, "Like", "like", "VBP", 1, 1], [2, "Flipkart", "flipkart", "NNP", 1, 2], [0, ".", ".", ".", 0, 3]]
Now what is [0, "I", "i", "PRP", 0, 0] this means.
This implies:
[word_id, raw_word, lemmetize_lower_word, POS_tag, keep, idx]
Now let’s understand what those tags are.
word_id: Id from unique word dictionary whose Parts-of-Speech is starting with 'v', 'n' and 'j'.
For example : our sample text was:
'I Like Flipkart.He likes Amazone. she likes Snapdeal. Flipkart and amazone is on top of google search.'
So dictionary of unique word, whose Parts-of-Speech (POS) starts with 'v', 'n' and 'j' will be like:
word_id: After filtering out data based on Parts-of-Speech (starting from v, n, j). Word_id will be id of those unique words based on appearance in the text.
Raw_word: Raw word is input word like: “Flipkart”, “Amazone” etc.
Related Article:
lemmatize_lower_word:1. Lower version of each word like “Flipkart” to “flipkart”
2. Lemmatize version of each word like: “is” to “be”. “likes” to “like”. i/he/she will converted to same word whose pos will be -PRON- etc.
keep: If pos starts with 'v', 'n', 'j' then keep = 1 else 0
idx: It will auto increase word by word.
Now Stage2
Stage2:
Stage 2 is doing its job in two steps.
Step1:
- First it draw weighted graph
- Then it calculates rank of each word based on google page rank algorithm.
import networkx as nx import pylab as plt # Draw network plot nx.draw(graph, with_labels=True) plt.show()
Output:
Words from Google Page Rank Algorithm (Page Rank words)
ranks = nx.pagerank(graph) print(ranks)
Output:
{u'be': 0.12312834625371089, u'search': 0.25443914067175, u'google': 0.13753443412982308, u'like': 0.053012554310560484, u'top': 0.19887377734684572, u'snapdeal': 0.06803267671851249, u'amazone': 0.09694639385028486, u'flipkart': 0.06803267671851249}
Step2:
1. Collect Keyword:
Select those words if word_id > 0, word is available in ranks words (PageRank words, words which are labelled in above network plot), words is noun or verb i.e. POS starts with "N"or "V", and not a stop word.
2. Collect Entities:
Select word after removing cardinal type entities and stop words.
3. Collect Phrases:
a) Select those two words which comming one ofter one and if word_id > 0, word is in rank list (PageRank)
b) Rank of a phrase will be the rank of first word of that phrase from PageRank(google PageRank).
Combine all:
a) Scale all ranks between 0 to 1
b) Combine all together.
import pytextrank import sys import json # Stage 1:" with open(path_stage1, 'w') as f: for graf in pytextrank.parse_doc(pytextrank.json_iter(path_stage0)): f.write("%s\n" % pytextrank.pretty_print(graf._asdict())) print(pytextrank.pretty_print(graf._asdict())) # Stage 2 extract keywords)) ## Google Page Rank import networkx as nx import pylab as plt nx.draw(graph, with_labels=True) plt.show()
Conclusion:
In this tutorial you learned:
- What is keyword?
- Why to do keyword extraction?
- Setting up PyTextRank for python
- Keyword extraction using PyTextRank in python
- What is happening at background of PyTextRank?
Related Article:
If you have any questions type those in comment box. I will try my best to answer those. | https://www.thinkinfi.com/2018/09/keyword-extraction-python-textrank.html | CC-MAIN-2020-34 | refinedweb | 1,281 | 66.23 |
The Material Design language was created for any platform, not just Android. When you write a Material app in Flutter, it has the Material look and feels on all devices, even iOS. If you want your app to look like a standard iOS-styled app, then you would use the Cupertino library.
You can technically run a Cupertino app on either Android or iOS, but (due to licensing issues) Cupertino won’t have the correct fonts on Android. For this reason, use an iOS-specific device when writing a Cupertino app.
What you’ll build?
In this tutorial, you’ll build a shopping app with an iOS materialistic design using the Flutter SDK. Your app will have:
- Three tabs for Products, Search and Cart.
- Holistic flow for buying any product.
- Use the
providerpackage to manage state between screens.
This tutorial focuses on building important components and Cupertino layout. Non-relevant concepts and code blocks are glossed over and are provided for you to simply copy and paste.
Github Repository | @ShivamGoyal1899
Package Used | provider
Setting up Flutter on your machine
The detailed steps to install Flutter on your personal computer & getting started with Flutter is available at the following blog post here.
Coding the application
Create the initial Cupertino app
- Create a simple templated Flutter app, using the instructions in the above blog. Name the project cupertino_store. You’ll be modifying this starter app to create the finished app.
- Replace the contents of
main.dartwith the following code.
- Add a file to the
libdirectory called
styles.dart. The
Stylesclass defines the text and color styling to customize the app.
- Add the following
CupertinoStoreAppclass to
lib/app.dart.
- Add the following
CupertinoStoreHomePageclass to
lib/app.dartto create the layout for the homepage.
- At the top of the project, edit the
pubspec.yamlfile. Add the libraries that you will need, and a list of the image assets.
Create the structure for a 3-tab app
- The final app features 3 tabs:Product list | Product search | Shopping cart
- Replace the
CupertinoStoreHomePageclass with the following, which sets up a 3-tab scaffold:
- Create a
lib/product_list_tab.dartfile for the first tab that compiles cleanly, but only displays a white screen. Use the following content:
- Create a
lib/search_tab.dartfile that compiles cleanly, but only displays a white screen. Use the following content:
- Create a
lib/shopping_cart_tab.dartfile that compiles cleanly, but only displays a white screen. Use the following content:
- Update the import statements in
lib/app.dartto pull in the new tab widgets:
Add state management
- Create a
modeldirectory under
lib. Add a
lib/model/product.dartfile that defines the product data coming from the data source:
- Create a
lib/model/products_repository.dartfile. This file contains all products for sale. Each product belongs to a category.
- Here is the list of method signatures provided by this class.
- In the
main()method, initialize the model. Add the lines marked with NEW.
List products for sale
- Create the
lib/product_row_item.dart file, with the following content:
- In
lib/product_list_tab.dart, import the
product_row_item.dartfile.
import 'package:flutter/cupertino.dart';
import 'package:provider/provider.dart';
import 'model/app_state_model.dart';
import 'product_row_item.dart'; // add this line
- In the
build()method for
ProductRowTab, get the product list and the number of products. Add the new lines indicated below:
- Also in the
build()method, add a new sliver to the sliver widgets list to hold the product list. Add the new lines indicated below:
Add product search
- Update the imports in
lib/search_tab.dart. Add imports for the classes that the search tab will use:
- Update the
build()method in
_SearchTabState. Initialize the model and replace the
CustomScrollViewwith individual components for searching and listing.
- Add supporting variables, functions, and methods to the
_SearchTabStateclass. These include
initState(),
dispose(),
_onTextChanged(), and
_buildSearchBox(), as shown below:
- Create a new file,
lib/search_bar.dart. The
SearchBarclass handles the actual search on the product list. Seed the file with the following content:
Add customer info
- Update the
lib/shopping_cart_tab.dartfile. Add private methods for building the name, email, and location fields. Then add a
_buildSliverChildBuildDelegate()method that builds out parts of the user interface.
- Update the
build()method in the
_SearchTabStateclass. Add a
SliverSafeAreathat calls the
_buildSliverChildBuildingDelegatemethod:
Add date picker
- Add imports and a
constto
lib/shopping_cart_tab.dart. Add the new lines, as shown:
- Add a
_buildDateAndTimePicker()function to the
_ShoppingCartTabwidget. Add the function, as follows:
- Add a call to build the date and time UI, to the
_buildSliverChildBuilderDelegatefunction. Add the new code, as shown:
Add selected items for purchase
- Import the product package in
shopping_cart_tab.dart.
import 'model/product.dart';
- Add a currency format to the
_ShoppingCartTabStateclass.
final _currencyFormat = NumberFormat.currency(symbol: '\$');
- Add a product index to the
_buildSliverChildBuilderDelegatefunction.
SliverChildBuilderDelegate _buildSliverChildBuilderDelegate(
AppStateModel model) {
return SliverChildBuilderDelegate(
(context, index) {
final productIndex = index - 4; // NEW
switch (index) {]
// ...
- In the same function, display the items to purchase. Add the code to the
default:section of the switch statement, as follows:
Building & running the application
- Connect your Emulator or physical Android device to test the application.
- Click on Build & Run.
- And Boooom 🔥, your app is ready.The final build would look like the below illustration.
🎯 That’s all for today.
If you got any queries hit me up in the comments or ping me over on hi@itsshivam.com 📧
If you learned even a thing or two, clap your hands👏 as many times as you can to show your support! It really motivates me to contribute towards the community.
Feeling too generous? Buy me a Drink 🍺
Wanna collaborate? Let’s talk some tech 😊
Stalk me over on itsshivam.com, GitHub, or LinkedIn. 👀
Discussion (1)
Cool! Thanks for sharing! | https://practicaldev-herokuapp-com.global.ssl.fastly.net/enappd/building-an-ios-style-shopping-app-with-a-minimalist-design-using-flutter-22ld | CC-MAIN-2021-17 | refinedweb | 939 | 52.15 |
Previous: statusgui, Up: Developer Tools See try –diff.
For this command to work, several pieces must be in place:
The buildmaster must have a
scheduler.Try instance in
the config file's
c['schedulers'] list. This lets the
administrator control who may initiate these “trial” builds, which
branches are eligible for trial builds, and which Builders should be
used for them.
The
TrySched
TryScheduler requires a bit more
configuration. There are currently two ways to set this up:
buildbot trycommand create that directory (with mkdiruler import Try_Jobdir s = Try_Jobdir("try1", [ (see Logfiles) as you start using the jobdir, to make sure the buildmaster is happy with it.
To use the username/password form of authentication, create a
Try_Userpass instance instead. It takes the same
builderNames argument as the
Try_Jobdir form, but
accepts an addtional
port argument (to specify the TCP port to
listen on) and a
userpass list of username/password pairs to
accept. Remember to use good passwords for this: the security of the
buildslave accounts depends upon it:
from buildbot.scheduler import Try_Userpass s = Try_Userpass("try2", [.
The try command needs to be told how to connect to the
TrySched --master
argument (in the form HOST:PORT) that points to TCP port that you
picked in the
Try_Userpass scheduler. It also takes a
--username and --passwd pair of arguments that match
one of the entries in the buildmaster's
userpass list. These
arguments can also be provided as
try_master,
try_username, and
try_password entries in the
.buildbot/options file.
For the SSH approach, the command must be given --tryhost,
--username, and optionally --password (TODO:
really?) to get to the buildmaster host. It must also be given
--trydir, which points to the inlet directory configured
above. The trydir can be relative to the user's home directory, but
most of the time you will use an explicit path like
~buildbot/project/trydir. These arguments can be provided in
.buildbot/options as
try_host,
try_username,
try_password, and
try_dir.
In addition, the SSH approach needs to connect to a PBListener status
port, so it can retrieve and report the results of the build (the PB
approach uses the existing connection to retrieve status information,
so this step is not necessary). This requires a --master
argument, or a
masterstatus entry in .buildbot/options,
in the form of a HOSTNAME:PORT string. --vc=cvs or --vc=tla.
This can also be provided as
try_vc in
.buildbot/options.
The following names are recognized:
cvs
svn
baz
tla
bzr
hg
darcs
git
p4 --try-topfile=ChangeLog, or set it in the
options file with
try_topfile = 'ChangeLog'.
You can also manually set the top of the tree with
--try (tla, baz, darcs, monotone, mercurial, git) do not require try to know the top directory, so the --try-topfile and --try-topdir arguments will be ignored.
If the try command cannot find the top directory, it will abort with an error message.
Some VC systems record the branch information in a way that “try” can locate it, in particular Arch (both tla and baz). For the others, if you are using something other than the default branch, you will have to tell the buildbot which branch your tree is using. You can do this with either the --branch argument, or a try_branch entry in the .buildbot/options file.
Each VC system has a separate approach for determining the tree's base revision and computing a patch.
CVS
-Dtime specification, uses it as the base revision, and computes the diff between the upstream tree as of that point in time versus the current contents. This works, more or less, but requires that the local clock be in reasonably good sync with the repository.
SVN
svn status -uto find the latest repository revision number (emitted on the last line in the “Status against revision: NN” message). It then performs an
svn diff -rNNto find out how your tree differs from the repository version, and sends the resulting patch to the buildmaster. If your tree is not up to date, this will result in the “try” tree being created with the latest revision, then backwards patches applied to bring it “back” to the version you actually checked out (plus your actual code changes), but this will still result in the correct tree being used for the build.
baz
baz tree-idto determine the fully-qualified version and patch identifier for the tree (ARCHIVE/VERSION–patch-NN), and uses the VERSION–patch-NN component as the base revision. It then does a
baz diffto obtain the patch.
tla
tla tree-versionto get the fully-qualified version identifier (ARCHIVE/VERSION), then takes the first line of
tla logs --reverseto figure out the base revision. Then it does
tla changes --diffsto obtain the patch.
bzr find the list of all patches back to and including the last tag that was made. This text file (plus the location of a repository that contains all these patches) is sufficient to re-create the tree. Therefore the contents of this “context” file ' ' (two spaces). try scans for this line and extracts the branch name and revision from it. Then it generates a diff against the base revision.
If you provide the --wait option (or
try_wait = True
in .buildbot/options), the buildbot try command will
wait until your changes have either been proven good or bad before
exiting. Unless you use the --quiet option (or
try_quiet=True), it will emit a progress message every 60
seconds until the builds have completed. | http://docs.buildbot.net/0.8.0/try.html | CC-MAIN-2014-15 | refinedweb | 911 | 61.46 |
Debugging Techniques in C#
C# solves three problems I faced when designing the useful and scalable debugging system. These problems exist either in Java, C/C++, or both (my main programming languages).
- Not having very much meta-information (e.g. line number, method name, etc.)
- Having to add and remove debug statements whenever the debug focus shifts
- Having the debug statements compiled into the program affecting performance
Ok, discussing the solution for these problems in order we'll here's some code that retrieves the file name, line number, and method name of the function that called it.
// create the stack frame for the function that // called this function StackFrame sf = new StackFrame( 1, true ); // save the method name string methodName = sf.GetMethod().ToString(); // save the file name string fileName = sf.GetFileName(); // save the line number int lineNumber = sf.GetFileLineNumber();
// create the namespaces hashtable namespaces = new Hashtable(); // get the assembly of this class Assembly a = Assembly.GetAssembly( new Debug().GetType() ); // now cycle through each type and gather up all the namespaces foreach( Type type in a.GetTypes() ) { // check if the namespace is already in our table if( ! namespaces.Contains( type.Namespace ) ) namespaces.Add( type.Namespace, true ); }
The above code will create a Hashtable object containing all the namespaces in the same assembly as the Debug class of which this code is a part. Of course, this is only half of the solution so here is the actual filtering code.
// only proceed if the namespace in question is being debugged if( (bool) namespaces[ method.DeclaringType.Namespace ] ) // this is where the debug statement display code would be
Ok, so far so good. With the problems number one and two knocked out that leaves us with the obstacle of removing those darn debug statements when the final release is to be made without actually having to manually comment out or delete each one. This is where those handy little things called attributes come in to play. Assuming you have knowledge of how attributes work in C# I'll cut to the chase and introduce the ConditionalAttribute which is part of the aforementioned System.Diagnostics namespace. So here's some showing how to use the ConditionalAttribute class.
[Conditional("DEBUG")] public void Debug( string msg ) { // this is where the debug statement // display code would be }
What this will do is when this program is compiled it will check if 'DEBUG' was #defined and if it was then the call to this function will be remain, however if 'DEBUG' is not #defined all calls to this function not will be compiled leaving us with no performance hit.. there.
About the author
Mike Borromeo is a college of engineering student at the University of Michigan (AA). He has experience in C/C++, Java, C#, PHP, VBScript, JavaScript, MSSQL, and HTML. He can be reached at MikeD227@hotmail.com. The ideas and code for this article were developed as part of the Gnutella client project Phosl (). | http://www.codeguru.com/csharp/.net/net_debugging/techniques/article.php/c5907/Debugging-Techniques-in-C.htm | CC-MAIN-2014-42 | refinedweb | 488 | 61.16 |
Future and Actor are two different paradigms to express concurrent computations. Both of them are perfectly valid abstractions. However one must be careful when it comes to mixing them up.
The scenario I have in mind is when an Actor must use a service that returns a Future in its API. The service might look something similar to this:
import scala.concurrent.Future import scala.util.Random object RandomService { import scala.concurrent.ExecutionContext.Implicits.global /** Generates a random Int **/ def performComputation: Future[Int] = Future { val number = Random.nextInt(5) // artificially wait to simulate a longer computation Thread.sleep(number.toLong + 1) number } }
This service defines a single method that returns a Future. It doesn’t matter what the service does – it can fetch data from a database, trigger a remote call or perform an intensive computation, … – the thing that matters is that it returns a Future.
Also notice that in this example the service imports the scala global execution context. It means that this service will use a different execution context than the one in the actor. This is usually the case (e.g. a service that defines its own thread pool like database connections) and this is a good thing too because we don’t want to block the actor’s thread to perform a long computation.
Now that we have a service let’s create an Actor that calls this service every time it receives a request message.
import akka.Actor import scala.concurrent.Future object FutureActor { /** the protocol messages to interact with this actor **/ case object Request // client sends a Request message ... case object Response // ... and expects a Response back // message used to get the actor's internal state during tests case object GetState /**) // call service RandomService.performComputation.foreach { _ => // processing done -> update state state = state.copy(processed = state.processed + 1) // reply to sender sender() ! Response } case GetState => sender() ! state } }
Nothing too complex here. We have an actor that keeps track of how many requests it as received and processed so far. This is not really important what the actor keeps track of. The important thing is that the actor has a state and it updates its state when the future completes successfully.
Now that we have an actor let’s write a test for it:
import akka.actor.ActorSystem import akka.pattern.ask import akka.testkit.{TestActorRef, TestKit} import akka.util.Timeout import org.scalatest.concurrent.{PatienceConfiguration, ScalaFutures} import org.scalatest.{BeforeAndAfterAll, Matchers, WorkSpecLike} import scala.concurrent.Future import scala.concurrent.duration._ class FutureActorSpec extends TestKit(ActorSystem("FutureActorSpec")) with WordSpecLike with Matchers with ScalaFutures with BeforeAndAfterAll { import system.dispatcher import FutureActor._ implicit val timeout = Timeout(10.seconds) implicit val patience = PatienceConfiguration.timeout(10.seconds) override def afterAll() = { system.shutdownActorSystem(system) super.afterAll() } "FutureActor" should { "process all received messages" in { val ref = TestActorRef[FutureActor] Future.traverse(1 to 100)(_ => ref ? Request).futureValue // check all requests have been processed val actorState = (ref ? GetState).futureValue actorState.received shouldBe 100 actorState.processed shouldBe 100 } } }
Our test looks pretty simple: Send 100 requests to the actor and wait for the responses.
Once we got all the responses, ask the actor for its state and check that both the received and processed counters equal 100.
So now let’s run it and … What? Test failed because of a timeout. How come? We’ve explicitly increased the default timeouts to 10s which is more than enough to process 100 requests.
mmmhh …our test looks ok but keeps failing. It might be something in our actor implementation … we seem to never receive some responses back. Let’s see what can happen…
Our random service computation might fail in which case the “foreach” is never called. Correct! That would be a good practice to add a recover block and make sure we deal with failures. However our random service implementation is simple enough and there were no such failures during the test.
The problem is far more subtle and is because the Future and Actor paradigms have been mixed together without careful consideration.
Remember! An actor processes one message a time. Therefore we can assume a “single-threaded” environment when we process the messages. This is what we’ve done here. The actor update its state by mutating the “state” property and this is perfectly fine (as long as the actor assumption holds).
Now let’s think how the actor interacts with the RandomService. It uses a Future and perform some actions when the Future completes. But wait! How does Future concurrency work? … yes it uses different assumptions. We have now turn our nice “single-threaded view” into a multi-threaded one. When the Future completes, our actor is no longer processing the message that triggered the service but has jump to another message.
That means that the call to sender() when the future completes no longer points to the sender who sent the original message but to the sender of the current message being processed by the actor. And that is why our future timed out (behind the scene the ask pattern creates an actor to wait for the reply and in our case we were sending some replies to the wrong actors, therefore some “ask” actors never got their reply and our future timed out).
We also have similar concurrency issues when updating the actor state as we are just mutating a var (which is fine in a “single-threaded” env but is subject to nasty bugs in a multi-threaded world).
In fact this case is so frequent that akka provides us with a pattern to address this: The pipe pattern.
The pipe pattern allows to send a message to an actor when a Future completes. We can use the pipe pattern to send the response to ourself and update the actor’s state safely under the “single-threaded” view of the actor paradigm.
Our actor code becomes:
import akka.Actor import akka.pattern.pipe import scala.concurrent.Future object FutureActor { /** the protocol messages to interact with this actor **/ case object Request // client sends a Request message ... case object Response // ... and expects a Response back case object GetState // message used to get the actor's internal state during tests // a new message that the actor sends to himself when the future completes case class ServiceResponse(number: Int) /**) RandomService.performComputation // call service .map(ServiceResponse.apply) // turn response into ServiceResponse .pipeTo(self)(sender()) // sends it back to itself case ServiceResponse(_) => // processing done -> safely update state state = state.copy(processed = state.processed + 1) // and notify sender that request has been processed sender() ! Response case GetState => sender() ! state } }
What we’ve changed now is that when the Future completes the response is turned into a ServiceResponse message.
This map operation is safe (no side-effect) and then the message is sent to the actor itself. (We also use the pipe pattern to preserve the sender reference).
We can then add a new case to the receive block to update the actor state and notify the correct sender.
Now if we run our test … it works just fine. But keep in mind that the remark about service failure still holds and we have to handle the failure ourselves. The pipe pattern does no magic here. | http://www.beyondthelines.net/computing/futures-in-actor/ | CC-MAIN-2020-40 | refinedweb | 1,202 | 58.89 |
[ RFC Index | RFC Search | Usenet FAQs | Web FAQs | Documents | Cities ]
Alternate Formats: rfc3245.txt | rfc3245.txt.pdf
RFC 3245 - The History and Context of Telephone Number Mapping (ENUM) Operational Decisions: Informational Documents Contributed to ITU-T Study Group 2 (SG2)
RFC3245 - The History and Context of Telephone Number Mapping (
Network Working Group J. Klensin, Ed. Request for Comments: 3245 IAB Category: Informational March 2002 The History and Context of Telephone Number Mapping (ENUM) Operational Decisions: Informational Documents Contributed to ITU-T Study Group 2 (SG2) Status of this Memo This memo provides information for the Internet community. It does not specify an Internet standard of any kind. Distribution of this memo is unlimited. Copyright Notice Copyright (C) The Internet Society (2002). All Rights Reserved. Abstract. Table of Contents 1. Introduction: ENUM Background Information ..................... 2 2. Why one and only one domain is used in ENUM ................... 2 3. Why .ARPA was selected as the top level domain for ENUM ....... 4 4. The selection of an operator for E164.ARPA .................... 7 5. Procedures to be followed by RIPE NCC ......................... 8 6. References .................................................... 8 6.1. Normative references ........................................ 8 6.2. Informative and explanatory references ...................... 8 7. Security Considerations ....................................... 9 8. IANA Considerations ........................................... 9 9. Authors' Addresses ............................................ 9 10. Full Copyright Statement ..................................... 10 1. Introduction: ENUM Background Information In January 2002, in response to questions from the ITU-T Study Group 2 (referred to just as "SG2", below), specifically its group working on "Questions 1 and 2", and members of the IETF and telecommunications communities, Scott Bradner, as Area Director responsible for the ENUM work and ISOC Vice President for Standards, initiated an effort to produce explanations of the decisions made by the IETF about ENUM administration. The effort to produce and refine those documents eventually involved him, Patrik Faltstrom (author of RFC 2916), and several members of the IAB. The documents have now been contributed to ITU-T, and are being published as internal SG2 documents. This document provides the IETF community a copy of the information provided to SG2. Section 2 below contains the same content as COM 2-11-E, section 3 contains the same content as COM 2-12-E, and section 4 contains the same content as SG2 document COM 2-10-E. The documents being published within SG2 show their source as "THE INTERNET SOCIETY ON BEHALF OF THE IETF", which is a formality deriving from the fact that ISOC holds an ITU sector membership on behalf of the IETF. 2. Why one and only one domain is used in ENUM 2.1. Introduction This contribution is one of a series provided by the IETF to ITU-T SG2 to provide background information about the IETF's ENUM Working Group deliberations and decisions. This particular contribution addresses the IETF's decision that only a single domain could be supported in ENUM. 2.2. The need for a single root in the DNS In the Domain Name System (DNS), each domain name is globally unique. This is a fundamental fact in the DNS system and follows mathematically from the structure of that system as well as the resource identification requirements of the Internet. Which DNS server is authoritative for a specific domain is defined by delegations from the parent domain, and this is repeated recursively until the so-called root zone, which is handled by a well-known set of DNS servers. Note that words like "authoritative" and "delegation" and their variations are used here in their specific, technical, DNS sense and may not have the same meanings they normally would in an ITU context. Given that one starts with the well-known root zone, every party querying the DNS system will end up at the same set of servers for the same domain, regardless of who is sending the query, when the query is sent and where in the network the query is initiated. In May 2000 the IAB published a document on the need for a single root in the DNS. This document explores the issues in greater detail. See RFC 2826 (). 2.3. Storing E.164 numbers in the DNS An E.164 number is also globally unique, and because of that it has most of the same properties as a domain name. This was the reason why storing E.164 numbers in the DNS system is technically a simple mapping. ENUM is just that, a way to store E.164 numbers in the DNS. Multiple ENUM trees in the DNS hierarchy would have the telephony equivalent of permitting every carrier to assign a different meaning to an E.164 country code, with each one potentially mapping a given number to a different circuit or rejecting it entirely. For the Internet, if there were multiple trees, there would be no way to determine which domains might contain ENUM records. Thus, each application that uses ENUM facilities would have to be manually configured with a list of domains to be searched. This would incur the same problems of scaling and updates that led to the development of the DNS. The goal with ENUM is that one party should be able to look up information in DNS, which another party has stored in DNS. This must be possible with only the E.164 number as input to the algorithm. If the party storing information in DNS has two (or more) places to choose from, and chooses one of them, how is a second party looking up things to know what place was selected? An analogy would be if one knew only, and not the TLD, and ask people to go to that website. Is the correct domain name, or? It should be noted that exists and is a pornography site. Thus, the only way of knowing where to look up E.164/ENUM numbers in DNS is to use one and only one domain, and have everyone agree on what that domain is. Note that ENUM is a system for use with E.164 numbers in their general, global, context. Nothing technical can, or should, try to prevent parties that wish to use ENUM-like mechanisms, or other systems that have the same general structure as telephone numbers, from working out private, out of band, agreements to support those applications. However, such applications are neither E.164 nor ENUM, any more than internal extension numbers in a PBX are normally considered to be part of either. 3. Why .ARPA was selected as the top level domain for ENUM 3.1. Introduction This memo is one of a series provided by the IETF to SG2 to provide background information about the IETF's ENUM Working Group deliberations and decisions. This particular memo addresses the IETF's decision that the ENUM DNS tree would use the .ARPA top level domain. 3.2. IAB Statement on Infrastructure Domain and Subdomains (Taken from, May 2000.) RFC 881- rfc0881.txt). Other than the IPv4 reverse-mapping subdomain, it became the only active subdomain of that domain as the <host-table-name>.ARPA names that were also part of the transition were gradually removed. Other infrastructure domains were, in the past, placed under the "INT" TLD and various organizational names. It is in the interest of general Internet stability, to pay adequate attention to. 3.3. Infrastructure subdomains Operationally, it is easier to ensure good stability for DNS in general if we have as few DNS zones as possible that are used for parameters for infrastructure purposes. Today, new infrastructure domains are put in ARPA and old assignments which were made in other domains are being migrated to ARPA. Currently, ARPA is used for in- addr.arpa (for reverse mapping of IPv4 addresses), ip6.arpa, (for reverse mapping of IPv6 addresses), and e164.arpa, (the subject of this memo). In the future, URI schemes, URN namespaces and other new address families will be stored in ARPA. Theoretically, each set of infrastructure parameters could be stored in a separate domain as a TLD. (For example, .URI, .UNI, .IPV6, new TLD, which only can be created via the ICANN process (which might take a year or more) and would unnecessarily and undesirably flatten the DNS tree. It is much easier to have one TLD with easily created new subdomains (2nd level domains), one for each parameter. Thus it was logical to store E.164 numbers in ARPA. 3.4. The ARPA domain (derived from RFC 3172, September 2001) The "arpa" domain was originally established as part of the initial deployment of the DNS, to provide a transition mechanism from the Host Tables that were previously standard in the ARPANET. It was also used to provide a permanent home for IPv4 address to name mappings ("reverse mappings") which were previously also handled using the Host Table mechanism. The Internet Architecture Board (IAB), in cooperation with the Internet Corporation for Assigned Names and Numbers (ICANN), is currently responsible for managing the Top Level Domain (TLD) name "arpa". This arrangement is documented in Appendix A of RFC 3172.. [referring to RFC 3172] [RFC 2860]. 3.5. Assignment of the .ARPA top level domain As documented in appendix A of RFC 3172, on April 28, 2000 the US Department of Commerce, acting under the authority of its purchase order with ICANN, directed ICANN to operate the .ARPA TLD under the guidance of the IAB, as a limited use domain for internet infrastructure applications. 3.6. Name Server Requirements for .ARPA (from RFC 3172). The efficient and correct operation of the "arpa" domain is considered to be sufficiently critical that the operational requirements for the root servers apply to the operational requirements of the "arpa" servers. All operational requirements noted in RFC 2870,, this arrangement is likely to change in the future. 3.7. Summary: ENUM use of .ARPA The ARPA domain is the preferred TLD for infrastructure and parameter use. The ENUM structure should be placed in a single domain subtree (see separate contribution, COM 2-11), and is expected to evolve into important Internet infrastructure, and hence should be placed there. This decision is facilitated by the MOU between ICANN and IETF and the instructions from the US Government to ICANN, which provide for IAB supervision of that domain. Despite some confusion with the name of a US Department of Defense agency, DARPA, these uses are consistent with all of the historical uses of the ARPA domain, which have been for infrastructure purposes (initially when the hierarchical DNS was created to replace the old flat namespace of ARPANET): the domain was never used for any internal or specific DARPA purpose. Recognizing the potential difficulties with multiple infrastructure domains, the Internet Architecture Board concluded in May 2000 that all new infrastructure information was to be stored in the ARPA domain and existing infrastructure subtrees migrated there as feasible. provides additional context for these decisions. The ENUM Working Group decided to follow that recommendation. 4. The selection of an operator for E164.ARPA 4.1. Introduction This contribution is one of a series provided by the IETF to SG2 to provide background information about the IETF's ENUM Working Group deliberations and decisions. This particular contribution addresses the IETF's selection of an operator for the E164.ARPA domain. 4.2. Name server operator requirements RFC 2870 () describes the requirements for operating DNS root servers. Important DNS-based infrastructure services require that their servers be operated with the same level of attention to reliability and security that the root servers require. In addition, for an infrastructure service such as E164.ARPA some additional requirements were felt by the IAB to be important. Organizations that operate core services such as IN- ADDR.ARPA and E164.ARPA must have a history of reliable operation of DNS servers and be highly respected and known for both their relevant technical skills and their fairness and impartiality. In addition, the IAB felt that the organization that operates such infrastructure domains must be a non-profit and public-service-oriented one to remove any incentive for exploitative behavior based on profit motives that depend on, e.g., the number of records in the database even if some reasonable registration fee is charged to recover costs. The IAB also felt that they wanted an organization with good (and extensive) experience working with governments when necessary and one with experience working with the IAB and the IETF more generally. 4.3. Evaluating possible operators The IAB researched various options for operators and came to the conclusion that the regional IP address registries (RIRs) met all of the criteria. They all had extensive experience providing and supporting infrastructure services reliably and securely and all three of them had a long history of working with the IETF. 4.4. Selecting a particular operator Given that all of the RIRs would have met the criteria, the selection of a particular RIR required looking at other factors. The IAB concluded that RIPE NCC would be the best operator for E164.ARPA, based largely on their somewhat greater experience in running DNS servers and on their location in a neutral legal jurisdiction. 4.5. Country administration of cc subdomains Of course, once a subdomain associated with a country code is assigned for registration and operations to an appropriately- designated entity for the associated country or numbering plan, administration of that subdomain is entirely a National Matter, with no involvement anticipated from the IAB/IETF, the E164.ARPA registry, or from the ITU. 5. Procedures to be followed by RIPE NCC The IAB and the RIPE NCC have agreed on procedures for the latter to follow in making ENUM registrations at the country code level. Those instructions are expected to evolve as experience is accumulated. Current versions will be posted on the IAB and/or RIPE NCC web sites. 6. References 6.1. Normative references None. This document is intended to be self-contained and purely informational. 6.2. Informative and explanatory references. [RFC 2860] Carpenter, B., Baker, F. and M. Roberts, "Memorandum of Understanding Concerning the Technical Work of the Internet Assigned Numbers Authority", RFC 2860, June 2000. [RFC 2870] Bush, R., Karrenberg, D., Kosters, M. and R. Plzak, "Root Name Server Operational Requirements", BCP 40, RFC 2870, June 2000. [RFC 2916] Faltstrom, P., "E.164 number and DNS", RFC 2916, September 2000. [RFC 3172] Huston, G., Ed., "Management Guidelines & Operational Requirements for the Address and Routing Parameter Area Domain ('arpa')", BCP 52, RFC 3172, September 2001. 7. Security Considerations This document provides information only and raises no new security issues. The security issues associated with the underlying protocols are described in RFC 2916. 8. IANA Considerations There are no IANA considerations regarding this document. Sections 3 and 4 contain a record of actions already performed by IANA and partial explanations for them. 9. Scott Bradner EMail: sob@harvard.edu Patrik Faltstrom EMail: paf@cisco ] | http://www.faqs.org/rfcs/rfc3245.html | crawl-002 | refinedweb | 2,472 | 54.02 |
Hi All. I trying to get step step response of each test case from suite TearDown script.
def testCaseCount = runner.testSuite.getTestCaseCount()
for (int i=0;i<testCaseCount;i++){
def testCaseName = runner.testSuite.getTestCaseAt(i).getName()
def testStepCount = runner.testSuite.getTestCaseAt(i).getTestStepCount()
for (int j=0;j<testStepCount;j++){
def testStepName = runner.testSuite.getTestCaseAt(i).getTestStepAt(j).getName()
// log.info(testStepName)
if (testStepName == "SendPayment"){
def request=context.expand('${SendPayment#Response}')
log.info(request)
}
//File f = new File(projectProperty+"/TearDownScriptFiles/"+testCase.name+".json")
//f.write(response)
}
log.info(testCaseName)
}
Above is my groovy code. I'm iterating all the testcases under suite and test step as well, I'm trying to get the test-step response based on the test step name. Right now I'm able to iterate the test cases and test steps but I could get the test step response..I belive I need to change below one
if (testStepName == "SendPayment"){
def request=context.expand('${SendPayment#Response}')
log.info(request)
}
Any input is appreciated. Thanks
Solved!
Go to Solution.
@arunbharath
Here you go:
Please follow comments inline
/**
* Tear down script of suite
**/
import com.eviware.soapui.impl.wsdl.teststeps.RestTestRequestStep
def processStep = {
log.info "Step name : ${it.name}"
log.info "Case name : ${it.testCase.name}"
log.info "Suite name : ${testSuite.name}"
log.info "Response :\n ${it.testRequest.responseContentAsString}"
//Write logic below to save the response data to file here
}
testSuite.testCaseList.collect { kase ->
kase.testStepList.collect {
switch(it) {
//Process only REST requests; add additional cases as needed
case {it instanceof RestTestRequestStep}:
processStep it
break
default:
break
}
}
}
If you don't want to have the above script for each test suite or project, then you can use events, "TestRunListener.afterStep" and have relevant logic to do the same.
View solution in original post
Appreciate if you can let us know what is the use case?
"Right now I'm able to iterate the test cases and test steps but I could get the test step response.." - did not understand the issue. Did you miss something?
Sorry my bad. Typo on the last message
Use Case:
=========
1) Let say I have a Test suite which has multiple testcases and each test case has multiple test steps. I want to iterate each test cases and test steps and get API response of test step based on the test-step name (using if-loop). after getting all the respective test-step response, I need to save those response in the file.
2) Currently I'm having a script to iterate test-cases and test-steps, I need script to recive test-step response.
@nmrao Thanks. It is working like a gem. I have one more question. How can we extract any specific datafield field value from the test-step Json api response?
Compare an expected JSON value and actual response in Events
Fetch value/data from JSON response using Groovy Script
Filtering data retrieved from a DataSource
Get data from Petstore and add it to Excel sheets | https://community.smartbear.com/t5/SoapUI-Pro/How-to-get-a-test-step-response-from-Suite-TearDown-script/m-p/198513/highlight/true | CC-MAIN-2020-40 | refinedweb | 496 | 59.9 |
!
Teacher Notes
Teachers! Did you use this instructable in your classroom?
Add a Teacher Note to share how you incorporated it into your lesson.!
If you liked it, Follow meh on instagram where I post project updates:!
15 People Made This Project!
gewkwn made it!
Sektor7G made it!
MrHaza made it!
danzou1275 made it!
LucasA47 made it!
harshmmistry made it!
harshmmistry made it!
OrC2 made it!
FilipM34 made it!
安陳 made it!
安陳 made it!
AcirM made it!
Jerrycan-Lemonade made it!
Cornelii made it!
EvanH333 made it!
See 6 More
69 Discussions
1 year ago
Hey guys, I added mute to the code! Here is the source. OP i strongly think you should add this.
Connect one side of the button (presumably the built in one on your encoder) to VIN, then connect the other side to p1. You can even change it from mute to whatever you like. Towards the bottom of my file you will see the MUTE command. You can change it to any of the ones given here...
But they dont all seem to work
You can even change it to whatever key you want
Reply 1 year ago
Im wondering if there is any way to make it work as scroll whell?
Reply 1 year ago
Thank you!
Reply 1 year ago
I've featured your comment!
5 weeks ago
Does anybody know if it's possible to add a white led to this controller?
It would be nice to be able to control the led brightness with same encoder, so when the volume is down, the led light is down and when you're increasing the volume you're increasing the led brightness too.
Thanks!
Question 5 weeks
3 months ago
This code works for me including the mute functionality:
Question 9 months ago
Hi, i´m making the project but the mute button doesnt work, it only turn off the intregated LED on the Digispark. What can i do?
Answer 4 months ago
If I connect cables like this then volume control is very smooth. With other configuration it doesn't work as well. Sometimes it doesn't change volume, sumetimes do.
I'm using rotary encoder with small motherboard underneath and it has 5 pins, so I can't copy from original post (which has only 3). I'm also using ATTINY85 with microUSB, not the one from the picture.
I really would like MUTE to work so I could finish my project. The red light near the P2 pin blinks if I press the switch so I must be very close. None of the solutions in comments doesn't work for me. Or I don't understand how to connect cables :)
So if anyone has the solution, please share.
Question 12 months ago
How to use the remaining 3 batteries (p3, p4, p5) to control led RGB (or 1pin-1led) when the Rotary encoder????. please help me!!!!!
1 year ago
Hey Kris, Please help! I make it work only with volume knob!!! But I can not do mute when i pres the knob... The photos show how I've connected Rotary encoder and The ATtiny85! Where am I wrong?
Reply 12 months ago
Hey psychodido.
Tôi cũng có cùng một vấn đề như bạn, và tôi giải quyết nó bằng cách loại bỏ các
bảng mạch và chỉ để lại bộ mã hóa quay sau đó nút tắt tiếng đã hoạt
động đúng cách. Tôi nghĩ rằng các điện trở trong bảng mạch đã gây ra
vấn đề này
Reply 1 year ago
GND to GND
CLK to 0
DT to 2
SW to 1
+ to 5v
Reply 1 year ago
Hey psychodido. Did you get it to work? I wired my Tiny85 with the encoder as shown in your pictures; my volume up/down now works correctly, but i have the same problem as you: The Mute-Button don't work. Any suggestions? :-/
Tip 1 year ago
You can use an another version of the board to avoid a wire connection :)
I used a encoder from old mouse. It's very small.
1 year ago
Interesting idea. Generally I use pennies and hot glue to add weight to dials. Unfortunately, none of mine ever seem to work the way I want... heh.
Is it possible to make a rotary controller like this, except use it for mouse control? You know, turning the knob makes the cursor move in that direction. I'm asking because I like playing dial games like Arkanoid, but there's not a controller for PCs with that functionality. Even adapters for Atari paddles don't support the mouse, and emulators pretty much demand it.
Question 1 year ago
I bought . But i don't now how to program it to use more 2 functions and how to make the swicths work.
I use this. Please help! I make it work only with volume knob and mute. I need more 2 functions for FWD/BACK. I have a old front panel autoradio and I transform it for a multimedia controller of a android autoradio. Please help!
Answer 1 year ago
My work...
1 year ago
Could you please guide me to add more media control button. I want to use new trend mechanical switch keyboard but i can't live without these DELL magic keys. Please...
2 years ago
Unable to compile, I keep getting an error. Looked over the steps multiple times and everything seems fine. Error:
C:\Users\Marmbo\Documents\Arduino\sketch_aug12a\sketch_aug12a.ino:1:29: fatal error: TrinketHidCombo.h: No such file or directory
#include "TrinketHidCombo.h"
^
compilation terminated.
exit status 1
Error compiling for board Digispark (Default - 16.5mhz).
Invalid library found in C:\Users\Marmbo\Documents\Arduino\libraries\Adafruit-Trinket-USB-master: C:\Users\Marmbo\Documents\Arduino\libraries\Adafruit-Trinket-USB-master
Invalid library found in C:\Users\Marmbo\Documents\Arduino\libraries\Adafruit-Trinket-USB-master: C:\Users\Marmbo\Documents\Arduino\libraries\Adafruit-Trinket-USB-master | https://www.instructables.com/id/Digispark-Volume-Control/ | CC-MAIN-2019-35 | refinedweb | 995 | 76.72 |
New to Alfresco.
I am writing Java-backed AbstractWebScript. I need to use implicit arguments.
My URI looks like:
mydocuments/param1/param2
The caller will call this URI as: documents/value1/value2
I need to get a handle on param1 and param 2 (and their values) inside the execute method.
public class MyWebScript extends AbstractWebScript{
public void execute(WebScriptRequest req, WebScriptResponse res) throws IOException {
// I need to get the value of param1 and param2 inside this method
}
My question is:
How do I get a handle on param1 and param2 inside the execute method?
If I defined it as explicit argument in the URI (as /param1=value1¶m2=value2), I know that I can get them as req.getParameter("param1") API. But as because I am using the implicit argument (as opposed to explicit argument), how do I get a handle of param1 and param2?
I found it out.
The API req.getPathInfo() returns the values of the parameters as:
myDocuments/value1/value2
After that, you can use StringTokenizer to get the value of each parameter. | https://community.alfresco.com/thread/230680-implicit-argument-in-abstractwebscript | CC-MAIN-2019-13 | refinedweb | 176 | 55.03 |
Question: Install Biom format under Windows
0
I tried to install Biom format from the source under Windows:
@python setup.py install
However, when I typed the following to check the version, I got a error message:
@python -c "from biom import __version__; print __version__"
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "biom\__init__.py", line 65, in <module>
from .table import Table
File "biom\table.py", line 194, in <module>
from ._filter import _filter
ImportError: No module named _filter
Any idea on how can I make it work in Windows?
ADD COMMENT • link •modified 4.6 years ago by anderspitman • 60 • written 4.6 years ago by songzewei • 10 | https://www.biostars.org/p/139127/ | CC-MAIN-2019-47 | refinedweb | 115 | 76.22 |
Speed BumpMembers
Content count457
Joined
Last visited
Community Reputation240 Neutral
About the Speed Bump
- RankMember
the Speed Bump replied to caseyd's topic in General and Gameplay ProgrammingResist the temptation to nest your namespaces too deeply. They are cool and all, but you can quickly make code a lot more unwieldly than it needs to be if you have a lot of namespaces floating around. I tend to create a single 'root' namespace for a project, and avoid going any deeper than that unless I am having troubles with symbol conflicts. (which is uncommon in C++, since it has such nice overloading rules)
the Speed Bump replied to vore2005's topic in General and Gameplay ProgrammingQuote:Original post by DrEvil Your timer event is essestially a hack for an update() call to be called constantly. It adds unnecessary overhead to implement that through events. In no way is that better than a game loop. Untrue. vore2005's game will not drain the life from a laptop battery in the same way that a conventional event loop does. (my own laptop lasts three times as long if not running such programs)
the Speed Bump replied to WilyCoder's topic in General and Gameplay ProgrammingThis is just an educated guess, but my money says that the file was the same as the one in the repository. Subversion doesn't use timestamps to determine whether a file has changed; it compares the contents of the file. If there are no changes to commit, it doesn't commit anything.
the Speed Bump replied to AndyGeers's topic in General and Gameplay ProgrammingI second the recommendation for test-driven development. Once you have several truckloads of non-interactive tests on the majority of your code, it becomes easy to make extremely aggressive changes to the code without worry of breaking existing behaviours. (another odd thing is that TDD seems to be more productive despite the fact that it involves writing a lot more code...)
the Speed Bump replied to torbjoen's topic in General and Gameplay ProgrammingI haven't tried Axiom personally, but it may be what you're after.
the Speed Bump replied to zedzeek's topic in General and Gameplay ProgrammingQuote:Original post by chollida1 C++ is a paint due to having to manually manage memory, allthough this can almost be completely be dealt with by using containers and smart ponters as some cleaver posters have noted!! C++/CLI allows you to allocate managed (ie garbage collected) classes on the stack or on the heap, as suits your needs at any given moments. It's also possible to do all kinds of other awesome things like mix generics and templates at will. (plus they added a 'for each'!) Now if only they would actually release the darned thing! ;)
the Speed Bump replied to zedzeek's topic in General and Gameplay ProgrammingWhy not take one out for a spin? The learning curve is pretty low if you already have a firm grasp of C++.
the Speed Bump replied to jimywang's topic in General and Gameplay ProgrammingYou could try Boost.test (or NUnit, JUnit, or whatever)
the Speed Bump replied to iduchesne's topic in General and Gameplay ProgrammingQuote:Original post by iduchesne We are using the Torque engine and with a good EULA, doesn't matter if the assets get stolen... if they are used somewhere else and we known it's our assets then it's a reason to get the law involved ;) This is somewhat tangental, but anything you release is always automatically protected by copyright, whether you slap a EULA on it or not.
the Speed Bump replied to ade-the-heat's topic in General and Gameplay ProgrammingThe example you're looking at is describing how to do it using the .NET class library. If that's what you had in mind, then you just have to tweak the "Use Managed Extensions" option in the project settings. If it's not, then you need to look around a bit for another example. (or wait for a reply from someone who knows the standard library better than I ;)
the Speed Bump replied to XXX_Andrew_XXX's topic in General and Gameplay ProgrammingSCons does have a build option to create Visual Studio project files for a compile target, but I can't see it scaling for very complex projects. What you can also do is create a "makefile project" and set it to run SCons as the build action.
the Speed Bump replied to Zodiak's topic in For BeginnersLonghorn's primary language is actually C++/CLI, which is something that is completely distinct from MC++. Nobody will be forced to switch to C# at gunpoint. C++/CLI is what MC++ really should have been. I'm rather excited about it. using namespace System::IO; IList<String^> readFile () { std::vector<String^> lines; // Hey look we can create this on the stack now StreamReader fs("myfile.txt"); while (String^ s = fs.ReadLine()) { lines.push_back(s); } return lines; // <-- !!! }
the Speed Bump replied to Abbacabba's topic in General and Gameplay ProgrammingIt's a bit Linux-centric, but you can find a number of language benchmarks at.
the Speed Bump replied to antareus's topic in General and Gameplay ProgrammingI found BOOST_FOREACH to be terribly leaky. It will fail with incomprehensible error messages in the weirdest situations. I can't remember the specifics any longer, but the first (and last) real problem I had with it went something like this: std::map<std::string, SomethingElse> mapOfStuff; foreach (std::pair<std::string, SomethingElse>& iter, mapOfStuff) // Fails, with an unintelligible error message { ... } typedef std::pair<std::string, SomethingElse> PairOfThings; foreach (PairOfThings& iter, mapOfStuff) // works { ... } I'd rather like to see both typeof and auto introduced into the language. They can frequently be used for the same thing, but they don't always overlap.
the Speed Bump replied to BlackWind's topic in General and Gameplay ProgrammingA good rule of thumb is to bear in mind that, until you see that your existing, working program is too slow, your time is infinitely more valuable than any number of CPU clock cycles. Write code in whatever way you can so as to get as much working functionality in as little time as possible. You can always make it fast later. | https://www.gamedev.net/profile/12507-the-speed-bump/ | CC-MAIN-2017-30 | refinedweb | 1,051 | 58.62 |
Hello! I'm a college student who is taking a beginners Java programming class. For the first time, I really need some assistance figuring out the latest assignment, which involves static methods. I have 5 such assignments, but I only need helping figuring out 1, because then I can do the other 4 on my own. Plus, the textbook (Java Software Solutions by Lewis & Loftus) didn't explain the concepts very well and I am quite lost...
To make things easier I'll post the assignment here, but can you only give me advice on how to get started? I'd greatly appreciate any help!!!
Assignment:
Part1
Write a method named replace that will accept 3 parameters: the original String, the search String, and the replace String. The method should return a new String that has all of the occurrences of the search String replaced by the replace String. For example, replace("Blue shoes are good shoes.", "shoe", "car") would return the String "Blue cars are good cars." The method header must be:
public static String replace (String original, String s, String r)
Part2
Write a Java program named Tester.java that contains a main method. Inside the main method, write statements that will call the methods from LabWork.java. You should try calling each method several times to make sure the method works for all possibilities.
I think the structure for LabWork.java should begin like this, but what to put in the body is where I'm having trouble:
import java.util.Scanner; public class LabWork { public static String replace (String original, String s, String r) { // body } // end replace method } // end class | https://www.daniweb.com/programming/software-development/threads/230251/help-with-an-assignment-involving-static-methods | CC-MAIN-2017-39 | refinedweb | 274 | 72.66 |
Your message has been sent to W3Schools. Air vs. See this previous tip for more details about the Action Center. Select “Change Action Center Settings” in the left panel of the Action Center dialog box. Uninstall Apport It is fairly simple to uninstall Apport, as you can open the Ubuntu Software Centre, search for apport, and simply click Remove. his comment is here
It works. Skip to main content social search Menu Gizmo's Freeware toggle-button toggle-button toggle-button Search form Search toggle-button Login / Register Username * Password * Create new accountRequest Here's What to Do Article How Do I Find a Driver's Version Number? rize Says: October 24th, 2013 at 7:13 am After upgrading to Win8.1 my scroll function hangs up and I have to refresh the screen to scroll.
But simply running the file in a different directory allowed it to show errors!
Turns out that the error_log file in the one directory was full (2.0 Gb). Join them; it only takes a minute: Sign up Turning error reporting off php [closed] up vote 13 down vote favorite 4 I wanted to turn off the error reporting on sagin Says: November 7th, 2015 at 10:24 pm The operating system couldn't be loaded because a crical system driver is missing or contains errors.
Please rate this article: Select ratingGive How To Disable Error Reporting in Windows 7 1/5Give How To Disable Error Reporting in Windows 7 2/5Give How To Disable Error Reporting in Windows more hot questions question feed about us tour help blog chat data legal privacy policy work here advertising info mobile contact us feedback Technology Life / Arts Culture / Recreation Science Here's A Free One. Disable Windows Error Reporting Server 2008 Separate namespaces for functions and variables in POSIX shells Why does Wikipedia list an improper pronunciation of Esperanto?
Here's how to disable Windows error reporting. Disable Windows Error Reporting Windows 10 Windows Error Reporting advanced options On the Windows Error Reporting Configuration dialog box, the following two options disable Windows Error Reporting: I don't want to participate, and don't ask me again I don't want to participate, and don't ask me again This option disables Windows Error Reporting, and prevents it from prompting you to send information about application failures to Microsoft. MacBook vs.
From Windows 7 to 8.1, this was possible under "Action Center", however the Action Center is no longer in Windows 10 in the same form as it was in previous versions. Disable Windows Error Reporting Group Policy If you want the setting to apply to all users, click “Change report settings for all users”. When this option is selected, if an application failure occurs, only non-personal data is sent to Microsoft. Given that ice is less dense than water, why doesn't it sit completely atop water (rather than slightly submerged)?
How to Disable, Stop or Uninstall Apport Error Reporting Ubuntu 12.04 is the first release of Ubuntu that ships with Apport Error Reporting enabled by default, and as a result, you I had to set
display_errors = On
error_reporting = ~E_ALL
to keep no error reporting as default, but be able to change error reporting level in my scripts.
I'm Turn Off Error Reporting Php Creative Commons Attribution Non-Commercial Share-Alike powered by Simplet the file-based blog for github disclaimer copyright cookies privacy terms Ubuntu, Canonical and the Circle of Friends are registered trademarks of Canonical Ltd. Turn Off Windows Problem Reporting Windows 10 Syntax error_reporting(level); Parameter Description level Optional.
Here’s how: Open the Action Center. this content Copyright 1999-2016 by Refsnes Data. Fixed me right up! lol, I'll edit and add that info. Disable Error Reporting Windows 10
Tip Passing in the value -1 will show every possible error, even when new levels and constants are added in future PHP versions. Continue Reading Up Next Up Next Article How Do I Change Another User's Password in Windows? Then why not have it published here and receive full credit? weblink Here’s how: Open the Action Center.
See Also Concepts Customer Experience Improvement Program The Server Manager Main Window Community Additions ADD Show: Inherited Protected Print Export (0) Print Export (0) Share IN THIS ARTICLE Is this page Disable Windows Error Reporting Registry share|improve this answer answered May 22 '12 at 23:37 Matthew 33.6k66373 What do you mean by appropriate? versus El Capitan Test Results Ultrabooks Best Ultrabooks Best Laptops Overall Best College Laptops Laptop-Tablet Hybrids Buying Guide Deals Gaming Best Gaming Laptops Sub-$1,000 Gaming Laptops VR-Ready Laptops Gaming Accessories Gaming
error_reporting(0); @ini_set('display_errors', 0); share|improve this answer answered May 22 '12 at 23:36 belgianguy 44135 add a comment| up vote 6 down vote Does this work? Choosing Each time a problem occurs, ask me before checking for solutions will keep error reporting enabled but will prevent Windows from automatically notifying Microsoft about the issue. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count). Windows Error Reporting Windows 7 Partial sum of the harmonic series between two consecutive fibonacci numbers Best way to repair rotted fuel line?
Information Apport is an Error Reporting Service provided by Ubuntu to intercept and analyze crashes and bugs as and when they occur. The procedure for disabling error reporting is quite simple. See this previous tip for more details about the Action Center. Select “Change Action Center Settings” in the left panel of the Action Center dialog box. check over here Please help me out.
yesterday i got a big update which switched it on again and flash is now being falsely reported as crashing causing the plugin to crash again...how do i kill off the Windows 7 Startup Tips and Tricks for Linux Mint after Installation [Mint 17 to 17.2 - Cinnamon Edition] Tips and Tricks for Linux Mint after Installation [Mint 17 to 17.2 - What do you call someone without a nationality? If the optional level is not set, error_reporting() will just return the current error reporting level. | http://degital.net/error-reporting/turm-off-error-reporting.html | CC-MAIN-2018-22 | refinedweb | 1,043 | 50.46 |
.
The Athletic Wizard: Alicia Spinnet, Ginny Weasley, Gwendolyn Morgan, Robin Higgy, Debbie Muntz
The Daily Prophet: Alicia, Ginny, Robin, Gwendolyn, Debbie
Quidditch News: Robin, Ginny, Gwendolyn, Debbie, Alicia
Seeker Weekly: Gwendolyn, Ginny, Robin, Debbie, Alicia
The Quibbler: Debbie, Ginny, Robin, Gwendolyn, Alicia
As you can see, there’s quite a bit of disagreement and personal taste involved. You didn’t get to watch all of the games, but you’d like to make a decision on who the best players were, by somehow aggregating the opinions of the popular newspapers. An easy option would be to pretend that each newspaper votes for the player that they rank #1, and ignore the rest. As Alicia Spinnet is the only player getting two nominations for best player, she should win best player, right?
Upon closer inspection, Alicia seems very controversial, loved by two but hated by five of the newspaper. Ginny, on the other hand, didn’t stand out as best player to anybody, but she was uniformly considered runner-up. There should be some way to account for this. It would be nice if we would have a method of finding an optimal ranking that maximizes some sort of agreement with the opinions we are trying to aggregate.
Kendall’s Tau distance¶
One of the most interesting ways to measure disagreement between rankings is the Tau statistic introduced by Kendall. It essentially measures the number of pairwise disagreements between two rankings. Since you can think of it as the number of flips you need to perform on a ranking to turn it into the other, it is sometimes called bubble-sort distance.
While the closely-related Tau correlation coefficient is implemented in Scipy as
scipy.stats.kendalltau, let’s code it ourselves in a simpler way.
from __future__ import print_function import numpy as np from itertools import combinations, permutations def kendalltau_dist(rank_a, rank_b): tau = 0 n_candidates = len(rank_a) for i, j in combinations(range(n_candidates), 2): tau += (np.sign(rank_a[i] - rank_a[j]) == -np.sign(rank_b[i] - rank_b[j])) return tau
Now we can represent a rank as a numpy vector, with missing values.
# columns in order of appearance: cols = "Alicia Ginny Gwendolyn Robin Debbie".split() ranks = np.array([[0, 1, 2, 3, 4], [0, 1, 3, 2, 4], [4, 1, 2, 0, 3], [4, 1, 0, 2, 3], [4, 1, 3, 2, 0]])
Two rankings that agree completely should have a distance of 0.
kendalltau_dist(ranks[0], ranks[0])
0
The Athletic Wizard seems to be closer to the Daily Prophet than to Seeker Weekly.
print('d(athletic_wizard, prophet) = {}'.format(kendalltau_dist(ranks[0], ranks[1]))) print('d(athletic_wizard, seeker) = {}'.format(kendalltau_dist(ranks[0], ranks[3])))
d(athletic_wizard, prophet) = 1 d(athletic_wizard, seeker) = 5
Kemeny-Young rank aggregation¶
Now that we have a distance metric, we can formulate a loss function to minimize in rank-space. We are looking for a ranking $\hat\tau$ that satisfies $$ \sum_i d(\hat\tau, \tau_i) \leq \sum_i d(\tau, \tau_i) \text{ for all } \tau $$
This aggregation method was proposed by John Kemeny [1], and later shown by Peyton Young to be a maximum likelihood estimator of pairwise preferences under the assumption that a voter will randomly flip two candidates from the true ranking is the same $p < 0.5$ [2].
For rankings of small length, one way to compute this optimal aggregation is by comparing the scores of all possible rankings, in other words, a brute-force approach:
def rankaggr_brute(ranks): min_dist = np.inf best_rank = None n_voters, n_candidates = ranks.shape for candidate_rank in permutations(range(n_candidates)): dist = np.sum(kendalltau_dist(candidate_rank, rank) for rank in ranks) if dist < min_dist: min_dist = dist best_rank = candidate_rank return min_dist, best_rank
dist, aggr = rankaggr_brute(ranks) print("A Kemeny-Young aggregation with score {} is: {}".format( dist, ", ".join(cols[i] for i in np.argsort(aggr))))
A Kemeny-Young aggregation with score 15 is: Ginny, Robin, Gwendolyn, Debbie, Alicia
Integer Programming formulation¶
The brute-force approach is, as you can see, simple to understand and quick to code. However, the number of total ranks of size $n$ is $n!$, so this approach quickly becomes infeasible for real-world problems. Unfortunately, it turns out that this problem (along with many related problems in rank-world) is NP-hard even for only four voters [3]. There have been quite a few approaches and approximations. In many cases, such as search results aggregation, approximations are good enough. For the cases where an exact solution is required, a formulation as a constrained integer program is given in [4].
We build a weighted directed graph $G = (V, E)$ with the candidates as vertices. The edges are defined as such: for every pair of candidates $i, j$, let $\#\{i > j\}$ denote the number of voters who rank $i$ higher than $j$. Draw an edge $e$ between each $i, j$ with weight $w_e = |\#\{i > j\} - \#\{j > i\}|$ (if nonzero, of course). The orientation of the edge is from the less preferred to the more preferred node.
The formulation is based on the alternative interpretation of the Kemeny optimal aggregation as the ranking that minimizes the weights of edges it disagrees with:$$ \operatorname{minimize} \sum_{e \in E} w_e x_e \ \operatorname{subject to} \ \forall i \neq j \in V, x_{ij} + x_{ji} = 1 \ \forall i \neq j \neq k \neq i \in V, x_{ij} + x_{jk} + x_{ki} \geq 1 $$
In the above problem, all variables are integer, and effectively binary under the other constraints. The interpretation is that $x_{ij} = 1$ if, in the aggregated rank, $i$ is ranked lower than $j$.
The constraints essentially impose that the variables define a total order. The first set of constraints enforce antisymmetry and totality: either $i$ is ranked lower than $j$ or the other way around. The second set of constraints enforce transitivity.
def _build_graph(ranks): n_voters, n_candidates = ranks.shape edge_weights = np.zeros((n_candidates, n_candidates)) for i, j in combinations(range(n_candidates), 2): preference = ranks[:, i] - ranks[:, j] h_ij = np.sum(preference < 0) # prefers i to j h_ji = np.sum(preference > 0) # prefers j to i if h_ij > h_ji: edge_weights[i, j] = h_ij - h_ji elif h_ij < h_ji: edge_weights[j, i] = h_ji - h_ij return edge_weights print(_build_graph(ranks))
[[ 0. 0. 0. 0. 0.] [ 1. 0. 3. 3. 3.] [ 1. 0. 0. 0. 3.] [ 1. 0. 1. 0. 3.] [ 1. 0. 0. 0. 0.]]
from lp_solve import lp_solve def rankaggr_lp(ranks): """Kemeny-Young optimal rank aggregation""" n_voters, n_candidates = ranks.shape # maximize c.T * x edge_weights = _build_graph(ranks) c = -1 * edge_weights.ravel() idx = lambda i, j: n_candidates * i + j # constraints for every pair pairwise_constraints = np.zeros(((n_candidates * (n_candidates - 1)) / 2, n_candidates ** 2)) for row, (i, j) in zip(pairwise_constraints, combinations(range(n_candidates), 2)): row[[idx(i, j), idx(j, i)]] = 1 # and for every cycle of length 3 triangle_constraints = np.zeros(((n_candidates * (n_candidates - 1) * (n_candidates - 2)), n_candidates ** 2)) for row, (i, j, k) in zip(triangle_constraints, permutations(range(n_candidates), 3)): row[[idx(i, j), idx(j, k), idx(k, i)]] = 1 constraints = np.vstack([pairwise_constraints, triangle_constraints]) constraint_rhs = np.hstack([np.ones(len(pairwise_constraints)), np.ones(len(triangle_constraints))]) constraint_signs = np.hstack([np.zeros(len(pairwise_constraints)), # == np.ones(len(triangle_constraints))]) # >= obj, x, duals = lp_solve(c, constraints, constraint_rhs, constraint_signs, xint=range(1, 1 + n_candidates ** 2)) x = np.array(x).reshape((n_candidates, n_candidates)) aggr_rank = x.sum(axis=1) return obj, aggr_rank
_, aggr = rankaggr_lp(ranks) score = np.sum(kendalltau_dist(aggr, rank) for rank in ranks) print("A Kemeny-Young aggregation with score {} is: {}".format( score, ", ".join(cols[i] for i in np.argsort(aggr))))
A Kemeny-Young aggregation with score 15 is: Ginny, Robin, Gwendolyn, Debbie, Alicia
We get the same result as in the brute-force case. However, it’s much faster. Let’s verify this, and in the process, also test that we always get the same result.
from time import time import pandas as pd timings = pd.DataFrame(columns="method rank_len n_ranks time".split()) np.random.seed(0) for rank_len in range(4, 9): for n_ranks in (5, 20): ranks = [np.random.permutation(rank_len) for _ in range(n_ranks)] ranks = np.array(ranks) t0 = time() brute_score, brute_aggr = rankaggr_brute(ranks) timings = timings.append(dict(method="brute", rank_len=rank_len, n_ranks=n_ranks, time=time() - t0), ignore_index=True) t0 = time() _, lp_aggr = rankaggr_lp(ranks) timings = timings.append(dict(method="lp", rank_len=rank_len, n_ranks=n_ranks, time=time() - t0), ignore_index=True) assert (brute_score == np.sum(kendalltau_dist(lp_aggr, rank) for rank in ranks)) # lp is much faster, let's run it for longer rankings. for rank_len in range(9, 16): for n_ranks in (5, 20): t0 = time() _, lp_aggr = rankaggr_lp(ranks) timings = timings.append(dict(method="lp", rank_len=rank_len, n_ranks=n_ranks, time=time() - t0), ignore_index=True)
%matplotlib inline import matplotlib.pyplot as plt import seaborn as sns plt.figure(figsize=(7, 6)) plt.xticks(range(4, 16), range(4, 16)) for subplot, n_ranks in enumerate((5, 20)): for method in ('brute', 'lp'): this_rows = timings[(timings.n_ranks == n_ranks) & (timings.method == method)] plt.semilogy(this_rows.rank_len, this_rows.time, label="{} n={}".format(method, n_ranks)) plt.legend(loc="upper left") plt.suptitle("Ranking size vs. log time to solve") plt.show()
You can see that the brute force approach is a bit worse than exponential, while the integer programming approach is more reasonable and also is less sensitive to the number of voters being aggregated. We therefore have a reasonably fast efficient exact solution to the rank aggregation problem on small datasets.
References¶
[1] J Kemeny. [Mathematics without numbers](), 1959
[2] HP Young. [Condorcet’s theory of voting](), 1988
[3] JJ Bartholdi III, CA Tovey, MA Trick. [The computational difficulty of manipulating an election](), 1989
[4] V Conitzer, A Davenport, J Kalagnanam. [Improved bounds for computing Kemeny rankings](), 2006 | http://vene.ro/blog/kemeny-young-optimal-rank-aggregation-in-python.html | CC-MAIN-2016-44 | refinedweb | 1,605 | 56.35 |
Hybrid View
Compile and concatenate only app files with v3.0.0.230
trying with:
Code:
sencha compile -classpath=app union -r -namespace MyAppNamespace and concat -yui minified.js
EDIT: hmmm, seems that this one gives the expected output:
Code:
sencha compile -classpath=app exclude -all and include -namespace MyApp and concat -yui minified.js
The "class" option is used to specify individual class names. If you're trying to include classes matching MyAppNamespace.*, you'll want to use the "namespace" option instead, like so:
Code:
sencha compile -classpath=app union -r -namespace MyAppNamespace and concat -yui minified.js
burnnat, yes I noticed and reedited the post and just now saw your post, and also just now figured out with another cmd which seems to work
The "union -r" command is a full dependency (r=recursive) inclusion so it will include all files you specify and all files they require or use.
It sounds like you don't really want a dependency scan, just an ordering of the files in your namespace, so the command you picked should work for that but it will be all files in that namespace, regardless of whether you use them or not.Don Griffin
Director of Engineering - Frameworks (Ext JS / Sencha Touch)
Check the docs. Learn how to (properly) report a framework issue and a Sencha Cmd issue
"Use the source, Luke!")/page5
We are getting used with Sencha Cmd, thx for this great tool.
This is somewhat what I was looking for, however I get error
Code:
[ERR] Failed to find file for @core required by path/myfile.js | https://www.sencha.com/forum/showthread.php?248168-Compile-and-concatenate-only-app-files-with-v3.0.0.230&mode=hybrid | CC-MAIN-2015-48 | refinedweb | 266 | 67.28 |
Introduction: In this article I am going to explain with example How to create registration form and approve newly registered user by sending them account activation link on their email address in asp.net with both C#.Net and VB.Net languages.
Description: The concept is simple as mentioned below.
- First user will fill the form having Name, Email Id, Address and Contact Number field. This information will be stored in the Sql server database table where a field “Is_Approved” is set to 0 i.e. false by default.
- Also email id, and the user id based on email id is set in the query string parameters and sent to the email address of the newly registered user as an activation link.
- When user check his email and click on the activation link then he will be redirected to the "ActivateAccount.aspx" page where User id and email Id from the query string will be verified and the “Is_Approved” field in the sql server table is set to 1 i.e. True.
- Now he is an approved user and authorized to log in. Create contact us form and Recover and reset the forgot password using activation link in email id and Check login in asp.net by passing parameter to stored procedure in sql server .
Implementation: let’s create an asp.net web application to understand the concept.
First of all create a database e.g. “MyDataBase” in Sql server and create a table with the column and the data type as shown and name it “Tb_Registration”
Note: I have set the data type of the Is_Approved field to bit and set its default value to 0 i.e. false. It means whenever a new record is inserted in the table the “Is_Approved” will be 0. So the new users need to get their account approved by clicking on the activation link in their email address.
- In the web.config file create the connection string to connect your asp.net application to the Sql server database as:
<connectionStrings>
<add name="conStr" connectionString="Data Source=lalit;Initial Catalog=MyDataBase;Integrated Security=True"/>
</connectionStrings>
Note: Replace the Data Source and Initial Catalog(i.e. DataBase Name) as per your application.
Source Code:
- Add a page and name it “Registration.aspx” and design the page as:
<div>
<fieldset style="width:350px;">
<legend>Registeration page</legend>
<table>
<tr>
<td>Name *: </td><td>
<asp:TextBox</asp:TextBox><br /><asp:RequiredFieldValidator</asp:RequiredFieldValidator></td>
</tr>
<tr>
<td>Email Id: * </td><td>
<asp:TextBox</asp:TextBox><br />
<asp:RequiredFieldValidator</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator</asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td>Address : </td><td>
<asp:TextBox</asp:TextBox></td>
</tr>
<tr>
<td>Contact No.</td><td>
<asp:TextBox</asp:TextBox></td>
</tr>
<tr>
<td> </td><td>
<asp:Button</td>
</tr>
</table>
</fieldset>
</div>
Note: I have also implemented the validation on Name and the Email Id field to ensure they are not left blank using RequiredFieldValidator validation control and also used RegularExpressionValidator to check for the valid email address on the Email Id field.
Asp.Net C# Code for Registration.aspx
- In the code behind file (Registration.aspx.cs) write the code as:
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Text;
using System.Net;
using System.Net.Mail;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
protected void btnSubmit_Click(object sender, EventArgs e)
{
MailMessage msg;
SqlCommand cmd = new SqlCommand();
string ActivationUrl = string.Empty;
string emailId =)
{
con.Open();
}
cmd.ExecuteNonQuery();
//Sending activation link in the email
msg = new MailMessage();
SmtpClient smtp =() + "!\n" +
"Thanks for showing interest and registring in <a href=''> webcodeexpert.com<a> " +
" Please <a href='" + ActivationUrl + "'>click here to activate</a> your account and enjoy our services. \nThanks!";(this, this.GetType(), "Message", "alert('Confirmation Link to activate your account has been sent to your email address');", true);
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Error occured : " + ex.Message.ToString() + "');", true);
return;
}
finally
{
ActivationUrl = string.Empty;
con.Close();
cmd.Dispose();
}
}
private string FetchUserId(string emailId)
{
SqlCommand cmd = new SqlCommand();
cmd = new SqlCommand("SELECT UserId FROM Tb_Registration WHERE EmailId=@EmailId", con);
cmd.Parameters.AddWithValue("@EmailId", emailId);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
string UserID = Convert.ToString(cmd.ExecuteScalar());
con.Close();
cmd.Dispose();
return UserID;
}
private void clear_controls()
{
txtName.Text = string.Empty;
txtEmailId.Text = string.Empty;
txtAddress.Text = string.Empty;
txtContactNo.Text = string.Empty;
txtName.Focus();
}
- Add a new page and name it .
Code for ActivateAccount.aspx page
- In the code behind file (ActivateAccount.aspx.cs) write the code as:
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ActivateMyAccount();
}
}
private void ActivateMyAccount()
{
SqlConnection con = new SqlConnection();
SqlCommand cmd = new SqlCommand();
try
{
con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
if ((!string.IsNullOrEmpty(Request.QueryString["UserID"])) & (!string.IsNullOrEmpty(Request.QueryString["EmailId"])))
{ /)
{
con.Open();
}
cmd.ExecuteNonQuery();
Response.Write("You account has been activated. You can <a href='Login.aspx'>Login</a> now! ");
}
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Error occured : " + ex.Message.ToString() + "');", true);
return;
}
finally
{
con.Close();
cmd.Dispose();
}
}
Asp.Net VB Section:
Source code of Registration.aspx
- Design the Registration.aspx page as in C#.Net section but replace the line
<asp:Button With <asp:Button
."
VB.Net Code for Registration.aspx page
- In the code behind file (Registration.aspx.vb) write the code as:
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Text
Imports System.Net
Imports System.Net.Mail
Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("conStr").ConnectionString)
Protected Sub btnSubmit_Click(sender As Object, e As System.EventArgs) Handles btnSubmit.Click
Dim msg As MailMessage
Dim cmd As New SqlCommand()
Dim ActivationUrl As String = String.Empty
Dim emailId As String = Then
con.Open()
End If
cmd.ExecuteNonQuery()
‘Sending activation link in the email
msg = New MailMessage()
Dim smtp As() & "!" & vbLf & "Thanks for showing interest and registring in <a href=''> webcodeexpert.com<a> " & " Please <a href='" & ActivationUrl & "'>click here to activate</a> your account and enjoy our services. " & vbLf & "Thanks!"(Me, Me.[GetType](), "Message", "alert('Confirmation Link to activate account has been sent to your email address');", True)
Catch ex As Exception
ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('Error occured : " & ex.Message.ToString() & "');", True)
Return
Finally
ActivationUrl = String.Empty
con.Close()
cmd.Dispose()
End Try
End Sub
Private Function FetchUserId(emailId As String) As String
Dim cmd As New SqlCommand()
cmd = New SqlCommand("SELECT UserId FROM Tb_Registration WHERE EmailId=@EmailId", con)
cmd.Parameters.AddWithValue("@EmailId", emailId)
If con.State = ConnectionState.Closed Then
con.Open()
End If
Dim UserID As String = Convert.ToString(cmd.ExecuteScalar())
con.Close()
cmd.Dispose()
Return UserID
End Function
Private Sub clear_controls()
txtName.Text = String.Empty
txtEmailId.Text = String.Empty
txtAddress.Text = String.Empty
txtContactNo.Text = String.Empty
txtName.Focus()
End Sub
- Add a new page .
In the code behind file (ActivateAccount.aspx.vb) and write the code on the page load event as:
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
ActivateMyAccount()
End If
End Sub
Private Sub ActivateMyAccount()
Dim con As New SqlConnection()
Dim cmd As New SqlCommand()
Try
con = New SqlConnection(ConfigurationManager.ConnectionStrings("conStr").ConnectionString)
If (Not String.IsNullOrEmpty(Request.QueryString("UserID"))) And (Not String.IsNullOrEmpty(Request.QueryString("EmailId"))) Then
Then
con.Open()
End If
cmd.ExecuteNonQuery()
Response.Write("You account has been activated. You can <a href='Login.aspx'>Login</a> now! ")
End If
Catch ex As Exception
ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('Error occured : " & ex.Message.ToString() & "');", True)
Return
Finally
con.Close()
cmd.Dispose()
End Try
End Sub
Now over to you:
108 commentsClick here for comments
Fine Job but to send random password to user mail.Reply
Great work :)Keep blogging!!Reply
thanks for the appreciation. stay tuned and stay connected for more useful updates..Reply
hii sir, i have followed ol ur code, bt still my code nt works.. wat to do in this case????Reply
Please let me know the exact problem you are facing so that i can help you resolve that..Reply
sir why you are use Parameter variable without storedprocedure.Reply
please sir tell me the role of it.
Hello Danish..It is good programming practice and prevents from Sql injection and other hacking..So never pass the value to variable directly from the textbox,instead use this approach.Reply
thankyou sirReply
sir how i decide the name of parameter variable.is it the name of database table variable with @sign.
what is the use of cmd.ExecuteScalar() and Server.HtmlEncode
your code is very helpful to me .
Hello Danish Khan, parameters name can be anything with the @ prefix..Reply
ExecuteScalar executes the query and returns the very first column of first row, other columns and rows are ignored by this method.Basically it is used to retrieve single value from database.
The HTMLEncode method applies HTML encoding to a specified string.
I will try to create post related to the above so that you can better understand the concept.
thank u sirReply
sir please create post. that discribed how to genrate pdf file in asp.net
sorry sir i want ask you another queryReply
related to this program. UserId is a primary key and it doesnt repeated in table .but emailId and contact number genrated ambigulty
we can easily inserted same emailId and contact no into another record.please tell me the solution
Hi Danish..Read the below mentioned article to export gridview data to create pdf file
Dear Sir,Reply
I want to convert a panel content into pdf file but i have not used table,tr and td anywhere inside panel content. i have used only div and css inside panel. when i am trying to convert in pdf its giving exception 'the page source is empty' like that type of message. is it possible to write div content in .pdf format using iTextSharp ?. Please help me..
When i am using table ,tr and td then its writing in pdf
but i am not able to provide a good look and feel in table,tr and td..
So ,please reply me how to write a div content.
when i click on button. it doesn't send the email and doesn't give any message. there is no any errors. can you upload the whole project of this email example??Reply
Hello chirag..Check your spam emails. sometime mails goes in the spam folder. Also have you changed the localhost path as per your application in the lineReply
Server.HtmlEncode("" + FetchUserId(emailId) + "&EmailId=" + emailId);
Please check and notify me..
sir please give me the solution of my problumReply
You can create emailid and contact number field the unique key..this way they can not be duplicated..Reply
Hello danish..You can create emailid and contact number field the unique key..this way they can not be duplicated..Reply
thank you sir.Reply
sir please create a post about sharepoint.
Hello Danish Khan..right now i am not covering sharepoint..but i will cover it in near future..keep reading..:)Reply
thankyou sir for responseReply
Your welcome danish..:)Reply
hi sir,how send sms from asp.net website using way2smsReply
hello..i will post an article to send sms from asp.net as soon as possible..so stay connected for more useful updates. :)Reply
sir activation page is not working please let know what is process?Reply
Hi Mithlesh..exactly what problem you are facing?Reply
Hii sir, i want to create pdf file and send it to the user. Give me guidelines for it.Reply
when i click on button. it doesn't send the email and doesn't give any message. there is no any errors. Pls help meReply
Hello Thilaga R..Check your spam emails also. sometime mails goes in the spam folder. Also have you changed the localhost path as per your application in the lineReply
Server.HtmlEncode("" + FetchUserId(emailId) + "&EmailId=" + emailId);
Please check and notify me..
i checked that...but no use..its urgent pls help meReply
Have you tried debugging the code? if not then i suggest you to do that to know the exact problem in you code..check and notify me where you are getting error?Reply
there is no any errors sir. can you upload the whole project of this email?? because i m doing one projectReply
hello sir , how to get userid based on emailid and what is the FetchUserid ?Reply
ActivationUrl = Server.HtmlEncode("" + FetchUserId(emailId) + "&EmailId=" + emailId);
hello sir , what is the FetchUserid and how to get userid from database?Reply
the following query
ActivationUrl = Server.HtmlEncode("" + FetchUserId(emailId) + "&EmailId=" + emailId);
Hi, srikanth kalyan..FetchUserid is the function to get the userid based on entered email id. Userid is the primary key and will be unique always..Reply
thanks lalit sir,Reply
i saw for ur activation link Blog.
Your welcome roushan choudhary..stay connected and keep reading..:)Reply
how to generate random password that send to email id after registration is over...and that password is used for login..Reply
how to create auto generate passwords and send it newly created user email id....Reply
how to write code for auto generate password and send it to newly create user email id?Reply
Hello Santu..i will create an article as per your requirement and publish as soon as possible..so stay connected and keep reading for more updates..:)Reply
Great work thanks for this example!Reply
Hello Jeremy W..thanks for appreciating my work..keep reading and stay connected for more useful updates like this..:)Reply
Thanks for the wonderful tutorial.Graspable coding for beginners....Reply
It is always nice to hear that my tutorial helped anyone..Thanks Raasitha..:)Reply
Very good sirReply
thanks for the appreciation...:)Reply
hello sir i want to create a inquiry form & when ever from fill by user then all information send in my email ///////////i am very confuse pls help meReply
Hi, read the following article:Reply
it will help you..
hello,Reply
plz provide me solution for error ScriptManager does not exist in current context
try to include System.Web.ExtensionsReply
hi sir, i already applied everything u explained into this post but it doesn't work sending email point, please help me out doing this.Reply
Hello Mohammed Muthna..are you getting any error? if yes then send me the details of that error so that i can help you in solving that..:)Reply
Hello sir,Reply
My activation page is not working ??????
when i click on "click here to activate" this link. i redirect on ActivateAccount page
& i got this url ()
but d whole page is blank.
please revert ASAP
Hello Aarti..i suggest you to try to debug the code on page load of ActivateAccount.aspx page..this way you can get the exact error..then let me know the results..i will help you to solve your problem..Reply
Thank's for u r reply.Reply
i debug ActivateAccount.aspx page but still it is blank.
there is no any error.
string link = Server.HtmlEncode("" + FetchUserId(emailId) + "&email=" + emailId);
is it correct???????
Hello aarti..Reply
there must be a 4 digit port number attached with your url e.g. in the link..
when you will run the registration or signup.aspx page then check the url from browser, it will contain 4 digit port number also. add the port number in the url also..
it should look like ActivationUrl = Server.HtmlEncode("" + FetchUserId(emailId) + "&EmailId=" + emailId);
Goodmoring from GreeceReply
The article is great but when i run th app, i take this error
CS1502: The best overloaded method match for 'System.Data.SqlClient.SqlCommand.SqlCommand(string, System.Data.SqlClient.SqlConnection)' has some invalid arguments
Source Error:
Line 34: try
Line 35: {
Line 36: cmd=new SqlCommand("insert into Tb_Registration(Firstname,LastName,UserName,Password,EmailId,Phone,Address) values (@Firstname,@LastName,@UserName,@Password,@EmailId,@Phone,@Address)", con);
Line 37:
Line 38:
my email is kostasvit@gmail.com please help!!!!
Hello..i suggest you to recheck your table fields and their data types and ensure that you are passing the values to these parameters properly..if still you face the problem then let me know..i will help you in sorting your problem..Reply
Hellow Sir?I have deployed my application but dont want to hard code the url to send the email link to complete registration,how can i make sure it includes the current browser url i have than using my locallhost?Reply
Hi Sir Signup or Registration Page is Ok butReply
what about Login page and I trying this code for the login page without activating the link which come to my mail and now the login page is working without activating the link
Hello sir,Reply
I tried to implement your code but somehow its not working.
It gives no error but when I click on the Submit button it redirect to the same page (Registration,aspx).
And the database is not updated also.
Please help me out.
Hello aarzoo patel..i suggest you to recheck your code thoroughly and try once again..if still you face the problem then let me know..i will help you to sort out the issue..Reply
The error was resolved.Reply
Thank you sir for this valuable code.
And keep posting new stuffs it really helps a lot.
Hi aarzoo patel..i am glad to know that you have resolved your issue..stay connected and keep reading..:)Reply
Great Work and good effort to ans every Visitor ASAP Like it ReallyReply
Thanks Majeed Raju for your appreciations..Reply
Hello sirReply
i went to put Google map of specific location in my site .
if you like to help me then pls help me.
Hi rajat kumar..i will create an article as per your requirement and publish very soon..so stay connected and keep reading ...:)Reply
So It don't need do anything inReply
protected void Page_Load(object sender, EventArgs e)
{
} for this registration page?
Hi Sir Could you make sure I don't need add any code in th Page_Load event class?Reply
Yes , you don't need to write any code in page load event..Reply
Yes , you don't need to write any code in page load event..Reply
Thank you sir, I have a dropdown list in my table for user select different department. I code as:Reply
cmd.Parameters.AddWithValue("@department",DropDownListDP.SelectedItem.ToString().Trim());
in the clear_Controls() code as: DropDownListDP.SelectedIndex = 0;
are they correct. Do I need add any in the ActiveAccount.aspx page.
I code as your way and run it , there are no any problem but no email, no data add to database, nothing happen. Could you tell me what's the problem. Thanks
Hi sir,If I want to create a registration compete page to show the successful message and error message. how can I do. If use entered same email address, how to validate and show message say: Your email address already be used.ThanksReply
Could you post your Reset Password code without using stored procedure database. I am doing a project don't want to use store procedure. This is an registration system. User register, receive email confirmation click the link in email to active account. Login, reset password if forget. Change password if received random given password. user can go their profile change their information. Logon.Reply
Could help find code for all this steps without use stored procedure database. using very basic and easy way. thanks sir
Hello Lalit,Reply
I'd appreciate your advice and if possible help in the following:
Is it possible to activate the account by calling a Web Service? I mean, the user receives the e-mail with the activation link, and the activation/approval process is made by calling a Web Service, instead of a Web Page to make the process seamless for the user.
I'd be very thankful for your help/guidelines because it's huge demand made in a project I'm involved in.
Thank you very much in advance
Paul
Hi, you can read the following article as per your requirementReply
how to send data like name,address,contact information on email address in asp.netReply
hi, i have query regarding user registration whenever new user register have to generate user id and display in the label and using that id user have to login, so that next user should not have similar user id. also the previous registered user id should display automatically when next user login for new register.Reply
thanks in advance
i m a big fan of urs lalit.. god bless.Reply
keep blogging..
Hi Reshav..thanks for appreciating my work...it is always nice to hear that someone liked my work..:)Reply
good one, but if I can download this.........Reply
vReply
yesReply
Is it ok to use this code on my websiteReply
Yes, of course you can with little or no modification as per your requirement..Reply
Hi, I want to registered an form in a database and have given an identifier for use later in my project, can you please help meReply
Hi, I want to resgistred a form in a database and have given an identifier for use later in my project, can you please help meReply
sir i want to upload doc file in wef form..but doc file id download ..i want this file no download drct show the page a read ..please help meReply
How to get user details by entering his id in the registration form automatically by pressing enter buttonReply
Hello sirReply
good job
only one problem will u plz help me to solve?
port number get chnaged so cant redirected sometime wts d solution
ActivationUrl = Server.HtmlEncode("" + FetchUserId(emailId) + "&EmailId=" + emailId);
Dis port is changed evry time
When you make this page online you just need to replace the localhost path along with port number with your website name then it will work fine because the path will remain same always..Reply
ScriptManager Does not Exist"Reply
????
what is solution for this ?
Hello Bhavik,Reply
there may be two solutions to your problem. First include the namespace System.Web.UI
If still the problem remain the same then Go to solutions explorer -> right click on project -> Select add reference -> in .Net tab select System.Web.Extensions and click OK.
Please let me know it it resolved the issue or not?
in .net tab there is only System.web.Extensions .Reply
so now waht's the problem ??
Hi sir, is there any tutorial from you to create a complete website like way2sms? Needed for my project.Reply
Thank you.
Is System.web.Extensions checked? and have you included the namespace System.Web.UI ? I yes and still getting problem then send me the complete code , i will check and resolve your issueReply
Hello Syed..Currently there is no such article as per your requirement. In future i will try to create that and post that here. so stay connected and keep reading..Reply
My coding is running successfullyReply
Hi, i got error at this line under private void activate account. can help me to solve the problem?Reply
if (!string.IsNullOrEmpty(Request.QueryString["CUsername"]))&(!string.IsNullOrEmpty(Request.QueryString["CEmail"])))
There must be && instead of single & in the code. Please correct that and it will work fine.Reply
Thanx Lalit , it was really use full for me :)Reply
Simple and very usefull. thank u sir |o|Reply
Ur welcome.Stay connected and keep reading for more useful updates like this..Reply
Ur welcome..I am glad you found this article helpful for you..:)Reply
How to get notification email..because i already submit the registration form and check the db table, the IS APPROVED is 0 need to check the email?but i dont get any email. please helpReply
#newbie
very great work....May God keep you always happy.and closet wish of your heart come true...Ameen.. | https://www.webcodeexpert.com/2013/08/create-registration-form-and-send.html?showComment=1379911601412 | CC-MAIN-2021-04 | refinedweb | 4,000 | 61.02 |
Etch-A-Sketch is built from a pocket Etch-A-Sketch and 6 individual 3D printed components. The control is handled by a Raspberry Pi Zero (or Zero W) and a custom circuit board containing motor drivers and inputs. The wheels are driven by two stepper type motors mounted on the 3D printed frame, through two 3D printed gears. The camera is mounted in the final 3D printed piece. The total build & print time should be around 1 day allowing for snacks.
3D Parts
There are 6 parts to the build. The first, the largest, is a frame which surrounds the Etch-A-Sketch and holds the stepper motors in place. There are two wheel gears (printed in white, orange in the image below) to replace the control wheels of the Etch-A-Sketch, and two driver gears (printed in red) for the steppers. Finally, there is a small camera mount which sits on the top of a Raspberry Pi Zero to hold the camera.
The parts are all available to download as a zip of STL files or to tinker with directly on TinkerCAD. The colours are optional, but allow the parts to match the aesthetic of the original Etch-A-Sketch.
Development
The Etch-A-Sketch comes with two white plastic control wheels for drawing with. On the original and the pocket Etch-A-Sketch these are mounted onto metal drive rods, and can be removed with a little force. The best approach is to get something long and thing (like a metal ruler) underneath and lever it up. Put cardboard under it to avoid damaging the case.
Once removed the original wheels (L) are replaced with the 3D printed look-a-likes (R) with a cog built into the lower half. The replacement wheels are slightly larger in diammeter and lower profile, but don't look out of place.
The Etch-A-Sketch is still completely usable with these wheels attached.
The modern full-size Etch-A-Sketch (sold as "classic") now has plastic drive shafts and the wheels are glued onto it. The only option here is to cut into them. Cutting into something that rotates is asking for an accident, so be careful.
The circuit
The power management, motor driver circuit, status lights and inputs were laid out on a perfboard. The Raspberry Pi is mounted in the centre of the board, with the motor driver on the right hand side and the rest of the circuit on the left.
Most of the connections are under the board, using solder bridges and bits of wire. There are probably better ways to lay this out, particularly around the power-input where it got messy due to a busted component. The circuit diagram is given below.
The Fritzing file is available.
I had initially intended to have a flash mounted on the board too, but there wasn't enough room & in the end decided to omit it. An obvious improvement would be to have the status LEDs visible from the back (screen-side) of the camera, so you can see when it's grabbed a shot — although it currently works great for selfies.
The circuit board was mounted to the back of the Etch-A-Sketch with two small screws in the top of the board. I wasn't sure if this was going to break it, but it didn't.
Power supply
The Etch-A-Sketch takes 4x AA batteries and 3x 18650 LiPo cells. The former is used for driving the motors (6V) while the latter (11.1V) powers the Raspberry Pi through a buck converter regulated at 5V. A 100μF capacitor is added to smooth the output.
The soldering in this bit of the board is an absolute mess as the first buck converter mounted was faulty and the second blew it's capacitor during testing. The secondary capacitor (added to smooth the output) saves the day.
The Pi is doing some heavy processing during the graph generation (see later). The original plan was to power the Pi through the same AA batteries, but the power drop caused by the steppers ruled this out. Using a separate 4xAA pack solved this, but could only sustain the system for an hour or so.
The LiPo cells are more than enough to keep the Pi ticking over for quite some time, until the voltage drops to ~2.2V (6.6V total, which through the regular is <5V). The AA cells are run down fairly quickly (10-15 pictures worth). When this happens it just stops drawing, no harm done.
The 4xAA battery pack is hot-glued onto the back of the Etch-A-Sketch. I scored a bunch of lines into the back to improve attachment (increase the surface area). The LiPo battery pack is in turn hot-glued onto the case for the AA battery, so can be removed by sliding it off.
The AA battery pack has an integrated power switch, while the LiPo cells use a switch on the main circuit board.
The frame
It took ~20 iterations to get to the final version, both of the frame (positioning, and for different steppers) and the gearing (to get enough torque).
One useful tip is to print the frame prototypes at only 2mm thick, and use these to test the positioning and orientation. This allowed to rapid iteration through a lot of bad ideas. Unfortunately this doesn't work nearly as well for the gears, so I now have a box of 50 odd gear rejects.
This would have been a lot simpler if the entire construction was 3D printed as the measurements would have been known from the start.
The frame slips over the Etch-A-Sketch from the front. The back part (black) of the Etch-A-Sketch actually sticks out a little and catches it. This was entirely accidental. You can glue the frame on, but I left it free in case something went horrifically wrong and I had to start over.
The two motors sit in the semi-circle mounts on the corner of the frame and can be secured with bolts, washers and nuts through the holes. I used a couple of random-sized ones I had lying around.
The motors are connected to the two JST sockets on the bottom of the board, with the connection going to the closest side (i.e. left-to-left). There was quite a bit of spare wire on my motors so it was bundled up with a wire-tie.
Motors & Drivers
To accurately plot an image we need precise movement. Stepper motors allow precise step-wise control rotation in either direction. In the final build of the Etch-A-Sketch I used two 5V 28BYJ-48 motors, driven using ULN2003 ICs.
The motors are powered from 4xAA batteries (6V) a little over a full charge, but nothing to be concerned about. This combination of driver and motor provided enough torque to turn the Etch-A-Sketch wheels at 1:1 ratio and still give reliable movement.
The stepper motors drive the Etch-A-Sketch through 3D printed PLA cogs. These are the same size and ratio as the white plotter wheels mounted earlier. This allows us to drive the wheels without using an external hacks (belts, cables, etc.)
What didn’t work
Finding a combination of driver and stepper motor which could drive an Etch-A-Sketch from 4xAA batteries reliably took a large chunk of the build time.
The initial prototype used a smaller stepper motor than the final design, to try and keep things as portable as possible. Turning the Etch-A-Sketch wheels by hand is not difficult, but the little stepper couldn’t do it. Stepper motor driver boards (which can overdrive voltage with regulated current to get maximal torque) did better but it was still not enough.
Switching to the larger stepper offered more torque, but now the power was limited by the 6V battery pack — it was not really over-driving at all. The ULN2003 finally solved the problem by allowing the energising of paired adjacent coils — effectively doubling the torque. This gave enough leeway to continue turning even if the input voltage from the AA batteries drops.
Inputs & Outputs
Taking a picture is triggered by the shutter button, wired up as a standard
gpiozero.Button using
.wait_for_press() to detect the click. The switch is a standard momentary switch, with two legs pulled off (so they don't show on the front) and then superglued to the frame.
The same approach is used for the tilt sensor — a mercury-type switch — which is orientated to be triggered when the Etch-A-Sketch is face-down. There is no way to detect whether the screen is clear, so we have to assume the user has some common sense.
You could detect a certain number of on/off states from the tilt switch to detect shaking, or add a separate shake sensor.
Status LEDs
There are 3 status LEDs on the back of the Etch-A-Sketch to give some feedback on what is currently happening. These are powered directly from the GPIO. As only a single LED is lit at any point only a single current-limiting resistor is needed.
The possible states are shown below along with what is required to move past this status (in the code) —
- stopped — red on; waiting to be tipped over to clear the screen (until tilt switch)
- ready — green on; waiting to take a picture (until shutter press)
- processing — yellow on; we have an image and it’s being processed
- drawing — yellow pulsing; we are drawing the image
Once the drawing completes the status resets back to stopped with the red light on. At this point you can tip the Etch-A-Sketch over to clear the screen and start again.
The camera
The Etch-A-Sketch camera itself is just a standard Raspberry Pi camera module with a Pi Zero cable interfaced using
picamera. To hold the camera in place there is a 3D printed mount which clips loosely to the top of the Pi Zero. The camera can sit in the small notch on top.
The fixture isn't particularly tight, but some soft glue is enough to keep the camera secure when shaking (and is easily removable).
It should be possible to adjust the 3D printed part to make this a tighter fit.
The code & command-line tools
The camera code
main.py is shown below, containing the main execution flow for the camera, the status LED control and inputs from the shutter and tilt switch. The camera starts up in Complete state with the red LED illuminated and must be turned over and shaken before taking the first shot (it assumes there may already be a photo present).
import time from gpiozero import Button, LED, PWMLED import graph, plotter, camera red = LED(21) yellow = PWMLED(20) green = LED(16) shutter = Button(25) tilt = Button(12) # Status light shortcuts. def status_ready(): red.off() yellow.off() green.on() def status_complete(): green.off() yellow.off() red.on() def status_processing(): green.off() red.off() yellow.on() def status_drawing(): green.off() red.off() yellow.pulse() def main(): while True: status_complete() # Wait for flip & shake. tilt.wait_for_press() time.sleep(1) # Setup the camera interface. camera.prepare() status_ready() # Wait for shutter, then take picture. shutter.wait_for_press() status_processing() image = camera.take_photo() image = camera.process_image(image) # Process the image & generate plotter moves. moves = graph.generate_moves(image) # Draw the paths. status_drawing() plotter.enqueue(moves) # Complete. if __name__ == "__main__": main()
The camera is started up using
cron at reboot using the following line.
@reboot python3 /home/pi/etchasnap/main.py
Once started the camera will continue to run in an infinite loop, waiting for the screen to clear, waiting for the shutter, taking a picture, drawing it, waiting for the screen to clear, and so on. To turn the camera off the power to the Raspberry Pi (and optionally the steppers) can be cut.
What's next
Now we have an assembled Etch-A-Snap and the outline control code, we can move on to the code to take and process the photos to get ready to draw.
| https://www.mfitzp.com/invent/etch-a-snap--build/ | CC-MAIN-2021-43 | refinedweb | 2,032 | 71.04 |
Structuring real-world code using monadic abstractions
In this article I present a simple relatively boilerplate-free approach to structuring Scala code using monadic abstractions. I use cats but it can be done using any other library, like Scalaz.
Introduction
Presented approach is nothing new but just well-known patterns used in a cohesive way. In a sense it tries to compete with free monads or more modern Eff monad without going crazy too much. Those techniques are much more complicated and consequently more powerful, but they require a lot of boilerplate (even when using some libraries born to reduce it, like Freek or Liberator for free monads) and refactoring.
On the other hand, monadic abstractions approach in a sense is a less radical step forward to pure functional programming. It's much simpler and can be more easily applied to existing code that uses
scala.concurrent.Futures directly, without re-writing it from scratch.
Step by step guide by example
So, let's pretend we're writing a microservice that uses Scala futures for asynchronicity, Slick 3 for relational database access, and something like
akka-http to make REST calls to other microservices. First thing we do is...
Abstracting interfaces
Let's say we have a service layer and a repository layer. The first trick is to abstract away from concrete "monad" used as a methods result types wrapper, e.g.
Future or
DBIO, in interfaces:
Currently dominant style is to use
scala.concurrent.Future as
M in service trait and
scala.concurrent.Future or
DBIO as
M in repository traits. There are two downsides with such approach:
- using futures in repositories would force to evaluate your
DBIOactions too early (before leaving repository layer) effectively disallowing a transaction to span across multiple repository calls;
- using
DBIOas
Min repository interfaces would leak repository layer implementation details to upper layers, adding `Slick* stuff to services classpath.
So, by abstracting it out, we want to be able to run cross-repository calls transactions and fix the implementation details leak. And we don't really want to have Slick classes in service layer auto-complete!
We use higher order type parameter
M, saying that we return a "container" of something, but we're not explicit about its type. It can be Scala
Future, Monix
Task, Slick's
DBIO, cats'
Eval, or even
Function0!
Implementing repositories
Next we implement repositories by using
DBIO to substitute abstract
Ms:
Implementation details aren't relevant here and therefore omitted for brevity. More interesting is how we implement the service.
Implementing services
Notice that service implementation should not depend on repository implementation but only on interfaces. We can say that each layer (e.g. repository, service, etc) has at least two parts, and consequently build artifacts: the
api part and one or more
impl parts. So each layer above only depends on
api artifact of a layer below. Explicitly:
- service
apidoesn't depend on repository artifacts, cause it would make them available to layers above - something we what to disallow;
- service
impldepends on repository
api(not
impl!) so that repository implementation could be swapped without changing service code (ideally);
- there is an app layer on the very top, where all the wiring takes place, it depends on both service and repository layers
implartifacts (and
apis transitively) and provides a concrete repository layer implementation to the service layer.
But how the service code looks then? Here comes the most interesting part:
Let's iterate it one thing at a time.
Still generic
M[_]
Notice that service code is still generic in the sense that it's detached from a concrete monad implementation, we're still using
M[_]. And it's a good sign!
DbEffect type parameter
Additionally, our service implementation declares a type parameter to abstract over a concrete "monad" (or "effect", or "container") of the repository layer. We could call it just
D but I like the
DbEffect name as more self-explanatory here. We also parameterize our repositories dependencies with
DbEffect effectively saying that we depend on repositories that produce values within a generic container called
DbEffect - and that's all we know about them so far, but... stay tuned!
And yes - we're using constructor parameters for dependency injection.
evalDb argument
We've also got a fancy looking
evalDb: DbEffect ~> M constructor parameter. It can be written more explicitly like this:
In cats' code it's just a type alias for
FunctionK trait:
This thing is called a natural transformation and all it can do is to convert a value of one generic type
F[_] to another generic type
G[_]. And that's exactly what we need to "run" our underlying
DbEffects: whatever monad service code uses for its results, we want to transform repository effects into it. For
DBIO actions, when we pass
evalDb implementation to our service in the app layer, we are going to execute them transactionally and get back futures (if we decide to use them as service's
M implementation).
There is one aspect of
DbEffect and
M that gives compile-time guarantee of not having long-running transactions (what is probably a good idea). If you decide to do something like making REST call when transaction is running, you'll get a result of type
DbEffect[M[DbEffect[T]]]. And you won't be able to escape out of it. Strictly speaking, there is a typeclass called
Traverse that brings the ability to "traverse" one context with another, i.e. go from
F[G[T]] to
G[F[T]], and since we can't have it for
DbEffect and
M (at least when
DbEffect is
DBIO and
M is some asynchronous boundary like
Future), - we cannot traverse it!
Now to the...
Implicit parameters
To recap, we require the following implicits when creating the service:
In case you know what is a
Monad (e.g. from my previous article) but never saw the
MonadError, you can think about it like a
Monad with built-in error handling. You can use standard Scala
Future methods intuition, like
Future.failed,
Future.recover, or
Future.recoverWith. They allow to create a failed value and to recover from a failure. Same for the
MonadError typeclass but in much more abstract purely functional setting.
Why we require
MonadError for
M but
Monad for
DbEffect? It's just a rule of least power: I'm not going to use error handling for
DbEffect values in the method implementation so I just stick with the
Monad instance for
DbEffect but it could definitely be
MonadError[DbEffect, Throwable] as well - no trickery here!
So, by having this implicit parameters we declare that:
Mis a monad (with error handling) and consequently we can
map/
flatMap/
recovervalues of type
M- same way as one would use
Futures in for comprehension;
DbEffectis a monad, so we can chain
DbEffectvalues as well, before transforming them to
Musing
evalDbnatural transformation (you can think about it like about transaction).
Wiring it all together
Before actually implementing our service method, let's see how the components can be wired in the top app level. Here are some common Slick helpers to be used:
I won't go into much detail here, this is something similar to what many teams come up with when using Slick. The most important thing is to be able to define
~> instance that can evaluate
DBIO values. Notice that we're using same "abstracting interfaces" approach for shared common code as for the components above.
Now, wiring can look similar to this:
For simplicity I'm not going to define web layer, but it might use
akka-http and require services dependencies as
securityService: SecurityService[Future]-like constructor parameters (or even
securityService: SecurityService[M] if you decide to generify your controllers/resources/whatever-you-call-it as well, though there's less benefit from doing that in comparison to service code).
But what about monad instances?
An astute reader might notice that something is missing when creating the
SecurityServiceGenericImpl above - namely the implicit
Monad and
MonadError instances:
MonadError[Future];
Monad[DBIO].
The first is defined in cats and can be put in scope by adding
import cats.implicits._ import.
As for the second one, there is a project on Github called slick-cats that defines
MonadError and some other instances for
DBIO. They can be brought in scope by introducing a dependency on
slick-cats and adding
import com.rms.miu.slickcats.DBIOInstances._ import statement.
Finally we're ready to implement our example service method.
Service method implementation
Method logic is following:
- get user's password last changed date;
- independently, get user's password validity period setting;
- if password is expired, call some other microservice to send a notification email to the user;
- if an error occurs during the notification sending, recover error to a specific
SendNotificationResultADT value.
Even in this simplified example we have multiple things to consider, namely:
- we want to make first two calls independently on each other, i.e. no
flatMaping;
- execute both calls in a single transaction (it might be more important in more real-world scenario than here);
- return a
ErrorWhileSendingADT value if an error occurs during notification sending (error handling);
- though we imply that repository calls cannot fail in our example, we might want to provide
MonadErrorinstance for
DbEffectand handle DB errors gracefully (not covered here).
Here is the implementation split to several methods:
Steps 1 and 2 are implemented in
isPasswordExpired method. Notice that it doesn't leave
DbEffect monad yet, effectively causing both repository calls to execute in a single transaction, when run later by
evalDb. This method uses applicative builder syntax to leverage the fact that
Monad is also an
Applicative functor. In a nutshell,
Applicative is a less powerful abstraction that allows to, in this case, apply a function
(A, B) => C to
F[A] and
F[B] to get
F[C]. First, we use the fact that
DbEffect is an
Applicative, then the fact that
Option is also an
Applicative (typeclass instance for
Applicative[Option] provided by cats).
The main difference between
Monad and
Applicative is that the former allows for computations chaining making one computation to depend on another, while the latter doesn't allow chaining and considers computations simultaneously, even with ability to run them in parallel when looking at how
Applicative[Future] instance works. See cats documentation for more information.
In
sendNotificationIfPasswordExpired method we
evalDb the
isPasswordExpired method result and, since it has
DbEffect[Option[Boolean]] type, we can apply
OptionT monad transformer to it. Monad transformers (hence the
T in
OptionT) allow to stack one monad on top of another and work with them without nesting. Again, google for cats monads transformers if needed. In
semiflatMap method lambda we're already in
M "domain" and we call
sendExpiredPasswordEmail method, mapping it to
NotificationSent ADT on success and recovering to
ErrorWhileSending ADT on an error. In the end of the method, to get out of
OptionT transformer, we call
getOrElse method and return
UserNotFound ADT if we were unable to get user data out of our repositories (any of two calls).
sendExpiredPasswordEmail method implementation is supposed to make email sender microservice call, here we pretend it does it successfully and use
pure monadic operation to wrap
Unit value into monadic context.
Observations
As you can see, we are very abstract about what monads we're using in the service implementation. This allows to decouple application layers and change our monads without touching the service code. If one day you decide to go for Monix'
Task instead of Scala
Future, you won't need to change the service implementation at all. Just provide the required
Monad/
MonadError instances (and yes - Monix does have them!) and all' keep working.
Applications to unit testing
Last thing to touch upon is how this approach affects unit testing. Instead of dealing with asynchronous results in unit tests (even though ScalaTest has a decent support for them), you can instantiate the service by substituting
cats.Eval as your
M and
DbEffect monads.
Notice that cats have
MonadError instance for
Eval in the master branch at the moment of writing, but it's not released yet.
Using ScalaTest and Mockito, you can do something like this:
I use
FunctionK.id[Eval] that's just a "higher order identity"(i.e. like Scala
identity but applied to
M[_]) to "evaluate"
DbEffect values. So, same
Eval monad for both service and repository layers in tests.
It's worth saying that this test reveals another problem with our implementation: invoking side-effective methods like
LocalDateTime.now() in the service code. Instead, some date/time provider component should be passed to the service constructor to make the code more purely functional and consequently testable.
Wrapping blocking APIs
To wrap blocking APIs - those that return immediate values and do IO during their computation - one can define a transformation from
Eval to whatever monad you use, e.g.
Future:
And then use it to transform blocking calls into
Ms:
Conclusion
I hope you came away with something applicable to the real-world from the presented monadic approach to abstract and structure (are these two synonyms in a sense?) the code. You can imagine having more "effects" like
DbEffect in your code and that's completely fine if you have required natural transformations machinery for them in place.
The thing I like the most about this approach is that it is simple. If you looked at free monads or Eff, you know what I mean. It doesn't force you to rewrite your code from scratch and can be adapted iteratively: first you apply it to the commons code, like
DatabaseSupport in the above examples, then to app's bottom layers, then move higher to services, and so on.
Next logical step to investigate is how to abstract streaming - very important technique nowadays. It would be cumbersome to have akka-http, or Monix, or Reactive Streams classes along with
M and
DbEffect. But that's the topic of another article. | http://blog.alexander-semenov.com/monadic-abstraction | CC-MAIN-2017-47 | refinedweb | 2,336 | 50.67 |
How could I import multiple GPX workout files?
I exported the GPX files from runkeeper and like to move them to EndMondo
How could I import multiple GPX workout files?
This topic is no longer open for comments or replies.
- Ture (Community Manager) April 24, 2012 19:56Hi, you can import multiple .gpx and .tcx files by going to Workouts and then follow these steps:
1. Import Workout
2. Import from file
3. Click Browse - and select the file you want to import
4. Next
When you see the workout list with name, date, distance and duration of the workout, you click Back and follow step 3 and 4 until you have imported all files. Once you have imported all the files click Save and they will saved to your profile.
Cheers, TureComment
- Hi Ture,
This solution isn't adequate.I'd like to import all of my history from RunKeeper application and I have 10's of files to import.The solution you provided is very tedious, isn't there something quicker, like bulk import?
Roman
- Thanks Ture,
Looks like its still a bit of a pain if many (hundreds of) activities are to be imported. Wonder if it can be automated with something like iMacros or handled on your end.
- Ture (Community Manager) May 03, 2012 14:55Hi guys, at the moment we unfortunately don't have bulk, mass or automated import. I know that would be great if you plan to move hundres of workouts.
Sorry, don't have better news. Cheers, Ture
- Sorry but it is what I call loose the timing...
Many users are moving from a plataform that does not support WP7 and you can ́t bulk import...
As a developer, I can say that if you have the process to import one file, few hours latter you can bulk import. It is called "while":
while [you have files]
import [the current file]
end while | https://getsatisfaction.com/endomondo/topics/how_could_i_import_multiple_gpx_workout_files?page=1 | CC-MAIN-2014-10 | refinedweb | 321 | 74.08 |
.
def thingy(hello):
if hello:
return ""
return "EPIC FAIL"
compare = lambda x,y: x == y
a = [1,2,3]
b = [1,5,3]
for i in [0,1,2]:
print str(i) + thingy(compare(a[i],b[i]))
if v is True:
or
if v == True:
or the like is a kind of not nice or confusing way of testing. The "if" expects the boolean condition (the boolean result of an expression). Put the constant values instead of v and you can see:
if True is True:
...
if False is True:
...
if True == True:
...
if False == True:
Or you can go to the verbal extreme:
if (v does not hold) does hold: # this is not abou the syntax which is not acceptable by Python
1ce shows the way how it should be done. In my opinion, the key point to fix the code also is to replace the "hello" identifier to something more meaningfull.
I think you are not real clear on what lambda functions really are. They are "anonymous" functions which the "lambda" keyword allows you to define without ever giving it a name. The anonymous function thusly defined will always accept as a parameter the variable (or comma-separated list of variables) on the left of the colon, and will always return as a value the expression on the right side of the colon. Thus you can think of this expression:
myfunc = lambda x: x == 2
as being equivalent to
def anonymous(x):
return x == 2
myfunc = anonymous
This creates a function named "myfunc" that accepts one parameter and tests if that parameter is 2. Note that no function called "anonymous" is ever actually created - but you can think of what's happening as if it was.
At this point, if you want to evaluate this function, you would do so by calling myfunc and passing it a parameter:
x = 1
if (myfunc(x)):
print "X is 2"
else
print "X is not 2"
(prints "X is not 2")
So in your original example, your lambda expression defines a function that takes one parameter. As a result, strictly speaking, the direct answer to your original question, "how do I test if hello is true within the function", is this: you must pass hello a single parameter for it to evaluate. Thus in your original sample code, strictly speaking you would need to change it to:
def thingy(hello):
if hello('SOME PARAMETER GOES HERE'):
return []
return "EPIC FAIL"
However, "thingy's" problems go deeper that that, because as defined, you don't have any parameter to pass to hello inside thingy. This is what led to 1ce's solution where he defines a lambda with 2 parameters; then he actually evaluates that lambda prior to calling thingy, which in his version does nothing but test the result, circumventing the issue of what parameters to pass to "hello" from inside "thingy".
This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.
>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> a == b
True
>>> (lambda a: a == b)
<function <lambda> at 0x000000000203D828>
>>> bool(lambda a: a == b)
True
>>> b = []
>>> bool(lambda a: a == b)
True
The bool() function returns the boolean value of whatever object is passed in. It returns the same value that would be evaluated in a boolean context. As the doc (above says), the function object does not fall into category of things evaluated as False. It is always evaluated as True. However, the operator "is" does not introduce a boolean context. It compares the object that represents the lambda function with the object that represents the constant True.
This way, 1ce changed the testing to use the boolean context evaluation (always True), Richard shown that using "hello is True" will evaluate always to False for the lambda function.
def thingy( hello):
left = input("Enter left side of comparison: ")
right = input("Enter right side of comparison: ")
if hello( left, right):
print "They are equal."
else:
print "They are not equal"
>>> thingy( lambda a,b: a == b)
Enter left side of comparison: [1,2,3]
Enter right side of comparison: [1,2,3]
They are equal
>>> thingy( lambda a,b: a==b)
Enter left side of comparison: "hello"
Enter right side of comparison: "world"
They are not equal
Some notes:
The "input" statement expects a Java object, so strings must be entered with quotes around them, otherwise you'll get an exception. For clarity I didn't put exception handling in.
Also note that in the lambda expression, there is no need for the program to define "a" and "b" prior to running thingy, as you had attempted to do in your original sample. Those are purely syntactical placeholders used in the definition of the anonymous function. | https://www.experts-exchange.com/questions/26482141/Python-Lambda-functions.html | CC-MAIN-2018-26 | refinedweb | 802 | 53.14 |
Introduction to Multi-Tenant Architecture
The following code listing shows a page sending an email after a user registers for the site. Typically upon registration, some sort of email is sent to give that sense of confirmation or welcome message to the new user. If I had multiple tenants, I couldn't store the email settings in the Web.config because each site may want a different subject, body, and so forth. And, you definitely do not want to hard code for each case!!
namespace MultiTenantSite { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void CreateUserWizardControl_CreatedUser(object sender, EventArgs e) { // Create the Mail Message from the Cached App Settings // For the Tenant MailMessage confirmEmail = new MailMessage() { From = new MailAddress(new Data.AppSettings() ["Site.Registration.Email.From"]), Subject = new Data.AppSettings() ["Site.Reigstration.Email.Subject"], Body = new Data.AppSettings() ["Site.Registration.Email.Body"], }; // Create the SMTP Client and Send the Message SmtpClient emailSender = new SmtpClient("Some SMTP Host"); emailSender.Send(confirmEmail); } } }
Using a Content Management System
The next component to a multi-tenant application, a Content Management System (CMS), is optional but will help to display content dynamically on-demand for tenants that use the site. Designing a CMS can be an article within itself. Really, in this situation, you would want to use the CMS system to create content in a web-part format. You then can use these web parts interchangeably and on demand as you design your pages for a tenant. Typically, if the content is static with only different app settings and different App Themes, a CMS may not be needed.
To illustrate what I am talking about, assume I have a CMS system for a Multi-Tenant site where a database drives the system and stores web parts that are created are stored through some web part manager on the site. Now, in the actual solution, I have a footer control that is rendered on the master page, and on the footer I have three links: FAQ, Contact Us, and About. Each tenant that is using this base website may have different text that will need to be displayed for each link. With a Multi-Tenant site powered by CMS, I could create web parts for each different link for each tenant and set the PostBackUrl Property of each link button through the app settings.
Footer Markup
<table width="100%"> <tr> <td align="center"> <asp:LinkButton </asp:LinkButton> </td> <td align="center"> <asp:LinkButton </asp:LinkButton> </td> <td align="center"><asp:LinkButton </asp:LinkButton> </td> </tr> </table>
Code Behind (Setup Links)
public partial class Footer : System.Web.UI.UserControl { protected void Page_Load(object sender, EventArgs e) { // Set the Post Back URLs for each link lnContactUs.PostBackUrl = GetRelativeCmsUrl("Site.Link.ContactUs"); lnFAQ.PostBackUrl = GetRelativeCmsUrl("Site.Link.FAQ"); } public static string GetRelativeCmsUrl(string configKeyName) { // return link to the CMS Page that Handles Web Parts, // Retrieve the ID of the Web Part from the // Cached App Settings return (String.Format("~/cms/page.aspx?ContentID={0}", new Data.AppSettings()[configKeyName])); } }
IIS Setup
The last piece to successfully implement a Multi-Tenant Web Site is setting up IIS to handle each website. This is a relatively simple concept, especially if you have already set up a basic ASP.NET website in IIS. To make this a little more complex and really demonstrate where Multi-Tenant architecture is handy, assume your server has only one public facing IP to register a website under. First, you will need to create a new website for each tenant. One problem with this: You need to assign an IP to each site but you only have one. A solution to this is to use host headers for each site, map each host header to the single IP, and then register the host headers with your respective DNS server.<< | https://www.developer.com/design/article.php/10925_3801931_3/Introduction-to-Multi-Tenant-Architecture.htm | CC-MAIN-2018-39 | refinedweb | 640 | 51.99 |
We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hello,
I’m trying to transfer images over net between Processing-sketches on different computers. I’ve been making making some small test sketches to test this out. I’m using built-in java library to convert PImage to JPEG-encoded byte-arrays (to keep size down) which I in turn send over the net.
However, I’ve never really done much networking programming before and I’m having trouble getting this to work reliably. Generally my problem is that very often I just get a part of the image, but not the whole thing.
I am not really looking for code help per se, just what approach I should take. Do I need to send the image in parts and then stitch it together (or the corresponding bytes together)? Will I then need some way to make sure the server know it received a whole part? Or should I just read from the buffer in a different way? Are there any ready-made solutions like libraries that can deal with this?
And generally my goal here is simply to transfer a image from one computer to another, am I going about this in the easiest and smartest way? Would be easier to just bounce this stuff off a web server somewhere?
Any pointers here would be hugely appreciated.
Here is my server code:
import processing.net.*; Server server; JPGEncoder jpg; PImage img; void setup() { size(1400, 800); jpg = new JPGEncoder(); // Start a server at port 5204 server = new Server(this, 5204); img = createImage(100, 100, RGB); println("Starting server"); } void draw() { checkForIncomingImage(); image(img, 0, 0); } void checkForIncomingImage() { Client nextClient = server.available(); if (nextClient != null) { println("Client is available, reading bytes"); byte[] byteBuffer = nextClient.readBytes(); if (byteBuffer.length > 0) { println("Received data. Trying to decode."); try { img = jpg.decode(byteBuffer); } catch (IOException e) { println("IOException"); } catch (NullPointerException e) { println("Probs incomplete image"); } catch (ArrayIndexOutOfBoundsException e) { println("Probs also incomplete image (Out of Bounds)"); } } else { println("Byte amount not above 0"); } } }
And here is my client code:
import processing.net.*; import processing.video.*; Client client; Capture cam; JPGEncoder jpg; void setup() { jpg = new JPGEncoder(); cam = new Capture(this, Capture.list()[1]); cam.start(); // String server = "192.168.1.15"; String server = "127.0.0.1"; client = new Client(this, server, 5204); background(255); println("Starting client"); } void draw() { } void keyTyped() { if (cam.available()) { println("Cam available. Going to read"); cam.read(); try { println("Getting image to memory"); PImage img = cam.get(); img.resize(500, 0); println("Encoding"); byte[] encoded = jpg.encode(img, 0.1F); println("Writing to server"); client.write(encoded); } catch (IOException e) { // Ignore failure to encode println("IOException"); } } }
You can also view the code at GitHub here:
Example of what an incomplete transfer of image looks like:
Answers
I would start by printing the number of bytes sent and received, see if there's a discrepancy
I guess the data input stream is buffered and hence not the entire set of bytes is available.
Have you found a better solution?
I stumbled upon the same problem. In order to work I have downgraded the framerate and the resolution of the sent image.
I would like to be able to send larger images in a faster pace.
If you improved your solution, let me know!
Hello everyone,
@TorbjornLunde you almost had it. Let me point out the problems:
I have not tested it, but I think the problem with the code you posted was that when you read with the server, the image may not have arrived entirely (there are still bytes to come).
I saw your code on github () and spoted the only error you had: first you transmit the length of the array of bytes that comprises the image; then you transmit the array of bytes. But the length of the byte array is an int! An int has 32 bits in Java. So, an int can be decomposed into 4 bytes, but not 2! The only way to decompose it in two bytes is to make sure that the length of the byte array is less than 2^16. For that reason, you could send complete images only if they were very compressed.
The solution can be found, together with a finite-state machine that manages the server and the client (I do not know if this is better or worse for efficiency) in:
However, the key is:
Finally, I will mention @leopessanha because he seemed interested, and I do not know if he would receive a notification otherwise.
P.D.: does anyone knows how to format properly the code after "from bytes to int"? I can not use "< pre" and "< /pre>" without something disappearing...
Rather than using
<pre>, just highlight your code and hit CTRL+O. ;;)
If you'd still prefer
<pre>, replace
<w/
<. :\">
Thanks @GoToLoop. I did not like that the line was so long with CTRL+O...
You can remove most of those parentheses to make the whole statement shorter: :ar!
imageLength = lengthBytes[3] << 030 | (lengthBytes[2] & 0xff) << 020 | (lengthBytes[1] & 0xff) << 010 | lengthBytes[0] & 0xff;
And even place them in separate lines: :bz
And if we assume that each indexed value of lengthBytes[] is never greater than
255(0xff), we can remove all
& 0xffand parentheses too: \m/
Thank you for answering! I was meaning to get back to this (and post) after I'd finish my class on OS and networks but I never got around to it. Thank you anyway!
@TorbjornLunde, thank you for your JPGEncoder class. You did all the hard work.
@GoToLoop, I'm afraid that part of your code is incorrect:
The use you made of octatal literals (
010,
020,
030, ...) is correct, but I think it could cause confusion. I'm not familiar with these expressions, and I do think many others either. However, it is correct.
It is correct to know the operators precedence and save some parentheses with it, but I often doubt the exact order, so I prefer to use parentheses to clarify the expression. Even so, your first and second expressions are correct.
Your third expression is not correct. The variable
lengthBytesis a byte array. It contains bytes. When you apply the left shift operator (
<<), the result is still a byte. Then, after applying the bitwise inclusive ORs (
|) you get a byte. The
& 0xFFmask is necessary to transform the byte into an int, so that the left shift can be done correctly.
Please, for the next time consider testing the code before posting. It could have saved the time I inverted writing this, or in case I had not responded, the time that others could have lost using that code, then debug...
intis auto-converted to
intwhen used as operands. @-)
lengthBytes[3] << 030, the value stored in
lengthBytes[3]is converted to
intbefore being used as the 1st operand of the operator
<<. :-B
You are right. That statement was incorrect. Still, check the following code:
I already had to test your code twice ...
Hello again @pbp! B-)
As a condition to this shortcut:
I've stated: X_X
Actually I shoulda stated instead: within the range from
0to
255. :-\"
I confess I haven't really paid much attention that your lengthBytes[] was of datatype
byte[].
I was assuming it'd much likely be of
int[]instead. 3:-O
Java's datatype
byteis very problematic, b/c its Byte.MAX_VALUE is
127, not
255: :-O
println(Byte.MAX_VALUE); // 127
Therefore,
(byte) 0x80isn't
128, but
-128:
println((byte) 0x80); // -128
And
(byte) 0xffisn't
255, but
-1:
println((byte) 0xff); // -1
Funnily, applying
& 0xffto a
bytevalue, removes its negative form: :ar!
println((byte) 0x80 & 0xff); // 128
If you change
byte[]to
short[],
char[]or
int[], the negative glitch goes away! O:-)
Here's another recent post w/ that problematic
byteconversion. This time to String: =;
@GoToLoop, certainly, "Java's datatype
byteis problematic", but it is the only 8-bit datatype that Java has. Communication methods need to use that datatype. I have had some problems trying to send data between sketches, and also trying to send data between Arduino and Processing. You came to help, I'm sorry if I was a bit harsh in my response. I probably should have pointed out your error in a private message, but I guess we both learned something from this. Again, thanks for your help.
Never mind that at all, @pbp. Always ready for a tech debate! :-j
I wanna learn as much as I wanna teach! O:-) | https://forum.processing.org/two/discussion/20667/reliably-send-images-over-net | CC-MAIN-2019-35 | refinedweb | 1,430 | 65.83 |
Ok so in what I did was I converted a fairly big API (Like one which has a lot of text) into JSON. However, only a certain part of the API is actually being converted. Although I do suspect that the API webpage might be too big to be converted, it isn’t ideal since it just so happens that the part of the API that I need hasn’t been converted. Would be ideal to know if there’s something I could do to convert that certain part I need
What makes you think not everything is parsed?
It’s not that it makes me think that, when I print it, that specific part isn’t there. Alongside that when I try to use the key’s inside of the not parsed things I get a Keyerror message.
There’s a certain size that can be displayed in console, the rest will be cut off. Try saving it to file to make sure.
To get to a specific key inside of the parsed JSON you may need to go through other keys, depending how structured is the actual JSON.
Yeah, I do go through other keys and it still manages to find a KeyError.
So I’m pretty confused. Also if it helps, it’s a chunk of the start that’s cut off. Not the end.
Would you mind updating code on replit? It currently shows only trying to load both keys from the top level of dictionary, what’s not a structure of that JSON.
Yes, the beginning is cut off in the console.
What do you mean by trying to load both keys from the top level?
If something isn’t updated, this is the code.
import requests
response = requests.get(‘’)
lolerz = response.json()
lol = lolerz[‘Bedwars’]
winstreak = lolerz[‘winstreak’]
print(winstreak.text)
Taking as an example:
dictionary = {'A': {'B': {'C': 3, 'D': 4}}}
To get value of
'C' it’s needed to get to the appropriate dictionary:
dictionary['A']['B']['C'] # 3 dictionary['C'] # KeyError
Situation here is similar, JSON is can have multiple nested dictionaries or lists.
I already know that and indeed have done it. In my dictionary, ‘winstreak’ (The key I want to access) is inside of ‘Bedwars’.
So what’s the problem?
But where in the whole JSON is the
'Bedwars'? It is nested deeper inside of the structure, the most outer dictionary doesn’t have
'Bedwars' key.
Oh… well, I’m really dumb… sorry for that. And thanks for your help!
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed. | https://forum.freecodecamp.org/t/not-everything-is-being-parsed-into-json/475773 | CC-MAIN-2022-40 | refinedweb | 438 | 74.9 |
On 09/15/2010 12:13 PM, Andrea Arcangeli wrote:
Subject: allow more than 1T in KVM x86 guest From: Andrea Arcangeli<address@hidden> When host supports 48 bits of physical address reflect that in the guest cpuid to allow the guest to use more than 1TB of RAM. The migration code should probably be updated accordingly checking if the size of the guest ram is bigger than the migration target cpuid 0x80000008 limit and failing migration in that case. (not a real practical issue, I don't see many people migrating>1T guests yet :) The comment below refers to a 42 bit limit on exec.c, but I didn't identify what the comment refers to yet. At least now guest should be able to use 4TB.
target-i386/cpu.h #ifdef TARGET_X86_64 #define TARGET_PHYS_ADDR_SPACE_BITS 52 /* ??? This is really 48 bits, sign-extended, but the only thing accessible to userland with bit 48 set is the VSYSCALL, and that is handled via other mechanisms. */ #define TARGET_VIRT_ADDR_SPACE_BITS 47 #else #define TARGET_PHYS_ADDR_SPACE_BITS 36 #define TARGET_VIRT_ADDR_SPACE_BITS 32 #endif The macros are then used in exec.c Regards, Anthony Liguori
Signed-off-by: Andrea Arcangeli<address@hidden> --- diff --git a/target-i386/cpuid.c b/target-i386/cpuid.c index d63fdcb..462e709 100644 --- a/target-i386/cpuid.c +++ b/target-i386/cpuid.c @@ -1189,6 +1189,12 @@ void cpu_x86_cpuid(CPUX86State *env, uint32_t index, uint32_t count, /* 64 bit processor */ /* XXX: The physical address space is limited to 42 bits in exec.c. */ *eax = 0x00003028; /* 48 bits virtual, 40 bits physical */ + if (kvm_enabled()) { + uint32_t _eax; + host_cpuid(0x80000000, 0,&_eax, NULL, NULL, NULL); + if (_eax>= 0x80000008) + host_cpuid(0x80000008, 0, eax, NULL, NULL, NULL); + } } else { if (env->cpuid_features& CPUID_PSE36) *eax = 0x00000024; /* 36 bits physical */ | http://lists.gnu.org/archive/html/qemu-devel/2010-09/msg01178.html | CC-MAIN-2014-35 | refinedweb | 287 | 60.85 |
hi
i send me creating jar file in java
through command promt & jcreater.
u mail me plzzz
hii
u send me code for creating jar file in java
throug command prompt & jcreater.plz mail me
What are the arguments that needs to be passed from the command prompt to create the jar file.
Post your Comment
jar file - Java Beginners
jar file jar file When creating a jar file it requires a manifest... an application packaged as a JAR file (requires the Main-class manifest header)java -jar... options in jar file. What is Jar File? JAR files are packaged in the zip
???
The given code creates a jar file using java.
import java.io.*;
import...();
System.out.println("Jar File is created successfully.");
} catch (Exception ex..
quotion on .jar
quotion on .jar in realtime where we use .jar class files.
A Jar file combines several classes into a single archive file. Basically,library classes are stored in the jar file.
For more information,please go through
Creating JAR File - Java Beginners
Creating JAR File Respected Sir,
I would like you to please help me, in letting me know, as to how to create JAR file from my JAVA source...();
}
out.close();
fout.close();
System.out.println("Jar File
jar File creation - Swing AWT
jar File creation I am creating my swing applications.
How can i... in java but we can create executable file in java through .jar file..
how can i convert my java file to jar file?
Help me
Creating JAR File - Java Beginners
Creating JAR File Respected Sir,
Thankyou very much for your..., which says, Failed to load Main-Class manifest attribute from H:\Stuff\NIIT\Java... to change the contents of my manifest file. I read somewhere regarding i have to
for creating a JAR file is:
jar cf jar-file input-file(s)
* The c option...Only change jar file icon Dear Friend
I know that how to create a jar file but i don't know How to change jar file Icon.
I can change .exe file
Java Jar File
Java Jar File
In Java, JAR (Java ARchive) is a
platform-independent file format that allows you... for reading and writing
the JAR (Java ARchive) file format, which is based
creating jar file in javadevesh kumar singh April 21, 2011 at 11:36 AM
hi i send me creating jar file in java through command promt & jcreater. u mail me plzzz
creating jar file in javadevesh kumar singh April 21, 2011 at 11:38 AM
hii u send me code for creating jar file in java throug command prompt & jcreater.plz mail me
creating a jar file in javabalaji May 25, 2011 at 2:36 PM
What are the arguments that needs to be passed from the command prompt to create the jar file.
Post your Comment | http://www.roseindia.net/discussion/18289-Creating-a-JAR-file-in-Java.html | CC-MAIN-2015-11 | refinedweb | 473 | 74.29 |
Summary: An explanation of transforms (python code stored in modules) in the Code Engine and how get a specific transform, get all of the transforms, or reset or remove a transform.
You can use the API. For more information about working with code modules, see Splitting your code into modules in the Code Engine documentation.
Note
Sub-modules should not exceed 10,000 lines of code.
You can start by getting the current code from the Code Engine with
api.get_code_engine_module(module_name='main'). Pass a module name if you want a specific module, otherwise it will return the main code block (which is also the code you view in the UI).
You can get all the modules defined in the system using
api.get_code_engine_code(). This returns a dictionary which reflects modules names and their content.
Deploy code to the Code Engine using
api.set_code_engine_code(modules)
"modules" is a python map of a module name (string) to code (string)
On success the function returns an HttpResponse object with status code 2XX.
On failure, an exception is raised.
Note that you can delete a module via
delete_code_engine_module(module_name).
Example:
import alooma ## Using API Key ## APIKEY = "<YOUR_API_KEY>" # get this from your Alooma admin ACCOUNTNAME = "<DEPLOYMENT NAME>" # Used to specify which deployment # to use if you have more than one api = alooma.Client(api_key=APIKEY, account_name=ACCOUNTNAME) # Define and submit a code module named 'submodule'. # this module contains a dict called 'transform_names' # and a method called 'transform_ft_to_mtr' my_submodule = {"submodule" : """transform_names = {'John': 'Jonathan', 'Bob': 'Robert', 'Rick': 'Richard'} def transform_ft_to_mtr(x): return x * 0.3048"""} api.set_code_engine_code(my_submodule) # Now edit the main code to use 'submodule' by importing it. # You can also perform this step via the Alooma UI # by editing the code in the Code Engine. my_main = {"main" : """ from ."""} api.set_code_engine_code(my_main)
As any good developer knows, you don't just go and deploy code without testing it! Learn more about how to test your Code Engine code using alooma.py.
Article is closed for comments. | https://support.alooma.com/hc/en-us/articles/360007193932 | CC-MAIN-2019-04 | refinedweb | 331 | 64.91 |
tag: Kickstarter: Through Triumph & Tragedy 50 Years Of The FDNY Pipes & Drums 2013-07-10T23:05:18-04:00 tag: 2013-07-10T23:05:18-04:00 2013-07-10T23:29:35-04:00 Documentary Premiere <p>The documentary premiere of Through <strong><em>Triumph & Tragedy - 50 Years of the F.D.N.Y. Pipes & Drums</em></strong> will premiere in New York City On October 12, 2013.</p> tag: 2013-07-10T21:58:01-04:00 2013-07-10T22:00:21-04:00 World Premiere Of Documentary <p>The F.D.N.Y. Emerald Society Pipes & Drums is proud to announce The Documentary Premiere of <i>Through Triumph & Tragedy - 50 Years Of The F.D.N.Y. Pipes & Drums</i>. The documentary screening will take place on October 12, 2013 at the Frank Sinatra School Of The Performing Arts/ Tony Bennett Concert Hall in Long Island City, Queens. Directly Following will be a Cocktail Reception at Studio Square which is one block away. <?xml:namespace prefix = o</p> <p>The details of the Event are as follows:</p> <p><b>DOCUMENTARY SCREENING</b>:</p> <p>The screening of the documentary will take place at the Tony Bennett Concert Hall. Doors open at 5:15pm and ceremony and screening starts promptly at 6:00p.m.Seating is limited.</p> <p>Here is the link to theater:</p> <p><a href="" target="_blank"><b></b></a></p> <p><b>COCKTAIL RECEPTION</b>:</p> <p>The cocktail reception will be held at Studio Square ½ block away from theater. Celebration will include 4 hour top shelf open bar, dinner buffet, live music and a performance by the F.D.N.Y. Emerald Society Pipes & Drums. There will be no assigned seating.</p> <p>Here is Link to Studio Square:</p> <p><a href="" target="_blank"><b></b></a></p> <p><b>TICKETS</b><b>: </b></p> <p>The event is $125.00 per person which includes both the screening and after party. Tickets will be sold online at the website below. There will be no assigned seating and tickets are limited. </p> <p>To Purchase Tickets Go To: </p> <p><a href="" target="_blank"><b></b></a></p> tag: 2012-12-23T20:19:48-05:00 2012-12-23T20:31:33-05:00 All Prizes Have Been Shipped! <p>Hello Supporters,<?xml:namespace prefix = o</p> <p>I just wanted to thank you once again for your support. I also want to thank everyone for their concern and well wishes for the members of the FDNY Pipes & Drums after Hurricane Sandy. We are slowly re-building and appreciate all the help and support we have received. </p> <p>I also want to let our supporters know that all prizes have been shipped (excluding the DVD of the Documentary.) If you did not receive your prize, please e-mail me via <a href="" target="_blank">kickstarter.com</a> or my e-mail <a href="" target="_blank">timgeraghty@yahoo.com</a> and I will personally make sure you receive your gifts.</p> <p>For those that will be receiving a DVD copy of the documentary, they will not be shipped until some time in 2013. Firstly, we cannot release copies of the documentary until we find out if it has been accepted into any film festivals. Secondly, the release of the film has been delayed due to Hurricane Sandy. I will keep you posted via <a href="" target="_blank">Kickstarter.com</a> and I thank you for your support.</p> <p>Have a Merry Christmas</p> <p>Timothy Geraghty</p> <p> </p> tag: 2012-11-08T20:31:01-05:00 2012-11-08T20:35:48-05:00 Hurricane Sandy <p>Hello Supporters,</p> <p>Parts of New York City has been devastated by Hurricane Sandy, the largest Hurricane that has ever made land fall in the United States. Over one thousand Firefighters have been effected by the Hurricane including myself and many more members of the pipe band. I live in Long Beach, New York and my town, including my house has been flooded. It will be months before I will be able to return. Members of the band have cancelled all engagements and are working around the clock, on duty and off, to help people that have been effected by the storm. The documentary has been placed on hold, but we are still trying to get out the prizes. Luckily all prizes were saved and are being stored at a UPS Store. UPS will now be packaging and shipping them ASAP. Keep all members of the Department who have been effected by the storm in your thoughts and prayers.</p> <p>Timothy Geraghty</p> <p>FDNY Pipes & Drums</p> <p><br> </p> tag: 2012-10-04T23:56:32-04:00 2012-10-05T00:55:08-04:00 Getting It Done! tag: 2012-06-20T10:51:58-04:00 2012-06-20T11:03:06-04:00 Thank You! We are Doing It! !</p><p> </p><p>Thank You From The Bottom of My Heart.</p><p> </p><p>Timothy Gergahty</p><p>FDNY Pipes & Drums</p> | http://www.kickstarter.com/projects/1139469356/through-triumph-and-tragedy-50-years-of-the-fdny-p/posts.atom | CC-MAIN-2013-48 | refinedweb | 852 | 73.27 |
version 1.0.24 released: 14 Jul 2020
Note: This release is not binary compatible with previous releases. It is source compatible.
- Tag: fixed XML namespace for attribute with empty namespace (fixes #278) (thanks to drizt72)
- PubSub::Event: add simple ctor (thanks to Daniel Kraft)
- PubSub::Manager: fixed subscription error case handling (thanks to Daniel Kraft)
- PubSub: fixed support for instant nodes
- RosterManager: fixed behavior if subscription attribute is absent in roster item
version 1.0.23 released: 08 Dec 2019
- fixed a memory leak in dns.cpp (thanks to Daniel Kraft)
- fixed session management/stream resumption (thanks to Michel Vedrine, François Ferreira-de-Sousa, Frédéric Rossi)
- MUCRoom::MUCUser: include reason if set
- ClientBase: fix honorThreadID (first noticed by Erik Johansson in 2010)
- TLSGnuTLS: disabled TLS 1.3 for now, as there are connection issues with it
version 1.0.22 released: 04 Jan 2019
- TLSOpenSSLBase: conditionally compile in TLS compression support only if available in OpenSSL (fixes #276) (thanks to Dominyk Tiller)
- TLSGNUTLS*Anon: fix GnuTLS test by explicitely requesting ANON key exchange algorithms (fixes #279) (thanks to elexis)
- TLSGNUTLSClient: fix server cert validation by adding gnutls_certificate_set_x509_system_trust() (fixes #280) (thanks to elexis)
- DNS: fix compilation on OpenBSD sparc64 (fixes #281) (thanks to Anthony Anjbe)
- Enable getaddrinfo by default (fixes #282) (thanks to Filip Moc)
version 1.0.21 released: 12 Jun 2018
- InBandBytestream: error handling corrected
- doc fix: CertInfo::date_from/to set correctly when using OpenSSL
version: ‘from’ and ‘initi):
version 1.0.7.1 released: 11 Oct 2013
- fixed/updated the win32 project files
version 1.0.7 released:)
version 1.0.6 released:
version 1.0.5 released: 02 Sep 2013
version 1.0.4 released:)
version 1.0.3 released:
version 1.0.2 released:()
version 1.0.1 released: ‘… | https://camaya.net/gloox/changelog/ | CC-MAIN-2020-34 | refinedweb | 294 | 54.12 |
Table Of Content
Which Platform Should You Choose for Developing Java Desktop Applications?
1- Introduction
In fact, there are some common questions with Java:
- What solution should I choose to programme a Desktop application?
- Is there any solution for programming a website whose interface is alike Desktop application's?
- Trong tài liệu này tôi sẽ trả lời tổng quan về câu hỏi trên đồng thời có các giải pháp giúp bạn làm được điều đó.
Desktop Application:
- This is a desktop application written in Java Swing:
Web Application:
- And this is a Web application whose interface is alike a Desktop application's, and it is written on Eclipse RAP:
-
2- Programming Java Desktop Application
- In fact, to programme a Desktop application you have 2 choices:
- Use Swing - is a integrated library available on JDK and able to run on every different operating systems (Window, Unix, Mac OS,..)
- Use SWT - is a library for programming Desktop applications and is developed by IBM. It is able to run on every different operating systems (Window, Unix, Mac OS,..)
- This is an image of a Desktop application written with SWT and run on different operating systems.
- This is an image of a Desktop application written with Swing. With a default "Look And Feel", it seems foolish. In programme, you can choose another L-A-F to get an interface similar with Windows or Linux if you want.
2.1- Swing
- AWT (Abstract Window Toolkit) - is a library package developed for Desktop programme available in JDK. However, regrettably, it does not work as well as expected on different operating systems. This is the reason why Swing was born and replaced AWT in order to ensure that it runs well on different operating systems.
- Swing builds graphical interface totally by Java and runs on every operating system. It does not replace AWT, but inherits from AWT instead. This is its weakness that makes programmers confused. A large number of classes owned by AWT have not been used, or become classes inherited by Swing's classes. In my opinion, this makes Swing is not appreciated.
2.2- SWT (Standard Widget Toolkit)
- SWT (Standard Widget Toolkit) is a programming library for Desktop applications developed by IBM. It does not totally develop graphics with only Java. When running on an operating system, it manages to make use of graphical interfaces of that operating system (Button, Label,...) and creates only component graphics that has not existed in that operating system with Java.
- When programming SWT, you should choose Eclipse IDE for the best. Eclipse can integrate with WindowBuilder plugin to help drag and drop interface components easily. WindowBuilder used to be a commercial product, but now it is free when integrated with Eclipse.
2.3- Compare SWT and Swing
- Swing is a pure Java library. After you finished programming the application, you can set up Look And Feel to get an interface similar to Windows or Linux or Mac Os. Some Look And Feels are available on JDK, so you can use or buy L-A-F. Thus, you run a Swing application on the Windows platform on which display interface belongs to Linux, Mac Os,...
- This is an introduction link of pretty L-A-F:
-
- SWT - This library is not written completely by Java. When running on an operating system, it tries to make use of component libraries of that operating system (for example, it makes use of Buttons, Labels, Frames, etc) and only use Java for drawing components if they are unavailable on the operating system. Therefore, as for speed, SWT is faster than Swing.
- To SWT, we don't have the concept of Look And Feel as to Swing. When you run the application on the platform of any operating system, the interface is characterized by that operating system.
Compare application performance:
2.4- You should choose SWT or Swing?
- I think that you should choose SWT for programming a Desktop application because it is a library package with a plentiful supply of different interface components. Moreover, it was born after Swing, so it is the result of studying and remedying weaknesses of Swing.
- SWT with expanding library packages is being developed, for example:
-
- Eclipse develops a new platform named as RAP (Remote Application Platform) - RAP allows you to programme applications whose interfaces are alike Desktop applications' and which use familiar classes in SWT. Thus, you can write an application which can run both on the web platform and Desktop one. This is a strength if you choose SWT.
- Let's see a Demo program written with RAP:
-
3- Eclipse Technology
- We need to have an overview of technology of Eclipse
- RCP is a Platform based on SWT library for programming Desktop applications . Running on different operating systems.
(More details RCP below.)
- RAP (Remote Application Platform): is a Platform using RWT library for programming applications running on Web like the Desktop application.
- RWT (RAP Widget Toolkit) is a library package whose classes' name is the same as SWT' s. It has similar methods helping you programme RAP applications running on Web. Thank to this characteristic, with only a source code, you can run the application on the Desktop platform or Web one.
- RAP runs well on different browsers.
- Tabris - is a library package writing Mobile applications, and able to operate on different Mobile types.
4- RCP do what?
- RCP (Rich Client Platform): A Platform using SWT library for programming Desktop applications . Running on different operating systems, It is a platform created Eclipse IDE
- So RCP is a Platform using SWT as the basis of building. You can use RCP Platform to programme Desktop applications.
- The below image illustrates a simple application (Only use SWT, but not advanced things of RCP Platform):
- Platform RCP has built a platform allowing you to programme complicated structural interfaces like I DE Eclipse. It includes the systems of Menu, Toolbar, View, Editor,...
- RCP also allows you to develop Plugin integrated in Eclipse that you are using.
5- RAP do what?
- RAP (Remote Application Platform): is a Platform using RWT library to programme applications running on Web like applications of Desktop.
- RWT (RAP Widget Toolkit) is a set of library with classes whose names are the same as those of classes of SWT and whose methods are similar. This helps you programme RAP applications on Web. Since this feature needs only 1 source code, you can run the application as an application of Desktop or on Web.
- Like RCP, RAP is a Platform which allows us to create applications whose interfaces are as complicated as those of Eclipse IDE.
6- RAP and RCP - Why is the same code?
- This is the structure of two Platform:
- RCP based on SWT (Standard Widget Toolkit)
- RAP based on RWT (RAP Widget Toolkit)
- This is an example of code to add a Button to a Composite:
- ** MyApplicationWindow **
import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; public class MyApplicationWindow { ....... protected void createContents() { ....... Composite composite = new Composite(shell, SWT.NONE); composite.setLayout(new GridLayout(1, false)); Button btnMyButton = new Button(composite, SWT.NONE); btnMyButton.setText("My Button"); } }
- Both SWT and RWT use org.eclipse.swt.widgets.Button class to create a button.
Code of Button class of SWT (run on desktop) is obviously different from code of Button class of RWT (inherently run on WEB).
- Button class of SWT is packed in jar file named org.eclipse.swt_*.jar
- Button class of SWT is packed in jar file named org.eclipse.rap.rwt_*.jar
- Target Platform is a library environment where you can declare.
You can declare two Target Platforms. One includes RCP libraries, and another includes RAP libraries.
- RCP Target Platform
- RAP Target Platform
Of course, RAP and RCP have some differences. No all components of SWT have equivalently on RWT, and vice versa. In specific situations, we can handle this difference. Applications which can run on both Desktop and Web are known as "Single Sourcing".
7- You should start from?
- If you choose RAP-RCP programming, you will have to study SWT. This means you can easily learn about RWT.
Working with SWT means working with Widget objects ( Button, Label,...) and handle Layout. WindowBuilder is a Plugin allowing us to drag & drop components on the interface and automatically generate equivalent codes.
- You can reference the following document that instruct you to program SWT with WindowBuilder which is a visual tool helping drag & drop interface components easily.
-
- After you have been fluent in programming with SWT, you can continue with RCP or RAP.
SWT:
-
RCP
-
RAP
- | https://o7planning.org/en/10177/which-platform-should-you-choose-for-developing-java-desktop-applications | CC-MAIN-2018-09 | refinedweb | 1,451 | 56.96 |
Observables
Observables are objects which have properties that can be observed. That means when the value of such property changes, an event is fired by the observable and the change can be reflected in other pieces of the code that listen to that event.
Observables are common building blocks of the CKEditor 5 Framework. They are particularly popular in the UI, the
View class and its subclasses benefiting from the observable interface the most: it is the templates bound to the observables what makes the user interface dynamic and interactive. Some of the basic classes like
Editor or
Command are observables too.
Any class can become observable; all you need to do is mix the
ObservableMixin into it:
import ObservableMixin from '@ckeditor/ckeditor5-utils/src/observablemixin'; import mix from '@ckeditor/ckeditor5-utils/src/mix'; class AnyClass { // ... } mix( AnyClass, ObservableMixin );
Observables are useful when it comes to managing the state of the application, which can be dynamic and, more often than not, centralized and shared between components of the application. One observable can also propagate its state (or its part) to another using property bindings.
Observables can also decorate their methods which makes it possible to control their execution using event listeners, giving external code some control over their behavior.
Since the observables are just another layer on top of the event emitters, check out the event system deep dive guide to learn more about the advanced usage of events with some additional examples.
# Making properties observable
Having mixed the
ObservableMixin into your class, you can define observable properties. To do that, use the
set() method.
Let’s create a simple UI view (component) named
Button with a couple of properties and see what they look like:
class Button extends View { constructor() { super(); // This property is not observable. // Not all properties must be observable, it's always up to you! this.type = 'button'; const bind = this.bindTemplate; // this.label is observable but undefined. this.set( 'label' ); // this.isOn is observable and false. this.set( 'isOn', false ); // this.isEnabled is observable and true. this.set( 'isEnabled', true ); // ... } }
Note that because
Button extends the
View class (which is already observable), you do not need to mix the
ObservableMixin.
The
set() method can accept an object of key/value pairs to shorten the code. Knowing that, making properties observable can be as simple as:
this.set( { label: undefined, isOn: false, isEnabled: true } );
Finally, let’s create a new view and see how it communicates with the world.
Each time the
label property changes, the view fires the
change:label event containing information about its state in the past and the new value. The
change:isEnabled and
change:isOn events will be fired for changes of
isEnabled and
isOn, respectively.
const view = new Button(); view.on( 'change:label', ( evt, propertyName, newValue, oldValue ) => { console.log( `#${ propertyName } has changed from "${ oldValue }" to "${ newValue }"` ); } ) view.label = 'Hello world!'; // -> #label has changed from "undefined" to "Hello world!" view.label = 'Bold'; // -> #label has changed from "Hello world!" to "Bold" view.type = 'submit'; // Changing a regular property fires no event.
The events fired by the view are used to update the DOM and make the component dynamic. Let’s give our view some template and bind it to the observable properties we created.
class Button extends View { constructor() { super(); // ... // This template will have the following symbolic representation in DOM: // // <button class="[ck-disabled] ck-[on|off]" type="button"> // {{ this.label }} // </button> // this.setTemplate( { tag: 'button', attributes: { class: [ // The 'ck-on' and 'ck-off' classes toggle according to the #isOn property. bind.to( 'isOn', value => value ? 'ck-on' : 'ck-off' ), // The 'ck-enabled' class appears when the #isEnabled property is false. bind.if( 'isEnabled', 'ck-disabled', value => !value ) ], type: this.type }, children: [ { // The text of the button is bound to the #label property. text: bind.to( 'label' ) } ] } ); } }
Because
label,
isOn, and
isEnabled are observables, any change will be immediately reflected in DOM:
const button = new Button(); // Render the button to create its #element. button.render(); button.label = 'Bold'; // <button class="ck-off" type="button">Bold</button> button.isOn = true; // <button class="ck-on" type="button">Bold</button> button.label = 'B'; // <button class="ck-on" type="button">B</button> button.isOff = false; // <button class="ck-off" type="button">B</button> button.isEnabled = false; // <button class="ck-off ck-disabled" type="button">B</button>
# Property bindings
One observable can also propagate its state (or part of it) to another observable to simplify the code, e.g. to avoid numerous
change:property event listeners. To start binding object properties, make sure both objects (classes) mix the
ObservableMixin, then use the
bind() method to create the binding.
# Simple bindings
Let’s use our bold button instance from the previous chapter and bind it to the bold command. That will let the button use certain command properties and automate the user interface in just a couple of lines.
The bold command is an actual command of the editor (registered by the
BoldEditing) and offers two observable properties:
value and
isEnabled. To get the command, use
editor.commands.get( 'bold' ).
Note that both
Button and
Command classes are observable, which is why we can bind their properties.
const button = new Button(); const command = editor.commands.get( 'bold' );
Any “decent” button must update its look when the command becomes disabled. A simple property binding doing that could look as follows:
button.bind( 'isEnabled' ).to( command );
After that:
button.isEnabledinstantly equals
command.isEnabled,
- whenever
command.isEnabledchanges,
button.isEnabledwill immediately reflect its value,
- because the template of the button has its class bound to
button.isEnabled, the DOM element of the button will also be updated.
Note that
command.isEnabled must be defined using the
set() method for the binding to be dynamic. In this case we are lucky because
isEnabled is a standard observable property of every command in the editor. But keep in mind that when you create your own observable class, using
set() method is the only way to define observable properties.
# Renaming properties
Now let’s dive into the
bind( ... ).to( ... ) syntax for a minute. As a matter of fact, the last example corresponds to the following code:
const button = new Button(); const command = editor.commands.get( 'bold' ); button.bind( 'isEnabled' ).to( command, 'isEnabled' );
You probably noticed the
to( ... ) interface which helps specify the name of the property (or just “rename” the property in the binding).
Both
Button and
Command class share the same
isEnabled property, which allowed us to shorten the code. But if we decided to bind the
Button#isOn to the
Command#value, the code would be as follows:
button.bind( 'isOn' ).to( command, 'value' );
The property has been “renamed” in the binding and from now on, whenever
command.value changes, the value of
button.isOn will reflect it.
# Processing a property value
Another use case is processing the bound property value, for instance, when a button should be disabled only if certain conditions are met. Passing a callback as the third parameter allows implementing a custom logic.
In the example below, the
isEnabled property will be set to
true only when
command.value equals
'heading1.
const command = editor.commands.get( 'heading' ); button.bind( 'isOn' ).to( command, 'value', value => value === 'heading1' );
# Binding multiple properties
It is possible to bind more that one property at a time to simplify the code:
const button = new Button(); const command = editor.commands.get( 'bold' ); button.bind( 'isOn', 'isEnabled' ).to( command, 'value', 'isEnabled' );
which is the same as:
button.bind( 'isOn' ).to( command, 'value' ); button.bind( 'isEnabled' ).to( command, 'isEnabled' );
In the above binding, the value of
button.isEnabled will reflect
command.isEnabled and the value of
button.isOn will reflect
command.value.
Note that the
value property of the command has also been “renamed” in the binding like in the previous example.
# Binding with multiple observables
The binding can include more than one observable, combining multiple properties in a custom callback function. Let’s create a button that gets enabled only when the
command is enabled and the editing document (also an
Observable) is focused:
const button = new Button(); const command = editor.commands.get( 'bold' ); const editingDocument = editor.editing.view.document; button.bind( 'isEnabled' ).to( command, 'isEnabled', editingDocument, 'isFocused', ( isCommandEnabled, isDocumentFocused ) => isCommandEnabled && isDocumentFocused );
The binding makes the value of
button.isEnabled depend both on
command.isEnabled and
editingDocument.isFocused as specified by the function: both must be
true for the button to become enabled.
# Binding with an array of observables
It is possible to bind the same property to an array of observables. Let’s bind our button to multiple commands so that each and every one must be enabled for the button to become enabled:
const button = new Button(); const commands = [ commandA, commandB, commandC ]; button.bind( 'isEnabled' ).toMany( commands, 'isEnabled', ( isAEnabled, isBEnabled, isCEnabled ) => { return isAEnabled && isBEnabled && isCEnabled; } );
The binding can be simplified using the spread operator (
...) and the
Array.every() method:
const commands = [ commandA, commandB, commandC ]; button.bind( 'isEnabled' ).toMany( commands, 'isEnabled', ( ...areEnabled ) => { return areEnabled.every( isCommandEnabled => isCommandEnabled ); } );
This kind of binding can be useful e.g. when a button opens a dropdown containing a number of other commands’ buttons and it should be disabled when none of the commands is enabled.
# Releasing the bindings
If you don’t want your object’s properties to be bound any longer, you can use the
unbind() method.
You can specify the names of the properties to selectively unbind them
const button = new Button(); const command = editor.commands.get( 'bold' ); button.bind( 'isOn', 'isEnabled' ).to( command, 'value', 'isEnabled' ); // ... // From now on, button#isEnabled is no longer bound to the command. button.unbind( 'isEnabled' );
or you can dismiss all bindings by calling the method without arguments
const button = new Button(); const command = editor.commands.get( 'bold' ); button.bind( 'isOn', 'isEnabled' ).to( command, 'value', 'isEnabled' ); // ... // Both #isEnabled and #isOn properties are independent back again. // They will retain the last values determined by the bindings, though. button.unbind();
# Decorating object methods
Decorating object methods transforms them into event–driven ones without changing their original behavior.
When a method is decorated, an event of the same name is created and fired each time the method is executed. By listening to the event it is possible to cancel the execution, change the arguments or the value returned by the method. This offers an additional flexibility, e.g. giving a third–party code some way to interact with core classes that decorate their methods.
Decorating is possible using the
decorate() method. Let’s decorate a
focus method of a
Button class we created in the previous chapters and see what if offers:
class Button extends View { constructor() { // ... this.decorate( 'focus' ); } /** * Focuses the button. * * @param {Boolean} force When `true`, the button will be focused again, even if already * focused in DOM. * @returns {Boolean} `true` when the DOM element was focused in DOM, `false` otherwise. */ focus( force ) { console.log( `Focusing button, force argument="${ force }"` ); // Unless forced, the button will only focus when not already focused. if ( force || document.activeElement != this.element ) { this.element.focus(); return true; } return false; } }
# Cancelling the execution
Because the
focus() method is now event–driven, it can be controlled externally. E.g. the focusing could be stopped for certain arguments. Note the
high listener priority used to intercept the default action:
const button = new Button(); // Render the button to create its #element. button.render(); // The logic controlling the behavior of the button. button.on( 'focus', ( evt, [ isForced ] ) => { // Disallow forcing the focus of this button. if ( isForced === true ) { evt.stop(); } }, { priority: 'high' } ); button.focus(); // -> 'Focusing button, force argument="undefined"' button.focus( true ); // Nothing is logged, the execution has been stopped.
# Changing the returned value
It is possible to control the returned value of a decorated method using an event listener. The returned value is passed in the event data as a
return property:
const button = new Button(); // Render the button to create its #element. button.render(); // The logic controlling the behavior of the button. button.on( 'focus', ( evt, [ isForced ] ) => { // Pretend the button wasn't focused if the focus was forced. if ( isForced === true ) { evt.return = false; } } ); console.log( button.focus() ); // -> true console.log( button.focus( true ) ); // -> false
# Changing arguments on the fly
Just like the returned value, the arguments passed to the method can be changed in the event listener. Note the
high listener priority of the used to intercept the default action:
const button = new Button(); // Render the button to create its #element. button.render(); // The logic controlling the behavior of the button. button.on( 'focus', ( evt, args ) => { // Always force the focus. args[ 0 ] = true; }, { priority: 'high' } ); button.focus(); // -> 'Focusing button, force="true"' button.focus( true ); // -> 'Focusing button, force="true"' | https://ckeditor.com/docs/ckeditor5/latest/framework/guides/deep-dive/observables.html | CC-MAIN-2021-49 | refinedweb | 2,096 | 50.94 |
Skyclad + 0 comments
This is an excellent problem! (If you really delve into it...)
First you need to understand what you are trying to solve. The descriptions are already very clear. This problem is nothing but a string matching task. Don't be confused by those "DNA", "gene" terms. If you don't understand, like many of you posted here, read again carefully and pay attention to the example given here. The example already covers all the cases you need to consider.
This problem makes you think about: What really slows down my string matching? Why this strategy is bad? You may need to see some test case files to know what you are really facing with. (100,000 pattern strings to search for, for each 'DNA' text string; file size up to several MB)
You need to know some advanced string matching algorithms, way beyond KMP, as you may know as a fast one. If you really don't, it is a perfect chance to learn about them this time! (And yes, other players here already gave you the hint Aho-Corasick algorithm is the one you should go after.) You need to understand why you are choosing AC instead of other advanced algorithms. AC is, to some extent, similar to KMP in its idea.
You will not only need to fully understand AC algorithm, but also make some implementation designing, because AC itself tells you the presence of a pattern string, while you need the "health score".
I don't know about AC and some other advanced string matching algorithms before doing this problem. It took me at least 8 hours to get all ACCEPTED. I feel really happy when I am done!
adam_s_develop + 0 comments
This is very poorly explained. Need to clarify with plain language, and give better examples.
msebi + 0 comments
Does anybody know how a sequence of genes comprised of overlaping genes should be handled?
It's not clear from the exercise if, once a sequence has been found, if it is maximal then another should be looked up even if it may have a lower value and is also overlapping the first sequence.
For example: gene "caaab" with gene pairs
b c aa aaa b
and health values
2 3 4 9 6
"aaa" (9) is healthier than two "aa"'s (4 * 2 = 8). Should the algorithm pick
"aaa",
"aa" + "aaa" (and the its swapped equivalent)
or the maximal value of overlapping sequences:
"aa" + "aaa" + "aa" or "aaa" + "aa"
This looks like it could only be solved through bruteforcing gene subsequences and check for a maximal value. The gene lookup could be optimized using a hash table but that seems pretty much it.
franceaz + 0 comments
Very beautiful (and hard) problem. My super optimized solution in Python3 (easily passes all the test cases):
from math import inf from bisect import bisect_left as bLeft, bisect_right as bRight from collections import defaultdict # ------------------------------------------------------------------------------ def getHealth(seq, first, last, largest): h, ls = 0, len(seq) for f in range(ls): for j in range(1, largest+1): if f+j > ls: break sub = seq[f:f+j] if sub not in subs: break if sub not in gMap: continue ids, hs = gMap[sub] h += hs[bRight(ids, last)]-hs[bLeft(ids, first)] return h # ------------------------------------------------------------------------------ howGenes = int(input()) genes = input().rstrip().split() healths = list(map(int, input().rstrip().split())) howStrands = int(input()) gMap = defaultdict(lambda: [[], [0]]) subs = set() for id, gene in enumerate(genes): gMap[gene][0].append(id) for j in range(1, min(len(gene), 500)+1): subs.add(gene[:j]) for v in gMap.values(): for i, ix in enumerate(v[0]): v[1].append(v[1][i]+healths[ix]) # ------------------------------------------------------------------------------ largest = max(list(map(len, genes))) hMin, hMax = inf, 0 for _ in range(howStrands): firstLastd = input().split() first = int(firstLastd[0]) last = int(firstLastd[1]) strand = firstLastd[2] h = getHealth(strand, first, last, largest) hMin, hMax = min(hMin, h), max(hMax, h) print(hMin, hMax)
Sort 150 Discussions, By:
Please Login in order to post a comment | https://www.hackerrank.com/challenges/determining-dna-health/forum | CC-MAIN-2020-50 | refinedweb | 673 | 71.34 |
IRC log of databinding on 2008-02-19
Timestamps are in UTC.
14:58:13 [RRSAgent]
RRSAgent has joined #databinding
14:58:13 [RRSAgent]
logging to
14:58:15 [trackbot-ng]
RRSAgent, make logs public
14:58:15 [Zakim]
Zakim has joined #databinding
14:58:17 [trackbot-ng]
Zakim, this will be DBWG
14:58:17 [Zakim]
ok, trackbot-ng; I see WS_DBWG()10:00AM scheduled to start in 2 minutes
14:58:18 [trackbot-ng]
Meeting: XML Schema Patterns for Databinding Working Group Teleconference
14:58:18 [trackbot-ng]
Date: 19 February 2008
14:58:24 [pauld]
scribe: pauld
14:58:27 [gcowe]
gcowe has joined #databinding
14:59:47 [gcowe]
ok, no problem!
15:00:44 [Zakim]
WS_DBWG()10:00AM has now started
15:00:52 [Zakim]
+George_Cowe
15:02:32 [Zakim]
+ +0207809aaaa
15:02:38 [pauld]
zakim, code?
15:02:38 [Zakim]
the conference code is 3294 (tel:+1.617.761.6200 tel:+33.4.89.06.34.99 tel:+44.117.370.6152), pauld
15:03:06 [Zakim]
+ +0791888aabb
15:03:12 [pauld]
zakim, aabb is me
15:03:16 [Zakim]
+pauld; got it
15:03:30 [pauld]
zakim, aaaa is Jonc
15:03:30 [Zakim]
+Jonc; got it
15:03:38 [JonC]
JonC has joined #databinding
15:03:40 [pauld]
zakim, who is here?
15:03:40 [Zakim]
On the phone I see George_Cowe, Jonc, pauld
15:03:41 [Zakim]
On IRC I see JonC, gcowe, Zakim, RRSAgent, pauld, trackbot-ng, Yves
15:03:59 [pauld]
Topic: Administriva
15:04:11 [pauld]
minutes from the last telcon approved
15:05:49 [pauld]
Topic: Missing Examples?
15:06:34 [pauld]
Jonc: we're down to the last 17 patterns
15:06:56 [JonC]
List of patterns without example: AttributeFormQualified
15:07:11 [pauld]
pauld: I felt that as far as Basic was concerned, we're done!
15:08:25 [pauld]
gcowe: I've been checking and putting them into CVS on Jon's behalf
15:09:18 [pauld]
pauld: how do we know which ones we can't write examples for?
15:09:33 [pauld]
jonc: formqualified is hard one to hit
15:09:56
15:10:35 [pauld]
pauld: unqualified we can probably ignore, except I know the WSDL 2.0 test suite used them. Nobody in the wild does, and they're not BP
15:11:54 [pauld]
gcowe: we can't really prove unqualified elements, without adding a default namespace
15:12:19 [pauld]
pauld: unless the default namespace is "" it's not a valid test
15:13:50 [pauld]
pauld: at this point, I'm not worried about running the tests, but good examples in 6/09 would be, er, good
15:14:40 [JonC]
15:16:00 [pauld]
this example looks easy to write an example for?
15:17:02 [pauld]
pauld: can't we add a flag to an example to fill in a default namespace
15:20:01 [pauld]
ACTION: downeyp to enhance the explode_examples.xsl to add a default namespace
15:20:01 [trackbot-ng]
Sorry, couldn't find user - downeyp
15:20:12 [pauld]
ACTION: pdowney to enhance the explode_examples.xsl to add a default namespace
15:20:12 [trackbot-ng]
Created ACTION-128 - Enhance the explode_examples.xsl to add a default namespace [on Paul Downey - due 2008-02-26].
15:23:02 [pauld]
if it's elementFormDefault="unqualified" (the default), then you need a flag to switch that off in the generated WSDL/Schemas.
15:24:03 [pauld]
pauld: I'll have a think about supporting these and other xs:schema attibutes
15:24:55 [pauld]
jonc; last issue is the ExtendedSequence etc
15:25:04 [pauld]
s/;/:/
15:26:10 [pauld]
jonc: exploding into lots of separate patterns
15:26:18 [pauld]
pauld: how do we know when we're done?
15:26:44 [pauld]
.. want to be driven by the collection
15:26:53 [pauld]
jonc: I'm prepared to do the work
15:29:00 [pauld]
pauld: at this stage we'll accept patterns, so long as they don't make "Basic" "Advanced"
15:29:14 [pauld]
.. i.e don't bu993r it up :)
15:29:49 [pauld]
gcowe: gday, gyear, gmonth, are simple, but don't involve timezones
15:30:17 [pauld]
jonc: it's all paul's fault - wanted to keep it simple as possible!
15:30:25 [pauld]
pauld: *dunk*
15:31:21 [pauld]
gcowe: .NET and others have issues for non-timezone instances
15:31:49 [pauld]
s/ACTION: downeyp to enhance the explode_examples.xsl to add a default namespace//
15:32:47 [JonC]
G pattern <xs:pattern
15:34:02 [pauld]
pauld: does timezone qualified make sense here?
15:34:53 [pauld]
gcowe: yeah, looks fine as we are
15:35:08 [pauld]
pauld: thanks so much for all this work!
15:35:15 [pauld]
Topic: Collection
15:38:04 [pauld]
pauld: I'm still working on the collection, in particular annotating the schema with patterns detected. turns out to be computing intensive.
15:38:12 [pauld]
.. will continue to work on this
15:38:22 [pauld]
15:38:47 [pauld]
we hope to use this to drive patterns
15:40:28 [pauld]
15:41:18 [pauld]
15:42:00 [pauld]
15:42:38 [pauld]
pauld: some sites, you have to sign up, in which case I've taken a snapshot, but that's member-visible
15:43:45 [pauld]
jonc: I see lots of pendings in the report
15:45:45 [pauld]
pauld: jonc, you need to push me to work on the collection!
15:45:56 [pauld]
gcowe: is the collection report upto date?
15:46:03 [pauld]
pauld: rebuilding, now ..
15:46:54 [pauld]
pauld: ah, Origo are all Advanced! cool!
15:50:38 [pauld]
jonc: list looking good
15:52:06 [pauld]
gcowe: will add some more Origo schemas
15:52:48 [pauld]
pauld: if you know of other schemas, let us know!
15:52:55 [pauld]
Topic: Test Suite
15:53:17 [pauld]
gcowe: not been running it, waiting until we clear the missing examples list
15:53:26 [pauld]
pauld: sounds absolutely fine!
15:56:09 [pauld]
Topic: Meeting
15:56:36 [pauld]
pauld: not planning on meeting again. sounds fine?
15:57:21 [pauld]
s/meeting/meeting F2F/
15:57:30 [pauld]
next telcon in three weeks time
15:58:14 [Zakim]
-George_Cowe
16:00:39 [Zakim]
-Jonc
16:00:43 [Zakim]
-pauld
16:00:45 [Zakim]
WS_DBWG()10:00AM has ended
16:00:47 [Zakim]
Attendees were George_Cowe, +0207809aaaa, +0791888aabb, pauld, Jonc
16:01:46 [pauld]
rrsagent, generate minutes
16:01:46 [RRSAgent]
I have made the request to generate
pauld
16:01:54 [pauld]
rrsagent, make logs public
16:22:32 [pauld]
pauld has joined #databinding
17:06:11 [Zakim]
Zakim has left #databinding | http://www.w3.org/2008/02/19-databinding-irc | CC-MAIN-2015-06 | refinedweb | 1,135 | 70.26 |
and 1 contributors
NAME
Adapter::Async::Model - helper class for defining models
VERSION
version 0.018
DESCRIPTION
Generates accessors and helpers for code which interacts with Adapter::Async-related classes. Please read the warnings in Adapter::Async before continuing.
All definitions are applied via the "import" method:
package Some::Class; use Adapter::Async::Model { some_thing => 'string', some_array => { collection => 'OrderedList', type => '::Thing', } };
Note that methods are applied via a UNITCHECK block by default.
import
defer_methods - if true (default), this will delay creation of methods such as
newusing a UNITCHECK block, pass defer_methods => 0 to disable this and create the methods immediately
model_base - the base class to prepend when types are specified with a leading ::
AUTHOR
Tom Molesworth <TEAM@cpan.org>
LICENSE
Copyright Tom Molesworth 2013-2015. Licensed under the same terms as Perl itself. | https://metacpan.org/pod/Adapter::Async::Model | CC-MAIN-2020-40 | refinedweb | 133 | 53.92 |
Create a new Java Class Rectangle – This Python Tutorial will explain the creation of a new Java class named Rectangle with the following class specification:
How To Create a New Rectangle Class in Java
- Write a Java program using Objects and Classes concepts in Object Oriented Programming. Define the Rectangle class that will have:
- Two member variables width and height ,
- A no-arg constructor that will create the default rectangle with width = 1 and height =1.
- A parameterized constructor that will create a rectangle with the specified x, y, height and width.
- A method getArea() that will return the area of the rectangle.
Note: Formula for area of rectangle is (width x height)
Formula for perimeter of rectangle is: 2 x (width+height)
A method getPerimeter() that will return the perimeter of the rectangle.
Write a test program that creates two rectangle objects. It creates the first object with default values and the second object with user specified values. Test all the methods of the class for both the objects.
How to Calculate Area and Perimeter in Rectangle Class
Formula for Area of a Rectangle
To calculate area of triangle, we need the number of square units to cover the surface of a figure.
Hence, the formula is: Area = Length x Width
Formula for perimeter of Rectangle
The perimeter may be defined as the distance around a figure.
Hence formula is:
Perimeter of Rectangle = 2 x Length + 2 x Width
Perimeter of Rectangle = 2 (Length + Width)
The Source Code of Java Rectangle Class Program
/* * Write a Java program to create a new class called 'Rectangle' with length and height fields and a no argument constructor and parameterized constructor. Moreover add two methods to calculate and return area and perimeter of rectangle. Write a test class to use this Rectangle class. Create different objects initialized by constructors. Call methods for these objects and show results. */ package testrectangle; /** * @author */ class Rectangle{ // define two fields double length, width; // define no arg constructor Rectangle() { length = 1; width = 1; } // define parameterized constructor Rectangle(double length, double width) { this.length = length; this.width = width; } // define a method to return area double getArea() { return (length * width); } // define a method to return perimeter double getPerimeter() { return (2 * (length + width)); } } public class TestRectangle { public static void main(String[] args) { // create first object //and initialize with no arg constructor Rectangle rect1 = new Rectangle(); // create first object //and initialize with no arg constructor Rectangle rect2= new Rectangle(15.0,8.0); System.out.println("Area of first object="+rect1.getArea()); System.out.println("Perimeter of first object="+rect1.getPerimeter()); System.out.println("Area of second object="+rect2.getArea()); System.out.println("Perimeter of second object="+rect2.getPerimeter()); } }
The output of a sample run of the Java Program
Area of first object=1.0 Perimeter of first object=4.0 Area of second object=120.0 Perimeter of second object=46.0
Pingback: Define Circle Class in Java with Radius and Area | EasyCodeBook.com | https://easycodebook.com/create-a-new-java-class-rectangle-java-program/ | CC-MAIN-2019-51 | refinedweb | 492 | 54.42 |
Subject: [Boost-bugs] [Boost C++ Libraries] #7674: Compile failures in Boost.Test using mingw clang and gcc
From: Boost C++ Libraries (noreply_at_[hidden])
Date: 2012-11-09 17:06:23
#7674: Compile failures in Boost.Test using mingw clang and gcc
-------------------------------------+--------------------------------------
Reporter: pbristow | Owner: rogeeff
Type: Bugs | Status: new
Milestone: Boost 1.53.0 | Component: test
Version: Boost Development Trunk | Severity: Optimization
Keywords: test clang |
-------------------------------------+--------------------------------------
Compiling Boost.Test using NetBeans IDE and minggw32 gcc and Clang (and VS
10) compilers I foudn some failures.
I was building a dll with all the components (perhaps some are not
normally used?)
(Don't ask why I wasn't using b2! Grrrrr!)
Using Boost-trunk I found two compile failures
1 in config_file_iterator.cpp
I needed to add
#include <boost/noncopyable.hpp>
so that noncopyable was found,
2 in config_file.cpp, a missing 3rd parameter was reported:
assign_op( p_name.value, name );
needed to be
assign_op( p_name.value, name, 0 ); // But this might wrong?
3 template<typename T>
struct is_named_params : public mpl::false_ {};
added #include <boost/mpl/bool.hpp>
template<typename T>
variable<T>::variable( cstring var_name )
: variable_base( environment::var<T>( var_name ) )
{}
4 in variable.hpp
I replaced var<T> by variable<T>
in config_file_iterator.cpp an undefined function erase
erase(name); I just commented out to get it to compile and build at least.
-- Ticket URL: <> Boost C++ Libraries <> Boost provides free peer-reviewed portable C++ source libraries.
This archive was generated by hypermail 2.1.7 : 2017-02-16 18:50:11 UTC | https://lists.boost.org/boost-bugs/2012/11/26185.php | CC-MAIN-2020-40 | refinedweb | 251 | 52.36 |
Every C program begins execution in the main function. It is the first piece of code that is run, and it's responsible for ensuring that other parts of your code are executed appropriately. Sometimes a main function can be a few lines, as is often the case in software written with the Cocoa frameworks (see Chapter 8), and at other times it may constitute the whole program. Here is a simple example to get started:
#include <stdio.h> int main (int argc, const char * argv[]) { printf("Why me? Why C?"); return 0; }
The first line in this snippet is called a preprocessor directive:
#include <stdio.h>
The preprocessor, which is explained in more detail later in the chapter, is a program that passes over the source code, modifying it, before the compiler is called to turn the program into binary machine code that the computer can run. This particular line tells the preprocessor to replace the directive with all the text from the file stdio.h. The file stdio.h is part of the standard C library, and the preprocessor automatically knows where to find it. This type of file is known as a header file, and it contains definitions that can be used in C programs. Header files are an important part of C, and you generally need to write many of them to define the functions and data structures in your programs.
The main function itself begins on the next line:
int main (int argc, const char * argv[]) {
The word int at the beginning of the line is known as the return type. It ...
No credit card required | https://www.oreilly.com/library/view/beginning-mac-os/9780764573996/9780764573996_getting_started.html | CC-MAIN-2018-51 | refinedweb | 271 | 69.21 |
In this article, I am going to walk over easy to follow examples and show how to create Hive User Defined Functions (UDF) and User Defined Aggregate Functions (UDAFs), package into a JAR, and test in Hive CLI. So let’s begin.
In my Sqoop import article, I imported a customers table. Similarly, I have imported an orders table, which I used in my Hive Joins article. Also, I am using a dummy table for UDF verification. You can find the relevant Sqoop commands on GitHub.
Hive supports of a lot of built-in SQL-like functions in HiveQL. But just in case, if there is a need to write your own UDF, no one is stopping you.
UDF (User Defined Function)
Here I am going to show how to write a simple “trim-like” function called “Strip” – of course, you can write something fancier, but my goal here is to take away something in a short amount of time. So let’s begin.
How to Write a UDF function in Hive?
- Create a Java class for the User Defined Function which extends ora.apache.hadoop.hive.sq.exec.UDF and implements more than one evaluate() methods. Put in your desired logic and you are almost there.
- Package your Java class into a JAR file (I am using Maven)
- Go to Hive CLI, add your JAR, and verify your JARs is in the Hive CLI classpath
- CREATE TEMPORARY FUNCTION in Hive which points to your Java class
- Use it in Hive SQL and have fun!
There are better ways to do this, by writing your own GenericUDF to deal with non-primitive types like arrays and maps – but I am not going to cover it in this article.
I will go into detail for each one.
Create Java Class for a User Defined Function
As you can see below I am calling my Java class “Strip”. You can call it anything, but the important point is that it extends the UDF interface and provides two evaluate() implementations.
evaluate(Text str, String stripChars) - will trim specified characters in stripChars from first argument str. evaluate(Text str) - will trim leading and trailing spaces.
package org.hardik.letsdobigdata; import org.apache.commons.lang.StringUtils; import org.apache.hadoop.hive.ql.exec.UDF; import org.apache.hadoop.io.Text; public class Strip extends UDF { private Text result = new Text(); public Text evaluate(Text str, String stripChars) { if(str == null) { return null; } result.set(StringUtils.strip(str.toString(), stripChars)); return result; } public Text evaluate(Text str) { if(str == null) { return null; } result.set(StringUtils.strip(str.toString())); return result; } }
Package Your Java Class into a JAR
There is a pom.xml attached in GitHub. Please make sure you have Maven installed. If you are working with a GitHub clone, go to your shell:
$ cd HiveUDFs
and run "mvn clean package". This will create a JAR file which contains our UDF class. Copy the JAR's path.
Go to the Hive CLI and Add the UDF JAR
hive> ADD /HiveUDFs-0.0.1-SNAPSHOT.jar]
Verify JAR is in Hive CLI Classpath
You should see your jar in the list.
hive> list jars; /usr/lib/hive/lib/hive-contrib.jar /home/cloudera/workspace/HiveUDFs/target/HiveUDFs-0.0.1-SNAPSHOT.jar
Create Temporary Function
It does not have to be a temporary function. You can create your own function, but just to keep things moving, go ahead and create a temporary function.
You may want to add ADD JAR and CREATE TEMPORARY FUNCTION to .hiverc file so they will execute at the beginning of each Hive session.
UDF Output
The first query strips ‘ha’ from string ‘hadoop’ as expected (2 argument evaluate() in code). The second query strips trailing and leading spaces as expected.
hive> CREATE TEMPORARY FUNCTION STRIP AS 'org.hardik.letsdobigdata.Strip'; hive> select strip('hadoop','ha') from dummy; OK doop Time taken: 0.131 seconds, Fetched: 1 row(s) hive> select strip(' hiveUDF ') from dummy; OK hiveUDF
If you have made this far, congratulations! That was our UDF in action! You can follow the code on GitHub.
UDAF (User Defined Aggregated Function)
Now, equipped with our first UDF knowledge, we will move to a next step. When we say aggregation, COUNT, AVG, SUM, MIN, and MAX come to our mind.
I am picking a very simple aggregation function AVG/MEAN, where I am going to work with the “orders” table imported using Sqoop. Once you import it into Hive, it will look like the below (or you can use LOAD DATA INPATH – it is totally up to you.)
hive> select * from orders; OK orders.order_id orders.order_date orders.customer_id orders.amount 101 2016-01-01 7 3540 102 2016-03-01 1 240 103 2016-03-02 6 2340 104 2016-02-12 3 5000 105 2016-02-12 3 5500 106 2016-02-14 9 3005 107 2016-02-14 1 20 108 2016-02-29 2 2000 109 2016-02-29 3 2500 110 2016-02-27 1 200
The goal of our UDAF is to find the average amount of orders for all customers in the orders table.
We are looking for Query: SELECT CUSTOMER_ID, AVG(AMOUNT) FROM ORDERS GROUP BY CUSTOMER_ID;
I am going to replace AVG function with “MEAN” function
But before I begin, let’s stop and think as we are entering the MapReduce world. One of the bottlenecks you want to avoid is moving too much data from the Map to the Reduce phase.
An aggregate function is more difficult to write than a regular UDF. Values are aggregated in chunks (across many maps or many reducers), so the implementation has to be capable of combining partial aggregations into final results.
At a high-level, there are two parts to implementing a Generic UDAF:
- evaluator – The evaluator class actually implements the UDAF logic.
- resolver – The resolver class handles type checking and operator overloading (if you want it), and helps Hive find the correct evaluator class for a given set of argument types.
We are not creating a GenericUDAF. We are creating our one-time aggregation function, so we do not have to worry about a resolver. I am planning write on GenericUDF/GenericUDAF, though. It may be some other day, but soon. :)
How to Write UDAF?
- Create a Java class which extends org.apache.hadoop.hive.ql.exec.hive.UDAF;
- Create an inner class which implements UDAFEvaluator;
- Implement five methods ()
- init() – The init() method initializes the evaluator and resets its internal state. We are using new Column() in the code below to indicate that no values have been aggregated yet.
- iterate() – this method is called every time there is a new value to be aggregated. The evaulator should update its internal state with the result of performing the aggregation (we are doing sum – see below). We return true to indicate that the input was valid.
- terminatePartial() – this method is called when Hive wants a result for the partial aggregation. The method must return an object that encapsulates the state of the aggregation.
- merge() – this method is called when Hive decides to combine one partial aggregation with another.
- terminate() – this method is called when the final result of the aggregation is needed.
- Compile and package the JAR
- CREATE TEMPORARY FUNCTION in hive CLI
- Run Aggregation Query and Verify Output!!!
MeanUDAF.java
package org.hardik.letsdobigdata; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.hive.ql.exec.Description; import org.apache.hadoop.hive.ql.exec.UDAF; import org.apache.hadoop.hive.ql.exec.UDAFEvaluator; import org.apache.hadoop.hive.ql.metadata.HiveException; import org.hardik.letsdobigdata.MeanUDAF.MeanUDAFEvaluator.Column; @Description(name = "Mean", value = "_FUNC(double) - computes mean", extended = "select col1, MeanFunc(value) from table group by col1;") public class MeanUDAF extends UDAF { // Define Logging static final Log LOG = LogFactory.getLog(MeanUDAF.class.getName()); public static class MeanUDAFEvaluator implements UDAFEvaluator { /** * Use Column class to serialize intermediate computation * This is our groupByColumn */ public static class Column { double sum = 0; int count = 0; } private Column col = null; public MeanUDAFEvaluator() { super(); init(); } // A - Initalize evaluator - indicating that no values have been // aggregated yet. public void init() { LOG.debug("Initialize evaluator"); col = new Column(); } // B- Iterate every time there is a new value to be aggregated public boolean iterate(double value) throws HiveException { LOG.debug("Iterating over each value for aggregation"); if (col == null) throw new HiveException("Item is not initialized"); col.sum = col.sum + value; col.count = col.count + 1; return true; } // C - Called when Hive wants partially aggregated results. public Column terminatePartial() { LOG.debug("Return partially aggregated results"); return col; } // D - Called when Hive decides to combine one partial aggregation with another public boolean merge(Column other) { LOG.debug("merging by combining partial aggregation"); if(other == null) { return true; } col.sum += other.sum; col.count += other.count; return true; } // E - Called when the final result of the aggregation needed. public double terminate(){ LOG.debug("At the end of last record of the group - returning final result"); return col.sum/col.count; } } }
Package and ADD JAR
hive> ADD JAR /StudentCourseMRJob-0.0.1-SNAPSHOT.jar]
CREATE FUNCTION in HIVE
hive> CREATE TEMPORARY FUNCTION MeanFunc AS 'org.hardik.letsdobigdata.MeanUDAF'; OK
Verify Output
Execute the below group by query. Our function is called MeanFunc
hive> select customer_id, MeanFunc(amount) from orders group by customer_id; FAILED: SemanticException [Error 10001]: Line 1:42 Table not found 'orders' hive> use sqoop_workspace; OK Time taken: 0.247 seconds hive> select customer_id, MeanFunc(amount) from orders group by customer_id; Query ID = cloudera_20160302030202_fb24b7c1-4227-4640-afb9-4ccd29bd735f Total_1456782715090_0020, Tracking URL = Kill Command = /usr/lib/hadoop/bin/hadoop job -kill job_1456782715090_0020 Hadoop job information for Stage-1: number of mappers: 2; number of reducers: 1 2016-03-02 03:03:16,703 Stage-1 map = 0%, reduce = 0% 2016-03-02 03:03:53,241 Stage-1 map = 50%, reduce = 0%, Cumulative CPU 3.31 sec 2016-03-02 03:03:55,593 Stage-1 map = 100%, reduce = 0%, Cumulative CPU 3.9 sec 2016-03-02 03:04:09,201 Stage-1 map = 100%, reduce = 100%, Cumulative CPU 6.18 sec MapReduce Total cumulative CPU time: 6 seconds 180 msec Ended Job = job_1456782715090_0020 MapReduce Jobs Launched: Stage-Stage-1: Map: 2 Reduce: 1 Cumulative CPU: 6.18 sec HDFS Read: 12524 HDFS Write: 77 SUCCESS Total MapReduce CPU Time Spent: 6 seconds 180 msec OK 1 153.33333333333334 2 2000.0 3 4333.333333333333 6 2340.0 7 3540.0 9 3005.0 Time taken: 72.172 seconds, Fetched: 6 row(s)
Verify Individual customer_id : As you can see, group by value matches – you can cross check manually. Thanks for your time and reading my blog – hope this is helpful!!!
hive> select * from orders where customer_id = 1; OK 102 2016-03-01 1 240 107 2016-02-14 1 20 110 2016-02-27 1 200 Time taken: 0.32 seconds, Fetched: 3 row(s) hive> select * from orders where customer_id = 2; OK 108 2016-02-29 2 2000 Time taken: 0.191 seconds, Fetched: 1 row(s) hive> select * from orders where customer_id = 3; OK 104 2016-02-12 3 5000 105 2016-02-12 3 5500 109 2016-02-29 3 2500 Time taken: 0.093 seconds, Fetched: 3 row(s)
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }} | https://dzone.com/articles/writing-custom-hive-udf-andudaf | CC-MAIN-2017-26 | refinedweb | 1,894 | 57.27 |
Ever wish you could control all of your electronics with a simple command, or just the push of a button? Well, armed with a Raspberry Pi, a smart phone, and PubNub’s Global Data Stream Network, you can make that dream a reality. Get ready to use your smart phone to be able to control outlets in your house from anywhere in the world.
In this tutorial, I’ll show you how to use a Raspberry Pi to control a power outlet using an RF transmitter, a process facilitated by commands sent via PubNub. Then, I’ll show you how to build a very simple app using Swift, Apple’s programming language, to send those commands with either your voice or the press of a button. This tutorial will assume you’ve already set up your Raspberry Pi with Raspbian or a comparable operating system. If you haven’t, no worries, just check out the first section of this tutorial on creating a Raspberry Pi Smart Home entitled “Setting Up the Raspberry Pi” and you’ll be brought up to speed.
Required Hardware
- Raspberry Pi 2, Model B
- USB keyboard
- USB mouse
- External monitor
- HDMI Cable
- Micro-SD card
- Micro-SD card adapter
- 2.5A power supply
- USB WiFi dongle
- Solderless breadboard
- Etekcity Remote Control Outlet
- SMAKN 433Mhz RF Transmitter and Receiver Kit
- Male/female jumper wires
RF Transmissions
In this project you’re going to use an RF Transmitter to send codes to an Etekcity outlet, a job that was previously done by a remote. This process requires wiring the transmitter and the receiver to the Raspberry Pi, finding the codes the remote uses, and transmitting those codes to control the outlet without the remote.
Hardware Setup
Wiring the transmitter and receiver is a fairly simple process. On the transmitter (the component with 3 pins), connect DATA to GPIO 17, VCC to 5V, and GND to Ground. On the receiver (the component with 4 pins), the left pin, when viewed face-up with the pins facing down, should be connected to 5V, the second pin from the left to GPIO 21, and the right pin to Ground. You’re ready to start using it!
Using RFSniffer
To figure out the codes that you need to send, you first need to install WiringPi. Navigate to the command line on your Raspberry Pi and download the software using git.
$ sudo apt-get install git
$ git clone git://git.drogon.net/wiringPi
To finish the installation, type the following commands.
$ cd wiringPi
$ ./build
To make sure it worked, type gpio -v into the command line, and you should see details about your Raspberry Pi printed to the console. To use RFSniffer, type the following command.
$ sudo /var/www/rfoutlet/RFSniffter
Now when you press buttons on the remote that came with the outlet, you should see numbers appear on the console. Record the five-digit numbers that appear when you press off and on – you’ll need them to toggle the outlet.
Testing the Codes
To make sure your RF Transmitter is working properly, try turning the outlet on and off using the command line. Just type the code below, replacing [code] with either of your five-digit numbers.
$ sudo /var/www/rfoutlet/codesend [code]
If the light on the outlet turned on and off based on your commands, congratulations! You’re right on track. If not, you’ll need to go back and make sure everything is properly installed, then try again.
The Raspberry Pi Script
Now that you know your RF transmissions are working properly, it’s time to write a Python script to send the codes for you, based on messages that will be sent using PubNub.
Script Setup
Then, at the top of your script, include the necessary libraries.
import os import sys from pubnub import Pubnub
Finally, to initialize PubNub, just input your publish and subscribe keys and define your channel.
pubnub = Pubnub(publish_key='your-publish-key', subscribe_key='your-subscribe-key') channel = 'OutletControl'
Receiving PubNub Commands
To receive commands from PubNub, you first need to subscribe to your channel and define your callback and error functions.
def _callback(m, channel): def _error(m): print (m) pubnub.subscribe(channels=channel, callback=_callback, error=_error)
Next you should fill in your callback function to react to PubNub messages by turning the light on or off.
def _callback(m, channel): if m.get("outlet") == "on": os.system('sudo /var/www/rfoutlet/codesend [code]') if m.get("outlet") == "off": os.system('sudo /var/www/rfoutlet/codesend [code]')
And you’re done with the Raspberry Pi part! Time to move on to creating the app.
Creating the App
Now that you’ve set up the Raspberry Pi, you’re ready to build an app to control it. In this tutorial I’m going to show you how to do it using Swift, but it can easily be adapted for many different programming languages or mobile devices, just take a look at all the PubNub SDKs and pick one! The syntax will be different, but all you really need is a subscribe call to make it work.
Installing PubNub and SpeechKit
To install both PubNub and SpeechKit, you’ll need to use CocoaPods. There’s a great tutorial on the CocoaPods website to install and get started with pods. After you install the software, just follow the directions under Creating a New Xcode Project with CocoaPods to begin your project. Your podfile should look like this when you’re done.
target 'Outlet Control' do source '' platform :ios, '8.0' use_frameworks! pod ‘PubNub’, '~> 4.4.1' pod 'SpeechKit', '~> 2.1' end
Initializing PubNub in Swift
To use PubNub, you’ll have to initialize it in the AppDelegate.swift file using your publish and subscribe keys.
class AppDelegate: UIResponder, UIApplicationDelegate, PNObjectEventListener { var window: UIWindow? var client : PubNub? override init() { let configuration = PNConfiguration(publishKey: "your-publish-key", subscribeKey: "your-subscribe-key") client = PubNub.clientWithConfiguration(configuration) super.init() client?.addListener(self) } ...
Building the User Interface
The UI for this project is fairly simple, though you’re free to add some more flair if you’d like.
To control the outlet, all you really need is a switch. I also included a button to use with Speechkit to that the outlet can be controlled using voice commands. To create the components, open Main.storyboard in Xcode. In the toolbar on the right side side of the screen, show the object library by clicking on its icon.
Drag a button and a switch onto the storyboard and label them appropriately. Customize the page to your liking using different colors, fonts, and spacing. Here’s a peek of my finished product.
Finally, you need to link your UI elements to your code. Make sure you’re using the assistant
editor by selecting the appropriate icon at the top of the page. You should have both Main.storyboard and ViewController.swift visible. In ViewController.swift, import UIKit, PubNub, and SpeechKit at the top of the program.
import UIKit import PubNub import SpeechKit
Hold the control key while you click the Listen button on your storyboard, then drag it to your ViewController class. Name the button, but don’t change any of the other settings. Do the same for your switch, so you can easily reference it later. Now control-drag the button and the switch again, but this time change Connection to Action. This will allow you to create functions that are only called when each button is pushed, which you’re now ready to do.
Using SpeechKit
Let’s start with the Listen button. You’ll want to be able to push it, say a command, and have the app interpret that command and send a corresponding message to your channel. This is actually pretty simple using SpeechKit from Nuance Developers. They give you all the functions you need, you just need to include them in your app and tweak them for your needs. First, you’ll need to create an account with Nuance. It’s easy to do through the Nuance website, plus it’s free!
Once you’ve got all your credentials settled, you need to define the delegate in the class header.
class ViewController: UIViewController, SKTransactionDelegate { … }
Now, in the ListenClicked function, define the session with your various tokens.
@IBAction func ListenClicked(sender: AnyObject) { ListenButton.setTitle("Listening", forState: .Normal) let session = SKSession(URL: NSURL(string: "your-string"), appToken: "your-token") session.recognizeWithType(SKTransactionSpeechTypeDictation, detection: .Long, language: "eng-USA", delegate: self) }
Next you’ll need to create a transaction function inside of your ListenClicked function for SpeechKit to use to interpret speech. You can choose any keywords you like to control the outlets, but I chose “off” and “on” for simplicity.
func transaction(transaction: SKTransaction!, didReceiveRecognition recognition: SKRecognition!) { if recognition.text.lowercaseString.rangeOfString("on") != nil { print("Found \"on\" in speech") } if recognition.text.lowercaseString.rangeOfString("off") != nil { print("Found \"off\" in speech") } }
Now when you click the Listen button in your app, you’ll see a message on the console when you say “off” or “on.”
Sending PubNub Messages
It’s time to start streaming information between the Raspberry Pi and the app using PubNub. To do this, you just have to publish messages to your channel when either the switch is pressed or SpeechKit detects your commands. First you’ll need to link your initialization in AppDelegate to ViewController.
let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
Next, write publish functions that correspond to pressing the switch.
@IBAction func Switch(sender: AnyObject) { if OnOffSwitch.on { appDelegate.client?.publish(["outlet":"on"], toChannel: "OutletControl", compressed: false, withCompletion:{(status)->Void in if !status.error { } else{ print("Publishing Error (On)") } }) } else { appDelegate.client?.publish(["outlet":"off"], toChannel: "OutletControl", compressed: false, withCompletion:{(status)->Void in if !status.error { } else{ print("Publishing Error (Off)") } }) } }
Now just put a publish function in the “if” statements you made for the Listen button and you’re good to go!
Testing the Setup
To test your app and Raspberry Pi setup, make sure your script is running on the Raspberry Pi, and upload the app to your favorite mobile device. You should be able to toggle your outlet on and off by using either the switch, or by pressing Listen and saying either “off” or “on.” Ta-da! Now you can control the outlet from anywhere, with just your voice or the simple tap of a button.
Next Steps
Congratulations! You’ve successfully put together an outlet that can be controlled remotely from your phone. Hopefully you’ve also learned a little bit about Raspberry Pi, Swift, and PubNub along the way. Now you’re ready to tackle other projects using Swift, like this AppleTV controlled simulated Smart Home, or this real-time radio station. If you want to explore more with Raspberry Pi, check out these cool tutorials on building a heart rate monitor or a dashboard camera. Whatever you choose to do, have fun, and good luck! | https://www.pubnub.com/blog/voice-controlled-outlet-using-raspberry-pi-and-apple-swift/ | CC-MAIN-2021-31 | refinedweb | 1,821 | 55.74 |
I have several links I'm trying to create to either perform custom controller methods or the destroy action. I'm using jquery via the jquery-rails gem and have ran the generator and seems to be including properly:
<script type="text/javascript" src="/javascripts/jquery.js?1312255663">
<script type="text/javascript" src="/javascripts/rails.js?1312407526">
<script type="text/javascript" src="/javascripts/jquery.min.js?1312255664">
<script type="text/javascript" src="/javascripts/application.js?1312256996">
<%= link_to "Delete", list_path(@list), :method => :delete, :confirm => "Are you sure?" %>
resources :lists
def destroy
@list = current_user.lists.find(params[:id])
@list.active = false
@list.save
if @list.save
redirect_to root_path, :notice => "List '#{@list.name}' deleted."
else
render :action => 'edit'
end
end
I'm not sure whether or not the issue is related to jquery, but I would suggest replacing
link_to with
button_to.
link_to should work too, but
button_to is "the safest method to ensure links that cause changes to your data are not triggered by search bots or accelerators" (source: Rails API doc) | https://codedump.io/share/HvZ5WZb78Kpg/1/rails-3---linkto-delete-is-redirecting-to-show-action-with-jquery-installed | CC-MAIN-2018-09 | refinedweb | 169 | 51.95 |
Feature #7240
Inheritable #included/#extended Hooks For Modules
Description
An inheritable hook mechanism for modules would be a great way for module/gem authors to simplify their implementations.
The Problem¶
Let's say I have the following module.
module A
def self.included(base)
# add class methods to base
end
end
So, A is overriding the #included hook to add class methods to base.
module B
include A
# class methods from A are here.
end
Since B is including A, A's #included method is invoked and A's class methods will be copied to B.
module C
include B
# class methods from B are lost.
end
When including B into C, B's #included is invoked and A's #included is lost. In our example, this means no class methods from A are in C.
Proposal¶
It would be cool if #included/#extended in a module could be inherited to including descendants. I wrote a small gem "uber" that does this kind of stuff with a simple recursion. Roughly, it works like this.
module A
extend InheritableIncluded # "execute my #included everytime me or my descendents are included."
def self.included(base) # add class methods to base end
end
Now, A's #included is invoked every time it or a descending module is included. In our example, class methods from A would be around in C.
When discussing this with Matz we agreed that this might be really useful in Ruby itself. I'm just not sure how to mark inheritable hooks.
History
#1
Updated by Eric Hodel almost 4 years ago
=begin
What is wrong with using super?
$ cat t.rb
module A
def self.included mod
puts "#{mod} included A"
end
end
module B
def self.included mod
puts "#{mod} included B"
super end include A
end
module C
include B
end
$ ruby20 t.rb
B included A
C included B
=end
#2
Updated by Eric Hodel almost 4 years ago
Sorry, I didn't read my own output, please disregard.
#3
[ruby-core:48632]
Updated by Alexey Muranov almost 4 years ago
In my opinion, the most common use case for the
included hook in modules is adding class methods. However, to me this looks hackish -- hard to follow and understand. I would have preferred if there was a way to define both instance-level and class-level behavior in a module and include both at once:
module M
def foo
# ...
end
def base.bar # here a fictional method Module#base is called # ... end
end
class C
meta_include M
end
a = C.new
a.foo
C.bar
After all, ordinary objects have no method table, classes have one method table, why not to allow modules to have 2 method tables?
Talking about method tables, maybe if objects were allowed to have one, there would be no need for metaclasses? (Then classes would have 2 method tables, modules would have 3, and in fact methods and method tables could be regarded as different kinds of attributes.)
By the way, i think that from the point of view of English, the method name
included is not consistent with the method name
extended (the module is included, but the base is extended).
#4
[ruby-core:48637]
Updated by Thomas Sawyer almost 4 years ago
=begin
I have always thought module class methods should be included. Matz has stated his opposition to it b/c he sees it as a hindrance for some use cases, for example, internal methods spilling in when including the Math module. But I've always felt that those occurrences would always be easier to counteract (by just making a separate inner-module) if it were really necessary, than hacking around the limitations of the current behavior.
Short of changing the behavior of (({#include})), there are two other options. The first is to add another method like #include that does the deed. A good name for which is, as usual, hard to come up with. (Maybe (({#include!})) would be a viable option?) The other possibility is to allow class methods to be classified as inclusive or exclusive. By default module class methods would be exclusive, but using a keyword/method this could be changed in much the same way that methods are classed into public/private/protected.
For example:
module M def self.foo; "foo"; end inclusive def self.bar; "bar"; end end module N include M end N.bar => "bar" N.foo => Error
I'm not sure I like this idea --I still think it would be better just to make it the usual behavior of (({#include})), but it is an option.
=end
#5
[ruby-core:48651]
Updated by Alexey Muranov almost 4 years ago
=begin
trans (Thomas Sawyer) wrote:
I'm not sure I like this idea --I still think it would be better just to make it the usual behavior of (({#include})), but it is an option.
I think that there would be issues with "including" methods defined on the module itself. For example:
module M
# ...
end
class C
include! M
end
Now, which methods defined of M can be called on C? Only those from the meta-class of M? Those from the meta-class of M and from the ancestors of the meta-class? All public? All? I cannot come up from the top of my mind with a (({Module})) public method which is not defined in (({Class})), but there are at least private ones, for example: should (({C.send(:module_function, :f)})) work after the inclusion in the above example?
To me, a possible solution seems to be to have a second method table in modules (i suggested above to define such methods as singleton methods on some object returned by some private method named, for example, (({Module#base}))). The inclusion method could be still called (({include})) as it would not conflict with the current usage.
To state completely my current point of view, meta-class looks to me like a hack (to make up for the fact that objects are not allowed to keep their own methods), and inheriting (({Class})) from (({Module})) does not look as a very good idea (this is witnessed for example by the fact that a class cannot be ((included)), despite that (({Class < Module}))) :).
=end
#6
[ruby-core:48652]
Updated by Alexey Muranov almost 4 years ago
#7
[ruby-core:48654]
Updated by Nick Sutterer almost 4 years ago
=begin
Interesting points, mates. I don't know about the method tables so all I can do is summarizing what we came up with so far.
== 1. Explicitely define inheritable class methods.
module M
inclusive/inheritable
def self.i_will_be_inherited
When then included, this method will be inherited. This would solve most problems as
inclusive/inheritable
def self.included(..)
would mean that the #included method itself can be made inheritable!
== Explicitely inherit when including
If we had a new #include! method we inherit all (?) class methods.
module M
def self.m
end
module U
include! M
# class method #m is now around.
end.
=end
#8
[ruby-core:48656]
Updated by Alexey Muranov almost 4 years ago
apotonick (Nick Sutterer) wrote:.
If i understood correctly, Thomas suggested the
include! method name simply to not change the current behavior of
include, but it seems that he also prefers a single method.
I do not think that in your example the method
m should be callable on
U because i think it is really a personal method of
M not intended for inclusion. This is why i suggested to have a separate space (object/table/module/etc) where to keep methods intended for inclusion as class methods. But i think this is a huge feature request, which may bring into question even the relationship
Class < Module. I wonder what the core developers would say.
However it seems to me that if it is possible to implement this "single instance/class method inclusion", the end user of a gem would do exactly as before: simply call
include (or
meta_include, but it can be called
include as it wouldn't conflict with current
include). The fine tuning by the developer should be possible by choosing which methods to declare as "includable instance methods" and "includable class methods".
#9
[ruby-core:48657]
Updated by Nick Sutterer almost 4 years ago
#10
[ruby-core:48658]
Updated by Alexey Muranov almost 4 years ago
apotonick (Nick Sutterer) wrote:
I am sorry, i used your thread to propose my own feature request in a sense, i have already corrected this with #7250. I hoped that maybe there would be no need for inheritable
self.included if "class-level includable" methods could be defined in a module, and if including one module in another would treat those methods appropriately.
"Inheritable self.included" seems a confusing concept for me, because modules do not inherit from one another. I even think that including a module in a class and including a module in a module are different operations which maybe should have been called differently.
I propose roughly the following diagram and behavior:
module
personal_singleton_methods
includable_instance_methods
includable_class_methods
class
personal_singleton_methods
instance_methods
object
personal_singleton_methods
Writing
module M; end
module N
include M # not the same as including a module into a class with respect to includable_class_methods
end
class C < AnAncestor
include N # not the same as including a module into a module with respect to includable_class_methods
end
would result in having pointers
N.includable_instance_methods -> M.includable_instance_methods
N.includable_class_methods -> M.includable_class_methods
and hidden inheritance
C < N_proxy_for_C < M_proxy_for_C < AnAncestor
where N_proxy_for_C has N.includable_instance_methods for its own instance methods and has N.includable_class_methods for its own class methods.
These are rough ideas, i am not familiar with Ruby implementation details.
#11
[ruby-core:48875]
Updated by Yukihiro Matsumoto almost 4 years ago
Oops, I made mistakes.
I am positive about the change, but I have concern about compatibility.
Maybe we should provide a new method, but I cannot think of any good name right now.
Matz.
#12
[ruby-core:49943]
Updated by Yusuke Endoh almost 4 years ago
- Status changed from Open to Feedback
- Target version set to next minor
#13
[ruby-core:62083]
Updated by Brian Katzung over 2 years ago
I'm a relatively new Ruby programmer so I may have missed some of the nuances, but I have written that I believe satisfies the original posting requirements.
In a nutshell:
require 'extended_include' module A # ... include_class_methods # (module=ClassMethods, ...) -OR- include_class_methods do def cm; "Well I'll be a class method!!!"; end end # (A.extend Extended_Include to get ::included is automatic) end module B extended_include A # include + arrange to chain A's ::included (if present and base needs it) in ours def self.included (base) # Only if we need to do something beyond Extended_Import::included super base rescue nil # Let Extended_Include extend and chain # Do something more... end end
If somebody more experienced would like to look it over, I would love some feedback.
Also available in: Atom PDF | https://bugs.ruby-lang.org/issues/7240 | CC-MAIN-2016-40 | refinedweb | 1,815 | 62.48 |
differences between cell spacing and cell padding
differences between cell spacing and cell padding What are the differences between cell spacing and cell padding
Plz Provide correct program code for all questions.
Plz Provide correct program code for all questions.
Write a program to find the difference between sum of the squares and the square of the sums of n numbers?
Develop a program that accepts the area of a square
Ask JavaFX Questions Online
Ask JavaFX Questions Online
Ask programming questions related... as our visitor can answer your questions.
JavaFX
Event helpers
between it and '.bind()' is that it will execute only once .After...
Event helpers
Event helpers
As we all know events are actions or occurrences
BoxLayout spacing
Java NotesBoxLayout spacing
Fillers - struts, glue, rigid areas... space between components. The most useful
are struts (or rigid areas). Glue may... horizontal and vertical size.
Glue is an expandable component. Used if you want spacing
Ask Questions with Options
Ask Questions with Options using Java
In this section, we are going to ask five questions one after the other with four options to test the user. For this, we have stored 5 questions, answers with four options into a list. The list
JavaFX
JavaFX
JavaFX 3D Effect Example
We can create an Object in JavaFX and can give him 3D Effect (like Creating Sphere with Circle and 3D text
Java event-listener
Java event-listener What is the relationship between an event-listener interface and an event-adapter class
javaFx technology
javaFx technology how to call a Form to another Form in javaFx programme
and need a proper professional guide with example for javaFx technology
plz send as soon as possible
difference between marker and tag interface - Java Interview Questions
difference between marker and tag interface what is the difference between marker interface and tag interface? Hi friend,
nterface..., SingleThreadModel, Event listener. Marker Interfaces are implemented by the classes
delegation event model
delegation event model What is delegation event model?
delegation event model
In the event-delegation model, specific objects are designated as event handlers for GUI components. These objects implement event
JavaFX deployment in Jboss
JavaFX deployment in Jboss Hi,
How to deploy javafx application into JBoss
Identify correct and incorrect conditional expressions,
BETWEEN expressions, IN
expressions, LIKE expressions, and
comparison expressions.
Identify correct and incorrect conditional expressions,
BETWEEN expressions, IN
expressions, LIKE expressions, and
comparison...;
Identify correct and incorrect conditional expressions
How to raise an event on a flash mp3 player after 30 seconds from starting song..?
How to raise an event on a flash mp3 player after 30 seconds from starting song..? Can you help me for writing a couple of codes in action script...) with full source code (.fla, .swf, .js) files. I need to raise an event and call
XML response correct in broser but incorrect in Java
XML response correct in broser but incorrect in Java Firs of all I... is not correct.
In browser shows me (correct):
<ENELIT>
<GESI>...">
</head>
<body>
<SCRIPT FOR=window EVENT=onload
PHP GD image gamma correct
<?php
$im = imagecreatefromjpeg('im.jpg');
imagegammacorrect($im,
1.0, 1.537);
imagejpeg($im,
'php_gamma_corrected.jpeg');
echo("Image
corrected and saved successfully.");
imagedestroy($im);
?>
After
Hibernate Event System
Hibernate Event System
In this tutorial you will learn about the Event system in Hibernate.
As concerned to Event it can be said that Event has replace... pre-requisite
or post-requisite operations before or after the functional logic
set background image in javafx
set background image in javafx Hi,
How to add backgroung image in javafx integrated with jswing
questions
questions difference between lazy=true and lazy=false? with brief explanation
JavaFX
what is the difference between the eclipse and myeclipse - IDE Questions
what is the difference between the eclipse and myeclipse what is the difference between the eclipse and myeclipse Hi Friend,
Difference:
Eclipse is an IDE or platform for developing, whereas MyEclipse
JavaFX
JavaFX
...;
Emergence of
JavaFX
JavaFX began as a project by
Chris Oliver... making GUI programming easier in general.
JavaFX Mobile
JavaFX
JavaFX
JavaFX
: New Paradigm in Rich Internet Applications... Microsystems announced JavaFX, a family of products based on Java
technology to create Rich Internet applications (RIAs).
JavaFX: Sun?s New Product Family
Event Handling In Java
a simple example into which you
will see how an event generated after clicking...Event Handling In Java
In this section you will learn about how to handle... that happens and your
application behaves according to that event. For example
Difference between C++ and Java - Java Interview Questions
Difference between C++ and Java Basic difference between C... was derived from C++ but still there is big difference between these two... am going to give you few differences between these two...1. Java does not support
JavaFX issue - Java3D
JavaFX issue Hi all,
I developed a widget in JavaFX using Netbeans6.1. I added the following line to disable the background frame view
fill: null
fill:Color.TRANSPARENT
}
visible: true
windowStyle
Understanding the jQuery event handling mechanism
Understanding the jQuery event handling mechanism
Understanding the jQuery event handling mechanism
First of all , you need to know -What is an event
jQuery blur event
jQuery blur event
In this tutorial , we will discuss how to handle blur event... inside or change text
of the first input field and after it, you click on any other elements in
the page ,it shows an alert box .The blur event is sent
JavaFX 3D Effect Example
JavaFX 3D Effect Example
Working with java Collections class
In this section... size adding and removing items even after
the Vector has been created
Questions and Answers Help
Questions and Answers Help
...
features of the questions posting form
You can ask questions in and provide...-example.html
Ask
Questions | Browse Latest
Questions and Answers
JavaFX
JavaFX
New
Paradigm in Rich....
Emergence
of JavaFX
JavaFX
Event handler for Visual Component in Flex 4
Event Handler for Visual Components in flex4:
Flex are provide event driven... and after that something
change occur in the appearance of the component life cycle or change in the
interface. This is alled Event. Flex provide the ability
how to use mysql event scheduler in hibernate
how to use mysql event scheduler in hibernate Hi all,
I am creating... that when i update something it has to reflect in database after specific interval of time, i need to use mysql event scheduler
My query is like this
create event
Return Value From Event - Java Beginners
Return Value From Event I would like to call a method that returns a value after an event has occurred and the value is determined by the event or listener.
eg:
public int mymethod()
{
static int value=0;
KeyAdapter
The scroll browser event of jQuery
The scroll browser event of jQuery
In this tutorial ,we will print message on browser's window scrolling using
scroll browser event of jQuery... scrolling :
After scrolling :
Download Source Code
Click
here to see demo
Difference between ServletContext and ServletConfig
Difference between ServletContext and ServletConfig What is the difference between ServletContext and ServletConfig?
ServletContext... .
ServletConfig : The object created after a servlet is instantiated and its
Event Dispatcher Thread
Event Dispatcher Thread
In the tutorial Java Event Dispatcher thread in Graphics... is going to show you Event Dispatcher thread that will wait for the
events
combobox cannot be resolved in JavaFX
Printing the integers before and after - JSP-Servlet
the integers before and after generated random number, and also stating...}
<c:ifIt is an even number and it is between and
It is an odd number, and it is between and
Hi Friend - Java Interview Questions
?
Interfaces form a contract between the class and the outside world... are implemented with the correct signature.Interfaces provides the ability
INTERFACE - Java Interview Questions
INTERFACE Why Use Interface in Java?i want region ?plz post answer Hi Friend,
Interfaces form a contract between the class... the methods of the interface are implemented with the correct signature.Interfaces
Ask iBatis Questions Online
Ask iBatis Questions Online
... and persistence API that automates the mapping between SQL databases and objects... between the classes and the tables that let the developers map freely between
JavaFX Mobile
JavaFX Mobile
I.
JavaFX Mobile
JavaFX Mobile is a complete mobile..., JavaFX Mobile enables control and flexibility for the mobile
ecosystem
Identify correct and incorrect statements or examples about the purpose and
use of EJB QL.
;Home Identify correct and incorrect conditional expressions,
BETWEEN...
Identify correct and incorrect statements or examples about...;Next
Identify correct and incorrect statements
what is difference between jdk1.5 and jdk1.6 - JSP-Interview Questions
what is difference between jdk1.5 and jdk1.6 what is difference between the jdk1.5 and jdk1.6 in java Hi Friend,
1)Java 1.6 runs faster than Java 1.5.
2)Java 1.6 makes programming easier by implementing various
Java interview questions
Java interview questions Plz answer the following questions... | 8 = ?
a. 8
b. 27
c. 19
d. 35
Identify the statements that are correct... code: int x, y, z;
y = 1;
z = 5;
x = 0 - (++y) + z++;
After execution
Event on Slide bar In Java
Event on Slide bar In Java
Introduction
In this section, you will learn about the event... is stayed in between both slide bar. When you drag the
horizontal slide bar
Clear the print button after onclicking the print - Ajax
correct answer....
pls clear the print and ok button when after onclicking...Clear the print button after onclicking the print var disp_setting="toolbar=no,location=no,directories=no,menubar=n0,";
disp_setting+="scrollbars
java - Java Interview Questions
difference between these two is that interface have all the methods abstract while... form a contract between the class and the outside world, and this contract... are implemented with the correct signature.Interfaces provides the ability to quickly
C interview questions
C interview questions Plz answer the following questions... = myArray;
Which of the following is the correct way to increment the variable "ptr...'%'!\"\n");
/question number 8/
What is a difference between a declaration
jsp interview questions
jsp interview questions what is difference betwen and ?
Difference between jsp:include and jsp:forward
jsp:include , includes the page... the forwarded page is called immediately after
servlet - Servlet Interview Questions
. This will reduce the time gap between request and response. And along with that we... in the application, immediately after container got started.
Example
Exception - Java Interview Questions
correct your question, nothing personal. Now here your answer which is very simple...( eg. Dfsdfgd{character}) then after compiling when we run our java program
What is difference between TRUNCATE & DELETE
What is difference between TRUNCATE & DELETE What is difference between TRUNCATE & DELETE?
Hi,
The DELETE command is used.... If no WHERE condition is specified, all rows will be removed. After performing
event handling
event handling diff btwn event handling in ASP.net and in HTML
JSF Interview Questions
JSF Interview Questions
....
They program objects, event handling, converters, validators. ... like input validation,
component-state management, page navigation, and event
After changing url params d req checkboxes are not showing as clicked in jsf programming - Java Server Faces Questions
After changing url params d req checkboxes are not showing as clicked in jsf programming Hi,
Here i have Library.java file (collected from Jboss richfaces)
There is having a list of artist .
If u click on a particular
servlets - Servlet Interview Questions
servlets hai this is jagadhish.
Iam preparing servlets.My question is,what is the difference between servletcex and servletconfig(full flezed... is deployed and after that only the context is available
to each servlet in the web
Match the correct description about purpose and function to which session bean type
they apply: stateless, stateful, or both.
Match the correct description about purpose and function to which...;
Match
the correct description about purpose and function....
There is no fixed mapping between clients
jQuery change event with multiple select option
jQuery change event with multiple select option
In this tutorial , we will discuss about 'change' event of jQuery with
multiple select list &... is given, when we select any option/options a change
event is triggered
JavaFX Scripting Language
JavaFX Scripting Language
II.
JavaFX Scripting
Language
JavaFX Script... authors.
In layman style - JavaFX
lets you enjoy a consistence user experience
Difference Between Servlet and JSP
Difference Between Servlet and JSP
In this section we will describe... the differences between Servlet and JSP.
Servlet
Servlet is a Java class that is usually... other. Here I will write a Servlet and JSP for
producing the output. After
Free Java Is it correct?
Free Java Is it correct? Hi,
Is Java free? If yes then where I can download?
Thanks
Hi,
You can download it from
Thanks
Identify correct and incorrect statements or examples about the client's view
of exceptions received from an enterprise bean invocation.
Identify correct and incorrect statements or examples about...;
Identify correct and incorrect statements or examples about the client's view... be thrown by the Container OR
by the communication subsystem between
Identify correct and incorrect statements or examples about the rules and
semantics for relationship assignment and relationship updating in a CMP bean.
Identify correct and incorrect statements or examples about... for Container-Managed Persistence (CMP) Next
Identify correct... relationship between field "person" and "telephones", adding a
"telephone
Correct errors - Java Beginners
Correct errors Identify and correct the errors in the following program:
public java Method
{
public static method1(int n, m)
{
n += m;
xMethod(3. 4);
}
public static int xMethod(int n)
{
if (n > 0) return 1
PHP and MySQL BETWEEN dates with different years
PHP and MySQL BETWEEN dates with different years I have a database which holds a bunch of events. Each event has a start date and an end date, so they should only show on the site when the date chosen falls between those dates
Identify correct and incorrect statements or examples about an entity bean's
primary key and object identity.
Identify correct and incorrect statements or examples about.... Entity Beans Next
Identify correct... by means of a set method on any of
its cmp-fields after it has been set
Difference between Struts and Spring
To know the difference between Struts and Spring, we must first explain... at runtime that reduces the coupling between various modules.
Spring provides... and invoke interceptors. Interceptor are invoked before and after
the action
Diff b/w servlet n jsp - Java Interview Questions
Diff b/w servlet n jsp hii
i want to know the difference between servlet and jsp. please give me the details to understand them in correct... for presentation after all JSP page also boil down to jsp servlet but presentation
please correct this program
please correct this program import java.util.Scanner;
public class Nam
{
public static void main (String arg[])
{
String[] name={"Aki","Karthi","Tk","Suba","Malu","Buvi","Janu","Sara","Sandy","Abi","Ani","Amu
correct the sql error
correct the sql error i am getting a SQL Error while retriving data from access to jframe called "datatype mismatch in criteria expression" plez do help me and studentId's datatye is number......
private void
Click event
Click event hi............
how to put a click event on a particular image, so that it can allow to open another form or allow to display result in tabular form????????/
can u tell me how to do that????????/
using java swings
Identify correct and incorrect statements about the Application Assembler's
responsibilities, including the use of deployment descriptor elements related to
transactions and the identifica
Identify correct and incorrect statements about the Application Assembler's...;
Identify correct and incorrect statements about the Application Assembler's... to
differentiate between methods with the same name and signature
Corejava Interview,Corejava questions,Corejava Interview Questions,Corejava
Core Java Interview Questions Page3
... between a data store
and a database ?
Ans :
Generally the term data store is used... iterator.
Q 7. How can I insert a new row between two
others ?
Ans
After authentication and connection establishmenr, Upload a zipfile by chunks in java
After authentication and connection establishmenr, Upload a zipfile by chunks... java. After authentication, I made use of those cookies to upload the file [My... chunk upload [Am not sure whether this idea is correct or not], so the file
After authentication and connection establishment, Upload a zipfile by chunks in java
After authentication and connection establishment, Upload a zipfile by chunks.... After authentication, I made use of those cookies to upload the file [My... chunk upload [Am not sure whether this idea is correct or not], so the file
difference between main thread and child thread?
difference between main thread and child thread? any one give correct exact difference.
in jsp 7 implicit objects are available those are
1:response->This denotes the data included with the HTTP Response.
2
Servlet Interview Questions
Servlet Interview Questions
Collection of large number of Servlet Interview Questions. These questions
are frequently asked in the Java Interviews.
Question: What
Difference between extends thread class vs implements runnable interface - Java Interview Questions
Difference between extends thread class vs implements runnable interface Hi Friends, can you give difference between extending thread class and implementing runnable interface. Hi Friend,
Difference:
1)If you | http://www.roseindia.net/tutorialhelp/comment/97263 | CC-MAIN-2013-48 | refinedweb | 2,859 | 54.93 |
Learn how easy it is to sync an existing GitHub or Google Code repo to a SourceForge project! See Demo
Bugs item #3293371, was opened at 2011-04-26 23:38: omit-frame-pointer still generates prolog
Initial Comment:
The following trivial example code:
int
func(int a)
{
return (a * 2);
}
when compiled with "sdcc -mz80 --fomit-frame-pointer --no-peep -c omit_fp.c" generates this:
_func_start::
_func:
push ix
ld ix,#0
add ix,sp
;omit_fp.c:4: return (a * 2);
ld iy,#4
add iy,sp
ld l,0 (iy)
ld h,1 (iy)
add hl,hl
00101$:
ret
_func_end::
The epilog (of "pop ix") is correctly omitted, but the prolog of push ix, etc... is still present. Thus, 8 redundant bytes per function are wasted (as ix is calculated but never referenced), and the saved ix is not popped, so the ret at 00101$ will jump to somewhere "random" based on the previous contents of ix.
Trying to run code produced like this produces strange results instantly (ranging from a "crash" to a coincidental loop round garbage in memory). However, as this seems to be such a fundamental problem with the option, I would guess that nobody actually uses it. Indeed, I only turned it on "for a laugh" to see how much larger the code would become. Thus it's by no means a high priority (as I don't intend to use it myself, but wanted to report the error).
Compiler used:
SDCC : z80 3.0.2 #6468 (Apr 26 2011) (Solaris i386)
----------------------------------------------------------------------
>Comment By: Brian Ruthven (u6c87)
Date: 2011-05-05 12:21
> Brian, you're wrong here in describing the use case. The Z80 uses IX as
> frame pointer and this CAN be used for other indexed actions, so it
could
> make sense to have this option.
What I meant was this:
, on x86, you can read directly from the %rsp+offset if you wanted to, so
you can dispense with setting up %rbp as the frame and use it for something
else. On Z80, you cannot do this with sp directly, hence use of the ix
----------------------------------------------------------------------
Comment By: Maarten Brock (maartenbrock)
Date: 2011-05-05 11:13
> --fomit-frame-pointer is currently the only way to tell sdcc not to use
the iy register.
I assume you mean IX here.
optralloc gen.c:4105
if(!_G.omitFramePtr)
is half of the fix. But
gen.c:4116
emit2 ("!enterx", sym->stack);
also needs to be fixed IMHO with
if (_G.omitFramePtr)
emit2 ("!ldaspsp", -sym->stack);
else
emit2 ("!enterx", sym->stack);
As well as
gen.c:4119
emit2 ("!enter");
if (!_G.omitFramePtr)
emit2 ("!enter");
Then gen.c:2371 (aopGet)
else
should be
else if (_G.omitFramePtr)
{
setupPair (PAIR_IX, aop, offset);
dbuf_tprintf (&dbuf, "!*ixx", offset);
}
else
Then with these fixes many regression tests fail and the first one
(addsub) destroys HL in testAdd() for result += 0xab00;
Brian, you're wrong here in describing the use case. The Z80 uses IX as
frame pointer and this CAN be used for other indexed actions, so it could
make sense to have this option.
So, Philipp, shall I commit these changes even though it fixes only half
the problem?
----------------------------------------------------------------------
Comment By: Philipp Klaus Krause (spth)
Date: 2011-05-05 10:19
This bug seems to have been at least partially fixed in the optralloc
branch some time ago (at least I cannot reproduce it with a small example,
such as the one the OP gave).
However many (about one in twenty or so) regression tests fail when when
using --fomit-frame-pointer.
I remember that the z88dk folks were experimenting with using sdcc as
their underlying compiler some time ago. AFAIR they used
--fomit-frame-pointer and got some applications to work.
Philipp
----------------------------------------------------------------------
Comment By: Philipp Klaus Krause (spth)
Date: 2011-05-05 10:11
Sorry, but IMO we still need this. AFAIR it worked somehow not too long
ago.
--fomit-frame-pointer is currently the only way to tell sdcc not to use
the iy register. Unfortunately some OS designers have made the bad choice
of reserving ix for OS or interrupt routine use, thus applciations meant to
be run under these OS are not allowed to touch ix (it'S similar for iy,
that's why I introduced --reserve-regs-iy some time ago).
Philipp
----------------------------------------------------------------------
Comment By: Brian Ruthven (u6c87)
Date: 2011-05-05 09:53
>From my point of view it was academic interest.
Given the limited scope of this, and the severe brokenness on z80
(combined with the increase in both code size and execution time), I would
have to conclude that nobody is actually using it, and it's probably better
to simply remove it.
Having an "omit-frame-pointer" option would probably make sense on
architectures where there is a dedicated stack pointer register which can
be used for indexed operations (like x86 and SPARC) and thus omitting the
frame pointer can free up another register. This certainly isn't the case
on Z80 (I can't say for the other architectures that SDCC supports), so I'd
be happy just dropping the option completely. I can't believe anybody else
is actually using it given the broken code it generates!
----------------------------------------------------------------------
Comment By: Maarten Brock (maartenbrock)
Date: 2011-05-04 20:46
I made an attempt to fix this, but after the stack frame was fixed it
failed register allocation in the regression tests.
Next I looked where this option is actually used and it hardly seems to
be.
The hc08 port sets the flag but doesn't use it.
The pic16 port uses it to setup/restore the framepointer but not for
access to the stack frame.
Only the z80 uses it and that is severely broken.
Now my question is: is this option useful or only of academic interest? Or
in other words: are we going to try to fix this or is it better to just
remove it? In the latter case I will remove my local patches instead of
committing them.
Maarten
----------------------------------------------------------------------
You can respond by visiting:
View entire thread | http://sourceforge.net/p/sdcc/mailman/message/27456212/ | CC-MAIN-2015-18 | refinedweb | 1,012 | 68.7 |
Create Intents, Utterances, and Slots
This document describes how you create the intents, slots, and sample utterances for your skill. An intent represents an action that fulfills a user's spoken request. Intents can optionally have arguments called slots. The sample utterances are set of likely spoken phrases mapped to the intents.
- Create a New Custom Intent
- Identify the Slots for the Intent
- Assign Slot Types to Your Slots
- JSON for Intents and Utterances (Interaction Model Schema)
- Related Topics utterances like this::
To create a new custom intent:
- From the left-hand sidebar, click Add next to Custom > Interaction Model > Intents.
- Select the Create custom intent option.
- Enter the name of the new intent and click Create."
- Sample utterances must be unique. You cannot have duplicate sample utterances mapped to different intents.
- Identify the slots in the utterances as described below.
The Alexa Skills Kit includes a large library of built-in intents you can use instead of creating your own. You do not need to write the utterances for these intents, thus simplifying development.
You can search the full built-in intent library from within developer console. Create a new intent as described above, but select the Use an existing intent from Alexa's built-in library option. Click Add Intent for each built-in intent to add.
Intent Name Requirements
The name of the intent can only contain case-insensitive alphabetical characters and underscores. No numbers, spaces or special characters are allowed. Intent names cannot overlap with any slot names in the schema.
Note that the built-in intents use the
AMAZON namespace, so they are specified using a period, like this:
AMAZON.HelpIntent. This notation is only valid for specifying the
AMAZON namespace. Periods should not be used in other intent names.
For example,
GetZodiacHoroscopeIntent is valid, while
Get Zodiac Horoscope Intent,
Zodiac.GetHoroscopeIntent and
Get2015HoroscopeIntent are invalid.
Rules for Sample Utterances
Follow these rules when you write your sample utterances.").
Identify the Slots for the Intent
Once you have written a few utterances, note the words or phrases that represent variable information. These will (
{ }):
- Click an intent in the left-hand navigation to open the detail page for the intent.
- In an utterance, highlight the word or phrase representing the slot value.
In the drop-down that appears, enter a name for the slot in the edit box and click Add. section below the sample utterances. When you highlight a word or phrase in an utterance, you can add a new slot or select an existing slot.
For example, the set of utterances shown earlier would now look like this: the user input is handled and passed slot types:
- Click an intent in the left-hand navigation to open the detail page for the intent.
In the Intent Slots section below the sample utterances, click the Select a slot type menu.
You can also open the detail page for the slot: in the left-hand navigation,.
- Be sure to click Save Model to save the slot type changes.
JSON for Intents and Utterances (Interaction Model Schema)
You can see.
This} " ] } ] } } } | https://developer.amazon.com/de/docs/custom-skills/create-intents-utterances-and-slots.html | CC-MAIN-2018-26 | refinedweb | 514 | 56.96 |
MVC 3 is becoming hugely popular thanks to Razor and the Helpers that make building web applications much easier. One of the common requirements in web development, both with web forms as well as MVC based development, is the cascading dropdownlist. Now, for Web Forms, we can use a variety of options viz. server side programming, jQuery or using the AJAX Control Toolkit’s cascading dropdownlist control for accomplishing this.
I saw a few samples on the internet that used the erstwhile Microsoft AJAX Library along with MVC and also few more samples which used hard coded values for wiring up the cascading dropdown. I have built this sample using Database with 3 tables i.e. Cars, Makes & Colours. The colours table is actually redundant but for the sake of showing a 3 dropdown hierarchy I have made it a relational table – just for the purpose of the sample. Also, all the cars mentioned are the brands that I could recollect and driven around in India
To begin with, lets examine the Database – CascadeSample. It has 3 tables
i. Cars
ii. Models
iii. Colours
I filled in some sample data. At the end of this post, I would provide link for downloading the database scripts as well as the solution.
First, lets create our MVC 3 Application using “File – New Project – ASP.NET MVC 3 Web Application” give it a name “CascadingDropdownSample” and select the “Internet Application” and click ok. This would create the basic scaffolding structure with Membership API. We won’t need it though.
As always with MVC, lets build the Model by right click Models Folder – Add – New Item and search for ADO.NET Entity in the search box of the Dialog.
Chose the ADO.NET Entity Data Model Template and give it a name CarModel.edmx and click Add.
Choose the “Generate from Database” option and in the Next steps, connect to the CascadeSample database and select all the 3 tables and then finish the steps to generate the Entity Model. Our Entity Model is now ready.
Next step is to start wiring up the Controller Actions. For the purpose of this simple demo, lets just use the default HomeController.
Lets add using CascadingDropdownSample.Models; to the namespaces in the HomeController.
Lets add CascadeSampleEntities cse = new CascadeSampleEntities(); within the class
Lets add the following within the Index Action.
public ActionResult Index()
{
ViewBag.Cars = cse.Cars.ToList();
ViewBag.Models = cse.Models.ToList();
ViewBag.Colours = cse.Colours.ToList();
return View();
}
Lets switch to the View (ROOT – Views – Home – Index.cshtml) and edit it to look as follows:-
@model CascadingDropdownSample.Models.CascadeSampleEntities
@{
ViewBag.Title = "Home Page";
}
<h2>Cars</h2>
<p>
@Html.DropDownListFor(Model => Model.CarId, new SelectList(ViewBag.Cars as System.Collections.IEnumerable, "CarId", "CarName"),
"Select a Car", new { id = "ddlCars" })
</p>
When we run the page, we will get to see the List of cars in the dropdown.
For the next set of actions i.e. populating the Model and Colour, we need the following Methods.
private IList<Model> GetModels(int id)
{
return cse.Models.Where(m => m.CarId == id).ToList();
}
private IList<Colour> GetColours(int id)
{
return cse.Colours.Where(c => c.ColourId == id).ToList();
}
The next main thing we need is Action methods which can send a JSon Result for both Models and Colours.
To first get the Models by car, we add the following to the HomeController
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult LoadModelsByCar(string id)
{
var modelList = this.GetModels(Convert.ToInt32(id));
var modelData = modelList.Select(m => new SelectListItem()
{
Text = m.ModelName,
Value = m.ModelId.ToString(),
});
return Json(modelData, JsonRequestBehavior.AllowGet);
}
and to get the Colours for the various Models, we add
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult LoadColoursByModel(string id)
{
var colourList = this.GetColours(Convert.ToInt32(id));
var colourData = colourList.Select(c => new SelectListItem()
{
Text = c.ColourName,
Value = c.ColourId.ToString(),
return Json(colourData, JsonRequestBehavior.AllowGet);
}
Finally, we need to add the following jQuery handlers for the dropdownlist selection changed
<script type="text/javascript">
$(document).ready(function () {
$("#ddlCars").change(function () {
var idModel = $(this).val();
$.getJSON("/Home/LoadModelsByCar", { id: idModel },
function (carData) {
var select = $("#ddlModels");
select.empty();
select.append($('<option/>', {
value: 0,
text: "Select a Model"
}));
$.each(carData, function (index, itemData) {
select.append($('<option/>', {
value: itemData.Value,
text: itemData.Text
}));
});
});
});
$("#ddlModels").change(function () {
var idColour = $(this).val();
$.getJSON("/Home/LoadColoursByModel", { id: idColour },
function (modelData) {
var select = $("#ddlColours");
select.empty();
select.append($('<option/>', {
value: 0,
text: "Select a Colour"
}));
$.each(modelData, function (index, itemData) {
select.append($('<option/>', {
value: itemData.Value,
text: itemData.Text
}));
});
});
});
});
</script>
And then add the dropdowns for Model and Colour
<p>
@Html.DropDownListFor(Model => Model.Models, new SelectList(Enumerable.Empty<SelectListItem>(), "ModelId", "ModelName"),
"Select a Model", new { id = "ddlModels" })
</p>
<p>
@Html.DropDownListFor(Model => Model.Colours, new SelectList(Enumerable.Empty<SelectListItem>(), "ColourId", "ColourName"),
"Select a Colour", new { id = "ddlColours" })
</p>
And then, when we build and run we can get to choose the Car, Model and Make, a cascading dropdown built using jQuery and MVC 3
I have uploaded the Visual Studio 2010 Solution as well as the Scripts for the CascadeSample Database to
Feel free to download and use it for your projects
Also, do share if you find better ways to implement the same.
Cheers!!
Print | posted on Tuesday, June 14, 2011 4:47 PM | http://geekswithblogs.net/ranganh/archive/2011/06/14/cascading-dropdownlist-in-asp.net-mvc-3-using-jquery.aspx | CC-MAIN-2014-52 | refinedweb | 873 | 52.15 |
United Technologies Corp (Symbol: UTX). So this week we highlight one interesting put contract, and one interesting call contract, from the January 2018 expiration for UTX. The put contract our YieldBoost algorithm identified as particularly interesting, is at the $77.50 strike, which has a bid at the time of this writing of 85 cents. Collecting that bid as the premium represents a 1.1% return against the $77.50 commitment, or a 1.3% annualized rate of return (at Stock Options Channel we call this the YieldBoost ).
Turning to the other side of the option chain, we highlight one call contract of particular interest for the January 2018 expiration, for shareholders of United Technologies Corp (Symbol: UTX) looking to boost their income beyond the stock's 2.3% annualized dividend yield. Selling the covered call at the $120 strike and collecting the premium based on the $3.80 bid, annualizes to an additional 4% rate of return against the current stock price (this is what we at Stock Options Channel refer to as the YieldBoost ), for a total of 6.3% annualized rate in the scenario where the stock is not called away. Any upside above $120 would be lost if the stock rises there and is called away, but UTX shares would have to advance 5.5% from current levels for that to happen, meaning that in the scenario where the stock is called, the shareholder has earned a 8.9% return from this trading level, in addition to any dividends collected before the stock was called.
Top YieldBoost UT. | http://www.nasdaq.com/article/interesting-january-2018-stock-options-for-utx-cm763018 | CC-MAIN-2017-13 | refinedweb | 262 | 64.91 |
Microsoft has a lot of fascinating APIs available to build intelligent applications with using their Cognitive Services. Among those services is the Text Analytics API. This API offers a wide range of valuable text-based functionality such as sentiment analysis and key phrase extraction.
With these useful APIs available, what could be a better means of utilizing them than incorporating them into a small app? The goal of this app will be to take data from Twitter and run it through some of the Text Analytics APIs to see if we can get some insights into what people are saying about Wintellect. In this post, I’ll be using Python to get Twitter data as well as call the Text Analytics API to extract our insights.
As usual, the notebooks for this post are available on GitHub: retrieving Twitter data and calling the API to detect languages. The API keys will be stored in a separate JSON file local to the application, but it will not be checked in. With that being said, you’ll have to create a JSON file and fill it in with your keys to enable the API functionality.
Getting Twitter Data
Instead of handling the Twitter API directly, we will make it easier on ourselves to get the data by using the
tweepy package. The two things we will do with the package are, authorize ourselves to use the API and then use the search API.
Let’s go ahead and get our imports loaded.
import tweepy import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import numpy as np sns.set() %matplotlib inline
Twitter Authorization
To use the Twitter API, you must first register to get an API key. To get
tweepy just install it via
pip install tweepy. The
tweepy documentation is best at explaining how to authenticate, but I’ll go over the basic steps.
Once you register your app you will receive API keys, next use
tweepy to get an
OAuthHandler. I have the keys stored in a separate config file as mentioned earlier.
auth = tweepy.OAuthHandler(config["twitterConsumerKey"], config["twitterConsumerSecretKey"])
Now that we’ve given
tweepy our keys to generate an
OAuthHandler, we will now use the handler to get a redirect URL. Go to the URL from the output in a browser where you can allow your app to authorize to your account so you can get access to the API.
redirect_url = auth.get_authorization_url() redirect_url
Once you’ve authorized your account with the app, you’ll be given a PIN number. Use that number in
tweepy to let it know that you’ve authorized it with the API.
auth.get_access_token('pin number')
Now that you’ve authorized your app to your account you can now use
tweepy to get an instance of the API.
api = tweepy.API(auth)
With an instance of the API made available by
tweepy, we can start using the API to perform a search for data.
Search API
Calling the search API is quite easy with
tweepy.
wintellect_search = api.search("Wintellect")
If we look at the variable
wintellect_search, we can see that it has a data type of
tweepy.models.SearchResults. And if we check out the documentation, it tells us that the
search method returns a
list so that we can iterate on the search results. Before we do that though, let’s see what attributes we can use on one of the
SearchResults objects. We can do that with the built in Python function
dir.
dir(wintellect_search[0])
In reviewing the results of the
dir function, a few useful attributes can be spotted including
text,
author, and
created_at. To get those for each tweet, we’ll loop through the search results and extract those attributes into a dictionary. We’ll also check if the tweet is a retweet. Since retweets can add noise to our data, we won’t include them here.
search_dict = {"text": [], "author": [], "created_date": []} for item in wintellect_search: if not item.retweet or "RT" not in item.text: search_dict["text"].append(item.text) search_dict["author"].append(item.author.name) search_dict["created_date"].append(item.created_at)
Now that we have a dictionary of our results, we can use
pandas to convert the dictionary into a data frame.
df = pd.DataFrame.from_dict(search_dict) df.head()
Next, we can determine the size of our data set by calling the
shape attribute on the data frame.
df.shape
Not a lot of data, but it’s enough for us to work with.
Language Detection API
One piece of information that can be extracted with the Text Analytics API is the language of the text. Before the Text Analytics API can be used, an API key must be created. To get an API key, go to the Text Analytics API page and click on “Try Text Analytics API” and from there, in the Text Analytics API row, click “Get API Key”. Now you’re ready to get some insights from text!
The Text Analytics API has great documentation, and it helps us out by giving us a URL to use for calling the API. This URL is only a quick start URL that we can use to play around with the API. If we were to use this URL in a production application that would involve a lot more requests to the API, we would need to go to Azure and set this up on our own.
But for our purposes, the quick start URL is a useful starting place. To call the API, we’ll be using the
requests package, which makes it very easy to make web requests and does a better job than what’s built into Python.
import requests text_analytics_language_url = ""
The documentation also gives us a structure for the data that the API expects. Since our data is in a
pandas data frame, we can iterate over the rows to build out the data structure. The
iterrows method returns a tuple that includes the index of the row and the row itself so that we can unpack the data structure directly in the
for loop statement.
documents = {"documents": []} for idx, row in df.iterrows(): documents["documents"].append({ "id": str(idx + 1), "text": row["text"] })
Now let’s take a look at the
documents variable to see what we have so far.
Our data structure for the API looks good, so now we can start building up the API call. The main piece we need is to supply our subscription key to a header to authorize the call. If we don’t supply this then we will get an unauthorized response.
headers = {"Ocp-Apim-Subscription-Key": config["subscriptionKey"]}
Now that the API key is set, we can now call the API.
response = requests.post(text_analytics_language_url, headers=headers, json=documents) languages = response.json() languages
It looks like most of the text is in English which is expected, however if we scroll down toward the end of our results, we’ll see something different.
Interesting, there was a tweet made in French.
Now that we have our results let’s extract what we need from it into another pandas data frame. Looking at the API documentation for the sentiment analysis, we can see that it takes in a language. From our results it appears that we can pass in the
iso6391Name, so we’ll extract that out.
detected_languages = [] for language in languages["documents"]: for detected in language["detectedLanguages"]: detected_languages.append(detected["iso6391Name"])
We can now create a data frame from the list of detected languages.
languages_df = pd.DataFrame(detected_languages, columns=["language"]) languages_df.head()
To persist the tweet and language data, let’s save them in a CSV file, so we can use this same data for in the future.
df.to_csv("./tweets.csv", index=False, encoding="UTF-8") languages_df.to_csv("./detected_languages.csv", index=False, encoding="UTF-8")
In this post, we got data from Twitter with the
tweepy package. Once we had our tweets, we used the Text Analytics API from the Microsoft Cognitive Services to detect the language of each tweet. In our next post, we’ll use the detected languages to determine what the sentiment of each tweet is. Are there more positive than negative tweets? We can find that out by continuing to use the Text Analytics API to perform sentiment analysis on each tweet. | https://www.wintellect.com/using-cognitive-services-text-analytics-api-detecting-languages/ | CC-MAIN-2021-39 | refinedweb | 1,386 | 61.97 |
We always compete in this technological world by providing our best services. One of our most prominent service is Amazon SES for sales and marketing module, where our clients are extremely happy and wants to continue their business partnership with our AWS consulting
Using Amazon SES, You can send and receive email from your verified emails and domains. SES offers email receiving for entire domains or for individual addresses within a domain.We can use other AWS services S3(to store encrypted messages in bucket), SNS topic(to process the message, lamda function).
To send, receive, process the incoming messages, we have a package called django-ses-gateway
pip install django-ses-gateway
1. You must have an AWS account and you need to verify domain in SES to confirm that we are using those domains or to prevent from others using it. Once your domain is verified, then all your emails in the domain will also be verified.
AWS_ACCESS_KEY_ID = "Your AWS Access Key" AWS_SECRET_ACCESS_KEY = "Your AWS Secret Key"
2.To use Amazon SES as your email receiver, you must create at least one active receipt rule set in which you have specified the sns topic(to route messages to an endpoint), s3 bucket(to store messages), lamda function(to process the receiving email) details.
3. After creating the rule set, for an sns topic you need to specify the list of recipients to which you want to process the message.
4. You need to subscribe to the specified SNS topic by providing your domain url(which handles email recieving) as an endpoint. You can give multiple enpoints which may either email, AWS SQS, HTTP or HTTPS.
5. In SES panel, you can also give a list of ip address to which you want reject the email receiving.
1. When user replies to an email, then it checks in the active receipt rule set(checks the specified email address, all addresses in the domain.) in the particular region.
2. If any rule set matches, then it checks against your IP address filters, and rejected if there any matches.
3. then after ses will store those messages in an crypted format using a key stored in AWS Key Management Service (KMS), publish the message to a specified SNS topic(endpoint).
1. Sending an email
from django_ses_gateway.receiving_mail import sending_mail sending_mail(subject, email_template_name, context, from_email, to_email)
Here we are sending a from_mail as <unique-identifier>@yourdomain.com. Here unique identifier will be used to process the reply to thi mail.
2. Receiving an email
from django_ses_gateway.receiving_mail import sns_notification subject, from_mail, to_mail, hash_code, mail_content = sns_notification(request.body)
Using the unique identifier(hash_code), we can easily process or store the incoming messages.
It will process your message content, will return the email subject, from mail, to email(abc@yourdomain.com), hashcode(abc) or unique-identifier, mail content.
You can view the complete documentation here.
Github Repository:... | https://micropyramid.com/blog/how-to-send-and-receive-email-with-django-amazon-ses/ | CC-MAIN-2020-05 | refinedweb | 483 | 53.71 |
JMS 101
By lindaschneider on Oct 19, 2007
Today - I'm going to start with writing a JMS 101 blog. If you've been using JMS for a long time, I will no doubt bore you to tears (I'll get to more technical stuff in the future) so you may want to simply run away now and try again on another day. If you stay on, you should be warned that my background is on the broker (our server) side of the equation so my terminology may be suspect - I learned JMS from writing tests for my software.
All of this is covered in far more detail in the JMS Specification and MQ has a whole host of sample applications and documentation from our wonderful doc writer that you can look at. I'm not going to pretend to be able to compete with the existing documents. This is the cheating version for people like me who try first and then read the documentation later.
So what do you need to know about JMS to write a simple application:
- Connection factories
- Connections
- Sessions
- Destinations
- Messages
- Producers
- Consumers
A quick diversion first. JMS has several ways to use the API. You can pick a "domain independent" version or something specific to a type of Destination. For example, there is a QueueConnectionFactory (which can only be used for queues), a TopicConnectionFactory (topic specific) and simply ConnectionFactory which can be used for either. In this blog, I'm going to use the domain independent apis. If you are wondering why there is all this confusion, its all because of how the specification has changed over the revisions.
Connection Factories
ConnectionFactories are a factory for Connections (a little obvious and probably a trifle confusing since we haven't talked about connections yet). The key thing to know about them is that they exist to hide all the proprietary stuff that a JMS provider may want you to set up, for example how to connect to the server. What happens is that you set up a configuration using JNDI which is specific to the implementation that you are using, and then everything in your code is generic. That way, if you switch to use someone else, all you have to do is change those settings. I'll talk about how to set up JNDI and use imqobjmgr (the MQ specific tool for doing that configuration) in a future blog
For now I am going to cheat and use the MQ specific API to create it.(from what I'm seen, other providers have these convenience apis as well but, in the end, you want to use JNDI to retrieve it because it makes your application portable).
ConnectionFactory cf= new com.sun.messaging.ConnectionFactory();
Connections
The JMS Specification defines a Connection as "the client's active connection to a provider". So connection is the stream of messages to and from the provider (aka the implementation used by MQ). In our case, it represents a TCP connection to MQ's server (called the Broker) that handles all of the heavy lifting of routing and persisting messages. When I create a connection, I have the option of passing in a username and password which is authenticated by the provider. (how I actually set that up depends on the specific implementation of JMS being used - for MQ you use imqusermgr if I am using our simple file-based version or else LDAP through JNDI). Since I haven't set up any authentication, I'll just use the defaults and not pass anything in.
I can also start and stop the connection which starts and stops the flow of messages.
Connection connection = cf.createConnection();
connection.start();
Sessions
A session is a single-threaded stream of control of messages. This means that a session can not be used concurrently by two threads at the same time. (warning - once you start feeling good about JMS and decide to fork some of the work on to other threads you are going to break this and get strange behavior - I think everyone does it at least once). Sessions have cool properties. Message order is guaranteed. You can acknowledge or commit (depending on whether or not you are using transactions) several message at a time. You can rollback or recover the messages if you need to reprocess them.
Session are going to be important because everything else starts from here. You create messages, producers, consumers, destinations from the Session.
The first thing you need to know about sessions is acknowledge modes. Acknowledgement is the way the client implementation (whether the piece supplied by MQ or another provider) or the client application (what you write) tells the system (aka notifies the broker) that you are done processing a message.
At this point, I am going to create a simple session in auto acknowledge mode.
Session session = connection.createSession( false /\* not transacted \*/, Session.AUTO_ACKNOWLEDGE);
JMS has two models for receiving messages. An application can use a "synchronous" api (receive) and explicitly call for a message where it wants it or it can register a message listener (which is a callback that is triggered when a message comes in). For now, I'm not going to set a message listener.
Destinations
I talked a little about destinations in my last entry. I'm not planning to go back over that, its just a storehouse for sending and retrieving a messages. It has a type (queue or topic) and a name. Similar to connection factories, you can retrieve an already created destination using JDNI but I'm going to go ahead and use the simple api's and create it on the fly (this time its not cheating, this is a standard part of the api).
I'll just create a queue, since that seems to lend itself more for a hello world example.
Destination destination = session.createQueue("HelloWorld");
Messages
Messages are the pieces that are passed back and forth - the core of the messaging. There are three pieces to a message:
- header - stuff stuck on by the provider
- properties - name/value pairs that tag simple information on to the message. This data can add additional information or even be used to pick out specific messages through what are called selectors (which is a kind of SQL-lite language used to help a receiver identify a specific message)
- body - the content of the message. It can be text, a java object, a map (so name/value pairs), bytes. At the point I create the message, I determine its type
TextMessage message = session.createTextMessage();
message.setText("Hello Word");
Producers
Producers put messages into the system. You can specify a lot of information about how the message is handled - how long it will live, whether or not it is persistent (stored on disk), how important it is. Since this is a simple example, I'm going to use the easiest method not set any of those.
MessageProducer producer = session.createProducer(destination);
producer.send(message);
Consumers
Consumers get messages from the system. You can create it with a selector to pull out a specific set of messages but I'm going to go for the simple approach (if nothing else because it always takes me 3 iterations to get the selector right). Since I didn't use a MessageListener (see session) I'm also going to call receive to get the message.
MessageConsumer consumer = session.createConsumer(destination);
Message = consumer.receive();
Putting it togetherPutting it together
Now I'm going to put together a pair of simple applications based on what we just discussed. The first will send a message to a queue called HelloWorld. The second will receive the message off of that Queue.
The Producing application
This simple application will:
- Create a connection factory (cheating)
- Create a connection
- Create a session - non-transacted, AUTO_ACKNOWLEDGE
- Create the queue HelloWorld
- Create a message producer
- Start the connection
- Create a HelloWorld message
- Send the message
- Clean everything up
import javax.jms.\*; /\*\* \* simple hello world consumer \*/ public class HelloProducer { /\*\* \* simple consumer \*/ public HelloProducer() { producer MessageProducer producer = session.createProducer(destination); // now that everything is ready to go, start the connection connection.start(); // create our message to send TextMessage message = session.createTextMessage(); message.setText("Hello World"); // send the message to Queue HelloWorld System.out.println("Sending Hello World"); producer.send(message); // close everything producer.close(); session.close(); connection.close(); } catch (JMSException ex) { System.out.println("Error running program"); ex.printStackTrace(); } } /\*\* \* main method \*/ public static void main(String args[]) { new HelloProducer(); } }
The Consuming application
This simple application will:
- Create a connection factory (cheating)
- Create a connection
- Create a session - non-transacted, AUTO_ACKNOWLEDGE
- Create the queue HelloWorld
- Create a message consumer
- Start the connection
- call receive to get the message from the queue.
- Print the body of the message
- Clean everything up
import javax.jms.\*; /\*\* \* simple hello world consumer \*/ public class HelloConsumer { /\*\* \* simple consumer \*/ public HelloConsumer() { consumer MessageConsumer consumer = session.createConsumer(destination); // now that everything is ready to go, start the connection connection.start(); // receive our message TextMessage m = (TextMessage)consumer.receive(); System.out.println(m.getText()); // close everything consumer.close(); session.close(); connection.close(); } catch (JMSException ex) { System.out.println("Error running program"); ex.printStackTrace(); } } /\*\* \* main method \*/ public static void main(String args[]) { new HelloConsumer(); } }
Running it with MQ
To run the application we just created, we need to do four things:
- Compile the classes
- Start the broker (MQ's server)
- Run the producing client to send a message
- Run the consuming client to receive a message
I'm going to give you the commands for doing these tasks on a Solaris system (since I work at sun, its the machine I normally run). You'll have to change them for other platforms.
Compiling
To compile you need to have imq.jar and jms.jar in the class path.
% javac -classpath /usr/share/lib/imq.jar:/usr/share/lib/jms.jar HelloConsumer.java HelloProducer.java
Starting the broker
To start the broker, you run the command imqbrokerd. When you see a string that says Broker ready, its ready to receive messages.
Running the producing clientRunning the producing client
% imqbrokerd [19/Oct/2007:16:00:35 PDT] ================================================================================ Sun Java(tm) System Message Queue 4.1 Sun Microsystems, Inc. Version: 4.1 (Build 34-b) Compile: Thu Jun 28 22:33:50 PDT 2007 Copyright (c) 2007 Sun Microsystems, Inc. All rights reserved. SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. This product includes code licensed from RSA Data Security. ================================================================================ Java Runtime: 1.5.0_09 Sun Microsystems Inc. /usr/jdk/instances/jdk1.5.0/jre [19/Oct/2007:16:00:35 PDT] IMQ_HOME=/ [19/Oct/2007:16:00:35 PDT] IMQ_VARHOME=/var/imq [19/Oct/2007:16:00:35 PDT] SunOS 5.10 sparc hostname (2 cpu) username [19/Oct/2007:16:00:35 PDT] Max file descriptors: 65536 (65536) [19/Oct/2007:16:00:35 PDT] Java Heap Size: max=174784k, current=35328k [19/Oct/2007:16:00:35 PDT] Arguments: [19/Oct/2007:16:00:35 PDT] [B1060]: Loading persistent data... [19/Oct/2007:16:00:35 PDT] Using built-in file-based persistent store: /var/imq/ instances/imqbroker/ [19/Oct/2007:16:00:36 PDT] [B1039]: Broker "imqbroker@hostname:7676" ready.
Now I'll start the producing client who sends a message.
Running the consuming clientRunning the consuming client
% java -classpath .:/usr/share/lib/imq.jar:/usr/share/lib/jms.jar HelloProducer Sending Hello World
Finally, I'll run the consumer.
% java -classpath .:/usr/share/lib/imq.jar:/usr/share/lib/jms.jar HelloConsumer Hello World
Everything else
Well, this has gone on long enough so I'm stopping for the moment. I promise to attack authentication and creating ConnectionFactories and DestinationFactories on some future day. (maybe not right away, I might need to take a break and talk about something else for a few entries).
cool introduction to JMS (we all know how it works, but i havent use it much)
Posted by raveman on October 25, 2007 at 05:57 PM BST #
Thanks for good introduction.
BTW, is there a way to cancel or modify a message already resides in a JMS queue?
Posted by behumble on October 25, 2007 at 08:44 PM BST #
Unfortunately, no - once a message is in the queue there isn't any way to modify or cancel it using JMS.
Posted by Linda Schneider on October 25, 2007 at 09:42 PM BST #
Another great entry Linda!
OK, so now a request from a regular reader.
Do you have any articles or other things you recommend to people who are trying to understand the types of enterprise problems people try to solve with messaging systems?
If not, I would love to see a post from you or a member of the team about common problems solved by messaging systems.
Posted by Tom Kincaid on November 01, 2007 at 05:19 AM GMT #
On useful papers which discuss when to use messaging in enterprise deployments, this comment reply is going to be deficient.
After a not terribly thorough journey through the wonderful world of google and wikipedia, I determined that actual use cases, one pagers, books and other information which provide a rational for using MOM (message oriented middleware) appear to be missing.
There are a lot of "what it is" articles but none which identify an enterprise problem and tell you how and why you would solve it with JMS.
Additionally, customers who have already made the decision to go to a JMS backbone are often reticent about revealing their architecture.
I'll try to address it in my next blog entry with some very high level information and give some real customer scenarios with any specific company information stripped out. (so you might have to wait another week for a description of MQ specific features)
Posted by Linda Schneider on November 01, 2007 at 07:32 AM GMT #
Nice blog!
One question: In the explanation about acknowledge modes, you write "the client has seen it". How does the client "see" a message? Or should I read "sent"?
Posted by Dies Koper on November 14, 2007 at 09:08 PM GMT #
.
So the mainframe running in batch mode can generate a lot of requests that could swamp an application running on a Windows box. By queuing those requests I could ensure there were no resource issues..
I've just started work in a Linux/Java shop which is why I suddenly find myself here. Thanks for the info Linda - it helps a lot.
Posted by David Clarke on November 15, 2007 at 12:40 PM GMT #
>One question: In the explanation about acknowledge modes, you write "the client has seen it". How does the client "see" a message? Or should I read "sent"?
I actually did mean seen. What was missing from my entry is the fact that Acknowledge modes (assuming that the session is not transacted) really only apply when you are receiving a message.
A message is considered "seen" (internally, we usually use the word consumed) after it has been delivered to the client application (either because receive() was called on the session OR the registered message listener was called)
For example,
\* you create a session with the mode set to CLIENT_ACKNOWLEDGE
\* you create two receivers (one on foo, one on bar)
\* you receive a message from destination foo
\* you receive a message from destination bar
\* you call acknowledge on the second message -> both are considered acknowledged which means that the broker will never send thos messages
to you again.
On the sender, MQ (and I'm sure other providers) uses an internal protocol (a reply) to confirm that a message has been received and persisted on the server. We only do this for persistent messages (since non-persistent messages can be lost). The way it works is:
\* the client sends a message which is put on a socket to be read by the broker and blocks waiting for a reply (if persistent)
\* the broker receives that message, stores the message and sends back a reply
Posted by Linda Schneider on November 15, 2007 at 01:23 PM GMT #
Great explanations, thx for being so precise on the caveats of JNDI for newby like me ! Is it possible that you add a link the code written in /tmp/jndi file ?
Posted by fbab on November 15, 2007 at 03:26 PM GMT #!
Posted by Brad Rippe on November 15, 2007 at 04:37 PM GMT #.
Posted by Michael Shaw on December 14, 2007 at 01:11 PM GMT #
I have 2 issues
1. My reciever is retaining messages after once it has consumed. Seems serverstoring in a file , I am not getting location.
2. what can be done if we dont want messages to be on server, once it is restarted.
I am working on RAD7.0 with default messaging and WAS6.0 . Pls i need some urgent help........Thankssssssssss
Posted by Puneeet on April 08, 2008 at 04:17 AM BST #
Hi Linda,
for JMS we would require Java messaging Queues to be installed, isnt there any wayout inwhich we can use Java to access native OS queues like Linux queues.
Posted by Neeraj on April 19, 2008 at 06:02 AM BST #
Hi,.
Thanks
Posted by Bhupinder on August 12, 2008 at 12:42 AM BST #
Hi Linda!
This is a great tutorial. It brought a lot to my knowledge about JMS and IMQ. One thing I wanted to know is which path can I see the queues physically lying.
Regards,
Kashif
Posted by Kashif on November 12, 2008 at 04:00 AM GMT #
What happens if the message is not been able to consume by the client and abruptly ends without confirming the message(using Client_ACk mode).
If the queue receiver is set to receive 10 messages at one time, and there are 100 pending messages, will this message which has abruptly came out without confirming by the client would be again resubmited
1>Alomost instantly
2>Will only get processed once the 100 messages got processed.
Will this be FIFO based on the client rejection or can maintain the old precedence?
Posted by atchayya on November 12, 2008 at 05:05 PM GMT #
There is no article or enough info on how to configure OpenMQ in Tomcat settings.xml.
If you know can you please write an article in blog so many people will come to know and get benefit of it.
Posted by Krunal Shimpi on September 10, 2009 at 04:56 AM BST #
Hi Guys,
I have a problem and might excite experts here. Please let me know if you have a solution for the problem.
Posted by KR Kumar on October 23, 2009 at 11:08 AM BST #
I am using MQactive will this code work with active mq. i have a problem receiving message with mqactive (using spring jms synchronous messaging). if this code works it will help me kindly let me know.
thanks
raj
Posted by guest on March 27, 2011 at 07:22 PM BST # | https://blogs.oracle.com/openmessagequeue/entry/jms_101 | CC-MAIN-2015-27 | refinedweb | 3,170 | 61.97 |
What problem Builder pattern solves in Java
As I said earlier Builder pattern is a creational design pattern it means its solves problem related to object creation. Constructors in Java are used to create object and can take parameters required to create object. Problem starts when an Object can be created with lot of parameters, some of them may be mandatory and others may be optional. Consider a class which is used to create Cake , now you need number of item like egg , milk , flour to create cake. many of them are mandatory and some of them are optional like cherry , fruits etc. If we are going to have overloaded constructor for different kind of cake then there will be many constructor and even worst they will accept many parameter.
Problems:
1) too many constructors to maintain.
2) error prone because many fields has same type e.g. sugar and and butter are in cups so instead of 2 cup sugar if you pass 2 cup butter, your compiler will not complain but will get a buttery cake with almost no sugar with high cost of wasting butter.
You can partially solve this problem by creating Cake and then adding ingredients but that will impose another problem of leaving Object on inconsistent state during building, ideally cake should not be available until its created. Both of these problem can be solved by using Builder design pattern in Java. Builder design pattern not only improves readability but also reduces chance of error by adding ingredients explicitly and making object available once fully constructed.
By the way there are many design pattern tutorial already there in Javarevisited like Decorator pattern tutorial and Observer pattern in Java. If you haven’t read them already then its worth looking.
Example of Builder Design pattern in Java
We will use same example of creating Cake using Builder design pattern in Java. here we have static nested builder class inside Cake which is used to create object.
Guidelines for Builder design pattern in Java
1) Make a static nested class called Builder inside the class whose object will be build by Builder . In this example its Cake .
2) Builder class will have exactly same set of fields as original class. 3) Builder class will expose method for adding ingredients e.g. sugar() in this example. each method will return same Builder object. Builder will be enriched with each method call.
4) Builder.build() method will copy all builder field values into actual class and return object of Item class.
5) Item class (class for which we are creating Builder) should have private constructor to create its object from build() method and prevent outsider to access its constructor.
public class BuilderPatternExample { public static void main(String args[]) { //Creating object using Builder pattern in java Cake whiteCake = new Cake.Builder().sugar(1).butter(0.5). eggs(2).vanila(2).flour(1.5). bakingpowder(0.75).milk(0.5).build(); //Cake is ready to eat :) System.out.println(whiteCake); } } class Cake { private final double sugar; //cup private final double butter; //cup private final int eggs; private final int vanila; //spoon private final double flour; //cup private final double bakingpowder; //spoon private final double milk; //cup private final int cherry; public static class Builder { private double sugar; //cup private double butter; //cup private int eggs; private int vanila; //spoon private double flour; //cup private double bakingpowder; //spoon private double milk; //cup private int cherry; //builder methods for setting property public Builder sugar(double cup){this.sugar = cup; return this; } public Builder butter(double cup){this.butter = cup; return this; } public Builder eggs(int number){this.eggs = number; return this; } public Builder vanila(int spoon){this.vanila = spoon; return this; } public Builder flour(double cup){this.flour = cup; return this; } public Builder bakingpowder(double spoon){this.sugar = spoon; return this; } public Builder milk(double cup){this.milk = cup; return this; } public Builder cherry(int number){this.cherry = number; return this; } //return fully build object public Cake build() { return new Cake(this); } } //private constructor to enforce object creation through builder private Cake(Builder builder) { this.sugar = builder.sugar; this.butter = builder.butter; this.eggs = builder.eggs; this.vanila = builder.vanila; this.flour = builder.flour; this.bakingpowder = builder.bakingpowder; this.milk = builder.milk; this.cherry = builder.cherry; } @Override public String toString() { return "Cake{" + "sugar=" + sugar + ", butter=" + butter + ", eggs=" + eggs + ", vanila=" + vanila + ", flour=" + flour + ", bakingpowder=" + bakingpowder + ", milk=" + milk + ", cherry=" + cherry + '}'; } }
Output:
Cake{sugar=0.75, butter=0.5, eggs=2, vanila=2, flour=1.5, bakingpowder=0.0, milk=0.5, cherry=0}
Builder design pattern in Java – Pros and Cons
Live everything Builder pattern also has some disadvantages, but if you look at below, advantages clearly outnumber disadvantages of Builder design pattern. Any way here are few advantages and disadvantage of Builder design pattern for creating objects in Java.
Advantages:
1) more maintainable if number of fields required to create object is more than 4 or 5.
2) less error-prone as user will know what they are passing because of explicit method call.
3) more robust as only fully constructed object will be available to client.
Disadvantages: 1) verbose and code duplication as Builder needs to copy all fields from Original or Item class.
When to use Builder Design pattern in Java Builder Design pattern is a creational pattern and should be used when number of parameter required in constructor is more than manageable usually 4 or at most 5. Don’t confuse with Builder and Factory pattern there is an obvious difference between Builder and Factory pattern, as Factory can be used to create different implementation of same interface but Builder is tied up with its Container class and only returns object of Outer class.
That’s all on Builder design pattern in Java. we have seen why we need Builder pattern , what problem it solves, Example of builder design pattern in Java and finally when to use Builder patter with pros and cons. So if you are not using telescoping constructor pattern or have a choice not to use it than Builder pattern is way to go.
Reference: Builder Design pattern in Java – Example Tutorial from our JCG partner Javin Paul at the Javarevisited blog.
Another important advantage this approach gives is the ability to protect read-only fields as final. Rather than using a manageable – but incomplete – constructor and a series of setters or something like that, you can use a builder and configure that via successive method calls…then have it render a complete and appropriately protected instance of your class.
Another nice thing about the builder is it can have a fluent api that allows you to chain calls together during setup, making object creation code a lot more readable.
I realize your example encapsulates both of these principles, but IMO these are worth mentioning explicitly, since they’re pretty nice features.
Agreed – these are definitely two distinct advantages of the builder pattern. I personally like Builder’s ability to generate immutable types, but I’m not a fan fluent API syntax (my builders generally just use regular getters and setters).
Another advantage is that you can put required parameters into the builder’s constructor. Consider a Name.Builder class. Have a constructor
public class Name {
public static class Builder {
public Builder(String givenName, String surName) {…}
public Builder middleName(String middleName) {this.middleName = middleName;}
public Builder honorific(String honorific) {this.honorific = honorific;}
//… abbreviations, generation marks, postnomials, etc.
}
}
Add error checking to each of the builder’s methods. The constructor’s parameters should be non-null and non-blank.
There is a rarer alternative. It is actually pretty dangerous, because it breaks equals(Object obj) methods that check for class equality. Use initializer blocks.
Name me = new Name(“Eric”, “Jablow”) {
{
setHonorific(“Mr.”); setMiddleName(“Robert”);
}
};
Note that me.getClass() != Name.class.
The only time one sees this in practice is in code like JMock Expectation objects.
Excellent article. One drawback I can think of is, if there are mandatory fields to construct an object then we can acheive it through traditional constructor pattern rather than builder.
There are a lot of grammar mistakes in this article. Would you like me to proofread it? I’m serious. I’d like for this to be more readable for both myself and others. You have my email. Cheers.
Thank you for your article,
I have some exercises related to design pattern and It’s very helpful for me. | http://www.javacodegeeks.com/2012/07/builder-design-pattern-in-java.html | CC-MAIN-2015-35 | refinedweb | 1,406 | 53.92 |
»
Product and Other Certifications
Author
000-341 sample test questions
Nadin Ebel
Greenhorn
Joined: Jan 06, 2005
Posts: 7
posted
Jan 07, 2005 07:49:00
0
Hi,
enclosed lots of questions but no answers ...
Configuring WebSphere queue connection factory settings for application clients requires what information?
(Select 2)
Host of JMS server for this connection factory
Port for queue destination
Fully qualified JNDI name
Server name of JMS server
Connection factory display name
When given a
J2EE
1.2 EAR, what steps in the Application Assembly Tool can the administrator take to migrate a copy of the EAR to enable installation into WebSphere Application Server V5?
(Select 2)
A. Select "Save As" from the file menu. Check the "J2EE 1.3" box on the SaveAs dialog. Click "OK".
B. Click Convert EAR from the file menu. Save the new J2EE 1.3 application.
C. Select Import J2EE 1.2 EAR from the file menu Click "Generate Code for Deployment" Save the new J2EE 1.3 application.
D. Take no steps - J2EE 1.2 applications can be installed in WebSphere V5.
An administrator has created a script named ShowApps.jacl to display the names of all running applications. What methods could the administrator use to cause that script to execute automatically each time wsadmin is executed?
(Select 2)
A. Modify the calling wsadmin.bat /.sh file to pass the ShowApps.jacl file as a profile parameter.
B. Append "ShowApps.jacl" to the end of wsadmin.xml.
C. Append the directory where the ShowApps.jacl file is stored to the system classpath.
D. Modify the wsadmin.properties file to include the ShowApps.jacl file as a profile script.
E. Modify the WAS_ADMIN environment variable to add "ShowApps.jacl".
While installing an enterprise application, an OutOfMemory exception is thrown and the EAR file will not install. Which of the following scenarios are MOST likely to cause the problem?
(Select 2)
A. The application may have too many modules. Repackage the application so it has fewer modules.
B. There is a problem with the connection factory bindings. Change the resource authorizations setting to per connection factory.
C. The
Java
Virtual Machine (JVM) settings should be increased for the application server.
D. There may be a problem due to the JSPs being pre-compiled. Turn off the Pre-compile
JSP
option and repackage the application.
E. In the Dynamic Cache Service, the cache size is too large. Adjust the maximum number of entries to a smaller number.
What types of objects CANNOT be added to the names space of IBM WebSphere Application Server V5.0 using configured bindings?
A.
EJB
hosted by a server, or server cluster, in the cell
B. CORBA object bound in another name space
C. JMS connection factory name on the local name space
D. Environmental
String
object relative to the root
What administrative console role has the permissions required to change Global Security Settings?
A. Monitor
B. Operator
C. Administrator
D. Configurator
What advantage is provided by selecting the use of SSL client authentication on the Web container for HTTPS traffic?
A. Enables the Web server to do certificate based authentication
B. Guarantees only trusted Web servers can talk to that Web container
C. Increases the level of encryption ensuring better network security
D. Eliminates the need for an LDAP directory for authentication
Which of the following would have to be configured to prevent an EJB client from authenticating using a certificate?
A. Ensure that the Web container's keyring does not contain the client's signing certificate
B. Configure inbound CSIv2 client certificate authentication to 'never'
C. Make sure the WebSphere keyring is readable only by root or administrator
D. In the LDAP directory, remove the client certificate from the user's certificate attribute
What value does Java 2 security provide to applications running in a WebSphere Application Server environment?
A. Is used by the Web server to limit access to the static content
B. Makes it possible for the application server to control access to system resources by the applications
C. Links into the operating system to enable Single Signon with the operating system
D. Ensures that native code is securely segregated from java code
While configuring WebSphere Application Server Network Deploy security for the first time, an administrator wants to set up SSO (Single Sign-On) and LTPA, using only IP addresses (not IP hostnames). What special considerations would need to be taken into account for LTPA?
A. Set the Single Signon Domain Name to the hostname of the application server
B. Leave the Single Signon Domain Name blank
C. Set the Single Signon Domain Name to the DNS domain name
D. This is not supported.
Which of the following situations does NOT require manually editing the plug-in configuration file?
A. A plug-in generated on a Win32 system is to be copied to a remote UNIX system having an HTTP server and a WebSphere Application Server V5.0 plug-in.
B. When IBM WebSphere Application Server V5.0 is installed into a directory other than the default directory.
C. A plug-in was generated in Network Deployment where the HTTP server is located on the same machine as the Deployment Manager.
D. When IBM WebSphere Application Server V5.0 is installed in the default directory locations in a heterogeneous environment.
Which session persistence mechanism requires the LEAST amount of administrative configuration when setting up a new cluster?
A. Database session persistence
B. Internal messaging client-server topology
C. Internal messaging N-way peer-to-peer topology
D. Internal messaging single replica peer-to-peer topology
What are the benefits of creating multiple cluster members in the same cluster on one physical node?
(Select 2)
A. Maximizes CPU utilization in multi-processor machines
B. Reduces HTTP server overhead
C. Provides process-level failover options
D. Eliminates a hardware single point of failure (SPOF)
It is NOT possible to configure session persistence options differently for two Web modules in an enterprise application when:
A. The two Web modules run in different clusters.
B. The two Web modules run in the same application server.
C. Session persistence is configured at the application server level.
D. Session context sharing is enabled in the enterprise application.
What steps are necessary to add a new cluster member to an existing cluster and allow it to start handling requests without interrupting requests to other cluster members?
(Select 3)
A. Create and configure a new cluster member.
B. Install the application to the new cluster member.
C. Start the new cluster member.
D. Update the HTTP server plug-in.
E. Stop and re-start the HTTP server.
A cluster has three cluster members. Their weights are: WLM_1 - 2 WLM_2 - 4 WLM_3 - 4 What percentage of new HTTP requests will be routed to WLM_1 ?
A. 0.2 %
B. 2%
C. 20%
D. 33.3%
A collection of four web modules forms an enterprise application. The web modules must share data within a single application session object. At which scope or in which files should the "shared
HttpSession
context" property be set?
A. At the node level
B. At the application server level
C. At the enterprise application level
D. On each web.xml file for the application
E. On the application.xml file for the application
The following command is executed on the Deployment Manager node: restoreConfig WebSphereConfig_<date>.zip It fails to update the cell configuration. The likely problem is that the:
A. file backup.log is missing.
B. command needs the -force option selected.
C. file WebSphereConfig_<date>.zip is missing.
D. command was run from <deployment manager install dir>/bin directory.
An application has bursty traffic back to the database. It is found that the application is slow to release database connections when not in use. What connection pool setting should be modified to improve this behavior?
A. Decrease the reap time
B. Decrease the aged timeout
C. Decrease the unused timeout
D. Decrease the minimum connections
A Web server is configured to deliver application requests to a cluster of application three servers. A typical client mix will have 40% of HTTP requests handled exclusively by the Web server. If the Web server is configured with a maximum concurrent client setting of 100, what is a good value to set each Web container maximum thread pool size?
A. 10
B. 20
C. 60
D. 100
Which of the following administration tasks cause the web server plug-in configuration file to need updating?
(Select 2)
A. Add an enterprise application.
B. Remove a cluster member from a cluster.
C. Change the application server trace string.
D. Change the startup setting for an application server.
E. Add a JMS Connection factory.
Three application servers form a replication domain. Two of them, svr1 and svr2, are part of a cluster that services user requests. The third application server, svr3, is only configured as an active repository for session data. What should be set to define this configuration?
(Select 2)
A. svr1 and svr2 should have their memory-to-memory runtime mode set to both.
B. svr1 and svr2 should listen to all partition IDs.
C. svr3 should have its memory-to-memory runtime mode set to both.
D. svr3 should have its memory-to-memory runtime mode set to server.
Which server parameter settings MOST influence EJB passivation?
(Select 2)
A. ORB service request timeout
B. Transaction service transaction lifetime timeout
C. EJB object cache size
D. EJB object cache cleanup interval
E. EJB object inactivity timeout
A remote performance team (such as IBM Support) needs to view PMI data to evaluate and diagnose an application performance problem. The administrator can BEST facilitate this by which of the following techniques?
A. Write a custom ARM 2.0 agent.
B. Set up a remote monitoring session with Tivoli Performance Viewer.
C. Save a monitoring session to a log and provide the log to the remote team.
D. Have the team use the performance monitoring
servlet
.
A trace of an application shows the Web container thread pool size is nearly always equal to the maximum pool size setting. At the same time, the average number of active threads is close to the minimum pool size and the percent maxed counter is less than 2%. What tuning changes should be considered for this application?
A. Decrease the maximum pool size
B. Decrease the minimum pool size
C. Decrease the inactivity timeout
D. Disable the growable property
Which file records the output from verbosegc for an IBM WebSphere Application Server V5.0 process?
A. SystemErr.log
B. native_stderr.log
C. serverStatus.log
D. activity.log
The dumpnamespace utility displays the name space of the IBM WebSphere Application Server. When dumpnamespace is used in a Network Deployment environment on a node running application servers it:
(Select 2)
A. presents a full logical view of the name space.
B. uses CORBA URLs to indicate that a link exists to an external context.
C. accesses the name space of the local node agent when dumpnamespace is run without arguments.
D. cannot be used to find IORs for bound objects.
The output of the Collector Tool is:
A. a set of files that contain configuration information.
B. a single archive containing installed application, configuration, and log information.
C. the collector.log file that contains the combined information of all the server log files.
D. the log information for all the nodes in the same cell.
Which of the following criteria CANNOT be specified when configuring log files to be self-managed?
A. The maximum number of historical log files.
B. The time of day for log file rotation.
C. The maximum file size that triggers log file rotation.
D. Whether logging of installed applications' output is included in files.
E. Whether to compress history files after rotation.
How can an IBM WebSphere Application Server V5.0 administrator BEST correlate failures in different servers running on different nodes?
A. Start multiple instances of the Log Analyzer tool, and then load the activity log from each node into each instance.
B. Run the Log Merge tool to combine the log entries for each server of each node, and then sort the result by timestamp.
C. Start the showlog script with multiple input files, and then view their combined output records sorted by timestamp.
D. Use the Log Analyzer tool's merge capability to open and combine multiple activity log files.
The IBM WebSphere Application Server V5.0 administrator uses Trace Specification strings to declare components or groups to be traced. What technique is NOT valid for entering and activating Trace Specification strings?
A. Type the string directly into the Trace Specification input areas of the console.
B. Include the string as a command line parameter when starting the server.
C. Compose the string using the administrative console GUI.
D. Use wsadmin to enable tracing by using a Trace Specification string.
When directing trace output to a file, what happens when the size of the log file reaches its maximum configured size?
A. The file wraps such that newer entries overwrite older entries.
B. Tracing stops.
C. The original file is closed and renamed. A new file is started.
D. A new file is created using the original name plus the current timestamp.
Which JMS Provider is MOST appropriate for an administrator to configure for a J2EE application that accesses an MQ Series application written in COBOL on a System 390?
A. Generic JMS Provider
B. Generic WebSphere MQ JMS Provider
C. WebSphere MQ JMS Provider
D. WebSphere JMS Provider
What is the value to an enterprise in installing and running WebSphere Application Server Deployment Manager running on its own dedicated machine?
(Select 2)
A. Deployment Manager can run on a machine with a smaller CPU
B. Reduces the number of single points of failure
C. Provides isolation of processes
D. Administrative console can run on the same machine
E. Allows for future coexistence with single installation of WebSphere Application Server
In a Network Deployment environment, what are the consequences of a Deployment Manager failure?
(Select 2)
A. The node.xml file on the deployment manager and each node may become unsynchronized.
B. The administrative console will not be available.
C. The workload management service will be delegated to the node agents.
D. Changes to the master configuration will not be propagated to individual nodes.
E. Changes to the local configuration will not be propagated to the master configuration.
What should be considered when comparing the vertical scaling of an application server (clustering) versus creating multiple stand-alone (Base) servers on the same machine?
(Select 2)
A. File synchronization will occur in the clustered environment.
B. Multiple physical servers running stand-alone application servers provide failover support.
C. The HTTP server plug-in distributes requests in a multiple stand-alone server environment.
D. The HTTP server plug-in distributes requests in a clustered environment.
E. Multiple stand-alone server machines can be easily combined into the vertically scaled environment.
What are the advantages of configuring Web containers so that they run in separate application servers from the EJB Containers?
A. Simplifies maintenance by logically separating presentation and business logic
B. Improves local JVM optimizations when the Web and EJB containers run in different JVMs
C. Reduces the number of single points of failure
D. Enables a configuration where different ratios of Web to EJB containers are possible, to better respond to the processing load
What are the consequences of configuring resources (
JDBC
Providers, JMS Providers, Resource Adapters, etc.) from different cells on the same set of machines?
A. Each cell will synchronize its master configuration with the node agents on the individual nodes.
B. All the resources will be managed from different cells by different deployment managers.
C. All the resources will be managed from a single cell by a single deployment manager.
D. All the resources will be managed from different cells by a single deployment manager.
When using LDAP as a user registry, what should be done to better ensure that user passwords are not compromised in the overall IBM WebSphere Application Server V5.0 security architecture design?
(Select 2)
A. The LDAP User Registry should be located in the same domain as the application server.
B. SSL should be enabled from the admin console to ensure secure socket communications.
C. The LDAP server should be physically located on the same machine as the application server.
D. SSL should be enabled from the application server to the LDAP server.
An enterprise hosts a trading application. The site is tightly connected to a database with a very high volume of complex transactions. There are a low number of requests. Which Workload Management strategies would be most appropriate in this scenario?
(Select 3)
A. Adding Web servers in the DMZ
B. Implementing connection pooling
C. Caching static pages
D. Implementing EJB workload management
E. Partitioning the database into multiple servers
Which of the following methods can be used in wsadmin to get help on the use of scripting objects?
A. Use wsadmin with the -h option
B. Use wsadmin with the -? option
C. Use the Help management object
D. Use wsadmin with the -help option
Which of the following files could be used to troubleshoot problems with the installation of either IBM WebSphere Application Server V5.0 or Network Deployment?
(Select 3)
A. activity.log
B. log.txt
C. mq_install.log
D. serverStatus.log
E. installAdminConsole.log
An administrator is attempting to install IBM WebSphere Application Server Version 5.0 and the installation wizard fails to detect an existing 5.0 installation. What are the administrator's options?
A. Edit the prereq.properties file and continue with the installation.
B. Start the installation from the command line with the option -W previousVersionDetectedBean.previousVersionDetected="true".
C. Start the installation from the command line with the option -W coexistenceOptionsBean.showCoexistence="true".
D. The only option is to perform a silent installation.
An administrator has decided to create multiple configuration instances for IBM WebSphere Application Server V5.0 on a single machine. What are some of the benefits of this approach?
(Select 3)
A. Multiple identical environments are available for development and
testing
.
B. The administrator can migrate configurations from an earlier release.
C. Multiple developers and testers can share one machine.
D. Installation and uninstallation are simplified.
E. Run time scripts and libraries are shared.
Which of the following will update the node's local configuration files to reflect the current contents of the master repository?
A. updateCell
B. cleanupNode
C. updateNode
D. syncNode
In the event of problems running scripts using wsadmin, the administrator can direct tracing output to a file. Which of the following statements regarding tracing is FALSE?
A. The location of the wsadmin tracefile can be specified in the wsadmin.properties file.
B. The trace string can be specified in the wsadmin.properties file.
C. The location of the wsadmin tracefile can be specified using the AdminControl scripting object.
D. The trace string can be specified using the AdminControl scripting object.
E. Setting up a profile makes it simpler to turn tracing on and off.
An administrator has installed IBM WebSphere Application Server V5.0 with WebSphere Embedded Messaging, and is having problems uninstalling and reinstalling. In order to reinstall IBM WebSphere Application Server V5.0, the administrator can:
A. Remove Queue Connection Factories from the operating system registry prior to reinstalling the product.
B. Reinstall using the option -P mqQueuingBean.active="true" on the command line or response file
C. Uninstall embedded messaging, and then uninstall prior to reinstalling the product.
D. Remove Queue Destinations from the configuration, and then proceed to simply reinstall the product.
When two single instances of IBM WebSphere Application Server V5.0 are running on the same computer, which precaution applies to ensure that no conflicts occur?
A. Objects must be registered in JNDI using unique names.
B. The servers' ports must be unique.
C. JNDI clients should specify the provider URL when obtaining the initial context.
D. Lookups should be performed using the node agent to be topology independent.
An IBM WebSphere Application Server V5.0 domain is currently running Enterprise Applications that utilize Message Driven
EJBs
(MDBs). Currently, the embedded WebSphere JMS Provider is being used. Which of the following requirements would necessitate the implementation of WebSphere MQ as the JMS provider?
(Select 2)
A. A full implementation of the J2EE JMS APIs is needed.
B. Durable topic subscriptions are required.
C. Communication with destinations outside the WebSphere environment is needed.
D. Both Point-to-Point and Publish/Subscribe message delivery mechanisms are required.
E. Queue manager to Queue manager communications need to be implemented.
The administrator needs to create a JDBC provider to support connection pooling and two-phase commit. Which of the following implementation classes will fulfill these requirements?
A. COM.ibm.db2.jdbc.DB2ConnectionPoolDataSource for DB2, or oracle.jdbc.pool.OracleConnectionPoolDataSource for Oracle
B. COM.ibm.db2.jdbc.DB2XADataSource for DB2, or oracle.jdbc.xa.client.OracleXADataSource for Oracle
C. COM.ibm.db2.jdbc.DB2TwoPhaseDataSource for DB2, or oracle.jdbc.pool.OracleTwoPhaseDataSource for Oracle
D. COM.ibm.db2.jdbc.DB2DistributedDataSource for DB2, or oracle.jdbc.pool.OracleDistributedDataSource for Oracle
Which of the following authentication mechanisms would a resource adapter use to access an EIS (Enterprise Information System)?
A. BasicPassword
B. Basic Authentication
C. Lightweight Third Party Authentication
D. Simple WebSphere Authentication Mechanism
In which file are the J2EE security role mappings stored?
A. was.policy
B. application.xml
C. sas.server.props
D. ibm-application-bnd.xmi
Which of the following situations require a re-start of an enterprise application in order to cause the changes to be effective?
(Select 2)
A. Placing a JSP in the proper location below the APP_INSTALL_ROOT directory
B. Adding a new EJB or Web module to an application
C. Updating an existing servlet class
D. Changing the deployment descriptors file for an application
E. Changing the HTTP plug-in configuration
Configuring WebSphere queue connection factory settings for application clients requires what information?
(Select 2)
A. Host of JMS server for this connection factory
B. Port for queue destination
C. Fully qualified JNDI name
D. Server name of JMS server
E. Connection factory display name
regards
nell
[ January 07, 2005: Message edited by: Nadin Ebel ]
Nadin Ebel - nell<br /><a href="" target="_blank" rel="nofollow"></a><br /> <br />WAS 5 CSA, WPS 5 CSA, ITIL Foundation, CCA, IBM Certified Advanced System Administrator - LND 6, IBM Certified Developer - LND<br /> <br />IT Consultant & Technical Editor Addison-Wesley/Pearson
I agree. Here's the link:
subject: 000-341 sample test questions
Similar Threads
IBM Test 340
Test 340 Answers
answer for IBM 340 WAS 5.0 Admin?
Another mock exam for Test 340 and Ansers
Passed 700,701 and 340 last Thursday
All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter
JForum
|
Paul Wheaton | http://www.coderanch.com/t/144997/po/certification/sample-test-questions | CC-MAIN-2015-22 | refinedweb | 3,811 | 51.55 |
The curious case of the disappearing PDF text
A case of disappearing text in an auto-generated PDF document led me to dig deeper and learn more about ReportLab: a PDF generation library. Here’s the story of what happened, with an excursion into how to build basic PDF documents in ReportLab.
A user of an app that we developed ages ago at work noticed a weird thing: when text in part of an automatically generated PDF document got too large, the text disappeared from the document entirely. This is a journey of debugging (as well as a journey of discovery) in which I work out what the bug was, why it appeared, and what the final fix was.
It all began with a bug
The application in question is a Django app that we still maintain, part of which produces automatically generated PDF output (via the ReportLab library) from various pieces of information stored in the backend database. A user contacted us and asked why text in one particular field (a field for comments and additional information) was missing. We investigated and worked out that when the text in the field was too long, the text within the relevant section in the generated PDF disappeared. This struck me as weird, because usually when some text is too big for a page it often just extends beyond its given margins: disappearing completely was new to me.
But where to begin? And how could we work out what the underlying problem was? Trying to hone in on the problem in the production code wasn’t an option as a lot of the document construction had been abstracted into various methods, so isolating the problem there turned out to be difficult. Also, since I hadn’t written this code (and the original author doesn’t wasn’t available to ask) I wasn’t very familiar with how the code went about its job.
Therefore it was back to basics: I needed to build a basic document using ReportLab which very roughly approximated the document the production code is trying to build. Then I needed to see if I could get the bug to show itself in the example document. The idea being that by reducing the scope of the problem, the bug would be easier to reproduce and therefore a solution would be more likely to present itself.
We need to know where we’re going before we can go there
Before we start simplifying the problem, let’s first get an idea of what the production code is trying to do. The document being generated has the following layout from top to bottom:
- a header block containing the document title and a logo image
- two columns of information; one column containing text, the other containing images
- a block of text containing comments and additional information
Graphically, it looks like this:
However that’s way too complicated to try to reproduce (at least, not just yet). Squinting a bit and considering the document layout from a higher level, we can think of this document layout as having just three blocks, each containing only text. Visually, that looks something like this:
Ok, that’s a much easier to work with! Let’s build this example document now.
A very basic document
After investigating the production code in more detail, I found that it uses
a
Canvas object to describe the page as a whole, and then breaks up the
document into parts using
Frame objects (e.g. for top, middle and bottom
rows), each containing
Paragraph or
Image objects depending upon the
exact content to be displayed. We’ll therefore build a basic document along
these lines: a
Canvas containing three
Frame objects, each containing a
Paragraph. If you’re interested in the details about these objects, have
a look at the ReportLab user
guide.
However, before we get started, it’s a good idea to make a directory to contain our work and create a Python virtual environment in there so that we can install any third party libraries we want without needing to install them system wide:
$ mkdir disappearing-reportlab-text && cd disappearing-reportlab-text $ virtualenv --python=/usr/bin/python3 venv $ source venv/bin/activate $ pip install reportlab
We can now construct a very simple document containing a single
Frame
with this code:
from reportlab.pdfgen.canvas import Canvas from reportlab.platypus import Paragraph, Frame from reportlab.lib.pagesizes import A4 from reportlab.lib.units import cm def render(): canvas = Canvas("basic-canvas-doc.pdf", pagesize=A4) frame = Frame(0, 0, 20*cm, 5*cm, showBoundary=True) frame.addFromList([Paragraph("A basic canvas document")], canvas) canvas.save() if __name__ == "__main__": render()
Here’s the output:
Although this doesn’t represent the document we’re trying to (roughly) reproduce (for instance, the frame is displayed at the bottom of the page; the rest of the page is white), it does get the ball rolling.
What’s happening in this code? Well, this is just a basic script where
we define a
render() function. This function is called only when the
script is run directly, this is what the check
if __name__ == "__main__":
does. The
render() function constructs a
Canvas with the name of the
file to be generated and specifies the page size to use (we use
A4 here to
be explicit). Then a
Frame is defined which contains the text (via a
Paragraph object) “A basic canvas document”.
Frame objects are fairly low-level objects and hence need to be specified
very explicitly: the first two arguments define the lower left coordinate
position of the frame within the canvas, the next two arguments are the
width and height of the frame respectively (in this case I’ve just set them
to be 20cm and 5cm explicitly by using the
cm unit imported from the
reportlab.lib.units package). The
showBoundary option draws a box
around the frame to aid in debugging when positioning frames within a
document. We then add the paragraph to the frame and specify the canvas
object that the frame will use as a reference for placing its contents.
Finally we call
save() on the canvas object which writes the document to a
file with the name we gave to the canvas object when we constructed it.
A closer approximation
There are few issues here that I’m not happy with (apart from the fact that there’s only one frame in the document):
- the frame is at the very bottom of the page,
- the page isn’t completely filled with text,
- the frame isn’t aligned with any margins in the document,
- and the text is way too short to cause any strange bugs to appear by being too long.
Nevertheless, it’s put us on the right path, so let’s fix these issues and get a closer approximation to the document we’re trying to represent.
Let’s define some margins for the document, say 1cm for the left and right margins respectively and 2cm for the top and bottom margins respectively:
LEFT_MARGIN = 1*cm RIGHT_MARGIN = 1*cm TOP_MARGIN = 2*cm BOTTOM_MARGIN = 2*cm
I’ve used all capitals for these parameters because they represent constants and hence should be treated differently to variables (which are usually lower or mixed-case in Python).
From the margins and knowing that we’re using A4 paper, we can work out the width and height of the text:
PAGE_WIDTH, PAGE_HEIGHT = A4 TEXT_WIDTH = PAGE_WIDTH - LEFT_MARGIN - RIGHT_MARGIN TEXT_HEIGHT = PAGE_HEIGHT - TOP_MARGIN - BOTTOM_MARGIN
Again, these are constants and hence we use all capitals for their names.
Now that we have this information, we can more easily position frames within the canvas and hence the document as a whole.
To save us some work in trying to think up some random text to add to each
frame, let’s use the
lorem-text package, so that we can automatically
generate long-ish blind text to fill the frames with content (which will be
a header, a bit of vertical space (via a
Spacer object), and some more
blind text).
We can install the
lorem-text package with
pip:
$ pip install lorem-text
and can use it in code to automatically generate text blocks like so:
from lorem_text import lorem lorem.paragraph() # create a single paragraph of blind text lorem.paragraphs(3) # create given number of paragraphs of blind text
where the
.paragraph() method just creates a single paragraph; if one
wants to make multiple paragraphs in one go, one can pass a number to the
paragraphs() method.
Making the changes described above gives us this code:("rough("One lorem"), HEADSKIP, Paragraph(lorem.paragraph())], canvas) canvas.save() if __name__ == "__main__": render()
which then generates this document:
We can see that the code got a lot harder to read and understand very quickly; especially because we have to position the frames explicitly.1 For instance, we need to know that the frames are positioned relative to the bottom left corner of the page (in this case the canvas and the page are the same thing). Therefore, each frame needs to be shifted to the right by the size of the left margin and the width of a frame needs to be set so that its right edge doesn’t encroach into the right margin.
The natural way to lay out the page would be to place place elements from
the top of the page downwards, thus we need to work out where the top of
text would be, and hence we calculate the position of the top of the text
and work down from there. We can then work out where the bottom of the
frame should be by subtracting the fraction of the text height that we’re
allocating to the given frame. Also, each frame needs to “know” how much
space has been used up by each previous frame so that the correct proportion
of the text height can be subtracted from the
top_of_text value in order
to get the correct bottom coordinate of the respective frame.
Not only is the code harder to understand, it’s also not easy to explain in words what the code is doing. Further, this code structure only supports creation of a single-page document; text can’t easily flow onto further pages if it becomes too large for the current page.
Nevertheless, this structure reflects the production code’s internals fairly well. The fact that the code is hard to understand and explain is a signal to us that something needs to be improved here.
Note that this isn’t a criticism of the original developer’s work: there
are probably very good reasons as to why the code was developed that way (if
I remember correctly, one reason was that it was easier to test the
preliminary output from a
Canvas object than it was to check the generated
PDF). Note that our perspective at this point in time is significantly
different to that available when the code was written. Much has been
learned in between times and time pressure will have been a factor, hence
getting something working (even if it only supports creation of a single
page document) is better than the perfect solution which is never delivered.
We’re now in a position to reproduce the bug we’re currently seeing in production.
Reproducing the bug
We can reproduce the bug by making the text in the final frame much too large (the final frame in the production document showed the problem of the disappearing text), e.g.:
frame.addFromList([ Paragraph("Too many lorems"), HEADSKIP, Paragraph(lorem.paragraphs(10))], canvas)
which then gives us:("overfull-frame-in("Too many lorems"), HEADSKIP, Paragraph(lorem.paragraphs(10))], canvas) canvas.save() if __name__ == "__main__": render()
And, in a puff of smoke, the text in the last frame has vanished! This has reproduced the bug!
Although this is what I’ve been hinting at all along, this confirms what my suspicions were from playing around with the comment text box in the production system: over-filling a frame with text causes the text to disappear from the generated PDF output. It’s odd that ReportLab doesn’t issue a warning or an error when this happens, but it’s good to know that we’ve isolated the problem.
Understanding bugs can create new requirements
Now we’re confronted with the next problem: how do we handle this situation? We know that we have a fixed page layout, however do the users of this application always expect a single-page document, or is it ok to generate a multi-page document? After contacting the main stakeholder, we found out that it’s acceptable to let text spill onto a second page as long as it is clear that the text on the second page carries on from the first.
This new requirement means we need to completely rethink how the document is structured: we need to move away from hard-coded sizes to objects which are able to grow dynamically and which allow text to flow across multiple pages if necessary. We also need to be able to handle single- and multi-page documents from the same code.
Bugs are opportunities
This bug is not only a great opportunity to learn something (for instance, I’ve never worked with ReportLab before) but also for me to sit back and think more carefully about the application and how parts of it could be structured so as to avoid issues cropping up in the future. For instance, how could we avoid assuming that the output will always be a single page? What else is lurking in there that could be a risk for future changes?
We need to step back/zoom out from the task at hand (i.e. bug fixing) and look at the code at larger scales. It can be instructive to take a moment and consider the code and the system in which it is contained, even if one doesn’t actively make any changes; it’s helpful just to load everything into your head and take a new perspective to see how things could look differently and how one could reduce future risk.
A short excursion into building documents with ReportLab
Before the bug can be fixed in the production code, it’s instructive to take a quick excursion into how to build a PDF document from scratch using ReportLab. This way, we’ll have a much better idea of what the code and its generic structure should look like before it’s actually changed “for real”.
ReportLab has a framework called PLATYPUS (see the ReportLab documentation
in Chapter 5 which
one can use to create documents. The name is derived from “Page Layout and
Typography Using Scripts”. Paraphrasing the documentation: within the
PLATYPUS framework one builds a PDF document by using a
DocumentTemplate
as the main container, which then contains one or more
PageTemplates, each
of which contains one or more
Flowable objects (such as
Paragraph,
Table, or
Image). To create a PDF document, one simply calls the
build() method of the instantiated document object.
Remember the full document layout I mentioned at the beginning?
Well, let’s slowly build an example document with this layout in mind, but
this time using
DocumentTemplate and
Flowable objects.
For simple documents, one can use the
SimpleDocTemplate class provided by
the ReportLab library because it already provides its own
PageTemplate and
Frame setup so we don’t have to. A document is created via the PLATYPUS
layout engine from a list of
Flowable objects passed to the
SimpleDocTemplate instance. The ReportLab docs have a nice way of doing
this: the variable containing the list of flowables is called
story, which
makes sense, because a document “tells a story” even if it is automatically
generated from some collection of database entries.
Here’s probably the simplest code one can use to create a PDF document:
from reportlab.platypus import SimpleDocTemplate, Paragraph def render(): story = [Paragraph("Hello, world!")] doc = SimpleDocTemplate("basic-doc-template-doc.pdf") doc.build(story) if __name__ == "__main__": render()
To add text to the document we simply pass a list containing a
Paragraph
of text to the
SimpleDocTemplate. What’s also good here is how nicely
this reads. In particular, the code
doc.build(story)
basically says “build the document from this story” (or equivalently “document: build this story”); it reads almost like an English sentence and makes the code much easier to understand at a glance.
Text spills onto subsequent pages
Now, just to make sure that creating a document from a “story” of paragraphs does flow automatically from one page onto another (as we expect it does), let’s take the basic example above and extend it to use multiple paragraphs of lorem ipsum text, separated by a bit of vertical whitespace to visually separate the blocks of text.
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer from reportlab.lib.units import mm from lorem_text import lorem def render(): story = [] story.append(Paragraph(lorem.paragraphs(3))) story.append(Spacer(1, 5*mm)) story.append(Paragraph(lorem.paragraphs(3))) story.append(Spacer(1, 5*mm)) story.append(Paragraph(lorem.paragraphs(3))) story.append(Spacer(1, 5*mm)) story.append(Paragraph(lorem.paragraphs(3))) doc = SimpleDocTemplate("multi-page-doc-template-doc.pdf") doc.build(story) if __name__ == "__main__": render()
Running this code we find that the text in the generated document flows naturally from the first page onto the second as we intend.
We now have the building blocks required to reproduce the full original document without being restricted to a single page.
Finally building the full document
Because the full document is split into three main blocks, let’s build these separately and then stitch everything together at the end.
Building the document title block
Remember that the document title block is an element with the document title text set to the left, and a logo image set to the right of the text:
To build this, we’re going to create a table with two columns and one row,
the left-hand column will contain a
Paragraph with the title text and the
right-hand column will contain an
Image with a sample logo image. Here’s
the code:
from reportlab.platypus import SimpleDocTemplate, Paragraph, Image, Table from reportlab.lib.units import mm def render(): logo_filename = "sample-logo.png" logo = Image(logo_filename, width=20*mm, height=10*mm) title_text = Paragraph("Document title") title = [Table([[title_text, logo]])] doc = SimpleDocTemplate("document-title-block.pdf") doc.build(title) if __name__ == "__main__": render()
Even though they are hard coded, the dimensions of the logo image are
sufficient for our purposes here. Note that a
Table takes a 2-D array of
strings or
Flowable objects as its data input, therefore to get a table
with one row and
n columns, we need to pass a
1xn array into the
Table
constructor, i.e.:
[['a', 'b', 'c', 'd']]
Similarly, to get a table with
n rows and one column, we pass an
nx1
array:
[['a'], ['b'], ['c'], ['d']]
Running this script we get the following output:
Which is a start, but it’s not styled the way we’d like it to be: the text should be larger, the logo should be aligned to the right-hand margin, and everything should be vertically distributed around the middle of the objects’ respective heights. We need to use styles to get things to look right.
A very brief introduction to ReportLab styles
ReportLab defines a set of base styles which one can access by calling the
getSampleStyleSheet function defined in the
styles package:
from reportlab.lib.styles import getSampleStyleSheet
I prefer to import this as
getBaseStyleSheet as this name seems to better
represent what this function returns: namely the base stylesheet defined by
the ReportLab library:
from reportlab.lib.styles import getSampleStyleSheet as getBaseStyleSheet
Calling the
.list() method on the stylesheet returns the available styles
in all their glory:
stylesheet = getBaseStyleSheet() stylesheet.list()
Running this code one sees that there are definitions for paragraphs, headings, unordered lists and many more typical textual elements.
Using ReportLab styles for the title text
The output of
stylesheet.list() contains a
Title style, so it seems
logical to use that for our title text. Looking at the output for the
Title style very carefully, we see that its
alignment property is set to
1:
Title title name = Title parent = <ParagraphStyle 'Normal'> alignment = 1 <snip>
What does the value of
1 mean for the
alignment? Searching through the
docs we find this text:
There are four possible values of
alignment, defined as constants in the module
reportlab.lib.enums. These are
TA_LEFT,
TA_CENTERor
TA_CENTRE,
TA_RIGHTand
TA_JUSTIFY, with values of 0, 1, 2 and 4 respectively. These do exactly what you would expect.
In other words,
alignment = 1 means that the text is centred, which isn’t
what we want: we’d like the title text to be left-justified, hence we import
the
TA_LEFT enum from the
enums package and set the
alignment
parameter of the imported
Title style to
TA_LEFT, in other words, we
extend the code with this import:
from reportlab.lib.enums import TA_LEFT
and these settings:
stylesheet = getBaseStyleSheet() title_style = stylesheet["Title"] title_style.alignment = TA_LEFT title_text = Paragraph("Document title", title_style)
which builds the title text the way we’d like. Note that we can select which of the various styles we want to use by using the style’s name as a key to the stylesheet data structure.
Styling a table with ReportLab
When styling a table, things are a bit more tricky, however a lot more flexible, because one can style individual table cells if one wants to. A table style is defined as a list of tuples defining the formatting commands to use for the given cells. For instance, to right-justify the cell in the second column of the first row, we use a tuple like this:
('ALIGN', (1, 0), (1, 0), 'RIGHT')
where the formatting command is
ALIGN.
The next two tuples define the cell (or range of cells) to format, by–confusingly–using column-row ordering for the tuples, rather than row-column ordering which one might expect. This is, however mentioned in the documentation:
The coordinates are given as (column, row) which follows the spreadsheet ‘A1’ model, but not the more natural (for mathematicians) ‘RC’ ordering.
Finally, we specify the alignment setting to use, in this case
RIGHT.
Since we also want to vertically centre the elements in the document title
block, we also use the
VALIGN command like so:
('VALIGN', (0, 0), (-1, -1), 'MIDDLE')
where we have defined a range of cells from the upper-left cell
(0, 0) to
the “last” cell in each dimension
(-1, -1) by using the Python convention
of specifying the last element of a list by using negative indices. The
vertical alignment is then set to
MIDDLE so that the objects are nicely
vertically distributed around their centre lines.
from reportlab.platypus import SimpleDocTemplate, Paragraph, Image, Table from reportlab.lib.styles import getSampleStyleSheet as getBaseStyleSheet from reportlab.lib.units import mm from reportlab.lib.enums import TA_LEFT def render():)] doc = SimpleDocTemplate("document-title-block.pdf") doc.build(title) if __name__ == "__main__": render()
which gives this output:
and is much closer to the styling we want for this part of the document.
Let’s now turn our attention to the middle part of the document, which, as we’ll see, requires a bit more thought to get the layout right.
Building the info and image boxes
As a reminder, the section of the document that we want to build looks like this:
Naively, (and after having read the documentation) one could assume that
since we want a two-column layout here, that the
BalancedColumns class
would be the best thing to use. Unfortunately, this isn’t the right thing
to use in this case because we want the info boxes to always be in the
left-hand column and we want the image boxes to always be in the right-hand
column. Using the
BalancedColumns class would make elements flow from one
column into the other in order to balance things out, which is probably what
one wants in most situations, however (just to be different!) we don’t want
that here: the columns have to be unbalanced and we don’t want any
excess from one column spilling over into the other column automatically.
To get this layout right, I’m going to use a single-column
Table just for
the info boxes, and a single-column
Table just for the image boxes. Then
I’m going to embed these single-column tables into a single-row, two-column
Table so that we can get the desired effect. Embedding tables within a
table allows the vertical content to stay within its given column and hence
allows us to have unbalanced columns in the main table.
The left-hand column ends up being quite simple, it’s just a single-column
table of
Paragraph objects:
left_table_style = [ ('BOX', (0, 0), (-1, -1), 2, red), # highlight table border ] left_column = Table( [ [Paragraph(lorem.paragraph())], [Paragraph(lorem.paragraph())], [Paragraph(lorem.paragraph())], ], style=left_table_style)
where I’ve added a red border to highlight the table’s extent. Note that
the
red colour is imported from the
colors package:
from reportlab.lib.colors import red
For the right-hand column, we load an image, scale it to be a bit under half
the width of the document (so that it fits nicely within the column) and
then add it twice to a single-column
Table via an
Image
object:2
doc = SimpleDocTemplate("info-and-image-box-block.pdf"))
where I’ve again added a red border to highlight this table’s extent and
I’ve had to instantiate the
doc object earlier so that I can get access to
its
width parameter.
Now we just combine these two tables in a
Table with one row and two
columns and build the document:
table_style = [ ('BOX', (0, 0), (-1, -1), 2, red), # highlight table border ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('ALIGN', (1, 0), (-1, -1), 'CENTER') ] columns = [Table([[left_column, right_column]], style=table_style)] doc.build(columns)
where all elements in this table (namely the two sub-tables) are aligned vertically to the top of the encapsulating table, and the right-hand column is aligned in the centre which looks a bit nicer than the default left-justification.
Putting this all together we get:
from reportlab.platypus import SimpleDocTemplate, Paragraph, \ Image, Table from reportlab.lib.colors import red from PIL import Image as PILImage from lorem_text import lorem def render(): doc = SimpleDocTemplate("info-and-image-box-block.pdf") left_table_style = [ ('BOX', (0, 0), (-1, -1), 2, red), # highlight table border ] left_column = Table( [ [Paragraph(lorem.paragraph())], [Paragraph(lorem.paragraph())], [Paragraph(lorem.paragraph())], ], style=left_table_style)) table_style = [ ('BOX', (0, 0), (-1, -1), 2, red), # highlight table border ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('ALIGN', (1, 0), (-1, -1), 'CENTER') ] columns = [Table([[left_column, right_column]], style=table_style)] doc.build(columns) if __name__ == "__main__": render()
which looks like this:
Note that this output can be cleaned up (i.e. the red borders can be
removed) by removing the
BOX table formatting commands.
Building the comments block
Creating the comments block is by far the easiest part about constructing this document:
from reportlab.platypus import SimpleDocTemplate, Paragraph from lorem_text import lorem def render(): comments = [Paragraph(lorem.paragraphs(4))] doc = SimpleDocTemplate("comments-block.pdf") doc.build(comments) if __name__ == "__main__": render()
which, as one would expect, gives this output:
We now just need to stitch all these pieces together in a single document.
Building the full document
Using the code from the previous three sections, we can create a
story
which contains all of the objects we want to add to the document as well as
their styling. The main task of laying out the code on the page is handled
by the PLATYPUS framework. We remove the red borders from the tables in the
info and image box block and reduce the length of the comments block
slightly. Making these changes gives us the following code for the full
document:
from reportlab.platypus import SimpleDocTemplate, Paragraph, Image, Table from reportlab.lib.styles import getSampleStyleSheet as getBaseStyleSheet from reportlab.lib.units import mm from reportlab.lib.enums import TA_LEFT from PIL import Image as PILImage from lorem_text import lorem def render(): doc = SimpleDocTemplate("full-document.pdf") # document title block) # info and image box block left_column = Table( [ [Paragraph(lorem.paragraph())], [Paragraph(lorem.paragraph())], [Paragraph(lorem.paragraph())], ]) image_fname = "colosseum-rome-2004.jpg" img_width, img_height = PILImage.open(image_fname).size scaled_img_width = doc.width/2.2 scaled_img_height = img_height*scaled_img_width/img_width right_column = Table( [ [Image(image_fname, width=scaled_img_width, height=scaled_img_height)], [Image(image_fname, width=scaled_img_width, height=scaled_img_height)], ]) table_style = [ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('ALIGN', (1, 0), (-1, -1), 'CENTER') ] columns = Table([[left_column, right_column]], style=table_style) # comments block comments = Paragraph(lorem.paragraphs(2)) story = [ title, columns, comments ] doc.build(story) if __name__ == "__main__": render()
which, when run, gives this output:
Playing around with the amount of text provided by the
lorem package, we
can see that the comments block text naturally and automatically flows onto
a subsequent page should the amount of content on the first page be too
large.
We did it!
Fixing the bug
Now comes the tricky part: fixing the bug in the production code.
Fortunately, we have lots of tests (at the time of writing, 259 tests with 84% total code coverage and 97% coverage in the affected module), therefore we can be fairly confident that any changes we make won’t randomly break something else.
First, we’ll need to add a failing test which reproduces the problem; this will catch any problems should a regression occur in the future. Then, we’ll update the production code to fix the issue and consequently should see the test pass.
Writing a failing test to expose the problem
In order to avoid leaking internal information about the system, I’m just going to describe the test I ended up creating in words:
- set up the object used to generate the PDF document.
- ensure that the text in the comment block is too big to fit into its assigned space (by repeating the string
This text is visible in the generated PDF.many times.
- assert that the string should appear in the output PDF (when compression is turned off, the string will appear as text in the raw PDF file).
As expected, this test fails. I also checked that the test passes when the text in the comment block isn’t too big for its assigned space, that way we know that the test is working correctly.
Now that we know we’ve got the right test, we can comment it out temporarily
and then refactor the current implementation to replace a collection of
Frame objects with a
SimpleDocTemplate; in other words (paraphrasing
Kent Beck):
Make the change easy, then make the easy change.
Refactoring the implementation to allow for more flexibility
The original implementation had a special method which extracted the PDF page content before it was saved to file so that the content (which is basically a string at this point) could be tested. IIRC, the reason for this method existing was because (at the time) the output PDF couldn’t be read as a string and hence we couldn’t check that the expected text elements appeared in the output. While working on this bug fix I noticed that PDF compression was the reason that one couldn’t use the saved PDF file to check for expected text elements.
A bit of testing showed that (in the case for the documents produced here)
compression didn’t bring much of a win (compressed and uncompressed files
were ~400kB and ~500kB respectively), so by importing the
rl_config module
and setting
pageCompression to zero:
from reportlab import rl_config rl_config.pageCompression = 0
meant that we can now, theoretically, tap into the saved PDF output to check for the presence of expected text elements.
Although it’s a bit of an anti-pattern to have a method on a class just for
testing, I decided to follow this pattern and add an extra method to access
the PDF output built via
SimpleDocTemplate before it was saved to file.
This allowed me to reproduce the assertions in the currently-available test
code (as well as maintain the general “shape” of the test code) so that I
could build a “shadow” version of the PDF output using
SimpleDocTemplate,
however without affecting the production code. This means that one could
have taken any commit and pushed it to production and the code would still
have used the original PDF generation implementation even though the new
implementation was only partially available.
This might sound like extra work (and it is), however it means that each
commit passes the test suite (which then allows us to use
git bisect
automatically in the future if necessary) and means that each commit is
potentially releasable, which is of great help in a continuous integration
environment.
I extended each test so that it tested both the original and the new implementation which in turn helped guide making the new implementation. The new code was thus built incrementally and checked against an already-available test suite to ensure the desired functionality was available in both the new implementation as well as the original implementation. Having already made a prototype implementation as discussed in previous sections helped a lot in this process because the problem space had already been well explored.
Out with the old; in with the new
Once the new implementation was in place–and once the page formatting was fine-tuned to better match the original implementation–it was possible to simply delete the old implementation and the tests of the old implementation and things “just worked”!
In the end I was also able to remove the special function used to access the
PDF output for testing because the final
render() method was able to be
used directly, since page compression was found to be no longer necessary.
Therefore, an anti-pattern “smell” could be removed from the code as well!
Win-win!
So, after squashing a few commits that were doing the same task and reorganising things a bit, it turned out to take 41 commits to refactor the code and make this bug fix.
Rolling out to production
I contacted the main stakeholder to get feedback as to whether or not the output from the new implementation is acceptable. In particular, the page layout changed slightly from the original implementation as there is less extra vertical whitespace present and I needed to confirm that such changes (which look ok to me) are ok for people using the system; after all, they’re the ones who are most affected by any changes.
They were happy with the new output and everything has now been rolled out on the production system. Job done! Yay!
That was fun!
Well, that was fun! Not only was the problem solved for the user, but I also got
to learn something at the same time.
I hope that this story was helpful and even interesting! If you have any comments, questions or feedback, feel free to ping me on Twitter or drop me a line via email.
Also, I’m sure there’s a classicist screaming somewhere at my use of the word “lorems”, but I digress. ↩
I use two images here in the right-hand column to simulate the situation in the production environment more closely. ↩
Support
If you liked this post and want to spur me on to write up more of my adventures in IT-land, please buy me a coffee or support me on Patreon!
| https://ptc-it.de/reportlab-vanishing-text-bug/ | CC-MAIN-2022-40 | refinedweb | 5,961 | 55.27 |
Connect chats bots to your API apps
Project description
CI:
PyPI:
Docs:
Build chat bots and connect then to your app APIs.
With Permabots you can build chat bots and with the same configuration use it for several instant messaging providers. Permabots was born to be a microservice to connect messaging providers to your apps using REST APIs.
Documentation
The full documentation is at.
Features
- Telegram, Kik and Facebook Messenger bots
- Message handling definition with regex, as django urls.
- HTTP methods: GET/POST/PUT/DELETE/PATCH
- Text responses and keyboards with Jinja2 templates
- Chat State handling
- Asynchronous processing of messages
- Media messages not supported
Quickstart
Install permabots:
pip install permabots
Add permabots to your INSTALLED_APPS, and run:
$ python manage.py migrate permabots
Instant messaging providers uses webhooks to send messages to your bots. Add permabots processing urls to your urlpatterns:
url(r'^processing/', include('permabots.urls_processing', namespace="permabots"))
Webhooks are generated with django.contrib.sites. You need it installed and SITE_ID configured. If you want to generate webhook manually you can do it:
MICROBOT_WEBHOOK_DOMAIN = ''
It is usefull when you don’t have https in your public domain but you have it in your autogenerated domain. i.e. heroku.
Bots are associated to Django Users. You need at least one user, for example admin user.
Then you can create all permabots data, Bots, Conversation Handlers, Notitication Hooks,… via Django admin or with REST API (recommended).
Remember there is an online implementation in to use it for free.
Demo
You can check and deploy a Permabots demo
Running Tests
Does the code actually work?
source <YOURVIRTUALENV>/bin/activate (myenv) $ pip install -r requirements/test.txt (myenv) $ make test (myenv) $ make test-all
History
0.1.0 (2016-05-16)
- First release on PyPI.
Project details
Release history Release notifications
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/permabots/ | CC-MAIN-2020-05 | refinedweb | 318 | 57.27 |
On Friday 07 August 2009 17:06:36 Juan Quintela wrote: > Bique Alexandre <address@hidden> wrote: > > The ATAPI pass through feature. > > +# define CHECK_SAME_VALUE(Val1, Val2) > > Can we call this something like: assert_equal() ? or anything else more > descriptive? It's not an assertion because Val1 and Val2 are allowed to be different and it doesn't call abort. It just displays some debut information. Would CHECK_EQUAL be alright for you ? > > +/* The generic packet command opcodes for CD/DVD Logical Units, > + * From Table 57 of the SFF8090 Ver. 3 (Mt. Fuji) draft standard. */ > +static const struct { > + unsigned short packet_command; > + const char * const text; > +} packet_command_texts[] = { > > Please, use C99 intializers: > > + { GPCMD_TEST_UNIT_READY, "Test Unit Ready" }, > > use this format, same for rest of structs > > { > .packet_command = GPCMD_TEST_UNIT_READY, > . }, I see no reason to do that. It takes more place. We are not going to add a lot of additional fields. And even if we do, this structure should be used only time at only one place and if we decide to add a new field in the beginning or the middle of this structure, it should be worth to do some regexp to fix the declaration. > +static void ide_atapi_pt_standard_reply(IDEState *s) > +{ > + uint32_t size = s->atapi_pt.reply_size_init; > + > + switch (s->atapi_pt.reply_size_len) > + { > + case 0: > + break; > + case 1: > + size += s->io_buffer[s->atapi_pt.reply_size_offset]; > + break; > + case 2: > + size += ube16_to_cpu(s->io_buffer + > s->atapi_pt.reply_size_offset); + break; > + case 3: > + size += ube24_to_cpu(s->io_buffer + > s->atapi_pt.reply_size_offset); + break; > + case 4: > + size += ube32_to_cpu(s->io_buffer + > s->atapi_pt.reply_size_offset); + break; > + default: > + assert(0); > ^^^^^^^ > print a nice error message? > die? > something? I Will do it, but what do you want me to say ? "We reached a part of the code we should never reach. Please send a bug report to Qemu developers. Thanks." ? > + break; > + } > > +static int ide_atapi_pt_read_cd_block_size(const uint8_t *io_buffer) > +{ > + int sector_type = (io_buffer[2] >> 2) & 7; > + int error_flags = (io_buffer[9] >> 1) & 3; > + int flags_bits = io_buffer[9] & ~7; > + int block_size = 0; > + > + // expected sector type > + switch (sector_type) > + { > + case 0: // Any type > + case 1: // CD-DA > + block_size = (flags_bits) ? 2352 : 0; > + break; > + > + case 2: // Mode 1 > + switch (flags_bits) > + { > + case 0x0: block_size = 0; break; > case 0x40: block_size = 0; break; > > move this one here, same fro the same two with 16 value? > group all of them by block_size? Same for the rest of the cases. I can but I don't want to. Because if you want to double check this, you would prefer to see this sorted so you can check the reference table at the same time you check your switch case. > + case 0x10: > + case 0x50: block_size = 2048; break; > + case 0x18: > + case 0x58: block_size = 2336; break; > + case 0x20: > + case 0x60: block_size = 4; break; > + case 0x30: > + case 0x70: > + case 0x78: block_size = 2052; break; > + case 0x38: block_size = 2340; break; > + case 0xa0: block_size = 16; break; > + case 0xb0: block_size = 2064; break; > + case 0xb8: block_size = 2352; break; > + case 0xe0: block_size = 16; break; > + case 0xf0: block_size = 2064; break; > + case 0xf8: block_size = 2352; break; > + > + default: return 0; // illegal > + } > > > +#if CONFIG_ATAPI_PT > +#include "atapi-pt.c" > +#endif > > Why do we include it here? coulden't yust compile it as a new file? I did. I am going to send you my new patches where I made some part of ide.c public and introduced 3 new headers. Thanks for review. -- Alexandre Bique | https://lists.gnu.org/archive/html/qemu-devel/2009-08/msg00359.html | CC-MAIN-2019-35 | refinedweb | 532 | 65.62 |
Hello, everyone. I need a little help. I am basically trying to make a crawler and then connect it to a database so that the crawled data can be stored and indexed there for retrieval later. But since I’m new to some aspects of Python and SQL, I need a little help. Any advice?
Firstly, welcome to the forums.
While we are primarily here to help people with their Free Code Camp progress, we are open to people on other paths, too. Free Code Camp focuses on using JavaScript instead of Python and SQL. / jsfiddle example of what they have tried so that anyone helping has more of an idea of what help is actually helpful.
Please provide some example of what you’ve tried and I’m sure you’ll get more help.
Happy coding
That’s the problem. As far as a connection between the two is concerned, I don’t have a code yet, not really. That’s what I am here for, to get an idea on how to handle this.
Try looking into the pyodbc module. I’ve used it quite a bit for connecting to Microsoft Access Databases.
Microsoft provides a python MSSQL driver. pymssql
@owel So I download the driver, then what? What do I do next? Do I have to configure something with SQL or something?
There are several example codes here.
This is just the driver for python to talk to an MSSQL server.
But you still need to know how to create/manage databases, tables and views in SQL Server, and know how to construct SQL commands. The driver is not magic, it’s just a go-between bridge between python and MSSQL server.
If you’ll be managing SQL databases, (creating tables, fields, indexes, views, stored procedures, full text, triggers, etc) you need to have Enterprise Manager software installed on your computer, and more importantly know how to use it.
I’m making the SQL connection using Visual Studio, but I’m unclear on how I can get the .py file, which is the crawler, to store crawled data into the SQL database. Suggestions?
Can you post the code you have so far in the .py file?
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
class ElectronicsSpider(CrawlSpider):
name = “electronics”
allowed_domains = [“”]
start_urls = [
‘’,
‘’
]
rules = ( Rule(LinkExtractor(allow=(), restrict_css=('.pageNextPrev',)), callback="parse_item", follow=True),) def parse_item(self, response): print('Processing..' + response.url) # print(response.text)
First off! What database are you using? Postgres, MySQL, Mongo…Hbase? Once you figure out that, you want to look if there is a client library that you can install and if you need to download native drivers (or if they are available). Native drivers are just drivers that the developers wrote to connect to the database instead of an open standard like say: ODBC. I use mostly postgres and so psycopg2 library works well. For psycopg2, I don’t think drivers are required on the client (but might be different for windows or might be a dependency that gets downloaded).
Usually, though this isn’t always the case, you establish a database connection using a connection function or by initiating a database engine that has a connect function. During this connection, you’ll have to provide a host, password and potentially a database name (if multiple entities exist within the database). Typically, you will either connect or get an error. This is normally binary: succeed or fail. If you get an error, there is a good chance that: 1. your credentials are wrong or 2. you are not establishing a connection to the database. The later is usually the result of: firewall, TCP/IP (internet) connection not being established or database permissions being off. You can usually figure this out through the error message.
If you succeed, it is often great to first query for the databases or users available within the database. This guarantees you are connected and have access to the right user/database. Afterwards, I’d query against actual data entities like relational tables or document stores. If you do this, you typically get returned an iterable object or generator, which you can manipulate.
Well depending on what sql database you are using you can pip install pymssql for microsoft sql (mssql), psycopg2 for postgres (psql) or mysqldb for mysql databases Here are a few examples of using it
Microsoft sql
\\
import pymssql
conn = pymssql.connect(server=server, user=user, password=password, database=db)
cursor = conn.cursor()
cursor.execute(“SELECT COUNT(MemberID) as count FROM Members WHERE id = 1”)
row = cursor.fetchone()
conn.close()
print(row)
//////
Postgres
\\
import psycopg2
conn = psycopg2.connect(database=db, user=user, password=password, host=host, port=“5432”)
cursor = conn.cursor()
cursor.execute(‘SELECT COUNT(MemberID) as count FROM Members WHERE id = 1’)
row = cursor.fetchone()
conn.close()
print(row)
/////
mysql
\\
import MySQLdb
conn = MySQLdb.connect(host=host, user=user, passwd=passwd, db=db)
cursor = conn.cursor()
cursor.execute(‘SELECT COUNT(MemberID) as count FROM Members WHERE id = 1’)
row = cursor.fetchone()
conn.close()
print(row)
////// | https://forum.freecodecamp.org/t/connecting-a-python-file-with-a-sql-database/192679 | CC-MAIN-2021-10 | refinedweb | 842 | 66.23 |
What is the problem
Validation and typing are separable but often conflated concepts. IDness is
Evidence of breakage
Many XML-related specs depend on knowing which attributes are of type ID - but all do it differently..] {color: red ! important}. Of course, elements in XML 1.0 documents without a DTD do not have IDs at all.).
Validity-based solutions
These solutions address the problem by insisting that validation be used to create IDness and that documents which are not valid have no IDs..
Require Schema processing is always validation as well?
Schema or DTD based solutions
These solutions address the problem by insisting that IDness only comes from DTD or Schema processing (irrespective of whether that processing is related to validation)..
Steal the string "id" existiing XML usage does indeed call its ID attributes 'id'. This solution is an XML language change.'
Add a predeclared id attribute, could be used by any XML vocabulary that wanted interoperability even in the case that DTDs were not being read. Because it is predeclared, it could not clash with whatever a DTD or schem asaid,..
Discussion
Requiring DTD validation to get IDs is too big a retrogressive step; it essentially throws away well formedness as a concept and also XML namespaces, and needlessly conflates validation with decoration.
Requiring W3C XML Schema validation to get IDs is probably too big a forwards step; it adds a lot of machinery to get a simple but crucial step forward and needlessly conflates validation with decoration. However, it is possible that creative use of xsi:type in the instance.
Some people have suggested that this problem is specific example of a more general problem that 'well formed' is a broken concept and should be removed or deptrecated,.
Conclusions
This document would benefit from more discussion. No conclusion is presented. This document is a summary made available by the TAG; it is hoped that it lists all the solutions that have been proposed, and their advantages and disadvantages, which should help any group chartered to deal with this problem. The TAG is unhappy with the current situation and would like to see further discussion and convergence on a solution. | http://www.w3.org/2001/tag/doc/xmlIDsemantics-32-20030512.html | CC-MAIN-2014-35 | refinedweb | 361 | 52.39 |
We want to separate report layout from data generation logic.
Our data generation logic is a class like this:
class Generator
{
public Data Generate(/* parameters here*/);
}
Where Data is like this:
class Data
{
public List<RowType1> List1;
public List<RowType2> List2;
// other collections
}.
Is there any way to do this elegantly with Telerik Reporting, while avoiding multiple calls to report generation logic and avoiding UI/logic mix?
6 Answers, 1 is accepted
Hello Dmytro,
Our ObjectDataSource component support Business objects - check Supported Object Types.
Basically, when you add the ObjectDataSource to the report and it points to the Generator class, you will see only one property - Generate (i.e. Fields.Generate). However, you still can display the data from the lists inside Generate. You will need to assign the DataSource of the List/Table/Crosstab item where the data of each list will be displayed through a Binding. For more information, refer to How to Databind to Collection Properties KB article. Note that you will not able to see the properties of the lists in Design time but they can be used, i.e. should be typed manually.
I hope the provided information will help. Let us know if you have further questions.
Regards,
Neli
Progress Telerik
Hi Neli,
thank you for reply. But i'm not sure if I completely get it.
So, i have this Generator class with Generate method (which potentially takes some parameters).
So, i've created an ObjectDataSource and set its "DataSource" method to "Generator" and "DataMember" to "Generate". I've also set "Parameters" to whatever parameters has to be passed. Is this correct so far?
Now, i add a Table component to my report and want to bind it's DataSource to List1 from the ObjectDataSource i have. How do I do that?
Best regards,
Dmytro
Hello Dmytro,
From the description, it seems that so far everything is correct.
I prepared sample project which demonstrates the following approach:
1. Create a ClassLibrary which has to lists - one with cars and another with items;
2. Build the project;
3. Add a Report Library to the solution (in your case you will need to add the dll file to the Standalone Designer's location);
4. Add an assembly reference in a Telerik section to the App.config file of the report library:
<configuration> <configSections> <section name="Telerik.Reporting" type="Telerik.Reporting.Configuration.ReportingConfigurationSection, Telerik.Reporting" allowLocation="true" allowDefinition="Everywhere" /> </configSections> <Telerik.Reporting> <assemblyReferences> <add name="ClassLibrary1"/> </assemblyReferences> </Telerik.Reporting> </configuration>
5. Add an ObjectDataSource for the cars (select Cars() for the DataMember);
6. Add a table item -> select its datasource -> add the desired fields;
7. Repeat the same for the items.
You can check the attached project (Build first), as well as our DataBinding report which demonstrates how to assign a datasource to a list item. The report can be found at: C:\Program Files (x86)\Progress\Telerik Reporting <Version>\Examples\CSharp\ReportLibrary
Regards,
Neli
Progress Telerik
Hi Neli,
Thank you for your reply. While your sample project is useful, it does not actually answer my question.
You see, in your sample project you have 2 datasets, each of which creates a separate DataObject. Thus, in a scenario where business objects call a DB (or a REST service), this will result in 2 calls. That's exactly what i want to avoid as i've described in my initial posting:
>.
Sorry, if this was not very clearly stated.
So ... is it possible to achieve what we need here while only having one DataObject created (and its Generate method called exactly once)?
Best regards,
Dmytro
Hello Dmytro,
I made the following changes to the previously provided application:
In the ClassLibrary:
1. Remove the Cars and Items classes.
2. Create a new class named Data and add the following properties:
public class Data { public List<Car> Cars { get; set; } public List<Item> Items { get; set; } }
3. Create a class named Generator where we will add the data:
public class Generator { public List<Item> Items() { List<Item> items = new List<Item>(); Item item; item = new Item("Reporting", 599); items.Add(item); item = new Item("DevCraft", 1499); items.Add(item); return items; } public List<Car> Cars() { List<Car> cars = new List<Car>(); Car car; car = new Car("Honda", "NSX GT", 2003); cars.Add(car); car = new Car("Nissan", "Skyline R34 GT-R", 2005); cars.Add(car); car = new Car("Audi", "S4", 2006); cars.Add(car); return cars; } public Data Generate() { Data data = new Data() { Cars = this.Cars(), Items = this.Items() }; return data; } }
3. Rebuild the solution.
Go to the ReportLibrary:
1. Remove the datasources;
2. Add a new ObjectDataSource and set is as follows:
- in Choose a Business Object dialog, select Generator;
- in Choose a Data Member -> Generate() : Data;
3. Set the ObjectDataSource to be the DataSource of the report;
4. Set the datasource of the tables through the following Bindings:
Property path: DataSource
Expression: =Fields.Cars / =Fields.Items
Regards,
Neli
Progress Telerik | https://www.telerik.com/forums/multiple-collections-in-objectdatasource | CC-MAIN-2021-39 | refinedweb | 823 | 58.38 |
Regular expressions are used for defining String patterns that can be used for searching, manipulating and editing a text. These expressions are also known as Regex (short form of Regular expressions).
Lets take an example to understand it better:
In the below example, the regular expression
.*book.* is used for searching the occurrence of string “book” in the text.
import java.util.regex.*; class RegexExample1{ public static void main(String args[]){ String content = "This is Chaitanya " + "from Beginnersbook.com."; String pattern = ".*book.*"; boolean isMatch = Pattern.matches(pattern, content); System.out.println("The text contains 'book'? " + isMatch); } }
Output:
The text contains 'book'? true
In this tutorial we will learn how to define patterns and how to use them. The java.util.regex API (the package which we need to import while dealing with Regex) has two main classes:. This is one of simplest and easiest way of searching a String in a text using Regex.
String content = "This is a tutorial Website!"; String patternString = ".*tutorial.*"; boolean isMatch = Pattern.matches(patternString, content); System.out.println("The text contains 'tutorial'? " + isMatch);
As you can see we have used matches() method of Pattern class to search the pattern in the given text. The pattern
.*tutorial.* allows zero or more characters at the beginning and end of the String “tutorial” (the expression
.* is used for zero and more characters).
Limitations: This way we can search a single occurrence of a pattern in a text. For matching multiple occurrences you should use the Pattern.compile() method (discussed in the next section).
2) Pattern.compile()
In the above example we searched a string “tutorial” in the text, that is a case sensitive search, however if you want to do a CASE INSENSITIVE search or want to do search multiple occurrences then you may need to first compile the pattern using Pattern.compile() before searching it in text. This is how this method can be used for this case.
String content = "This is a tutorial Website!"; String patternString = ".*tuToRiAl."; Pattern pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE);
Here we have used a flag Pattern.CASE_INSENSITIVE for case insensitive search, there are several other flags that can be used for different-2 purposes. To read more about such flags refer this document.
Now what: We have obtained a Pattern instance but how to match it? For that we would be needing a Matcher instance, which we can get using Pattern.matcher() method. Lets discuss it.
3) Pattern.matcher() method
In the above section we learnt how to get a Pattern instance using compile() method. Here we will learn How to get Matcher instance from Pattern instance by using matcher() method.
String content = "This is a tutorial Website!"; String patternString = ".*tuToRiAl.*"; Pattern pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(content); boolean isMatched = matcher.matches(); System.out.println("Is it a Match?" + isMatched);
Output:
Is it a Match?true
4) Pattern.split()
To split a text into multiple strings based on a delimiter (Here delimiter would be specified using regex), we can use Pattern.split() method. This is how it can be done.
import java.util.regex.*; class RegexExample2{ public static void main(String args[]){ String text = "ThisIsChaitanya.ItISMyWebsite"; // Pattern for delimiter String patternString = "is"; Pattern pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE); String[] myStrings = pattern.split(text); for(String temp: myStrings){ System.out.println(temp); } System.out.println("Number of split strings: "+myStrings.length); }}
Output:
Th Chaitanya.It MyWebsite Number of split strings: 4
The second split String is null in the output.
java.util.regex.Matcher Class
We already discussed little bit about Matcher class above. Lets recall few things:
Creating a Matcher instance
String content = "Some text"; String patternString = ".*somestring.*"; Pattern pattern = Pattern.compile(patternString); Matcher matcher = pattern.matcher(content);
Main methods
matches(): It matches the regular expression against the whole text passed to the Pattern.matcher() method while creating Matcher instance.
... Matcher matcher = pattern.matcher(content); boolean isMatch = matcher.matches();
lookingAt(): Similar to matches() method except that it matches the regular expression only against the beginning of the text, while matches() search in the whole text.
find(): Searches the occurrences of of the regular expressions in the text. Mainly used when we are searching for multiple occurrences.
start() and end(): Both these methods are generally used along with the find() method. They are used for getting the start and end indexes of a match that is being found using find() method.
Lets take an example to find out the multiple occurrences using Matcher methods:
package beginnersbook.com; import java.util.regex.*; class RegexExampleMatcher{ public static void main(String args[]){ String content = "ZZZ AA PP AA QQQ AAA ZZ"; String string = "AA"; Pattern pattern = Pattern.compile(string); Matcher matcher = pattern.matcher(content); while(matcher.find()) { System.out.println("Found at: "+ matcher.start() + " - " + matcher.end()); } } }
Output:
Found at: 4 - 6 Found at: 10 - 12 Found at: 17 - 19
Now we are familiar with Pattern and Matcher class and the process of matching a regular expression against the text. Lets see what kind of various options we have to define a regular expression:
1) String Literals
Lets say you just want to search a particular string in the text for e.g. “abc” then we can simply write the code like this: Here text and regex both are same.
Pattern.matches("abc", "abc")
2) Character Classes
A character class matches a single character in the input text against multiple allowed characters in the character class. For example [Cc]haitanya would match all the occurrences of String “chaitanya” with either lower case or upper case C”. Few more examples:
Pattern.matches("[pqr]", "abcd"); It would give false as no p,q or r in the text
Pattern.matches("[pqr]", "r"); Return true as r is found
Pattern.matches("[pqr]", "pq"); Return false as any one of them can be in text not both.
Here is the complete list of various character classes constructs:
[abc]: It would match with text if the text is having either one of them(a,b or c) and only once.
[^abc]: Any single character except a, b, or c (^ denote negation)
[a-zA-Z]: a through z, or A through Z, inclusive (range)
[a-d[m-p]]: a through d, or m through p: [a-dm-p] (union)
[a-z&&[def]]: Any one of them (d, e, or f)
[a-z&&[^bc]]: a through z, except for b and c: [ad-z] (subtraction)
[a-z&&[^m-p]]: a through z, and not m through p: [a-lq-z] (subtraction)
Predefined Character Classes – Metacharacters
These are like short codes which you can use while writing regex.
Construct Description . ->]
For e.g.
Pattern.matches("\\d", "1"); would return true
Pattern.matches("\\D", "z"); return true
Pattern.matches(".p", "qp"); return true, dot(.) represent any character
Boundary Matchers
^ Matches the beginning of a line. $ Matches then end of a line. \b Matches a word boundary. \B Matches a non-word boundary. \A Matches the beginning of the input text. \G Matches the end of the previous match \Z Matches the end of the input text except the final terminator if any. \z Matches the end of the input text.
For e.g.
Pattern.matches("^Hello$", "Hello"): return true, Begins and ends with Hello
Pattern.matches("^Hello$", "Namaste! Hello"): return false, does not begin with Hello
Pattern.matches("^Hello$", "Hello Namaste!"): return false, Does not end with Hello
Quantifiers
Greedy Reluctant Possessive Matches X? X?? X?+ Matches X once, or not at all (0 or 1 time). X* X*? X*+ Matches X zero or more times. X+ X+? X++ Matches X one or more times. X{n} X{n}? X{n}+ Matches X exactly n times. X{n,} X{n,}? X{n,}+ Matches X at least n times. X{n, m) X{n, m)? X{n, m)+ Matches X at least n time, but at most m times.
Few examples
import java.util.regex.*; class RegexExample{ public static void main(String args[]){ // It would return true if string matches exactly "tom" System.out.println( Pattern.matches("tom", "Tom")); //False /* returns true if the string matches exactly * "tom" or "Tom" */ System.out.println( Pattern.matches("[Tt]om", "Tom")); //True System.out.println( Pattern.matches("[Tt]om", "Tom")); //True /* Returns true if the string matches exactly "tim" * or "Tim" or "jin" or "Jin" */ System.out.println( Pattern.matches("[tT]im|[jJ]in", "Tim"));//True System.out.println( Pattern.matches("[tT]im|[jJ]in", "jin"));//True /* returns true if the string contains "abc" at * any place */ System.out.println( Pattern.matches(".*abc.*", "deabcpq"));//True /* returns true if the string does not have a * number at the beginning */ System.out.println( Pattern.matches("^[^\\d].*", "123abc")); //False System.out.println( Pattern.matches("^[^\\d].*", "abc123")); //True // returns true if the string contains of three letters System.out.println( Pattern.matches("[a-zA-Z][a-zA-Z][a-zA-Z]", "aPz"));//True System.out.println( Pattern.matches("[a-zA-Z][a-zA-Z][a-zA-Z]", "aAA"));//True System.out.println( Pattern.matches("[a-zA-Z][a-zA-Z][a-zA-Z]", "apZx"));//False // returns true if the string contains 0 or more non-digits System.out.println( Pattern.matches("\\D*", "abcde")); //True System.out.println( Pattern.matches("\\D*", "abcde123")); //False /* Boundary Matchers example * ^ denotes start of the line * $ denotes end of the line */ System.out.println( Pattern.matches("^This$", "This is Chaitanya")); //False System.out.println( Pattern.matches("^This$", "This")); //True System.out.println( Pattern.matches("^This$", "Is This Chaitanya")); //False } }
Reference
Regular expressions – Javadoc | http://beginnersbook.com/2014/08/java-regex-tutorial/ | CC-MAIN-2016-50 | refinedweb | 1,580 | 60.11 |
Bugzilla – Bug 1528
TypeInitializationException when using classes depending on System.Configuration.ConfigurationManager in packaged MonoMac application
Last modified: 2012-12-12 20:42:59 EST
MonoMac linker removes default constructor for
System.Configuration.ExeConfigurationHost type.
E.g. WebRequest request = WebRequest.Create(""); crashes with
such stack trace:
[ERROR] FATAL UNHANDLED EXCEPTION: System.TypeInitializationException: An
exception was thrown by the type initializer for System.Net.WebRequest --->
System.Configuration.ConfigurationErrorsException: Error Initializing the
configuration system. ---> System.MissingMethodException: Default constructor
not found for type System.Configuration.ExeConfigurationHost.
at System.Activator.CreateInstance (System.Type type, Boolean nonPublic)
[0x00000] in <filename unknown>:0
at System.Activator.CreateInstance (System.Type type) [0x00000] in <filename
unknown>:0
at System.Configuration.InternalConfigurationSystem.Init (System.Type
typeConfigHost, System.Object[] hostInitParams) [0x00000] in <filename
unknown>:0
at System.Configuration.InternalConfigurationFactory.Create (System.Type
typeConfigHost, System.Object[] hostInitConfigurationParams) [0x00000] in
<filename unknown>:0
at System.Configuration.ConfigurationManager.OpenExeConfigurationInternal
(ConfigurationUserLevel userLevel, System.Reflection.Assembly calling_assembly,
System.String exePath) [0x00000] in <filename unknown>:0
at System.Configuration.ClientConfigurationSystem.get_Configuration ()
[0x00000] in <filename unknown>:0
--- End of inner exception stack trace ---
at System.Configuration.ClientConfigurationSystem.get_Configuration ()
[0x00000] in <filename unknown>:0
at
System.Configuration.ClientConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection
(System.String configKey) [0x00000] in <filename unknown>:0
at System.Configuration.ConfigurationManager.GetSection (System.String
sectionName) [0x00000] in <filename unknown>:0
at System.Net.WebRequest..cctor () [0x00000] in <filename unknown>:0
Sebastien, since you have been looking at the linker, would you mind looking at
this MMP linker issue?
Not sure how (even if) this worked before, if it was then this could be related
to changes in the 4.0 profile.
Anyway the machine.config (that gets copied into the .app) references a lot of
types and WebRequest calls into System.Configuration to instantiate them.
Fixing this specific case brings another, which brings another... and so on
(got 5 fixes and still crashing for missing types/.ctor).
Since this is all "string" based this can't be statically detected so we need
to either:
a) update the linker to bring all this extra, potentially used, code (like I
started to do). Sadly this means larger app size for stuff that's rarely used -
i.e. everyone pays for some advanced features almost no one uses;
b) process the machine.config in the linker (it will need to be available at
link time) and mark the types required. Much more complex and if we don't have
a 'smaller/smarter' machine.config then we'll end up just like 'a';
c) use a customized, minimal machine.config that does not bring anything extra
when linking is enabled. That way applications with extra requirements can
still use the features and will work (without changes since they won't be
linked). That's the easy way where (only) extra power comes at the price of
larger app size.
d) Allow users (MD UI) to provide their own alternate 'machine.config' if their
apps requires it, defaulting to 'c' otherwise. This requires 'b' to work too
but it's the ultimate solution (i.e. allows linking even with extra features).
e) Catch TypeLoadException where System.Configuration is used (e.g.
WebRequest). Not sure if this affects compatibility with MS implementation -
but it will hide the error (which can be good or bad) from the
developers/users.
'c' and 'e' are much alike right now (unless we want to do 'd' later). 'c'
requires an update to the MonoMac addin, while 'e' requires an update to Mono.
FWIW I don't think 'a' (fixing mmp to include everything) is the right solution
(and also requires a MonoMac adding update).
note: this does not affect the MOBILE profile since it's not using
System.Configuration, however MonoMac uses the full framework.
Meanwhile a workaround (beside turning off the linker) is to manually
edit/replace the machine.config that is bundled into the .app (that might
require re-signing the .app for the appstore) and remove the (very likely)
unneeded stuff related to system.net.
Sorry, I don't understand what should I remove from machine.config to get
WebRequest working. I removed every config section where system.net was
mentioned. Still no luck, same exception.
Ok, I've rewritten my code using NSUrlConnection. Now I have this exception in
System.Xml.Serialization.XmlSerializer constructor.
Sebastien,
I think we should process the machine.config and look for the well-known nodes
that can cause more code to be brought in and bring those types as requested.
Our default until MonoDevelop gets a UI for it would be to consume the
machine.config that comes with Mono. Later we can teach the MonoDevelop IDE
that if a machine.config file is included as content on the project, we link
against that one instead.
So we end up doing these changes:
1. Extend MMP to parse machine.config and pass the information to the linker.
2. Extend MMP to allow a machine.config to be specified
3. Extend the MonoDevelop add-in to pass a specific machine.config if one is
added as Content to MMP
4. Add a machine.config template to the MonoMac templates with the 4.0 contents
with most features commented out.
Could you look at #1 and I can look at the other 3?
Sure, I can do #1 and #2 too since I'll need that to test the change anyway.
Out of curiosity I continued the build/fail loop to see what the linker static
analysis "missed" (i.e. what we need to provide in another way). For WebRequest
support the linker must keep around the following:
System.Configuration.dll
+ System.Configuration.ExeConfigurationHost [1]
System.dll
+ System.UriTypeConverter [1]
+ System.ComponentModel.BooleanConverter [1]
+ System.ComponentModel.CollectionConverter [1]
+ System.ComponentModel.EnumConverter [1]
+ System.ComponentModel.StringConverter [1]
+ System.ComponentModel.TimeSpanConverter [1]
+ System.Net.Configuration.DefaultProxySection
+ System.Net.Configuration.HttpWebRequestElement [1]
+ System.Net.Configuration.Ipv6Element [1]
+ System.Net.Configuration.NetSectionGroup
+ System.Net.Configuration.PerformanceCountersElement [1]
+ System.Net.Configuration.ProxyElement [1]
+ System.Net.Configuration.ServicePointManagerElement [1]
+ System.Net.Configuration.SettingsSection
+ System.Net.Configuration.SocketElement [1]
+ System.Net.Configuration.WebProxyScriptElement [1]
+ System.Net.Configuration.WebRequestModulesSection
+ System.Net.Configuration.WebRequestModuleElementCollection [1]
+ System.Net.Configuration.WebRequestModuleElement [1]
Sadly a lot of the above is not part of the machine.config itself (all types
marked with [1]) so parsing machine.config won't be enough. We'll likely need
to bring a lot of extra code "just in case" and/or spend more time to teach the
linker to bring what's required (likely both).
That also the _optimal_ case, including everything referenced in machine.config
(we can't single out every feature) will result in a larger list of types.
The good news is that the parsing itself does not look too hard.
Krt,
> Ok, I've rewritten my code using NSUrlConnection. Now I have this exception in
> System.Xml.Serialization.XmlSerializer constructor.
Please fill a separate bug report (and include a test case) otherwise we'll mix
up the issue(s) and fix(es) - been there, done that a few times ;-) Thanks!
I'm testing a general workaround (that will be useful in other cases too) where
`mmp` gets a new option `-xml=file` that allow people to provide extraneous
definition files to the linker (it's something I've been planning for MT, I'll
likely "sideport" that feature soon).
With the correct .xml file (which tells the linker to keep everything in the
System.*.Configuration namespaces in several assemblies) I can build and
execute (without missing types) a WebRequest. So far so good (but needs more
testing).
I'll also look at using custom machine.config files to see if we can minimize
the extra types being included (the apps are much larger than before to please
System.Configuration reflection-happy design).
Right now the biggest issue is that MD monomac addin UI does not let you
provide extra options to mmp (e.g. this one or others, like the -i18n option)
so this fix is not very helpful until some UI enhancements are made.
Sebastien,
I am not sure I understand what the contents of the xml file are, is this a
machine.config formatted file, and based on this, it brings the types that are
needed based on the definitions there, or is it something else?
UI-wise, Jeff Stedfast is doing a rewrite of the UI that is needed.
Miguel
XML == descriptors files, the linker is largely driven by them [1]. However
`mmp` does not let users provide their own custom files. This limits how
end-users can workaround issues (such as this one) since adding [Preserve]
attributes won't work on SDK assemblies (like System.dll).
> is this a machine.config formatted file, and based on this, it brings the types that are needed based on the definitions there
Not yet. machine.config does not provide enough data, i.e. adding the types
founds inside it is *very* incomplete since System.Configuration has too many
parts that depends on reflection (based on context and, only partially, on
machine.config). This means that using the "default" (4.0) machine.config
requires us to bring a lot of extra types "just in case" (that's what my .xml
files does, I'll attach it once the changes are cleaned up / committed).
The next step is providing a new, cleaned-up machine.config (w/mmp) that will
minimize (goal: to avoid) the need of using custom .xml files. That should
cover more than 90% of the cases and keep the application size down (close to
the one we have now).
Then we can try to be "smarter" and automagically add the required
System.Configuration types (for people that needs the default, or their own
custom, machine.config). That will likely take a few iterations to get right
(possibilities are nearly endless) but with --xml it will be easy to quickly
provide workaround for them.
c.c. Jeff for comment #10
[1]
Sebastien: ah, thanks for the Cc.
Once this is implemented in mmp, can you reassign to me to add the UI? thanks.
Jeff, it will take a while to go thru all the things (i.e. don't wait fir it
;-) but there's already bugs #2291 (general title but asking for --i18n) and
#1650 (more general for extra arguments) opened for this.
What I was thinking was perhaps creating a mapping that would basically know
how to map a given dependency in machine.config to the types that are needed.
So "foobar" in in the config file would map from possibly one to hundreds of
types, without the user having to dig into which types he need by trial and
error and having to add types once per crash iteration.
You can see the xml files (step 1) as just that, (dumb) mappings :-) and they
do does not need to be user-created, e.g. we can supply them (like the basic
descriptors) for most common cases (the WebRequest case if the #1, not sure we
even have a #2 right now) instead of per-xml element.
Smarter mappings are the third step but for several reasons I'd like to avoid
hitting that case as much as possible, e.g.
* there's a lot of mappings to create, both "xml to type" and "type to type"
and the trigger logic (i.e. does that xml section means something for this
application);
* the mappings will need to be reviewed/updated with new Mono releases (new
features and bug fixes);
* the mappings will need to be duplicated with new FX versions (new/different
entries/types);
So that's a lot of time to invest, both now and later, for covering potentially
very few cases.
Also I can't name an application that requires a custom machine.config file
(i.e. that will really benefit from the above) and that means applications are
using the default machine.config.
The one we provide today, mono/4.0/machine.config, is meant to cover every kind
of usage (from console to web apps). That's an overkill for many applications
and it requires a lot of extra code that's rarely needed (that's mostly what my
current .xml files does).
But a new smaller machine.config (step 2) aligned with the linker defaults
(i.e. no custom xml file) should cover the majority of the cases (for a
fraction of the time to implement/maintain step 3). Since all steps are in the
same direction we can, as time permit, do #1, #2 and, if there's a demand, #3.
The new MMP included in Xamarin.Mac solve this issue (and many similar ones). | https://bugzilla.xamarin.com/show_bug.cgi?id=1528 | CC-MAIN-2015-35 | refinedweb | 2,104 | 51.34 |
Thank you. I follow your suggestion, and use Bing Search v7 instead.
I seems that Bing Search Key link has been changed.
In addition, ims = results.attrgot(‘content_url’) should be changed to ims = results.attrgot(‘contentUrl’) to notebook to work
Thank you. I follow your suggestion, and use Bing Search v7 instead.
I seems that Bing Search Key link has been changed.
Hi, @czechcheck. SerpApi developer here. I’ve randomly noticed this comment. Thank you for trying our service to get image URLs.
We can offer free search credits for fast.ai students. Just write us a message via a contact form at serpapi.com.
I’ll post a wrapper function like
search_images_bing for SerpApi if someone is interested.
It seems everything has changed from how it was back in 2020. Maybe this is useful for someone who is trying to set up Bing Seach API in 2021 (March).
Cheers,
Man, you saved my life.
Hey Palaash, I have the same issue. Did you resolve it? Can you help me with me it?
I didn’t find a solution to this Bing issue, but found a great alternative that I use now. Try this!
Appreciate the help man. Thank you!
Thanks a lot dude. Appericate it @thatgeeman
Hey people!
Any updates regarding this? Especially the free api part?
Hi Abhay,
I don’t have a solution to this problem, but found a great (and much more easier to use) alternative
Thanks so much, this was great help for me.
Has anyone here in the recent week tried to obtain a bing search api key? I registered for the azure platform and tried to follow these screenshot instructions but it seems the layout has changed and I can’t seem to find a page to access the bing api key. Any recommendation or advice?
It is asking about card details, do we surely have to fill that? I’m just a student and I don’t have any to pay for it. And I have only my country card which is a Rupay card and not a master or visa card either. How can I afford the key? Someone out there, please help me out to fix this.
I tried this link and created a new API then:
Hello! I wrote a blog post on how to use Google Images API to get similar functionality (should work without a card). Please do check it out and let me know if it works for you
It worked like a charm
Thanks!
There’s quite a number of replies on using
bing-image-downloader and yes it works as well. I do found that the results aren’t very clean, as in lots of results that return aren’t grizzly bears for example. Requires more experimentation to support my claim.
I did through a modified
google_images_download :
pip install git+
from google_images_download import google_images_download #importing the library
response = google_images_download.googleimagesdownload() #class instantiation
arguments = {“keywords”:“titmouse bird,nightingale,sparrow”,“limit”:100,“print_urls”:True} #creating list of arguments
paths = response.download(arguments) #passing the arguments to the function
print(paths) #printing absolute paths of the downloaded images
can anyone suggest how to use this further in 02_production.ipynb ?how to correctly replace instead of
results = search_images_bing(key, f’{o} bear’) ?
This is out of date as of October 2020. This is now the way to set it up:
I think a new article should be written and used as the link on the images section:
Thanks Palaash! | https://forums.fast.ai/t/getting-the-bing-image-search-key/67417/100 | CC-MAIN-2022-27 | refinedweb | 581 | 76.32 |
NAME
atalk - AppleTalk protocol family
SYNOPSIS
#include <sys/types.h> #include <netatalk/at.h>
DESCRIPTION
The AppleTalk protocol family is a collection of protocols layered above the Datagram Delivery Protocol (DDP), and using AppleTalk address format. The AppleTalk family may provide SOCK_STREAM (ADSP), SOCK_DGRAM (DDP), SOCK_RDM (ATP), and SOCK_SEQPACKET (ASP). Currently, only DDP is implemented in the kernel; ATP and ASP are implemented in user level libraries; and ADSP is planned.
ADDRESSING
AppleTalk addresses are three byte quantities, stored in network byte order. The include file <netatalk/at.h> defines the AppleTalk address format. Sockets in the AppleTalk protocol family use the following address structure: struct sockaddr_at { short sat_family; u_char sat_port; struct at_addr sat_addr; char sat_zero[ 8 ]; }; The port of a socket may be set with bind(2). The node for bind must always be ATADDR_ANYNODE: ‘‘this node.’’ The net may be ATADDR_ANYNET or ATADDR_LATENET. ATADDR_ANYNET coresponds to the machine’s ‘‘primary’’ address (the first configured). ATADDR_LATENET causes the address in outgoing packets to be determined when a packet is sent, i.e. determined late. ATADDR_LATENET is equivalent to opening one socket for each network interface. The port of a socket and either the primary address or ATADDR_LATENET are returned with getsockname(2).
SEE ALSO
bind(2), getsockname(2), atalkd(8). | http://manpages.ubuntu.com/manpages/hardy/man4/atalk.4.html | CC-MAIN-2014-49 | refinedweb | 211 | 50.43 |
On Mon, Jun 25, 2012 at 06:58:35PM +0200, Stefano Zacchiroli wrote: > On Fri, Jun 22, 2012 at 11:01:56PM +0200, Martin Zobel-Helas wrote: > > The current practice for debian.net entries is that they are directly > > entered in the debian.net zone as 3rd-level records. I am seeking > > comments on a proposal to alter this practice. > > Thanks for working on the idea! > Here are a few comments of mine: > > - I like very much the idea of thinking at *.debian.net entries as > services in "incubation". It is way clearer than our current notion of > "official" vs "non-official" (hosting), which is something that people > who have no idea what "DSA" is simply cannot understand. Additionally, > it bring purpose to debian.net entries as something temporary that > should at least ideally strive to move to debian.org. Not because our > DSAs are control freak (they're not), but rather because debian.org > hosting gives more guarantees to the Debian Project of long term > maintenance, usually because it reduces the bus factor risk. > > Making this even clearer with a *.incubator.debian.org namespace might > be a good idea. (Modulo some transition time, doing so will eventually > replace *.debian.net, if I got that right.). So while I do agree that there are problems with the current usage of the debian.net domain, I'm not sure it's solved by changing the domain. -- The volume of a pizza of thickness a and radius z can be described by the following formula: pi zz a | https://lists.debian.org/debian-project/2012/06/msg00161.html | CC-MAIN-2014-10 | refinedweb | 256 | 67.35 |
An introduction to C++'s variadic templates: a thread-safe multi-type map
Posted on Mon 01 February 2016 in C++ of your code. Singletons are that kind of beast that revives itself without your permission and comes from hell to haunt your lovely unit-tests. Our main project being multi-threaded (hence highly bug-prone) and vital for the company, "singleton" became a forbidden word. Yet, our team recently started going down the dark path. Thanks to C++11 and its variadic templates, I carefully crafted a thread-safe multi-type map container that simplified our configuration reloading system and saved us from the dark side of the coder force. If you always wondered what are variadic templates, how C++11's tuples can be implemented, I am going to present these concepts in this post using my container as a cobaye.
Note: for the sake of your sanity and the fact that errare humanum est, this article might not be 100% accurate!
Why would I use a thread-safe multi-type map?
Let me explain our odyssey: we are working on a highly modular and multi-threaded application. One of its core feature is the ability to reload various configuration files or assets used by some components spread accross many threads and a giant hierarchy of objects. The reloading process is automic using Linux's inotify monitoring filesystem events. One thread is dedicated to the reception of filesystem events and must react accordingly by parsing any changes and pushing them to other threads. At first, we used, to pass-by any newly parsed asset, some thread-safe queues or something analog to go channels. Since we did not want to use singletons, we had to pass references to our queues all along our object hierarchy. Sadly, our queue implementation is one to one and supports only one type, none of our config/asset types share the same base-type. For each asset type and each component using this asset, we had to create a new queue and pass-it all along our hierarchy. That is certainely not convenient! What we really wanted was a hybrid class between a std::map and a std::tuple.
We could have used a std::map with Boost.Variant to store our items, using a type like the following "std::map< std::string, std::shared_ptr< Boost.Variant < ConfigType1, ConfigType2>>>". Boost.Variant permits to encapsulate a heterogeneous set of types without common base-type or base-class, which solves one of our point. Another solution would be to encapsulate manually all our configuration classes in the same familly of classes, that is pretty cumbersome. But anyway, std::map does not guaranty any safety if you are writing and reading at the same time on a map slot. Secondly, std::shared_ptr does guaranty a thread-safe destruction of the pointee object (i.e: the reference counter is thread-safe) but nothing for the std::shared_ptr object itself. It means that copying a std::shared_ptr that could potentially be modified from another thread, might lead to an undefined behaviour. Even if we were to encapsulate all these unsafe accesses with mutexes, we are still lacking a nice mechanism to get update notifications for our objects. We do not want to constantly poll the latest version and propagate it through our code. And finally, if that solution were elegant enough, why would I currently write this blog post?
C++11 brings another collection type called std::tuple. It permits to store a set of elements of heterogeneous types. Take a look at this short example:
auto myTuple = std::make_tuple("Foo", 1337, 42); std::cout << std::get<0>(myTuple) << std::endl; // Access element by index: "Foo" std::cout << std::get<1>(myTuple) << std::endl; // Access element by index: 1337 std::cout << std::get<2>(myTuple) << std::endl; // Access element by index: 42 std::cout << std::get<const char*>(myTuple) << std::endl; // Access element by type: "Foo" // compilation error: static_assert failed "tuple_element index out of range" std::cout << std::get<3>(myTuple) << std::endl; // compilation error: static_assert failed "type can only occur once in type list" std::cout << std::get<int>(myTuple) << std::endl;
Tuples are that kind of C++11 jewelry that should decide your old-fashioned boss to upgrade your team's compiler (and his ugly tie). Not only I could store a const char* and two ints without any compiling error, but I could also access them using compile-time mechanisms. In some way, you can see tuples as a compile-time map using indexes or types as keys to reach its elements. You cannot use an index out of bands, it will be catched at compile-time anyway! Sadly, using a type as a key to retrieve an element is only possible if the type is unique in the tuple. At my work, we do have few config objects sharing the same class. Anyway, tuples weren't fitting our needs regarding thread safety and update events. Let's see what we could create using tasty tuples as an inspiration.
Note that some tuples implementations were already available before C++11, notably in boost. C++11 variadic templates are just very handy, as you will see, to construct such a class.
A teaser for my repository class:
To keep your attention for the rest of this post, here is my thread-safe multi-type map in action:
#include <iostream> #include <memory> #include <string> #include "repository.hpp" // Incomplete types used as compile-time keys. struct Key1; struct Key2; // Create a type for our repository. using MyRepository = Repository < Slot<std::string>, // One slot for std::string. Slot<int, Key1>, // Two slots for int. Slot<int, Key2> // Must be differentiate using "type keys" (Key1, Key2). >; int main() { MyRepository myRepository; myRepository.emplace<std::string>("test"); // Construct the shared_ptr within the repository. myRepository.emplace<int, Key1>(1337); myRepository.set<int, Key2>(std::make_shared<int>(42)); // Set the shared_ptr manually. // Note: I use '*' as get returns a shared_ptr. std::cout << *myRepository.get<std::string>() << std::endl; // Print "test". std::cout << *myRepository.get<int, Key1>() << std::endl; // Print 1337. std::cout << *myRepository.get<int, Key2>() << std::endl; // Print 42. std::cout << *myRepository.get<int>() << std::endl; // ^^^ Compilation error: which int shall be selected? Key1 or Key2? auto watcher = myRepository.getWatcher<std::string>(); // Create a watcher object to observe changes on std::string. std::cout << watcher->hasBeenChanged() << std::endl; // 0: no changes since the watcher creation. myRepository.emplace<std::string>("yo"); // Emplace a new value into the std::string slot. std::cout << watcher->hasBeenChanged() << std::endl; // 1: the std::string slot has been changed. std::cout << *watcher->get() << std::endl; // Poll the value and print "yo". std::cout << watcher->hasBeenChanged() << std::endl; // 0: no changes since the last polling. return EXIT_SUCCESS; }
First and foremost, its name repository might not be well-suited for its responsibility. If your native language is the same as shakespeare and come-up with a better term, please feel free to submit it. In our internal usage, config repository sounded great!
I start by describing the slots necessary for my application by creating a new type MyRepository using a type alias. As you can see, I use the type of the slots as a key for accessing elements. But in case of contention, I must use a second key: an "empty type" ; like Key1 and Key2 in this example. If using types as keys seems odd for you, fear not! Here is the most rational explanation I can share with you: we are trying to benefit from our "know-it-all compiler". Your compiler is mainly manipulating types, one can change its flow using these types during the compilation process. Note that these structs are not even complete (no definition), it has no impact for the runtime memory or runtime execution and that's the amazing part of meta-programming. The dispatch of an expression such as "myRepository.get< int, Key1>()" is done during your build-time.
You may also notice that every slot is actually a std::shared_ptr. It enforces a clean ressource management: in a multithreaded application, one must be really careful of the lifetime of heap objects. std::shared_ptr in this case permits me to ensure that even if someone replaces a value in a slot, other components on other threads manipulating the old value won't end up with a dangling pointer/reference bomb in their hands. Another solution would be to use plain value objects, but not only it would require copying big objects in every other components but it would also remove polymorphism.
As for the updates signalisation, you first create a watcher object that establishes a contract between a desired slot to watch and your context. You can thereafter query in thread-safe way weither an update has been made and, if so, poll the latest changes. The watcher object is actually a std::unique_ptr for a special class, it cannot be moved nor copied without your permission and will automagically disable the signalisation contract between the slot and your context, once destroyed. We will dive deeper in this topic in the comming sections.
Within our application, the repository object is encapsulated into a RuntimeContext object. This RuntimeContext object is created explicitely within our main entry point and passed as a reference to a great part of our components. We therefore keep the possibility to test our code easily by setting this RuntimeContext with different implementations. Here is a simplified version of our usage:
// runtimecontext.hpp #include "repository.hpp" // Incomplete types used as compile-time keys. struct Key1; struct Key2; class ConfigType1; // Defined in another file. class ConfigType2; // Defined in another file. // Create a type for our repository. using ConfigRepository = Repository < Slot<ConfigType1>, Slot<ConfigType2, Key1>, Slot<ConfigType2, Key2> >; struct RuntimeContext { ILogger* logger; // ... ConfigRepository configRepository; }; // Main.cpp #include "runtimecontext.hpp" int main() { RuntimeContext runtimeContext; // Setup: runtimeContext.logger = new StdOutLogger(); // ... // Let's take a reference to the context and change the configuration repository when necessary. startConfigurationMonitorThread(runtimeContext); // Let's take a reference and pass it down to all our components in various threads. startOurApplicationLogic(runtimeContext); return EXIT_SUCCESS; }
Time for a C++11 implementation:
We can decompose the solution in 3 steps: at first we need to implement a map that accepts multiple types, we then need to work on the thread safety and finish by the watcher mechanism. Let's first fulfill the mission of this post: introducing you to variadic templates to solve the multiple-type problem.
Variadic templates:
You may not have heard of variadic templates in C++11 but I bet that you already used variadic functions like printf in C (maybe in a previous unsafe life). As wikipedia kindly explains "a variadic function is a function of indefinite which accepts a variable number of arguments". In other words, a variadic function has potentially an infinite number of parameters. Likewise, a variadic template has potentially an infinite number of parameters. Let's see how to use them!
Usage for variadic function templates:
Let's say that you wish to create a template that accept an infinite number of class as arguments. You will use the following notation:
template <class... T>
You specify a group of template parameters using the ellipsis notation named T. Note that this ellipsis notation is consistent with C's variadic function notation. This group of parameters, called a parameter-pack, can then be used in your function template or your class template by expanding them. One must use the ellipsis notation again (this time after T) to expand the parameter pack T:
template <class... T> void f(T...) // ^ pack T ^expansion { // Your function content. }
Now that we have expanded T, what can we do Sir? Well, first you give to your expanded parameter types, a fancy name like t.
template <class... T> void f(T... t) // ^ your fancy t. { // Your function content. }
If T = T1, T2, then T... t = T1 t1, T2 t2 and t = t1, t2. Brilliant, but is that all? Sure no! You can then expand again t using an "suffix-ellipsis" again:
template <class... T> void f(T... t) { anotherFunction(t...); // ^ t is expanded here! }
Finally, you can call this function f as you would with a normal function template:
template <class... T> void f(T... t) { anotherFunction(t...); } f(1, "foo", "bar"); // Note: the argument deduction avoids us to use f<int, const char*, const char*> // f(1, "foo", "bar") calls a generated f(int t1, const char* t2, const char* t3) // with T1 = int, T2 = const char* and T3 = const char*, // that itself calls anotherFunction(t1, t2, t3) equivalent to call anotherFunction(1, "foo", "bar");
Actually, the expansion mechanism is creating comma-separated replication of the pattern you apply the ellipsis onto. If you think I am tripping out with template-related wording, here is a much more concret example:
template <class... T> void g(T... t) { anotherFunction(t...); } template <class... T> void f(T*... t) { g(static_cast<double>(*t)...); } int main() { int a = 2; int b = 3; f(&a, &b); // Call f(int* t1, int* t2). // Do a subcall to g(static_cast<double>(*t1), static_cast<double>(*t2)). return EXIT_SUCCESS; }
I could use the pattern '*' for f parameters and therefore take them as a pointer! In the same manner, I applied the pattern 'static_cast< double>(*) to get the value of each arguments and cast them as doubles before forwarding them to g.
One last example before moving to variadic class templates. One can combine "normal" template parameters with parameter packs and initiate a compile recursion on function templates. Let's take a look at this printing function:
#include <iostream> template <class HEAD> void print(HEAD head) { std::cout << "Stop: " << head << std::endl; } template <class HEAD, class... TAIL> void print(HEAD head, TAIL... tail) { std::cout << "Recurse: " << head << std::endl; print(tail...); } int main() { print(42, 1337, "foo"); // Print: // Recurse: 42 // Recurse: 1337 // Stop: foo // Call print<int, int, const char*> (second version of print). // The first int (head) is printed and we call print<int, const char*> (second version of print). // The second int (head again) is printed and we call print<const char*> (first version of print). // We reach recursion stopping condition, only one element left. return EXIT_SUCCESS; }
Variadic templates are very interesting and I wouldn't be able to cover all their features within this post. It roughly feels like functional programming using your compiler, and even some Haskellers might listen to you if you bring that topic during a dinner. For those interested, I would challenge them to write a type-safe version of printf using variadic templates with the help of this reference. After that, you will run and scream of fear at the precense of C's vargs.
"Variadic" inheritance:
Sometimes during my programming sessions, I have a very awkward sensation that my crazy code will never compile and, yet, I finally see "build finished" in my terminal. I am talking about that kind of Frankenstein constructions:
struct A { }; struct B { }; template <class... T> struct C: public T... // Variadic inheritance { }; C<A, B> c;
Yes, we can now create a class inheriting of an infinite number of bases. If you remember my explanation about pattern replications separated by commas, you can imaginge that struct C: public T... will be "transformed" in struct C: public A, public B, public T being the pattern. We start to be able to combine multiple types, each exposing a small amount of methods, to create a flexible concret type. That's one step closer to our multi-type map, and if you are interested in this concept, take a look at mixins.
Instead of inheriting directly from multiple types, couldn't we inherit from some types that encapsulate our types? Absolutely! A traditional map has some slots accessible using keys and these slots contain a value. If you give me base-class you are looking for, I can give you access to the value it contains:
#include <iostream> struct SlotA { int value; }; struct SlotB { std::string value; }; // Note: private inheritance, no one can access directly to the slots other than C itself. struct Repository: private SlotA, private SlotB { void setSlotA(const int& value) { // I access the base-class's value // Since we have multiple base with a value field, we need to "force" the access to SlotA. SlotA::value = value; } int getSlotA() { return SlotA::value; } void setSlotB(const std::string& b) { SlotB::value = b; } std::string getSlotB() { return SlotB::value; } }; int main() { Repository r; r.setSlotA(42); std::cout << r.getSlotA() << std::endl; // Print: 42. r.setSlotB(std::string("toto")); std::cout << r.getSlotB() << std::endl; // Print: "toto". return EXIT_SUCCESS; }
This code is not generic at all! We know how to create a generic Slot using a simple template, and we acquired the magic "create varidiac inheritance" skill. If my Repository class inherit from Slot< TypeA> and you call a method template with TypeA as a template argument, I can call the doGet method of the Slot< TypeA> base-class and give you back the value of TypeA in that repository. Let's fix the previous ugly copy-paste code:
#include <iostream> #include <string> template <class Type> class Slot { protected: Type& doGet() // A nice encapsulation, that will be usefull later on. { return value_; } void doSet(const Type& value) // Same encapsulation. { value_ = value; } private: Type value_; }; template <class... Slots> class Repository : private Slots... // inherit from our slots... { public: template <class Type> // Give me a type and, Type& get() { return Slot<Type>::doGet(); // I can select the Base class. } template <class Type> void set(const Type& value) { Slot<Type>::doSet(value); } }; // Incomplete types used as compile-time keys. struct Key1; struct Key2; // Create a type for our repository. using MyRepository = Repository < Slot<int>, // Let's pick the type of our slots. Slot<std::string> >; int main() { MyRepository myRepository; myRepository.set<std::string>("toto"); myRepository.set(42); // Notice the type deduction: we pass an int, so it writes in the int slot. std::cout << myRepository.get<int>() << std::endl; // Print: "toto". std::cout << myRepository.get<std::string>() << std::endl; // Print: 42. return EXIT_SUCCESS; }
This repository starts to take shape, but we are not yet done! If you try to have two int slots, you will raise a compilation error: "base class 'Slot
struct DefaultSlotKey; // No needs for a definition template <class T, class Key = DefaultSlotKey> // The Key type will never be trully used. class Slot { // ... }; template <class... Slots> class Repository : private Slots... { public: template <class Type, class Key = DefaultSlotKey> // The default key must be here too. Type& get() { return Slot<Type, Key>::doGet(); } template <class Type, class Key = DefaultSlotKey> void set(const Type& value) { Slot<Type, Key>::doSet(value); } }; struct Key1; // No need for definition. struct Key2; // Now you can do: using MyRepository = Repository < Slot<int>, // Let's pick the type of our slots. Slot<std::string, Key1>, Slot<std::string, Key2> >;
Here is a UML representation of this Repository using distinct Keys for the type std::string:
Our repository class is missing an emplace method, right? emplace is taking a variable number of arguments with different types and forward them to create an object within one of our slots. A variable number of arguments and types must remind you something... variadic templates! Let's create this variadic emplace method as well as its equivalent in the Slot class:
// In class Slot: template <class... Args> void doEmplace(const Args&... args) // Here the pattern is const &. { value_ = Type(args...); // copy-operator (might use move semantics). } // In class Repository: template <class Type, class Key = DefaultSlotKey, class... Args> void emplace(const Args&... args) // Here the pattern is const &. { Slot<Type, Key>::doEmplace(args...); } // Usage: myRepository.emplace<std::string>(4, 'a'); // Create a std::string "aaaa".
One last improvement for the future users of your repositories! If one morning, badly awake, a coworker of yours is trying to get a type or key that doesn't exist (like myRepository.get< double>();), he might be welcomed by such a message:
/home/jguegant/Coding/ConfigsRepo/main.cpp:36:33: error: call to non-static member function without an object argument return Slot<Type, Key>::doGet(); ~~~~~~~~~~~~~~~~~^~~~~ /home/jguegant/Coding/ConfigsRepo/main.cpp:67:18: note: in instantiation of function template specialization 'Repository<Slot<int, DefaultSlotKey>, Slot<std::__1::basic_string<char>, DefaultSlotKey> >::get<double, DefaultSlotKey>' requested here myRepository.get<double>(); ^ /home/jguegant/Coding/ConfigsRepo/main.cpp:36:33: error: 'doGet' is a protected member of 'Slot<double, DefaultSlotKey>' return Slot<Type, Key>::doGet(); ^ /home/jguegant/Coding/ConfigsRepo/main.cpp:10:11: note: declared protected here Type& doGet() ^ 2 errors generated.
This message is very confusing, our class does not inherit from Slot< double, DefaultSlotKey>! And we are talking about a clang output, I wonder what gcc or MSVC could produce... If you do not want to be assinated from your moody colleague with a spoon, here is a nice solution using C++11's static_asserts. Static asserts give you the possibility to generate your own compiler error messages in the same fashion as normal asserts but at compile-time. Using a the trait like std::is_base_of, you can suggest the user of your repository to check twice his type. Let's put this static_assert at the beggining of all the methods of Repository:
static_assert(std::is_base_of<Slot<Type, Key>, Repository<Slots...>>::value, "Please ensure that this type or this key exists in this repository");
We are done for this part (finally...), time to think about multi-threading! If you want to know more about the magic behind std::is_base_of, I would suggest you to read my previous post on SFINAE, it might give you few hints. Here is a gist of what we achieved so far. Did you notice the change on emplace? If you do not understand it, have a look at this explanation on perfect forwarding. Sadly, it would be a way too long topic for this post (trust me on that point!) and has a minor impact on our repository right now.
Let's play safe:
The repository we just succeeded to craft can now be used in a single-thread environment without further investigation. But the initial decision was to make this class manipulable from multiple-threads without any worries considering the safety of our operations. As explained in the beginning of this post, we will not use direct values as we currently do, but instead allocate our objects on the heap and use some shared pointers to strictly control their lifetime. No matter which version (recent or deprecated) of the object a thread is manipulating, it's lifetime will be extended until the last thread using it definitely release it. It also implies that the objects themselves are thread-safe. In the case of read-only objects like configs or assets, it shouldn't be too much a burden. In this gist, you will find a repository version using std::shared_ptrs.
std::shared_ptr is an amazing feature of C++11 when dealing with multi-threading, but has its weakness. Within my code (in the previous gist link) a race condition can occur:
// What if I try to copy value_ at the return point... std::shared_ptr<Type> doGet() const { return value_; } // ... meanwhile another thread is changing value_ to value? void doSet(const std::shared_ptr<Type> &value) { value_ = value; }
As specified: "If multiple threads of execution access the same std::shared_ptr object without synchronization and any of those accesses uses a non-const member function of shared_ptr then a data race will occur". Note that we are talking about the same shared pointer. Multiple shared pointer copies pointing to the same object are fine, as long as these copies originated from the same shared pointer in first place. Copies are sharing the same control block, where the reference counters (one for shared_ptr and one for weak_ptr) are located, and the specification says "the control block of a shared_ptr is thread-safe: different std::shared_ptr objects can be accessed using mutable operations, such as operator= or reset, simultaneously by multiple threads, even when these instances are copies, and share the same control block internally.".
Depending on the age of your compiler and its standard library, I suggest two solutions:
1) A global mutex:
A straightforward solution relies on a std::mutex that we lock during doGet and doSet execution:
... std::shared_ptr<Type> doGet() { // The lock is enabled until value_ has been copied! std::lock_guard<std::mutex> lock(mutex_); return value_; } void doSet(const std::shared_ptr<Type> &value) { // The lock is enabled until value has been copied into value! std::lock_guard<std::mutex> lock(mutex_); value_ = value; } private: std::mutex mutex_; ...
This solution is ideal if you have a Linux distribution that only ships gcc 4.8.x like mine. While not particularly elegant, it doesn't have a great impact on performances compared to the next solution.
2) Atomic access functions:
Starting from gcc 4.9, one can use atomic access functions to manipulate shared pointers. I dream of a day where a specialisation for std::atomic< std::shared_ptr
... std::shared_ptr<Type> doGet() const { return std::atomic_load(&value_); } void doSet(const std::shared_ptr<Type> &value) { std::atomic_exchange(&value_, value); } private: std::shared_ptr<Type> value_; ...
Atomics are elegants and can often bring a great increase of performances if using lock-free instructions internally. Sadly, in the case of shared_ptrs, atomic_is_lock_free will return you false. By digging in libstdc++ and libc++, you will find some mutexes. gcc seems to use a fixed size "pool" of mutexes attributed to a shared_ptr according to a hash of its pointee address, when dealing with atomic operations. In other words, no rocket-science for atomic shared pointers until now.
Our own watchers:
"...I shall live and die at my post. I am the sword in the darkness. I am the watcher on the walls. I am the shield that guards the realms of men..." -- The Night's Watch oath
We want to be able to seal a bond between one of the slot and a context. By context, I mean the lifetime of an object in a thread, a function or a method. If an update has been made on that slot, we must be signaled in that context and to retrieve the new update. The bond must be destroyed if the context does not exist anymore. It should reminds you the Night's Watch oath ... as well as the RAII idiom: "holding a resource is tied to object lifetime: resource acquisition is done during object creation, by the constructor, while resource deallocation is done during object destruction, by the destructor. If objects are destroyed properly, resource leaks do not occur.". A strong ownership policy can be obtained with the help of a std::unique_ptr and the signalisation can be done using a boolean flag.
We will, therefore, encapsulate a std::atomic_bool into a class Watcher automagically registered to a slot once created, and unregistered once destructed. This Watcher class also takes as a reference the slot in order to query its value as you can see:
template <class Type, class Key> class Watcher { public: Watcher(Slot<Type, Key>& slot): slot_(slot), hasBeenChanged_(false) { } Watcher(const Watcher&) = delete; // Impossible to copy that class. Watcher & operator=(const Watcher&) = delete; // Impossible to copy that class. bool hasBeenChanged() const { return hasBeenChanged_; } void triggerChanges() { hasBeenChanged_ = true; } auto get() -> decltype(std::declval<Slot<Type, Key>>().doGet()) { hasBeenChanged_ = false; // Note: even if there is an update of the value between this line and the getValue one, // we will still have the latest version. // Note 2: atomic_bool automatically use a barrier and the two operations can't be inversed. return slot_.doGet(); } private: Slot<Type, Key>& slot_; std::atomic_bool hasBeenChanged_; };
As for the automatic registration, we will add two private methods registerWatcher and unregisterWatcher to our Slot class that add or remove a watcher from an internal list. The list is always protected, when accessed, with a std::mutex and tracks all the current watchers that must be signaled when set is called on that slot.
template <class Type, class Key> class Slot { public: using ThisType = Slot<Type, Key>; using WatcherType = Watcher<Type, Key>; ... private: void registerWatcher(WatcherType* newWatcher) { std::lock_guard<std::mutex> l(watchers_mutex_); watchers_.push_back(newWatcher); } void unregisterWatcher(WatcherType *toBeDelete) { std::lock_guard<std::mutex> l(watchers_mutex_); watchers_.erase(std::remove(watchers_.begin(), watchers_.end(), toBeDelete), watchers_.end()); delete toBeDelete; // Now that we removed the watcher from the list, we can proceed to delete it. } void signal() { std::lock_guard<std::mutex> l(watchers_mutex_); for (auto watcher : watchers_) { watcher->triggerChanges(); // Let's raise the hasBeenChanged_ atomic boolean flag. } } private: std::vector<WatcherType*> watchers_; // All the registered watchers are in that list. ... };
You may have notice that we are passing a bare WatcherType pointers. The ownership is actually given to whoever is using that watcher encapsulated within a std::unique_ptr. C++11's unique pointers are designed such as you can pass a custom deleter, or a delete callback so to speak. Hence, we can create a method that get a Watcher for a Slot, and register as the deleter of that Watcher a lambda function designed to call unregisterWatcher. Note that the slot MUST always lives longer than the unique pointer and its associated watcher (it should not be a problem in most cases). Let's finish that Slot class forever and ever:
template <class Type, class Key> class Slot { public: using ThisType = Slot<Type, Key>; using WatcherType = Watcher<Type, Key>; // We use unique_ptr for a strong ownership policy. // We use std::function to declare the type of our deleter. using WatcherTypePtr = std::unique_ptr<WatcherType, std::function<void(WatcherType*)>> ; ... public: WatcherTypePtr doGetWatcher() { // Create a unique_ptr and pass a lambda as a deleter. // The lambda capture "this" and will call unregisterWatcher. WatcherTypePtr watcher(new WatcherType(*this), [this](WatcherType* toBeDelete) { this->unregisterWatcher(toBeDelete);}); registerWatcher(watcher.get()); return watcher; } ... };
Are we done? Hell no, but we will be really soon. All we need is to expose the possibility to acquire a watcher from the repository itself. In the same manner as set and get, we simply dispatch using the type and the key on one of our slot:
template <class Type, class Key = DefaultSlotKey> typename Slot<Type, Key>::WatcherTypePtr getWatcher() // typename is used for disambiguate { return Slot<Type, Key>::doGetWatcher(); }
WAIT, don't close that page too fast. If you want to be able to snub everyone, you can replace this ugly typename Slot
Conclusion:
Once again, I hope you enjoyed this post about one of my favourite subject: C++. I might not be the best teacher nor the best author but I wish that you learnt something today! Please, if you any suggestions or questions, feel free to post anything in the commentaries. My broken English being what it is, I kindly accept any help for my written mistakes.
Many thanks to my colleagues that greatly helped me by reviewing my code and for the time together. | https://jguegant.github.io/blogs/tech/thread-safe-multi-type-map.html | CC-MAIN-2018-05 | refinedweb | 5,131 | 55.84 |
Some time ago I blogged on Conditional Validation in MVC, and Adding Client-Side Script to an MVC Conditional Validator. A number of people have asked me to update the sample to MVC 3, so guess what – it’s your birthday! The main differences are summarised below… and check out the code download to see it working. I’d recommend reading my previous two posts if you want the background on how it all works.
Important: Note that this is by no means a complete solution, and neither were my previous ones. They’re POCs intended to get you started! For example, you may need to handle different data types (Int32, perhaps) or control types (radio buttons, perhaps) yourself. I’d also recommend thoroughly testing the code. Enjoy…
Hooray! There’s no need for an adapter class anymore. The Attribute instead can implement an interface;
1: public class RequiredIfAttribute : ValidationAttribute, IClientValidatable
2: {
3: }
IClientValidatable demands that we implement GetClientValidationRules on our Attribute, in a very similar way to the example in my previous posts. That’s much neater.
I’m not particularly happy with this workaround right now, so if you’ve a better solution let me know. The issue is that when we are emitting the Client Validation Rules described above, we must calculate the Identifier that the control we depend upon will have when it is written out into the HTML. To do this, we call;
1: string depProp = viewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(this.DependentProperty);
However… now that this method is being called from within the Attribute itself, rather than within an Adapter, that means it is executed while the field the Attribute applies to is being rendered. That means the context is one level lower than it was for my original solution. MVC tracks a “stack” of field prefixes in this context whilst rendering fields, and each time it ducks into a new template it adds a prefix. So when rendering our Person entity (which is a variable called model for example) the prefix would be “model_”. When rendering Person’s Name, it would be “model_Name”. And if we had an address field on Person, that in turn had a City field, it could become “model_Address_City”. Note the “model_” bit often isn’t there – it depends, and I’m simplifying
What this means is that when calculating the dependent property ID with the code above, this context is “City” or “Country” (as the attribute is used on two fields it is called twice) rather than String.Empty. Which means it calculates the HTML ID of the “IsUKResident” field to be “City_IsUKResident”, instead of “IsUKResident”, and of course “City_IsUKResident” doesn’t exist. Therefore I have to post-process it to strip off “City_”.
Yuck. Anyone know how to navigate the prefix hierarchy to stop this happening? It does seem to work though.
Next up, we use the jQuery.validate library to write our validation functions. This is now the only option, instead of one of two options as it was before. My validator looks like this;
1: $.validator.addMethod('requiredif',
2: function (value, element, parameters) {
3: var id = '#' + parameters['dependentproperty'];
4:
5: // get the target value (as a string,
6: // as that's what actual value will be)
7: var targetvalue = parameters['targetvalue'];
8: targetvalue =
9: (targetvalue == null ? '' : targetvalue).toString();
10:
11: // get the actual value of the target control
12: // note - this probably needs to cater for more
13: // control types, e.g. radios
14: var control = $(id);
15: var controltype = control.attr('type');
16: var actualvalue =
17: controltype === 'checkbox' ?
18: control.attr('checked').toString() :
19: control.val();
20:
21: // if the condition is true, reuse the existing
22: // required field validator functionality
23: if (targetvalue === actualvalue)
24: return $.validator.methods.required.call(
25: this, value, element, parameters);
26:
27: return true;
28: }
29: );
You can see I’m just reusing the built in “required” validation if I determine it needs to be run.
However, we do also need to add an adapter that extracts the HTML 5 Custom Data Attributes that MVC adds to my input controls (use View Source and look for “data-XXX” on the <input> elements if you don’t know what these are – or read my article here) and passes them to my validation method. Mine looks like this;
1: $.validator.unobtrusive.adapters.add(
2: 'requiredif',
3: ['dependentproperty', 'targetvalue'],
4: function (options) {
5: options.rules['requiredif'] = {
6: dependentproperty: options.params['dependentproperty'],
7: targetvalue: options.params['targetvalue']
8: };
9: options.messages['requiredif'] = options.message;
10: });
This states that I require two parameters – dependentproperty and targetvalue. These are therefore passed in the options object for me. I must then do any processing on them that is required (none, in this case) and create an entry in options.rules with their processed values. I also need to ensure I put the error message into a dictionary indexed by the name of my validation rule. Phew! I’m sure that could be easier, couldn’t it? Perhaps I’ll write a little helper… there are helper functions for rules that only have a single parameter or need a boolean, but mine didn’t fit that pattern.
… is no longer required in the View, because it is enabled in Web.config instead, and is set to “true” by default! Excellent news!
Well, I hope that has been pleasantly brief. Download the code and have a play if you’re interested, and let me know how you get on. I think MVC 3 is a giant leap towards far better validation… and to celebrate that the sample uses Razor, of course!
Original post by Simon Ince on 04/02/11 here: | http://blogs.msdn.com/b/ukadc/archive/2011/02/10/conditional-validation-in-asp-net-mvc-3.aspx | CC-MAIN-2014-23 | refinedweb | 943 | 55.24 |
The CephFS driver enables manila to export shared filesystems backed by Ceph’s File System (CephFS) using either the Ceph network protocol or NFS protocol. Guests require a native Ceph client or an NFS client in order to mount the filesystem.
When guests access CephFS using the native Ceph protocol, access is controlled via Ceph’s cephx authentication system. If a user requests share access for an ID, Ceph creates a corresponding Ceph auth ID and a secret key, if they do not already exist, and authorizes the ID to access the share. The client can then mount the share using the ID and the secret key. To learn more about configuring Ceph clients to access the shares created using this driver, please see the Ceph documentation (). If you choose to use the kernel client rather than the FUSE client, the share size limits set in manila may not be obeyed.
And when guests access CephFS through NFS, an NFS-Ganesha server mediates access to CephFS. The driver enables access control by managing the NFS-Ganesha server’s exports.
The following operations are supported with CephFS backend:
Create/delete share
Allow/deny CephFS native protocol access to share
cephxaccess type is supported for CephFS native protocol.
read-onlyaccess level is supported in Newton or later versions of manila.
read-writeaccess level is supported in Mitaka or later versions of manila.
(or)
Allow/deny NFS access to share
ipaccess type is supported for NFS protocol.
read-onlyand
read-writeaccess levels are supported in Pike or later versions of manila.
Extend/shrink share
Create/delete snapshot
Create/delete consistency group (CG)
Create/delete CG snapshot
Warning
CephFS currently supports snapshots as an experimental feature, therefore the snapshot support with the CephFS Native driver is also experimental and should not be used in production environments. For more information, see ().
Important
A manila share backed by CephFS is only as good as the underlying filesystem. Take care when configuring your Ceph cluster, and consult the latest guidance on the use of CephFS in the Ceph documentation ()
Enable snapshots in Ceph if you want to use them in manila:
ceph mds set allow_new_snaps true --yes-i-really-mean-it
Warning
Note that the snapshot support for the CephFS driver is experimental and is
known to have several caveats for use. Only enable this and the
equivalent
manila.conf option if you understand these risks. See
()
for more details.
cephfs_enable_snapshotsconfiguration option needs to be set to
Trueto allow snapshot operations. Snapshot support will also need to be enabled on the backend CephFS storage.
.snap/{manila-snapshot-id}_{unknown-id}folder within the mounted share.
Each share’s data is mapped to a distinct Ceph RADOS namespace. A guest is restricted to access only that particular RADOS namespace.
An additional level of resource isolation can be provided by mapping a
share’s contents to a separate RADOS pool. This layout would be be preferred
only for cloud deployments with a limited number of shares needing strong
resource separation. You can do this by setting a share type specification,
cephfs:data_isolated for the share type used by the cephfs driver.
manila type-key cephfstype set cephfs:data_isolated=True
Except where otherwise noted, this document is licensed under Creative Commons Attribution 3.0 License. See all OpenStack Legal Documents. | https://docs.openstack.org/manila/queens/admin/cephfs_driver.html | CC-MAIN-2018-26 | refinedweb | 551 | 54.63 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.