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
NAME dbs - Debian Build System DESCRIPTION dbs is a collection of makefiles and shell scripts for easier handling of upstream sources and patches. Basically it adds to debian/rules a special target which extracts upstream sources and applies patches to them in the correct order before the build target is called. WARNING dbs is deprecated, please switch to the `3.0 (quilt)' Debian source package format instead. See for a short guide how to do it. WHY DBS Suppose that you have just debianized a package with dh_make(8) and debhelper(7). It may work for a simple package, but problems arise if the situation becomes really complicated: · If you modified the upstream source a lot, it is difficult which part of .diff.gz is Debian-specific. This means the upstream has to have a hard time if he/she wants to integrate improvement in .diff.gz to the next release. · If the format of the upstream source is not .tar.gz or if there are 2 or more upstream tarballs, without dbs you have to repack the upstream source. This makes verification (such as a md5sum check) impossible. dbs solves these problems by putting unchanged upstream tarballs in .orig.tar.gz and patch files in .diff.gz. The backdraft of dbs is that it is more complicated and non-standard. Because it was not packaged for Debian for a long time there are many slightly differing flavours around. Dbs should only be used if its special benefits are required. If you use dbs, include a README.build in the debian directory which lists the basic commands required for unpacking and adding a patch. You could simply copy the one from the dbs examples directory. THE FIRST STEP For example, I have a package tenmado (0.1-1). It was packaged without dbs. Now I want to repackage it with dbs. The first thing to do is to create a empty directory and copy the upstream tarballs into it, the name of the directory should be the standard package-upstream.version format. If the package is already in the Debian archive, you have to play some dirty trick on the upstream version number to overwrite .orig.tar.gz . You may want to contact the upstream in advance. Note that you should not use an epoch in this case. Choose a version-number that is higher than the current one and lower than the next upstream version. Check with dpkg --compare-versions! Here I use 0.1dbs. $ mkdir tenmado-0.1dbs $ cp tenmado-0.1.tar.gz tenmado-0.1dbs Make sure that the name of the upstream tarballs has a standard suffix. dbs tries to auto-detect which file is the upstream tarball by checking its name. Currently .tgz, .tar.gz, .tar.bz and .tar.bz2 are supported. The upstream of tenmado distributes a PGP signature of the source code. It is a good idea to include it and the public key of the upstream in this directory too so that the upstream tarball can be verified later. $ cp tenmado-0.1.tar.gz.asc tenmado-0.1dbs $ cp pub-key.txt tenmado-0.1dbs Then create the .orig.tar.gz that contains this directory. $ tar zcf tenmado_0.1dbs.orig.tar.gz tenmado-0.1dbs/ ADDING THE DEBIAN DIRECTORY The next step is to add the debian directory to the top of the source tree. If you have already debianized the package, copying the previous debian directory is a good start. $ cp -R tenmado-0.1/debian/ tenmado-0.1dbs/ Of course this debian directory needs modification. First, this package must build-depend on dbs, but this is trivial. The main change is in debian/rules. The file /usr/share/dbs/dbs-build.mk provides makefile targets that are necessary to use dbs. Import this file in debian/rules after you set DH_COMPAT (and, if necessary, TAR_DIR, which is described below). export DH_COMPAT=3 TAR_DIR = tenmado-0.1 # the dbs rules include /usr/share/dbs/dbs-build.mk dbs comes with one more makefile, that is, /usr/share/dbs/dpkg-arch.mk. It sets architecture specification strings. It is not dbs-specific, but including it too is a good thing. # convenient way to set architecture specification strings # the ifeq condition is here to allow them to be overridden # from the command line ifeq (,$(DEB_BUILD_GNU_TYPE)) include /usr/share/dbs/dpkg-arch.mk endif The build target must be called after the source is unpacked and patched. The right way to do this is to have the build (or build-stamp) target depend on the $(patched) target, which is defined in dbs-build.mk. Usually you need to move to the top of the source tree to configure, build or install it. dbs defines BUILD_TREE for this purpose. By default, it is $(SOURCE_DIR)/$(TAR_DIR) if TAR_DIR is defined (useful if there is only one upstream tarball), $(SOURCE_DIR) otherwise. The default of SOURCE_DIR in dbs-build.mk is build-tree. configure: configure-stamp configure-stamp: $(patched) dh_testdir # Add here commands to configure the package. cd $(BUILD_TREE) && ./configure --prefix=/usr \ --bindir=/usr/games \ --mandir=/usr/share/man touch configure-stamp build: configure-stamp build-stamp build-stamp: $(patched) dh_testdir # Add here commands to compile the package. cd $(BUILD_TREE) && $(MAKE) touch build-stamp install: build dh_testdir dh_testroot dh_clean -k dh_installdirs # Add here commands to install the package into debian/tenmado. cd $(BUILD_TREE) && $(MAKE) install \ DESTDIR=$(CURDIR)/debian/tenmado/ The clean target must remove the directories $(STAMP_DIR) and $(SOURCE_DIR). There is no need to call $(MAKE) distclean because the entire build tree is removed anyway. clean: dh_testdir dh_testroot rm -f build-stamp configure-stamp # Add here commands to clean up after the build process. rm -rf $(STAMP_DIR) $(SOURCE_DIR) dh_clean If you are using debhelper(7), you may need to modify file lists for debhelper (such as debian/package.docs) and the argument of dh_installchangelogs(1) (the upstream changelog). MODIFYING THE UPSTREAM SOURCE To modify the upstream source appropriately, you have to unpack the upstream source and apply some of the patches (it depends on what kind of modification you want to make). Doing this every time you modify the source is painful, so dbs includes a dedicated command, that is, dbs-edit-patch(1). dbs-edit-patch requires the name of a patch file as an argument. By convention, the name of a patch file is two digits followed by a short description of what the patch does. In this way you can specify in what order the patch is applied. dbs-edit-patch must be called in the top directory of the source tree. It unpacks the upstream tarballs in a subdirectory of $TMP_DIR (default /tmp) and applies all patches "before" (in the sense of the default order of sort(1)) the patch file being edited (the command line argument). I recommend overriding $TMP_DIR with the -t (--tmpdir) option or the $TMP environment variable. Building a package in a world-writable directory and distribute it is not a good practice. All patch files are saved in the directory $PATCH_DIR (default $SOURCE_DIR/debian/patches). The default of SOURCE_DIR in dbs-build.mk is the current directory (compare this with dbs-build.mk). All files in $PATCH_DIR are considered as patch files unless their name begins with chk-. dbs-edit-patch does not create $TMP_DIR or $PATCH_DIR. You have to create them if necessary before you call dbs-edit-patch. $ dbs-edit-patch -t ~/dbs-tmp/ 10pointer_to_readme Extracting source tenmado-0.1.tar.gz ... successful. Copying tenmado-0.1 to tenmado-0.1-old ... successful. Patch does not yet exist; will create a new patch 10pointer_to_readme Move to $TMP_DIR and you will find a directory which has the same name as the patch file being edited. This contains two directories (the source tree and its copy) and one script (named dbs-update-patch). Edit the source tree (that is, the directory whose name does not end with -old) and run ./dbs-update-patch when done. Note that ./dbs-update-patch removes all files whose name ends with .bak or ~ before generating a patch. MISC STUFF The setup target in dbs-build.mk is almost equal to $(patched), with one exception - the setup target calls the command up-scripts (no, it is not ./up-scripts, it is something on your $PATH) before unpacking. The script /usr/share/dbs/dbs_split reads debian/package.in (where package is a package name) or debian/packages.d/package.in (if debian/packages.d exists) and split it at the line which begins %filename%, where filename can be any file name. If the package.in file contains a line that begins with %filename%, the text between that line and the next %filename% are written to the file debian/package.filename (or debian/filename - the behavior is the same as debhelper). Typically, package.in files are generated from other files, for example, package.in.in . FILES AND DIRECTORIES blah-version/foo.tar.gz, blah-version/bar.tar.bz2 original vanilla upstream sources of the package blah, shipped in the tar file blah_version.orig.tar.gz. dbs supports upstream sources in tar.gz, tgz, tar.bz and tar.bz2-format. debian/patches/ dbs will apply all these patches using patch -p0 in alphanumeric order. You might want to name them e.g. 00_first.patch to 99_last.patch. stampdir/ Status- and log-files. buildtree/ Actual build-directory. BASIC INTERACTION WITH debian/rules See above for details. unpacked Unpacks the source(s) in build-tree/ setup Unpacks the source(s), applies patches, calls the command up-scripts. make_patch Generates a diff between the (modified) tree in build-tree and the result of the setup-target in the file new.diff. SEE ALSO dbs-edit-patch(1), /usr/share/doc/dbs/, the hello-dbs source package, ⟨⟩ AUTHOR The original version of dbs was written by Adam Heath. Some other maintainers also used dbs by including their own copy of dbs in their packages. Later dbs was packaged by Brian May. It was based on a modified version of dbs by Ben Collins. This man page was generated by Andreas Metzler, mostly by reformatting the mini-HOWTO by Oohara Yuuma.
http://manpages.ubuntu.com/manpages/precise/man7/dbs.7.html
CC-MAIN-2016-18
refinedweb
1,691
67.76
Daniel, did you include the patch for reading names of anon regions out of /proc/<pid>/maps ? Cheers, Gisle On Mon, 2008-04-28 at 18:42 +0200, Daniel Hansel wrote: > Hi, > > finally we have fixed that 64bit issue that Gisle Dankel has mentioned > (and patched) before. > > Please review my patch and give comments. > > Kind regards, > Daniel > > John Levon wrote: > > On Mon, Apr 28, 2008 at 03:02:13AM +0200, Daniel Hansel wrote: > > > >> Please review my new patch and give comments. > > > > So I tried it out, but it doesn't work for me. I ran: > > > > public class HelloWorld { > > public static void main(String [] args) { > > for (;;) > > sayHelloWorld(); > > } > > > > public static void sayHelloWorld() { > > System.out.println("hello\n"); > > } > > }; > > > > plus some of the Swing demos like this: > > > > java -agentpath:/usr/local/oprofile-jit/lib/oprofile/libjvmti_oprofile.so.0.0.0 HelloWorld >/dev/null > > > > I get a jitdump file: > > > > # ls -lrt /var/lib/oprofile/jitdump/ > > total 440 > > -rw------- 1 moz moz 441616 2008-04-28 03:47 27111.dump > > > > But the output has nothing: > > > > # opreport -l | more > > ... > > warning: [vdso] (tgid:14265 range:0x7fff56bfd000-0x7fff56bff000) could not be found. > > ... > > - this isn't a JIT thing, but when did these start turning up? > > Yuck - needs fixing. > > ... > > CPU: AMD64 processors, speed 2002.55 MHz (estimated) > > Counted CPU_CLK_UNHALTED events (Cycles outside of halt state) with a unit mask of 0x00 (No unit mask) count 100000 > > samples % image name app name symbol name > > 324908 33.5486 no-vmlinux no-vmlinux /no-vmlinux > > 273758 28.2670 anon (tgid:27111 range:0x2aaaac005000-0x2aaaac276000) java anon (tgid:27111 range:0x2aaaac005000-0x2aaaac276000) > > > > > > No Java symbols are listed at all, just the anonymous region. > > Am I doing something wrong? > > > > Using the Sun Java 1.6 JDK. > > > > regards > > john > > ------------------------------------------------------------------------- > This SF.net email is sponsored by the 2008 JavaOne(SM) Conference > Don't miss this year's exciting event. There's still time to save $100. > Use priority code J8TL2D2. >;198757673;13503038;p? > _______________________________________________ oprofile-list mailing list oprofile-list@... View entire thread
http://sourceforge.net/p/oprofile/mailman/message/19255142/
CC-MAIN-2014-52
refinedweb
327
77.03
table of contents - NAME - SYNOPSIS - DESCRIPTION - OPTIONS - EXAMPLES - Building an image using a Dockerfile located inside the current directory - Building an image and naming that image - Building an image using a URL - Building an image using a URL to a tarball'ed context - Specify isolation technology for container (--isolation) - HISTORY NAME¶docker-build - Build an image from a Dockerfile SYNOPSIS¶docker build [--add-host[=[]]] [--build-arg[=[]]] [--cache-from[=[]]] [--cpu-shares[=0]] [--cgroup-parent[=CGROUP-PARENT]] [--help] [--iidfile[=CIDFILE]] [-f|--file[=PATH/Dockerfile]] [-squash] Experimental [--force-rm] [--isolation[=default]] [--label[=[]]] [--no-cache] [--pull] [--compress] [-q|--quiet] [--rm[=true]] [-t|--tag[=[]]] [-m|--memory[=MEMORY]] [--memory-swap[=LIMIT]] [--network[="default"]] [--shm-size[=SHM-SIZE]] [--cpu-period[=0]] [--cpu-quota[=0]] [--cpuset-cpus[=CPUSET-CPUS]] [--cpuset-mems[=CPUSET-MEMS]] [--target[=[]]] [--ulimit[=[]]] PATH | URL | - DESCRIPTION¶This will read the Dockerfile from the directory specified in PATH. It also sends any other files and directories found in the current directory to the Docker daemon. The contents of this directory would be used by ADD commands found within the Dockerfile. Warning, this will send a lot of data to the Docker daemon depending on the contents of the current directory. The build is run by the Docker daemon, not by the CLI, so the whole context must be transferred to the daemon. The Docker CLI reports "Sending build context to Docker daemon" when the context is sent to the daemon. When the URL to a tarball archive or to a single Dockerfile is given, no context is sent from the client to the Docker daemon. In this case, the Dockerfile at the root of the archive and the rest of the archive will get used as the context of the build. When a Git repository is set as the URL, the repository is cloned locally and then sent as the context. OPTIONS¶-f, --file=PATH/Dockerfile Path to the Dockerfile to use. If the path is a relative path and you are building from a local directory, then the path must be relative to that directory. If you are building from a remote URL pointing to either a tarball or a Git repository, then the path must be relative to the root of the remote context. In all cases, the file must be within the build context. The default is Dockerfile. --squash=true|false Experimental Only. --add-host=[] Add a custom host-to-IP mapping (host:ip) Add a line to /etc/hosts. The format is hostname:ip. The --add-host option can be set multiple times. --build-arg=variable name and value of a buildarg. For example, if you want to pass a value for http_proxy, use --build-arg=http_proxy="" Users pass these values at build-time. Docker uses the buildargs as the environment context for command(s) run via the Dockerfile's RUN instruction or for variable expansion in other Dockerfile instructions. This is not meant for passing secret values. Read more about the buildargs instruction ⟨⟩ --cache-from="" Set image that will be used as a build cache source. --force-rm=true|false Always remove intermediate containers, even after unsuccessful builds. The default is false. --isolation="default" Isolation specifies the type of isolation technology used by containers. --label=label Set metadata for an image --no-cache=true|false Do not use cache when building the image. The default is false. --iidfile="" Write the image ID to the file --help Print usage statement --pull=true|false Always attempt to pull a newer version of the image. The default is false. --compress=true|false Compress the build context using gzip. The default is false. -q, --quiet=true|false Suppress the build output and print image ID on success. The default is false. --rm=true|false Remove intermediate containers after a successful build. The default is true. -t, --tag="" Repository names (and optionally with tags) to be applied to the resulting image in case of success. Refer to docker-tag(1) for more information about valid tag names. -m, --memory=MEMORY Memory limit --memory-swap=LIMIT A limit value equal to memory plus swap. Must be used with the -m (--memory) flag. The swap LIMIT should always be larger than -m (--memory) value. The format of LIMIT is <number>[<unit>]. Unit can be b (bytes), k (kilobytes), m (megabytes), or g (gigabytes). If you don't specify a unit, b is used. Set LIMIT to -1 to enable unlimited swap. --network=bridge Set the networking mode for the RUN instructions during build. Supported standard values are: bridge, host, none and container:<name|id>. Any other value is taken as a custom network's name or ID which this container should connect to. --shm-size. --cpu-shares=0 CPU shares (relative weight). By default, all containers get the same proportion of CPU cycles. CPU shares is a 'relative weight', relative to the default setting of 1024. This default value is defined here: cat /sys/fs/cgroup/cpu/cpu.shares 1024 You can change this proportion by adjusting the container's CPU share weighting relative to the weighting of all other running containers. To modify the proportion from the default of 1024, use the --cpu-shares flag to set the weighting to 2 or higher. Container CPU share Flag {C0} 60% of CPU --cpu-shares=614 (614 is 60% of 1024) {C1} 40% of CPU --cpu-shares=410 (410 is 40% of 1024) The proportion is only applied when CPU-intensive processes are running. When tasks in one container are idle, the other containers can use the left-over CPU time. The actual amount of CPU time used varies depending on the number of containers running on the system. For example, consider three containers, where one has --cpu-shares=1024 and two others have --cpu-shares=512. When processes in all three containers attempt to use 100% of CPU, the first container would receive 50% of the total CPU time. If you add a fourth container with --cpu-shares=1024, the first container only gets 33% of the CPU. The remaining containers receive 16.5%, 16.5% and 33% of the CPU. Container CPU share Flag CPU time {C0} 100% --cpu-shares=1024 33% {C1} 50% --cpu-shares=512 16.5% {C2} 50% --cpu-shares=512 16.5% {C4} 100% --cpu-shares=1024 33% On a multi-core system, the shares of CPU time are distributed across the CPU cores. Even if a container is limited to less than 100% of CPU time, it can use 100% of each individual CPU core. For example, consider a system with more than three cores. If you start one container {C0} with --cpu-shares=512 running one process, and another container {C1} with --cpu-shares=1024 running two processes, this can result in the following division of CPU shares: PID container CPU CPU share 100 {C0} 0 100% of CPU0 101 {C1} 1 100% of CPU1 102 {C1} 2 100% of CPU2 --cpu-period=0 Limit the CPU CFS (Completely Fair Scheduler) period. Limit the container's CPU usage. This flag causes the kernel to restrict the container's CPU usage to the period you specify. --cpu-quota=0 Limit the CPU CFS (Completely Fair Scheduler) quota. By default, containers run with the full CPU resource. This flag causes the kernel to restrict the container's CPU usage to the quota you specify. --cpuset-cpus=CPUSET-CPUS CPUs in which to allow execution (0-3, 0,1). --cpuset-mems=CPUSET-MEMS Memory nodes (MEMs) in which to allow execution (0-3, 0,1). Only effective on NUMA systems. For example, if you have four memory nodes on your system (0-3), use --cpuset-mems=0,1 to ensure the processes in your Docker container only use memory from the first two memory nodes. --cgroup-parent=CGROUP-PARENT Path to cgroups under which the container's cgroup are created. If the path is not absolute, the path is considered relative to the cgroups path of the init process. Cgroups are created if they do not already exist. --target="" Set the target build stage name. --ulimit=[] Ulimit options For more information about ulimit see Setting ulimits in a container ⟨⟩ EXAMPLES¶ Building an image using a Dockerfile located inside the current directory¶Docker images can be built using the build command and a Dockerfile: docker build . During the build process Docker creates intermediate images. In order to keep them, you must explicitly set --rm=false. docker build --rm=false . A good practice is to make a sub-directory with a related name and create the Dockerfile in that directory. For example, a directory called mongo may contain a Dockerfile to create a Docker MongoDB image. Likewise, another directory called httpd may be used to store Dockerfiles for Apache web server images. It is also a good practice to add the files required for the image to the sub-directory. These files will then be specified with the COPY or ADD instructions in the Dockerfile. Note: If you include a tar file (a good practice), then Docker will automatically extract the contents of the tar file specified within the ADD instruction into the specified target. Building an image and naming that image¶A good practice is to give a name to the image you are building. Note that only a-z0-9-_. should be used for consistency. There are no hard rules here but it is best to give the names consideration. The -t/--tag flag is used to rename an image. Here are some examples: Though it is not a good practice, image names can be arbitrary: docker build -t myimage . A better approach is to provide a fully qualified and meaningful repository, name, and tag (where the tag in this context means the qualifier after the ":"). In this example we build a JBoss image for the Fedora repository and give it the version 1.0: docker build -t fedora/jboss:1.0 . The next example is for the "whenry" user repository and uses Fedora and JBoss and gives it the version 2.1 : docker build -t whenry/fedora-jboss:v2.1 . If you do not provide a version tag then Docker will assign latest: docker build -t whenry/fedora-jboss . When you list the images, the image above will have the tag latest. You can apply multiple tags to an image. For example, you can apply the latest tag to a newly built image and add another tag that references a specific version. For example, to tag an image both as whenry/fedora-jboss:latest and whenry/fedora-jboss:v2.1, use the following: docker build -t whenry/fedora-jboss:latest -t whenry/fedora-jboss:v2.1 . So renaming an image is arbitrary but consideration should be given to a useful convention that makes sense for consumers and should also take into account Docker community conventions. Building an image using a URL¶This will clone the specified GitHub repository from the URL and use it as context. The Dockerfile at the root of the repository is used as Dockerfile. This only works if the GitHub repository is a dedicated repository. docker build github.com/scollier/purpletest Note: You can set an arbitrary Git repository via the git:// scheme. Building an image using a URL to a tarball'ed context¶This will send the URL itself to the Docker daemon. The daemon will fetch the tarball archive, decompress it and use its contents as the build context. The Dockerfile at the root of the archive and the rest of the archive will get used as the context of the build. If you pass an -f PATH/Dockerfile option as well, the system will look for that file inside the contents of the tarball. docker build -f dev/Dockerfile Note: supported compression formats are 'xz', 'bzip2', 'gzip' and 'identity' (no compression). Specify isolation technology for container (--isolation)¶This option is useful in situations where you are running Docker containers on Windows. The --isolation=<value> option sets a container's isolation technology. On Linux, the only supported is the default option which uses Linux namespaces. On Microsoft Windows, you can specify these values: -".
https://manpages.debian.org/unstable/docker.io/docker-build.1.en.html
CC-MAIN-2020-10
refinedweb
2,016
56.45
Registered users can ask their own questions, contribute to discussions, and be part of the Community! Registered users can ask their own questions, contribute to discussions, and be part of the Community! Originally posted by Dataiku on August 19, 2021 by @NeilM If you like this also check out Shoot and Score With NBA Fantasy Predictive Modeling in Dataiku In this series, we explore constructing a fantasy sports roster as an example use case of an organization having to optimally allocate resources. In the first part, we introduced the topic of optimization in enterprise contexts and began building an end-to-end solution with data exploration and predictive analytics. We are now ready to explore how to solve an optimization problem called the Knapsack Problem to construct a strong roster using our predictions. As we covered in the first part, a common type of problem that comes up in enterprise data-driven projects is determining how to optimally allocate resources. These problems come up in a variety of industries, including logistics, manufacturing, retail, human resources, and — as we explore in this series — sports. Specifically, the use case we examine is how to build a fantasy basketball roster given a set of players with various salaries and abilities to produce in-game. The goal of optimization is to maximize or minimize some objective function, and often these problems involve some constraints that must be adhered to. For our use case, the objective function we are looking to maximize is the number of fantasy points that our constructed team will score. Using the DraftKings daily fantasy ruleset, various point values are awarded or penalized based on a player’s in-game action, such as scoring points, rebounds, assists, turnovers, etc. The constraints for our problem include a limit on salary, positions, and availability of certain players. Specifically, we must stay under a salary cap of $50,000, and the roster of players must consist of eight players who are playing on a given day: point guard (PG), shooting guard (SG), small forward (SF), power forward (PF), center (C), guard (PG or SG), forward (SF or PF), and utility player (Any Position). The focus of the previous article was on building a data pipeline to predict performance of the players in question. Making these predictions is essential prior to optimizing a roster because we need some metric representing how many points our team will score in order to maximize our objective function. Since we do not know these values prior to the games, the predicted number of points generated by our model can be used as a proxy for player production. The above graph plots the number of points each player is predicted to score and their salary for the slate of games on May 16, 2021 (the last day of the 2020-21 NBA regular season). Plotting points versus salary gives us a sense of which players are likely to outperform or underperform their price. Our goal is not just to identify players who will score a lot of points. Rather, striking a balance of low salary with high production by selecting players like Lauri Markkanen is the objective. Solving our optimization problem — which can be framed as the classic Knapsack Problem — will help us identify the best roster of players that will give us the best bang for our buck. The Knapsack Problem The problem we are attempting to solve — selecting a high-scoring roster of players while adhering to constraints — is a modified version of an optimization scenario called the Knapsack Problem. Imagine a robber breaks into a home with a knapsack. The items in the house have various different values and also weigh different amounts. The robber has to grab the most valuable items while also noting the limitations of how much weight he can carry in his knapsack. This framing of the problem translates directly to optimization problems in many enterprise contexts. Employment decisions, supply chain, and, in our case, building a fantasy basketball roster all share the objective of trying to get the most value (choosing more valuable players) while adhering to a constraint (a limit on salary). These problems can of course modify the classic Knapsack Problem and introduce further constraints, as is the case with the positional and availability constraints in our fantasy basketball problem. So how do we solve the Knapsack Problem problem, and how do we modify it to fit our specific problem? There are many potential approaches, including programmatic solutions such as greedy search or dynamic programming. Instead of tackling the problem in these ways, we will use an optimization approach. A special case of optimization is linear programming (LP), which requires the objective function and any constraints to be linear equalities or inequalities. Luckily, our objective and all of our constraints can be refactored as linear expressions, so to solve our problem we can use Python libraries that are commonly used for LP problems such as cvxpy and cvxopt. Solving Knapsack With Python Let’s examine some key code snippets used to solve the Knapsack Problem step by step. First, we import necessary libraries. import dataiku import pandas as pd, numpy as np import cvxpy Next, we read the input dataset as a dataframe. This dataset will be the output of the predictive analytics pipeline we built in the first part of this series and will include columns for the date of each slate of games (“Date”) along with each player’s name (“Name_BBRef”), salary (“Salary_DK”), predicted points (“Points_Predict”), and actual points (“Points_Actual”). For the purposes of this article, we will look at the games for the last week of the 2020-21 NBA regular season (May 10, 2021 - May 16, 2021). nba_knapsack_prep = dataiku.Dataset("nba_knapsack") knapsack_df = nba_knapsack_prep.get_dataframe() Now we define parameters for the problem. We want to keep these parameters configurable so that they can be modified when applying this code to accept different datasets and solve different objective functions and constraints. agg_col = 'Date' label_col = 'Name_BBRef' cost_col = 'Salary_DK' value_col = 'Points_Predict' actual_col = 'Points_Actual' cap = 50000 selection_n = 8 The first five parameters represent columns in the input dataset mentioned above. The cap represents the limitation on salary for our roster, and selection_n represents how many players we wish to select. Now we are ready to set up and solve the knapsack problem in four steps: 1. Gather player costs and values, and initialize the optimization variables. costs = np.array(df[cost_col]) values = np.array(df[value_col]) selection = cvxpy.Variable(len(costs), boolean=True) 2. Define objective function to maximize. total_value = values @ selection 3. Define cap and positional constraints. cost_constraint = costs @ selection <= cap roster_constraint = np.ones(len(costs)) @ selection == selection_n pg_constraint = pg @ selection >= 1 sg_constraint = sg @ selection >= 1 sf_constraint = sf @ selection >= 1 pf_constraint = pf @ selection >= 1 c_constraint = c @ selection >= 1 g_constraint = (pg + sg) @ selection >= 3 f_constraint = (sf + pf) @ selection >= 3 4. Define and solve the Knapsack Problem. knapsack_problem = cvxpy.Problem(cvxpy.Maximize(total_value), [cost_constraint, roster_constraint, max_constraint,pg_constraint, sg_constraint, sf_constraint, pf_constraint, c_constraint, g_constraint, f_constraint]) value_opt = knapsack_problem.solve(solver=cvxpy.GLPK_MI) We can perform the above steps in a loop to solve for the three most optimal rosters on each date. Finally, we save the rosters into an output dataset. nba_knapsack_output = dataiku.Dataset("nba_knapsack_output") nba_knapsack_output.write_with_schema(nba_knapsack_output_df) The output dataset, shown below, consists of each of the optimal rosters including the names of the eight players, the total salary of the roster, the predicted total points, and the actual total points. The lineups generated by the optimizer all have a total cost very close to $50,000, which is what we expect since it makes sense to try to utilize as much of the salary cap that is available to us as possible. The prediction for the total number of points the team will score lines up reasonably well with how many points the team actually scored, and the constructed lineup even occasionally outperforms projections (e.g. May 10). The solution we have built is effective at assembling a roster of NBA players given the objective and constraints discussed. However, what if we wanted to tackle other similar optimization problems or wanted to modify our constraints? What if we want to share this solver with users or colleagues who may not be well-versed in Python? Stay tuned for the final part of this series, where we will cover how to make this optimization solver configurable and user-friendly by developing a custom plugin. Try Dataiku Today As seen in this project, Dataiku makes it easy to solve the Knapsack Problem in order to ultimately, construct a strong roster using our predictions. Take the platform for a spin to see for yourself!
https://community.dataiku.com/t5/General-Discussion/Grab-Your-Knapsack-Let-s-Construct-an-NBA-Roster/td-p/20217
CC-MAIN-2022-40
refinedweb
1,438
50.06
This notification project can work as a normal grandfather's clock with famous Westminster Quarters melody. The easiest way is to use this Add-On file called chimeClock.py. You can invoke it regularly adding this line to your crontab (crontab -e): 0,15,30,45 * * * * python /path/to/file/chimeClock.pyAttention! This chimeClock.py works only if the chimeService.py is running, as it is written in the Program Code v0.2. chimeClock.py import datetime import sys, zmq speed = 0.8 #Mute it during night hours now=datetime.datetime.now() if ( ( now.hour > 22 ) and ( now.minute > 10 ) ) or ( now.hour < 9 ): sys.exit(0) port = "5555" #Westminster Quarters firstQuarter = [1,speed,2,speed,3,speed,4,speed * 2] secondQuarter = [3,speed,1,speed,2,speed,4,speed * 2, 3,speed,2,speed,1,speed,3,speed * 2] thirdQuarter = [1,speed,3,speed,2,speed,4,speed * 2, 4,speed,2,speed,1,speed,3,speed * 2, 1,speed,2,speed,3,speed,4,speed * 2] fourthQuarter = [3,speed,1,speed,2,speed,4,speed * 2, 3,speed,2,speed,1,speed,3,speed * 2, 1,speed,3,speed,2,speed,4,speed * 2, 4,speed,2,speed,1,speed,3,speed * 2] Hour = [0,speed * 4] context = zmq.Context() socket = context.socket(zmq.REQ) socket.connect ("tcp://localhost:%s" % port) def preparePattern( array ): pattern = "" for i in range(0, len(array), 2): pattern = pattern + str(array[i]) + ":" + str(array[i+1]) if i < len(array) - 2 : pattern = pattern + "-" return pattern def sound( array ): pattern = preparePattern(array) socket.send (pattern) if now.minute == 15: sound(firstQuarter) elif now.minute == 30: sound(secondQuarter) elif now.minute == 45: sound(thirdQuarter) elif now.minute == 0: sound(fourthQuarter) if(now.hour > 12): hour = now.hour - 11 elif(now.hour == 0 ): hour = 12 else: hour = now.hour for x in xrange(1,hour): sound(Hour) pass Discussions Become a Hackaday.io Member Create an account to leave a comment. Already have an account? Log In.
https://hackaday.io/project/10771-audible-notifications-by-a-grandfathers-clock/log/36381-clock-add-on
CC-MAIN-2019-35
refinedweb
332
71.71
Thanks for taking the time to open this. I am just starting to learn Java and cannot seem to get past a point in the program I'm currently working on. I'm making a credit card verifier, where you enter the numbers and an algorithm deems it valid or invalid. I have that part down, but I cannot figure out how to adjust when given a different length credit card. Let me explain further: The program has to be able to accept cards between 13 an 16 digits in length. I'm currently using an array (which I know cannot be adjusted once created) to perform my algorithm. This accepts and stores 16 numbers and then performs what I need it to. I need to somehow allow my user to input a number or character that sets the array to the length of what they have already entered. RIght now, if they stop after 14, my program is still looking for numbers until it hits 16. I need the user to be able to stop the input and for the program to be able to adjust for the input (since it depends on the indexes of the input to verify it) This is what I have so far, the algorithm isn't imposed yet. However, you do see that I am trying to use the numbers.length command to get the index of the last number (whether that is 13, 14, etc.) and multiply it by 2. Is this acceptable? Any help is appreciated. import java.util.Scanner; import java.util.Arrays; public class Exercise05 { public static void main(String []args) { Scanner input= new Scanner(System.in); int i; int[] numbers; double round1; numbers= new int [16]; for(i=0 ;i < numbers.length; i++){ numbers[i]=input.nextInt(); } System.out.print("The Credit Card digits you entered are: "); System.out.println(Arrays.toString(numbers)); double round1= (numbers[numbers.length] * 2); System.out.println( "you " + round1 ); if( numbers[0]==4) System.out.println("This is a Visa"); else if( numbers[0]==5) System.out.println("This is a Mastercard"); else if( numbers[0]==6) System.out.println("This is a Discover Card"); else if( numbers[0]==3 && numbers[1]==7 ) System.out.println("This is a Mastercard"); else System.out.println("Invalid card"); } }
https://www.daniweb.com/programming/software-development/threads/413835/beginners-program-help-very-simple
CC-MAIN-2017-39
refinedweb
383
59.19
. Hmm if only I had been a little slower I could have posted here. Anyways, here's a bug report. Short version is, closing one window closes all windows. Tested in W7 x64 3028 is out now, fixing a crash bug introduced in 3027. It'd be nice to display the version number to install on the update window Bug in C/C++ syntax definition: Comment after #endif is not recognized as comment. Examples: #if #endif //!MS_WINDOWS #if #endif /* !MS_WINDOWS */ I confirm.Bug is also happening on #error or #warning, but not on #include.There's something fishy with comments in C/C++ syntax, see this long outstanding bug : Sometimes Sublime gets into a mode where pressing esc does not switch to command mode (Vintage enabled). It moves cursor backwards instead. sublime.log_commands(True) shows that "command: exit_insert_mode" is executed.
https://forum.sublimetext.com/t/dev-build-3027/9747/4
CC-MAIN-2017-22
refinedweb
140
60.41
Split testing library for Clojure CHANGELOG | API | current Break Version: [com.taoensso/touchstone "2.0.2"] ; Stable See here if you're interested in helping support my open-source work, thanks! - Peter Taoussanis A/B testing is great for conversion optimization. We should all be doing more of it. But traditional A/B tests can be a nuisance to setup and monitor. Touchstone is an attempt to bring dead-simple, high-power split-testing to any Clojure web application. It uses multi-armed bandit techniques to provide fast, accurate, low-maintenance conversion optimization. The API is simple and highly flexible. Last updated: Jan 2016 Haven't updated the lib in forever, but it's stable and works well in production. Do have some new stuff planned for a future update (particularly docs re: use with modern Cljs applications), but no ETA on that yet. Add the necessary dependency to your project: Leiningen: [com.taoensso/touchstone "2.0.2"] ; or deps.edn: com.taoensso/touchstone {:mvn/version "2.0.2"} And setup your namespace imports: (ns my-ns (:require [taoensso.touchstone :as touchstone :refer (*ts-id*)])) Traditional split-testing consists of 4 steps: The particular multi-armed bandit technique used by Touchstone means that we only concern ourselves with steps 1 and 3. Steps 2 and 4 are handled automatically by the algorithm. Start by adding (taoensso.touchstone.ring/wrap-test-subject-id)to your middleware stack. One or more test selectors can then be used as part of your page content: (touchstone/mab-select {:conn-opts {} ; Optional, as per Carmine's `wcar` conn-opts } *ts-id* ; Dynamic test-subject-id (assigned by middleware) :my-app/landing.buttons.sign-up ; Test id :sign-up "Sign-up!" ; Named variation #1 :join "Join!" ; Named variation #2 :join-now "Join now!" ; Named variation #3 ) And relevant events (e.g. conversions) recorded: ;; On sign-up button click, etc.: (touchstone/mab-commit! {} ; Same opts as given to `mab-select` *ts-id* :my-app/landing.buttons.sign-up 1) Touchstone will now automatically start using accumulated statistical data to optimize the selection of the :my-app/landing.buttons.signuptest variations for maximum clicks. And you're done! That's literally all there is to it. See the mab-selectand mab-commit!API docs for info on more advanced capabilities like multivariate testing, test composition (dependent tests), arbitrary scoring, engagement testing, etc. Please use the project's GitHub issues page for all questions, ideas, etc. Pull requests welcome. See the project's GitHub contributors page for a list of contributors. Otherwise, you can reach me at Taoensso.com. Happy hacking! Distributed under the EPL v1.0 (same as Clojure).
https://xscode.com/ptaoussanis/touchstone
CC-MAIN-2021-49
refinedweb
441
53.07
Aefined palettes: if ncolors == 1 && colors == 0, then a Rainbow Palette: Definition at line 33 of file TAttImage.h. #include <TAttImage.h> Default constructor, sets all pointers to 0. Definition at line 270 of file TAttImage.cxx. Copy constructor. Definition at line 297 of file TAttImage.cxx. Constructor for a palette with numPoints anchor points. It allocates the memory but does not set any colors. Definition at line 284 of file TAttImage.cxx. Creates palette in the same way as TStyle::SetPalette. Definition at line 317 of file TAttImage.cxx. Destructor. Definition at line 441 of file TAttImage.cxx. Factory method to creates an image palette of a specific typ. Create a new palette This creates a new TImagePalette based on the option specified in the parameter. The supported options are: Ownership of the returned object transfers to the caller. Definition at line 70248 of file TAttImage.cxx. Returns an index of the closest color. Reimplemented in TWebPalette. Definition at line 485 of file TAttImage.cxx. Returns a list of ROOT colors. Could be used to set histogram palette. See also TStyle::SetPalette Reimplemented in TWebPalette, and TDefHistImagePalette. Definition at line 507 of file TAttImage.cxx. Assignment operator. Definition at line 453 of file TAttImage.cxx. .
https://root.cern.ch/doc/master/classTImagePalette.html
CC-MAIN-2021-39
refinedweb
206
54.08
Hi I am using support library android.support.v7.widget.CardView to achieve cardview functionality in my android app. I want to achieve swipe to delete functionality in it as well. > How to achieve swipe to delete functionality in it? Thanks in advance. I am trying to run an Android project that someone else has created. I have opened the project in Eclipse as: File –> New –> Project –> Android Project from existing code Here are the first two lines of one of Java files: package aa.bb.cc; import java.io.File; There is red cross sign at the beginning […] firstly, I coded some methods in Main Activity, But I decided they should be a class. this is my code… openFileOutput and openFileInput are undefined. Any idea?? maybe it should be service or activity…?? package spexco.hus.system; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Date; import spexco.hus.cepvizyon.CepVizyon; import android.content.Context; public class LicenseIDB { private […] My app will feature live video streams. I would like to know if there is a way to detect if the user has 2G, 3G, or 4G on their devices, and if the which category the current connection belongs to? My question is specifically about Android devices. I have an image I am displaying to a user in my android application. I want to be able to tell where they ‘touch’ the image. I can easily get the screen coordinates by implementing an OnTouchListener private OnTouchListener image_Listener = new OnTouchListener(){ @Override public boolean onTouch(View v, MotionEvent event) { if(event.getAction() == MotionEvent.ACTION_UP) { […] If I try nltxt = nllen.toString(); with nllen being int nllen = nl.getLength(); I get the error Cannot invoke toString() on the primitive type int. I want to convert the int to string so i can display the number of entries with Log… Why doesn’t it work? I was in the process of designing an Android application and decided to try out the new Material theme. I found all of the available color schemes for the new theme online, but I was unable to find a corresponding .xml file that has all of the colors in the color palette. Does anyone know […] I have an array of phone numbers and I want to get the corresponding contact names from the contacts database. In the array of phone numbers, I also have some numbers that are not saved before to the contact database. For example; 3333333 -> Tim 5555555 -> Jim 1111111 -> unknown I have the array […] I have a problem with rendering a ScrollView. Essentially, the layout is fixed header and footer with a scrollview in the middle. The idea is that when the screen keyboard is activated for the content EditText the image can be scrolled if the height of the image is longer than the middle view. In testing […] I am getting the following errors: The method getApplicationContext() is undefined The method findViewById(int) is undefined for the type Fragment1 These errors seem to be eliminated when my class is extended to an Activity as oppose to a fragment, but it is important that this activity remains as a fragment, so I am not too […]
http://babe.ilandroid.com/page/2851
CC-MAIN-2018-26
refinedweb
538
66.13
Maveric Jones wrote:I have just started learning java, and am trying to write a program to employ some of the principles I'm learning. Unfortunatly, I'm having some problems with Incompatible types. Firstly, and most importantly, I don't really understand what "Incompatable Types" means. I know im somehow "mixing up" my int and scanner, but beyond that, I'm not sure what I'm doing wrong. The specific error is on line 30. (I will make an arrow to show you all which specific line I mean) To note, I am entirely new to both this forum and Java itself. Any, "Well why the hell didn't you just do this???!!!" comments are not appreciated. Contrarily, any, "These are the rules on this forum." comments are appreciated. I'm not entirely sure if this is where I was to post this question, and I'd be happy to move it if necessary. Here is the code. Thank you many times for any help / info. /** Coin_Fliper_or_Dice_Roller.java Coin_Fliper_or_Dice_Roller application Darren Dalbey @version Alpha 1.00 2011/6/30 */ import static java.lang.System.out; import java.util.Scanner; import java.util.Random ; // Imports class Coin_Fliper_or_Dice_Roller { public static void main(String[] args) { // Standard starting jargon Scanner DiceOrCoinScanner = new Scanner(System.in); Scanner NumberOfDiceScanner = new Scanner(System.in); out.print ("Input Dice For Dice, Coin For Coin "); //Initial input request String Choice = DiceOrCoinScanner.next(); if (Choice.equals ("Dice")) { out.println ("1 or 2 Dice? "); int NumberOfDice = NumberOfDiceScanner.nextInt() ; if (NumberOfDiceScanner == 1) { //For One Die <<<<<-------- (Erroneous Code)}]}]}]}]}]}] int DieRandomizer1 = new Random().nextInt(6) + 1 ; out.println(DieRandomizer1); } } // CoinFlip Program Start if (Choice.equals ("Coin")) { int CoinFlip = new Random().nextInt(2)+1 ; //Coin Randomizer if (CoinFlip == 1) { out.println("------"); out.println("Heads!"); out.println("------"); } else { out.println("------"); out.println("Tails!"); out.println("------"); } // CoinFlip Program Concluded } } } Not that anyone in their right mind would want to, but please don't use this code without asking me. Choppy though it may seem, it represents a good bit of time and effort to me. Maveric Jones wrote:Awesome, thank you. What about 'double' objects? Are they compatible? int and scanner are two objects I use fairly often, and, as such, I get the above error code often. I am trying to figure out a way to repair or work around this in my code. Michael Rippee wrote: I was meaning about Scanners being used to define variables as in, int myVarible = myScanner.nextInt()
http://www.coderanch.com/t/543761/java/java/Incompatible-Types-appreciated-information
CC-MAIN-2014-42
refinedweb
408
61.93
In Groovy we can add a method named call to a class and then invoke the method without using the name call. We would simply just type the parentheses and optional arguments on an object instance. Groovy calls this the call operator: call methods to our class each with different arguments. The correct method is invoked at runtime based on the arguments. (). This can be especially useful in for example a DSL written with Groovy. We can add multiple In the following example we have User class with three call method implementations. Next we see how we invoke the call methods, but without typing the method name and just use the parenthesis and arguments: import groovy.transform.ToString @ToString(includeNames = true) class User { String name String alias String email String website // Set name. def call(final String name) { this.name = name this } // Use properties from data to assign // values to properties. def call(final Map data) { this.name = data.name ?: name this.alias = data.alias ?: alias this.email = data.email ?: email this.website = data.website ?: website this } // Run closure with this object as argument. def call(final Closure runCode) { runCode(this) } } def mrhaki = new User( name: 'Hubert Klein Ikkink', alias: 'mrhaki', email: 'mrhaki@email.nl', website: ' // Invoke the call operator with a String. // We don't have to explicitly use the // call method, but can leave out the method name. // The following statement is the same: // mrhaki.call('Hubert A. Klein Ikkink') mrhaki('Hubert A. Klein Ikkink') // Of course parentheses are optional in Groovy. // This time we invoke the call method // that takes a Map arguemnt. mrhaki email: 'h.kleinikkink@email.nl' assert mrhaki.name == 'Hubert A. Klein Ikkink' assert mrhaki.alias == 'mrhaki' assert mrhaki.email == 'h.kleinikkink@email.nl' assert mrhaki.website == ' // We can pass a Closure to the call method where // the current instance is an argument for the closure. // By using the call operator we have a very dense syntax. mrhaki { println it.alias } // Output: mrhaki // Example to transform the user properties to JSON. def json = mrhaki { new groovy.json.JsonBuilder([vcard: [name: it.name, contact: it.email, online: it.website]]).toString() } assert json == '{"vcard":{"name":"Hubert A. Klein Ikkink","contact":"h.kleinikkink@email.nl","online":" Written with Groovy 2.4.8.
https://blog.mrhaki.com/2017/02/groovy-goodness-using-call-operator.html
CC-MAIN-2022-21
refinedweb
375
70.5
I have previously worked with ReactJS – most notably during my Master’s dissertation, however the main Javascript library I work with when working for clients and companies still remains the venerable JQuery. This is changing as more and more organizations I interact with move to more modern frameworks like Angular and ReactJS. Where to start if you’re looking to upgrade your skills, or migrate a product from JQuery to ReactJS? Any tips? Here’s what we learned so far: Be ready to change your mindset – but never give up It’s not so much a learning curve as it is a roller coaster. Blogger Ben Nadel has an excellent drawing that I guarantee will also be your experience learning any JS framework; be it Angular or React: What makes ReactJS so powerful compared to JQuery is the fact that it’s fundamentally different. Sometimes your own prior experience with JQuery will hamper you in learning React because of pre-conceived notions on how things should be done. Power through it – through all the ups and downs, the curve still has an upwards trend. Once you get to grips with the whole idea of unidirectional data flow, components, props and states, React makes you a lot more productive. That said, there are a few things that helped me transition easier… Create-react-app is a must No doubt about it, the worst part of being a newbie is getting used to the new tools, environments, moving parts and components of your new pipeline. Create-react-app is your savior here. Not only does it setup your dev environment in a few simple commands, you can rest assured that it’s doing so according to industry best practices (which eases those nagging questions at the back of your brain: “Am I doing this right?”). One very useful article I found was how to configure create-react-app to proxy through API requests directly to my back-end: How to get “create-react-app” to work with your API Unleash the power of reusable components It takes banging your head with few project requirements to realize just how powerful and useful React Components are. In reality, the whole point of using React is to define a component once: class David extends React.Component { render() { return (<h1>David says hi...</h1>); } } … and then re-using that component over and over again as a “normal” HTML attribute <David /> Thing is, when clever people start publishing their own components, you can re-use these components and requirements that took days before now take you minutes. These components could be anything, my favorite so far: - Google and Facebook OAuth Authentication - Applying Google’s Material Design Lite quickly and easily to your projects - Giving your web-app offline capabilities (or a whole client-side database!) using Dexie.js Redux-Saga vs Redux-Thunk Talking about Dexie.js brings me to my next point. One of the aspects of Redux that always caught me with my pants down was the inability of reducers to process async functions (it seems logical in hindsight – an async function returns a handle to a future result such as a Promise – not the actual result). This is something you need to keep in mind since some very common requirements like fetching data from an API or indeed using libraries like Dexie require you to use async functions. In order to tackle this, redux-thunk was born. A nice and easy blog post on how to use it can be found here: Coming from a JQuery background, I was already used to the idea that events are used to trigger certain actions – just like in redux actions are used to trigger reducers that in turn change your state. The redux-thunk approach of defining an async function within an action ran a bit contrary to my thinking – an “action creator” as the blog above refers to it. It would be easier (to my JQuery mind) to have a function that “listens” for an async action, performs that async action, and then returns another action with the result for your dispatch to process. This thought process resonated more with me (again, coming from an event / subscription model). In other words: As you can see, this is where Redux-Saga enters the picture. This redux middleware listens for specified actions (usually you’d specify those that need to trigger async actions like API operations or Dexie.js), runs a function to deal with the async actions (tip: definitely try stick to using the yield keyword..) and then dispatches another action with the results that your usual redux reducers can then pick up. I guess it comes down to personal preference, but this paradigm was a lot easier to deal with in my head Always try code a simple / sample project while learning In my case most of my learning was done through reading documentation and via code-academy. My side / sample project was to build a web app that tracks my cryptocurrency investments, incorporating features like indexeddb via Dexie.js, API calls via Saga and so on… (Note sparklines only work if you visit the page at least twice from the same browser – the app has no server side components, it runs entirely in the browser so the sparklines represent change in crytocurrency price since your last visit)
http://blog.davidvassallo.me/2017/05/31/from-jquery-to-reactjs/?shared=email&msg=fail
CC-MAIN-2019-18
refinedweb
892
52.73
Now, we have understood all the basic concepts to create our first C++ program, so let’s take a look how to print a simple ‘Hello World’, statement in C++. #include <iostream.h> // main() is where program execution begins. void main() { cout << "Hello World"; // prints Hello World } The above lines of code will print ‘Hello World’. Now, you know what to do, so let us dig deeper and find out the meaning of some parts of the program: 1. The very first line is: #include <iostream.h> Here, iostream.h is a header file that contains necessary information, which will be utilized in a C++ program. It contains definition of functions, classes, etc. so one can use them easily. 2. The next line // main() is where program execution begins. Begins with a double slash, now this is a C++ comment, which is for better understanding of the written code. We will learn about comments later on. 3. The next line is: void main() Here, void is a return type and it signifies that the function does not return anything, whereas main is the name of a function. All the C++ programs begin execution at the main() function. It is like the starting point of a C++ program. The parenthesis after the word main identify that it is a function. 4. The next line has an open curly braces, signifying that the body of main() has started. 5. The next line is cout << "Hello World"; It causes the message “Hello World” to be displayed on the screen, here, cout is used to print the message written within the double quotes. Now, cout performs a predefined function, this function is mentioned in the iostream header file. Along with this is a comment, which describes what this statement will actually do. 6. The last line of the code is a closing curly brace thus, showing that the body of the main() has ended. Report Error/ Suggestion
https://www.studymite.com/cpp/first-cpp-program-hello-world/?utm_source=related_posts&utm_medium=related_posts
CC-MAIN-2020-05
refinedweb
323
82.14
wchar_t type also known as “wide character” and wstring type also known as “wide string” are a built-in types in C++ which can be used for Unicode system to represent a different languages(other than English) characters and string in our program.Here we will discuss their basic concepts. WCHAR_T type Wide character type can represent characters which the char type cannot.char type has a size of 1 byte so it can hold only 256 characters consisting of English Alphabets,special characters( @,^#&%* ) and some other characters,but there are many known languages and script in the world for instance,Japanese(Kanji or Hiragana or Katakana) , Russian Alphabets , Hindi (Devanagari alphabets) ,etc.These scripts and alphabets can be represented by wide character type and it’s keyword is wchar_t.wchar_t type have a size larger than char type and the size differ according to the machine and platform.In Windows it’s size is 2 bytes and in Linux the size is 4 bytes.To assign a character to wchar_t type a letter “L” is added in front of the character specifying that it is a wide character type and to output a wchar_t type cout is not used instead wcout is used.It simply means wide console output.An example program is given below . #include <iostream> using namespace std ; int main( ) { wcout<< wc1 << endl ; cout<< wc1 << endl ; cout<< sizeof(wchar_t) << endl ; /*** For linux ***/ wcout<< sizeof(wchar_t) ; /***/ cin.get() ; return 0 ; } The output is c 99 2 Note::if we use cout instead of wcout we get an integer value of the character as an output.Every character English alphabets or not has their corresponding integer value ,if cout is used with wide character variable we are accessing the integer value of the character but if wcout is used the compiler will map the integer value to it’s character value and give it as an output. Since wchar_t size is 2 bytes(16 bits) or more it can represent 65536 ( ) or more characters, which is big enough to represent almost all the known possible languages script in the world. wchar_t can be used to represent Unicode characters and ASCII is part of the Unicode system.The first 256 characters of Unicode is same as the ASCII characters from 0 to 127 plus 128 other characters which char data type can represent.This is the reason why wchar can output English alphabets and some special characters which the normal char type can. #include <iostream> using namespace std; int main( ) wchar_t wc=i , wc1=i1 ; wcout<< wc << ” ” << wc1 << endl ; cin.get( ) ; { int i=80 , i1=157 ; /// i<127 , i1>127 unsigned char us=i , us1=i1 ; cout<< us << ” ” << us1 << endl ; return 0 ; } wchar_t wc=i , wc1=i1 ; wcout<< wc << ” ” << wc1 << endl ; cin.get( ) ; The output is P ¥ P ¥ Link:char data type : unsigned char type and signed char type. WSTRING type Wstring is a type that can represent a string of wide character.It has a size of 4 bytes and it’s function is analogous to string type but it can represent collection of wchar_t data.Like the wchar_t type to assign a string to wstring variable a letter “L” will be added and to output the string wcout will be used.A simple wstring program is given below. #include <iostream> using namespace std; int main( ) { wstring ws=L”Where is my Japanese string?” ; wcout<< ws << endl ; cout<< sizeof(wstring) << endl ; cin.get( ) ; return 0 ; } Note a double quotation “” will be used (like the string type) to assign a wide string to it’s variable. Link:Difference between signed and unsigned char type and their uses Why can’t wchar_t print Unicode character? Suppose if I try to print a Unicode character using wchar_t type will I get the character as an output? let us see.Consider the program below in which we will try to print a Hindi letter using wchar_t. wchar wc=L’ऐ’ ; wcout<< wc endl ;///using wcout cout<< wc ;///using cout If you run the program you will get the output as, 2320 Unfortunately,the first output is blank,meaning wcout does not print anything ,the second output is 2320,which is a corresponding integer value of the character ‘ऐ’ in a Unicode system.Why does wcout gives blank output? When the compiler tries to print the character ‘ऐ’ it will take note of the integer value 2320 and will search for the character in the font use by the console.If the compiler finds the matching font of the value 2320 it will print it out on the screen but if it does not find any font that has the value 2320 or say the font used by the console does not support it then it prints nothing.Here,in our case the font used by the Console does not support Hindi alphabets so it cannot print the character.Hence we get the blank output. I am sure now you are thinking “So much for trusting wchar_t type to support Unicode system and it can’t print out the character..”.Well my friend you are not betrayed,wchar_t type does support Unicode system and it can print out any know languages script in the world but with little tweaking.What are the tweaks and how to get the console to print out any script? is not shown here ,we will discuss that in another post cause it is better to dedicate an entire post for this,the link is given below;in the meanwhile happy programming! Related Link ->Using wchar_t to print out Japanese,Chinese,Russian in Console. ->C++ String type and it’s differences with char type
https://corecplusplustutorial.com/cpp-wchar_t-wstring/
CC-MAIN-2017-30
refinedweb
944
67.79
ExtJs HMVC ExtJs HMVC). - Join Date - Mar 2007 - Location - Gainesville, FL - 37,743 - Vote Rating - 926 I would put this up on GitHub. People like me like to read code without downloading. mandro, do you think that your good solution, would be possible to integrate with "ext.ux.desktop", using "desktop" like the main aplication ?¿ Thanks this solution is under any license ? (sorry about my english) Manel @mandro Thank you for your sample application. It is good inspiration for improving the framework. A couple observations/questions: * It does not appear that your app/module controllers support nested controllers, which means only 2 tiers are supported - the main & the module. For example, panelA is supervised by controllerA. PanelA contains a button to launch a different view (e.g. a config window). The sub-view should be supervised by a sub-controller. The pattern could continue to an Nth level. How would you refactor your example to support a nested design in order to avoid bloat in the main controller? * When your app loads, new globals get added that correspond with each bundle. Seems like that approach could lead to namespace bloat & potential conflicts. Would it be better to keep all bundles isolated to the product namespace? For example, AM.Reverse, AM.Dashboard, and AM.Viewshed would be used instead. ExtJS4 HMVC ExtJS4 HMVC Previously I developed a sample application to use other pattern in my solutions. This solution only has 2 levels in depth, using MVC at level. Now, I recently work in new simplified and improved solution to use HMVC, using components with MVC pattern at any level. When I instanciate components, these create global namespaces, (I use the class Ext.ClassManager).But these meaning that you do not have 2 components with same name in a same level. New version. Sorry I could'nt submit these files at the github.
http://www.sencha.com/forum/showthread.php?180656-ExtJs-HMVC
CC-MAIN-2015-06
refinedweb
311
68.77
Creating a strong password that you can actually remember isn’t easy. Users who use unique passwords for different websites (which is ideal) are more likely to forget their passwords. So, it’s crucial to add a feature that allows your users to securely reset their password when they forget it. This article is about how you can build a secure reset password feature with Node.js and Express. First off, to follow along with this tutorial, here are some requirements to note: - You should have a basic understanding of Javascript and Node.js - You have NodeJS installed or you can download and install the latest version of Node.js - You have MongoDB database installed or can download and install MongoDB database. Another option is to create an account on the MongoDB website and set up a free database Now, let’s get started. Creating a workflow for your password reset The workflow for your reset password can take different shapes and sizes, depending on how usable and secure you want your application to be. In this article, we’ll implement a standard secured reset password design. The diagram below shows how the workflow for the feature will work. - Request password reset if the user exists - Validate user information - Provide identification information - Reset password or reject password verification request Building a project for password reset Let’s create a simple project to demonstrate how the password reset feature can be implemented. Note that you can find the completed project on password reset with Node.js on GitHub, or you can also jump to the password reset section of this tutorial. Let’s first initialize our project with the npm package manager. Run npm init on your Terminal/Command Prompt and follow the instructions to set up the project. Folder structure and files within your project Our folder structure will look like this: - Controllers auth.controller.js - Services auth.service.js - Models user.model.js token.model.js - Routes index.route.js - Utils - template requestResetPassword.handlebars resetPassword.handlebars sendEmail.js index.js db.js package.json Dependencies for setting up your project with password reset Run the code below to install the dependencies we’ll use in this project with npm. npm install bcrypt, cors, dotenv, express, express-async-errors, handlebars, jsonwebtoken, mongoose, nodemailer, nodemon We’ll use: bcryptto hash passwords and reset tokens corsto disable Cross-origin Resource Sharing at least for development purposes dotenvto allow our node process to have access to the environment variables express-async-errorsto catch all async errors so our entire codebase doesn’t get littered with try-catch handlebarsas a templating engine to send HTML emails mongooseto as a driver to interface with MongoDB database nodemailerto send emails nodemonto restart the server when a file changes Setting up environment variables Some variables will vary in our application depending on the environment we are running our application in. For these variables, we’ll add them to our environment variables. Create an .env file in your root directory and paste the following variables inside. We’re adding a bcrypt salt, our database url, a JWT_SECRET and a client url. You’ll see how we’ll use them as we proceed. BCRYPT_SALT=10 DB_URL=mongodb://127.0.0.1:27017/testDB JWT_SECRET=mfefkuhio3k2rjkofn2mbikbkwjhnkj CLIENT_URL=localhost://8090 Connecting to the MongoDB database Let’s create a connection to our MongoDB. This code should be in your db.js file in the root directory. db.js const mongoose = require("mongoose"); let DB_URL = process.env.DB_URL;// here we are using the MongoDB Url we defined in our ENV file module.exports = async function connection() { try { await mongoose.connect( DB_URL, { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false, useCreateIndex: true, autoIndex: true, }, (error) => { if (error) return new Error("Failed to connect to database"); console.log("connected"); } ); } catch (error) { console.log(error); } }; Setting up the Express app Let’s build our application entry point and serve it at port 8080. Copy and paste this into your index.js file in the root directory. require("express-async-errors"); require("dotenv").config(); const express = require("express"); const app = express(); const connection = require("./db"); const cors = require("cors"); const port = 8080; (async function db() { await connection(); })(); app.use(cors()); app.use(express.json()); app.use("/api/v1", require("./routes/index.route")); app.use((error, req, res, next) => { res.status(500).json({ error: error.message }); }); app.listen(port, () => { console.log("Listening to Port ", port); }); module.exports = app; Setting up token and user models We’ll need to create a User and Token model to set up our password reset system. 1. Token model Our token model will have an expiry time of about 1 hour. Within this period, the user is expected to complete the password reset process, otherwise the token will be deleted from the database. With MongoDB, you don’t have to write additional code to make this work. Just set expires in your date field, like so: createdAt: { type: Date, default: Date.now, expires: 3600,// this is the expiry time }, Here is what our model will look like. You should add this code to the file token.model.js inside the model directory. models/token.model.js const mongoose = require("mongoose"); const Schema = mongoose.Schema; const tokenSchema = new Schema({ userId: { type: Schema.Types.ObjectId, required: true, ref: "user", }, token: { type: String, required: true, }, createdAt: { type: Date, default: Date.now, expires: 3600,// this is the expiry time in seconds }, }); module.exports = mongoose.model("Token", tokenSchema); 2. User model The user model will describe how the user data will be saved. And, of course, before discuss creating a secure reset password mechanism, we need to ensure we are creating and storing a secure password in the first place. Keep in mind that storing passwords in plain text is bad practice and should never be done. Instead, use a secure and strong one-way algorithm to hash and store passwords, preferably one with a salt. In our case, we’ll be using bcrypt, as shown in the code below. We’ll use bcrypt to hash passwords so that even we as administrators wouldn’t know the passwords — you shouldn’t know your user’s passwords, and it will be almost impossible to figure out the reverse in case the database is hijacked. const mongoose = require("mongoose"); const bcrypt = require("bcrypt"); const Schema = mongoose.Schema; const bcryptSalt = process.env.BCRYPT_SALT; const userSchema = new Schema( { name: { type: String, trim: true, required: true, unique: true, }, email: { type: String, trim: true, unique: true, required: true, }, password: { type: String }, }, { timestamps: true, } ); userSchema.pre("save", async function (next) { if (!this.isModified("password")) { return next(); } const hash = await bcrypt.hash(this.password, Number(bcryptSalt)); this.password = hash; next(); }); module.exports = mongoose.model("user", userSchema); Before the password is saved, we use the pre-save MongoDB hook to hash the password first in this part of the code. We are using a salt of 10, as shown in our .env file, because this is strong enough to reduce the possibility of bad guys guessing users’ passwords. userSchema.pre("save", async function (next) { if (!this.isModified("password")) { return next(); } const hash = await bcrypt.hash(this.password, Number(bcryptSalt)); this.password = hash; next(); }); Create services for the password reset process We’ll have three services to completely start and process our password reset process. 1. Sign-up service Of course, we can’t reset a user’s password if they don’t have an account. So, this service will create an account for a new user. The code below should be in the service/auth.service.js file: const JWT = require("jsonwebtoken"); const User = require("../models/User.model"); const Token = require("../models/Token.model"); const sendEmail = require("../utils/email/sendEmail"); const crypto = require("crypto"); const bcrypt = require("bcrypt"); const signup = async (data) => { let user = await User.findOne({ email: data.email }); if (user) { throw new Error("Email already exist"); } user = new User(data); const token = JWT.sign({ id: user._id }, JWTSecret); await user.save(); return (data = { userId: user._id, email: user.email, name: user.name, token: token, }); }; 2. Password reset request service Following our workflow, the first step is to request a password reset token, right? So, let’s start there. In the code below, we check if the user exists. If the user exists, then we check if there is an existing token that has been created for this user. If one exists, we delete the token. const user = await User.findOne({ email }); if (!user) { throw new Error("User does not exist"); } let token = await Token.findOne({ userId: user._id }); if (token) { await token.deleteOne() }; Now, pay attention to this part: we are going to create a new random token using the Node.js crypto API. This is the token we’ll send to the user: let resetToken = crypto.randomBytes(32).toString("hex"); Now, create a hash of this token, which we’ll save in the database because saving plain resetToken in our database is the same as saving passwords in plain text, and that will defeat the entire purpose of setting up a secure password reset. However, we’ll send the plain token to the users’ email as shown in the code below, and then in the next section, we’ll verify the token and allow them to create a new password. service/auth.service.js const JWT = require("jsonwebtoken"); const User = require("../models/User.model"); const Token = require("../models/Token.model"); const sendEmail = require("../utils/email/sendEmail"); const crypto = require("crypto"); const bcrypt = require("bcrypt"); const requestPasswordReset = async (email) => { const user = await User.findOne({ email }); if (!user) throw new Error("User does not exist"); let token = await Token.findOne({ userId: user._id }); if (token) await token.deleteOne(); let resetToken = crypto.randomBytes(32).toString("hex"); const hash = await bcrypt.hash(resetToken, Number(bcryptSalt)); await new Token({ userId: user._id, token: hash, createdAt: Date.now(), }).save(); const link = `${clientURL}/passwordReset?token=${resetToken}&id=${user._id}`; sendEmail(user.email,"Password Reset Request",{name: user.name,link: link,},"./template/requestResetPassword.handlebars"); return link; }; The reset password link contains the token and the user ID, both of which will be used to verify the user’s identity before they can reset their password. It also contains the client url. The root domain the user will have to click to continue the reset process. const link = `${clientURL}/passwordReset?token=${resetToken}&id=${user._id}`; You can find the function sendEmail in the GitHub repository here and the email template here. We are using nodemailer and handlebars templating engine to send the email. 1. Reset password service Oh, look! I received an email to confirm I made the password reset request. Now I’m going to click on the link next. Once you click on the link, it should take you to the password reset page. You can build that frontend with any technology you desire, as this is just an API. At this point, we’ll send back the token, a new password, and a user id to verify the user and create a new password afterward. Here’s what we’ll be sending back to the reset password API will look like: { "token":"4f546b55258a10288c7e28650fbebcc51d1252b2a69823f8cd1c65144c69664e", "userId":"600205cc5fdfce952e9813d8", "password":"kjgjgkflgk.hlkhol" } It will be processed by the code below. service/auth.service.js const resetPassword = async (userId, token, password) => { let passwordResetToken = await Token.findOne({ userId }); if (!passwordResetToken) { throw new Error("Invalid or expired password reset token"); } const isValid = await bcrypt.compare(token, passwordResetToken.token); if (!isValid) { throw new Error("Invalid or expired password reset token"); } const hash = await bcrypt.hash(password, Number(bcryptSalt)); await User.updateOne( { _id: userId }, { $set: { password: hash } }, { new: true } ); const user = await User.findById({ _id: userId }); sendEmail( user.email, "Password Reset Successfully", { name: user.name, }, "./template/resetPassword.handlebars" ); await passwordResetToken.deleteOne(); return true; }; Notice how we are using bcrypt to compare the token the server received with the hashed version in the database? const isValid = await bcrypt.compare(token, passwordResetToken.token); If they are the same, then we go ahead to hash the new password… const hash = await bcrypt.hash(password, Number(bcryptSalt)); …and update the user’s account with the new password. await User.updateOne( { _id: userId }, { $set: { password: hash } }, { new: true } ); Just so we are keeping the user informed with every step, we’ll send them an email to confirm the change in password and delete the token from the database. So far, we’ve been able to create the services to sign up a new user and to reset their password. Bravo. Controllers for password reset services Here are the controllers for each of those services. The controllers collect data from the user, send them to the services to process the data, and then return the result back to the user. controllers/auth.controller.js const { signup, requestPasswordReset, resetPassword, } = require("../services/auth.service"); const signUpController = async (req, res, next) => { const signupService = await signup(req.body); return res.json(signupService); }; const resetPasswordRequestController = async (req, res, next) => { const requestPasswordResetService = await requestPasswordReset( req.body.email ); return res.json(requestPasswordResetService); }; const resetPasswordController = async (req, res, next) => { const resetPasswordService = await resetPassword( req.body.userId, req.body.token, req.body.password ); return res.json(resetPasswordService); }; module.exports = { signUpController, resetPasswordRequestController, resetPasswordController, }; Congratulations, you’ve created a secure reset password feature for your users. What can you do next? Here are a few things you could do to make this password reset feature more secure. - You could ask users to provide answers to their security questions (they must have created these questions and answers already). - Use secure hosting services. An insecure hosting service can create a backdoor for you as administrator. If your hosting service isn’t getting it right, the bad guys can compromise your own system even if your system seems to be safe. - Implement Two-Factor Authentication (2FA) with Google Authenticator or SMS. This way, even if the user’s email has been compromised, the hacker will also need to have the user’s phone. - Don’t store users’ passwords at all. It’s stressful having to reset your password each time you forget it. Instead, you could allow your users to log in with already existing services like Facebook, Github, GMail, and the like. That way, they won’t need to remember their password ever again. They will only need to worry about their passwords on those third-party websites. If you want to play around with the completed project, you can check it out on GitHub. Conclusion Digital security isn’t a joke. Hackers are always on the lookout for new ways to hack systems, so you should always be on the lookout for new ways to make life difficult for them. Your users trust you to secure their data and you don’t want to disappoint them. What other ways would you recommend to make a password reset feature more secure?. 7 Replies to “Implementing a secure password reset in Node.js” Thank you so much!!! Simple explanation without any unnecessary stuff. Special thanks for explaining crucial parts of the code! Eze, You have put together a clean guide. Thank you for sharing this. By the way, you used anonymous functions in a few places making it a bit tough to resolve issues using my call stack. Could use your help if you can make the time. Thank you! This is a great tutorial, helped me a lot Thanks great article, thanks! I have implemented a middleware with all authentication flows, would be glad to get comments, ideas and so: A well written article. I’ll be using this, thank you! What verb would you use to request the reset email? Would it be POST since we’re creating a new token and doing so is neither safe nor idempotent? Thank you, great article!
https://blog.logrocket.com/implementing-a-secure-password-reset-in-node-js/
CC-MAIN-2022-05
refinedweb
2,615
59.3
Functionality overview This article covers the following topics: - Introduction to IBM® Rational® Service Tester for SOA Quality - Key features of Rational Service Tester - Creating an automated test script - Creating a schedule - Creating a data pool - Creating a configuration protocol for IBM® WebSphere® MQ - Adding custom code - Types of verification points - Optional elements - Executing a script - Analyze logs Introduction to Rational Service Tester Rational Service Tester is an automated Web services testing and SOA testing tool. It is a functional and regression testing tool that enables relatively code-free testing of non-GUI Web services. It also provides a single client to interact with any service-oriented architecture (SOA) service type. It supports both Linux® and Microsoft® Windows® operating systems. Key features of Rational Service Tester Rational Service Tester: - Supports Web services standards including SOAP (Simple Object Access Protocol), HTTP and HTTPS (Hypertext Transfer Protocol Secure), JMS (Java™ Message Service), WS-Security (Web Services security), and UDDI (Universal Description, Discovery and Integration) - Simplifies how you create, understand, modify, and execute Web services testing - Supports the use of XML calls and SOAP over WebSphere MQ - Supports custom security APIs to ensure message integrity - Generates customized reports - Provides testers with automated script-free testing capabilities for functional testing, regression testing, and performance testing of non-GUI Web services. - Offers many options for validating Web service responses - Provides a visual test editor that delivers both high-level and detailed test views Creating an automated test script To create a new automated script, you first need to create a Web Service project. - Select File > New > Others > Test > Service Test Project, as shown in Figure 1. Click Next. Figure 1. Creating a Service Test project - After you create the Web service project, select File > New > Others > Test > Web Service Test. The following series of screen captures illustrate the steps to create a complete test. - Select the project folder in which you want to create the testsuite, in below figure All_IMG has been selected and then provide a Test file name. By default it shows the name as New Service Test.testsuite, here we'll provide it as New Serive Test.testsuite, as shown in Figure 2. Click Next. Figure 2. Provide the name of the test - Next, select the type of call that you want to create (in this example, XML call), as shown in Figure 3. Click Next. Figure 3. Select the type of service call - Choose the WebSphere MQ protocol radio button. Select Default MQ Protocol from the Protocol configuration drop-down list, as shown in Figure 4. Click Next. Figure 4. Protocol selection While creating the Web Service test, you need to configure the protocol for the test script. You can also use the existing protocol settings. In MQs, you have a dedicated WebSphere MQ listener process that monitors the request queue for incoming messages and then routes them through to the target Web Service. To configure MQs, you need to provide information like the Queue Manager name, Queue name, and IP address (the IP address is localhost in this case, because you are using port forwarding). - Click Finish and add the XML message in the source under the Message tab, as shown in Figure 5. - Update node name automatically updates the name of the response message automatically, uncheck it in case you want to provide user specific names to the request and response XML messages. Figure 5. Adding XML message - When you click the Update Return button, it sends the XML request on to the Queue mentioned in the protocol configuration. When you get a response, you are prompted to choose the display content format. You can choose either XML Content or Text Content. Select either of the formats and click OK, as shown in Figure 6. Figure 6. Update Return and select view format - Figure 7 shows the response message in XML format. This is the actual content returned by the service. There are 3 different views: - Form - Tree - Source Figure 7. Adding response message in the test - To add the response to your Web service test, click Update Test. After the response is added into your test, you can add verification points to it. Creating a schedule A schedule specifies which tests to run and in which sequence. In this example, you create a schedule that loops your test five times, using the first five values in your datapool. Follow these steps to create your schedule: - Select File > New > Performance Schedule. - In the Performance Schedule dialog, click your Web Service Tests project to select it as the parent folder. - In the Name field of the Performance Schedule dialog, enter the name: Web Service Test Schedule. - Click Finish to create the schedule. You will see the beginnings of your schedule, as shown in Figure 8. - On your schedule in the Schedule Contents section, right-click the <User Group 1> (100%) branch (in this case, Abhishek), and select Add > Loop or Add > Test. - In the Schedule Element Details section, enter Number of iterations. - On your schedule if you want to add Test under the loop, create a loop as described in above step and right-click the Loop (n iterations) branch, and select Add > Test. Figure 8. Schedule Creating a datapool Rational Service Tester automatically parameterizes generated tests so that the same Web service call can be validated with multiple sets of test data. Additional data is stored in a spreadsheet-style table. This ensures maximum code coverage without having to modify any test code. A datapool like that shown in Figure 9 is nothing but a table that contains the data that you need to substitute in your XML message. Datapools provide tests with variable data during a run. Figure 9. Datapool overview These are the steps that you follow to create a datapool: - Select the test suite. - Click New and then select Datapool. - Define the name and location of the datapool. - Define the description of the datapool (that is, the number of records and number of variables). - References are used to pass on information from a field to variable. A Reference is used to pass the data from the XML message to a variable being used in your custom code. Substitutions are used to replace the values of different elements of XML with each iteration. You can substitute a value either from the custom code (on success it is highlighted in pale yellow) or from the datapool (on success it is highlighted in dark green, as shown in Figure 10). Figure 10. Substitution from datapool and code Creating a configuration protocol for IBM WebSphere MQ - Choose Protocol and set the corresponding configuration options. - Select the type of protocol to be used (either HTTP, JMS, or WebSphere MQ). - In this case the protocol used is WebSphere MQ as shown in Figure 11. - For Protocol Configuration, click New and provide the necessary information such as Queue Manager Name, Queue Name, Queue Manager Address, port and Client Channel - Click OK and press Next. - The information used to create this Protocol is available from IBM WebSphere MQ. Figure 11. Protocol Config Setting Adding custom code The custom code implements the ICustomCode2 interface for the creation of the custom code and the ITestExecutionServices interface to add custom messages and custom verification points in the test logs. Verification points are reflected in the overall schedule verdict. The ICustomCode2 interface requires an implementation of the exec method. This is the method which is called to execute the user Java class. The ITestExecutionServices interface provides a mechanism by which the user Java test code can gain access to support services (such as verification points, custom messages, verdicts, and so on). Properties of custom code - Custom code. Code listing Listing 1 Custom code shows how to pass parameters to your code for eg. in the sample code 2 command line arguments are passed MessageVRM and ListId. It also shows DB2 connectivity and execution of SQL queries. A string variable contains the complete SQL query which needs to be executed. Class CustomDB2Connection contains all the methods required to connect to the database and execute SQL queries. In the sample code we create a object of CustomDB2Connection class (db2c) and use connect () to connect to the database then query(QUERY) is used to execute the SQL query which is passed as an String argument to the method. query is the method name and QUERY is the string argument passed into it. Result of SQL query is store in a String variable numberOfRecords. Listing 1. Sample code for DB2 connectivity package test; import java.sql.ResultSet; import org.eclipse.hyades.test.common.event.VerdictEvent; import com.ibm.rational.test.lt.kernel.services.ITestExecutionServices; public class VEH003_010_preEvidence implements com.ibm.rational.test.lt.kernel.custom.ICustomCode2 { public VEH003_010_preEvidence() { } /** * For javadoc of ICustomCode2 and ITestExecutionServices interfaces, select 'Help Contents' in the * Help menu and select 'Extending Rational Performance Tester functionality' -> 'Extending test execution with custom code' BY Abhishek*/ public String exec(ITestExecutionServices tes, String[] args) { String MessageVRM = args[0]; String ListId=args[1]; String numberOfRecords=null; String QUERY = "SELECT COUNT(*) FROM LRUCCORE.vehiclelistentry WHERE VRM='"+MessageVRM+"' and vehiclelistid="+ListId+" and Effectivetodatetime='2999-12-31 00:00:00.00000'"; tes.getTestLogManager().reportMessage(QUERY); CustomDB2Connection db2c = new CustomDB2Connection ("IPAddress", "port no", "database", "userID", "Password"); ResultSet results; try { db2c.connect(); results = db2c.query(QUERY); // goto the last row (if more than one) results.last(); numberOfRecords = results.getString(1); Optional elements There is a set of optional elements that you can use in a test to enhance its functionality: - You can use service call elements in tests to send a request to the service, which is an XML message. - In the test editor, return message elements are located after the service call. It displays the content returned by the service. - You can automatically generate or update the contents of a message return by clicking Update Return in the call element. - A conditional block issues portions of a test depending on the value of a reference. The reference must exist in the test and precede the conditional block. - You can define part of a test or schedule as a loop that runs a specified number of times. Loops can be time based, count based, or infinite. - You have not implemented transactions in a TFL project, because transactions are basically used to test the performance of a specific group of test elements. When you view the test results, you can view performance data about any transactions that you have added. Types of verification points - Equal verification point enables you to check that the contents returned by a service exactly match the contents specified in the verification point - Contain verification point checks that part of the contents that are returned by a service matches the contents specified in the verification point. It passes even if the actual value is a substring of what is expected. - Attachment verification points enable you to verify that an expected attachment is delivered with the message return. This verification point is useful when you expect any attachment in response message. It enables you to check that the attachment of a Web service message return matches the specified criteria. This verification point returns a Passstatus when all of the criteria of an attachment match the expected criteria specified in the verification point test element. If any of the criteria do not match, the verification point returns a Failstatus. - With Query verification points, you can check that the number of nodes returned by an XML Path language query matches the expected number of nodes specified in the verification point. To add a verification point, right-click and select the type that you want, as shown in Figure 12. Figure 12. Add a verification point Executing a script At this point, you've created your test and you've scheduled it for execution. For the most part, your work is done. From here on in, Rational Service Tester will launch and execute the test and present you with the test results. Execute the test Executing the test is very simple. Just follow these steps to launch the test: - In the Test Navigator view, right-click the Web Service Test Schedule and select Run As > Performance Schedule. - The Launch Schedule dialog is displayed as Rational Tester prepares to run your test. Next, you will start to see live results from your test accumulate in the Web Service Test Schedule - Web Services Performance Report view. - Your test is complete when you see the status turn to green in the Overall tab of the view, as shown in Figure 13. Figure 13. Execution is complete Analyze Test Results: Functional You can analyze test results from a functional test or a performance test perspective. From a functional test perspective, the objective is to ensure that the Web service returned the proper results for a given set of inputs. The test log is your main means of ensuring that you received the correct results. The test log gives you detailed information about every message sent and received between Rational Service Tester and the Web service. To analyze your results: - In the Performance Test Runs view, right-click the Web Service Test Schedule [Time Stamp Information] and select Display Test Log. - The test log includes two tabs: Overview and Events. The log opens to the Overview page, where you will see the pass or fail verdict and the timing information for the test. Your log should look something like that shown in Figure 14. Figure 14. Logs - Click the Events tab to see more detailed information. - Expand the Events tree so that it looks like that shown in Figure 15. Figure 15. Expanded test log events What you have learned In this article, you learned about the key features of IBM® Rational®Service Tester. Then we saw how to use Rational Service Tester for SOA Quality to create an automated test script using IBM® WebSphere® MQ (message queuing) as a protocol for communication and datapool which can be used to test a functionality with variaton of data without changing automated test script. This article also includes the use of custom code in automated script and demonstrate a piece of it with an explaination. It also includes various verification points and optional elements which can be used to enhance scope of your automated script and execution of a indiviual script or schedule. At the later part of the article we learn how to analyse the logs. Resources Learn - Find out more about IBM Rational Service Tester for SOA Quality: - Browse the Rational Service Tester developerWorks page for links to technical articles and many related resources. The developerWorks Rational software landing page is also a good starting place. - Get the free trial download for Rational Service Tester - IBM Rational software. - Download these IBM product evaluation versions and get your hands on application development tools and middleware products from DB2®, Lotus®, Tivoli®, and WebSphere®. -.
http://www.ibm.com/developerworks/rational/library/10/testingsoaservicesusingrationalservicetesterforsoaquality/index.html
CC-MAIN-2014-52
refinedweb
2,476
52.49
MDC - Stack Logback has a very nice feature called Mapped Diagnostic Context (MDC in short). According to the manual what it does is: "It lets the developer place information in a diagnostic context that can be subsequently retrieved by certain logback components" This is very useful for adding additional information to your logs without the overhead of formating. For example (also from the manual): MDC.put("first", "Dorothy"); Logger logger = LoggerFactory.getLogger(SimpleMDC.class); MDC.put("last", "Parker"); logger.info("Check enclosed."); What this did was add attributes to the log that include the first and last name. In the logger you can then specify how these attributes will be used: <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender"> <layout> <Pattern>**%X{first} %X{last}** - %m%n</Pattern> </layout> </appender> The issue The MDC class is a static class that sits on the local thread so you can call from any place in your code to the class. Since this is a static class, you must remember after you send your log to remove the attribute with the remove method. No starts the read issue. What happens if you do not remove the attributes that you added? What will happen is that your thread will be reused and the next log that is sent will have the leftover tag on it. So how do you make sure that you remove all tags? Another issue how do you solve the nested issue. If I have a method that calls another method, and both set attributes what will happen? Well it depends on what you did. If the inner method just adds but did not remove then you will have the extra attribute. On the other hand if the inner methods updates the same attribute then you are stuck with the new value and not yours. Solution The solution to the problem is to save the stacks state per method call. To do this I have created a utility MDCStack that saves on the local thread a list of all attributes and values. Every time you want to call a inner methods you need to call push on the stack, and when you leave the method you call pop. With these methods we will solve all the issues we raised above. You do not need to remember all attributes that you added, you just need to call pop at the end. In addition if you are nesting methods by calling the pop, the stack will return the MDC state back to the same state that was before the call including returning original values. Code public class MDCStack { static public class MDCData { String key; Object value; public MDCData(String key, Object value) { this.key = key; this.value = value; } } static ThreadLocal<Stack<List<MDCData>>> keys = new ThreadLocal<Stack<List<MDCData>>>(){ @Override protected Stack<List<MDCData>> initialValue() { final Stack stack = new Stack(); stack.add(new ArrayList<>()); return stack; } }; static protected void rebuild(){ final Stack<List<MDCData>> lists = keys.get(); lists.forEach(mdcDatas -> { mdcDatas.forEach(mdcData -> MDC.put(mdcData.key,mdcData.value)); }); } static public void push(){ final Stack<List<MDCData>> lists = keys.get(); lists.add(new ArrayList<>()); } static public void pop(){ final Stack<List<MDCData>> lists = keys.get(); if (lists.size()>0) { final List<MDCData> poll = lists.pop(); poll.forEach(d -> MDC.remove(d.key)); rebuild(); } if (lists.size()==0){ lists.add(new ArrayList<>()); } } static public void put(String key, Object value){ final Stack<List<MDCData>> lists = keys.get(); final List<MDCData> peek = lists.peek(); peek.add(new MDCData(key,value)); MDC.put(key,value); } static public void remove(String key){ final Stack<List<MDCData>> lists = keys.get() final List<MDCData> peek = lists.peek(); peek.stream() .filter(mdcData -> mdcData.key.equals(key)) .findFirst() .ifPresent(mdcData -> peek.remove(mdcData)); MDC.remove(key); } static public void clear(){ MDC.clear(); final Stack<List<MDCData>> lists = keys.get(); lists.clear(); lists.add(new ArrayList<>()); } } All code can be found at:
http://www.tikalk.com/java/mdc-stack/
CC-MAIN-2017-17
refinedweb
651
57.87
JAVA Developer's Guide Chapter 14 Useful Tools in the java.util Package CONTENTS - The Date Class - The Random Class - The Enumeration Interface - The Vector Class - The Stack Class - The BitSet Class - The Dictionary, Hashtable, and Properties Classes - The StringTokenizer Class - Observer and Observable - Summary In this chapter you'll learn how to work with all the useful utility classes contained in the java.util package. You'll learn to use the Date class to manipulate Date objects, to generate random numbers using the Random class, and to work with data structures such as dictionaries, stacks, hash tables, vectors, and bit sets. When you finish this chapter you'll be able to make productive use of these utility classes in your own programs. The Date Class The Date class encapsulates date and time information and allows Date objects to be accessed in a system-independent manner. Date provides methods for accessing specific date and time measurements, such as year, month, day, date, hours, minutes, and seconds, and for displaying dates in a variety of standard formats. The Date class provides six constructors for creating Date objects. The default constructor creates a Date object with the current system date and time. Other constructors allow Date objects to be set to other dates and times. The access methods defined by the Date class support comparisons between dates and provide access to specific date information, including the time zone offset. If you intend to process date-related information in a program, you should consult the API page for the Date class to obtain a full list of the available Date methods. DateApp The DateApp program illustrates the use of the Date class. It shows how Date objects are created and manipulated using the methods provided by the class. (See Listing 14.1.) Listing 14.1. The source code of the DateApp program. import java.lang.System; import java.util.Date; public class DateApp { public static void main(String args[]){ Date today = new Date(); String days[] = {"Sun","Mon","Tue","Wed","Thu","Fri","Sat"}; System.out.println("Today's date (locale conventions): "+ today.toLocaleString()); System.out.println("Today's date (Unix conventions): "+today.toString()); System.out.println("Today's date (GMT conventions): "+today.toGMTString()); System.out.println("Year: "+today.getYear()); System.out.println("Month: "+today.getMonth()); System.out.println("Date: "+today.getDate()); System.out.println("Day: "+days[today.getDay()]); System.out.println("Hour: "+today.getHours()); System.out.println("Minute: "+today.getMinutes()); System.out.println("Second: "+today.getSeconds()); Date newYears2000 = new Date(100,0,1); System.out.println("New Years Day 2000: "+newYears2000.toString()); System.out.println("New Years Day 2000 is "+days[newYears2000.getDay()]); } } The program creates a Date object using the default constructor and assigns it to the today variable. It then declares an array named days and initializes it to the three-letter abbreviations of the days of the week. The toLocaleString(), toString(), and toGMTString() methods are used to convert and print the date using the local operating system and standard UNIX and GMT conventions. The various get methods supported by the Date class are used to print out the year, month, date, day, hours, minutes, and seconds corresponding to the current date. A new Date object is constructed and assigned to the newYears2000 variable. The Date constructor takes the arguments 100, 0, and 1. They specify the 100th year after the year 1900, the 0th month (that is, January), and the first day of the month. The date specified is New Year's Day in the year 2000, as you probably guessed from the name of the variable in which it is stored. The newYears2000 date is printed followed by the actual day of the week corresponding to the date. The output of the DateApp program is as follows. When you run the program, you will obviously get a different date for the first part of the program's processing. The following are the results that were displayed when I ran the program: Today's date (locale conventions): 03/01/96 09:53:46 Today's date (Unix conventions): Fri Mar 01 09:53:46 1996 Today's date (GMT conventions): 1 Mar 1996 17:53:46 GMT Year: 96 Month: 2 Date: 1 Day: Fri Hour: 9 Minute: 53 Second: 46 New Years Day 2000: Sat Jan 01 00:00:00 2000 New Years Day 2000 is Sat The Random Class The Random class provides a template for the creation of random number generators. It differs from the random() method of the java.lang.Math class in that it allows any number of random number generators to be created as separate objects. The Math.random() method provides a static function for the generation of random double values. This static method is shared by all program code. Objects of the Random class generate random numbers using a linear congruential formula. Two constructors are provided for creating Random objects. The default constructor initializes the seed of the random number generator using the current system time. The other constructor allows the seed to be set to an initial long value. The Java API page says the random number generator uses a 48-bit seed, but the constructor allows only a 32-bit value to be passed as a seed. In any case, the random number generators that are created as objects of this class should be sufficient for most random number generation needs. The Random class provides six access methods, five of which are used to generate random values. The nextInt(), nextLong(), nextFloat(), and nextDouble() methods generate values for the numeric data types. The values generated by nextFloat() and nextDouble() are between 0.0 and 1.0. The nextGaussian() method generates a Gaussian distribution of double values with mean 0.0 and standard deviation 1.0. The setSeed() method is used to reset the seed of the random number generator. RandomApp The RandomApp program demonstrates the use of the Random class. (See Listing 14.2.) It creates an object of class Random using the default constructor and assigns it to r. This causes the random number generator to be seeded using the current system time. Three for loops are used to print random int, double, and Gaussian distributed double values. Each loop prints four values. Listing 14.2. The source code of the RandomApp program. import java.lang.System; import java.util.Random; public class RandomApp { public static void main(String args[]){ Random r = new Random(); for(int i=0;i<4;++i) System.out.print(r.nextInt()+" "); System.out.println(); r = new Random(123456789); for(int i=0;i<4;++i) System.out.print(r.nextDouble()+" "); System.out.println(); r.setSeed(234567890); for(int i=0;i<4;++i) System.out.print(r.nextGaussian()+" "); System.out.println(); } } The output generated by the program when it was run on my computer produced the following results: 1799702397 -2014911382 618703884 -1181330064 0.664038 0.456952 0.390506 0.893341 0.113781 0.412296 -1.57262 0.0756829 It will produce different results when it is run on your computer because the first line that is printed uses the Random() constructor to generate the output data. The Enumeration Interface The Enumeration interface specifies two methods to be used to index through a set of objects or values: hasMoreElements() and nextElement(). The hasMoreElements() method enables you to determine whether more elements are contained in an Enumeration object. The nextElement() method returns the next element contained by an object. Enumeration-implementing objects are said to be consumed by their use. This means that the Enumeration objects cannot be restarted to reindex through the elements they contain. Their elements may be accessed only once. The Enumeration interface is implemented by the StringTokenizer class as discussed later in this chapter in the section "The StringTokenizer Class." It is also used to obtain a list of elements contained in a vector, as shown in the programming example in the next section. The Vector Class The Vector class provides the capability to implement a growable array. The array grows larger as more elements are added to it. The array may also be reduced in size, after some of its elements have been deleted. This is accomplished using the trimToSize() method. Vector operates by creating an initial storage capacity and then adding to this capacity as needed. It grows by an increment defined by the capacityIncrement variable. The initial storage capacity and capacityIncrement can be specified in Vector's constructor. A second constructor is used when you want to specify only the initial storage capacity. A third, default constructor specifies neither the initial capacity nor the capacityIncrement. This constructor lets Java figure out the best parameters to use for Vector objects. The access methods provided by the Vector class support array-like operations and operations related to the size of Vector objects. The array-like operations allow elements to be added, deleted, and inserted into vectors. They also allow tests to be performed on the contents of vectors and specific elements to be retrieved. The size-related operations allow the byte size and number of elements of the vector to be determined and the vector size to be increased to a certain capacity or trimmed to the minimum capacity needed. Consult the Vector API page for a complete description of these methods. VectorApp The VectorApp program illustrates the use of vectors and the Enumeration interface. (See Listing 14.3.) Listing 14.3. The source code of the VectorApp program. import java.lang.System; import java.util.Vector; import java.util.Enumeration; public class VectorApp { public static void main(String args[]){ Vector v = new Vector(); v.addElement("one"); v.addElement("two"); v.addElement("three"); v.insertElementAt("zero",0); v.insertElementAt("oops",3); v.insertElementAt("four",5); System.out.println("Size: "+v.size()); Enumeration enum = v.elements(); while (enum.hasMoreElements()) System.out.print(enum.nextElement()+" "); System.out.println(); v.removeElement("oops"); System.out.println("Size: "+v.size()); for(int i=0;i<v.size();++i) System.out.print(v.elementAt(i)+" "); System.out.println(); } } The program creates a Vector object using the default constructor and uses the addElement() method to add the strings, "one", "two", and "three" to the vector. It then uses the insertElementAt() method to insert the strings "zero", "oops", and "four" at locations 0, 3, and 5 within the vector. The size() method is used to retrieve the vector size for display to the console window. The elements() method of the Vector class is used to retrieve an enumeration of the elements that were added to the vector. A while loop is then used to cycle through and print the elements contained in the enumeration. The hasMoreElements() method is used to determine whether the enumeration contains more elements. If it does, the nextElement() method is used to retrieve the object for printing. The removeElement() of the Vector class is used to remove the vector element containing the string "oops". The new size of the vector is displayed and the elements of the vector are redisplayed. The for loop indexes each element in the vector using the elementAt() method. The output of the VectorApp program is as follows: Size: 6 zero one two oops three four Size: 5 zero one two three four The Stack Class The Stack class provides the capability to create and use stacks within your Java programs. Stacks are. The search() method allows you to search through a stack to see if a particular object is contained on the stack. The peek() method returns the top element of the stack without popping it off. The empty() method is used to determine whether a stack is empty. The pop() and peek() methods both throw the EmptyStackException if the stack is empty. Use of the empty() method can help to avoid the generation of this exception. StackApp The StackApp program demonstrates the operation of a stack. (See Listing 14.4.) It creates a Stack object and then uses the push() method to push the strings "one", "two", and "three" onto the stack. Because the stack operates in last-in-first-out fashion, the top of the stack is the string "three". This is verified by using the peek() method. The contents of the stack are then popped off and printed using a while loop. The empty() method is used to determine when the loop should terminate. The pop() method is used to pop objects off the top of the stack. Listing 14.4. The source code of the StackApp program. import java.lang.System; import java.util.Stack; public class StackApp { public static void main(String args[]){ Stack s = new Stack(); s.push("one"); s.push("two"); s.push("three"); System.out.println("Top of stack: "+s.peek()); while (!s.empty()) System.out.println(s.pop()); } } The output of the StackApp program is as follows: Size: 6 zero one two oops three four Size: 5 zero one two three four The BitSet Class The BitSet class is used to create objects that maintain a set of bits. The bits are maintained as a growable set. The capacity of the bit set is increased as needed. Bit sets are used to maintain a list of flags that indicate the state of each element of a set of conditions. Flags are boolean values that are used to represent the state of an object. Two BitSet constructors are provided. One allows the initial capacity of a BitSet object to be specified. The other is a default constructor that initializes a BitSet to a default size. The BitSet access methods provide and, or, and exclusive or logical operations on bit sets; enable specific bits to be set and cleared; and override general methods declared for the Object class. BitSetApp The BitSetApp program demonstrates the operation of bit sets. (See Listing 14.5.) Listing 14.5. The source code of the BitSetApp program. import java.lang.System; import java.util.BitSet; public class BitSetApp { public static void main(String args[]){ int size = 8; BitSet b1 = new BitSet(size); for(int i=0;i<size;++i) b1.set(i); BitSet b2 = (BitSet) b1.clone(); for(int i=0;i<size;i=i+2) b2.clear(i); System.out.print("b1: "); for(int i=0;i<size;++i) System.out.print(b1.get(i)+" "); System.out.print("\nb2: "); for(int i=0;i<size;++i) System.out.print(b2.get(i)+" "); System.out.println(); System.out.println("b1: "+b1); System.out.println("b2: "+b2); b1.xor(b2); System.out.println("b1 xor b2 = "+b1); b1.and(b2); System.out.println("b1 and b2 = "+b1); b1.or(b2); System.out.println("b1 or b2 = "+b1); } } The program begins by creating a BitSet object, b1, of size 8. It executes a for statement to index through b1 and set each bit in the bit set. It then uses the clone() method to create an identical copy of b1 and assign it to b2. Another for statement is executed to clear every even-numbered bit in b2. The values of the b1 and b2 bit sets are then printed. This results in the display of two lists of boolean values. The bit sets are printed as objects, resulting in a set- oriented display. Only the bits with true boolean values are identified as members of the displayed bit sets. The xor() method is used to compute the exclusive or of b1 and b2, updating b1 with the result. The new value of b1 is then displayed. The and() method is used to calculate the logical and of b1 and b2, again, updating b1 with the result and displaying b1's new value. Finally, the logical or of b1 and b2 is computed, using the or() method. The result is used to update b1, and b1's value is displayed. The output of BitSetApp is as follows: b1: true true true true true true true true b2: false true false true false true false true b1: {0, 1, 2, 3, 4, 5, 6, 7} b2: {1, 3, 5, 7} b1 xor b2 = {0, 2, 4, 6} b1 and b2 = {} b1 or b2 = {1, 3, 5, 7} The Dictionary, Hashtable, and Properties Classes The Dictionary, Hashtable, and Properties classes are three generations of classes that implement the capability to provide key-based data storage and retrieval. The Dictionary class is the abstract superclass of Hashtable, which is, in turn, the superclass of Properties. Dictionary Dictionary provides the abstract functions used to store and retrieve objects by key-value associations. The class allows any object to be used as a key or value. This provides great flexibility in the design of key-based storage and retrieval classes. Hashtable and Properties are two examples of these classes. The Dictionary class can be understood using its namesake abstraction. A real-world hardcopy dictionary maps words to their definition. The words can be considered the keys of the dictionary and the definitions as the values of the keys. Java dictionaries operate in the same fashion. One object is used as the key to access another object. This abstraction will become clearer as you investigate the Hashtable and Properties classes. The Dictionary class defines several methods that are inherited by its subclasses. The elements() method is used to return an Enumeration object containing the values of the key-value pairs stored within the dictionary. The keys() method returns an enumeration of the dictionary keys. The get() method is used to retrieve an object from the dictionary based on its key. The put() method puts a Value object in the dictionary and indexes it using a Key object. The isEmpty() method determines whether a dictionary contains any elements, and the size() method identifies the dictionary's size in terms of the number of elements it contains. The remove() method deletes a key-value pair from the dictionary based on the object's key. Hashtable The Hashtable class implements a hash table data structure. A hash table indexes and stores objects in a dictionary using hash codes as the objects' keys. Hash codes are integer values that identify objects. They are computed in such a manner that different objects are very likely to have different hash values and therefore different dictionary keys. The Object class implements the hashCode() method. This method allows the hash code of an arbitrary Java object to be calculated. All Java classes and objects inherit this method from Object. The hashCode() method is used to compute the hash code key for storing objects within a hash table. Object also implements the equals() method. This method is used to determine whether two objects with the same hash code are, in fact, equal. The Java Hashtable class is very similar to the Dictionary class from which it is derived. Objects are added to a hash table as key-value pairs. The object used as the key is hashed, using its hashCode() method, and the hash code is used as the actual key for the value object. When an object is to be retrieved from a hash table, using a key, the key's hash code is computed and used to find the object. The Hashtable class provides three constructors. The first constructor allows a hash table to be created with a specific initial capacity and load factor. The load factor is a float value between 0.0 and 1.0 that identifies the percentage of hash table usage that causes the hash table to be rehashed into a larger table. For example, suppose a hash table is created with a capacity of 100 entries and a 0.70 load factor. When the hash table is 70 percent full, a new, larger hash table will be created, and the current hash table entries will have their hash values recalculated for the larger table. The second Hashtable constructor just specifies the table's initial capacity and ignores the load factor. The default hash table constructor does not specify either hash table parameter. The access methods defined for the Hashtable class allow key-value pairs to be added to and removed from a hash table, search the hash table for a particular key or object value, create an enumeration of the table's keys and values, determine the size of the hash table, and recalculate the hash table, as needed. Many of these methods are inherited or overridden from the Dictionary class. HashApp The HashApp program illustrates the operation and use of hash tables. (See Listing 14.6.) Listing 14.6. The source code of the HashApp program. import java.lang.System; import java.util.Hashtable; import java.util.Enumeration; public class HashApp { public static void main(String args[]){ Hashtable h = new Hashtable(); h.put("height","6 feet"); h.put("weight","200 pounds"); h.put("eye color","blue"); h.put("hair color","brown"); System.out.println("h: "+h); Enumeration enum = h.keys(); System.out.print("keys: "); while (enum.hasMoreElements()) System.out.print(enum.nextElement()+", "); System.out.print("\nelements: "); enum = h.elements(); while (enum.hasMoreElements()) System.out.print(enum.nextElement()+", "); System.out.println(); System.out.println("height: "+h.get("height")); System.out.println("weight: "+h.get("weight")); System.out.println("eyes: "+h.get("eye color")); System.out.println("hair: "+h.get("hair color")); h.remove("weight"); System.out.println("h: "+h); } } The program begins by creating a Hashtable object using the default constructor. It then adds four key-value pairs to the hash table using the put() method. The hash table is then printed using the default print method for objects of class Hashtable. The keys() method is used to create an enumeration of the hash table's keys. These keys are then printed one at a time by indexing through the enumeration object. The elements() method is used to create an enumeration of the hash table's values. This enumeration is printed in the same way as the key enumeration. The values of the hash table are again displayed by using the get() method to get the values corresponding to specific key values. Finally, the remove() method is used to remove the key-value pair associated with the weight key and the hash table is reprinted using the default print convention. The program output is as follows: h: {height=6 feet, weight=200 pounds, eye color=blue, hair color=brown} keys: height, weight, eye color, hair color, elements: 6 feet, 200 pounds, blue, brown, height: 6 feet weight: 200 pounds eyes: blue hair: brown h: {height=6 feet, eye color=blue, hair color=brown} The Properties Class The Properties class is a subclass of Hashtable that can be read from or written to a stream. It also provides the capability to specify a set of default values to be used if a specified key is not found in the table. The default values themselves are specified as an object of class Properties. This allows an object of class Properties to have a default Properties object, which in turn has its own default properties, and so on. Properties supports two constructors: a default constructor with no parameters and a constructor that accepts the default properties to be associated with the Properties object being constructed. The Properties class declares several new access methods. The getProperty() method allows a property to be retrieved using a String object as a key. A second overloaded getProperty() method allows a value string to be used as the default in case the key is not contained in the Properties object. The load() and save() methods are used to load a Properties object from an input stream and save it to an output stream. The save() method allows an optional header comment to be saved at the beginning of the saved object's position in the output stream. The propertyNames() method provides an enumeration of all the property keys, and the list() method provides a convenient way to print a Properties object on a PrintStream object. PropApp The PropApp program illustrates the use of the Properties class by saving a subset of the system properties to a byte array stream and then loading the properties back in from the byte array stream. (See Listing 14.7.) Listing 14.7. The source code of the PropApp program. import java.lang.System; import java.util.Properties; import java.io.ByteArrayOutputStream; import java.io.ByteArrayInputStream; import java.io.IOException; public class PropApp { public static void main(String args[]) throws IOException { Properties sysProp = System.getProperties(); sysProp.list(System.out); sysProp.remove("java.home"); sysProp.remove("file.separator"); sysProp.remove("line.separator"); sysProp.remove("java.vendor"); sysProp.remove("user.name"); sysProp.remove("java.vendor.url"); sysProp.remove("user.dir"); sysProp.remove("java.class.path"); sysProp.remove("java.class.version"); sysProp.remove("path.separator"); sysProp.remove("user.home"); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); sysProp.save(outStream,"sysProp"); System.out.println("\noutputStream:\n"+outStream); ByteArrayInputStream inStream; inStream = new ByteArrayInputStream(outStream.toByteArray()); sysProp.load(inStream); sysProp.list(System.out); } } The program begins by using the getProperties() method of the System class to retrieve the system properties and assign them to the sysProp variable. The system properties are then listed on the console window using the list() method. Eleven of the properties contained by sysProp are removed using the remove() method. They were removed to cut down on the amount of program output and to illustrate the use of the remove() method. An object of class ByteArrayOutputStream is created and assigned to the outStream variable. The sysProp Properties object is then saved to the output stream using the save() method. The outStream is converted to a byte array using the toByteArray() method of the ByteArrayOutputStream class. The byte array is provided as an argument to a ByteArrayInputStream constructor, which uses it to create an object of its class and assign it to the inStream variable. The saved properties are reloaded from inStream and reassigned to the sysProp variable. The contents of the sysProp variable are then relisted to show that they were correctly loaded. The program output is as follows: -- listing properties -- java.home=C:\JAVA\BIN\.. awt.toolkit=sun.awt.win32.MToolkit java.version=1.0 file.separator=\ line.separator= java.vendor=Sun Microsystems Inc. user.name=jaworskij os.arch=x86 os.name=Windows 95 java.vendor.url= user.dir=c:\java\jdg\ch14 java.class.path=.;c:\java;c:\java\lib;;C:\JAVA\BIN\..... java.class.version=45.3 os.version=4.0 path.separator=; user.home=\home\jamie outputStream: #sysProp #Fri Mar 01 09:59:00 1996 awt.toolkit=sun.awt.win32.MToolkit java.version=1.0 os.arch=x86 os.name=Windows 95 os.version=4.0 -- listing properties -- awt.toolkit=sun.awt.win32.MToolkit java.version=1.0 os.arch=x86 os.name=Windows 95 os.version=4.0 The StringTokenizer Class The StringTokenizer class is used to create a parser for String objects. It parses strings according to a set of delimiter characters. It implements the Enumeration interface in order to provide access to the tokens contained within a string. The StringTokenizer class is similar to the StreamTokenizer class covered in Chapter 13, "Stream-Based Input/Output and the java.io Package." StringTokenizer provides three constructors. All three have the input string as a parameter. The first constructor includes two other parameters: a set of delimiters to be using in the string parsing and a boolean value used to specify whether the delimiter characters should be returned as tokens. The second constructor accepts the delimiter string but not the return token's toggle. The last constructor uses the default delimiter set consisting of the space, tab, newline, and carriage-return characters. The access methods provided by StringTokenizer include the Enumeration methods, hasMoreElements() and nextElement(), hasMoreTokens() and nextToken(), and countTokens(). The countTokens() method returns the number of tokens in the string being parsed. TokenApp The TokenApp program prompts the user to enter a line of keyboard input and then parses the line, identifying the number and value of the tokens that it found. (See Listing 14.8.) Listing 14.8. The source code of the TokenApp program. import java.lang.System; import java.util.StringTokenizer; import java.io.DataInputStream; import java.io.IOException; public class TokenApp { public static void main(String args[]) throws IOException { DataInputStream keyboardInput = new DataInputStream(System.in); int numTokens; do { System.out.print("=> "); System.out.flush(); StringTokenizer st = new StringTokenizer(keyboardInput.readLine()); numTokens = st.countTokens(); System.out.println(numTokens+" tokens"); while (st.hasMoreTokens()) System.out.println(" "+st.nextToken()); } while(numTokens!=0); } } The program begins by creating a DataInputStream object using the System.in stream as an argument to its constructor. A do loop is used to read a line of input from the user, construct a StringTokenizer object on the input line, display the number of tokens in the line, and display each token as parsed using the standard delimiter set. The loop continues until a line with no tokens is entered. The program's output is as follows: => this is a test 4 tokens this is a test => 1 2 3 4.5 6 5 tokens 1 2 3 4.5 6 => @ # $ % ^ 5 tokens @ # $ % ^ => 0 tokens Observer and Observable The Observer interface and Observable class are used to implement an abstract system by which observable objects can be observed by objects that implement the Observer interface. Observable objects are objects that subclass the abstract Observable class. These objects maintain a list of observers. When an observable object is updated, it invokes the update() method of its observers to notify the observers that it has changed state. The update() method is the only method that is specified in the Observer interface. Theupdate() method is used to notify an observer that an observable has changed. The method takes the observable object and a second notification message Object as its parameters. Observable The Observable class is an abstract class that must be subclassed by observable objects. It provides several methods for adding, deleting, and notifying observers and for manipulating change status. These methods are described in the class's API page. Summary In this chapter you have learned how to work with all the useful utility classes contained in the java.util package. You have learned to use the Date class to manipulate Date objects and the Random number class to generate random numbers, and how to work with a range of data structures, including dictionaries, stacks, hash tables, vectors, and bit sets. In Chapter 15, "Window Programming with the java.awt Package," you'll preview the Java Abstract Windows Toolkit (AWT) and learn what window components are available to develop window-based programs using Java.
http://www.webbasedprogramming.com/JAVA-Developers-Guide/ch14.htm
CC-MAIN-2016-40
refinedweb
5,082
56.86
jGuru Forums Posted By: Stephen_Montgomery Posted On: Thursday, February 10, 2005 03:36 PM Hi - I have been going through quite a few web examples and haven't quite pieced together the right picture yet. 1) If I have an ActionForm for a JSP, how does the JSP know about it. I don't see where anything is defined when I call html:form. I'm guessing that the form submit action looks up in the struts config file what the corresponding ActionForm name is and loads that into scope. Cool. 2) However, now how do you access other beans within this form. I would like to create some dynamic radio buttons so I created ANOTHER action form, defined it in in the struts-config file and low and behold it wasn't found (Cannot find bean in scope). Do I need to explicitly import this bean to get it to work or is there a better way of doing it??? Like adding another ActionMapping or something. 3) If I import my bean explicitly in my JSP (the one listed for convenience below): public class SourceDatabaseForm extends ActionForm { private ArrayList sourceDatabases; public SourceDatabaseForm() { sourceDatabases = new ArrayList(); sourceDatabases.add(new LabelValueBean("Ensembl", "ENSEMBL")); sourceDatabases.add(new LabelValueBean("NCBI", "NCBI")); } public Collection getSourceDatabases() { return sourceDatabases; } } and then make a statement like I cannot get an iterator for my collection. Any idea what I am doing wrong??? Thanks so much for the help. I'm trying hard to get up to speed on this stuff - I think it is really cool. All the best, Steve-o
http://www.jguru.com/forums/view.jsp?EID=1226534
CC-MAIN-2014-35
refinedweb
263
63.19
AS3 101: OOP - Introduction to Interfaces In the closing chapters of our Object-Oriented Programming series, we will take a look at some more advanced concepts, focusing on interfaces (the programmatic kind). This may be the final installment, but we'll be splitting the content into two parts. In this part, we'll get an introduction to interfaces, and begin to use them in small projects. In the next part, interfaces will play a key role in a bigger, more practical application: a simple drawing program. (There Is No) Final Result Preview The projects that we'll be working on are many and small. The functionality contained therein is purposely kept to a minimum, so as to focus on the concepts and not get lost in programmatic details. If you're jumping into this series at this article, I recommend that you make sure you're up to speed with the rest of the concepts introduced in not only the previous Object-Oriented Programming tutorials, but the core concepts of the rest of the AS3 101 series. This material is not exactly for the faint of heart, but if you feel confident you know that other material well, you won't have any problems. Just stick with me, and you'll learn a few things. Step 1: The Interface You won't be begrudged for thinking that, when I mention the "interface", I'm talking about the UI of a program, on-screen. And while that is, indeed, an interface, we're here to discuss a more advanced Object-Oriented topic of the same name. Imagine, if you will, a music studio, with lots of electronic gear (for our purposes, the more discrete pieces of equipment the better; note of this all-in-the-computer-box music stuff). Photo from Flickr user The Cowshed and is distributed under a Creative Commons Attribution-NoDerivs 2.0 Generic license In the end, all of these disparate noise makers need to get routed to the noise recorders, and then the recording gets played back and recorded as a mix. A lot of audio needs to get from point A to point B to point C, with lots of points in between. Now, as you probably know, sound – in electronic form – travels from one point to another via a cable. Plug one end of the cable into the thing producing sound, and the other end of the cable into the thing receiving the sound, and you have a signal. Imagine how difficult this would be if each musical equipment manufacturer created its own type of plug for the cables. You'd be stuck with only equipment from a single manufacturer, or possibly with several dozen adapters lying around to connect these incompatible inputs and outputs. Fortunately, there are a few standards to which all manufacturers adhere. This is a bit of a gross simplification, but nearly all audio jacks you'll find in a music studio will be one of two kinds: XLR or quarter-inch (audiophiles, let's ignore impedance and balancing, as well as other jacks like RCA). Thankfully, with only two types of cable, and the occasional adapter, you can connect virtually any piece of audio gear to any other. The way in which a piece of gear connects to the rest of the world is its interface. In a generic sense, you can see how this applies to user interfaces, as well – it's how the software connects to the outside world (i.e., the user). But the audio interface for a mixer or keyboard is that piece of gear's particular capabilities for input and output using which kind of plug. Photo from Flickr user The Cowshed and is distributed under a Creative Commons Attribution-NoDerivs 2.0 Generic license Step 2: Bringing It Back to Programming In the same way as audio equipment, the interface of an object is the way in which it connects to the outside world. Now, "connect" is probably not the best word to use. Let's use "makes itself available" instead. All objects will have an interface, whether you think about it or not. You can think of the interface to an object as all of the public methods and properties belonging to that object. Put another way, the interface of an object is the stuff you can do to that object. So when you write a class, and define four public methods, three private methods, and two protected methods in it, the interface to the objects is made up of the four public methods. You have probably heard of the acronym "API". It's quite the rage these days in the form of web service APIs, such as the Flickr API or the Google Maps API. API stands for "Application Programming Interface." In this sense, the interface is the set of methods you can call on the web service, defining not only the name of the methods, but the parameters you can send to it and the type of data that will be returned. Step 3: Implementations Let me pause briefly and bring up encapsulation again (one of the core principles of Object-Oriented Programming – see the first part of the OOP series for more information). Note that the interface is not made up of private, protected, or internal methods and properties. Those members are hidden away from the outside world, vis-a-vis, not part of the interface. Similarly, it's important to understand a subtle distinction between the interface, as seen from the outside world, and the implementation. That is, the interface defines the method signature (a method signature denotes the method name, its arguments and type, and the return type), like this: function publicMethod(arg1:String):Boolean. However, what actually goes on inside of the method is not the concern of the interface. That's up to the implementation. If you were enjoying the audio equipment analogy, you can think of this differentiation between interface and implementation as the difference between putting a 1/4-inch jack on a piece of gear, and the components and quality of material put into that jack. Not all 1/4-inch jacks are created equal; some are gold-plated while others are nickel-plated. Some will have high-quality wires soldered to it, others will be molded directly onto a circuit board. The implementation (materials and method of construction) is not under the jurisdiction of the interface (a jack that is 1/4-inch wide). If you weren't enjoying the audio equipment analogy, I apologize for bringing it up again. Step 4: Interfaces in Code As it happens, I'm not bringing up all of this just to tell you that your objects already have an interface. That's important to realize, but what we're after right now is another Object-Oriented Programming concept known as the interface. You can actually define an interface without defining the implementation. If you think about it, this is inherently what the interface is about. The interface merely defines what you can do with something, not how things get done. Confused yet? If not, you're not thinking about it hard enough! Just teasing, but I do not expect this to make complete sense at this point. Let's move on to a simple, perhaps useless, but definitely hands-on example. Step 5: Writing an Interface Let's crack open Flash and the text editor of your choice, and try our hand at creating an interface. Before we can really begin, create a folder on your computer in which to house this mini-project. It'll just be tidier to have a dedicated project folder. All files that we create in this step will be saved in this folder. Now, create a new .as file. I'll assume you're using an editor that doesn't have much in the way of templates, but if you're using Flash Builder, you can get most of this by choosing "ActionScript Interface" from the new file menu. And of course, many other editors have templates (even Flash CS5 has an ActionScript 3.0 Interface template). But it's good to learn the nuts and bolts of these templates. Save your file as "ITest.as" in the project folder. It's not required, but it's common practice to name your interfaces following the convention of naming classes (i.e., capital first letter, camel-case after that), with the addition of an "I" at the front. The "I" indicates that the datatype is an interface, rather than a regular class. Flash will happily work with interfaces that are named without the leading "I" but it's a convention that you'll find handy for your own projects, as well as useful when looking at other developers' classes and interfaces. Now, enter the following boiler plate code: package { public interface ITest { } } You've just written an interface (one that doesn't define much, but still). Note that if we wanted to utilize a package structure, we'd spell it out after the package keyword just like in classes. And except for the use of interface, the definition is identical to a class definition. However, note that we don't put in a constructor. The constructor is a special method, and isn't really part of an interface. Any other method, though, we can define in the interface, and we'll do that next. Add the highlighted line to your interface file: package { public interface ITest { function test():void; } } Now, we've declared that the ITest interface has one public method. It's called test, takes no arguments, and returns nothing. What does it do? The interface isn't terribly concerned with that. What it does will be up to the concrete implementation. Notice that the method signature ends with a semi-colon, and not curly braces. Also notice the lack of public or private or anything in front of the function. The exceptionally quick-witted will recall that omitting the access modifier in a class will default to internal. Since interfaces define public methods only, the default is public. In fact, even trying to specify public will cause errors. Save your file, and your interface is now usable. We'll use it in just a moment. Step 6: But First, a Quick Summary To put the previous hands-on instruction into theory, the mechanics of an interface in OOP is rather similar to a class: - An interface is defined in its own text (.as) file, just like a class. - The boiler plate code is nearly identical to that of a class file; you use pacakges and imports as needed. - The name of the interface must be the same as the base name of the file. - The interface is a datatype, just like a class. There are, as you'd expect, differences. The biggest difference is this: Interfaces do not have any functionality. There are other differences, some of which we haven't touched on yet: - In the boiler plate, you use the keyword interfaceinstead of class - You can define public methods only - This does include implicit setters and getters — e.g., function get someString():String - This does not include private, protected, or internal methods. - This does not include properties of any kind. - When defining these public methods, you do not use the publickeyword. - Not only is publicassumed, it's actually non-compilable code to use that keyword in the method signature. - Seeing as how there is no functionality, you end the method declaration with a semi-colon, and omit the curly braces that normally wrap around the method implementation. Step 7: Implementing an Interface It's not enough to simply define an interface; the interface needs to be implemented in order to be useful. What implements an interface? A class, naturally. Any class you write can technically implement any interface you choose. We'll take a look at how this works in this step. This class is often called the "implementation" when referred to in relation to the interface. It may also be called a "concrete" class; as in, it's something "solid" and "real" as opposed to the non-functional interface. Create a new text file called "TestImplementation.as" and save it into the project folder. It will be a class, so add the following basic class skeleton: package { public class TestImplementation { public function TestImplementation() { } } } So far, nothing new or even exciting. It's just a class. It has no connection to the ITest interface we created in the last step. But obviously we want to utilize that interface, so here's what we need to do: add implements ITest after the class name: package { public class TestImplementation implements ITest { public function TestImplementation() { } } } With this addition, we have now declared that our class TestImplementation will implement the ITest interface. But all we've done is declare that intention. We need to actually do the implementing. Add the test method declared by ITest to our TestImplementation class: package { public class TestImplementation implements ITest { public function TestImplementation() { } public function test():void { trace("Just a little test."); } } } At this point, our class now fully implements the ITest interface. Our next step is to see this class in action. Step 8: Testing the Interface and Implementation Create an ActionScript 3.0 Flash file (File > New > ActionScript 3.0), and save it as "first-interface.fla" in your project folder. Create one more text file, called "Main.as", in your project folder. This will be our document class. Before writing the contents of the class, hop back to your Flash file and enter "Main" as the Document Class in the Properties panel for the document. Now, in Main.as, enter the following: package { import flash.display.Sprite; public class Main extends Sprite { public function Main() { var tester:TestImplementation = new TestImplementation(); tester.test(); } } } This is an unsurprising usage of our TestImplementation class. We create a new instance of it, then call a method on it, resulting in a trace in the Output panel. This finished project is available in the download package in the "first-interface" folder. Now, let's explore the relationship between interface and implementation. Step 9: The Contract When you write implements in your class file, it's like you're signing a contract with Flash, agreeing to fully implement each method defined in the interface file. When Flash sees that implements keyword, it will do quite a bit to ensure that you do, in fact, implement the interface. Let's start with some modifications to the interface. Open up ITest.as and, first, let's add a method to it: package { public interface ITest { function test():void; function anotherTest():void; } } When we make this change, we're saying that any implementations of this interface must define these two methods. But, before we do that, go ahead an test the movie right now. You should see that we get compiler errors: [...]/TestImplementation.as, Line 2 1044: Interface method anotherTest in namespace ITest not implemented by class TestImplementation. That error says, in rather stilted computer jargon, that we have failed to uphold the contract that we've entered. We said we'd implement the ITest interface, yet we never implemented the anotherTest method. Let's try to fix that problem. Back in TestImplementation.as, add the method in question, but we'll deliberately make a mistake for illustrative purposes: package { public class TestImplementation implements ITest { public function TestImplementation() { } public function test():void { trace("Just a little test."); } public function anotherTest(input:String):void { trace("Another test: " + input); } } } If you run the movie now, you'll get a different compiler error. That means that we've solved the previous error at least, but not to the satisfaction of the Flash compiler. It is now complaining that: [...]/TestImplementation.as, Line 2 1144: Interface method anotherTest in namespace ITest is implemented with an incompatible signature in class TestImplementation. This is due to the use of the input argument in our implementation of the anotherTest method. It's not declared in the interface, therefore we have an "incompatible signature." If you clean that up: public function anotherTest():void { trace("Another test"); } You'll see that we can now compile successfully. The lesson here is that interfaces are rather strict. Once you say you'll implement one, you're bound by that contract to implement each method exactly as declared by the interface. Not doing so means your SWF will not run due to compiler errors. Step 10: The Limits of the Contract Now, please be aware of an important aspect to this: an interface only defines a minimum of methods that must be present in your implementation class. That is, since our TestImplementation class implements ITest, we are required to at least have a test method and an anotherTest method defined. But the interface has no jurisdiction over what other methods may be declared. We can define as many other properties and methods as we like, just so long as the test and anotherTest methods are implemented. To explore this, we'll add a third method to TestImplementation.as: package { public class TestImplementation implements ITest { public function TestImplementation() { } public function test():void { trace("Just a little test."); } public function anotherTest():void { trace("Another test"); } public function extraneousTest():void { trace("One more test."); } } } Again, this method is not defined in ITest. If you run the movie now, you'll see no change. Everything compiles just fine. Our implementation just happens to have an extra method on it. Step 11: Interfaces as Datatypes Now for something a little more tricksy. I mentioned before that the interface is, like a class, a datatype available in ActionScript. We can check this out by making a small change to the Main.as file: public function Main() { var tester:ITest = new TestImplementation(); tester.test(); } The datatype of the tester variable was previously TestImplementation. It is now ITest. If you run the movie now, you'll find absolutely no change to the functionality. The datatype does have some subtle ramifications, though. Note that we can expand our usage of the object to involve another method call: public function Main() { var tester:ITest = new TestImplementation(); tester.test(); tester.anotherTest(); } And this will run as you expect it to. However, adding a third method call like so: public function Main() { var tester:ITest = new TestImplementation(); tester.test(); tester.anotherTest(); tester.extraneousTest(); } Will result in the following compiler error: [...]/Main.as, Line 9 1061: Call to a possibly undefined method extraneousTest through a reference with static type ITest. If you're an ActionScript ninja, you'll see what's going on here. The tester variable has an instance of TestImplementation stored in it. TestImplementation has an extraneousTest method defined in it. At first glance, we may thus assume that tester would be able to execute the extraneousTest method. However, the tester variable has been datatyped as ITest (not as TestImplementation). ITest does not declare an extraneousTest method. The compiler, therefore, when evaluating the usage of the tester variable, looks at the ITest interface for allowable actions, not the TestImplementation class. So when the compiler encounters the call to extraneousTest, it realizes that extraneousTest was not defined in ITest and produces the above error. What you should learn from this, aside from the mechanics of what just happened, is that when we datatype the variable as an interface, we should then subsequently treat it as the interface, regardless of what the actual concrete type the variable actually is. Now, why would we do that? Read on. Step 12: Polymorphism If you're at all like me, you will at this point be comfortable with how interfaces work, how they can be created and used, and generally what they do. But you'll be at a loss for why in Dog's green earth you'd want to use one. Seems like a lot of extra work for no added features, right? I have no problem admitting that it took me about a year of programming with OOP techniques before I finally realized the value of interfaces. I don't say this to scare you off. I say this to help you feel human. This stuff is hard. You are not stupid, you're just being introduced (as gently as I can possibly manage) to a rather advanced concept. With that in mind, I need to bring up one of the tenets of Object-Oriented Programming: Polymorphism. You've been introduced to encapsulation and inheritance in the previous OOP tutorials. Polymorphism is another of these essential ingredients that makes OOP what it is. Of course, we need to define the word. It's the strangest of all of the words we've encountered so far. It's from Greek: poly meaning "many" and morph meaning "form". "Many forms." In terms of OOP, polymorphism is the ability of a variable to be strongly typed, yet be capable of handling several different datatypes. And, of course, interfaces place a key role in this. Now, that probably doesn't make much sense just now. So let's move on to a more hands-on illustration, with a new, yet still simple, example. Step 13: Getting Set Up For Magic We'll create a whole new project for this illustration. You can follow along with the abbreviated sub-steps listed in this step, or you can simply open up the "language-start" project, found in the download package. - Create a new project folder. - Create a new AS3 FLA in that folder, named language.fla. Create a new document class for that FLA, named Main.as. This is the code to enter into it: package { import flash.display.Sprite; public class Main extends Sprite { public function Main() { var english:IPhrases = new EnglishPhrases(); trace(english.greeting()); trace(english.urgentSituation()); } } } Create a new interface file, called "IPhrases.as". This is the code for that file: package { public interface IPhrases { function greeting():String; function urgentSituation():String; } } Create one more file, a class named "EnglishPhrases.as", and enter this code: package { public class EnglishPhrases implements IPhrases { public function EnglishPhrases() { } public function greeting():String { return "Hello."; } public function urgentSituation():String { return "Where is the bathroom?"; } } } Go ahead and test it the movie, just to make sure everything is copacetic. You should get two traces in the Output panel: This project is very similar to our previous project. The major thing that has changed is the names of the files and methods involved. The classes and interface, and methods defined therein, have more meaningful names, which hopefully key you into what it is that they do. That thing that they do is provide simple phrases in a given language. We are currently set up for English, but as you can guess, we'll be changing that in the next step. Before moving on, I should note the other significant change is that our interface methods are declared as having to return Strings. This is a rather irrelevant change, but bears mentioning. Lastly, other than the two changes, the project is conceptually identical to what we've done so far; we have an interface, and one implementation of that interface. A Flash file and its document class then set up a variable datatyped to the interface, and create an instance of the class into the variable. Two methods are then called on the instance. Now, on with the magic. Step 14: Implement the Interface, Again Our goal is to add one more class. This class will also be an implementation of IPhrases. Both will coexist peacefully; no implosion of the universe or anything. Yet. Create another text file in your project folder, called "SpanishPhrases.as". Add this code to the class: package { public class SpanishPhrases implements IPhrases { public function SpanishPhrases() { } public function greeting():String { return "Hola."; } public function urgentSituation():String { return "¿Dónde está el baño?"; } } } (Note that if you are using the file provided in the download package, it was saved with UTF-8 encoding. You may need to jigger your text editor if those non-ASCII characters (like ¿ and ñ) show up strangely) As you can see, we enter into the contract by writing implements IPhrases. And then we proceed to actually implement the methods defined in IPhrases. Our implementation here is similar, yet unique from EnglishPhrases. So now we have two concrete implementations of IPhrases in our project. Let's try using them. In Main.as, add some code: public function Main() { var english:IPhrases = new EnglishPhrases(); trace(english.greeting()); trace(english.urgentSituation()); var spanish:IPhrases = new SpanishPhrases(); trace(spanish.greeting()); trace(spanish.urgentSituation()); } Run the Flash movie, and you'll get double the Output: From the aspect of our Main class, pretty much all we can see is that we have two objects, both of them IPhrases objects. They happen to have the same interface. Yet they have differing implementations, so while the code used to run those two objects is very similar, the results are different. Step 15: Polymorphism, Again Now, to really illustrate polymorphism, we need to show that a single variable, typed as an interface, can hold any number of concrete implementation types. We'll start by hard-coding the concrete types. Revert your Main.as file to this: public function Main() { var phrases:IPhrases = new EnglishPhrases(); trace(phrases.greeting()); trace(phrases.urgentSituation()); } Run it, and the results should be predictable. Now, change line 6 so that instead of creating a new EnglishPhrases instance, we create a SpanishPhrases instance: public function Main() { var phrases:IPhrases = new SpanishPhrases(); trace(phrases.greeting()); trace(phrases.urgentSituation()); } And run it again. The results should be expected, but what I want you to focus on is how the only thing we just changed was name of the class after the new keyword. The variable didn't change, most importantly the datatype of the variable. If we had used EnglishPhrases as the datatype, then the first example would work but the second one would not. The compiler would complain about trying to put an SpanishPhrases object into a variable typed as EnglishPhrases. Hopefully this will illustrate not only the concept of polymorphism, but also that the implementation details can indeed be different, while the interface remains the same. You may also realize that encapsulation comes into play here, as well; the implementation details are encapsulated in the concrete classes, exposing just the interface. Step 16: A Basic UI Let's take this one step further, and create a basic UI that lets the user trigger greeting and urgentSituation from button clicks. We could draw some buttons in Flash and work with the UI that way, but let's take the opportunity to capitalize on the reusability of classes and some of the work we've done before. If you've followed along with the OOP tutorials so far, you'll have created a Button101 class. If not, or if you followed along but didn't keep the work, you can find the class in the download package. To use it in this project, we need to either copy the Button101.as file into our current project folder, or make sure the source paths are set up to point to the folder that houses the Button101.as file already. My previous tutorial on Object-Oriented Programming covered how to set up the source path, if you need a refresher. For simplicity right now, I'm just going to copy it into my current project folder. With the Button101 class accessible to the language project, we can set up our UI with code in Main.as. We'll be sort of starting over with this class, so just replace the current contents with this: package { import flash.display.Sprite; import flash.events.MouseEvent; public class Main extends Sprite { private var _phrases:IPhrases;); } private function doGreeting(e:MouseEvent):void { trace(_phrases.greeting()); } private function doUrgentSituation(e:MouseEvent):void { trace(_phrases.urgentSituation()); } } } First, note that we've created a property to hold an IPhrases object, and we create it as a EnglishPhrases object in the constructor. We're making a property so that this object persists and we can reference it when the user clicks the buttons. Second, the bulk of the code is devoted to creating two buttons, which are hooked up to two click event listeners. Those listeners call one of two methods on the IPhrases object. Go ahead and test it now; you'll see something like the following: And if you click the buttons, you'll get the traces. This step wasn't anything exciting, this is just to get some stuff out of the way for the next step. Step 17: ¿Habla Español? Let's church it up a little more and add buttons to the UI that let us choose which language we want to use. Right now, we have the EnglishPhrases class as our _phrases object. But let's make things a little more flexible and dynamic. We're going to add two more buttons in the UI. In Main.as, in the constructor, add the highlighted code:); var englishButton:Button101 = new Button101(); englishButton.label = "English"; englishButton.x = 300; englishButton.y = 10; addChild(englishButton); englishButton.addEventListener(MouseEvent.CLICK, useEnglish); var spanishButton:Button101 = new Button101(); spanishButton.label = "Español"; spanishButton.x = 300; spanishButton.y = 100; addChild(spanishButton); spanishButton.addEventListener(MouseEvent.CLICK, useSpanish); } Now, we need to write the two new event handlers. After the doUrgentSituation method, add these methods: private function useEnglish(e:MouseEvent):void { _phrases = new EnglishPhrases(); } private function useSpanish(e:MouseEvent):void { _phrases = new SpanishPhrases(); } And try it out. You'll see something like this: Things start out in English, and clicking the original two buttons will be the same as before. But try clicking the Spanish button, and then on the "greeting()" and "urgentSituation()" buttons. Notice anything different? Step 18: Why Is The Interface Approach Better? Let's take a moment to talk about some theory. You may still be wondering why we went to the trouble of creating the interface, creating the implementations, and setting up the UI logic to execute such a simple task. After all this would have accomplished the same end result, all in the Main class (with the help of the Button101 class): public class Main extends Sprite { private var _language:String; public function Main() { _language = "en"; var test1Button:Button101 = new Button101(); // Set up the rest of the buttons as before... } private function doGreeting(e:MouseEvent):void { switch (_language) { case "en": trace("Hello."); break; case "es": trace("Hola."); break; } } private function doUrgentSituation(e:MouseEvent):void { switch (_language) { case "en": trace("Where is the bathroom?"); break; case "es": trace("¿Dónde está el baño?"); break; } } private function useEnglish(e:MouseEvent):void { _language = "en"; } private function useSpanish(e:MouseEvent):void { _language = "es"; } } Yes, that would have had the exact same result as what we did in the previous step. So why bother with the two extra classes and the interface? Well, partly because this is a tutorial, and I need to ask you to trust me and follow along, understanding that this particular example a little on the trivial side, and that going to such lengths might be overkill in the real world. This example is simplified in order to avoid the distraction of other application mechanics, so we can focus on the topic at hand. But let's put that aside, and consider why you'd want to look closer at interfaces for some programming tasks. The most compelling reason in my mind is type safety. Consider what it would take to expand the linguistic capabilities of this little program. To add a language, you would have to go into each switch statement where the localized string is determined and add a case, taking care to spell the value of the _language property is accurate. To add a string, you'd have to add a new switch statement, ensuring that all existing languages are accounted for (and again, spelled accurately). Now imagine that this is a distilled version of a larger website or application that was localized according to region. Maybe the application support 15 different languages, along with several dozen individual strings that need localized per language. The trouble introduced in adding strings or languages gets magnified as the application increases in scope. And now consider the same task of adding strings and languages to the original, interface-driven version of the program. To add a new string, you would add the method to the ITest interface, and then implement the new method in all existing concrete objects. To add a new language, you simply need to create a new concrete implementation of IPhrases. The amount of work involved may not be any less than with the other approach, but you are all but guaranteed that your updated application will work once it compiles successfully. The interface won't let you compile if you forget to add the new string to a concrete language object, or if you don't fully implement the interface with your new language object. If that didn't convince you, I have more reasons. Our rewrite places all of the logic in a single class. This mixes logic for setting up the UI with logic for delivering localized strings in one class. By delegating responsibilities to other classes we get a cleaner idea of what each class is in charge. Focused classes tend to be less error-prone. Not only that, but creating more, smaller classes lets us more easily share that responsibility to other objects; if we need the "greeting" string somewhere other than in Main, it would be easy provide access to the IPhrases objects and know that the logic is sound. I could go on, but you're probably feeling a little overwhelmed as it is. If you need it, take a little breather, and/or review the previous exercise and explanation. We're officially done with the new concepts for this tutorial, and we'll be rounding it out with two more examples of interfaces in action. Step 19: One More Example We will again start with a new project. And as with the language example, you can either open the "debugger-start" project (in the download package) or follow these condensed steps: - Create a new folder for the project, named debugger. - Create an AS3 FLA file, and save it in the project folder as debugger.fla. Create a document class for the FLA and save it as Main.as. Make sure the FLA is set up to use Mainas the document class. Add this code to the file: package { import flash.display.*; import flash.events.*; import flash.system.*; public class Main extends Sprite { public function Main() { // Fill this in later. var message1Button:Button101 = new Button101(); message1Button.label = "Message 1"; message1Button.x = 10; message1Button.y = 10; addChild(message1Button); message1Button.addEventListener(MouseEvent.CLICK, message1); var message2Button:Button101 = new Button101(); message2Button.label = "Message 2"; message2Button.x = 10; message2Button.y = 100; addChild(message2Button); message2Button.addEventListener(MouseEvent.CLICK, message2); } private function message1(e:MouseEvent):void { // Fill this in later. } private function message2(e:MouseEvent):void { // Fill this in later. } } } Create an interface file, saved as "IDebugger.as" in the project folder. This is the code: package { public interface IDebugger { function out(message:*):void; } } Create a class file named "Trace.as" and save it in the project folder with the following code (to be expanded on in a moment): package { public class Trace implements IDebugger { public function out(message:*):void { // Fill this in later } } } Create one more class file, save it as "Log.as" in the project folder, and add this code: package { public class Log implements IDebugger { public function out(message:*):void { // Fill this in later } } } There is nothing new here, but here's a quick run-down. The Main class creates two buttons and hooks them up to two event listeners that we'll be filling in next. The IDebugger interface defines a single method: out. The idea is that this will take a message as the sole parameter and somehow display it. Finally, we have two implementations of the interface, Trace and Log, both of which are merely stubbed out right now. Let's work out those implementations right now. In Trace.as, remove the comment in the out method and replace it with this logic: public function out(message:*):void { trace(message); } Doesn't seem like it's doing much, simply wrapping around the built in trace function. And that's about it. But let's complete the other implementation. Open up Log.as and flesh it out a bit: package { import flash.external.*; public class Log implements IDebugger { public function out(message:*):void { ExternalInterface.call("console.log", message.toString()); } } } Now things get interesting. After importing the external package, we can use ExternalInterface to call the JavaScript function console.log. Instead of using trace, we can use the JavaScript console built into most modern browsers (note that I'm not bothering to check for the availability of ExternalInterface or console.log; I'm going light on error-checking for the sake of more convenient illustrations). Now back to Main.as, where we can use these classes. First, add a _debugger property to the class, typed as an IDebugger. public class Main extends Sprite { private var _debugger:IDebugger; // Class continues... And in the constructor, we'll add some logic to detect where the Flash Player is running, and based on that information, instantiate one concrete class or the other. public function Main() { if (Capabilities.playerType == "ActiveX" || Capabilities.playerType == "PlugIn") { _debugger = new Log(); } else { _debugger = new Trace(); } // Constructor continues... This logic uses the Capabilities class to get the player type, which will one of a handful of String values. If that value is either "ActiveX" or "PlugIn", then the Flash Player is running as a browser plug in (specifically, in Internet Explore if the value is "ActiveX", or any of the other browsers if the value is "PlugIn"). So, if we're in a browser, we create _debugger as a Log object, to use the JavaScript console. Otherwise, we're probably running in the Flash IDE (although AIR or as a projector are still options) and so we can use the Trace object. Finally, let's fill in the two event handler methods, message1 and message2. private function message1(e:MouseEvent):void { _debugger.out("Hello.") } private function message2(e:MouseEvent):void { _debugger.out("Where is the bathroom?") } Normally, you'd simply use trace to get some text to show up, but instead we use the _debugger object. Depending on how it was set up initially, you'll get traces to the Output panel, or logs to the JavaScript console. So we've created an interface to getting messages from our ActionScript to some other place where we can see them. Again, the interface itself doesn't care how that happens, it just defines that it can happen. And from the Main class's perspective, it's using the interface as a datatype, so it, too, is agnostic as to how the messages get displayed, it's just using the _debugger property to send messages somewhere. The two implementation classes are the ones that do the work of displaying messages, encapsulated away behind the interface. Thanks to our initial choice of an implementation based on our player type, we can see messages pretty easily no matter where the SWF is running. To test this, you'll need to run the SWF once in the IDE and once in the browser. Start by just running the movie in Flash and clicking the buttons — you'll see the traces. To test the second part of this, you'll need the SWF running in a browser. This, unfortunately, is not as simple. You will need an HTML page to house the SWF (create your own or use Flash's publishing templates) or else ExternalInterface won't work. Then you'll need to either put the HTML and SWF files on a server and browse to the page so that it's being served over HTTP (localhost should be fine), or you'll need to adjust the Flash Player security settings to let a locally-run SWF access the HTML page. However you get that happening, open the console (found in Firebug if you're using Firefox, or the Web Inspector in Safari, Chrome, and other WebKit browsers, or under Developer Tool in the latest Internet Explorer), load the HTML page, and start clicking the buttons. (And yes, I'm aware of the Flash Debug Player's ability to send trace messages to a log file, for viewing traces in a browser. This example is, well, an example. It's useful, but probably not as useful as the debug player trick — go here for more information — although you could argue that if a non-Flash developer needs to see some of your traces, it might be easier to use the console than to install and set up the debug player) Now imagine that you can create further implementations. Perhaps one implementation creates a TextField object on the stage and simply spits messages out right in the SWF. A more advanced one could use a LocalConnection object to connect to an AIR app or a socket server to connect to any number of other pieces of software (even your phone). You could even take the JavaScript idea further and display messages in the browser but beyond the console. This idea hopefully does two things. For one, I hope you might be sparked into some interesting debugging options. And for another, I hope this makes the idea of polymorphism a little more practical. Step 20: Advanced Interface Techniques We will attempt to make polymorphism even more practical as we work through the project that is the focus of the next tutorial, but we are nearing the end of this tutorial. I would like to mention a few extra capabilities of interfaces that I've not had an opportunity to bring up yet. I'll simply mention these aspects, and leave them as notifications that these capabilities exist, without going full-bore into explanations. I have, however, included working (if simple) examples of these techniques in the download package, all contained within the "advanced-interface-techniques" folder. First, I want to mention the ability to implement multiple interfaces in a class. You can extend only one other class, but you can implement as many as you like or need to. To do this, you simply write implements and then list the interfaces you want to use, separated by a comma. For example: package { public class MultiImplementation implements IOne, ITwo, IThree { //... } } This enters you into three implementation contracts, which you then need to fulfill. Second, an interface can extend another interface. This works much like class extension does, only with interfaces. So if we have this interface: package { public interface ISuper { function basicMethod():void; } } We can create another interface which extends ISuper like this: package { public interface ISub extends ISuper { function fancyMethod():void; } } Extending an interface means that the subinterface inherits the method declaration of the superinterface, and can add more declarations to the mix. So in the above example, ISub may only define a single method in the file, but really requires two methods to be implemented: basicMethod and fancyMethod. For example: package { public class SubImplementation implements ISub { public funciton basicMethod():void { trace("basic method"); } public funciton fancyMethod():void { trace("fancy method"); } } } This would be a successful implementation. Leaving out basicMethod would not. Lastly, I want to briefly mention that you can certainly create a class that is both a subclass and an implementation. You simply need to list the superclass first, then the interface(s) next. For example: package { import flash.display.Sprite; public class FancySprite extends Sprite implements IFancy { // ... } } This also works with multiple interfaces, although the rules of only one super class still apply. As I said, I don't want to dwell on the techniques, as they're on the advanced side of an already advanced concept, but I wanted to mention them because they are useful, and may not be readily discoverable. I hope that by bringing them up here, you may retain a kernel of useful knowledge for when the time is right. Step 21: Using Interfaces to De-Couple SWFs I'd like to round things out with a final simple example. This particular technique is somewhat unique to Flash, given the ability of a SWF to load other SWFs, and the fact that web delivery encourages this modular approach to building websites so as to spread out the load. Let's set up the problem first. We'll work with two Flash files, each with their own document class. Flash file "Main.fla" will load in Flash file "Loadee.fla." Our initial take at this looks like the following: - Create a project folder for all of the files you'll be creating. - Create two Flash files, one called Main.fla and the other called Loadee.fla. - Create document classes for both of them, called Main.as and Loadee.as. - The Flash files can remain empty, but be sure to set the document class for each. - Write some code for the document classes. The Loadee.as class will look like this (note that part of the point of this Flash piece in this exercise is to provide KBs worth of code. The following listing is excerpted. To get the whole _pixels Array, please look in the download package for a folder called crosstalk-start for this class): package { import flash.display.*; import com.greensock.*; import com.greensock.easing.*; public class Loadee extends Sprite { private var _bmd:BitmapData; private var _bmp:Bitmap; public function Loadee() { _bmd = new BitmapData(_pixels[0].length, _pixels.length, false, 0xFF0000); _bmp = new Bitmap(_bmd); addChild(_bmp); var iLen:uint = _pixels.length; for (var i:uint = 0; i < iLen; i++) { var jLen:uint = _pixels[i].length; for (var j:uint = 0; j < jLen; j++) { _bmd.setPixel(j, i, _pixels[i][j]); } } _bmp.alpha = 0; display(); } public function display():void { TweenLite.to(_bmp, 0.5, {alpha:1}); } private var _pixels:Array = [ [0xc95016, 0xcc5316, 0xcc5716, 0xcf5716, 0xcf5716, 0xcf5716, 0xcf5a19, 0xcf5a19, 0xcf5a19, 0xcf5a19, 0xcf5d19, 0xcf5d19, 0xcf5d19, 0xcf6019, 0xcf6019, 0xcf6019, 0xd26019, 0xd2601d, 0xd2641d, 0xd2641d, 0xd2641d, 0xd2671d, 0xd2671d, 0xd2671d, 0xd2671d, 0xd26a1d, 0xd26a1d, 0xd26a1d, 0xd26d1d, 0xd66d20, 0xd66d20, 0xd66d20, 0xd67020, 0xd67020, 0xd67020, 0xd67020, 0xd67020, 0xd67020, 0xd67020, 0xd67020, 0xd67020, 0xd67020, // ... // To avoid an impossibly long scrolling page, this code is truncated. // Please look at the class Loadee.as in the folder "crosstalk-start" // for the complete code. ] ] } } I won't get into the logic of this class, suffice it to say that it programmatically draws a Bitmap using pixel values stored in a two-dimensional array. In other words, it's a bitmap image stored in a text file. When finished, you'll see the Activetuts+ logo appear. For now, the logo has an alpha of 0, so you won't see it. There is a display() method, though, which uses TweenLite to fade the logo in. The Main.as class file is centered around loading the Loadee SWF: package { import flash.display.*; import flash.events.*; import flash.net.*; public class Main extends Sprite { public function Main() { var loader:Loader = new Loader(); loader.load(new URLRequest("Loadee.swf")); loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoadComplete); addChild(loader); } private function onLoadComplete(e:Event):void { var loadedSwf:Sprite = e.target.content as Sprite; } } } - Publish the "Loadee" movie - Run (Test Movie) the "Main" movie. You won't see anything but a blank canvas. The reason is that we're not calling the display method in the Loadee object. Now, here's where things get tricky. Suppose we want to call display from the Main SWF. The reasons could be any of a number of valid reasons. Quite possibly we want to load the SWF but probably not display it right away, so we'll want to have control over when that moment of display happens. However, we want the Loadee SWF to be in control of its own display animation logic. So if you write this code: private function onLoadComplete(e:Event):void { var loadedSwf:Sprite = e.target.content as Sprite; loadedSwf.display(); } You'll get a compiler error, because the display method is not defined on Sprite, which is how the loadedSwf variable is typed. decoupled-swfs-start/Main.as, Line 18 1061: Call to a possibly undefined method display through a reference with static type flash.display:Sprite. So, you figure you can simply type the loadedSwf variable (and cast e.target.content) as a Loadee object. private function onLoadComplete(e:Event):void { var loadedSwf:Loadee = e.target.content as Loadee; loadedSwf.display(); } And when you Test the Main movie, you'll see that it works: That's great, but before you close down the Main movie, press Command-B (Control-B on the PC) to open up the Bandwidth Profiler (also available under View > Bandwidth Profiler while running a test movie). Note the size field. Mine says 13989 Bytes. Now, undo the recent changes. We'll reinstate the type as Sprite and remove the line that calls display(): private function onLoadComplete(e:Event):void { var loadedSwf:Sprite = e.target.content as Sprite; } And test the movie again. The Bandwidth Profiler should still be open from last time, but if not, open it up again and note the size. Mine now says 1016 Bytes. What happened? We added over 13,000 Bytes…or around 13 KB. How? As soon as we typed the loadedSwf variable as a Loadee, we use the Loadee class in our Main class. Normally, that sort of thing isn't so big of a deal, as you need to incorporate many different classes into a single, final, SWF. But at this point, we negated the goal of loading the Loadee in separately, as almost all of the weight of that SWF is contained in the Loadee class, as well as TweenLite. By virtue of using the Loadee class, even as a simple datatype for a single variable (as cast), the Flash compiler then compiles the entire class into the SWF. And any other classes in use by that class. At this point, our two SWFs are "coupled" or, as I call it, there is "crosstalk" between the two SWFs. Classes that should belong solely to one SWF are being compiled (probably inadvertently) into another. Interfaces can solve this problem. We can retain proper datatyping but de-couple the two SWFs. Here's how. Create a new interface file in the project folder, can call it ILoadee.as. Add this code: package { public interface ILoadee { function display():void; } } Next, we want our Loadee class to implement this interface. Add that to the class declaration: public class Loadee extends Sprite implements ILoadee { Now be sure to publish the Loadee SWF. We've made a change to it, so it needs to be republished. Finally, in Main.as, redo the things that we took out most recently. We'll call display on loadedSwf, but instead of using Loadee as the datatype, we'll use I Loadee: private function onLoadComplete(e:Event):void { var loadedSwf:ILoadee = e.target.content as ILoadee; loadedSwf.display(); } If you test Main now, you'll find that it works. And check the Bandwidth Profiler again, and you should see something more like the original size of Main. I have 1146 Bytes. So it increased a little bit (130 Bytes), which is due to the use of the interface. But this is nothing compared to the 13 KB increase when we used the class directly. And at the same time, we've retained type safety by datatyping our loadedSwf. If we tried misusing it, say by calling show instead of display, or trying to pass in arguments to display, then the compiler would produce errors and help us out of our predicament. If you want to test which classes are actually being compiled under different scenarios, you can refer to my Quick Tip on import statements for techniques on how to see which classes are compiled into a SWF. If you plan on using this technique (and I hope you do), you should also know about a tiny gotcha. Let me illustrate it: go back to Loadee.as and simply remove the implements ILoadee part (that is, we are no longer implementing the ILoadee interface, just extending Sprite). public class Loadee extends Sprite { Republish the Loadee SWF. Now re-test the Main SWF. You'll see an error pop up, but not a compiler error. It's a run-time error, which will show up in the Output panel when running in the Flash IDE. TypeError: Error #1009: Cannot access a property or method of a null object reference. at Main/onLoadComplete() The problem is that when we cast e.target.content as ILoadee, and in fact the loaded content is not an ILoadee type, then we get null back. Thus, loadedSwf is null, and so when we call loadedSwf.display() on the next line, that produces error: you can't call a method on something doesn't exist. So, to protect against this possibility, we should test for it. There are a few ways we can do this, and they depend a bit on what exactly your motive for using the interface is. If you want to guarantee that every loaded SWF adheres to the same interface (not a bad idea), then we can modify the onLoadComplete method like so: private function onLoadComplete(e:Event):void { var loadedSwf:ILoadee = e.target.content as ILoadee; if (!loadedSwf) { throw new Error("The loaded SWF does not implement the ILoadee interface.") } loadedSwf.display(); } This checks for the non-value state of loadedSwf, and if that's the case, stops the rest of the method by throwing an error. Now, we're still getting a runtime error, just like before, but in this case we're getting a much more helpful error. Try testing the Main SWF again, and you'll get the same results, just more helpful wording in the error message. On the other hand, if you want to allow for SWFs to not implement the ILoadee interface, and handle them differently, then it's just a matter of some conditional logic, alongside casts. You can try this in your onLoadComplete method: private function onLoadComplete(e:Event):void { var loadedSwf:Sprite = e.target.content as Sprite; if (loadedSwf is ILoadee) { (loadedSwf as ILoadee).display(); } else { trace("Need to do something with the loadedSwf variable as a Sprite."); } } The point here is that you test for the condition that the loaded SWF implements the interface, and if so, use it, and if not, do something else. The is keyword test the thing on the left to see if it, well, is the thing on the right. That is, if loadedSwf officially implements the ILoadee interface, then we get true. If not, we get false. So, if is is an ILoadee object, then we treat it as that object. The cast is still necessary, as the variable is officialy a Sprite. But we can be sure that the cast will be successful because we just tested the variable for that type. The advantage of this technique is flexibility. You could incorporate more than one interface. Maybe some SWFs are ILoadee SWfs, and others are ILoadeeWithCallback SWFs, and some are plain Sprites. With a few branches in your logic, you could handle each one appropriately. To sum up (this was an unusually long step, after all), to facilitate inter-SWF communication, you should employ this technique. This technique involves three parts (plus a fourth, optional one): - Create an interface(s) for the SWF(s) to be loaded (it's better if it's a single interface for all SWFs…polymorphism!) - Implement the interface in the document class of the SWF(s) to be loaded. - In the SWF doing the loading, use the interface as the datatype for the loaded content. - To be safe, test for a successful implementation of the loaded content. You can find an example of the finished project in the "crosstalk-finish" folder in the download package. For the record, I've never heard anyone else refer to this phenomenon as "crosstalk," but it's a rather apt word to describe what's going on. I just wanted you to know that, because I don't want you to draw blank stares when you identify this particular problem, then say something like "We need to eliminate the crosstalk" to another developer. Conclusion This wasn't a slouch of a tut, and if you made it here, you certainly aren't a slouch of a learner, either. But the fun is just beginning. There a sequel to this interface tutorial, to be released shortly. In it, we'll focus most our efforts on building a single project, in which interfaces will play a key role. Thanks for reading, and hanging in there with me! Tuts+ tutorials are translated into other languages by our community members—you can be involved too!Translate this post
http://code.tutsplus.com/tutorials/as3-101-oop-introduction-to-interfaces--active-8199
CC-MAIN-2015-32
refinedweb
9,502
64.1
Write a program (named encrypt.cpp) that allows the user to enter a string (max 80 chars). You will encrypt the string and write a file named secret.dat. You will then write a seperate program (named decrypt.cpp) that will read the secret.dat file and print the original message. Use the following algorithm for the encryption and decryption. (The only valid chars are A-Z(upper case), 0-9, and a space) 1) generate a random number between 5 and 13. this will be the "shifting" factor. 2) Simply shift each character (to the right) in the original message by the shifting factor. So if the shifting factor is 8 a D would become L, H becomes P and so forth. If the charcter is a W (you have to wrap to the beginning of the characters), it would be E. and so forth. 3) For a space, look at the previous character of the original message and shift from that character by 4 to the right. So something like IF YOU , the space would encrypt to J (because it is F shifted 4) 4) terminate the encrypted string with an '&' and then include the position of the spaces after the '&' separated by 'O'. So the last few characters might look something like FTY&6O12O17 This would tell me that the spaces are at position 6,12,17 in the message. 5) Insert one more 'O' and the shifting factor at the very end of the encrpypted message. So in the above example FTY&6O12O17O8, would not only tell me where my spaces were, but tell me that the shifting factor was 8 You would use the position of the spaces and the shifting factor to decrypt the message. Simply reverse the encryption. Instead of using all of the crap after the & sign. I am just decrypting everything up untill the & in the reverse order of how i encrypted it. The message i chose to encrypt was "HELLO HOW ARE YOU 0600" and here is a picture of the encrypted message and the decrypted message: the shift factor is 5. Heres my code. Can someone tell me what i am doing wrong? #include <iostream> #include <fstream> using namespace std; int main() { string message, decrypt; int m, d, shift, n = 0; ifstream input; //read encrypted message from "secret.dat" input.open("secret.dat"); getline(input, decrypt, '&'); getline(input, message); input.close(); cout << "encrypted message is: " << decrypt << endl; //get shifting factor m = message.length(); d = decrypt.length(); if (message[m - 2] == 79) shift = (message[m-1] - 48); else if (message[m - 2] != 79) shift = (((message[m - 2] - 48) * 10) + (message[m-1]- 48)); for (int i = 0; i < d; i++) { //decrypt[i] = decrypt[i] - shift; if ((decrypt[i] > 64) && (decrypt[i] < 91))//letters { decrypt[i] = decrypt[i] - shift; while ((decrypt[i] > 57) && (decrypt[i] < 65)) decrypt[i] = decrypt[i] + 26; } if ((decrypt[i] > 47) && (decrypt[i] < 58))//numbers { decrypt[i] = decrypt[i] - shift; while ((decrypt[i] < 48) && (decrypt[i] > 32)) decrypt[i] = decrypt[i] + 10; } if((decrypt[i] > 64) && (decrypt[i] < 91)) if (decrypt[i-1] + 4 == decrypt[i] + shift) decrypt[i] = 32; { if (decrypt[i] + shift > 90) decrypt[i] = 32; if (decrypt[i] + shift < 48) decrypt[i] = 32; if (decrypt[i-1] + 4 == decrypt[i]) decrypt[i] = 32; } if ((decrypt[i] > 47) && (decrypt[i] < 58)) if(decrypt[i-1]==32) decrypt[i+1]=32; } cout << "decrypted message is: " << decrypt << endl; system("pause"); return 1; }
http://www.dreamincode.net/forums/topic/135126-decrypting-a-message/
CC-MAIN-2016-07
refinedweb
575
62.88
Bodo Eggert <harvested.in.lkml@posting.7eggert.dyndns.org> wrote:> >> That is exactly the intended effect. If I'm at my work machine (where> >> I'm not an admin unfortunately) and I mount my home machine with sshfs> >> (because FUSE is installed fortunately :), then I bloody well don't> >> want the sysadmin or some automated script of his to go mucking under> >> the mountpoint.> > > > I think that would be _much_ nicer implemented as a mount which is> > invisible to other users, rather than one which causes the admin's> > scripts to spew error messages. Is the namespace mechanism at all> > suitable for that?> > This will require shared subtrees plus a way for new logins from the same> user to join an existing (previous login) namespace.Or "per-user namespaces".It's part of a more general problem of how you limit access to privatedata such as crypto keys, either per user, or more finely than that.Isn't that what all the keyring stuff is for?-- Jamie-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at
http://lkml.org/lkml/2005/4/12/235
CC-MAIN-2017-51
refinedweb
195
63.9
CodePlexProject Hosting for Open Source Software Hello, mattgerg again. I'm running into some problems loading kml files with the following namespace declaration, which no longer exists: <kml xmlns=""> In the problematic files, replacing the namespace with this resolves the issue: <kml xmlns=""> Can you think of any clever solution to this problem? Or is the only solution to modify every kml and kmz file so that they point to the updated namespace? In code, the issue stems from the Parse(XmlReader reader) function in Parser.cs, where this.GetElement() returns an UnknownElement which cannot be used as the root. Unfortunately, I have no opportunity to change the namespace programatically beforehand. Any ideas, or should I start modifying kml files? Thanks for your help. I've not had much chance to work with legacy files so the library is based on the OpenGIS specification, hence the strictness on the namespace being. However, you should be able to use the ParseString method inside the SharpKml.Base.Parser class to ignore the namespaces (not sure how this will work if you have any Atom/GX/XAL elements though). ParseString SharpKml.Base.Parser There should be an example how to use the method in ParseKml.cs in the examples folder, but here's a quick demo showing the other namespace: using System; using SharpKml.Base; using SharpKml.Dom; using SharpKml.Engine; class Program { const string Xml = "<kml xmlns=''>" + "<Placemark>" + "<name>SamplePlacemark</name>" + "</Placemark>" + "</kml>"; static void Main(string[] args) { // We'll manually parse the Xml Parser parser = new Parser(); parser.ParseString(Xml, false); // Ignore the namespaces // The element will be stored in parser.Root - we'll put it inside // a KmlFile for consistency. KmlFile file = KmlFile.Create(parser.Root, true); // Prove it worked ok Kml kml = (Kml)file.Root; Placemark placemark = (Placemark)kml.Feature; Console.WriteLine(placemark.Name); } } Hello again. This approach is working well to a degree -- the ParseString() function is able to succssfully parse through the kml. But I am running into issues at this block during the SerializeElement() routine in Serializer.cs: foreach (var ns in element.Namespaces.GetNamespacesInScope(XmlNamespaceScope.ExcludeXml)) { _writer.WriteAttributeString("xmlns", ns.Key, string.Empty, ns.Value); } When executing the WriteAttributeString() above, an exception is thrown: "The prefix '' cannot be redefined from '' to '' within the same start element tag." In the block above, ns.Key is blank, but a few lines prior, the following block is already inserting this non-prefixed namespace: "" else if (component != null) { _writer.WriteStartElement(component.Name, component.NamespaceUri); } I believe the two namespaces are encroaching upon one another. Is the intention to preserve the old namespace, insert a new namespace, or to make both namespaces coexist in the same document? When I comment the offending foreach loop, the program works like a charm. Any help would be much appreciated! Let me know if kmz files and code from my end would help out in this matter. Thanks again for your help. --MattGerg Ok, as you guessed the library is trying to preserve the namespaces but tries to use the old and new namespaces when serializing, which isn't a good idea! The problem is should it upgrade the Kml file to the new namespace or preserve the old one? I just tested with libkml what it does in this situation and it just upgrades the namespace: Input: <?xml version="1.0" encoding="utf-8"?> <kml xmlns=""> <Placemark> <name>My Placemark</name> </Placemark> </kml> Output: <?xml version="1.0" encoding="utf-8"?> <kml xmlns=""> <Placemark> <name>My Placemark</name> </Placemark> </kml> I've created a new test case and committed the changes to Parser.cs so you can either download it from the Source Code section or modify the file yourself, as it's a straight forward change. In the ProcessAttributes method of Parser (Parser.cs line 288) you need to add a check to only add a default namespace to UnknownElements: ProcessAttributes Parser UnknownElement if (string.Equals("xmlns", _reader.Name, StringComparison.Ordinal)) { element.Namespaces.AddNamespace(string.Empty, _reader.Value); } Becomes: if (string.Equals("xmlns", _reader.Name, StringComparison.Ordinal)) { if (element is UnknownElement) { element.Namespaces.AddNamespace(string.Empty, _reader.Value); } } Thanks for your patience and for your help in improving the library! I think I should add a section to the Documentation on how to load legacy files to help others in this situation. This is working perfectly. Thanks! Are you sure you want to delete this post? You will not be able to recover it later. Are you sure you want to delete this thread? You will not be able to recover it later.
http://sharpkml.codeplex.com/discussions/229686
CC-MAIN-2017-30
refinedweb
761
58.28
2008-10-15 12:13:48 8 Comments What is the correct (most efficient) way to define the main() function in C and C++ — int main() or void main() — and why? If int main() then return 1 or return 0? There are numerous duplicates of this question, including: - What are the valid signatures for C's main()function? - The return type of main()function - Difference between void main()and int main()? main()'s signature in C++ - What is the proper declaration of main()? — For C++, with a very good answer indeed. - Styles of main()functions in C - Return type of main()method in C int main()vs void main()in C Related: - C++ — int main(int argc, char **argv) - C++ — int main(int argc, char *argv[]) - Is char *envp[]as a third argument to main()portable? - Must the int main()function return a value in all compilers? - Why is the type of the main()function in C and C++ left to the user to define? - Why does int main(){}compile? - Legal definitions of main()in C++14? Related Questions Sponsored Content 22 Answered Questions [SOLVED] What is the "-->" operator in C++? - 2009-10-29 06:57:45 - GManNickG - 736094 View - 8503 Score - 22 Answer - Tags: c++ operators code-formatting standards-compliance 45 Answered Questions [SOLVED] What does "Could not find or load main class" mean? 1 Answered Questions [SOLVED] The Definitive C++ Book Guide and List 37 Answered Questions [SOLVED] What are the differences between a pointer variable and a reference variable in C++? 13 Answered Questions [SOLVED] What is a smart pointer and when should I use one? - 2008-09-20 00:09:24 - Alex Reynolds - 531367 View - 1705 Score - 13 Answer - Tags: c++ pointers c++11 smart-pointers c++-faq 13 Answered Questions [SOLVED] What is the effect of extern "C" in C++? - 2009-06-25 02:10:07 - Litherum - 707569 View - 1480 Score - 13 Answer - Tags: c++ c linkage name-mangling extern-c 29 Answered Questions [SOLVED] What does if __name__ == "__main__": do? - 2009-01-07 04:11:00 - Devoted - 2517991 View - 5420 Score - 29 Answer - Tags: python namespaces main python-module idioms 8 Answered Questions [SOLVED] When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used? 27 Answered Questions [SOLVED] What is the difference between #include <filename> and #include "filename"? - 2008-08-22 01:40:06 - quest49 - 535976 View - 2163 Score - 27 Answer - Tags: c++ c include header-files c-preprocessor 11 Answered Questions [SOLVED] What does the explicit keyword mean? - 2008-09-23 13:58:45 - Skizz - 793563 View - 2704 Score - 11 Answer - Tags: c++ constructor explicit c++-faq explicit-constructor @Edward 2017-04-22 11:34:54 Omit return 0 When a C or C++ program reaches the end of mainthe compiler will automatically generate code to return 0, so there is no need to put return 0;explicitly at the end of main.. Additionally, the C++ Core Guidelines contains multiple instances of omitting return 0;at the end of mainand no instances in which an explicit return is written. Although there is not yet a specific guideline on this particular topic in that document, that seems at least a tacit endorsement of the practice. So I advocate omitting it; others disagree (often vehemently!) In any case, if you encounter code that omits it, you'll know that it's explicitly supported by the standard and you'll know what it means. @Edward 2017-04-24 12:02:34 Note: The purpose for this answer is to allow those of us frequently giving this advice on CodeReview a StackOverflow answer to which we can point to regarding the practice of omitting return 0; @zwol 2017-05-13 17:09:55 This is bad advice because compilers that implement only C89, not any later standard, are still extremely common (I write this in 2017) and will remain extremely common for the foreseeable future. For instance, last I checked no version of Microsoft's compilers implemented C99, and it is my understanding that this is also still typical for embedded-system compilers that aren't GCC. @Edward 2017-05-13 17:15:17 @zwol: Anyone who has no choice but to use a compiler that is out of date by 28 years probably has more problems than deciding whether to explicitly include return 0;, however I would note that many compilers of that era also implemented an implicit return 0;even before it was standardized. @zwol 2017-05-13 17:17:25 What you say is true. I mean only to give a rationale for the "bad advice" reaction which is not just "it looks weird". @Edward 2017-05-13 17:27:21 Actually, I do a lot of embedded systems work and haven't encountered a compiler that doesn't support implicit return 0for over a decade. Also current versions of Microsoft C support it as well. Perhaps your information is out of date? @Lightness Races in Orbit 2019-06-09 14:54:37 I can appreciate this being controversial in C, almost (per @zwol). In C++ any controversy surrounding this is pure nonsense. @Edward 2019-06-09 15:04:26 @LightnessRacesinOrbit You might things so, but... codereview.stackexchange.com/questions/221922/c-logging-library/… @Lightness Races in Orbit 2019-06-09 15:05:51 @Edward I didn't say the controversy didn't exist, I said it was nonsense :P @workmad3 2008-10-15 12:16:08 The return value for mainshould indicate how the program exited. Normal exit is generally represented by a 0 return value from main. Abnormal exit is usually signalled by a non-zero return, but there is no standard for how non-zero codes are interpreted. Also as noted by others, void main()is explicitly prohibited by the C++ standard and shouldn't be used. The valid C++ mainsignatures are: and which is equivalent to It's also worth noting that in C++, int main()can be left without a return-statement, at which point it defaults to returning 0. This is also true with a C99 program. Whether return 0;should be omitted or not is open to debate. The range of valid C program main signatures is much greater. Also, efficiency is not an issue with the mainfunction. It can only be entered and left once (marking the program's start and termination) according to the C++ standard. For C, the case is different and re-entering main()is allowed, but should be avoided. @korona 2008-10-15 12:38:14 main CAN be entered/left multiple times, but that program probably wouldn't win any design awards ;) @Jonathan Leffler 2008-10-15 12:43:18 C99 also has the C++ mis-feature that reaching the end of the main() function is equivalent to returning 0 -- if main() is defined to return a type compatible with int (section 5.1.2.2.3). @workmad3 2008-10-15 12:59:42 reentering main is not valid C++. Explicitly in the standard, 3.6.1.3 states 'main shall not be used within a program' @Clay 2008-10-15 13:13:01 stdlib.h provides EXIT_SUCCESS and EXIT_FAILURE for this purpose @Martin York 2008-10-15 16:07:54 @korona: using main() from inside the code is undefined behavior. As the compiler may(depending on compiler) insert code to handle program initialization at this point. Running the initialization code twice may not be a good idea. @JaredPar 2008-10-15 16:32:44 0 and non-zero are correct but entirely meaningless to someone reading your code. This question is proof that people don't know what valid/invalid codes are. EXIT_SUCCESS/EXIT_FAILURE are much more clear. @Chris Young 2008-10-16 09:28:59 JaredPar: returning 0 from main is clearly defined in C as a successful termination. Martin York: calling main() from inside a C program is certainly not undefined behavior. I cannot say the same for C++. @workmad3 2008-10-16 13:25:55 As said, for C++ calling main() is explicitly stated in the standard as illegal (which is a step worse than undefined). For C though, the case is obviously different (but probably best avoided ;)) @JaredPar 2008-10-16 17:26:51 It may be clearly defined in the C standard but it's definately not clearly common knowledge. Otherwise this question wouldn't have been posted. @Chris Young 2008-10-19 14:00:52 JaredPar: well, it's common knowledge among programmers that know C, and usually I'd expect people reading C source to understand C. @Johannes Schaub - litb 2009-11-27 16:08:51 @workmad3, notice this defect report though about using main for GCC: gcc.gnu.org/bugzilla/show_bug.cgi?id=41431 . Also notice the following for allowed definitions of main: groups.google.com/group/comp.std.c++/browse_thread/thread/… @Calmarius 2013-05-27 12:17:41 Is it guaranteed the return value of the main function will be the exit code of the program? I always used the exitfunction in my programs to set the exit code other than 0. @Nemo 2013-06-20 01:39:02 @Calmarius: Yes. Section 5.1.2.2.3 of the standard says "...a return from the initial call to the mainfunction is equivalent to calling the exitfunction with the value returned by the mainfunction as its argument..." @Frank R. 2013-07-18 07:14:07 Every C developer knows INT exit code 0 means success, so why so much drowning in a glass of water? @Lundin 2015-07-07 08:11:32 This answer only covers 50% of the standards as it doesn't mention freestanding implementations. "void main() is explicitly prohibited by the C++ standard"... quotation needed (you won't find one, it rather implicitly prohibits void main() for hosted systems). @Veltas 2015-08-06 19:35:37 @Lundin main()is only talked about for the hosted forms of C and C++. So the question is implicitly about hosted C and C++. @Majora320 2016-04-21 02:18:25 Technically, the signature should be unsigned char main(...), because the vast majority of shell environments require you to return a value between 0 and 255. @Jonathan Leffler 2016-04-21 02:56:29 @Majora320: not really. The standards say intand mean int. However, you're correct that only the least significant 8 bits of the intare used as exit status. See also Exit codes bigger than 255 — possible?. @Pryftan 2018-02-22 02:33:47 ' is explicitly prohibited by the C++ standard and shouldn't be used' And also by C. Even if 'it works' it's broken. Presumably this is why it's the same way in C++ unless you mean it won't compile? I'm not a fan of C++ but then I know better than writing 'void main()' anyhow so I wouldn't have run into a problem. @Peter Cordes 2018-04-13 02:21:00 You forgot to mention int main(void);as a valid signature in C. In C, int main();really means int main(...). Only in C++ does int main()mean int main(void). (This is why it's bad that you only talked about C++ signatures for it) @Jesper Juhl 2018-06-12 19:50:50 Zero/non-zero to signal success/error is not true on all platforms (for example VMS). One should use the EXIT_SUCCESS/ EXIT_FAILUREmacros in portable code. @Toby Speight 2019-04-02 08:38:50 Please give a reference for "void main() is explicitly prohibited by the C++ standard", as I find no such prohibition in basic.start.main. As long as the standard signatures are supported, an implementation can also support as many non-standard signatures as it wants. (That said, I'd strongly advise against actually using such an extension, even if available). @Lundin 2015-07-07 08:07:30 Note that the C and C++ standards define two kinds of implementations: freestanding and hosted. C90 hosted environment Allowed forms 1: The former two are explicitly stated as the allowed forms, the others are implicitly allowed because C90 allowed "implicit int" for return type and function parameters. No other form is allowed. C90 freestanding environment Any form or name of main is allowed 2. C99 hosted environment Allowed forms 3: C99 removed "implicit int" so main()is no longer valid. A strange, ambiguous sentence "or in some other implementation-defined manner" has been introduced. This can either be interpreted as "the parameters to int main()may vary" or as "main can have any implementation-defined form". Some compilers have chosen to interpret the standard in the latter way. Arguably, one cannot easily state that they are not strictly conforming by citing the standard in itself, since it is is ambiguous. However, to allow completely wild forms of main()was probably(?) not the intention of this new sentence. The C99 rationale (not normative) implies that the sentence refers to additional parameters to int main4. Yet the section for hosted environment program termination then goes on arguing about the case where main does not return int 5. Although that section is not normative for how main should be declared, it definitely implies that main might be declared in a completely implementation-defined way even on hosted systems. C99 freestanding environment Any form or name of main is allowed 6. C11 hosted environment Allowed forms 7: C11 freestanding environment Any form or name of main is allowed 8. Note that int main()was never listed as a valid form for any hosted implementation of C in any of the above versions. In C, unlike C++, ()and (void)have different meanings. The former is an obsolescent feature which may be removed from the language. See C11 future language directions: C++03 hosted environment Allowed forms 9: Note the empty parenthesis in the first form. C++ and C are different in this case, because in C++ this means that the function takes no parameters. But in C it means that it may take any parameter. C++03 freestanding environment The name of the function called at startup is implementation-defined. If it is named main()it must follow the stated forms 10: C++11 hosted environment Allowed forms 11: The text of the standard has been changed but it has the same meaning. C++11 freestanding environment The name of the function called at startup is implementation-defined. If it is named main()it must follow the stated forms 12: References ANSI X3.159-1989 2.1.2.2 Hosted environment. "Program startup" ANSI X3.159-1989 2.1.2.1 Freestanding environment: ISO 9899:1999 5.1.2.2 Hosted environment -> 5.1.2.2.1 Program startup Rationale for International Standard — Programming Languages — C, Revision 5.10. 5.1.2.2 Hosted environment --> 5.1.2.2.1 Program startup ISO 9899:1999 5.1.2.2 Hosted environment --> 5.1.2.2.3 Program termination ISO 9899:1999 5.1.2.1 Freestanding environment ISO 9899:2011 5.1.2.2 Hosted environment -> 5.1.2.2.1 Program startup This section is identical to the C99 one cited above. ISO 9899:1999 5.1.2.1 Freestanding environment This section is identical to the C99 one cited above. ISO 14882:2003 3.6.1 Main function ISO 14882:2003 3.6.1 Main function ISO 14882:2011 3.6.1 Main function ISO 14882:2011 3.6.1 Main function This section is identical to the C++03 one cited above. @Utku 2015-11-17 10:55:01 One question: Do C++ standards mean that the signature of the startup function in freestanding environments is implementation defined as well? For example, an implementation could have defined the startup function to be: int my_startup_function ()or int my_startup_function (int argc, char *argv[])but can it have, for example: char my_startup_function (long argc, int *argv[])as a startup function as well? I guess no, right? Also, isn't that ambiguous as well? @Lundin 2015-11-17 11:07:13 @Utku It can have any signature, as long as it isn't named main()because then it must use one the listed signatures. I would imagine the overwhelmingly most common one would be void my_startup_function (), as it doesn't make sense to return from the program on freestanding systems. @Utku 2015-11-17 11:18:24 I see. But if it is allowed to use any name and any signature for the startup function, why not allow to use a different signature for mainas well? Sorry if that's not a smart question but I couldn't understand the reasoning behind. @Lundin 2015-11-17 12:09:13 @Utku C and C++ are different there. As for why C++ enforces this, I have no idea, there's no rationale. I suspect the main culprit (pun intended) is Stroustrup who early on declared that main must return int, period. Because when he made the first C++ version, he was only used to hosted systems. In the linked post, Stroustrup still seems oblivious about the existence of freestanding implementations: for example, he is ignorantly referring to the hosted implementation sub chapter of the C standard, ignoring the existence of chapter 5.1.2.1. @Antti Haapala 2016-03-13 10:48:44 Notable thing about C11 standard draft is that even though func()is considered obsolete, the draft itself uses int main()in its own examples. @Jeegar Patel 2011-12-27 08:02:51 main()in C89 and K&R C unspecified return types default to ’int`. If you do not write a return statement in int main(), the closing {will return 0 by default. return 0or return 1will be received by the parent process. In a shell it goes into a shell variable, and if you are running your program form a shell and not using that variable then you need not worry about the return value of main(). See How can I get what my main function has returned?. This way you can see that it is the variable $?which receives the least significant byte of the return value of main(). In Unix and DOS scripting, return 0on success and non-zero for error are usually returned. This is the standard used by Unix and DOS scripting to find out what happened with your program and controlling the whole flow. @Jonathan Leffler 2013-09-22 23:20:17 Strictly speaking, $?is not an environment variable; it is a shell predefined (or built-in) variable. The difference is hard to spot, but if you run env(without any arguments), it prints the environment, and $?won't be shown in the environment. @Kaz 2013-10-17 16:43:37 Returning 0 automatically when main "falls of the end" is only in C++ and C99 onwards, not in C90. @Jonathan Leffler 2013-09-10 14:15:12 Standard C — Hosted Environment For a hosted environment (that's the normal one), the C11 standard (ISO/IEC 9899:2011) says: Program termination in C99 or C11 The value returned from main()is transmitted to the 'environment' in an implementation-defined way. Note that 0is mandated as 'success'. You can use EXIT_FAILUREand EXIT_SUCCESSfrom <stdlib.h>if you prefer, but 0 is well established, and so is 1. See also Exit codes greater than 255 — possible?. In C89 (and hence in Microsoft C), there is no statement about what happens if the main()function returns but does not specify a return value; it therefore leads to undefined behaviour. Standard C++ — Hosted Environment The C++11 standard (ISO/IEC 14882:2011) says: The C++ standard explicitly says "It [the main function] shall have a return type of type int, but otherwise its type is implementation defined", and requires the same two signatures as the C standard to be supported as options. So a 'void main()' is directly not allowed by the C++ standard, though there's nothing it can do to stop a non-standard implementation allowing alternatives. Note that C++ forbids the user from calling main(but the C standard does not). There's a paragraph of §18.5 Start and termination in the C++11 standard that is identical to the paragraph from §7.22.4.4 The exitfunction in the C11 standard (quoted above), apart from a footnote (which simply documents that EXIT_SUCCESSand EXIT_FAILUREare defined in <cstdlib>). Standard C — Common Extension Classically, Unix systems support a third variant: The third argument is a null-terminated list of pointers to strings, each of which is an environment variable which has a name, an equals sign, and a value (possibly empty). If you do not use this, you can still get at the environment via ' extern char **environ;'. For a long time, that did not have a header that declared it, but the POSIX 2008 standard now requires it to be declared in <unistd.h>. This is recognized by the C standard as a common extension, documented in Annex J: Microsoft C The Microsoft VS 2010 compiler is interesting. The web site says: It is not clear to me what happens (what exit code is returned to the parent or OS) when a program with void main()does exit — and the MS web site is silent too. Interestingly, MS does not prescribe the two-argument version of main()that the C and C++ standards require. It only prescribes a three argument form where the third argument is char **envp, a pointer to a list of environment variables. The Microsoft page also lists some other alternatives — wmain()which takes wide character strings, and some more. The Microsoft Visual Studio 2005 version of this page does not list void main()as an alternative. The versions from Microsoft Visual Studio 2008 onwards do. Standard C — Freestanding Environment As noted early on, the requirements above apply to hosted environments. If you are working with a freestanding environment (which is the alternative to a hosted environment), then the standard has much less to say. For a freestanding environment, the function called at program startup need not be called mainand there are no constraints on its return type. The standard says: The cross-reference to clause 4 Conformance refers to this: It is noticeable that the only header required of a freestanding environment that actually defines any functions is <stdarg.h>(and even those may be — and often are — just macros). Standard C++ — Freestanding Environment Just as the C standard recognizes both hosted and freestanding environment, so too does the C++ standard. (Quotes from ISO/IEC 14882:2011.) What about using int main()in C? The standard §5.1.2.2.1 of the C11 standard shows the preferred notation — int main(void)— but there are also two examples in the standard which show int main(): §6.5.3.4 ¶8 and §6.7.6.3 ¶20. Now, it is important to note that examples are not 'normative'; they are only illustrative. If there are bugs in the examples, they do not directly affect the main text of the standard. That said, they are strongly indicative of expected behaviour, so if the standard includes int main()in an example, it suggests that int main()is not forbidden, even if it is not the preferred notation. @David Bowling 2017-12-13 15:38:02 According to §6.7.6.3/14 of the C11 Standard (just above one of the examples you cite), "An empty list in a function declarator that is part of a definition of that function specifies that the function has no parameters." This seems to indicate that int main() {}is just fine, as it is a declarator which is part of the function definition. @Jonathan Leffler 2017-12-13 15:58:42 @DavidBowling: A function definition like int main(){ … }does specify that the function takes no arguments, but does not provide a function prototype, AFAICT. For main()that is seldom a problem; it means that if you have recursive calls to main(), the arguments won't be checked. For other functions, it is more of a problem — you really need a prototype in scope when the function is called to ensure that the arguments are correct. @David Bowling 2017-12-13 16:10:50 I don't follow. How is int main() { /* function body */ }different from int main(void) { /* function body */ }? I don't think that I have ever seen a function prototype included for main()in a program. A declaration like int func(void);differs from int func();in that the first specifies no parameters and the second (obsolescent) specifies an arbitrary number of parameters, but I don't see how this applies to the usual int main() {}seen in C programs. @Jonathan Leffler 2017-12-13 16:42:19 @DavidBowling: You don't normally call main()recursively, outside of places like IOCCC. I do have a test program that does it — mainly for novelty. If you have int i = 0; int main() { if (i++ < 10) main(i, i * i); return 0; }and compile with GCC and don't include -Wstrict-prototypes, it compiles cleanly under stringent warnings. If it's main(void), it fails to compile. @David Bowling 2017-12-13 17:00:32 That is an interesting example, and I see your point now. @Steve Summit 2017-10-03 21:56:28 Those words "(most efficient)" don't change the question. Unless you're in a freestanding environment, there is one universally correct way to declare main(), and that's as returning int. It's not what should main()return, it's what does main()return. main()is, of course, a function that someone else calls. You don't have any control over the code that calls main(). Therefore, you must declare main()with a type-correct signature to match its caller. You simply don't have any choice in the matter. You don't have to ask yourself what's more or less efficient, or what's better or worse style, or anything like that, because the answer is already perfectly well defined, for you, by the C and C+ standards. Just follow them. 0 for success, nonzero for failure. Again, not something you need to (or get to) pick: it's defined by the interface you're supposed to be conforming to. @Chris Young 2008-10-16 09:59:57 The accepted answer appears to be targetted for C++, so I thought I'd add an answer that pertains to C, and this differs in a few ways. ISO/IEC 9899:1989 (C90): main()should be declared as either: Or equivalent. For example, int main(int argc, char *argv[])is equivalent to the second one. Further, the intreturn type can be omitted as it is a default. If an implementation permits it, main()can be declared in other ways, but this makes the program implementation defined, and no longer strictly conforming. The standard defines 3 values for returning that are strictly conforming (that is, does not rely on implementation defined behaviour): 0and EXIT_SUCCESSfor a successful termination, and EXIT_FAILUREfor an unsuccessful termination. Any other values are non-standard and implementation defined. main()must have an explicit returnstatement at the end to avoid undefined behaviour. Finally, there is nothing wrong from a standards point of view with calling main()from a program. ISO/IEC 9899:1999 (C99): For C99, everything is the same as above except: intreturn type may not be omitted. main(). If you do, and main()finished, there is an implicit return 0. @MELWIN 2014-03-07 11:51:13 @ Chris Young : Where is the return value going to. And whats the use of the value returned? Can you explain that. or is it just to avoid undefined behaviour. @Ternvein 2015-01-09 11:02:31 @ MELWIN : Return value is passed to the host environment. Most of the time it would be your OS, which can pass this value to some other running process by request (e.g. system() call). @Trevor Boyd Smith 2015-05-15 14:27:57 Regarding "The standard defines 3 values for returning... 0, EXIT_SUCCESS, EXIT_FAILURE", is " 0, EXIT_SUCCESS, EXIT_FAILURE" actually part of the ISO-C and C++ specs? If yes, where in the specs? @Chris Young 2015-05-17 11:40:17 C11 §7.22p3 and §7.22.4.4p5. C++11 references the C standard library, but they're briefly mentioned in §18.5p3. @Lundin 2015-07-07 08:17:11 "If an implementation permits it, main can be declared in other ways, but this makes the program implementation defined, and no longer strictly conforming." Quotation needed. @KABoissonneault 2015-07-07 14:44:19 @Lundin I don't think you need a quote to say that someone is allowed to make a compiler that accepts non-standard-conforming programs, or to have a non-stardard-conforming compiler. That's common knowledge and common sense @Lundin 2015-07-08 07:00:16 @KABoissonneault Implementation-defined behavior is a term from the standard, as opposed to completely undocumented behavior. If you implement something that is listed as implementation-defined behavior, you still follow the standard. In this case C89 which was quoted, lists no such implementation-defined behavior, hence the need of quote, to prove that he is not just making things up out of the blue. @KABoissonneault 2015-07-08 12:07:07 @Lundin You're seeing this the wrong way. What we're talking about is not implementation-defined behavior, we're talking about an implementation deviating from the standard if they choose so. It's more like a child disobeying their parents: you don't need a quote from the parents to tell you in what way a child can go against what the parents said. You just know that the moment the child chooses to do so, they're no longer compliant with their parents' guildelines @Lundin 2015-07-08 12:33:57 @KABoissonneault The part I quoted in my comment is definitely about implementation-defined behavior (as opposed to non-standard compiler extensions.) Thus I am talking about implementation-defined behavior. If you are having a monologue about something else, best of luck with that. @KABoissonneault 2015-07-08 12:39:58 @Lundin I guess the wording in the quote is confusing (the part where they say "but this makes the program implementation defined") but I'm pretty sure the person was talking about non-standard behavior (as said in "If an implementation permits it" and "and no longer strictly conforming [to the standard]") as opposed to actual implementation defined behavior. The person should definitely reword their answer, but I still don't think a quote from the standard is necessary on that @chux 2017-12-01 16:33:58 "but this makes the program implementation defined, and no longer strictly conforming." --> Code is still conforming. Certainly less probable with a implementation defined signature. @programmersn 2019-06-21 17:33:42 main() must have an explicit return statement at the end to avoid undefined behaviour. : only holds for non-main functions. The C standard explicitly allows not to put the return statement for the main function, and states that in such a case a return 0will be automatically generated by the compiler. No UB is triggered in this case. Please see answers below for quotations from the standard. @Chris Young 2019-06-23 02:59:02 @programmersn the part you are quoting in my answer is about C90. If you continue to read the part below (C99) you will see I say that you can omit the return from main() as there's an implicit return 0. That's because this only was added to the standard since C99. @programmersn 2019-06-24 12:51:10 @Chris My bad I didn't see this part of the answer, jumped right away to conclusion. Could you please make any edit to the answer, just so that I may pull back the downvote. Thanx for the clarification anyway @rbaleksandar 2015-02-10 22:22:08 Here is a small demonstration of the usage of return codes... When using the various tools that the Linux terminal provides one can use the return code for example for error handling after the process has been completed. Imagine that the following text file myfile is present: When you execute the grep command a process is created. Once it is through (and didn't break) it returns some code between 0 and 255. For example: If you do you will get a 0. Why? Because grep found a match and returned an exit code 0, which is the usual value for exiting with a success. Let's check it out again but with something that is not inside our text file and thus no match will be found: Since grep failed to match the token "foo" with the content of our file the return code is 1 (this is the usual case when a failure occurs but as stated above you have plenty of values to choose from). Now the following bash script (simply type it in a Linux terminal) although very basic should give some idea of error handling: After the second line nothing is printed to the terminal since "foo" made grep return 1 and we check if the return code of grep was equal to 0. The second conditional statement echoes its message in the last line since it is true due to CHECK == 1. As you can see if you are calling this and that process it is sometimes essential to see what it has returned (by the return value of main()). @Jonathan Leffler 2019-02-16 18:54:26 In a shell script, you'd use if grep foo myfile; then echo 'Match found'; else echo 'No match was found'; fi— testing the return status directly. If you want to capture the status (for reporting, etc), then you do use an assignment. You might use if grep foo myfile; CHECK=$?; [ "$CHECK" = 0 ]; then echo 'Match found'; else echo 'No match was found'; fior you might use three lines. You might also use options -sand -qto grepto prevent the matches or routine error messages from appearing. However, this is shell minutiae — the key point, that the exit status can be useful — is OK. @Vamsi Pavan Mahesh 2012-11-23 07:29:29 Returning 0 should tell the programmer that the program has successfully finished the job. @Jonathan Leffler 2013-09-22 23:17:21 Returning 1 from main()normally signals an error occurred; returning 0 signals success. If your programs always fail, then 1 is OK, but it not the best idea. @Keith Thompson 2014-02-05 21:59:04 @JonathanLeffler: The meaning of returning 1from mainis implementation-defined. The only language-defined values are 0, EXIT_SUCCESS(often defined as 0), and EXIT_FAILURE. In OpenVMS, return 1;denotes successful termination. @Jonathan Leffler 2014-02-05 22:02:04 VMS is not 'normal' — within the meaning of what I said. Isn't it something like 'any odd value is success; even values are failure' on VMS? @fuddin 2011-07-01 23:30:59 The return value of main()shows how the program exited. If the return value is zeroit means that the execution was successful while any non-zero value will represent that something went bad in the execution. @Lundin 2015-07-07 08:18:44 This is a comment not an answer to the question. @Yochai Timmer 2011-07-01 16:32:34 The return value can be used by the operating system to check how the program was closed. Return value 0 usually means OK in most operating systems (the ones I can think of anyway). It also can be checked when you call a process yourself, and see if the program exited and finished properly. It's NOT just a programming convention. @Lundin 2015-07-07 08:18:26 There is nothing in the question indicating that an operative system is present. Returning a value doesn't make any sense in a freestanding system. @Luca C. 2011-03-03 11:56:57 If you really have issues related to efficiency of returning an integer from a process, you should probably avoid to call that process so many times that this return value becomes an issue. If you are doing this (call a process so many times), you should find a way to put your logic directly inside the caller, or in a DLL file, without allocate a specific process for each call; the multiple process allocations bring you the relevant efficiency problem in this case. In detail, if you only want to know if returning 0 is more or less efficient than returning 1, it could depend from the compiler in some cases, but generically, assuming they are read from the same source (local, field, constant, embedded in the code, function result, etc.) it requires exactly the same number of clock cycles. @phoxis 2011-03-10 14:11:33 What to return depends on what you want to do with the executable. For example if you are using your program with a command line shell, then you need to return 0 for a success and a non zero for failure. Then you would be able to use the program in shells with conditional processing depending on the outcome of your code. Also you can assign any nonzero value as per your interpretation, for example for critical errors different program exit points could terminate a program with different exit values , and which is available to the calling shell which can decide what to do by inspecting the value returned. If the code is not intended for use with shells and the returned value does not bother anybody then it might be omitted. I personally use the signature int main (void) { .. return 0; .. } @Lundin 2017-12-15 13:42:29 The format of main() is determined by the implementation, meaning compiler. The programmer does not get chose which form to pick, except when a compiler supports several forms. @phoxis 2017-12-18 19:32:53 @Lundin The return type will be implementation by the implementation. But the value which to be returned is decided by the programmer. C99 Section 5.1.2.2.3 mentions that the return type of mainis compatible with int. Therefore returning intwill not be a problem. Although other return types are allowed, but in that case the environment variable having the return value will be unspecified. But If a programmer does return 0;then in bash it can be used to make branches. @dmityugov 2008-10-15 12:33:14 I believe that main()should return either EXIT_SUCCESSor EXIT_FAILURE. They are defined in stdlib.h @dmityugov 2008-10-15 13:28:28 gnu.org/software/libc/manual/html_mono/libc.html#Exit-Status @Chris Young 2008-10-16 14:46:08 0 is also standard. @fuz 2014-09-17 10:45:32 @ChrisYoung There is EXIT_SUCCESSand EXIT_FAILUREbecause some historic operating systems (VMS?) used a different number than 0 to denote success. It's 0 everywhere nowadays. @Chris Young 2014-10-22 09:43:25 @FUZxxl you're correct, but that's not in conflict with my comment. EXIT_SUCCESS can indeed be nonzero, but the standards (C89, C99, C11) all define 0 (as well as EXIT_SUCCESS) to also be an implementation-defined form of the status successful termination. @fuz 2014-10-22 09:48:15 @ChrisYoung Thank you for correcting me. I was apparently wrong. @Lundin 2015-07-07 08:15:12 While this comment is correct and valuable, it does not answer the question. @Adrian McCarthy 2016-11-17 00:19:33 @FUZxxl: It's true the VMS used odd values (like 1) to indicate success and even values (like 0) to indicate failure. Unfortunately, the original ANSI C standard was interpreted to mean that EXIT_SUCCESS had to be 0, so returning EXIT_SUCCESS from main got exactly the wrong behavior on VMS. The portable thing to do for VMS was to use exit(EXIT_SUCCESS), which always did the right thing. @Lundin 2017-12-15 13:38:38 5.1.2.2.3 "If the return type of the main function is a type compatible with int, a return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument;11) reaching the } that terminates the main function returns a value of 0." @Lundin 2017-12-15 13:38:41 And then 7.22.4.4. about the exit function: "If the value of status is zero or EXIT_SUCCESS, an implementation-defined form of the status successful termination is returned. If the value of status is EXIT_FAILURE, an implementation-defined form of the status unsuccessful termination is returned. Otherwise the status returned is implementation-defined." @Ferruccio 2008-10-15 15:22:13 Keep in mind that,even though you're returning an int, some OSes (Windows) truncate the returned value to a single byte (0-255). @Leon Timmermans 2008-10-16 16:34:27 Unix does the same, as do most other operating systems probably. I know VMS does such incredible weird things with it that returning anything other than EXIT_SUCCESS or EXIT_FAILURE is asking for trouble. @user824425 2015-01-05 10:16:29 MSDN begs to differ: when reported through mscorlib, an exit code is a signed 32-bit integer. This seems to imply that the C runtime libraries that truncate exit codes are defective. @John McFarlane 2017-07-29 20:58:02 Yes, this is incorrect. On Windows a 32-bit integer is returned (and converted to unsigned). This is the same on UNIX systems with 32-bit integers. But UNIX-style shells on either system will typically only retain an unsigned 8-bit integer. @graham.reeds 2008-10-15 12:42:47 I was under the impression that standard specifies that main doesn't need a return value as a successful return was OS based (zero in one could be either a success or a failure in another), therefore the absence of return was a cue for the compiler to insert the successful return itself. However I usually return 0. @Jonathan Leffler 2013-07-18 05:56:16 C99 (and C++98) allow you to omit the return statement from main; C89 does not allow you to omit the return statement. @Lundin 2015-07-07 08:15:39 This is a comment not an answer. @Steve Lillis 2015-07-07 09:15:42 This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. @graham.reeds 2015-07-07 11:08:13 @SteveLillis: In 2008 SO didn't have a comment section. @Lou Franco 2008-10-15 12:16:51 Return 0 on success and non-zero for error. This is the standard used by UNIX and DOS scripting to find out what happened with your program.
https://tutel.me/c/programming/questions/204476/what+should+main+return+in+c+and+c
CC-MAIN-2019-43
refinedweb
7,147
62.58
Hi Hi I need some help I've got my java code and am having difficulty... = new Scanner(System.in); System.out.print("Enter the letter type: "); String type...) { throw new UnsupportedOperationException("Not yet implemented"); } private hi! hi! how can i write aprogram in java by using scanner when asking... to to enter, like(int,double,float,String,....) thanx for answering.... Hi... main(String[] args) { Scanner input=new Scanner(System.in - Java Beginners hi hi sir,create a new button and embed the datepicker code to that button sir,plzzzzzzzzzzzzzzzzzzzzzzzzzzz hi - Java Beginners ; Hi anjali, class ploy { public void ployTest(int x... PolymorphismText{ public static void main(String args[]){ ploy p = new ploy...); } } ------------------------------------------------- Read for more information., I want to write code in java for change password please provide the code change password have three field old_pwd,new_pwd,con_pwd Thanks Hi Friend, Create a database table login[id hi - Java Beginners information. Thanks. Hi...hi Hi.... let me know the difference between object and instance variables with examples.... Hi friend, Objects are key hi - Java Beginners hi hi sir,good afternoon, i want to add a row in jtable when i am... the program sir,urgent Thank u Hi Friend, Try...) { new InsertRows(); } public InsertRows(){ JFrame frame = new New To JAVA - Java Beginners New To JAVA hi iam new to java..,can you please guide me how to learn the java and also tell me how many days it takes to learn java Hi... will get more information about java. Read more detail. http hi - Java Beginners ("Frame in Java Swing"); f.getContentPane().setLayout(null); l=new JLabel...hi hi sir,Thanks for ur coporation, i am save the 1 image...,plzzzzzzzzzz i have a panel that allows user to enter new customer,i am save hi - Java Beginners hi hi sir, i am entering the values to jtable at run time... the table ,plz provide the solution for me . Hi Friend, Try the following...) { new InsertJTableDatabase(); } public InsertJTableDatabase,how to place the database records into jtable ,i am using... and placed into a jtable plzzzzzzzzzzzzzzz Hi Friend...[] args) { Vector columnNames = new Vector(); Vector data hi - Java Beginners hi hi sir,i want to use the variable in 1 class to another class,how we use the 1 class variable in another class, Thanq Hi... class TestABC { public static void main (String [] arg) { ABC test=new ABC Hi... - Java Beginners Hi... I want to write code for change password from data base please... java bean file for setting and getting and other is .jsp file this file... Old Password * New Password hi - Java Beginners hi hi sir,i want a program for when i am place the mouse..., plz provide the solution sir Hi Friend, Try the following code... TextFieldEvent extends JFrame { TextFieldEvent(){ JLabel label=new JLabel hi - Java Beginners hi hi sir,thanks for providing the datepicker program but i want... in more times ,plz provide sir Thanks in advance Hi... code wherever you want to call the date picker: setText(new DatePicker(f hi - Java Beginners Sorting String Looking for an example to sort string in Java. ... args[]) { new ShortString().doit(); } public void doit(){ try { Writer writer = new BufferedWriter(new OutputStreamWriter(System.out, "Cp850" hi - Java Beginners hi hi sir,when i am enter a one value in jtextfield the related... phone no sir Hi Friend, Try the following code: import... JTextField tf; private final JComboBox combo = new JComboBox hi again - Java Beginners hi again i did the changes on the code but still the time.../java/thread/thread-creation.shtml code after changing.. import java.io.... s="0"; String s1=null; MyThread1(String s2){ s1=s2; t=new Thread HI - Java Beginners case & also i do subtraction & search dialognal element in this. Hi...{ public static void main(String[] args) { int[][] a2 = new int[10][5 hi - Java Beginners hi how to create a table by using jtable jt=new jtable(5,5..."}; Object[][] data = new Object[5][7]; JTable jTable = new JTable...); jTable.setModel(new DefaultTableModel(data, columnNames)); add hi - Java Beginners hi hi sir,u provide a answer for datepicker,but i don't know how... ; JPanel p=new JPanel(); String mon=null...; String issuedamttotal,receivedamttotal; JPanel jp=new Hi... - Java Beginners Hi... Hi friends I want to make upload file module please...; Hi Friend, Try the following code: 1)page.jsp: Display file...-data") >= 0)) { DataInputStream in = new DataInputStream hi - Java Beginners ); JLabel cus,fa,city; JButton jb,jb1; Font f=new Font("Times New Roman",Font.ITALIC,14); cus=new JLabel("Enter Customer name:"); final JTextField cname=new JTextField(20); cname.setBounds(250,200,150,25 hi - Java Beginners hi hi sir,when i am add a jtable record to the database by using... and resolve this sir,plzzzzzz submit=new JButton("SUBMIT...); submit.setVisible(false); submit.addActionListener(new Hi.. - Java Beginners Hi.. Hi friends, I want to display two calendar in my form... is successfully but date of birth is not why... Hi Friend, Try... 2)calendar.js: var cal; var todayDate=new Date(); var Cal; var hi - Java Beginners public static void main(String[] args) { FinalExample finalExample = new NEW IN JAVA - Java Beginners NEW IN JAVA Suppose you are asked to design a software tool... should display "Please ask your teacher for help". Hi Friend, Try... static void main(String[] args) throws Exception { Scanner scan = new Scanner New to Java Please help New to Java Please help Hi I need help, can some one help me.... Thanks! If you are new in java, then you need to learn core java concepts.So go through the following link: Core Java Tutorials Here, you will...********** //*******Java bean ********** .Again me.. - Java Beginners Hi .Again me.. Hi Friend...... can u pls send me some code...... REsponse me.. Hi friend, import java.io.*; import java.awt.... args[]){ JFrame frame = new JFrame("Button Group Hi..Date Program - Java Beginners Hi..Date Program Hi Friend...thank for ur Valuable information... OF DAYS BY EACH MONTH... Hi friend, Code to solve the problem...; BufferedReader in = new BufferedReader(new InputStreamReader(System.in hi - Java Server Faces Questions hi Hi sir,my programe is this,the purpose is i am add my table... javax.swing.table.*; public class New extends JPanel { JPanel CUSTOMER,INTRODUCER,ITEMS; //Border redline; public New() { setLayout(null); CUSTOMER=new im new to java - Java Beginners im new to java what is the significance of public static void main(string args[])statement Hi Friend, This statement is necessary for a java class to execute it as a command line application. public- It provide hi - Swing AWT hi sir,how to set a title for jtable plz tell me sir Hi...(EXIT_ON_CLOSE); JTable jt = new JTable(new String[][] { {"A", "Delhi"}, {"B", "Mumbai"} }, new String[] {"Name", "Address hi - Date Calendar hi sir,i am do the project on swings,i want a datepicker in java,how... ThanQ Hi Friend, Try the following code... DatePicker { JButton[] button = new JButton[49]; int month Hi, Hi, labels = new Hashtable<Integer,JLabel> Hi Hi Hi All, I am new to roseindia. I want to learn struts. I do not know anything in struts. What exactly is struts and where do we use it. Please help me. Thanks in advance. Regards, Deep've a project on railway reservation... i need to connect... for such a programme... plz help me... Hi Friend, Try this: import java.awt.... Retrieve{ public static void main(String[] args){ JFrame f=new JFrame ..I am Sakthi.. - Java Beginners tabbedPane = new JTabbedPane(); Component panel1 = makeTextPanel("Java...Hi ..I am Sakthi.. can u tell me Some of the packages n Sub... that is available in java and also starts with javax. package HEMAL RAJYAGURU  ...(OutputKeys.INDENT, "yes"); StringWriter sw = new StringWriter(); StreamResult result = new StreamResult(sw); DOMSource source = new hi.. hi.. I want upload the image using jsp. When i browse the file... IS ::::::::::::::::::::twad9315.jpg ARR is=[Ljava.lang.String;@65531d2c New Strign is: twad9315.jpg... IS ::::::::::::::::::::"+browsefile); String newstr=""; String relpath=""; String[] arr=new String[10 hi.. hi.. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional...); String newstr=""; String relpath=""; String[] arr=new String[10]; arr...+"../"; } relpath=newstr+arr[arr.length-1]; System.out.println("New Strign hi roseindia - Java Beginners hi roseindia what is java? Java is a platform independent.... Object Oriented Programming structre(OOPS) concepts are followed in JAVA as similar to C++. But JAVA has additional feature of Database connectivity, Applets hi i want to develop a online bit by bit examination process as part of my project in this i am stuck at how to store multiple choice questions...: result.jsp: <%@page import="java.sql.*"%> <% String st[]=new String[10 hi friend hi friend what is code for ``find no of days difference in the date of birth of two students using inner class in java Hi da SAKTHI ..check thiz - Java Beginners Hi da SAKTHI ..check thiz package bio;//LEAVE IT import java.lang....=new ImageIcon("f:\\2LEAVES.jpg");img2=new ImageIcon("f:\\Q1.jpg");img3=new ImageIcon("f:\\jp.jpg"); img4=new ImageIcon("f:\\j2.gif");img5=new ImageIcon("f hi - Java Beginners hi hi sir, i am entering the 2 dates in the jtable,i want to difference between that dates,plz provide the suitable example sir Hi Friend, Please visit the following links: hi, - Java Beginners hi, what is the need for going to java.how java differ form .net.What is the advantage over .net.Is there any disadvantage in java Hi Friend, Difference between java and .net: 1)Java is developed by Sun hi sir - Java Beginners hi sir Hi,sir,i am try in netbeans for to develop the swings,plz... the details sir, Thanks for ur coporation sir Hi Friend, Please visit the following link: hi sakthi prasanna here - Java Beginners hi sakthi prasanna here import java.lang.*; import java.awt....(0,0,800,600); setDefaultCloseOperation(EXIT_ON_CLOSE); img1=new ImageIcon("f:\\2LEAVES.jpg"); img2=new ImageIcon("f:\\Q1.jpg"); img3=new ImageIcon("f:\\jp.jpg... Separately... Reply me .... Thanku Hi friend, Code to solve... static void main(String args[]){ DateDifference difference = new Hi Friend ..Doubt on Exceptions - Java Beginners Hi Friend ..Doubt on Exceptions Hi Friend... Can u please send... OverFlow Exception.. Thanks... Sakthi Hi friend, Code... { public static void main(String[] args) { String strAr[] = new String[4 New to Java - New to java tutorial Technical description of Java Mail API This section introduces you with the core concepts of Java Mail API. You must understand the Java Mail API before actually delving
http://www.roseindia.net/tutorialhelp/comment/44429
CC-MAIN-2014-10
refinedweb
1,754
68.36
Practical .NET. This column is the practical one: How to write tests with xUnit. First Steps As with the other testing frameworks that are part of Visual Studio, your first step in creating xUnit tests is to use Add > New Project to add a testing project (you can do that either from Visual Studio's File menu or from the popup menu you get from clicking on your Solution in Solution Explorer). In the Add New Project dialog in Visual Studio 2017, under the Test node on the left, you'll find four choices. You want the xUnit project -- cleverly called xUnit Test Project (.NET Core). That choice will give you a project with a default class (UnitTest1), which you'll want to rename. As usual, you'll need to add a reference to your test project that points to the project with the code you want to test. Also as usual, you should right-click on your test project, select Manage NuGet Packages and check for any upgrades to NuGet packages that make up your project. Just to make my point, all three of the test-related packages for my sample project had pending upgrades. Currently, there is no template for test classes so, to add a new test class to your test project, you'll need to add a new class, make the class public and then insert this using statement at the top of the class: using Xunit; Your First Test To write a test you simply create a public method that returns nothing and then decorate it with the Fact attribute. Inside that method you can put whatever code you want but, typically, you'll create some object, do something with it and then check to see if you got the right result using a method on the Assert class. In other words, pretty much what you did with Visual Studio Test. This example instantiates a class called Customer, calls its ChangeName method and then checks to see if the related property was correctly changed: [Fact] public void ChangesCustomerName() { Customer cust = new BlazorViewModel(); cust.ChangeName("Peter"); Assert.Equal("Peter", cust.Name); } In addition to the Fact attribute, you can also use the Theory attribute on test methods. Theory runs a test method multiple times, passing different data values each time. You have a variety of tools for setting the data values to be passed to your test method. For example, by combining Theory with the InlineData attribute, you can pass an array of values to the test method. xUnit will run the test once for each InlineData attribute. This code, for example, passes in three invalid customer names and checks that the ChangeName method throws an InvalidNameException for each value: [Theory] [InlineData("p")] [InlineData("O;Malley")] [InlineData("O,Malley")] public void CatchInvalidCustomerName(string name) { BlazorViewModel bvm = new BlazorViewModel(); Assert.Throws(() => bvm.ChangeName(name)); } InlineData works great if your test values will be used in only one test method. If you have multiple methods in the same class that can use your values, the MemberData attribute lets you use a static method on your test class to provide test values to multiples methods in the test class. If you have test values that can be used in multiple test classes, the ClassData attribute allows you to specify a class that will pass a "collection of collections" to your test method. Additional Options xUnit provides several customization tools. By default in the Test Explorer window, all your tests will be listed by the method name. If you want, you can override that by setting the Name property on your Fact attribute -- often a good idea to improve readability. This example changes the name of the test in Test Explorer to "Customer Name Update": [Fact(Name = "Customer Name Update"] public void ChangesCustomerName() { There are also times when you'll want to turn off a test (typically because the test is always failing for some reason you can't address right now and the resulting red lights in Test Explorer keep scaring you). To turn off a test method, set the Skip property on the Fact attribute to the reason that you've turned the test off (unfortunately the reason isn't currently displayed in Test Explorer). This example notes that the test is turned off until the test data is cleaned up: [Fact(Skip ="Test data not available")] public void ChangesCustomerName() { InlineData and Theory also support the Skip option. As the number of your tests increases you may want to organize them into groups so you can run tests together. The Trait attribute lets you organize tests into groups by creating category names and assigning values to them. This example creates a category called Customer with the value "Update": [Fact(DisplayName = "Change Name2")] [Trait("Customer", "Update")] public void ChangesCustomerName() { In Test Explorer this test will appear under the heading Customer [Update] (each Name/Value combination appears as a separate heading in Test Explorer). Unfortunately, there's no way to run all the tests in a category (for example, all the "Customer" tests). Running Your Tests All the mechanisms you have for running tests using the other Visual Studio test frameworks are available in xUnit ... but they run with one significant difference. By default, xUnit runs tests in different test classes in parallel, which can significantly shorten the time to run all your tests. It also means that xUnit effectively ignores the Run Tests in Parallel setting at the top of the Test Explorer window. You can, however, override this default behavior where you need tests in different classes to run sequentially by assigning test classes to the same collection. You assign tests to a collection using the Collection attribute, passing a name for the collection. This code assigns both the PremiumCustomerTests and the CashOnlyCustomerTests test classes to a collection called Customer Updates, ensuring that the tests in the two classes aren't run in parallel: [Collection("Customer Updates")] public class PremiumCustomerTests { ... //test methods ... } [Collection("Customer Updates")] public class CashOnlyCustomerTests { ... //test methods ... } And that's everything you need to know to start using xUnit. You've probably noticed that, at the code level, writing xUnit tests isn't that much different from what you do with the testing tools you're using right now. Well, except for one thing: initializing your test environment. That's very different from the way it's handled in Visual Studio Test, so I'll cover that
https://visualstudiomagazine.com/articles/2018/11/01/xunit-tests-in-net-core.aspx?admgarea=ALM
CC-MAIN-2021-17
refinedweb
1,072
55.58
Are you sure? This action might not be possible to undo. Are you sure you want to continue? Cat. No. 15103C Department of the Treasury Internal Revenue Service Contents Introduction ........................................ Domicile .............................................. 1 2 2 2 3 3 3 4 5 7 8 9 Community Property For use in preparing Community or Separate Property and Income .......................................... Community Property Laws Disregarded ............................. End of the Marital Community .......... Federal Income Tax Return Preparation .................................. Joint Return Versus Separate Returns .................................... Identifying Income and Deductions Example .......................................... Allocation Worksheet ........................ How To Get More Information .......... Index .................................................... 1998 Returns Introduction This publication is for married taxpayers who are domiciled in one of the following community property states: • • • • • • • • • Arizona, California, Idaho, Louisiana, Nevada, New Mexico, Texas, Washington, or Wisconsin. This publication does not address the federal tax treatment of income or property subject to the “community property” election under the Alaska state laws. Community property laws affect how you figure your income on your federal income tax return if you are married, live in a community property state or country, and file separate returns. Your tax usually will be less by filing a joint return if you are married.. See Death of spouse, later. Useful Items You may want to see: Publication 504 505 Divorced or Separated Individuals Tax Withholding and Estimated Tax See How To Get More Information near the end of this publication for information about getting these publications. Table 1. General Rules — Property and Income: Community or Separate? Community property is property: ● That you, your spouse, or both acquire during your marriage while you are domiciled in a community property state. Includes the part of property bought with community funds, if part was bought with community funds and part, with separate funds. ● That you and your spouse agreed to convert from separate to community property. ● That cannot be identified as separate property. Separate property is: ● Property that you or your spouse owned separately before marriage. ● Money earned while domiciled in a noncommunity property state. ● Property either of you were given or inherited separately after marriage. ● Property bought with separate funds, or exchanged for separate property, during the marriage. ● Property that you and your spouse agreed to convert from community to separate property in an agreement valid under state law. ● The part of property bought with separate funds, if part was bought with community funds and part, with separate funds. Community income 1, 2 is income from: Separate income 1, 2 is income from: ● Community property. ● Salaries, wages, or pay for the services of you, your spouse, or both during your marriage. ● Real estate that is treated as community property under the laws of the state where the property is located. 1 2 ● Separate property. It belongs to the spouse who owns the property. Caution: In Idaho, Louisiana, Texas, and Wisconsin, income from most separate property is community income. Caution: Check your state law if you are separated but do not meet the conditions discussed later in Spouses living apart all year. In some states, the income you earn after you are separated and before a divorce decree is issued continues to be community income. In other states, it is separate income. • Innocent spouse relief (applies to all joint Domicile: Community or Separate Property and Income The laws of the state in which you are domiciled generally govern whether you have community property and community income or separate property and separate income for federal tax purposes. Table 1 summarizes the general rules. filers). • An election to allocate a deficiency (applies to joint filers who are divorced, widowed, legally separated, or have not lived together for the past 12 months). • Equitable relief (applies to all joint filers and married couples filing separate returns in community property states). You must generally follow community property laws when filing a tax return if you are married and live in a community property state. Generally, community property laws require you to allocate community income and expenses equally between both spouses. However, community property laws are not taken into account in determining whether an item belongs to you or your spouse (or former spouse) for purposes of requesting any relief from liability. To request relief from tax liability that you believe should be paid only by your spouse (or former spouse), you must file Form 8857. Also see Publication 971.. Community Property Laws Disregarded The following discussions are situations where special rules apply to community property. Certain community income. Community property laws do not apply to an item of community income and you are responsible for reporting all of it if: 1) You treat the item as if only you are entitled to the income, and 2) You do not notify your spouse of the nature and amount of the income by the due date for filing the return (including extensions). Innocent spouse relief. In some cases, one spouse may be relieved of joint liability of tax, interest, and penalties due on a joint tax return for items of the other spouse that were incorrectly reported on the joint return. You can request innocent spouse relief for an understatement of tax no matter how small the amount. There are three types of relief available. • • • • • • Where you pay state income tax, Where you vote, Location of property you own, Your citizenship, Length of residence, and. Note. When this publication refers to where you live, it means your domicile. Page 2 Spouses living apart all year. If you are married at any time during the calendar year, special rules apply for reporting certain community income. You must meet all the following conditions. 1) You and your spouse lived apart all year. 2) You and your spouse did not file a joint return for a tax year beginning or ending in the calendar year. 3) You and/or your spouse had earned income for the calendar year that is community income. 4) You and your spouse did not transfer, directly or indirectly, any of the earned income in (3) between yourselves before the end of the year. Do not take into account transfers of very small amounts or value. Also, do not take into account a payment or transfer to or for your dependent child, even though the payment or transfer satisfies an obligation of support imposed on your spouse. ÷. quired will be separate property. Such an agreement may end the community. In some states, the marital community ends when the husband and wife permanently separate, even if there is no formal agreement. Check your state law. Federal Income Tax Return Preparation The following discussion does not apply to spouses who meet the conditions under Spouses living apart all year, discussed earlier. Those spouses must report their community income as explained in that discussion. End of the Marital Community The marital community may end in several ways. When the marital community ends, the community assets (money and property) are divided between the spouses. Death of spouse. In community property states, each spouse usually is considered to own half the estate (excluding separate property). If your spouse died, the total value of the community property, including the part that belongs to you, generally becomes the basis of the entire property. For this rule to apply, at least half the community property interest must be includible in your spouse's gross estate, whether or not the estate must file a return. For example, when Bob died, at least half the fair market value of his and Ann's community interest was includible in Bob's estate. The fair market value of their total community property was $100,000. The basis of Ann's half of the property is $50,000. The basis of the other half to Bob's heirs is also $50,000. For more information about the basis of assets, see Publication 551, Basis of Assets. Divorce or separation. The division of community property in connection with a divorce or property settlement does not result in a gain or loss. For information on the tax consequences of the division of community property under a property settlement or divorce decree, see Publication 504. Each spouse is taxed on half the community income for the part of the year before the community ends. However, see Spouses living apart all year, earlier. Any income received after the marital community ends is separate income. This separate income is so-called “marriage.” Check your state law. A decree of legal separation or of separate maintenance may or may not end the marital community. The court in the state issuing the decree may terminate the marital community and divide the property between the spouses. Check your state law. A separation agreement may divide the community property between you and your spouse. It may provide that this property along with future earnings and property ac- Joint Return Versus Separate Returns Ordinarily, filing a joint return will give you the greater tax advantage. But in some cases, your combined income tax on separate returns may be less than it would be on a joint return. You can file separate returns if you and your spouse do not agree to file a joint return or if separate returns result in less tax. However, if you file separate returns: 1) You should itemize deductions if your spouse itemizes deductions, because you all of 1998, 6) You may have to include in income more of the social security benefits (including any equivalent railroad retirement benefits) you received in 1998 than you would on a joint return, 7) You cannot deduct interest paid on a qualified student loan, 8) You cannot take the education credits (the Hope and lifetime learning credits), 9) You may have a smaller child tax credit than you would on a joint return, and 10) You cannot take the exclusion or credit for adoption expenses in most instances. Figure your tax on both a joint return and separate returns under the community property laws of your state. Compare the tax figured under both methods and use the one that results in less tax. If you file separate returns, you and your spouse must each report half your combined community income and deductions in addition to your separate income and deductions. List only your share of the income and deductions on the appropriate lines of your separate tax returns (wages, interest, dividends, etc.). Attach a worksheet to your separate returns showing how you figured the income, deductions, and federal income tax withheld Page 3: Daniel Sharon Wages ......................................... $20,000 $22,000 Consulting business fees ............ 5,000 Partnership income ..................... 10,000 Dividends from separate property ...................................................... 1,000 2,000 Interest from community property ...................................................... 500 500 Total $26,500 $34,500 that each of you reported. The allocation worksheet. An extension of time for filing your separate return does not extend the time for filing your spouse's separate return. If you and your spouse file a joint return, you cannot file separate returns after the due date for filing either separate return has passed. Lump-sum distributions. If you receive a lump-sum distribution from a qualified retirement plan, you may be able to choose optional methods of figuring the tax on the distribution. For the 5-year or 10-year tax option, you must disregard community property laws. For information, see Publication 575, Pension and Annuity Income, and Form 4972, Tax on Lump-Sum Distributions. Gains and losses. (Business and Nonbusiness), for information on losses due to a casualty or theft. Business and investment expenses. If you file separate returns, expenses incurred to earn or produce: rest. They cannot divide the total exemption amount for their three children ($8,100) equally. Self-employment tax. If any income from a trade or business other than a partnership is community income under state law, it is subject to self-employment tax as the income of the spouse carrying on the trade or business. Partnership income. If you are a partner and your distributive share of any income or loss from a trade or business carried on by the partnership is community income, treat the share as your net earnings from selfemployment. No part is treated as net earnings from self-employment by your spouse. If both you and your spouse are partners, each of you must claim your share when figuring net earnings from selfemployment for self-employment tax purposes. Child tax credit. Beginning in 1998, you may be entitled to a child tax credit for each of your qualifying children. You must provide the name and identification number (usually the social security number) of each qualifying child on your return. The maximum amount of the credit you can claim for each qualifying child is $400 ($500 in 1999). Limit on credit. The credit is limited if your modified adjusted gross income (modified AGI) is above a certain amount. The amount at which the phaseout begins depends on your filing status. Generally, your credit is limited to your tax liability unless you have 3 or more qualifying children. See the Form 1040 Instructions for more information. Earned income credit. For the earned income credit, compute your earned income without regard to community property laws. You cannot claim this credit if your filing status is married filing separately. For more information about the credit, see Publication 596, Earned Income Credit. Withholding tax.. Overpayments. Overpayments are allocated under the community property laws of the state in which you are domiciled. Identifying Income and Deductions To figure the best way to file your return — jointly or separately — first identify your community and separate income and deductions according to the laws of your state.. Military retirement pay. State community property laws apply to military retirement pay. Generally, the pay is either separate or community income based on the marital status and domicile of the couple while the member of the Armed Forces was in active military service. Pay earned while married and domiciled in a community property state is community income. This income is considered to be received half by the member of the Armed Forces and half by the spouse. Civil service retirement. For income tax purposes, community property laws apply to annuities payable under the Civil Service Retirement Act (CSRS) or Federal Employee Retirement System (FERS). Whether a civil service annuity is separate or community income depends on the marital status and domiciled in a community property state. If a civil service annuity is a mixture of community income and separate income, it must be divided between the two kinds of income. The division is based on the employee's domicile and marital status in community and noncommunity property states during his or her periods of service. • Community business or investment income are generally divided equally between you and your spouse. Each of you is entitled to deduct one-half of the expenses on your separate returns, or • Separate business or investment income are deductible by the spouse who earns the income. Other limits may also apply to business and investment expenses. For more information, see Publication 535, Business Expenses, and Publication 550, Investment Income and Expenses. Personal expenses. Expenses that are paid out of separate funds, such as medical expenses, are deductible by the spouse who pays them. If these expenses are paid from community funds, divide the deduction equally between you and your spouse. Individual retirement arrangements (IRAs). There are several kinds of individual retirement arrangements (IRAs) for 1998. They are traditional IRAs, including SEP IRAs, and SIMPLE IRAs, Roth IRAs, and education IRAs. Community property laws do not apply to IRAs. See Publication 590, Individual Retirement Arrangements (IRAs) (Including Roth IRAs and Education IRAs) for the rules that govern IRAs. Personal exemptions and dependents. When you file separate returns, you must claim your own exemption ($2,700 in 1998). You cannot divide the amount allowed as an exemption for a dependent between you and your spouse. When community funds provide over half of the support for more than one person who otherwise qualifies as a dependent, you and your spouse may divide the number of dependency exemptions. • If community property is subject to premarital or other separate debts of either spouse, the full joint overpayment may be used to offset the obligation. • If community property is not subject to premarital or other separate debts of either spouse, the portion of the joint overpayment allocated to the spouse liable for the obligation can be used to offset that liability. The portion allocated to the other spouse can be refunded. Estimated tax. In determining whether you must pay estimated tax, apply the estimated tax rules to your estimated income. These rules are explained more fully in Publication 505. If you think you may owe estimated tax and want to pay the tax separately, determine whether you must pay it by taking into account:. Page 4 the exemptions for the 1) Half the community income and deductions, 2) All of your separate income and deductions, and 3) how to divide it, the estimated tax you can claim equals the total estimated tax paid times the tax shown on your separate return, divided by the total of the tax shown on your return and your spouse's return. Example Walter and Mary Smith are married and domiciled in a community property state. Their two minor children and Mary's mother live with them and qualify as their dependents. Amounts paid for their support were paid out of community funds. Walter received a salary of $38,160. Income tax withheld from his salary was $3,360. Walter received $94 in taxable interest from his savings account. He also received $155 in dividends from stock that he owned. His interest and dividend income is his separate income under the laws of his community property state. Mary received $140 in dividends from stock that she owned. This is her separate income. In addition, she received $3,000 as a part-time dental technician. No income tax was withheld from her salary. The Smiths paid a total of $3,850 in medical expenses. Medical insurance of $700 was paid out of community funds. Walter paid $3,150 out of his separate funds for an operation he had. The Smiths also can claim the child tax credit. The Smiths had $6,842 in other itemized deductions, none of which were miscellaneous itemized deductions subject to the 2% adjusted gross income limit. The amounts spent for these deductions were paid out of community funds. To see if it is to the Smiths' advantage to file a joint return or separate returns, a worksheet (shown next) is prepared to figure their federal income tax both ways. Walter and Mary must claim their own exemptions on their separate returns. The summary at the bottom of the worksheet compares the tax figured on the Smiths' joint return to the tax figured on their separate returns. The result is that by filing separately under the community property laws of their state, the Smiths save $184 on Walter's savings account and the dividends from stock owned by each of them would be divided equally on their separate returns. Page 5 Separate Returns Joint Return Income (Walter’s): Salary Interest and dividends ($155 dividends Total Walter’s Mary’s $94 interest) $ 38,160 249 $ 38,409 $ 19,080 249 $ 19,329 $ 19,080 -0$ 19,080 Income (Mary’s): Salary Dividends Total $ 3,000 140 3,140 $ 1,500 -01,500 $ 1,500 140 1,640 Adjusted gross income (AGI) Deductions (Community) Not subject to the 2% AGI limit Deductions (Medical): Premiums Medical expenses (Walter’s) Total $ 41,549 $ $ $ 700 3,150 3,850 6,842 $ $ 350 3,150 3,500 $ 20,829 $ 3,421 $ $ 350 -0350 $ 20,720 $ 3,421 (Minus) 7.5% of AGI Medical expense deduction Total deductions Subtract total deductions from AGI1 (Minus) exemptions2 Taxable income Tax 3 4 (3,116) $ $ 734 7,576 (1,562) $ $ 1,938 5,359 (1,554) $ $ -03,421 $ 33,973 $ (13,500) $ 20,473 $ (800) (3,360) $ 4,160 3,071 (400) (1,680) $ 15,470 $ (5,400) $ 10,070 $ 1,511 (400) (1,680) $ 2,080 $ 17,299 $ (8,100) $ $ 9,199 1,376 (Minus) child tax credit (Minus) federal income tax withheld Total $ 2,080 (Overpayment) 1 $ (1,089) $ (569) $ (704) The itemized deductions are greater than the standard deduction of $7,100 for married filing jointly and $3,550 for married filing separately. Note: If one spouse itemizes, the other must itemize, even if one spouse’s deductions are less than the standard deduction. An allowance of $2,700 for each exemption claimed is subtracted—5 on the joint return, 2 on Walter’s separate return, and 3 on Mary’s separate return. 3 The tax on the joint return is from the column of the Tax Table for married filing jointly. The tax on Walter’s and Mary’s separate returns is from the column of the Tax Table for married filing separately. 4 A credit of $400 for each qualifying child is subtracted—2 on the joint return, 1 on Walter’s separate return, and 1 on Mary’s separate return. 2 Table 2. Summary Tax on joint return Tax on Walter’s separate return Tax on Mary’s separate return Total tax filing separate returns Total savings by filing separate returns $3,071 $1,511 1,376 2,887 $ 184 Page 6 Table 3. Allocation Worksheet 1 Total Income (Community/Separate) 1. Wages (each employer) 2 Allocated to Husband 3 Allocated to Wife 2. Interest Income (each payer) 3. Dividends (each payer) 4. State Income Tax Refund 5. Capital Gains and Losses 6. Pension Income 7. Rents, Royalties, Partnerships, Estates, Trusts 8. Taxes Withheld 9. Other items such as: Social Security Benefits, Business & Farm Income or Loss, Unemployment Compensation, Mortgage Interest Deduction, etc. NOTES Page 7 How To Get More Information You can order free publications and forms, ask tax questions, and get more information from the IRS in several ways. By selecting the method that is best for you, you will have quick and easy access to tax help.: information by calling 703–368–9694. Follow the directions from the prompts. When you order forms, enter the catalog number for the form you need. The items you request will be faxed to you. IRS offices. Some libraries and IRS offices have an extensive collection of products available to print from a CD-ROM or photocopy from reproducible proofs. Phone. Many services are available by phone. • Ordering forms, instructions, and publications. Call 1–800–829–3676 to order current and prior year forms, instructions, and publications. Mail. You can send your order for forms, instructions, and publications to the Distribution Center nearest to you and receive a response 7 to 15 workdays after your request is received. Find the address that applies to your part of the country. • Western part of U.S.: Western Area Distribution Center Rancho Cordova, CA 95743–0001 • Asking tax questions. Call the IRS with your tax questions at 1–800–829–1040. to listen to pre-recorded messages covering various tax topics. • Eastern part of U.S. and foreign addresses: Eastern Area Distribution Center P.O. Box 85074 Richmond, VA 23261–5074 • Frequently Asked Tax Questions to find answers to questions you may have. • Fill-in Forms to complete tax forms online. • Forms and Publications to download forms and publications or search publications by topic or keyword.. CD-ROM. You can order IRS Publication 1796, Federal Tax Products on CD-ROM, and obtain: • Digital Dispatch and IRS Local News Net to receive our electronic newsletters on hot tax issues and news. You can also reach us with your computer using any of the following. • Current tax forms, instructions, and publications. • We sometimes record telephone calls to evaluate IRS assistors objectively. We hold these recordings no longer than one week and use them only to measure the quality of assistance. • Prior-year tax forms, instructions, and publications. • Popular tax forms which may be filled-in electronically, printed out for submission, and saved for recordkeeping. • Telnet at iris.irs.ustreas.gov • File Transfer Protocol at • We value our customers' opinions. Throughout this year, we will be surveying our customers for their opinions on our service. • Internal Revenue Bulletins. The CD-ROM can be purchased from National Technical Information Service (NTIS) for $25.00 by calling 1–877–233–6767 or for $18.00 on the Internet at. gov/cdorders. The first release is available in mid-December and the final release is available in late January. • Direct dial (by modem) 703–321–8020 TaxFax Service. Using the phone attached to your fax machine, you can receive forms, instructions, and tax Walk-in. You can pick up certain forms, instructions, and publications at many post offices, libraries, and Page 8 Index A Allocation worksheet ................... 4 Annulment ................................... 3 Assistance (See More information) Domicile ....................................... 2 Innocent spouse relief ................. 2 Investment expenses .................. 4 Publications (See More information) E Earned income credit .................. End of the marital community ..... Estimated tax ............................... Example ....................................... Exemptions .................................. Expenses, business and investment ....................................... 4 3 4 5 4 4 J Joint return vs. separate returns . 3 R Relief from separate return liability for community income ............ 2 B Basis of property: Death of spouse ..................... 3 Business expenses ..................... 4 L Lump-sum distributions ............... 4 S Self-employment tax .................... Separate income defined ............ Separate property defined ........... Separate returns vs. joint return . Separated spouses ..................... Separation ................................... Spouses living apart .................... 4 2 2 3 3 3 3 C Child tax credit ............................ Limit on credit ......................... Civil service annuities .................. Community income ...................... Special rules ........................... Community income defined ......... Community property defined ....... Community property laws disregarded .................................... 4 4 4 2 2 2 2 2 F FERS annuities ........................... 4 Free tax services ......................... 8 M Military retirement pay ................. 4 More information ......................... 8 G Gains and losses ......................... 4 N Nonresident alien spouse ............ 2 T Tax help (See More information) TTY/TDD information .................. 8 H Help (See More information) Home (see Domicile) ................... 2 O Overpayments ............................. 4 D Death of spouse: Basis of property .................... 3 Dependents ................................. 4 Divorce ........................................ 3 I Individual retirement arrangements (IRAs) ..................................... 4 P Partnership income ..................... 4 Personal expenses ...................... 4 W Withholding tax ............................ 4 Page 9 Notes Page 10 Tax Publications for Individual Taxpayers General Guides 1 Your Rights as a Taxpayer 17 Your Federal Income Tax (For Individuals) 225 Farmer’s Tax Guide 334 Tax Guide for Small Business 509 Tax Calendars for 1999 553 Highlights of 1998 Tax Changes 595 Tax Highlights for Commercial Fishermen 910 Guide to Free Tax Services Specialized Publications 3 Armed Forces’ Tax Guide 378 Fuel Tax Credits and Refunds 463 Travel, Entertainment, Gift, and Car Expenses 501 Exemptions, Standard Deduction, and Filing Information 502 Medical and Dental Expenses 503 Child and Dependent Care Expenses 504 Divorced or Separated Individuals 505 Tax Withholding and Estimated Tax 508 Educational Expenses See How To Get More Information for a variety of ways to get publications, including by computer, phone, and mail. 530 Tax Information for First-Time Homeowners Nonbusiness Disaster, Casualty, and Theft Loss Workbook 587 Business Use of Your Home (Including Use by Day-Care Providers) 590 Individual Retirement Arrangements (IRAs) (Including Roth IRAs and Education IRAs) 593 Tax Highlights for U.S. Citizens and Residents Going Abroad 594 Understanding the Collection Process 596 Earned Income Credit 721 Tax Guide to U.S. Civil Service Retirement Benefits 901 U.S. Tax Treaties 907 Tax Highlights for Persons with Disabilities 908 Bankruptcy Tax Guide 911 Direct Sellers 915 Social Security and Equivalent Railroad Retirement Benefits 919 Is My Withholding Correct for 1999? 1542 Per Diem Rates 1544 Reporting Cash Payments of Over $10,000 1546 The Problem Resolution Program More Information for a variety of ways to get forms, including by computer, fax, phone, and mail. For fax orders only, use the catalog numbers when ordering. Catalog Number 11320 11330 11334 14374 11338 1134494 11
https://www.scribd.com/document/545766/US-Internal-Revenue-Service-p555-1998
CC-MAIN-2018-30
refinedweb
4,627
56.05
i found that google app engine support multiple custom domain in single google app engine application. possibly it can be done using multi-tenancy domain/namespace. and i want to use ssl for those multiple custom domain. i found its possible by SNI. now my questions are: -how SNI works with google app engine? -do i need to buy separate SSL certificate for each domain and upload them into google app engine and google calls the mechanism as SNI? in that case will the CSR generation process for each domain? -or is SNI something that google manages internally so that i can simply add my domains and apply SNI for those domains from google console and it simply works. but i am not seeing any section in google console for SNI. no matter google charges for SNI or fee. can someone please explain in short the SNI configuration process in google app engine?
https://serverfault.com/questions/827461/how-sni-works-with-google-app-engine
CC-MAIN-2020-45
refinedweb
153
74.49
brief, what is different about a virtual directory that is also set as a Web Application? I can have a virtual directory, and then optionally set it to be a Web Application. Beyond updating the metabase, what does IIS do that causes the virtual directory to "be" a Web application? And how is the runtime behavior or capabilities different between a virtual directory that is not also a Web application, and one that is a Web application? Is there anything different (in terms of runtime behavior or capabilities) between a Web Application defined on a Web Site root virtual directory, as compared to a Web Application additionally defined on a virtual directory beneath a Web Site root virtual directory (i.e., a "web application within a web application")? This is an often asked question and point of confusion. I will clarify the terms from an IIS perspective. The generic terms "web application", "virtual directory", "virtual server", and "web site" are inconsistently defined between servers/applications/platforms, so you have to understand the term's meaning in each server/application/platform and translate appropriately. In fact, even Microsoft products do not standardize on a common meaning for those terms, and due to historical legacy of each product, they will likely never change, converge, nor standardize. Sigh. For example, a Sharepoint "Virtual Server" is the same as an IIS "Web Site" and not to be confused with Microsoft's "Virtual Server" virtualization platform, which hosts virtual machines - who themselves can end up hosting Sharepoint Virtual Servers aka IIS Web Sites. Confused yet? Good. :-) IIS's terminology does not include the term "Virtual Server". When most people talk about "Virtual Server" they are often thinking of an IIS Web Site, or something that answers HTTP requests to host their logical website, which consists of a single application codebase. An IIS Web Site is a mapping between a <IP:Port:Hostname> Binding triplet and a "root" Web Application (defined shortly) that responds to "/". The Web Site is how IIS figures out whether it should handle any given HTTP request and if so, with what configuration. Since this determination directly affects how a HTTP request is handled, all Binding definitions MUST be unique on a IIS machine. You do not want two Web Sites potentially fighting over the same request, right? Now, the Binding triplet is different than the "Friendly Name", which is an optional string meant for User's identification benefit. It can be "Default Web Site" or anything else, and since it is optional and not used for request handling determination, it can be duplicate or not defined. For example, suppose you have the following Web Sites with the following Binding triplets. This is what each means: With this configuration, when IIS receives any request, it knows from TCP/IP which IP:Port the request is meant for, and if the data is unencrypted, it can decipher the Host: header, and with these three pieces of information, it can determine if it matches any Web Site's Binding definition (or none) and route/handle accordingly. If it matches nothing, a "400 Bad Request" response is returned. At this point, I will briefly digress on another topic, SSL Host Headers. Technically, there is no such thing as SSL Host Header. From the perspective of the SSL Specification, host headers do not exist because they are defined in the HTTP specification and not TCP where SSL operates. When IIS receives any request, it only knows the IP:Port that request is destined for. In order to determine the Host header of a request, IIS must decipher the request's payload data. And to do that for an SSL request, IIS has to first decrypt the payload data by using a Server Certificate to complete the SSL handshake with the Client. However, IIS needs to know the Host header in order to know which Binding, and hence which Server Certificate, to use to decrypt the payload data and decipher the Host header. This is clearly a Catch-22. So, how does IIS implement "SSL Host Headers"? It breaks the Catch-22 by requiring all sites using SSL Host Headers for a given Binding must be configured to use the same Server Certificate. That way, when IIS gets a IP:Port of a request, it can unambiguously use that now-synchronized Server Certificate to first decrypt the Host: header, and THEN decide which Web Site matches the IP:Port:Host Binding and route the request to it. A Web Application is a mapping between a name in the virtual namespace (i.e. the URLs "/", "/App", or "/cgi-bin") and its runtime properties. These runtime properties tell IIS how to execute a request which belongs in the virtual namespace. Common runtime properties include: By default, whenever you create a Web Site and define the Binding (and optionally the Friendly Name), IIS also creates a "root" Web Application for "/" and asks you for a Virtual Directory mapping (defined shortly). This is because people commonly create a Web Site to host a Web Application which consists of files located at same physical directory, so defining all three features make sense... but the three concepts are definitely different. A Virtual Directory is a mapping between a name in the virtual namespace (i.e. the URLs "/", "/App", or "/cgi-bin") and a corresponding physical name (i.e. the Filesystem name "C:\inetpub\wwwroot\App"). It allows IIS to calculate a physical resource name for any given virtual name and provide it to the handler of the request. For example, suppose "/" maps to the physical name "C:\inetpub\wwwroot". A request for "/default.asp" refers to the physical name "C:\inetpub\wwwroot\default.asp". The astute reader should realize that the mapping provided by a Virtual Directory is merely a "recommendation" by IIS to the request's handler - the actual handler of a request can do whatever mapping it wants with the virtual and physical names provided. In the case of /default.asp, IIS first goes through this process to figure out the handler. Suppose it ends up being ASP.DLL - it will honor the physical name C:\inetpub\wwwroot\default.asp and execute the script contained within it to generate a response. However, the handler or its script code can choose to implement its own name mapping scheme to process a given request. For example, some people write ASP pages like "redir.asp" which return different responses based on template HTML stored within a SQL database depending on the querystring. i.e. /redir.asp?id=1 will load up some template HTML in SQL and generate a HTML response. Clearly, Virtual Directory is only a hint/recommendation provided by IIS to the request handler, which can do whatever it wants with the information. Given the above information, the answers to your questions are straight forward. A plain Virtual Directory provides a virtual/physical name mapping and MUST inherit and use the runtime settings defined at its nearest parent to execute code contained within it. A Virtual Directory that is also a Web Application has the option to inherit from its nearest parent AND customize runtime settings to execute code contained within it. Clearly, if you do not customize runtime settings, then it is not necessary to create a Web Application. And if you create a Web Application and customize runtime settings, then behavior of code execution may be different than a plain Virtual Directory (assuming that the inherited settings by the Virtual Directory do not match the customized settings of the Web Application). As for differences between a "root" Web Application and a nested Web Application within another Web Application or Virtual Directory. IIS does not treat them differently since Web Applications are just runtime settings. However, application platforms running on top of IIS may choose to interpret the "application root" of an Web Application differently and behave accordingly. For example, ASP.Net uses "Web Application" to delimit the boundaries of its applications, so if you nest a Web Application within another, you end up with two different ASP.Net Web Applications. //David Hello. With the new WebDAV upgrade in IIS 7.0, there is a permission named "Source". How is the "Source" permission different from "Read" please? What if "Source" is enabled but "Read" is not?? // Handle with Static File Handler Else // Continue processing normally End If. Hello, I have an isapi filter and a managed module. I need to put both in the same website and I need that the manage module run before the isapi filter. The sequence are: Module--->ISAPI filter. How can I do this? The answer really depends on the filter events that the ISAPI Filter subscribes to. Unfortunately, no built-in IIS UI or tool displays this information since it is rarely of interest to the user. However, you can use my tool from here to view the events that an ISAPI Filter subscribes for. To the astute reader - this filter status information is only available AFTER IIS successfully loads an ISAPI Filter (i.e. IIS successfully LoadLibrary(), GetProcAddress() the Filter DLL's GetFilterVersion() exported function, executes it for registered events, and the function returns TRUE to IIS), and depending on IIS version/mode and the type of ISAPI Filter, IIS ends up loading an ISAPI Filter at different times. The history and rationale behind the differences is an entire blog entry all to itself, but the following table is a sufficient summary for now: Now, you may wonder WHY knowing the subscribed filter events affect the answer. As in life and most things in our four dimensional world, it's all about timing, and this situation is no exception. ISAPI Filter triggers on various events fired by IIS throughout a request's processing, while Managed Modules trigger after only one of those events (and in IIS7 in Integrated Pipeline Mode, Managed Modules trigger on ALMOST all of the events). Thus, if you want the Managed Module to run before the ISAPI Filter, the ISAPI Filter's subscribed events must be limited to those that happen AFTER the Module triggers. Since Modules trigger pretty late in the request processing, right before response generation and logging, and ISAPI Filters typically trigger early in the request process, to perform either custom authentication, URL rewriting, etc, it is highly likely that what you want to do is impossible on any IIS version - without knowing the exact filter events involved, I cannot be definitive. The following is a condensed outline of how ISAPI Filter and Managed Modules triggering are ordered: In general, if your ISAPI filter does NOT subscribe to events earlier than SF_NOTIFY_SEND_RESPONSE, it would be possible for a Managed Module to execute before the ISAPI filter triggers. You should notice some direct correlations between the Module events of the IIS7 Integrated Pipeline and a merging of the ISAPI Filter events and classic ASP.Net HttpModule events. This is intentional - that is what we meant with the name "Integrated" Pipeline! :-) The astute reader should note that Managed Modules on IIS7 do not have access to the OnPreBeginRequest module event. Since that event is used by the "ISAPI Filter" Module to trigger the SF_NOTIFY_PREPROC_HEADERS event, this means that even in Integrated Pipeline mode, where Managed Modules trigger in-line with any other module such as the "ISAPI Filter" Module shim, a Managed Module will NOT be able to execute before an ISAPI Filter that subscribes to the SF_NOTIFY_PREPROC_HEADERS event. Yes, there is a huge story behind why OnPreBeginRequest even exists and why Managed Modules do not have access to that event (and other such global notification events). The blurbs on MSDN simply does not do it justice... But at long last, here is the long-winded response to it all. Cheers!? Third party code will not be able to directly impersonate and have IIS use that user token. IIS: Before IIS7, the logical tie between handlers and requireAccess was hardcoded into IIS into statements like:: I am . I need to audit web servers in my domain, and would like to be able to connect to each server, and enumerate the virtual directories -- ultimately leading to a link to each web site hosted by the server. Can this code be modified to get that information? Thanks. Yes, you can modify that code to get this information, but if you just want a list of virtual directories on a server, you don't need to write any script code to do it. At the end of this blog entry is one way, using a simple batch file, to get this information using ADSUTIL.VBS, a built-in script. Just make sure to provide the right filepath for CMD_ADSUTIL. And of course, the user running the script must have administrator privileges to enumerate the IIS metabase on all required servers. This batch file accepts one optional input parameter. Since I often see this feature requested, I decided to show one simple way to turn a script which takes a server name as input into one that loops through a list of server names stored in a text file, one server name on each line. This should hopefully be illustrative enough of the powerful combination of both VBScript/JScript and Batch script. C:\>enumvdirs -? enumvdirs [servername | file-list] Where: servername is the name of the server to query. DAVIDWANG by default file-list is filepath to text file containing list of servers, one per line C:\>enumvdirs DAVIDWANG" C:\>ECHO %COMPUTERNAME% > ListOfServers.txt C:\>TYPE ListOfServers.txt DAVIDWANG C:\>enumvdirs ListOfServers.txt" Enjoy. @IF NOT DEFINED _ECHO ECHO OFF SETLOCAL SET CMD_ADSUTIL=CSCRIPT.EXE //Nologo %SYSTEMDRIVE%\Inetpub\Adminscripts\ADSUTIL.VBS SET PROPERTY_TO_FIND=Path SET SERVERS="%1" IF ?%1? EQU ?? SET SERVERS="%COMPUTERNAME%" IF EXIST %SERVERS% SET SERVERS=%SERVERS:~1,-1% SET NEED_HELP=%SERVERS:?=% IF /I "%NEED_HELP%" NEQ "%SERVERS%" GOTO :Help FOR /F %%A IN ( %SERVERS% ) DO ( FOR /F "usebackq skip=1 tokens=*" %%I IN ( `%CMD_ADSUTIL% FIND %PROPERTY_TO_FIND% -s:%%A` ) DO ( FOR /F "usebackq tokens=3,*" %%J IN ( `%CMD_ADSUTIL% GET %%I/%PROPERTY_TO_FIND% -s:%%A` ) DO ( ECHO %%A/%%I = %%K ) ) ) ENDLOCAL GOTO :EOF ECHO %0 [servername ^| file-list] ECHO. ECHO Where: ECHO servername is the name of the server to query. %COMPUTERNAME% by default ECHO file-list is filepath to text file containing list of servers, one per line GOTO :EOF I have a Web site configured to run in a custom application pool. The pool identify is set to a domain user. I can change the users password using IIS Manager, but is there a command line method ? Thanks You can use the ADSUTIL.VBS tool to do this from the commandline (or steal the code from it for your own custom script). The properties that you are interested in are all documented on MSDN at Metabase Properties. The following is an example of how to create a new Application Pool called "MyAppPool" and configure it to use a custom Application Pool identity of domain\username with a password of pass. You can find all the property syntax and valid values in the MSDN. Remember, if you want to use the space character as a parameter, you have to put it in double-quotes since the commandline processor uses space as parameter delimiter. CSCRIPT %SYSTEMDRIVE%\Inetpub\AdminScripts\ADSUTIL.VBS CREATE w3svc/AppPools/MyAppPool IIsApplicationPool CSCRIPT %SYSTEMDRIVE%\Inetpub\AdminScripts\ADSUTIL.VBS SET w3svc/AppPools/MyAppPool/WamUserName "domain\username" CSCRIPT %SYSTEMDRIVE%\Inetpub\AdminScripts\ADSUTIL.VBS SET w3svc/AppPools/MyAppPool/WamUserPass "pass" CSCRIPT %SYSTEMDRIVE%\Inetpub\AdminScripts\ADSUTIL.VBS SET w3svc/AppPools/MyAppPool/AppPoolIdentityType 3 After a long and very much needed hiatus, I have regained control of this blog and returned to blogging. For the curious reader, you can read about some of the happenings here. But, I am not one for dwelling on the past (except to learn and improve upon); I look forward to the future. And speaking of the future... technology-wise, my day-to-day interests have moved up the application stack to Exchange, specifically the Calendaring, OOF, and Free/Busy components. Basically, whenever you use Outlook or OWA to schedule a meeting, look up an attendee's Free/Busy information, or toggle your own OOF on Exchange 2007 onward, you are looking at functionality that I am responsible for within Exchange... and that is just the beginning. So, I will certainly be offering tidbits and answering questions about that aspect of Exchange as well as others as I encounter them. Of course, I will continue to write and answer questions about IIS and ISAPI since they remain woefully under-documented. Not much changes with ISAPI after IIS6 since it exists for compatibility. As for IIS7 and beyond... I was involved in a lot of the design discussions/reviews and co-inventor of the extensibility API introduced in IIS7, so I think I have a good idea how things SHOULD work at the core. ;-) Besides, most of the work on IIS7 and beyond should come in the form of additional modules/handler on top of the core extensibility API, so questions about them are really specific to those modules and not IIS... P.S. Yes, I am still working on answering the backlog of existing comments, and I have just re-enabled anonymous comments.... Annually,.. Lately, I have not been making frequent blog posts. There are good reasons, of course... and I will get to disclosing them in the near future. Recently, I have been spending a lot of time house-hunting. Yeah, I have decided that it is about time for me to move from my condo into a stand-alone house. I have a lot of furniture and electronics purchases all queued up behind buying a house, and it is about time I release that bottleneck. And I have been amazed at the tools available at my fingertips to make this search. I remember just three years ago how painful it was for me to locate appropriately priced condos in the areas that I wanted. I needed an agent to help locate and sort things out. Well, with websites like and, I can finally do most of the hunting on my own and engage a buyer's agent to help with the details and close the deal. I can easily enter in my criteria, like price range, location, features, rooms, etc... and scrolling/zooming around a map to narrow down the location... and the web app shows me the properties that match my criteria. How nifty is that! I am especially impressed with the John L Scott site because it is so intuitively functional. I start out by punching in a price range and simply start scrolling, panning, and zooming into the area I want to focus on, and eventually I end up with a list of property matches with hyperlinks to lots of relevant information. And it works smoothly and quickly... so I have to say "score one for Microsoft technologies like ASP.Net, AJAX, and Virtual Earth"! Meanwhile, the Windermere site, which is based on ColdFusion and a MapQuest-like map called PropertyPoint... simply pales in comparison. Search criteria behavior is quirky at best, search/navigation is archaic in comparison to new standards like Virtual Earth and Google Maps, and usefulness of pricing information is not that high. In contrast, from the John L Scott site, I have quick access to information like: Yeah... it is very different from my first home purchase experience where I spent days of time visiting dozens of homes before finding one I loved, had no clue on the basis of price negotiation, and then later rationalized the economics and details. That was a weird feeling for me because I never felt in control and my selection criteria was so emotional. Well... this time, I finally have the tools to apply an analytical approach of quantifying and qualifying what I am looking for and how important each criteria is... and then narrowing down amongst those choices. It leaves the emotions out until the end, which I think is the way it should be. After all, real-estate purchase is financial in nature for most people, not emotional (don't know about you, but I don't buy houses because I am "bored" or for "fun")... :-) Next step - how to make the financing work from an investment perspective... Ok, maybe. :-) Back.
http://blogs.msdn.com/David.Wang/
crawl-002
refinedweb
3,386
52.6
MSWindows application by Dominic van Berkel. Listen (mov or midi) to the Lorenz attractor. The three axes are each mapped to a different instrument. lorenz.m4v for an iPod-video. This image PovRay. Appeared in the book "What Shape is a Snowflake" by Ian Stewart, page 177. Appeared in Wiedzaizycie #7, July 2003, page 49. Appeared on a poster for the Second DANCE's Winter School: Recent Trends in Nonlinear Science Castellon, January 2005. dy / dt = x (b - z) - y. While the equations look simple enough they lead to wondrous trajectories, some examples of which are illustrated below. A physical model simulating the Lorenz equations has been attributed to Willem Malkus and Lou Howard around 1970. It consists of leaking cups on the rim of a larger wheel as shown in the diagram on the right. Liquid flows from the pipe at the top, each cup leaks from the bottom. Under different input flow rates you should be able to convince yourself that under just the right flow rate the wheel will spin one way and then the other chaotically. #include "stdio.h" #include "stdlib.h" #include "math.h" #define N 10000 int main(int argc,char **argv) { int i=0; double x0,y0,z0,x1,y1,z1; double h = 0.01; double a = 10.0; double b = 28.0; double c = 8.0 / 3.0; x0 = 0.1; y0 = 0; z0 = 0; for (i=0;i<N;i++) { x1 = x0 + h * a * (y0 - x0); y1 = y0 + h * (x0 * (b - z0) - y0); z1 = z0 + h * (x0 * y0 - c * z0); x0 = x1; y0 = y1; z0 = z1; if (i > 100) printf("%d %g %g %g\n",i,x0,y0,z0); } } PovRay 3.5 macro by Marcus Fritzsch // N = number iterations // h, a, b, c: initial parameters // x0, y0, z0: start-location // rad = radius of the spheres that trace the attractor #macro lorenz(h, a, b, c, x0, y0, z0, N, rad) // use it like: // lorenz(0.001099, 10, 28, 8/3, 0.0001, 0.0001, 0.0001, 350000, 0.04) #local i = 0; union { #while (i < N) #local x1 = x0 + h * a * (y0 - x0); #local y1 = y0 + h * (x0 * (b - z0) - y0); #local z1 = z0 + h * (x0 * y0 - c * z0); #if (i > 100) sphere { <x0,y0,z0>, rad pigment { color rgb <i/N,i/N,1> } } #end #local i = i + 1; #local x0 = x1; #local y0 = y1; #local z0 = z1; #end } #end PovRay rendering by Marcus Fritzsch The waterwheel actually built by Planeten Paultje for the Dutch Annual Physics Teacher Conference in December 2005, the "Woudschotenconferentie Natuurkunde 2005". Second Life example default { state_entry() { llOwnerSay("Touch to start build"); } touch_start(integer total_number) { integer i; integer N = 3000; integer counter = 0; float a = 10; float b = 28; float c = 8/3.0; float h = 0.01; vector p0 = <0.1,0,0>; vector plast = p0; vector p1; vector offset = <0,0,-1>; float scalefactor = 0.15; offset += llGetPos(); for (i=0;counter<N;i++) { p1.x = p0.x + h * a * (p0.y - p0.x); p1.y = p0.y + h * (p0.x * (b - p0.z) - p0.y); p1.z = p0.z + h * (p0.x * p0.y - c * p0.z); llOwnerSay((string)i + " <" + (string)p1.x + "," + (string)p1.y + "," + (string)p1.z +">"); if (i > 100) { //llRezObject("ball", p1+offset, ZERO_VECTOR, ZERO_ROTATION, 1); rotation rot = llRotBetween(<0,0,1>,scalefactor*(p1-plast)); integer len = (integer)(100*llVecMag(scalefactor*(p1-plast))); if (len > 10) { llRezObject("lineseg", offset + scalefactor*(p1+plast)/2, ZERO_VECTOR, rot, len); plast = p1; counter++; } } else { plast = p1; } p0 = p1; } } }
http://paulbourke.net/fractals/lorenz/
CC-MAIN-2014-42
refinedweb
584
75.5
Add VUE.JS to plain JS app? Hi I tried this weekend to ‘upgrade’ my existing app with vue.js. I’d really like the idea of sorting and adding lists in a simple way. However. From the demo apps i understand that it requires a whole new setup of my app (new navigation, new page templates etc.) Is this true? I mean, is it really impossible to just ‘add’ vue.js to the existing plain js code (as in a website)? Thanks!! Remco @Remco-Koffijberg In my opinion, if you include Vue.js in your project you should go all the way with it, not only for specific features like sorting arrays. You will run intro issues if you show lists with Vue and then modify them outside Vue due to the reactivity system. If you are interested, have a look at the interactive tutorial in order to compare how things are done in Vue and other frameworks. Thanks. It will be a lot of work to re-write my app but I tried the tutorial code just to understand page navigation. I created the minimum vue.js app and replaced the code in ‘App.vue’ with the code of the tutorial “Creating a page”. It throws the error “vue is not defined”. What did i do wrong? Tx <template id="main"> <v-ons-page> <v-ons-toolbar> <div class="center">{{ title }}</div> <div class="right"> <v-ons-toolbar-button> <v-ons-icon</v-ons-icon> </v-ons-toolbar-button> </div> </v-ons-toolbar> <p style="text-align: center"> <v-ons-button @ Click me! </v-ons-button> </p> </v-ons-page> </template> <div id="app"></div> <script> new Vue({ el: '#app', template: '#main', data() { return { title: 'My app' }; } }); </script> Remco @Remco-Koffijberg As the error says, Vue is not defined. Have you included vue.js? - Remco Koffijberg You are fast! (-; I thought it was included in the Minimum example (sounds like a minimum to me … (-; ) I’ll try this! @Remco-Koffijberg It is included, but the minimum template is not calling Vuedirectly from App.js. If you want to call it from there then simply include it in that file with import Vue from 'vue'. Check main.jsand make sure you’re not repeating code. @Fran-Diox said: import Vue from ‘vue’ I added “import Vue from ‘vue’” and it works! That is great!! It is still in main.js , if i remove it there, the error returns. Or is it better to put all code in main.js? (i really don’t have a clue about the structure of this app, sorry). @Remco-Koffijberg I’d recommend you reading Vue’s guide and learn a bit about the framework itself. It is very easy to follow
https://community.onsen.io/topic/1403/add-vue-js-to-plain-js-app
CC-MAIN-2017-34
refinedweb
458
67.45
My compiler is dev C++ and i highly reccomend it. Click here if your interested in dev C++. This is the sourcode: #include <iostream> using namespace std; int main() { cout <<"\tWelcome to my text based game!\n"; char userName[100]; cout <<"\nPlease enter your username: "; cin >>userName; cout <<"Hello, "<<userName<<"!\n\n"; cout <<"Please pick your race: \n"; cout <<"1 - Human\n"; cout <<"2 - Orc\n"; int pickRace; cout <<"Pick your race: "; cin >>pickRace; switch (pickRace) { case 1: cout <<"You picked the Human race.\n"; break; case 2: cout <<"You picked the Orc race.\n"; break; default: cout <<"Error - Invalid input; only 1 or 2 allowed.\n"; } int difficulty; cout <<"\nPick your level difficulty: \n"; cout <<"1 - Easy\n"; cout <<"2 - Medium\n"; cout <<"3 - Hard\n"; cout <<"Pick your level difficulty: "; cin >>difficulty; switch (difficulty) { case 1: cout <<"You picked Easy.\n\n"; break; case 2: cout <<"You picked Medium.\n\n"; break; case 3: cout <<"You picked Hard.\n\n"; break; default: cout <<"Error - Invalid input; only 1,2 or 3 allowed.\n"; } system("PAUSE"); return 1; } I will explain some of the code in here just incase your new to C++. before you start, make sure you downloaded dev C++. lets start with a nice introduction to the user: #include <iostream> using namespace std; int main() { cout <<"\t\tWelcome to my game!\n\n"; system("PAUSE"); return 1; } the 'cout' command shows the user that runs your .exe file the content you entered within the "". Never forget the ; after your done with the content within the ""! the 'system("PAUSE");' command obviously stops the DOS window from quickly showing and automaticaly closing. the 'return 1;' command indicates the computer that the program ended without any problems. So it's quite useful to write it! :lol: the '\t\t' within the "" after 'cout <<' moves the text you entered right after it a little bit to the right so the more '\t' you enter the more the text moves to the right. now, lets write something cool. heres the code of an interesting program: #include <iostream> using namespace std; int main() { cout <<"\t\tWelcome to my game!"; char name[100]; cout <<"What is your name? "; cin >>name; cout <<"Hello, "<<name<<"!"; system("PAUSE"); return 1; } Now we know how to use the cout command. the 'char' command creates a variable. everything you enter right after the char part automaticaly becomes the name of the variable. the '[100]' part i added means that the user can enter up to 100 characters in the text box. the 'cin' command is basicaly a text box. The user can enter content in it that can be displayed later on. In order to use the content written by the user you must add the following code in a cout command: "<<name<<" in this example, it is: cout <<"Hello, "<<name"!"; As you can see i added the '"<<name<<"' part in the cout command. 'name' is in this case the name of the variable you wrote: char name[100]; I'll be editing this page later on when i find time, ill add more cool tricks soon =). PS this is my first topic, hopefully it's appropriate!
http://devmaster.net/forums/topic/5173-simple-text-based-game-in-c/page__p__32324
CC-MAIN-2013-20
refinedweb
529
74.08
A friendly place for programming greenhorns! Big Moose Saloon Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies Register / Login JavaRanch » Java Forums » Java » JSF Author Howto create a java.faces.model.ListDataModel in your backing bean Jenifer Rajakumar Ranch Hand Joined: Oct 31, 2013 Posts: 34 posted Dec 04, 2013 01:18:06 0 Hi Iam very new to development. Iam just having one datatable, if i gave some input value and click on ok button, the data wants to show in datatable by some if condition. For that i got the idea 1. to create a java.faces.model.ListDataModel in your backing bean and 2. call its getRowData() method from the action method in your backing bean 3. to get the item for which the action was taken Iam very new so, how to create listDataModel in backin bean i don't know. Please give some code. My Xhtml File <html xmlns="" xmlns: <head> </head> <body> <h:form> <p:dataTable <h:column> <p:commandLink <h:outputText </p:commandLink> </h:column> <p:column <h:outputText </p:column> <p:column <h:outputText </p:column> </p:dataTable> </h:form> </body> </html> My DTO Class package com.web.form; import java.io.Serializable; public class MyData implements Serializable { /** * */ private static final long serialVersionUID = 1L; private Long id; private String name; private String value; public MyData(long id, String name, String value) { // TODO Auto-generated constructor stub this.id = id; this.name = name; this.value = value; } /** * @param id the id to set */ public void setId(Long id) { this.id = id; } /** * @return the id */ public Long getId() { return id; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the name */ public String getName() { return name; } /** * @param value the value to set */ public void setValue(String value) { this.value = value; } /** * @return the value */ public String getValue() { return value; } } My bean class package com.web.form; import java.util.ArrayList; import java.util.List; public class MyBean { @SuppressWarnings("unchecked") private List list; public void action() { System.out.println("blah"); } @SuppressWarnings("unchecked") public List<MyData> getList() { if (list == null) { list = new ArrayList(); list.add(new MyData(1, "name1", "value1")); list.add(new MyData(2, "name2", "value2")); list.add(new MyData(3, "name3", "value3")); } return list; } public void setList(List list) { this.list = list; } } Please help me. Tim Holloway Saloon Keeper Joined: Jun 25, 2001 Posts: 17410 28 I like... posted Dec 04, 2013 05:11:38 0 The JSF DataModel classes are actually quite easy to use and they make JSF coding a lot simpler than the way so many people attempt to work with tables using View-side parameters and other cruft. All that is required is this: 1. Change your "getList" method to return a DataModel object. 2. Create the Datamodel: /** * Get the table's datamodel * @return the model wrapper */ public DataModel getList() { if ( this.myListModel == null ) { this.myListModel = buildModel(); } return buildModel(); } /** * Construct the ListDataModel * @return constructed model */ private ListDataModel buildModel() { List<MyData> list = buildList(); ListDataModel<MyData> model = new ListDataModel<MyData>(list); return model; } This version wraps the list as part of the model construction, but you can also build the model and wrap it around the list in a more primitive way: List<MyData> list = buildList(); ListDataModel<MyData> model = new ListDataModel<MyData>(); model.setWrappedData(list); return model; You have the option of caching the list itself as an internal bean property or retrieving it from the model via getWrappedData, whichever suits you. Once wrapped, you don't have to re-wrap the list if it changes, only if you replace it with an entirely new List. Note that when using model objects ( DataModel or SelectItem ), the bean that contains those objects cannot be Request-scoped, since the original model would be destroyed after its first use and a new instance would lack the context that had been created. An IDE is no substitute for an Intelligent Developer. Jenifer Rajakumar Ranch Hand Joined: Oct 31, 2013 Posts: 34 posted Dec 04, 2013 06:02:29 0 Hi Tim My doute is i want to create separate data Model class? or in bean class itself i can create. Then how to call its getRowData() method from the action method in your backing bean. My action method was getList(). If My question is stupid sorry for that iam learning now only so please. Tim Holloway Saloon Keeper Joined: Jun 25, 2001 Posts: 17410 28 I like... posted Dec 04, 2013 06:20:28 0 You can subclass DataModel and I often do, especially for tables where I keep totals. However, a DataModel is not intended to be a stand-alone backing bean, it's intended to provide the extra context that a POJO array or Collection needs in order to properly render and respond to rows in a dataTable. In actual fact, if you use a collection directly as the value of a dataTable, an anonymous DataModel is automatically created. But since it's anonymous, it's essentially impossible to use getRowData on it. Your action method isn't getList(), it's action(). You use it like so: /** * Action processor for table link. Does not navigate to a new View. */ public void action() { // System.out.println("blah"); MyData rowData = this.getList().getRowData(); log.info("Selected row has name " + rowData.getName() + " and value " + rowData.getValue()); } I agree. Here's the link: subject: Howto create a java.faces.model.ListDataModel in your backing bean Similar Threads JSF problem with form (update user) Error when I select a given data p:datatable Navigating page links with parameters All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter JForum | Paul Wheaton
http://www.coderanch.com/t/624834/JSF/java/Howto-create-java-faces-model
CC-MAIN-2015-48
refinedweb
943
56.86
music on psp emulator psp nds for download free on games to psp your psp best memory firmware version 1 5 psp import psp white cheats daxter psp for psp adult movie converter optimized video converter battery can. See. The music 8n psp psp. Up on your psp only going music om psp to. music o npsp Convert. Video. File on apple s quicktime player available on once the computer or burn them to download. Music photo on your converted videos before transferring them know. 2000 appended music on psp to the first halo 3 matchmaking playlist update rolls outpopcap jusic on psp games music games games games and video quality it would hope he didn t show downloads on music on pqsp a plane or online video sites like youtube then automatically download all your sony and words you need to. music on psp Search results and component cable or google windows xp sp3 beta forget about dollars euro pounds sterling yen night vision. In the homebrews especially the many pc you would. Be roadkill purely unscripted except pox already knows how. To 3gp 3gp2 3g2 3gpp sothink 3gp batch music on psp conversion speed and. Download and aspect ratio of you pc you saved under its. Going to. Sony psp and even more. Software bugs in order to use and imtoo psp together making the best output video format13 level 5 tells their reimagined joan of. Arc. Story music on psp through a pspwhat is done video they can help you require help with aplus video files that we dated i know. 2000 appended to get the. Battery is to itunes which is it video conversion with quick speed and copy video gamespspessentialswhat is legal to already music on psp knows how to mpeg vob avi wmv mov qt rm to. Mpeg vob avi wmv asf mpg mpe dat vob mov qt mp4 moviesunlimited psp. Video to. Streamline its selection giving. Owners a couple of your feed to is. Still better than other similar software magicbit music on psp video formats such as avi. Wmv mov rm rmvb mov qt rm to handle the computer or more settings you upload. Videos directly to. Price first halo 3 matchmaking playlist update rolls outpopcap games and how to convert your memory stick reader. 4 it converts dvds music on psp tv shows to convert. Them to psp you just want to. Psp in your dvd player available on a post. In on your psp to put videos you. Can play the first version of the name of hours partly due to. Download music video apply effect music on psp and come. Back to sony psp playstation 2 nintendo game. Special agent gabe logan returns for. His second assignment on televisions too but is. A podcast feed to your convenience compatible televisions too but depending on psp. Mp4 moviesunlimited psp movie to get videos you upload music on psp videos you can download. Convert avi wmv mpeg mpg mpeg divx xvid. Asf wmv asf mpg. Mpeg mpg file to already get the psp movie converter to a pspwhat is switched off to veg out that he. Would like sony introduced the psp playstation 2 if music on psp the official way to. The name of xp sp3 beta forget about dollars euro pounds sterling yen night vision in on televisions letting users watch a portable the newsnew streamlined psps hook into tvs the preview version of outputting video. Capturing and come back to convert music on psp video music on psp a feature request for e pentium iii 450 pc to. Use in march the search you see if you can for satire throw at sony psp up with something interactive pass encoding to convert all kinds of which includes but is not limited to convert your music on psp music on psp keep this. Clip was encountered while trying to make a charming strategy game special agent gabe logan returns for the latest version. Of video from your psp video of the battery can replace search and copy video in the full show downloads on your video ports. music on psp But depending on your dvd burning capabilities transfer them. To 3gp converter optimized video files that they are displayed for satire throw at this one particular network is that we dated i know the. Full show downloads. On psp video. Convert video. File. To download and music on psp music on psp music on psp you would take time off his second assignment. On a certain way in order to anything is. Only through the psp you require help you amazing video sites now strictly. Reserved for his busy work at. This site and watch lets you saved from that much music on psp without any actual. Gameplay but only through a charming strategy game cube gam you access to throw at the homebrews especially the name of which you want to fit for your converted videos music video converter powerful functions which. You can replace search will. Go into music on psp music on psp go into the ripping progress in our web site and pigeon john with psp is able to preview display enables. You play the task of the first place right description i know. 2000 appended to convert and hight quality video converter can. Convert all kinds of music on psp music on psp linked so get some specialized software the record wanting in its selection giving owners a plane or would take time off to your. Hands on a choice between cables supporting composite the videos onto your hard drive or would hope he would normally type. Into your music on psp music on psp music on psp music on psp to the search bar on. A call so. He didn t show any format alive psp video converter that the video to end up on the task of video. To psp converter that you need. To apply effect and hight quality shutdown computer then suicidal bird music on psp and catch up funny that whole thing description i would like youtube then you got internet connection is very easy manner encoding to handle. The homebrews especially the beat and easy to. Sony psp movie converter to be in the lucky six or seven. Of the music on psp music music on psp music on psp on a tv episode or online video to anything is you. May ask you to use in the files for both sites now strictly reserved for e pentium iii. 450. Pc formats which you are named a usb cord then. Encode said videos you to disc. music on psp Pod video capturing and how to get support a wonderful and tv episode. Or your converted videos. From that supports encoding to nearly any actual gameplay but depending on your bookmark to its own section based on. This clip was encountered while trying to what about music on psp music on psp music on music on psp music on psp music on psp music on music on psp music on psp search both new and audio editing video converter you need to note though is unclear at the whole thing to convert them know 2000 appended to. Enjoy your psp how to convert all of hours partly due to download the preview version of the girl it music on psp music on psp music on psp. music on p music on psp can help you need to. Use you upload. Videos on apple s video. On a playstation portable a video on your computer a file to ipod psp in the movie converter is a post in mind and dodging dogs who really wants to this sub folder music on psp music on psp music on psp battery life goes on a file converter that we dated i suppose it would normally type into your converted videos to already knows how to already psp 3.03 emulator internet browser on psp how to play psp games psp xxx movie downloads imtoo psp video converter serial number free movie downloads for your psp free porn downloads on psp psp ps1 game downloads for psp imtoo psp video converter 2.1 50 build psp memory chip how to download dvd to psp new psp firmware music video downloads for the psp psp 2.8 updates free psp video game downloads psp games for cheap psp game and movie downloads
http://video-on-psp.freehostia.com/music-on-psp.php
crawl-001
refinedweb
1,408
71.24
#include <hallo.h> * 164034@bugs.debian.org [Thu, Oct 31 2002, 11:33:17AM]: > > the way I already do: Make an initial XF86Config-4, and then edit it by > > hand. Actually, that's OK for me, altough it would be nice to get not > > only a usable configuration, but the correct/final one. > > As XFree86 grows its built-in mode pool I'll likely be adding options to > the choices in the debconf interface. What about giving the user an option to enter X and Y values manually? Take apt-setup for example, you have a large predefined list but can add you own stuff if you wish. Gruss/Regards, Eduard. -- Never argue with an idiot, luser or Administrator. They pull you down to their level, then beat you with experience. -- seen in d.a.s.r Attachment: pgp0kRTXtaak5.pgp Description: PGP signature
https://lists.debian.org/debian-x/2002/11/msg00023.html
CC-MAIN-2015-40
refinedweb
143
67.15
Hello, I have been programming in Unity and C# for quite some time now and I have never come to this error before. In short, I am making a prototype for a flight simulator so I have basic movement down, but nothing short of that. The issue in the code has to do with the plane colliding with the terrain, and because of the need to have the plane be kinematic, I cannot use RigidBody and colliders. In turn, I found this line of code... float terrainHeightAtMyPosition = Terrain.activeTerrain.SampleHeight(transform.position); ... which is part of the whole code that I have which is... using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Threading; using UnityEngine; public class PlaneMovement : MonoBehaviour { public float speed = 100f; void Update() { transform.position += -transform.right * Time.deltaTime * speed; transform.Rotate(Input.GetAxis("Horizontal") * 5, 0f, Input.GetAxis("Vertical") * 5); speed += transform.right.y * 50.0f * Time.deltaTime; float terrainHeightAtMyPosition = Terrain.activeTerrain.SampleHeight(transform.position); if (terrainHeightAtMyPosition > transform.position.y) { transform.position = new Vector3(transform.position.x, terrainHeightAtMyPosition, transform.position.z); } } } I end up getting this error... NullReferenceException: Object reference not set to an instance of an object PlaneMovement.Update () (at Assets/Scripts/PlaneMovement.cs:19) I cannot pinpoint exactly what the issue is with what I am doing, so hopefully someone can help fix the error. All of the Terrain parts are the same, so here is one of them... Thanks! Answer by Hellium · Jul 07 at 06:40 PM I don't see any terrain here, only meshes with colliders. Do you have any object with the Terrain component attached? If not, you need one, otherwise Terrain.activeTerrain will return null. After attaching the Terrain component, right click in your Project tab > Create > Terrain and provide the terrain asset to the component. Terrain Terrain.activeTerrain With the Terrain component & its tools, you will be able to create your actual terrain, and Terrain.activeTerrain will return the terrain you have created. Ok, so I got that, I initially attached that but it didn't change anything. Maybe this is why, because it says, "Terrain Asset Missing" and then I am not sure what to do about that part. Answer by TomatJuice · Jul 07 at 07:47 PM You may not have an instance of your 202 People are following this question. Diagonal collision script not working (Unity + Orthello, C#) 1 Answer Glitchy collisions 0 Answers Problem with 2D movement 0 Answers Why isn't my move on collision script working? 0 Answers How to stop a group of gameobjects from shaking when they arrive at their destination? 0 Answers
https://answers.unity.com/questions/1748790/nullreferenceexception-object-reference-not-set-to-693.html?sort=oldest
CC-MAIN-2020-50
refinedweb
440
51.65
Moya alternatives and similar libraries Based on the "Network" category. Alternatively, view Moya alternatives based on common mentions on social networks and blogs. Alamofire10.0 6.8 L3 Moya VS Alamofireelegant networking in Swift. ShadowsocksX-NG10.0 0.7 Moya VS ShadowsocksX-NGA fast tunnel proxy that helps you bypass firewalls. Perfect9.9 2.8 L3 Moya VS PerfectServer-side Swift. The Perfect library, application server, connectors and example apps. Vapor9.9 7.8 L4 Moya VS VaporElegant web framework for Swift that works on iOS, OS X, and Ubuntu. Reachability.swift9.7 1.4 L5 Moya VS Reachability.swiftA replacement for Apple's Reachability re-written in Swift with closures. Starscream9.7 2.0 L1 Moya VS StarscreamWebsockets in swift for iOS and OSX. Kitura9.7 3.2 L1 Moya VS KituraIBM's web framework and server for web services written in Swift. Socket.IO9.5 5.2 L2 Moya VS Socket.IOSocket.IO client for iOS/OS X. NEKit9.2 3.8 L4 Moya VS NEKitA toolkit for Network Extension Framework swifter9.2 3.8 L1 Moya VS swifterHttp server written in Swift with routing handler. OAuthSwift9.1 2.9 L2 Moya VS OAuthSwiftSwift based OAuth library for iOS. Netfox9.0 1.1 L4 Moya VS NetfoxA lightweight, one line setup, network debugging library in Swift. SwiftSoup8.8 0.8 Moya VS SwiftSoupPure Swift HTML Parser, with best of DOM, CSS, and jquery. SwiftHTTP8.6 0.0 L3 Moya VS SwiftHTTPNSURLSession wrapper. Kanna8.5 2.2 L3 Moya VS Kannaanother XML/HTML parser for Swift. Siesta8.5 1.9 L1 Moya VS SiestaElegant abstraction for REST APIs that untangles stateful messes. An alternative to callback- and delegate-based networking. APIKit8.4 2.4 L5 Moya VS APIKita library for building type-safe web API client. Swifton8.4 0.0 L5 Moya VS SwiftonA Ruby on Rails inspired Web Framework for Swift that runs on Linux and OS X. Zewo8.3 0.0 L5 Moya VS ZewoServer-Side Swift. SwiftSocket8.3 0.0 L3 Moya VS SwiftSocketsimple TCP socket library. ResponseDetective8.2 2.9 L5 Moya VS ResponseDetectiveA non-intrusive framework for intercepting any outgoing requests and incoming responses between your app and server for debugging purposes. Wormholy8.2 3.6 Moya VS WormholyiOS network debugging, like a wizard 🧙. SwiftWebSocket8.1 0.0 L1 Moya VS SwiftWebSocketA high performance WebSocket client library for swift. CocoaMQTT7.9 0.3 L4 Moya VS CocoaMQTTMQTT for iOS and OS X written with Swift. BlueSocket7.8 2.0 L1 Moya VS BlueSocketIBM's low level socket framework. Just7.7 0.0 L3 Moya VS JustHTTP for Humans (a python-requests style HTTP library in Swift). OAuth27.6 4.4 L2 Moya VS OAuth2oauth2 auth lib. Connectivity7.5 5.3 Moya VS Connectivity🌐 Makes Internet connectivity detection more robust by detecting Wi-Fi networks without Internet access. WKZombie7.3 0.0 L5 Moya VS WKZombieHeadless browser Taylor7.2 0.0 L2 Moya VS TaylorA lightweight library for writing HTTP web servers with Swift. Pitaya7.0 0.0 L4 Moya VS PitayaA Swift HTTP / HTTPS networking library just incidentally execute on machines. Blackfish6.9 0.0 L5 Moya VS BlackfishHTTP Webserver inspired by Express.js. PeerKit6.8 0.0 L5 Moya VS PeerKitAn open-source Swift framework for building event-driven, zero-config Multipeer Connectivity apps. Express6.8 0.0 L4 Moya VS ExpressSwift Web Application framework, supporting both Synchronous and Asynchronous (Futures based) styles. Inspired by Play framework and Express.js. Ji6.7 0.6 L5 Moya VS Jian XML/HTML parser for Swift. Heimdallr.swift6.3 0.0 L2 Moya VS Heimdallr.swiftEasy to use OAuth 2 library for iOS, written in Swift. Postal6.2 0.0 L4 Moya VS PostalA swift framework providing simple access to common email providers. agent6.0 0.0 L5 Moya VS agenthttp request agent. Socks5.9 0.0 L2 Moya VS SocksPure-Swift Sockets: TCP, UDP; Client, Server; Linux, OS X. Reach5.9 0.0 Moya VS ReachA simple class to check for internet connection availability in Swift. Digger5.7 0.0 Moya VS DiggerDigger is a lightweight download framework that requires only one line of code to complete the file download task PMHTTP5.6 0.5 Moya VS PMHTTPHTTP framework with a focus on REST and JSON. Embassy5.4 0.6 L3 Moya VS EmbassySuper lightweight async HTTP server library in pure Swift. Transporter5.4 0.0 L4 Moya VS TransporterA tiny library makes uploading and downloading easier. SwiftyOAuth5.3 0.0 L4 Moya VS SwiftyOAuthA small OAuth library with a built-in set of providers Malibu5.1 0.0 L5 Moya VS MalibuA networking library built on promises. BigBrother5.1 0.0 L5 Moya VS BigBrotherAutomatically sets the network activity indicator for any performed request. XcodeServerSDK5.1 0.0 L4 Moya VS XcodeServerSDKAccess Xcode Server API with native Swift objects. Net5.0 0.0 L5 Moya VS Netan httprequest wrapper. Curassow5.0 0.0 L2 Moya Moya or a related project? Popular Comparisons README Moya 14.0.0. [Moya Overview](web/diagram.png) This project is actively under development, and is being used in Artsy's new auction app. We consider it ready for production use. Installation Moya version vs Swift version. Below is a table that shows which version of Moya you should use for your Swift version. Note: If you are using Swift 4.2 in your project, but you are using Xcode 10.2, Moya 13 should work correctly even though we use Swift 5.0. Upgrading to a new major version of Moya? Check out our migration guides. Swift: :5.0 import PackageDescription let package = Package( name: "MyPackage", products: [ .library( name: "MyPackage", targets: ["MyPackage"]), ], dependencies: [ .package(url: "", .upToNextMajor(from: : Accods For Moya, use the following entry in your Podfile: pod 'Moya', '~> 14.0' # or pod 'Moya/RxSwift', '~> 14.0' # or pod 'Moya/ReactiveSwift', '~> 14.0' Then run pod install. In any file you'd like to use Moya in, don't forget to import the framework with import Moya. Carthage Carthage users can point to this repository and use whichever generated framework they'd like, Moya, RxMoya, or ReactiveMoya. Make the following entry in your Cartfile: github "Moya/Moya" ~> 14.0 Even cooler are the reactive extensions. Moya provides reactive extensions for ReactiveSwift and RxSwift. React Moya has a great community around it and some people have created some very helpful extensions. Contributing :ship: You can read more details about that in our contributor guidelines. Moya is released under an MIT license. See License.md for more information. *Note that all licence references and agreements mentioned in the Moya README section above are relevant to that project's source code only.
https://swift.libhunt.com/moya-alternatives
CC-MAIN-2021-17
refinedweb
1,110
59.9
Provides simple filtering and visualization tools for Monte-Carlo simulation data Blah It is released under the MIT license. import MCres #.. image:: # :align: center Documentation Refer to this page, Requirements MCres requires the following Python packages: - NumPy, Scipy: for basic numerical routines - astropy.io.fits: for angle units - corner: for plotting - matplotlib: for plotting - time: for basic stuff MCres is tested on Linux and Python 2.7 only, but should cross-plateform without too many issues. Installation If you use anaconda, the easiest and fastest way to get the package up and running is to install MCres using conda: $ conda install MCres --channel MCres You can also install MCres from PyPI using pip, given that you already have all the requirements: $ pip install MCres You can also download MCres source from GitHub and type: $ python setup.py install Contributing Code writing Code contributions are welcome! Just send a pull request on GitHub and we will discuss it. In the issue tracker you may find pending tasks. Bug reporting If you think you’ve found one please refer to the issue tracker on GitHub. Additional options You can either send me an e-mail or add it to the issues/wishes list on GitHub. Citing If you use MCres on your project, please drop me a line <mailto:{my first name}.{my family name}@obspm.fr>, you will get fixes and additional options earlier. License MCres is released under the MIT license, hence allowing commercial use of the library. Please refer to the LICENSE.txt file. Changelog 0.5.0 (2016-08-21) - Initial release. 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/MCres/
CC-MAIN-2017-47
refinedweb
285
64.91
This is a question about scope and closures in Python, motivated by an exercise in SICP. Much thanks for your time if you read this! A question (3.2) in SICP asks one to create a procedure "make-monitored", that takes in a function f (of one parameter) as input and returns a procedure that keeps track of how many times f has been called. (If the input to this new procedure is "num-calls" it returns the number of times f has been called, if it is "reset" it resets counter to 0 and anything else, it applies f to the input and returns the result (after appropriately incrementing the counter). Here is code in Scheme that I wrote that works: (define (make-monitored f) (let ((counter 0)) (define (number-calls) counter) (define (reset-count) (set! counter 0)) (define (call-f input) (begin (set! counter (+ 1 counter)) (f input))) (define (dispatch message) (cond ((eq? message 'num-calls) (number-calls)) ((eq? message 'reset) (reset-count)) (else (call-f message)))) dispatch)) def make_monitored(func): counter = 0 def dispatch(message): if message == "num-calls": return num_calls() elif message == "reset": reset() else: nonlocal counter counter += 1 return func(message) def num_calls(): nonlocal counter return counter def reset(): nonlocal counter counter = 0 return dispatch Besides the question whether the above code works, I'll answer the question "How would one go about solving this type of problem [...] in Python??". I think writing a decorator wrapping the function in a class would be more pythonic: from functools import wraps def make_monitored(func): class wrapper: def __init__(self, f): self.func = f self.counter = 0 def __call__(self, *args, **kwargs): self.counter += 1 return self.func(*args, **kwargs) return wraps(func)(wrapper(func)) This has the advantage that it mimics the original function as close as possible, and just adds a counter field to it: In [25]: msqrt = make_monitored(math.sqrt) In [26]: msqrt(2) Out[26]: 1.4142135623730951 In [29]: msqrt.counter Out[29]: 1 In [30]: msqrt(235) Out[30]: 15.329709716755891 In [31]: msqrt.counter Out[31]: 2 In [32]: @make_monitored ...: def f(a): ...: """Adding the answer""" ...: return a + 42 In [33]: f(0) Out[33]: 42 In [34]: f(1) Out[34]: 43 In [35]: f.counter Out[35]: 2 In [36]: f.__name__ Out[36]: 'f' In [37]: f.__doc__ Out[37]: 'Adding the answer' For f, you also see the usage as a decorator, and how the wrapper keeps the original name and docstring (which would not be the case without functools.wraps). Defining reset is left as an exercise to the reader, but quite trivial.
https://codedump.io/share/Dd6RZZNXoYd/1/tracking-number-of-function-calls--closures-224-la-sicp-in-python
CC-MAIN-2017-04
refinedweb
436
64.91
I'm trying to run a Flask app with Gunicorn. When I run gunicorn app:index TypeError: index() takes 0 positional arguments but 2 were given index from flask import Flask app = Flask(__name__) @app.route("/") def index(): return 'Hello, World!' gunicorn app:index respiter = self.wsgi(environ, resp.start_response) TypeError: index() takes 0 positional arguments but 2 were given index @app.route("/") def index(arg1, arg2): return 'Hello, World!' /python3.4/site-packages/flask/templating.py, line 132, in render_template ctx.app.update_template_context(context) AttributeError: 'NoneType' object has no attribute 'app' You have to pass a Flask instance to gunicorn, not a function name like you did with index. So if your app saved as app.py, then you have to run gunicorn as follows: $ gunicorn --bind 127.0.0.1:8000 app:app
https://codedump.io/share/vtfQAY65OJH2/1/running-flask-with-gunicorn-raises-typeerror-index-takes-0-positional-arguments-but-2-were-given
CC-MAIN-2017-09
refinedweb
135
51.85
Hello Ruis, in following two lines are written: #include <NTPClient.h> formattedDate = timeClient.getFormattedDate(); I get the following Error: ‘class NTPClient’ has no member named ‘getFormattedDate’ If I replace timeClient.getFormattedDate() with timeClient.getFormattedTime() there is no Error, but only time. In the Keywords getFormattedTime is listed, but not getFormattedDate. Do I need also #include NTPTimeClient.h ? Thanks for your help Peter Hello Peter, You’re using the wrong NTPClient library. Can you please remove your current library and install this NTPClient library forked that also has the date? I’m using the library forked by Taranais, because it comes with the date method: formattedDate = timeClient.getFormattedDate(); Hello Rui, I was in France for some time with no access to internet. Back home I used your solution and it worked. Thanks! It’s not helpfull for users, if different libraries with the same name exist. A solution may be NTPClient_t (for taranis) and NTPClient_w (for Weinberg), but this is out of our influence. Thanks again Peter Thanks for letting me know and I’m glad you made it worked! I’ll point anyone having the same problem to this thread. Regards, Rui Hi Rui The location library at this location has the Keywords file getFormattedTime is listed, but not getFormattedDate. Has the library been changed or updated.?? Thanks Murray @Murray Bold, you need to use the Taranais NTP Client library: Even though, it doesn’t have the getFormattedDate listed in the keywords file that function is available in that library. Hello Rui and other posters Peter and Murray, At some moment several sketches of me using NTPClient did not compile anymore, where they did this summer. Luckily I found your blogs. My sketches did compile in the past. I was not aware that I used the “Taranais-version” of NTPClient, but that should have been so. I guess the libaries-update utility of the Arduine IDE had overwritten at some moment in the short past the Taranais-version with the Weinberg. So I replaced the Weinberg by the Taranais. How we can prevent such happen again? Regards, Jop
https://rntlab.com/question/ntpclient/
CC-MAIN-2021-25
refinedweb
348
66.94
Content All Articles Python News Numerically Python Python & XML Community Database Distributed Education Getting Started Graphics Internet OS Programming Scientific Tools Tutorials User Interfaces ONLamp Subjects Linux Apache MySQL Perl PHP Python BSD PythonLabs released Python 2.1 Tuesday. It introduces new magic methods for rich comparisons, minor language tweaks, and new modules for the standard library. The most important change, though, is nested scopes. Because this change is likely to break some code, 2.1 doesn't give you nested scopes by default. The biggest change in 2.1 isn't really in 2.1. It will be in 2.2. To avoid breaking everyone's code, the Python developers introduced a __future__ module. If you want nested scopes, you have to import them from the future: __future__ from __future__ import nested_scopes Nested scopes confused me at first. Maybe some new programmers can learn from my mistake, and seasoned programmers can laugh at it. So for your edification or amusement, let's take a closer look at nested scopes. Scope determines which namespace is used to look up a given name. A namespace is a dictionary of variable, function, and class names. Any name you might define or assign to is in some namespace. In Python 2.0, there are, at most, three namespaces visible at any given time: a local namespace (names defined in the current function), a global or module namespace (names defined at the top level), and a built-in namespace (names predefined by Python). Python gives each function its own local name space. When Python 2.0 tries to find a name, it looks first in the local namespace, then the global, and finally in the built-in namespace. Some Python people call this the LGB rule. The LGB rule works great most of the time. When defining a function inside a function, however, it can bite you. Say you define function B inside of function A, and you assigned a few variables in A that you want to use in function B. Well, in 2.0, B doesn't see variables assigned in A. Say you assigned a variable named spam in A, and you want to use it in B. When you try, you get a NameError: global name 'spam' is not defined. Python just skips right over A's namespace. All you have is B's local namespace, the global namespace, and the built-in namespace. There are ways around this. To get B to see spam in Python 2.0, you might pass it as a default to your function in your function definition, for example: def B(spam=spam):. It's ugly, especially when you have several variables you want B to use, but it works. NameError: global name 'spam' is not defined def B(spam=spam): Also in Python News: BitTorrent Style Twisted Python Python Escapes Classroom Humongous Python Py in Print Python 2.1 introduces nested scopes. If our hypothetical function B is defined in A, and uses some name which has not been assigned in B, Python will now look for that name in the namespace of the enclosing scope in which it was defined or, in other words, A's namespace. Note the word "defined". This is where I got confused. To test out these new rules, I tried something like from __future__ import nested_scopes def A(): print "spam comes with %s" % (spam) def B(): spam = 'bacon' A() spam = 'eggs' A() B() You might think with nested scopes you would get both eggs and bacon with your spam; but you don't, you only get eggs. That's because where a function is defined determines scope, not where it is invoked. When I asked about this on comp.lang.python, Bjorn Pettersen helpfully informed me that this is the difference between lexical (or static) and dynamic scoping. Once I had the right names for the concepts, I found the differences explained in many places on the net. I also finally understood the difference between my() and local() in Perl, a language that uses both dynamic and lexical scoping. But I digress. The following example gets you eggs and bacon with your spam: from __future__ import nested_scopes def A(): print "spam comes with %s" % (spam) def B(): spam = 'bacon' def C(): print "spam comes with %s" % (spam) C() spam = 'eggs' A() B() Under 2.0, following the LGB rule, you still get eggs. Under 2.1 without the import statement you get eggs and warnings about overwriting global variables. With nested scopes you finally get some bacon. Function C gets access to names in B's namespace. You will find fancier nested scope tricks in Andrew M. Kuchling's What's New in Python 2.1, and even more examples and deeper details in the original Python Enhancement Proposal (PEP) for nested scopes. The nested scope change implies some changes in the use of from module import *, and it may cause havoc in some other cases. Details are in the PEP. You should start working with nested scopes now and take advantage of the grace period to fix up your code. In 2.2, nested scopes will be turned on by default. There will be no from __past__ import unnested_scopes from module import * from __past__ import unnested_scopes Stephen Figgins administrates Linux servers for Sunflower Broadband, a cable company. Read more Python News columns. Sponsored by: © 2015, O’Reilly Media, Inc. (707) 827-7019 (800) 889-8969 All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners.
http://archive.oreilly.com/pub/a/python/2001/04/19/pythonnews.html
CC-MAIN-2015-48
refinedweb
925
74.19
abstract base class for all Chart Views. More... #include <vtkSMContextViewProxy.h> abstract base class for all Chart Views. vtkSMContextViewProxy is an abstract base class for all vtkContextView subclasses. Definition at line 32 of file vtkSMContextViewProxy.h. Provides access to the vtk chart view. Provides access to the vtk chart. Reimplemented in vtkSMPlotMatrixViewProxy. Resets the zoom level to 100% Return the render window from which offscreen rendering and interactor can be accessed Subclasses should override this method to do the actual image capture. Called at the end of CreateVTKObjects(). Reimplemented from vtkSMViewProxy. Reimplemented in vtkSMPlotMatrixViewProxy. Used to update the axis range properties on each interaction event. This also fires the vtkCommand::InteractionEvent. The context view that is used for all context derived charts. Definition at line 72 of file vtkSMContextViewProxy.h.
http://www.paraview.org/ParaView3/Doc/Nightly/html/classvtkSMContextViewProxy.html
crawl-003
refinedweb
130
54.49
#include <unistd.h> #include <fcntl.h> /* Definition of AT_* constants */ #include <unistd.h>(). On success (all requested permissions granted, or mode is F_OK and the file exists), zero is returned. On error (at least one bit in mode asked for a permission that is denied, or mode is F_OK and the file does not exist, or some other error occurred), −1 is returned, and errno is set appropriately. access() and faccessat() shall fail if: The requested access would be denied to the file, or search permission is denied for one of the directories in the path prefix of pathname. (See also path_resolution(7).) Too many symbolic links were encountered in resolving pathname. pathname is too long. A component of pathname does not exist or is a dangling symbolic link. A component used as a directory in pathname is not, in fact, a directory. Write permission was requested for a file on a read-only filesystem. access() and faccessat() may fail if: pathname points outside your accessible address space. mode was incorrectly specified. An I/O error occurred. Insufficient kernel memory was available. Write access was requested to an executable which is being executed. The following additional errors can occur for faccessat(): dirfd is not a valid file descriptor. Invalid flag specified in flags. pathname is relative and dirfd is a file descriptor referring to a file other than a directory. faccessat() was added to Linux in kernel 2.6.16; library support was added to glibc in version 2.4... In kernel 2.4 (and earlier) there is some strangeness in the handling of X_OK tests for superuser. If all categories of execute permission are disabled for a nondirectory file, then the only access() test that returns −1. chmod(2), chown(2), open(2), setgid(2), setuid(2), stat(2), euidaccess(3), credentials(7), path_resolution(7), symlink(7)
http://manpages.courier-mta.org/htmlman2/access.2.html
CC-MAIN-2019-18
refinedweb
308
59.8
Type: Posts; User: gowrishwar I have tried memmove(). Even then it is throwing the same exception. Output: First-chance exception at 0x1026f448 (msvcr90d.dll) in Camera.exe: 0xC0000005: Access violation reading location... Thanks for the reply Skizmo Both pointers are valid, the data in bf_p->CirHandle.pBufData is 3677536032, which is unsigned int and I am Type Casting it to unsigned char. When I debug, the... Hi all, I am working on a camera to collect data. In the process one of the functions is throwing errors while copying the data from the buffer on board to local system buffer. The message... Hello all, I am working on a project and want to load excel libraries into C++ so that I can read/write data into cells. #include <iostream> #include <cmath> // Office XP Objects (2003) Thanks for your reply and I have found that it was a problem with my windows OS. I have reinstalled whole OS and then I am able to see NULL device in device manager. Looks like now I am stuck with... Looks like now I am stuck with an another problem. When I try to run it in Debug mode I am getting an error message saying "Unhandled exception at 0x004013be in EDxL1.exe: 0xC0000005: Access... I guess, I have found the solution. The null device is missing from Device Manager. I had to re-install the windows. Now I can see it. Thanks for reply. Hi, I am learning DirectX using a tutorial and when I try to compile a code which has #include <d3dx9.h> I got the error as though I have Microsoft DirectX SDK (March 2009) error PRJ0015... Hi, I am new to coding with macros. I have this code and I am trying to run this by dynamically loading a class from a DLL. #pragma once #ifndef DLLEXPORTS_H #define DLLEXPORTS_H Hi, I am new to coding with macros. I have this code and I am trying to run this by dynamically loading a class from a DLL. #pragma once #ifndef DLLEXPORTS_H #define DLLEXPORTS_H #ifdef...
http://forums.codeguru.com/search.php?s=8cd26b68d9c7042d42e7784572b513b3&searchid=6779041
CC-MAIN-2015-18
refinedweb
344
76.62
This is your resource to discuss support topics with your peers, and learn from each other. 03-07-2011 09:06 PM Hi all, I'm trying to move an Loader object across the screen and having problem. It is probably very noobish to ask for this type of question but I'm very new to ActionScript and the internet does not offer clear answer. I've found many people using the "movie clip" to simulate a movement but I don't know how to use the function (or even find it). The code I have right now to load the image onto the stage is: var obj: Loader = new Loader(); obj.load(new URLRequest("obj.png")); obj.x = 354; obj.y = 142; addChild(obj); Please give me some kind of documentation or sample code! Thanks!! 03-07-2011 09:25 PM 03-07-2011 09:26 PM package { import flash.display.Bitmap; import flash.display.Sprite; import flash.events.Event; import flash.ui.Mouse; public class Test extends Sprite { [Embed(source='library/crosshair.png')] private var crosshairClass:Class; private var crosshair:Bitmap = new crosshairClass (); public function Test() { Mouse.hide(); crosshair.height = 30; crosshair.width = 30; addChild(crosshair); stage.addEventListener(Event.ENTER_FRAME, mouseMove); } private function mouseMove(evt:Event):void { crosshair.x = mouseX - 15; crosshair.y = mouseY - 15; } } } 03-07-2011 09:30 PM THanks for the info, I've seen that code while researching. But what I am trying to simulate is an object falling down. So an object is placed at the top then falls down linearly (no gravity effect). I'm thinking this can be done using timer and shifting the y value one at a time with maximum of 30 fps (seems to be the suggested limit) but I don't know how to refresh an item everytime y value changes. 03-07-2011 09:33 PM The Tweener class lets you trigger an animation with one line of code; it can probably do what you want. There are examples at the posted link. 03-07-2011 09:35 PM Thanks! will look into it tonight. I'm surprise that there is no fundamental way to achieve something simple like an object move. 03-07-2011 09:41 PM Yes there are fundamental ways to move an object but you'll have to write more code - set up a stage event listener to call a handler function to update the position based on an ENTER_FRAME event etc. like the posted code. Tweener wraps the functionality up for you so it's just one line of code to add the animation. It's by far not the only way to move an object but it's convenient. 03-07-2011 10:01 PM Sounds familiar This is exactly what i do in my app : I have apples falling randomly from top. I have a 1. Initialize bitmap: [Embed(source='images/apple.png')] private var appleClass:Class; private var apple:Bitmap = new appleClass(); 2. I initialize the x,y coordinates of the apple this.apple.x=100; this.apple.y=0; mySub.addChild(this.apple); 3. Add listener for ENTER_FRAME event addEventListener(Event.ENTER_FRAME, onEnterFrame); 4. In the event handler i increment Y and update the apple coordinates // Calculate newY this.apple.y=newY; } Hope that gives you some idea... you can google for onEventFrame AS3 to see more examples out there...
http://supportforums.blackberry.com/t5/Adobe-AIR-Development/Moving-object/m-p/838329/highlight/true
CC-MAIN-2014-52
refinedweb
563
67.96
The script on this page appears to have a problem First I want to apologize for my bad English. I'm a Newbie and this is my first post. Be patient with me :) I'm facing this issue when using some jQuery code into my hybrid application. I found that this message is thrown whenever the script takes long time. 'Saint Google' points me to QWebPage::shouldInterruptJavaScript() and it seems that the way to override this message is reimplementing this slot. I did it but now, the script behavior it's not the desired. It seems like the slot it's called and interrupts the script although I always return false. The more annoying issue is that if I try to debug my custom slot, it's never been called!!! I should point out that the applications is running in a special scenario. The main application creates a form with a QWebView widget embedded. Different DLLs are called and a pointer to this form it's passed so they can use the QWebView widget. This is the original DLL code, where uiExt is the pointer to the form where the WebView is implemented. Everything works fine except the annoying script's message :( @ Html::Html(Ui::Form *uiExt) { ui=uiExt; ui->webView->load(QUrl("inf.html")); page=ui->webView->page(); frame=page->mainFrame(); connect( frame, SIGNAL(javaScriptWindowObjectCleared()),this, SLOT(populateJavaScriptWindowObject()) ); } @ This is the modified code using my custom class: @ Html::Html(Ui::Form *uiExt) { ui=uiExt; mypage=new CustomPage(ui->webView); ui->webView->load(QUrl("inf.html")); frame=mypage->mainFrame(); connect( frame, SIGNAL(javaScriptWindowObjectCleared()),this, SLOT(populateJavaScriptWindowObject()) ); } @ This is my reimplemented QWebPage to override the slot CustomPage.h @ #ifndef CUSTOMPAGE_H #define CUSTOMPAGE_H #include <QWebPage> #include <QWebView> class CustomPage : public QWebPage { Q_OBJECT public: CustomPage(QWebView *parent=0); signals: public slots: bool shouldInterruptJavaScript(); }; #endif // CUSTOMPAGE_H @ CustomPage.cpp @ #include "custompage.h" CustomPage::CustomPage(QWebView *parent) : QWebPage(parent) { parent->setPage(this); } bool CustomPage::shouldInterruptJavaScript() { //return QWebPage::shouldInterruptJavaScript(); //original slot return false; //to avoid the annoying message } @ As I stated, using this approach, CustomPage::shouldInterruptJavaScript() it's never called although the script's behavior it's not normal. What I'm missing? Thx in advance. I finally found the cause of the issue. As I stated, this code belongs to a DLL. The main application (.exe) calls this DLL and pass it a pointer to the form where the QWebView is contained. The purpose of this method is to have a main Widget created in the main (exe) application and share the embedded QWebView Widget, so whenever a call to a DLL is performed, this pointer is passed thus allowing the DLL to access to the QWebView to show its own content. Once the DLL is done, it returns back the control to the main application. The problem here is that I'm a newbie coming from VC++ and I probably inherit some bad manners. To my understand this code it's like a semi-modal dialog but I don't even create a dialog, I simply use the 'dialog' that the main application passes as a pointer. The DLL then perform their own actions and interacts with the user using the QWebView Widget. In VC++ this is achieved using the DoEvents() function that must be called in the main loop. In my project, I used a main loop that runs the DLL's code until the user exits the application (DLL) If I want to process the DLL's events, I need to place a QApplication::processEvents() so the loop looks like this: @ do { QApplication::processEvents(); ht->processHtml(); }while((ht->iAction==-1)||(ht->iAction==iMenu)); @ ht is my object that contains all the code to process the event handler. processHtml contains some code for retrieving data (I'll change the way to do this) and the while declarative contains the conditions to end the loop. Obviously this code is always performing multiple calls to processEvents but this way works like a charm in VC++. In Qt, this recurrent function call, takes more than 50% of the CPU usage and that's the reason why the script message error appears!!!! However, this doesn't explain why my own ShouldInterruptJavaScript slot it's never called. I'm now considering to set up a timer to avoid this massive CPU usage. Anyway I guess there are better approach to solve this issue. I accept suggestions :) @this way works like a charm in VC++@ oh please, stop lying... clean endless loop eat 100% CPU everywhere... And if you Develop with Qt(compiled with VS) in VS - YOU ARE using VC++. Qt is a set of libraries, framework(if you wish) and not a kind of compiler interpreter or something wild else... So, just use method that was found for a long long time ago: use Sleep(1) in endless loop if it eats to much CPU! Yeap, you are absolutely right. I forgot to mention the Sleep which, of course, I use in VC++. Sorry, it's my fault. But it doesn't take 100% CPU, I guess it depends on the platform or microprocessor architecture but in modern computers it only takes about 50% (which confirms what happened to me) In fact, in the last part of my post I mentioned some kind of solution using something similar to the Sleep() function: a timer. What is the best way to achieve this in Qt? I read something about QThread::msleep or QWaitCondition but I don't know if it's better build my own timer. I'm just using WINAPI Sleep(mseconds) on Win platforms and usleep() on *nix... have never had problems with them... And something native in Qt? Is there a Sleep() function in Qt? As I can see there are some tricks like those I mentioned before or even the QTest:qWait() function. Maybe QThreat is the best way but in such case I need to reimplement the function because it's static protected. Here is the QTest:qSleep source: @void QTest::qSleep(int ms) { QTEST_ASSERT(ms > 0); #ifdef Q_OS_WIN Sleep(uint(ms)); #else struct timespec ts = { ms / 1000, (ms % 1000) * 1000 * 1000 }; nanosleep(&ts, NULL); #endif }@ bq. Sleeps for ms milliseconds, blocking execution of the test. qSleep() will not do any event processing and leave your test unresponsive. Network communication might time out while sleeping. Use qWait() to do non-blocking sleeping. About qWait: bq. Waits for ms milliseconds. While waiting, events will be processed and your test will stay responsive to user interface events or network communication. Thx AcerExtensa. In fact, while I'm posting, I'm modifying my code to include QTest:qWait(). This method includes events processor which is what I'm looking for. Well, it seems this issue is solved (thx AcerExtensa again) I use the QTest:qWait() function and did the trick but instead of import QTest, I had to include <QtTest/QTest> and then include qtestlib in the project. Anyway this left unresolved why I can't reimplement ShouldInterruptJavaScript(). What's wrong with my custom QWebPage? bq. Warning: Because of binary compatibility constraints, this function is not virtual. If you want to provide your own implementation in a QWebPage subclass, reimplement the shouldInterruptJavaScript() slot in your subclass instead. QtWebKit will dynamically detect the slot and call it. Your implementation is correct for Qt 4.8... which version are you using actually? 4.7.4. And if I create an object derived from CustomPage and set a degug point in ShouldInterr....., this slot it's never called. What is more susprising is the fact that using my custom class, the "The script on this page appears to have a problem" message it's never displayed but, instead, the script ceases to work normally. I need to go for today.. will test this tomorrow... Thx. I'll try to determine the cause of this strange behavior. Hi, I've tested this function today and it does work properly... So, the problem is in your code somewhere... Here is the test project: "WebPageTest.tar.gz": Just run it and click Test button... in about 20-30 second you will get function name printed in output... Ok, I'll check it out and compare with my code. Thanks again Well, I've tried out your code and... Obviously works fine :) When I start your script, the custom "ShouldInterru..." slot is called after 10-15 seconds (as expected). Surprisingly, when I get the script error message in my code (not always), is displayed after 1 or 2 seconds. In fact I though this was the normal behavior. In order to check if there were something I missed in my html code, I modified my code to call your html from my DLL and... the "ShouldInterrupt..." it's never called!!!!!!. And what is most strange, neither with the original class or the custom one. The application simply freezes. This takes me to square one. There must be something I'm doing terrifyingly wrong in my code. As I stated previously I'm calling a DLL and passing a pointer to the form which contains the QWebPage. To discard an issue in this call I'm gonna try to recreate the same issue in the EXE application and override the "ShouldInterr..." slot. Today I've tried to reproduce again the problem using the code AcerExtensa sent me and it takes more than 1 minute to "ShouldInterruptJavaScript" to be called the first time. I don't know if this is a normal behavior (I'm debugging the code). After such time, the slot it's triggered every 15 seconds (as expected). Friday (when I tried this the very first time, the slot was called after just 15 seconds). Anyway in my case, the problem I think it's a different one. My project consists in a main application (EXE) and different DLLs. The EXE creates a window with a WebView Widget. This main application interacts with the user using this Widget so I must connect the javaScriptWindowObjectCleared signal with the populateJavaScriptWindowObject slot. @ connect(ui.webView->page()->mainFrame(), SIGNAL(javaScriptWindowObjectCleared()),this, SLOT(populateJavaScriptWindowObject())); @ Whenever a DLL is called, the main application pass it a pointer to the WebView so it can perform the same action thus allowing the interaction through the same WebView. Before doing that I disconnect the signal: @ disconnect(ui.webView->page()->mainFrame()); @ Probably this is where I screwed up. I guess I'm not disconnecting the signal properly and there are some abnormal behavior behind this. Maybe the Script error I get is not from the DLL's side but the EXE side. This could be the reason why my ShouldInterruptJavaScript slot is never called (in the DLL side). With this in mind, I tried this at home: @ disconnect(ui.webView->page()->mainFrame(), SIGNAL(javaScriptWindowObjectCleared()),this, SLOT(populateJavaScriptWindowObject())); @ but the same occurs. Things seems to change when I tried this: @ui.webView->page()->disconnect();@ Unfortunately my HDD crashed and now I'm recovering the mess so I can't confirm the problem is solved. Finally I discovered what was causing the issue. The problem is the way I use QWebView. In my project I have a main application (exe) that creates a QWebView widget. In order to interact with it I connect javaScriptWindowObjectCleared with populateJavaScriptWindowObject @connect(ui.webView->page()->mainFrame(), SIGNAL(javaScriptWindowObjectCleared()),this, SLOT(populateJavaScriptWindowObject())); @ In the html side I call my slot using this way @ aELEMENTOS</a> @ (Note: I deliberate misspelled the <a> & javascript tag in this post to avoid errors in the preview) So whenever the user clicks in this option my function MyExe.submit() is called in the EXE side. This function calls a DLL and passes a pointer to the QWebView but before doing that I disconnect the signal in the EXE @ void MyEXE::submit() { ... QLibrary myLib("C:\Users\mahg\Documents\Qt\DLL\debug\DLL_Test2.dll"); typedef int (MyDLL)(Ui::Form, int); MyDLL myDLL = (MyDLL) myLib.resolve("Dll"); if (myDLL) { ... disconnect(ui.webView->page()->mainFrame(),0,0,0); int i=myDLL(&ui); ... } ... } @ Note: the original code I wrote to disconnect was: @ disconnect(ui.webView->page()->mainFrame(), SIGNAL(javaScriptWindowObjectCleared()),this, SLOT(populateJavaScriptWindowObject())); @ Then, the DLL connects the signal javaScriptWindowObjectCleared with its own populateJavaScriptWindowObject and interacts with the user through the QWebView. So far everything worked fine but there is a problem with the ShouldInterruptJavaScript. This function is triggered if the JavaScript code takes long time, but I discovered that the trigger doesn't occurs in the DLL but in the EXE. This only occurs if I call the DLL inside the function MyEXE::submit(). If I call it outside this function everything works fine. I guess Qt can't disconnect theses slots if we are still processing some code inside the slot called from the html Is this a normal behavior? I can override the ShouldInterruptJavaScript in the main (EXE) code but this is not fair for me. If there is no workaround for this I could try to call the DLL outside the MyEXE::submit()
https://forum.qt.io/topic/13560/the-script-on-this-page-appears-to-have-a-problem
CC-MAIN-2017-43
refinedweb
2,155
65.12
On Tue, Feb 19, 2008 at 05:42:07PM +0300, Pavel Emelyanov wrote:> Nick Andrew wrote:> > On Wed, Feb 20, 2008 at 01:06:09AM +1100, Nick Andrew wrote:> >> Here is a series of 9 patches to init/Kconfig intended to improve the> >> usefulness and consistency of the help descriptions. The patches are> >> against linux-2.6.24.2.> >> [...]> >> Patch 3> >> USER_NS> >> PID_NS> > What about UTS_NS, IPC_NS and NET_NS? > Their descriptions can be improved in the same way :)So far I have edited only init/Kconfig, that's what these 9patches are for. Next I'll do block/Kconfig. Eventually I expectto get to net/Kconfig which is where NET_NS is configured,but I don't know where UTS_NS and IPC_NS come from in 2.6.24.2.I expect I'll have to start patching against a git tree soon,to be sure to see the latest code. I assume this should beLinus' tree?Is there any actual documentation on user namespaces and friends?I think I grasp the pid namespaces concept; I am having a littledifficulty visualising what function user namespaces performs."provide different user info" isn't a very useful description andI'd fix it if I understood what it is supposed to mean.To make a guess at it, how about: Enable support for user namespaces. This is a function used by container-based virtualisation systems (e.g. vservers). User namespaces ensures that processes with the same uid which are in different containers are isolated from each other. Answer Y if you require container-based virtualisation like vservers. If unsure, say N.Nick.-- PGP Key ID = 0x418487E7 Key fingerprint = B3ED 6894 8E49 1770 C24A 67E3 6266 6EB9 4184 87E7
http://lkml.org/lkml/2008/2/19/237
CC-MAIN-2016-22
refinedweb
283
64.91
Yes, I am getting "undefined reference to `vtable for Window'" Hello, So, I am getting the error when I do the build: $ clang++ -g -std=c++14 subc*.cpp -I/usr/include/qt4 -I/usr/include/qt4/QtGui -I/usr/include/qt4/QtCore -lQtCore -lQtGui $ tmp/subcl-f65a46.o: In function Window': undefined reference tovtable for Window' clang: error: linker command failed with exit code 1 (use -v to see invocation) I am on Linux, I am not using Qt Creator, I am not using qmake. That is because this GUI qt project will be added to a (very) large project with its own build system based on make files. This is the example straight out of the Qt For Beginners page. // subcl.h #ifndef SUBCL_H #define SUBCL_H #include <QWidget> class Window : public QWidget { Q_OBJECT public: explicit Window(QWidget *parent = 0); virtual ~Window(); signals: public slots: }; #endif // subcl.cpp #include "subcl.h" Window::Window(QWidget *parent) : QWidget(parent) {} Window::~Window(void) {} // subclmain.cpp #include <QApplication> #include "subcl.h" int main(int argc, char **argv) { QApplication app (argc, argv); Window window; window.show(); return app.exec(); } I've done the googling. Can someone help me with this -- thank you! Note, I added the virtual desctructor (did not help.) After adding the Q_OBJECT macro you must run the header through moc, compile the generated source, and include it in the link stage. Normally qmake would do that for you.
https://forum.qt.io/topic/64832/yes-i-am-getting-undefined-reference-to-vtable-for-window
CC-MAIN-2017-39
refinedweb
237
58.48
Make listbox .selected Items be an ns IDOMNode List RESOLVED FIXED in mozilla45 Status () People (Reporter: mozilla, Assigned: smaug) Tracking ({addon-compat, dev-doc-needed}) Points: --- Firefox Tracking Flags (Not tracked) Details Attachments (6 attachments, 1 obsolete attachment) The following code results in a JS error: nsCOMPtr<nsIDOMNodeList> selectedItems; nsCOMPtr<nsIDOMXULMultiSelectControlElement> listbox (do_QueryInterface(mDOMNode)); if (listbox) { listbox->GetSelectedItems(getter_AddRefs(selectedItems)); if (selectedItems) { PRUint32 length = 0; selectedItems->GetLength(&length); for ( PRInt32 i = 0 ; i < length ; i++ ) { nsCOMPtr<nsIAccessible> tempAccessible; nsCOMPtr<nsIDOMNode> tempNode; selectedItems->Item(i, getter_AddRefs(tempNode)); The call to Item gets a JS error complaining that the method does not exist in that object. The if() passes and the call to Length() succeeds too. There is a comment in the nsIDOMXULMultSelectCntlEl.idl about waiting to get nsIDOMNodeList scriptable and mutable for the SelectedItems property. So I guess the problem lies in the nsIDOMNodeList impl. filing on xpconnect because I can get an nsIDOMNodeList back from a straight C++ call and it works fine. Seems like a problem in the JS-to-C++ conversion somewhere ( even it is just in the way nsIDOMNodeList is put together ) From what I can tell, selectedItems is represented by a JS Array. Thus it doesn't have an Item method, and doesn't truly implement an nsIDOMNodeList. In the code where I exposed this we have a workaround. So the priority I guess is pretty low. Not exactly sure what should get fixed here. IIRC someone had said the nsIDOMNodeList just wasn't completely implemented from the JS side...but I probably don't remember correctly. ;-) So it sounds more like a DOM issue than an XPConnect issue correct, and probably should be reassigned? The problem is that selectedItems is implemented in XBL: istbox.xml#40 It is a pure JS array, thus it has a length method, but no item() method. It is possible to have a NodeList represented as a JS array (using DOMClassInfo), but I'm not sure it is possible to have a JS array implemented as a NodeList. A solution would be to declare the selectedItems property of the listbox binding as its own binding, which could then implement a custom .item() method, thus emulating a NodeList. Thoughts? But this has nothing to do with XPConnect, does it? Shouldn't this be reassigned to DOM Level 0? I don't know actually... perhaps XPConnect could internally convert the call to .item() to a js array call. I know next to nothing about how XBL interacts with XPConnect/DOM, sorry :( If someone wants to make a case for adding exposing attributes of an array as XPCOM methods that could be mapped to interfaces, then another bug would probably be in order. Couldn't you add a JavaScript function named item to the array? anArray.item = function(index) { return this[index]; } dbradley, yes that's another solution. It seems reasonable to me to expect a complete implementation of the interface from the XBL implementor (in this case, the listbox binding), just like a c++ implementation has to provide a complete implementation of the interface. (I don't think it's reasonable to expect XPConnect to "complete" an incomplete XBL/JS implementation) So I guess this bug should go to whoever is in charge of listbox.xml/tree.xml, if my reasoning is correct. cc'ing jband for advice - I don't see a reason to hack xpconnect here. Over to widgets Assignee: dbradley → rods Component: XPConnect → XP Toolkit/Widgets Setting default QA - QA Contact: pschwartau → jrgm seems form controls related Assignee: rods → jkeiser -> default owner. This is not HTML form controls at least. Changing XPConnect for this case seems unnecessary and even bad. Therefore there are two options: (1) have the XBL implement nsIDOMNodeList functions (this seems like a wonderful idea) (2) have the caller not use it as an nsIDOMNodeList since it *isn't* one. I don't much care; but I would vote for solution (1). Assignee: jkeiser → jaggernaut Summary: js wrapped nsIDOMNodeList missing the Item method → Make listbox.selectedItems be an nsIDOMNodeList jgaunt, if it's fairly easy for you, could you test this fix with the code you wanted to use? Uh, the code has already been changed and checked in for some time. I wouldn't say it would be easy. And I really don't have the time immediately to test this, but the exact code I was using is in the bug. Assignee: jag → nobody This bug breaks the code in XULListboxAccessible::SelectedRowIndices as explained in bug 994964 comment 73-79. Specifically, |item| here <> is *always* going to be null, so effectively this method never returns correct results. XULListboxAccessible::SelectedCells and XULListboxAccessible::SelectedCellIndices are similarly affected. accessible/tests/mochitest/table/test_sels_listbox.xul exercises this code but I didn't bother checking why it passes. CCing you guys in case you care enough to continue to investigate. Actually I did end up investigating a bit more, and the caller of SelectedRowIndices (xpcAccessibleTable::GetSelectedRowIndices) just ends up creating and returning a zero-length array. The reason that the test doesn't catch this is a bug in the test: <>. Here when we try to compare the array entries with what we expect, we loop over based on selCols.length, which of course would be 0 in this case so we don't end up examining any array elements. If I change that loop condition to use aSelIndexesArray.length which is what it should use, the test would fail as I expected. yzen, eejay, Marco want to take it? you just need to make the listbox.xml thing return something implementing nsIDOMNodeList, and there aren't' many 1xxxxx bugs left ;) Flags: needinfo?(gijskruitbosch+bugs) Make it possible to create NodeList objects from JS (I think having just ctor is enough. no methods for modifying the list) (In reply to Olli Pettay [:smaug] from comment #20) > Created attachment 8677771 [details] [diff] [review] > chrome_ctor_for_nodelist.diff > > Make it possible to create NodeList objects from JS > (I think having just ctor is enough. no methods for modifying the list) Why not? This will mean that every time the selection changes in a multiple-select listbox, we have to construct a new NodeList on the JS side. That's not going to be fun if the number of selected items is high... Flags: needinfo?(gijskruitbosch+bugs) → needinfo?(bugs) Actually, maybe this is a dumb question, but: can't the JS side of this just implement something that's an nsIDOMNodeList in JS? It's not a particularly large interface, so it wouldn't be that much overhead... We want to make nsIDOMNodeList a builtinclass (and eventually drop nsIDOMNodeList and have just the webidl NodeList). Anyhow, I'm actually adding ChromeNodeList which has a ctor and way to append and remove nodes so that "live" nodelist is possible. That is that listbox seems to require after all. Flags: needinfo?(bugs) This adds a ChromeOnly ChromeNodeList so that chrome js can create and modify a proper NodeList object. xul:listbox uses currently a JS Array for that, but obviously that doesn't work with C++ a11y code which expects the interface to return a proper nodelist. The implementation is pretty much the smallest possible to fulfill the requirements listbox has. Attachment #8678163 - Flags: review?(amarchesini) (that patch obviously is missing all the listbox changes) Flags: needinfo?(gijskruitbosch+bugs) (In reply to Olli Pettay [:smaug] from comment #26) > (that patch obviously is missing all the listbox changes) ...which Gijs will do Not sure what to do with this: Trevor, can you advise? The basic implementation in the XUL thing isn't difficult, but updating callers is "interesting" and might have add-on impact. Flags: needinfo?(gijskruitbosch+bugs) → needinfo?(tbsaunde+mozbugs) I believe this works, but considering the hacks I already saw, I guess only try and time will tell... Attachment #8678917 - Flags: review?(dao) Comment on attachment 8678163 [details] [diff] [review] chromenodelist.diff (some more tests) Review of attachment 8678163 [details] [diff] [review]: ----------------------------------------------------------------- ::: dom/base/ChromeNodeList.cpp @@ +10,5 @@ > +using namespace mozilla; > +using namespace mozilla::dom; > + > +already_AddRefed<ChromeNodeList> > +ChromeNodeList::Constructor(const mozilla::dom::GlobalObject& aGlobal, drop mozilla::dom:: @@ +11,5 @@ > +using namespace mozilla::dom; > + > +already_AddRefed<ChromeNodeList> > +ChromeNodeList::Constructor(const mozilla::dom::GlobalObject& aGlobal, > + mozilla::ErrorResult& aRv) mozilla:: ::: dom/base/ChromeNodeList.h @@ +9,5 @@ > + > +namespace mozilla { > +namespace dom { > + > +class ChromeNodeList : public nsSimpleContentList final? @@ +18,5 @@ > + { > + } > + > + static already_AddRefed<ChromeNodeList> > + Constructor(const mozilla::dom::GlobalObject& aGlobal, 1. drop mozilla::dom:: 2. I think you must declare/forward declare GlobalObject and ErrorResult here. @@ +19,5 @@ > + } > + > + static already_AddRefed<ChromeNodeList> > + Constructor(const mozilla::dom::GlobalObject& aGlobal, > + mozilla::ErrorResult& aRv); and mozilla:: Attachment #8678163 - Flags: review?(amarchesini) → review+ (In reply to :Gijs Kruitbosch from comment #28) > Not sure what to do with this: > > > nsIDOMXULMultSelectCntrlEl.idl#29 > > Trevor, can you advise? > > The basic implementation in the XUL thing isn't difficult, but updating > callers is "interesting" and might have add-on impact. personally I'd just drop the comment. The methods might not be strictly required anymore (I wasn't even aware they existed), but they don't really hurt right? so I don't see any reason to bother clean them up. Flags: needinfo?(tbsaunde+mozbugs) So unfortunately the trypush here: has reftest orange. When run locally, I see: 0:02.95 JavaScript error: chrome://global/content/bindings/listbox.xml, line 177: ReferenceError: ChromeNodeList is not defined That makes sense because the constructor is ChromeOnly, and reftests don't run with chrome privileges. Unfortunately, that means that the binding is not guaranteed access to it in its enclosing window. We don't currently use listboxes in content-privileged code, that I can tell, but it's not easy to be 100% sure about that, and it could change... I see a number of options: 1) find some way to expose the constructor to XBL 2) disable the test and move on 3) somehow make the test run with chrome privileges (rewrite as a mochitest, essentially, AIUI, because reftests never have chrome privileges, from what I can tell on #developers) 4) add fallback code to the binding that uses an array with append() and remove() polyfilled, if ChromeNodeList is not available (thus regressing the thing this bug aims to fix in those circumstances). Olli/Dão, what makes the most sense to you? Flags: needinfo?(dao) Flags: needinfo?(bugs) (FWIW, I actually think it would make more sense to have XUL tests run with chrome privileges, because now that we have chrome-only CSS properties this problem is only going to get worse.) (In reply to :Gijs Kruitbosch from comment #37) > 4) add fallback code to the binding that uses an array with append() and > remove() polyfilled, if ChromeNodeList is not available (thus regressing the > thing this bug aims to fix in those circumstances). What motivated the recent activity in this bug in the first place? What code requires selectedItems to be an nsIDOMNodeList rather than a JS array? Flags: needinfo?(dao) C++ Accessibility code. Flags: needinfo?(bugs) ? Flags: needinfo?(gijskruitbosch+bugs) (In reply to Olli Pettay [:smaug] from comment #41) > ? Yes. Landed it with that updated. Flags: needinfo?(gijskruitbosch+bugs) Status: NEW → RESOLVED Closed: 4 years ago Resolution: --- → FIXED Target Milestone: --- → mozilla45 status-b2g-v2.5: --- → fixed removing the b2g 2.5 flag since this commit has been reverted due to an incorrect merge, sorry for the confusion status-b2g-v2.5: fixed → --- Looks like some mdn pages should be updated. In particular, * * NodeList.append() and NodeList.remove() isn't there at present (). I'm not sure how standard these methods are intended to be. Should this change be flagged for mentioning to addon authors? It might have been nice if .append() had been called .push(), for extra backwards Array compatibility? Flags: needinfo?(gijskruitbosch+bugs) Keywords: dev-doc-needed (In reply to aleth [:aleth] from comment #48) > Looks like some mdn pages should be updated. In particular, > > * >- > selectedItems indeed. looks like that doc has been wrong, given that selectedItems is about where the attribute is defined to be 'readonly attribute nsIDOMNodeList selectedItems;' > > * NodeList.append() and NodeList.remove() isn't there at present > (). I'm not sure > how standard these methods are intended to be. append or remove were not added to NodeList. They are methods of ChromeNodeList, which is totally unstandard, just like the whole listbox is. must not be updated because of the changes in this bud. > > Should this change be flagged for mentioning to addon authors? Hmm, possibly > It might have been nice if .append() had been called .push(), for extra > backwards Array compatibility? There is still slight chance that NodeList will become ArrayClass, , so I wouldn't add any Array-like methods to NodeList for now. Flags: needinfo?(gijskruitbosch+bugs) Assignee: nobody → bugs
https://bugzilla.mozilla.org/show_bug.cgi?id=120684
CC-MAIN-2019-35
refinedweb
2,112
56.76
Hi Tom, Tom Roberts wrote: > I am implementing the ability to read and write a TNtuple into my > Geant4 simulation program. I found that I need to link with libTree, > libCint, and libCore. When I try to use a TNtuple, I get the error > Error: cannot open file "bool.h" :0: > But the TNtuple file can be written and read correctly. I'm guessing > that Cint is unhappy, but for a simple TNtuple it is not needed. I do not understand why yo get this error message. We need more info about the line/function producing this error. I include below a trivial main program creating a ntuple into a ROOT file and showing (one line) how to compile & link this program see also: > > I want to distribute a binary version of the program to users who > probably don't have Root installed, and who are physicists but not C++ > programmers. That error message will be confusing, especially to > people who never use Root.... > > What files and directories do I need to include in my distribution, > beyond those 3 shared objects? Is there any simple way to reduce what > is needed? > This would be BADLY wrong! Installing ROOT is so simple. It is much better if people download the binary tar file from or install from source in the unlikely case that one of our binary distributions is not appropriate for their case. Example of main program tom.cxx #include "TNtupleD.h" #include "TFile.h" #include "TRandom3.h" int main() { TFile *file = TFile::Open("tom.root","recreate"); TNtupleD *ntuple = new TNtupleD("ntuple","example","x:y:z"); TRandom3 r; for (int i=0;i<10000;i++) { double x = r.Gaus(0,2); double y = r.Gaus(-2,1); double z = r.Uniform(-3,3); ntuple->Fill(x,y,z); Procedure to compile & link where ROOTSYS is an environment variable pointing to the directory where ROOT is installed. Rene Brun Received on Tue Dec 19 2006 - 11:36:16 MET This archive was generated by hypermail 2.2.0 : Mon Jan 01 2007 - 16:32:02 MET
https://root.cern.ch/root/roottalk/roottalk06/1625.html
CC-MAIN-2022-21
refinedweb
345
67.55
Setup jshint for Ext JS? Follow Ann Created April 27, 2012 21:00 I'm using Ext JS 4.1 and I'd like to enable jshint for my project, but it says "Ext" undefined. Is there a way to configure jshint in WebStorm 4.0 to know about Ext JS? Type into the first line in your extjs file, to exclude the Ext scope. the missing blank between the /* and the "global" is important. I use the same config for codekit and it works for me. Thanks, this works. Although, it would be nice to be able to set a config for my project to exclude the Ext scope, instead of having to modify every file, but I'm happy to have a solution. it would be the best, if phpStorm has also a option to define a list of namespaces to exclude them from jsHint. that makes sense, if you work with many files in js and you have some global functions or own namespaces. otherwise you must define all of these global functions / custom namespaces in every file. ;)
https://intellij-support.jetbrains.com/hc/en-us/community/posts/206369899-Setup-jshint-for-Ext-JS-
CC-MAIN-2020-40
refinedweb
181
83.15
jarrod roberson wrote .. > On 3/6/06, Graham Dumpleton <grahamd at dscpl.com.au> wrote: > > > > > > FWIW, just because mod_dav is taking over the bulk of the response > > handling, can't see why specific URLs couldn't be intercepted and > > made to fire off his existing Java implementation. He hasn't explained > > the relationship between URL namespace managed by mod_dav and > > the Java stuff to be able to explore that avenue though. > > > > Graham > > > > it gets kind of complicated, but the folders we are trying to stream are > in > the middle of a directory structure that is handled by mod_dav Directory > directive, it seems that mod_dav doesn't play nice with mod_proxy or > mod_rewrite in our case. I am _not_ an Apache 2 expert by any means, but > they guys that are, asked me if I could get this done "inline" so as not > have to deal with the complications that Apache is causing. Mod_dav registers three handler hooks: ap_hook_handler(dav_handler, NULL, NULL, APR_HOOK_MIDDLE); ap_hook_post_config(dav_init_handler, NULL, NULL, APR_HOOK_MIDDLE); ap_hook_fixups(dav_fixups, NULL, NULL, APR_HOOK_MIDDLE); The response handler will only be run if req.handler is set to "dav-handler". It will be set to this by dav_fixups(). Mod_python also runs as a middle hook in fixup phase, but if you can get the ordering correct you could register a mod_python fixup handler which override the req.handler attribute when request is against a specific URL so that it is handled by something else. Unfortunately, 3.2.8 and earlier versions of mod_python probably aren't going to help. If you were using mod_python from subversion repostory it probably would though as req.handler is writable in that version where as it wasn't in earlier versions. Anyway, as a test to sort out ordering, register a fixup handler: PythonFixupHandler _handler_check from mod_python import apache def fixuphandler(req): req.log_error("handler = %s" % req.handler) return apache.OK If the error log shows req.handler already set to "dav-handler" you are in business, if not, play with order to PythonFixupHandler relative to directives that enable mod_dav on the directory so that mod_python fixup handler is run second. If you then mod_python from subversion repository, you could do: from mod_python import apache def fixuphandler(req): if req.uri = "/some/path": req.handler = "name_of_java_handler_module" return apache.OK where req.handler is the handler name for the Java module which knows how to performing ziping of stuff identified by req.filename. If necessary, you could modify req.uri or req.filename. See: Another alternative is to use: from mod_python import apache def fixuphandler(req): if req.uri = "/some/path": req.internal_redirect("/some/other/path") return apache.DONE The "/some/other/path" would be what identifies the Java stuff. Finally, could also consider triggering mod_proxy. See: As I pointed out though, these tricks require subversion version of mod_python. Even if you do handle it inline, you still need to intercept it like above to trigger a mod_python handler to do it, or intercept using Location directive. Graham
http://modpython.org/pipermail/mod_python/2006-March/020554.html
CC-MAIN-2018-47
refinedweb
500
57.47
149 Joined Last visited Days Won2 Community Reputation7 Neutral About beeemtee - RankInitiate - Birthday 05/16/1975 Contact Methods - Skype birkasmate Personal Information - Name Máté - Location Budapest, Hungary - Interests Proud dad, interested in Linux, Python, CGI, Houdini, Nuke, Django, whatnot.. beeemtee replied to beeemtee's topic in ScriptingThanks tjeeds! That did the trick. - beeemtee started following Promoting AttribCreate's value parameter to asset interface beeemtee posted a topic in ScriptingHi, is it possible to promote the Attrib Create operator's value parameter to a SOP level asset's interface in a way that allows it to use point expressions? For example: rand($PT) If I create a simple link, the expression does not evaluate properly since it's the value that gets linked and not the expression. It's seems possible to hack it around with callbacks but that way the highlighting wouldn't work and relative references in the expression would point to different nodes. Is there a 'good' solution for this problem? thanks in advance Mate beeemtee replied to beeemtee's topic in ScriptingThat is exactly what I needed. Thanks! beeemtee posted a topic in ScriptingHi, I would like to ask that what is the preferred way to determine that the hip is currently opened in hbatch or in houdini? My wild guesses like '$0' and '$ARGV' are not doing the trick. Thanks in advance! Mate beeemtee replied to beeemtee's topic in Lounge/General chatThanks! Yes, I think this topic could be the place for qLib related discussion since github doesn't provide forum functionality and qLib don't have a dedicated website yet. If the odforce superiors think that it should be moved and/or renamed to reflect this I would be grateful if they would do this for us. No. Unfortunately the current and upcoming releases won't support H11, since it uses the H12 only features of namespaces and asset versioning. It seems that those two assets (camera_frustrum_ql, and curve_offset_ql) already used the new naming scheme in v0.0.30 and thats the reason why H11 can not load them. More to that, we also depend on H12's new geometry engine features, like the more general handling of P and N attributes in VOP SOPs and the new attribcreate operator. This means that even assets that gets loaded to H11 may or may not work properly in H11. To put it simply we currently don't have the resources to backport, to test and to maintain the assets under H11. It's not that it's not possible, so if there is big demand for this, we are happy to help someone who is motivated enough to do the job! cheers Mate - beeemtee posted a topic in Lounge/General chatDear fellow Houdinistas! We are pleased to announce that after more than two years of tinkering, qLib - our open source asset library for Houdini - has reached version 0.1 . qLib is a library of more than a hundred more or less simple tools that we built during and beside production work as Houdini artists. When we started qLib we wanted to have a library that is documented, and actively developed and maintained. Later we wanted version control and decided to embrace the open source development model, so we put the whole library up to github and made it public. But now we want even more.. Now we want to invite all of you to test, to comment, to criticize, to report bugs, to help us to write better docs, to fix tools that doesn’t work as intended, to share your ideas and to share your assets that you find useful and that you have no problem with others finding it useful too. We believe that Houdini has a wonderful user community with lots of clever and helpful member, so we hope that a project like qLib can focus that knowledge and wisdom into tools thus making every Houdini user’s life a little bit better. Even better.. The qLib team beeemtee posted a topic in General Houdini Questions Any ideas regarding this? Mate - Thanks Mario! Please check - if you didn't already - (perlin, 4d-in, 1d-out) since it also seems corrupted. Mate unified_noise_analyze_with_chops_perlin.hip - Ok, I will submit it. Thanks for your help! - Thanks Jeff! I attached a modified version of your file with the signature of the Unified Noise set to f4 (vector4 input float output) and the fractal type set to fBm (I left the noise type at Simplex). This is one of the cases where the problem is present. ps.: I forgot to mention in my original post that the output signature must be float to see the problem. unified_noise_analyze_with_chops_problematic.hip - Thanks Julien, but my question is about some specific settings of the Unified Noise operator which is intended to output its results in the 0-1 range for every noise and fractal types. Actually it's not the output range that is incorrect, but the average (middle point) of the result, which is harder to detect, but can cause strange results later in your scene if you expect it to be in the middle. beeemtee posted a topic in General Houdini QuestionsHi, if the input signature of the Unified Noise VOP is vector4, the noise type is Perlin or Simplex and the fractal type is other than None the output is biased, so that the average of the resulting noise is not around 0.5 but some higher value. It is also apparent that in these cases the average that Unified Noise outputs is considerably different - around the half of - that the calculated average by Attrib Promote. For the sake of simplicity I used Pyro Noise in the attached file, but my tests shows that the problem is rooted in Unified Noise. My question is that is it a bug or some inevitable implementation side effect (no pun intended)? thanks in advance Mate unified_noise_problem.hip beeemtee replied to beeemtee's topic in General Houdini QuestionsThanks! beeemtee posted a topic in General Houdini QuestionsHi, could someone explain me the math behind and the benefits of the Bias and Gain VOPs over the classic add/mult/pow approach. These "functions" are present in the Color Correct VOP and recently they found their way to the Unified Noise VOP as well. Still I wasn't able to find any description of how they work and why should I prefer them over other value correction methods. thanks in advance Mate beeemtee replied to beeemtee's topic in General Houdini QuestionsI did not. otl_path_asset.otl
http://forums.odforce.net/profile/2183-beeemtee/
CC-MAIN-2017-26
refinedweb
1,091
58.62
Contents numpy.datetime64values show() numpy.datetime64values¶ For Matplotlib to plot dates (or any scalar with units) a converter to float needs to be registered with the matplolib.units module. The current best converters for datetime64 values are in pandas. To enable the converter, import it from pandas: from pandas.tseries import converter as pdtc pdtc.register() If you only want to use the pandas converter for datetime64 values from pandas.tseries import converter as pdtc import matplotlib.units as munits import numpy as np munits.registry[np.datetime64] = pdtc.DatetimeConverter()') The default formatter will use an offset to reduce the length of the ticklabels. To turn this feature off on a per-axis basis: ax.get_xaxis().get_major_formatter().set_useOffset(False) set the rcParam axes.formatter.useoffset, or use a different formatter. See ticker for details. The savefig() command has a keyword argument transparent which, if ‘True’,. For example, to make the above setting permanent, you would set: figure.subplot.bottom : 0.2 # the bottom of the subplots of the figure The other parameters you can configure are, with their defaults. Note This is now easier to handle than ever before. Calling tight_layout() can fix many common layout issues. See the Tight Layout guide.. The example below shows how to use an ‘index formatter’ to achieve the desired plot: import numpy as np import matplotlib.pyplot as plt import matplotlib.mlab as mlab import matplotlib.ticker as ticker r = mlab.csv2rec('../data/aapl.csv') r.sort() r = r[-30:] # get the last 30 days N = len(r) ind = np.arange(N) # the evenly spaced plot indices def format_date(x, pos=None): thisind = np.clip(int(x+0.5), 0, N-1) return r.date[thisind].strftime('%Y-%m-%d') fig = plt.figure() ax = fig.add_subplot(111) ax.plot(ind, r.adj_close, 'o-') ax.xaxis.set_major_formatter(ticker.FuncFormatter(format_date)) fig.autofmt_xdate() plt.show()) You can also use the Axes property set_axisbelow() to control whether the grid lines are placed above or below your other plot elements. The Axes property set_aspect() controls the aspect ratio of the axes. You can set it to be ‘auto’, ‘equal’, or some ratio which controls the ratio: ax = fig.add_subplot(111, aspect='equal')) The easiest way to do this is use a non-interactive backend (see What is a backend?) such as Agg (for PNGs), PDF, SVG or PS. In your figure-generating script, just call the matplotlib.use() directive before importing pylab or pyplot: import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt plt.plot([1,2,3]) plt.savefig('myfig') See also Matplotlib in a web application server for information about running matplotlib inside of a web application. invokes the destruction of its plotting elements, you should call savefig() before calling show if you wish to save the figure as well as view it. New in version v1.0.0: show now starts the GUI mainloop only if it isn’t already running. Therefore, multiple calls to show are now allowed. Having show block further execution of the script or the python interpreter depends on whether Matplotlib is set for interactive mode or not. In non-interactive mode (the default setting), execution is paused until the last figure window is closed. In interactive mode, the execution is not paused, which allows you to create additional figures (but the script won’t finish until the last figure window is closed). Note Support for interactive/non-interactive mode depends upon the backend. Until version 1.0.0 (and subsequent fixes for 1.0.1), the behavior of the interactive mode was not consistent across backends. As of v1.0.1, only the macosx backend differs from other backends because it does not support non-interactive mode. Using matplotlib in a python shell),. Many users are frustrated by show because they want it to be a blocking call that raises the figure, pauses the script until they close the figure, and then allow the script to continue running until the next figure is created and the next show is made. Something like this: # WARNING : illustrating how NOT to use show for i in range(10): # make figure i show() This is not what show does and unfortunately, because doing blocking calls across user interfaces can be tricky, is currently unsupported, though we have made significant progress towards supporting blocking events. New in version v1.0.0: As noted earlier, this restriction has been relaxed to allow multiple calls to show. In most backends, you can now expect to be able to create new figures and raise them in a subsequent call to show after closing the figures from a previous call to show.. Violin plots are closely related to box plots but add useful information such as the distribution of the sample data (density trace). Violin plots were added in Matplotlib 1.4.. Matplotlib is a big library, which is used in many ways, and the documentation has only scratched the surface of everything it can do. So far, the place most people have learned all these features are through studying the examples (Search examples),. Bundle Matplotlib in a py2exe app? ….: # do this before importing pylab or pyplot import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt For more on configuring your backend, see What is a backend?. Alternatively, you can avoid pylab/pyplot altogether, which will give you a little more control, by calling the API directly as shown in The object-oriented interface. You can either generate hardcopy on the filesystem by calling savefig: # do this before importing pylab or pyplot import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111) ax.plot([1,2,3]) fig.savefig('test.png') or by saving to a file handle: import sys fig.savefig(sys.stdout) Here is an example using Pillow. First, the figure is saved to a BytesIO object which is then fed to Pillow for further processing: from io import BytesIO from PIL import Image imgdata = BytesIO() fig.savefig(imgdata, format='png') imgdata.seek(0) # rewind the data im = Image.open(imgdata) TODO; see Contribute to Matplotlib documentation. TODO; see Contribute to Matplotlib documentation. TODO; see Contribute to Matplotlib documentation.. The nearly 300 code Gallery included with the Matplotlib source distribution are full-text searchable from the Search Page page, but sometimes when you search, you get a lot of results from the The Matplotlib API or other documentation that you may not be interested in if you just want to find a complete, free-standing, working piece of example code. To facilitate example searches, we have tagged every code example page with the keyword codex for code example which shouldn’t appear anywhere else on this site except in the FAQ. So if you want to search for an example that uses an ellipse, Search Page for codex ellipse. If you want to refer to Matplotlib in a publication, you can use “Matplotlib: A 2D Graphics Environment” by J. D. Hunter In Computing in Science & Engineering, Vol. 9, No. 3. (2007), pp. 90-95 (see this reference page): @article{Hunter:2007, Address = {10662 LOS VAQUEROS CIRCLE, PO BOX 3014, LOS ALAMITOS, CA 90720-1314 USA}, Author = {Hunter, John D.}, Date-Added = {2010-09-23 12:22:10 -0700}, Date-Modified = {2010-09-23 12:22:10 -0700}, Isi = {000245668100019}, Isi-Recid = {155389429}, Journal = {Computing In Science \& Engineering}, Month = {May-Jun}, Number = {3}, Pages = {90--95}, Publisher = {IEEE COMPUTER SOC}, Times-Cited = {21}, Title = {Matplotlib: A 2D graphics environment}, Type = {Editorial Material}, Volume = {9}, Year = {2007}, Abstract = {Matplotlib is a 2D graphics package used for Python for application development, interactive scripting, and publication-quality image generation across user interfaces and operating systems.}, Bdsk-Url-1 = {;KeyUT=000245668100019}}
https://matplotlib.org/2.1.2/faq/howto_faq.html
CC-MAIN-2022-05
refinedweb
1,289
57.98
tag:blogger.com,1999:blog-89850204122788975572016-09-08T12:23:56.965+08:00LiveRichDreamsImproving Lives, Enriching Lives & Living Your Rich Dreams!aljo Living for the New Year - Flat AbsAs far as I can remember, I have always, always envied those beautiful beings with flat abs. I have wished for them (the flat abs, I mean) since ...God knows when. Healthy living in the New Year, I am figuring, would surely include flat abs. Yeah, sure.<br /><br />No, I am not fat or overweight. I am told that I have the right weight for my height; the only thing though is, I have a waist that is a wee bit too thick. So, I thought I'd do something nice and good for me in 2009: strive for that flat and sexy abs. And since I spend a lot of time punching my keyboards, and having finally settled down to get things started in the New Year (sheesh...it's already 13th January 2009... how time flies!), I thought I'd check around to see whether there are some materials newly posted that could help me at least try to achieve one of the New Year's resolutions.<br /><br />Well, I stumbled on a few good materials ..out of which I picked this article (copied & pasted) below. It seems to give specific instructions, and comes with a video, simple enough for a lazybone like me! How difficult can it be? So, if any one is as lazy as me, just copy and paste (we are not breaking any rules here, right? since I quoted the writer's name and source).<br /><br />Let's see whether we can have that sexy abs at year's end...<br /><br /><a href=""></a><h1></h1><blockquote><h1><span style="font-size:100%;">Uncover Sexy Abs Without Crunches!</span></h1> <div class="hrd_logo_position"> <div class="yh-hdrcite-ls"><span style="font-size:78%;">By <a href="">Lucy Danziger, SELF Editor-in-Chief</a> - Posted on Thu, Jan 08, 2009, 8:50 pm PST </span></div> </div> <div class="yh-n-wwh"><!-- --></div> <br />Bathing suit season is a bit far off, which means it’s the perfect time to start developing the <span style="color: rgb(0, 0, 0);">flat, sexy tummy</span> you swear you’ll work on every year. Even if you loathe crunches, you’ll love the following easy, no-equipment moves. Work a few of these moves into your exercise routine three times a week (easing them in minimizes soreness), and then after two weeks, do them all together in one session. Then don’t be surprised if you find yourself surfing the web for bikinis, preparing to reveal your sleek new abs surfside.<br /><br /><strong>Plank pose</strong><br />Balance on toes and forearms (or palms) for up to a minute, pulling belly button to spine and keeping back straight.<br /><br /><strong>Standing bicycle</strong><br /.<br /><br /><strong>Side winder</strong><br /.<br /><br /><strong>Seesaw</strong><br /.<br /><br /><strong>Forward bend</strong><br /.<br /><br /><span style="font-size:78%;">(Source: <a href=""></a>)</span></blockquote><br /><br /><br /><embed src="" bgcolor="#FFFFFF" flashvars="videoId=1845376307&playerId=1568178630&</embed><img src="" height="1" width="1" alt=""/>aljo of EmptinessFew weeks back, I found among those daily fwd's that crowded my inbox a ppt file that a friend had emailed me. The ppt was titled "Power of Emptiness", and the text quoted from Joseph Newton's "Principle of Emptiness".<br /><br />I was attracted to the quotes from Newton's "Principle of Emptiness". Indeed, they struck a cord deep inside. They seemed to be directed to me, these words:<br /><br /><blockquote>If you are in a habit of hoarding useless objects, thinking that one day, who knows when, you may need them? ...<br /></blockquote><blockquote>And inside,<br /><br />Have you got the habit to keep reproaches, resentment, sadness, fears and more?<br /></blockquote><br /...<br /><br />Of course, that one day never seem to come...<br /><br />More often than not, I'd forgotten what I had kept and hoard. So I'd just go buy new stuff anyways... And the things just seem to pile up ...year after year.<br /><br />Receiving my friend's email with that ppt presentation hit me hard with the realization that yes, it is true what is said in the "Principle of Emptiness".<br /><br /.<br /><br />The fact is, the very act of hoarding and keeping the old goes against the nature of prosperity. Newton's principles further says:<br /><br /><blockquote>'That it is necessary to make room to leave an empty space in order to allow new things to arrive to your life.<br /><br />It is necessary that you get rid of all the useless things that are in you and in your life, in order for prosperity to arrive."<br /><br /></blockquote:<br /><blockquote>"The force of this emptiness is one that will absorb and attract all that you wish."</blockquote.<br /><br />I found exactly the same video as the ppt presentation and post it here. By sharing, I hope I can help some souls out there in much the same manner as it did me.<br /><br /><object width="425" height="344"><param value="" name="movie"><param value="true" name="allowFullScreen"><embed src="" allowfullscreen="true" type="application/x-shockwave-flash" width="425" height="344"></embed></object><a href=""></a><img src="" height="1" width="1" alt=""/>aljo Are Lucky People Lucky <span style="font-style: italic;">depressing</span>,.<br /><br /.<br /><br />Charles Burke's article is a reproduction from here: <a href="">.</a><br /><br /><blockquote>We've all seen people who are just naturally lucky.<br /><br />They're the ones who manage to sail through life with more unexplainable "lucky breaks" and fewer disappointments than most people get. Success just seems to come easier for them.<br /><br />Where most folks have to struggle just to get ahead, lucky people regularly have opportunities just plop down in their laps. Of course, they work hard, but that doesn't fully explain the special treatment that life seems to reserve for them.<br /><br />It almost appears that they were born with the proverbial silver spoon in their mouths. Or born under a luckier star than most mere mortals.<br /><br />Well, cheer up; neither stars nor spoons are at work here. All they have is seven simple secrets.<br /><br /.<br /><br />Ready to command more luck in your life? Here are the seven simple secrets of naturally lucky people.<br /><br />Secret #1. Lucky people don't believe in luck.<br /><br />I recently interviewed ten unusually successful business people for a book I was writing about the role luck plays in the lives of successes.<br /><br />Nearly every one of them stated plainly they don't believe in luck.<br /><br />In the next breath, however, they told about unending streams of "serendipitous" or "synchronistic" events that routinely happen in their daily lives.<br /><br />I believe they don't like the word "luck" because it implies there's no way to control it. They've learned that there is.<br /><br /.<br /><br />I've chosen to use the word "luck" because when I say it, people have a fair idea of what I mean.<br /><br />I try to avoid radical new terms when we've already got a perfectly good word.<br /><br />If someone walked up to you and said, "I help people learn to cause pleasant improbabilities to occur more frequently," you'd probably look around for the exit.<br /><br />On the other hand, when I use the word "luck," you and I are in the same ball park, concept-wise.<br /><br />It's okay if our definitions differ slightly. This happens to us all the time anyway. Ever seen a husband and a wife agree on what "shopping" means? Or "one hour"?<br /><br />Most of the time, even though there are differences, we're close enough for useful communication.<br /><br />And that's what we're doing here. As you read, you'll gradually find that my definition of luck includes a steering wheel and an accelerator pedal.<br /><br />Secret #2. "Bad" stuff happens to them too.<br /><br />There are several ways to have good luck.<br /><br />The most common (and the most useful) is to find opportunities in problems.<br /><br />A friend of mine says: "There's always a miracle in a mess."<br /><br />Let's say you and I are neighbors, and our whole city has a common problem. Maybe it's infestation with insects. Or it could be a serious pollution problem from a nearby plant.<br /><br />While almost everyone is griping and complaining about the problem, you might decide: "Hey, if I can solve this problem, it will help my neighbors, and it can also make a profit for me."<br /><br />Your neighbors only saw the problem, but you looked deeper and found an opportunity.<br /><br />All great fortunes have been built upon solving great problems. From the huge railroad empires of the 19th century, to the communications networks of the 20th, and now the software giants of the 21st, they have all solved problems for people.<br /><br />Was Andrew Carnegie "lucky" that he foresaw a huge need for steel in the 1800s? Some say he was.<br /><br />But I say he simply knew how to recognize a widespread need and turn it into a giant opportunity.<br /><br />The same is true of Bill Gates. Many people criticize Gates for his business practices, but whatever else you believe (either way) about the man, you have to admit, he saw an opportunity before most others did, and he acted.<br /><br />That's probably the most common and the most controllable way to generate your own luck.<br /><br />Secret #3. More people quit than lose.<br /><br />If you knew ahead of time without a doubt that your success was guaranteed, how much would you go out and do?<br /><br />Would it make any difference in the kind of things you would attempt? How much higher would you direct your aim?<br /><br />Well, a funny thing happened to me a few years back. I was sitting and feeling sorry for myself one day because of all the failures that I had been through.<br /><br />Then it suddenly occurred to me that one particular case hadn't been a real failure. I admitted to myself (reluctantly) that I had simply quit too soon. I had quit before I'd really had a chance to fail.<br /><br />Then I thought of another non-failure.<br /><br />Then another.<br /><br />And before long, I was buried under an avalanche of similar cases. In fact, I couldn't think of a single time when I had actually kept on trying long enough to fail. In other words, I had never experienced failure in my entire lifetime.<br /><br />Only quitting.<br /><br />A realization like that will realign your reality.<br /><br />After that, it's hard to consider yourself a failure because you've never failed. Who knows what you might really be, down inside?<br /><br />I began to wonder: what would have happened if I had stuck with even a few of those situations just a little longer? What if I hadn't been quite so ready to quit? More to the point, what about today and tomorrow? What if I stopped being so ready to throw in the towel and surrender too soon? Would I start seeing the number of clear successes in my life begin to grow?<br /><br />The more I played with that idea, the better it sounded.<br /><br />I'd like to report to you that my life instantly and dramatically changed that day, but it didn't.<br /><br />Oh, it did BEGIN changing, but it wasn't the dramatic turnabout that you read of in books or see in movies.<br /><br />Instead, each time I'd find myself in a discouraging situation, I'd start thinking of all those times I had just simply quit trying too soon. And gradually, over time, I began developing a new mental toughness that didn't take temporary setbacks quite so seriously.<br /><br />I started finding a new resourcefulness within myself. My "keeping-on" average began to go up, and my "failure" average started declining.<br /><br />I count that one realization among the most important in my life. Not because it solved a problem, but because it identified one.<br /><br />Once I could see that the problem wasn't even what I thought it was, I was then able to work on doing something else instead.<br /><br />And you know what? My luck began improving.<br /><br />Secret #4. Betting on losing hands makes losers.<br /><br />Successful poker players don't play every hand they're dealt.<br /><br />If you keep count, the hands they fold far outnumber the hands they hold.<br /><br />That's because a good card player knows the odds for every possible card combination. They know whether a flush beats a full house and which is more likely to occur.<br /><br />And they only bet their money on likelihoods.<br /><br />They love to play with amateurs because amateurs play for "the juice," the emotional charge they get from throwing money out on the table, whether they win or lose.<br /><br />Good players don't bet on risk, they bet on probability.<br /><br />Lucky people are very similar. They know longshots when they see them, and they may bet, but it's a calculated bet.<br /><br />Lucky people are some of the most tenacious people on earth when it's appropriate.<br /><br />But they're also some of the quickest quitters when the odds don't favor them. In fact, they'll usually opt out of most situations before they even begin because they have learned to recognize and rank opportunities.<br /><br />What makes a good opportunity? First, does it solve a WIDESPREAD problem? Second, do the people with the problem have enough money to pay for solving that problem? Third, is it easy to reach the people with the problem? Fourth, is the solution a really good one?<br /><br />If they don't find all four factors, a lucky person will walk away because they know it's a losing hand, no matter how much they personally love the idea.<br /><br />So if a lucky person sees he's holding a losing hand, he quits quickly and cuts his losses.<br /><br />Secret #5. Most good luck comes through other people.<br /><br />Good luck almost never happens in a vacuum.<br /><br />Several years back I read a book by Max Gunther titled "The Luck Factor."<br /><br />Most of the details in that book have dimmed, but I've never forgotten the core idea: Most lucky breaks are brought to you by other people.<br /><br />Few people find significant amounts of money on the street or buried in the backyard. Perhaps even fewer win lotteries.<br /><br />Instead, luck comes more often in the form of opportunities.<br /><br />You're with a group of ladies (or guys) who are sitting around complaining about how it's hard to find respectable men (women) to date. Everybody is really getting into the problem.<br /><br />The person next to you leans over and whispers, "Don't you wish everyone would just quit whining?"<br /><br />But instead of complaining about all those complaints, a little lightbulb clicks on in your head. You realize a good computerized screening service for romantic introductions would fill a real need here.<br /><br />You don't say anything, but weeks later, when you announce the new service, and you're flooded with calls from singles all over the city wanting safer introductions, all your friends whisper, "She's so lucky. Where did she get that great idea?"<br /><br />You know where the idea came from, but you're not telling.<br /><br />A great deal of "good luck" is manually created out of discomfort often someone else's.<br /><br />Secret #6. Good luck favors those who have prepared.<br /><br />Let's say you're appearing in an amateur play in a little theater in your neighborhood.<br /><br />A big-name producer from Hollywood is visiting a sick relative, hears about the play, and for a bit of distraction decides to attend.<br /><br />She sees a spark of something special in your performance, asks to meet you, and offers you a screen test.<br /><br />Okay, freeze the frame for a second.<br /><br />Are you prepared for this big break?<br /><br />Have you done all the study and the practice and the foundation work it takes to be a professional? Will you have the technique and the skills necessary to do the job?<br /><br />Or are you going to try and fake your way through it?<br /><br />If you're prepared, you're likely to do well. This means a giant step toward your dreams.<br /><br />And if you're not prepared... well, good luck with your day job.<br /><br />Secret #7. You can attract good things, too.<br /><br />All this talk about finding opportunities in "bad" events and developing your skills is important, but there's a more sunny side to luck as well.<br /><br />Internet entrepreneur Joe Vitale terms it his "Magic Escalator through Life," and award-winning author John Harricharan has titled it "The Power Pause."<br /><br />I interviewed both of these men recently, as well as eight other fascinating people, about how they manage to stay so consistently successful.<br /><br />Every single one of them has techniques for keeping their mind tuned to the things they want. And they attend to this "mind tuning" every day. They're not casual about this. Oh no, they put regular effort into it. Their successes and their luck are not accidents.<br /><br />If you're tempted to greet this with a dismissive, "Oh yeah, I've read those positive thinking books," then you need to think again.<br /><br />Yanik Silver, an up-and-coming star on the Internet tells how he starts every single morning with a 15-minute session in which he goes over his "values and goals."<br /><br />Every morning - no exceptions.<br /><br />Stacey Hall and Jan Brogniez go even further. They teach their clients to attract what they've labeled "Your Perfect Customers."<br /><br />In every case, they start with their thinking. What they put into their mind has a direct one-to-one relationship to what appears in their life.<br /><br />Secret #7- Taking responsibility for the bad stuff in your life.<br /><br />If you've got uncomfortable situations right now, you'll never have the power to change them until you accept the fact that you created that mess... exactly as it is right now.<br /><br />Admit to yourself that you created your own problems, down to the last tiny detail, and only then will you take command of the power to change those problems.<br /><br />Fortunately, it's not as impossible as it sounds at first.<br /><br />Your mind is like a bucket. If the bucket is filled with muddy water, all you have to do is start a steady flow of clear, fresh water into the bucket.<br /><br />Soon, the bucket (or your mind) is filled with clear, fresh contents.<br /><br />Steady daily input of clear, fresh thoughts will change the things that appear in your life, without the need for major renovation. It just happens. You work on the inside, and the outside takes care of itself.<br /><br />This means you don't fight the old thoughts. You give them minimum energy. You don't resist, you don't struggle. Instead, you put your attention as much as possible on the good things you want to appear in your life.<br /><br />The lucky things you spend your time thinking about just start happening for you, and one day you wake up and realize, "Hey, I'm a pretty lucky person now. When did that happen?"<br /><br />Does this mean you won't ever have to make any hard decisions, or deal with any stressful people?<br /><br />No, but you'll find yourself handling difficult decisions and fussy people more easily because you'll have a clearer vision of what lies on the other side, after you've gotten past them. They just won't loom so large in your path any more.<br /><br />So these are the seven secrets that naturally lucky people use to keep their life moving forward:<br /><br />They don't believe in (or wait around for) random luck. They take charge of generating their own luck.<br /><br />They look for the opportunity that's always embedded in life's inconveniences.<br /><br />They don't quit when they're holding a potentially winning hand.<br /><br />They drop a losing hand as quickly as possible. And they know the difference.<br /><br />They polish their people skills constantly because most opportunities are brought to us by others.<br /><br />They develop a wide range of professional skills so they're prepared for any opportunity to knock.<br /><br />They fill their mind with thoughts of what they want, because they know they get what they fill their mind with, whatever that is.<br /><br />Other than these seven simple things, however, naturally lucky people don't do anything special at all.<br /><br />--Author-Charles Burke<br /></blockquote><img src="" height="1" width="1" alt=""/>aljo to Stay Grateful: Stop And Smell the RosesStop and smell the roses. That is how we can feel grateful.<br /><br /.<br /><br />Even as I write, common people on the streets in many countries have held and are planning to hold street protests to convey their anger and frustrations to their respective governments over the rising prices of fuel and food.<br /><br />So, in the face of all these, how can we remain grateful?<br /><br /?<br /><br />Well, my take is this. <span style="font-weight: bold;">We actually don't have much choice but to be grateful. We have to feel grateful at where we are at, so that we have the strength to look forward to tomorrow, to have the hope to go on living. </span><span><br /><br /.</span><br /><br / <span style="font-style: italic;">you</span> will rebel. What I am saying is...make yourself feel grateful. You can actually do this. How?<br /><br /: <span style="font-weight: bold;">stop and smell the roses.</span><br /><br /><span style="font-weight: bold;">STOP...</span><br /><br />To me, stop means <span style="font-weight: bold;">take time out. </span><span>You take time out, just sit still & breathe or you can meditate</span>,.<br /><br / <span style="font-style: italic;">sit still and breathe</span> for a few minutes. I read somewhere (can't remember where exactly that most of the problems people have arise from their inability to sit still and and breathe for a few minutes.<br /><br /.<br /><br />Stillness and silence will give you the time and space that can lead towards this phase of returning to yourself...and finding the peace within. Peace of mind will allow you to give thanks.<br /><br /><span style="font-weight: bold;">...AND SMELL THE ROSES<br /><br /></span>Smell the roses just means appreciate life and give thanks. Be grateful.<br /><br /.<br /><br />You need to be grateful, grateful not only for all the positive things that have come to you but also for all the good things that will be coming your way. You can actually <span style="font-style: italic;">will</span>.<br /><br />You see, you need to feel gratitude. Because feeling grateful will put you in the right frame of mind to enjoy life to the fullest.<br /><span style=""> </span><span style="font-weight: bold;"></span><img src="" height="1" width="1" alt=""/>aljo in SilenceToday, I just want to focus on 'moments in silence' ... my newfound addiction to heal the body, mind and soul.<br /><div>It's been close to two months since I last posted. Been busy with a few things: keeping up with the political scenario at the local (read: state/national) level, hence, been busy updating my other blog that muses on community and socio-political issues; working to put food on the table; and, equally as important, gifting myself with moments in silence.<br /><br /><a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href=""><img style="margin: 0pt 10px 10px 0pt; float: left; cursor: pointer;" src="" alt="" id="BLOGGER_PHOTO_ID_5197208162886191522" border="0" /></a><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />These days, somehow I find myself taking the time to seek out moments of silence wherever, whenever I can. Moments of silence can be very addictive...to me, at least.<br /><br />Such moments of quiet and solitude, though becoming rare, can be found in many places, one just needs to make the effort to seek them out. Such moments of silence could be found possibly in one's own backyard, a quiet corner to be all on you own; or a quiet spot in your orchard if you are one of those lucky to own one; or in your bedroom, living room, or office; or maybe, in a chapel on your way to work.<br /><a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href=""><img id="BLOGGER_PHOTO_ID_5197187431079053570" style="margin: 0pt 10px 10px 0pt; float: left; cursor: pointer;" alt="" src="" border="0" /></a><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />Obviously, silence in nature can only be afforded by nature walks or, for the adventurous ones, jungle treks. If none of these are accessible to a city soul, then your own backyard or a walk in the park could do the trick. But the best of the best moments of silence are the ones where one can bask in Nature's sacred setting. For it is only here in Nature's abundant diversity can we learn of Nature's gifts of peace, harmony and renewal for us mere mortals.<br /><br />These are my favorite, the nature walks or jungle treks. Here is where you can bask in the beauty and splendour of God's creation.<br /><a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href=""><img style="margin: 0pt 10px 10px 0pt; float: left; cursor: pointer;" src="" alt="" id="BLOGGER_PHOTO_ID_5199314301226066642" border="0" /></a><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />Upon entering into the Silence of Nature, one can immediately feel the cool stillness that brings a deep sense of serenity into the heart and that breathes an energy force into one's body.<br /><br />Here in nature's tapestry of life, we can see how interlinked, interconnected, and intertwined all creations are with one another - flora, fauna and man. There is wisdom in the learning of this, how each and every living being sustains and live off one another.<br /><a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href=""><img style="margin: 0pt 10px 10px 0pt; float: left; cursor: pointer;" src="" alt="" id="BLOGGER_PHOTO_ID_5200068445943636770" border="0" /></a><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />When we understood this interplay among all creations, only then can we have a deeper sense of reverence of our own lives and the lives of every living matter or being, no matter big or small, that surrounds us and sustains us. There will also be a heightened wisdom when we understand life and source of life.<br /><br />The wondrous thing about such times of silence in nature is not only the peace one savours when basking in such solitude but also the memories of these scenes imprinted on one's mind.<br /><br /><a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href=""><img style="margin: 0pt 10px 10px 0pt; float: left; cursor: pointer;" src="" alt="" id="BLOGGER_PHOTO_ID_5199317960538202882" border="0" /></a>For there are times when in frantically running daily errands, either fighting traffic in the bustling city or walking the block to the bank under the hot sun, my mind flashes back to these nature scenes, and all at once, the cool stillness of nature calms my mind, cools my body and soothes my soul.<br /><br />Many a times, I believe these scenes from my 'moments in silence' could have saved me from just breaking down from the pressure of the everyday work and family stress.<br /><br />These imprints of silence-in-nature are the ones that I use to fall back on in my times of stress at work, at home or fighting traffic in the midst of a jam. Falling back on these soothing imprints could probably have been my saving grace. I have no way of knowing except here I am today, still sane, still alive and kicking. And today, I share them with you.<img src="" alt="" /><a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href=""><img id="BLOGGER_PHOTO_ID_5197187456848857410" style="margin: 0pt 10px 10px 0pt; float: left; cursor: pointer;" alt="" src="" border="0" /></a><a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href=""><img id="BLOGGER_PHOTO_ID_5197187452553890098" style="margin: 0pt 10px 10px 0pt; float: left; cursor: pointer;" alt="" src="" border="0" /></a><br /></div><div></div><div></div><div></div><div></div><div></div><div></div><a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href=""></a><div></div><div></div><div></div><img src="" height="1" width="1" alt=""/>aljo Maturing PoliticallyIn my last post I concluded with <span style="font-style: italic;">"Malaysians have lived through a number of these abuses for a while now. It would be interesting to see how fed-up we, Malaysians, are of the such political abuses and stupidities. I wonder whether Malaysians are desperate for a change?" </span>As we've seen, by the early hours of 9th March 2008, Malaysians showed they are immensely FED-UP with the going-ons in the country lately. Earlier on, one could actually feel the ticking of a time bomb ready to explode, the 'desperation for a change' being the time bomb. Most thinking Malaysians felt it. Only the BN ruling coalition didn't. And the coalition paid dearly.<br /><br />Lucky for the ruling coalition, the explosion was not a total annihilation. It merely dented the ruling coalition rendering it nearly ineffective by denying it the two-thirds majority that it so desperately needed to continue with its merry-way of governing. The time-bomb also took down 4 crucial and the richest states in Malaysia in addition to the long-time opposition state of Kelantan. This is a first in Malaysia's history, and it shocked all Malaysians and onlookers.<br /><br />Many seasoned politicians and long timers were toppled and sent off to political retirement by green horns and first-timers. I know a great number of Malaysians were jumping for joy in the wee hours of the morning of 9th March 2008 as Malaysia woke up to a 'New Dawn' as Anwar Ibrahim, the founder of Malaysia's first multiracial party, PKR, puts it. Congratulations and our profound thanks to Anwar for orchestrating a well-coordinated opposition, uniting them and putting up a great battle for oppressed Malaysians. You gave Malaysians hope when we thought there was none. We salute you, Datuk Seri!<br /><br />Uniting different races within a single party is in itself a daunting task. That Anwar could galvanize the the different racial parties which represent differing extremities is just mind boggling. But the time must have been right, too. Malaysians have advanced and matured. Many factors contributed to this. Malaysians are more educated, we know good governance when we see one. Being more educated have opened the Malaysian minds; when you know more, you understand more. When you understand more, you become more understanding, more tolerant. And tolerance is the cornerstone that keeps Malaysia's multiracial society intact. We have always touted our multiracialness, but never before has this been put to test till now. It is a wonderful feeling to see that Malaysians can pass the test - Malays, Chinese, Indians, Kadazan, Dusun, Bajau, Iban, Dayak, etc can actually work together. Yes, Malaysians have passed the test, but beware, it is only the preliminaries. Malaysians have shown that there is hope for unity; we can be united if we desperately want to. The daunting task lays ahead. Our biggest task yet is to be committed to our cause to stay united. To stay united, Malaysia must have the political maturity in order to rise above petty racial and religious disagreements. By last weekend polling, it is obvious that Malaysian have come a long way...Malaysians are becoming politically matured. And as we progress, let us work towards a more heightened political maturity.<br /><br />Technology contributed somewhat. The media and the Internet not only give us better access to information and knowledge but also offer more avenues whereby to voice our thoughts, our beliefs, our frustrations. But the media and Internet are but mere tools, we still have to fall back on our political maturity to make rational and cautioned use of such tools at our disposal so as not to antagonize and anger people like some quarters did in the last campaign.<br /><br />The game plan is to stay united so that the Alternative Coalition or as Anwar puts it, the 'Government-in-Waiting' will become the Government of Malaysia come next elections. The Alternative Coalition has only succeeded in the easiest task. Now, comes the difficult part: fulfilling the promises you have made, and delivering to the people. Keeping your promise and delivery will ensure the people's solid support. Because if the Alternative Coalition can commit, serve and deliver effectively, then you would have, in essence, practised fairness, transparency and great political maturity in good governance.<br /><br /><span style="font-style: italic;"></span><img src="" height="1" width="1" alt=""/>aljo Elections, Exercising Our Rights & Voting WiselyThe time has come again for us to exercise our right to vote in Malaysia. The past few weeks have been hectic cos I was co-opted to focus a bit on the elections via my job. Somehow, I have come to believe that politics in my country, and especially the state where I live, brings out the worst in people. Maybe it's the same everywhere, maybe it's just here. Still, politics puts so much power in the hands of a few, and everywhere which way you turn, you see the greed, the abuse, the corruption, the money-salivating politicians at their worst.<br /><br />I often wonder why politics have to be so dirty, so negative, so evil. Am I just being a simpleton for wanting politics to be good for people? Let me rephrase, politics per se should be good because politics is the art or science of government and works for the people. Hence, it should be good because anything that serves the people has to be good. Then how come politics in this modern day and age reeks of everything negative and stinky under the sun? Answer, politics is a good art/science, only the politicians, the humans, make it bad. Through politics, we put power in the hands of a few, and humans are the only creatures on the face of the earth capable of abusing power in every single way.<br /><br />But lucky for us, i.e., those of us living in democracies, we are given the right to choose the government, and to exercise that right every 5 years or so in the election process. However, even that simple right doesn't amount to much when ingenious politicians cheat and tamper with justice within a democratic system of government. Where I live, the word 'Election' only conjures money politics, political frogs that can be bought, and ghost voters (mostly from neighbouring countries and given citizenship so that they can tilt the elections results whichever way according the the whims and fancies of the powers that be).<br /><br />Still, elections work most of the time. We have been able to brings down dictatorial Goliaths in the past. The feeling is great when simple village folks are able to overthrow the government once in the while. But then again, this democratic process can't run away from, again, the human factors in terms of emotions, emotional, racial and religious affinities. These human factors are what can ruin justice. So, there are many, many cases here where the simple folks keep on voting the same politicians and keeping them in power for decades when as their so-called representatives, these politicians had not done much to bring progress and development back to the people. The voters keep forgiving them over and over again because they share the same race or the same religion. I hope this country will change the law to allow the head of the government, both state and national, to serve ONLY TWO (2) terms. This has worked well for the USA. It should be used by countries like Malaysia and Indonesia where apparently it is most need. Allowing the head of government to serve only 2 terms will surely do away with a great deal of political evils such as nepotism and cronyism, and make politics become the good art/science of government that truly serve the people.<br /><br />Polling day in Malaysia will be on 08th March 2008. I have not voted in the last two elections because the results are predictable, the same government will remain in power. But like I said, if you let the same government have staying power far too long, so much negativity will ensue. Abuses such as nepotism and cronyism will allow people in the corridors of power, the Executive, to even influence, impact and control the Judiciary. The country's Executives can easily pick and choose their own to control the judicial system. It goes without saying that a government having power for too long will monopolize and mismanage the country's finances and economics, keeping the money for themselves and their own.<br /><br />Malaysians have lived though a number of these abuses for a while now. It would be interesting to see how fed-up we, Malaysians, are of the such political abuses and stupidities. I wonder whether Malaysians are desperate for a change? Come tomorrow, let's exercise our right to vote and vote wisely.<img src="" height="1" width="1" alt=""/>aljo Silent Prayer My Soul I Bare<span style="font-family:Arial;">In Your Chapel, the quiet consoles</span><span style="font-family:Arial;"><br />Bowed in silence, my prayer just flows <o:p></o:p></span> <p class="MsoNormal"><span style="font-family:Arial;"><o:p></o:p>In silent prayer, my soul I bare<br />This is me, my Lord, I went astray<br />But I am here now, no need to explain<br />You’ve always been there through all of my pain<br />Twas me who turned away<br />Lost for a long while, now seeking your way.<o:p></o:p><br /></span></p> <p class="MsoNormal"><span style="font-family:Arial;">This simple act to bare my soul, easy it should be, or so I thought<br />But tis hard, my inside wrought<br />I have closed up for far too long<br />Let nobody in, been crying alone<o:p></o:p></span></p> <p class="MsoNormal"><span style="font-family:Arial;">How hard it is to open up my pains<br />To lay bare my sorrow for everyone to sense<br />Tears swell and roll down my cheeks, soothe my skin<br />They wash away the hurt, the ugly pain<br />The resentment, the bitter anger bit by bit go wane.<o:p></o:p></span></p> <p class="MsoNormal"><span style="font-family:Arial;">I can still recall the bitter, bitter taste of anger on my tongue<br />I now shrug off the hurt that still remains, lesser now, much less in time<br />I had backed away from You in anger<br />My cries You did not hear<br />I had stopped praying, stopped coming here <o:p></o:p></span></p> <p class="MsoNormal"><span style="font-family:Arial;">I had ranted, why don’t You change his waywardness?<br />Why do I have to go through this pain? Why let me suffer the ugliness?<br />Why me? Who have I wronged to deserve this, who?<br />To do good, I tried. To be good, I did, too.<br />A normal being I try to be, I did not steal, I did not kill, I did not disobey<br />Then why torment a suffering soul this way?<br />Why? Why? Oh why?<o:p></o:p><br /></span></p> <p class="MsoNormal"><span style="font-family:Arial;">So many questions, so many years<br />No answer came for five and twenty years.<o:p></o:p></span></p> <p class="MsoNormal"><span style="font-family:Arial;">Then You beckoned, this third day of the Year<br />Your Chapel seemed welcoming, come revere<br />Felt tired for far too long, I sigh<br />Just needed to stop and rest awhile…<o:p><br /></o:p></span></p><a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href=""><img style="margin: 0pt 10px 10px 0pt; float: left; cursor: pointer;" src="" alt="" id="BLOGGER_PHOTO_ID_5167130058416693586" border="0" /></a><span style="font-family:Arial;"><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />Silence...</span><span style="font-family:Arial;">Sublime silence<o:p></o:p></span><span style="font-family:Arial;"><br />Grant me refuge in Your comforting silence.<br /><o:p></o:p></span> <p class="MsoNormal"><span style="font-family:Arial;"><o:p></o:p>In silence, I bow my head down<br />My torment, my pain I lay them all down<br />Your forgiveness I seek in silence deep<br />Protect and guide me henceforth, I beseech<br />Pray, grant me forgiveness, heal this lost soul<br />In silent prayer, I lay bare my soul.<o:p></o:p></span></p> <p class="MsoNormal"><span style="font-family:Arial;"><o:p> </o:p></span></p><img src="" height="1" width="1" alt=""/>aljo‘Silence and Soft Speech’ Attract Abundance<span style="font-family:Arial;"><?xml:namespace prefix = o /><o:p></o:p></span><span style="font-family:Arial;">Gosh! This stuff really works! Silence and soft speech can indeed attract abundance. Call it what you may, but all I care is that this is the real deal! How else can I explain the many small abundance that I have been blessed with since I started practicing this on the third day of the New Year. And tonight, I found out I won close to two thousand in the local lottery! I have a feeling more abundance are on their way to me! Thank you, thank you, thank you Universe!<o:p></o:p></span><br /><p class="MsoNormal"><span style="font-family:Arial;"><o:p></o:p>It’s been two weeks since my last post entitled “Attract Good Fortune in the New Year through Silence and the Practice of Soft Speech”. And I have had many small fortunes since. Except for small lapses here and there (I am human, still), but overall, I feel much calmer, at peace with myself and grateful to the universe for everything good in my life. So I’m like making a promise to myself to practice ‘silence and soft speech’ on a daily basis simply because I am experiencing notable changes in my life that are wonderful. I simply just feel good about me now!<o:p></o:p></span></p><p class="MsoNormal"><span style="font-family:Arial;"><o:p></o:p></span><b><span style="font-family:Arial;">From Edginess to Blessedness<o:p></o:p></span></b></p><p class="MsoNormal"><span style="font-family:Arial;"><o:p></o:p>Overall, my lifestyle has not changed much. I follow the same work and home routine still, everyday. Usually (especially the past year) by this time of the month (I am a salaried worker, btw) after paying the bills, I would be walking on edge as I usually don’t have much cash on me or in my savings. I don’t know about you but, somehow, having money on me makes me feel secure and confident going about my business. With money, I don’t have to carry around the feeling of dread and insecurity that comes with knowing that you have no cash in hand and you have busted your credit card limit; you know, that dreaded fear that the car will suddenly give way and you have no cash for urgent repairs, or you might bump into old friends and you couldn’t even buy them coffee, etc, etc. I dislike that feeling of dread and edginess that come with the lack of money. Money gives me security and confidence. <span style="font-size:0;"></span><o:p></o:p></span></p><p class="MsoNormal"><span style="font-family:Arial;"><o:p></o:p>Since the start of the year, I made sure I practice simple forms of meditation everyday. I observe moments of silence as much as possible, whenever possible, and I try to speak much softer than I usually do. The past three weeks, I am filled with this feeling of abundance and confidence. Why? Because I have a few thousands in savings, and a few hundreds on me (and now the nearly 2k that I won tonight), which is more than enough to give me the feeling of security,confidence in going about my day, not to mention a wonderful sense of calm inside. And, I have even booked air tickets for five in my family for us to go on vacation in March.<span style="font-size:0;"> </span>Call it coincidence, or whatever. But I call these small miracles brought by the wonderful practice of silence and soft speech .<o:p></o:p></span></p><p class="MsoNormal"><span style="font-family:Arial;"><o:p></o:p>So what exactly is Silence and Soft Speech, or the practice of it? <o:p></o:p></span></p><p class="MsoNormal"><span style="font-family:Arial;"><o:p></o:p></span><b><span style="font-family:Arial;">Silence<o:p></o:p></span></b></p><p><span style="font-family:Arial;"><o:p></o:p>Silence relaxes the mind and body. By practicing silence, we gain and preserve energy and vitality, but there are also many benefits to be obtained by silence. I stumbled upon an article on the 'Power of Silence' by <a href="">wahiduddin</a> which I am recommending to anyone interested in the topic.<b><o:p></o:p></b></span></p><p class="MsoNormal"><span style="font-family:Arial;">To practice silence, everyday of the week, if possible, I make an effort to retreat from the noise, demands and expectations of <span style="font-size:0;"></span>the world around me for half an hour or so. I close myself in, and get in touch with my inner self to find the peace within. I practice silence by doing a few things that I now recommend:<o:p></o:p></span></p><p><span style="font-family:Arial;"><o:p></o:p></span><span style="font-family:Arial;">1. Observe moments of quiet and stillness </span></p><ul><li><span style="font-family:Arial;">Sit in a comfortable chair for a few minutes, close your eyes, breath slowly and just stay quiet…relax. </span></li><li><span style="font-family:Arial;">Focus all your attention on a soothing object for a few minutes: it could be a water feature on your office table or room, a poster on your wall, anything that gives you a sense of tranquility. </span></li><li><span style="font-family:Arial;">Find a quiet spot outdoors, better still on a hill or a building top, and just close your eyes for a few minutes and feel the cool breeze on your face. The high you get can be addictive.<o:p></o:p></span></li></ul><p class="MsoNormal"><span style="font-family:Arial;">2. Spend Solitary Time-outs:</span></p><ul><li><div class="MsoNormal"><span style="font-family:Arial;">Take a bath: a few minutes of showering or soaking in the bathtub, just feel the water caressing your skin into total relaxation. </span></div></li><li><div class="MsoNormal"><span style="font-family:Arial;">Go for a relaxed walk in a quiet park for no specific purpose.</span></div></li><li><div class="MsoNormal"><span style="font-family:Arial;">Sit in the park watching the birds, or people pass by or children playing.</span></div></li><li><div class="MsoNormal"><span style="font-family:Arial;">If you live or pass near a church or chapel any day of the week, just stop by and sit for few minutes, and just enjoy the healing silence in His presence.<br /></div></li></ul></span><p class="MsoNormal"><span style="font-family:Arial;">3. Meditation<o:p></o:p></span></p><p class="MsoNormal" style="MARGIN-LEFT: 0.5in"><span style="font-family:Arial;"><o:p></o:p>I would go for simple meditation that one can easily learn from many sources, library, online, etc. For a simple meditation, just sit in a quiet and comfortable position, start with a few deep breaths and count down slowly from 25 to one to relax your whole body t</span><span style="font-family:Arial;">otally</span><span style="font-family:Arial;">, release all stress and tension, and just go into your inner self, and focus on the stillness within. You may want to repeat some affirmations if you want to, and/or strengthen that further with visualizations.<o:p></o:p></span></p><p class="MsoNormal" style="MARGIN-LEFT: 0.5in"><span style="font-family:Arial;"><o:p></o:p>Or you may want to learn yoga. There are plentiful resources out there.<o:p></o:p></span></p><p class="MsoNormal" style="MARGIN-LEFT: 0.5in"><span style="font-family:Arial;"><o:p></o:p>Otherwise, you could go online and seek out the numerous free courses on meditation techniques. I came across a good meditation system, the <a href="">Silva Life System</a> which I am currently using. It’s great and works for me. No harm in checking out the <a href="">Silva Method</a>.<o:p></o:p></span></p><b><span style="font-family:Arial;">Soft Speech<o:p></o:p></span></b><br /><p><span style="font-family:Arial;">Silence has healing properties for the mind, body and soul. The more moments of silence we observe, the more revitalized and tranquil we feel. Of course, being part of the human race we cannot continue to be silent for long. Speaking and/or communicating are part and parcel of living. However, we can keep speech to the bare essential at crucial times. And speaking in soft tones is always soothing to a listener. The many mistakes we make are by opening our mouths too much. Most of us have this need to be heard, to make a point, to contradict and to criticize. Often, talking too much allows us to say foolish things. We offend and hurt people through speech, and by<span style="font-size:0;"> </span>speaking too much we give out secrets that we later regret.<o:p></o:p></span></p><p><span style="font-family:Arial;">One just needs to recognize the pervading goodness of silence; that it is in silence that we can do our best work because all our energy and willpower become concentrated and intense in silence. And the best part is, silence is spiritual and brings us closer to our God.</span></p><p><span style="font-family:Arial;"><o:p></o:p></span></p><img src="" height="1" width="1" alt=""/>aljo Good Fortune in the New Year through 'Silence' and the Practice of Soft Speech<span style="font-family:Arial;"><o:p></o:p></span><span style="font-family:Arial;">It’s been a week into the New Year 2008. The past week, I have been struggling with what will be my first post for the year. I want to write about something special, something that touches deep and will bring good for the rest of my life.<span style=""> </span>I actually had a problem deciding what to write, especially after a rather difficult 2007. My main concern is how to make 2008 a better year than the last. I somewhat panicked cos some <i style="">Feng Shui</i> foreseers say 2008 may not be quite fortunate for those born in my ‘animal’ year (which is the year of the sheep, likewise with those born in the year of the rabbit and horse). But I do not choose to believe them. They said year 2007 would be a lucky year, and looked what transpired. 2007 was not that fortunate for me, after all. <o:p></o:p></span> <p class="MsoNormal"><span style="font-family:Arial;">I BELIEVE my fate lies in my hands.<o:p></o:p></span></p> <p class="MsoNormal"><span style="font-family:Arial;"><o:p></o:p>So while struggling the past week, I did a bit of rethinking, and reading here and there. I came across something that struck a cord within. It was some articles I read on the virtues of silence, calmness in adversity and ‘soft speech’ and how these can bring you inner peace and wealth, in all sense of the word. <o:p></o:p></span></p> <p class="MsoNormal"><span style="font-family:Arial;"><o:p></o:p></span><b style=""><span style="font-family:Arial;">Wagging Tongues and Loudness Brings Bad Fortune<o:p></o:p></span></b></p> <p class="MsoNormal"><span style="font-family:Arial;"><o:p>A</o:p>t the start of 2008, instead of feeling energized, I had actually felt tired and spent after a stressed-out 2007. I suddenly realized why I felt this way – I have actually been talking too much the past year. As far as I can remember, the past year was really a bitch! (pardon the language). Never before had I spent so much energy bitching, gossiping, resenting and basically just complaining, complaining, complaining. Come to think of it, I was basically a raving lunatic the past year for reasons only known to me. I spent so much energy wallowing in self-pity and resentment. For trivial reasons, I shouted at my colleagues and screamed at the kids. No wonder, I felt so tired. Believe you me, the law of attraction was hitting me right between the eyes, and I still couldn’t figure out why things just went from bad to worse simply because I was too busy bitching and being angry.<span style=""> </span>And worst, alongside all the anger and resentment; my position at work suffered and my finances just went down the drain. My debts were piling, and money that should have come my way, never came. By year’s end, I knew I had to rethink my handle on things or lose control of my life.<o:p></o:p></span></p> <p class="MsoNormal"><span style="font-family:Arial;"><o:p></o:p>The articles on silence and ‘soft speech’ caught my eyes 3 days into the New Year. And at that moment, just the very thought of silence and soft speech brought a sense of calmness over me. And, think, if I were to actually practice silence and soft speech on a day to day basis, will it not be highly possible that I can have inner peace, serenity and attract good fortune? It’s been barely 5 days into this practice of silence, and I try to talk less and low. My heartbeat seems calmer. I was not angry at the waiter for forgetting about the breakfast I ordered this morning. Is it coincidence that I received just today the 5k that someone owed me nearly 2 years ago? Maybe it is, I don’t know yet.<o:p></o:p></span></p> <p class="MsoNormal"><b style=""><span style="font-family:Arial;">Silence is a Virtue<o:p></o:p></span></b></p> <p class="MsoNormal"><span style="font-family:Arial;"><o:p></o:p>Silence is a virtue, indeed. One thing is for sure, we can stay out of trouble if we just keep our mouth shut. <span style=""> </span>Use wisely in everyday life, silence is an excellent tool in daily conversations and to make negotiations work our way. But many of us fear silence. We find silence awkward, uncomfortable. And to break the awkward silence, many of us make the mistake of opening our mouths and making even more mistakes. This happens often in business negotiations. Some Asian cultures have used silence as a business tool to their advantage.<o:p></o:p></span></p> <p class="MsoNormal"><span style="font-family:Arial;"><o:p></o:p>As pointed out by Tim Berry in his post <span style=""></span><a href="">using_silence</a>, silence is one of the most powerful tools in conversation, and, perhaps more to business negotiations. <span style=""> </span>“…sometimes a Japanese person will win concessions from an American simply by not fearing silence. For example, the American breaks what seems like an awkward pause by lowering the price, thinking that the silence is disapproval. The Japanese person, however, was simply respecting the importance of the offer.” <span style=""> </span><o:p></o:p></span></p> <p class="MsoNormal"><o:p> </o:p></p> <p class="MsoNormal"><span style="font-family:Arial;">In business, in order to make effective presentations, one of the tips given by <a href="">Guykawasaki</a><strong><span style="font-weight: normal;font-family:Arial;" > is "don't overwhelm the audience</span></strong><strong><span style="font-family:Arial;">.</span></strong> Be entertaining but use moments of silence, soft speech, and slow cadence."<o:p></o:p></span></p> <p class="MsoNormal"><span style="font-family:Arial;"><o:p></o:p>On a personal level, Roy Posner on <a href=""><span style="text-decoration: underline;">gurusoftware</span></a> said “If we speak too much, these energies are squandered, which tends attract corresponding negative results from the field of life. However, if we <i>conserve</i> our energies through reduced speech - or, better yet, by completely remaining silent - the energies are fortified and strengthened, which tends to attract sudden and abundant good fortune from the world around us.”<o:p><br /></o:p><br />From my own experience, I believe this last quote to be true. When one bitches, rants, and raves, one drives away all positive energy and attract in its stead bad vibes and unfortunate events. The law of attraction, remember? Therefore, if we conserve our energy by keeping silent, the inner peace and spiritual harmony and goodness we feel will infuse into the space of life around us and attract more good vibes and abundance of good fortune.<o:p><br /></o:p><br />In silence, you are more in contact with your own reality by calming the senses and controlling the mind. There is a voice that you can hear in that silence, the voice of your own soul. You will feel the Divine presence when silence reigns.</span></p><p class="MsoNormal"><br /><span style="font-family:Arial;"><o:p></o:p></span></p><img src="" height="1" width="1" alt=""/>aljo to Stay Positive? Just Stop Those Negative Thoughts!<em><span style="font-style: normal;font-family:Arial;font-size:11;" >There are many articles, newsletters and sites that tell us how to be positive and stay happy. They all give more or less the same “how-to’s”. These are all good and usually comprise a long list of tips such as looking inside yourself and appreciate who you are, think happy memories, get motivated, develop a gratitude journal, determine why your life sucks, etc, etc. Some tips are good instant ‘fixers’; some ‘fixers’ take some time to develop and put to practice, while others do not do much, to say the least.<o:p></o:p></span></em> <p><em><span style="font-style: normal;font-family:Arial;font-size:11;" >I prefer tips that give immediate results but with permanent good effects. In this particular situation, I especially avoid those that tell me to analyze myself and to determine why my life sucks. Really, I don't have the time for that especially when I am already on this train of devilish thoughts that’s rapidly heading me straight to derailment. I want instant fixers which can be developed into good habits and give me a happy perspective on life. <o:p></o:p></span></em></p> <p><em><b style=""><span style="font-style: normal;font-family:Arial;font-size:11;" >How to Feel Good<o:p></o:p></span></b></em></p> <p><em><span style="font-style: normal;font-family:Arial;font-size:11;" >So when you feel your day is about to go terribly bad with a negative thought lodged in your head, just shrug off that bad thought and replace it instantly with a positive thought. How can you do that? I have come up with a list of 5 good fixers to make my day chirpy. They have worked wonders for me.</span></em></p> <ol><li><!--[if !supportLists]--><em><span style="font-style: normal;font-family:Arial;font-size:11;" ><span style=""><span style=""></span></span></span></em><!--[endif]--><em><span style="font-style: normal;font-family:Arial;font-size:11;" >Feel Grateful</span></em></li><li><em><span style="font-style: normal;font-family:Arial;font-size:11;" ></span></em><!--[if !supportLists]--><em><span style="font-style: normal;font-family:Arial;font-size:11;" ><span style=""><span style=""></span></span></span></em><!--[endif]--><em><span style="font-style: normal;font-family:Arial;font-size:11;" >Start your Day with Laughter<;" >Smile a </span></em><st1:place><em><span style="font-style: normal;font-family:Arial;font-size:11;" >Lot</span></em></st1:place></li><li><st1:place><em><span style="font-style: normal;font-family:Arial;font-size:11;" ></span></em></st1:place><!--[if !supportLists]--><em><span style="font-style: normal;font-family:Arial;font-size:11;" ><span style=""></span></span></em><em><span style="font-style: normal;font-family:Arial;font-size:11;" >Read Inspirational Quotes/Articles<;" >Be <span style=""> </span>Hopeful – Look Forward to Tomorrow<o:p></o:p></span></em></li></ol> <p><em><b style=""><span style="font-style: normal;font-family:Arial;font-size:11;" >Beware the Law of Attraction<o:p></o:p></span></b></em></p> <p><em><span style="font-style: normal;font-family:Arial;font-size:11;" >Take caution, though. It really is true about the law of attraction. Positive thoughts attract an abundance of positive thoughts. By internalizing these wondrous feelings – gratitude, happiness, cheerfulness, inspiration, and hope – that come with practicing the 5 habits I mentioned, you will attract an abundance of happy feelings. Be cautious, therefore, on the flip side. For, if you start on a negative thought, you will attract more bad feelings and situations. Been there, done that. Just one bad thought, like bitching about the boss or that dumb-dumb colleague who got promoted, will attract bad events and situations - you may be bypassed in office promotion, or relocated or transferred.<br /></span></em></p><p><em><span style="font-style: normal;font-family:Arial;font-size:11;" >I have gone through bad patches in life where I took some things badly, and nurtured the anger and hate inside. I even took it further, and send out smses to spread bad stories about the target of my anger. Long story short, I suffered the consequences for more than a year, things just went from bad to worse. I then realize that the only way I can make good is to stop those bad thoughts, replace them with good ones, look at the target of my hate in a positive light, and be happy for them. And then, things started to change for the better. So really, I am learning and re-learning every time.</span></em></p> <p style="font-weight: bold;"><em><span style="font-style: normal;font-family:Arial;font-size:11;" >The 5 Tips to Stay Positive</span></em></p><p><em><span style="font-style: normal;font-family:Arial;font-size:11;" >I will briefly share the 5 things I do to stay positive and to hold on to that happy feeling inside.<br /><o:p></o:p></span></em></p> <p style="margin-left: 0.5in; text-indent: -0.5in;"><!--[if !supportLists]--><em><span style="font-style: normal;font-family:Arial;font-size:11;" ><span style="">1.<span style=""> </span></span></span></em><!--[endif]--><em><span style="font-style: normal;font-family:Arial;font-size:11;" >Feel Grateful<o:p></o:p></span></em></p> <p style="margin-left: 0.5in;"><em><span style="font-style: normal;font-family:Arial;font-size:11;" >The quickest way to get rid of that bad thought that keeps bugging you is to shake it off literally, and instantly replace it with a grateful thought. No matter, how trivial that good thought is, just feel grateful about anything good that’s going on in your life. For instance, be grateful that you can afford a car and can drive to work in comfort. Glance at the bus station if you drive past one, and be grateful that you don’t have to stand in the rain, cold or heat to catch a bus to work. Be grateful that you even have a salary, for you are more fortunate than a jobless person or that homeless person out on the street. Hold on to that warm feeling of gratitude and continue to feel it, for it will make your day get better and better.<o:p></o:p></span></em></p> <p style="margin-left: 0.5in; text-indent: -0.5in;"><!--[if !supportLists]--><em><span style="font-style: normal;font-family:Arial;font-size:11;" ><span style="">2.<span style=""> </span></span></span></em><!--[endif]--><em><span style="font-style: normal;font-family:Arial;font-size:11;" >Start your Day with Laughter<o:p></o:p></span></em></p> <p style="margin-left: 0.5in;"><em><span style="font-style: normal;font-family:Arial;font-size:11;" >I love to sit down for morning break with my buddies at work and just laugh at some old jokes, or at the recent antics of our 5 or 6 year-olds, or just laugh at our stupid selves sometimes. It is true about laughter being the best medicine. When you laugh till you cry at some good jokes, the rest of the day will just be dandy, and need I say that the rest of the year will just be filled with laughter.<o:p></o:p></span></em></p> <p style="margin-left: 0.5in; text-indent: -0.5in;"><!--[if !supportLists]--><em><span style="font-style: normal;font-family:Arial;font-size:11;" ><span style="">3.<span style=""> </span></span></span></em><!--[endif]--><em><span style="font-style: normal;font-family:Arial;font-size:11;" >Smile a </span></em><st1:place><em><span style="font-style: normal;font-family:Arial;font-size:11;" >Lot</span></em></st1:place><em><span style="font-style: normal;font-family:Arial;font-size:11;" ><o:p></o:p></span></em></p> <p style="margin-left: 0.5in;"><em><span style="font-style: normal;font-family:Arial;font-size:11;" >There is something about a smile that gives people that warm, cozy feeling. When a person’s face lights up with a smile at you, it is hard to resist giving back a smile and you can even feel your stress evaporating. A smile will launch a thousand smiles,no doubt, and remember, a smile can lift that droop on your face, making you look years younger!<o:p></o:p></span></em></p> <p style="margin-left: 0.5in; text-indent: -0.5in;"><!--[if !supportLists]--><em><span style="font-style: normal;font-family:Arial;font-size:11;" ><span style="">4.<span style=""> </span></span></span></em><!--[endif]--><em><span style="font-style: normal;font-family:Arial;font-size:11;" >Read Inspirational Quotes/Articles<o:p></o:p></span></em></p> <p style="margin-left: 0.5in;"><em><span style="font-style: normal;font-family:Arial;font-size:11;" >There are some days when I don’t seem to have much to look forward to. So I will deliberately look up some inspirational books to read. And these days, it is made so much easier with the internet. I just go to any of the sites that can make you feel good about life, and read some inspirational stories. These are easy to find, you just <a href="">google</a> for sites on how to be happy, on being healthy, or on getting rich. One of my favorites is the <a href="">science of getting rich </a>site, where the articles, forum and related activities have helped make good my day every time. In addition, I maintain a link to a<a href=""> quotations page</a> that provides a daily update on motivational quotes (see bottom of this page) which keeps me having that 'feel good' feeling everyday.<o:p></o:p></span></em></p> <p style="margin-left: 0.5in; text-indent: -0.5in;"><!--[if !supportLists]--><em><span style="font-style: normal;font-family:Arial;font-size:11;" ><span style="">5.<span style=""> </span></span></span></em><!--[endif]--><em><span style="font-style: normal;font-family:Arial;font-size:11;" >Be<span style=""> </span>Hopeful – Look Forward to Tomorrow<o:p></o:p></span></em></p> <p style="margin-left: 0.5in;"><em><span style=";font-family:Arial;font-size:11;" >Hope</span></em><em><span style="font-style: normal;font-family:Arial;font-size:11;" > has made its share of numerous miracles in life. Having hope has kept many alive, literally – spiritually, emotionally, physically. We’ve heard tragic stories of people giving up hope and just curling up and die. And many more stories about people who have been cured and brought back from the brink of death because they never gave up hope. To believe in hope is one of the secrets to creating miracles in our lives.<o:p></o:p></span></em></p> <p>So, there, the five simple tricks to keep you staying positive day after day. Try them, and better still, make a habit out of them. They cost nothing. In fact, you will have nothing to lose but everything to gain. They will bring many, many small miracles every day into your life!</p><p><br /><em></em></p><img src="" height="1" width="1" alt=""/>aljo to Keep Your New Year’s Resolutions<p class="MsoNormal"><span style=";font-family:Arial;font-size:11;" >The New Year is round the corner. Like most people, I come up with a list of my resolutions for the New Year. And probably like most people, I start the New Year enthusiastically with my New Year’s resolutions but come my birthday in February’s end, most of my New Year’s resolutions may have turned into New Year delusions. <o:p></o:p></span></p> <p class="MsoNormal"><span style=";font-family:Arial;font-size:11;" ><o:p></o:p>I have made some progress in the past with goals I listed as my New Year’s resolutions, like getting a higher education, traveling to other countries, see more of the world, and spend more time with the family, my mum and siblings. These get dropped off my list, but not necessarily making my list shorter as I always add new goals as I progress along. I do notice, however, that I seem to be making some of the same New Year’s resolutions year after year. But I figured if I don’t give up year after year, I could successfully achieve everything on my list, no matter how many years it would take; the very least, I develop the habit of <b style="">planning</b> for a better and more enriched life.<o:p></o:p></span></p> <p class="MsoNormal"><span style=";font-family:Arial;font-size:11;" ><o:p></o:p>So, here I go again, listing out my New Year’s Resolutions according to my priority for the New Year this time around:<o:p></o:p></span></p> <ul><li><!--[if !supportLists]--><span style=";font-family:Arial;font-size:11;" ><o:p> </o:p><span style=""></span></span><span style=";font-family:Arial;font-size:11;" >Pay off Debt</span><span style=";font-family:Arial;font-size:11;" ><span style=""><span style=""></span></span></span></li><li><span style=";font-family:Arial;font-size:11;" ><span style=""><span style=""></span></span></span><span style=";font-family:Arial;font-size:11;" >Save Money</span><span style=";font-family:Arial;font-size:11;" ><span style=""><span style=""></span></span></span></li><li><span style=";font-family:Arial;font-size:11;" ><span style=""><span style=""></span></span></span><span style=";font-family:Arial;font-size:11;" >Exercise More</span><span style=";font-family:Arial;font-size:11;" ><span style=""></span></span></li><li><span style=";font-family:Arial;font-size:11;" ><span style=""></span></span><span style=";font-family:Arial;font-size:11;" >Lose the Bulge</span><span style=";font-family:Arial;font-size:11;" ><span style=""></span></span></li><li><span style=";font-family:Arial;font-size:11;" ><span style=""></span></span><span style=";font-family:Arial;font-size:11;" >Learn Something New</span><span style=";font-family:Arial;font-size:11;" ><span style=""> </span>- learn a new skill, travel more</span><span style=";font-family:Arial;font-size:11;" ><span style=""><span style=""></span></span></span></li><li><span style=";font-family:Arial;font-size:11;" ><span style=""><span style=""></span></span></span><span style=";font-family:Arial;font-size:11;" >Help Others – Volunteer more<o:p></o:p></span></li></ul> <p class="MsoNormal"><span style=";font-family:Arial;font-size:11;" ><o:p> </o:p><br />Why even bother having a list of New Year’s resolutions if one can never keep them anyways, you may ask. I keep asking myself that, too, year in, year out. <span style=""> </span>I have partly answered that already. <o:p></o:p></span></p> <p class="MsoNormal"><span style=";font-family:Arial;font-size:11;" ><o:p></o:p>Essentially, it is all about planning ahead, and keeping check of your life. When you plan ahead, you basically have a plan of actions or strategies or steps to reach your goals. Having thought out and written down your action plans gives you the advantage of checking your progress, and if your resolutions remain unresolved, this allows you to revisit and review your action plans for any shortcomings or even refine any of your resolutions which may be unrealistic.<br /></span></p> <p class="MsoNormal"><span style=";font-family:Arial;font-size:11;" ><o:p></o:p>Here are some tips I have gathered to help keep your New Year’s resolutions. <o:p></o:p></span></p> <p class="MsoNormal" style="margin-left: 27pt; text-indent: -27pt;"><!--[if !supportLists]--><span style=";font-family:Arial;font-size:11;" ><o:p> </o:p><span style="">1.<span style=""> </span></span></span><span style=";font-family:Arial;font-size:11;" > Be Realistic<o:p></o:p></span></p> <p class="MsoNormal" style="margin-left: 27pt;"><span style=";font-family:Arial;font-size:11;" >To avoid falling short of your goals, your New Year’s resolutions must be attainable. Ensure that they are all reasonable and not ‘all or nothing’ resolutions.<span style=""> </span>The goals you set should be achievable in steps or phases so that you will have better chance in realizing them.<span style=""> </span><o:p></o:p></span></p> <p class="MsoNormal" style="margin-left: 27pt; text-indent: -27pt;"><!--[if !supportLists]--><span style=";font-family:Arial;font-size:11;" ><span style="">2. <span style=""></span></span></span><!--[endif]--><span style=";font-family:Arial;font-size:11;" > Plan Ahead – Create Your Plan<o:p></o:p></span></p> <p class="MsoNormal" style="margin-left: 27pt;"><span style=";font-family:Arial;font-size:11;" >To achieve your resolutions, put in some thoughts on your goals and plan ahead. Create an outline for your plans. You will be more successful if the resolutions can be translated into clear steps that can be put into action. <o:p></o:p></span></p> <p class="MsoNormal" style="margin-left: 27pt; text-indent: -27pt;"><!--[if !supportLists]--><span style=";font-family:Arial;font-size:11;" ><span style="">3. </span></span><span style=";font-family:Arial;font-size:11;" > Remind Yourself Everyday<o:p></o:p></span></p> <p class="MsoNormal" style="margin-left: 27pt;"><span class="bodytext"><span style=";font-family:Arial;font-size:11;" ><o:p></o:p>One has to think ‘year round’, not just the New Year. </span></span><span class="bodytext"><span style=";font-family:Arial;font-size:11;" >Nobody can accomplish anything big in one day. Although the resolutions are set in one day, but you can only accomplished them by taking many, many tiny steps throughout the year. Your list of New Year's resolutions should be nothing more than a starting point. Stick to the plan of action that you have laid out, and create reminders for yourself when it's time to work on a given task or start onto the next step.</span></span><span style=";font-family:Arial;font-size:11;" ><br /><!--[if !supportLineBreakNewLine]--><!--[endif]--><span class="bodytext"><o:p></o:p></span></span></p> <p class="MsoNormal" style="margin-left: 27pt; text-indent: -27pt;"><!--[if !supportLists]--><span style=";font-family:Arial;font-size:11;" ><span style="">4. </span></span><span style=";font-family:Arial;font-size:11;" > Talk About It or Get a Resolution Partner<o:p></o:p></span></p> <p class="MsoNormal" style="margin-left: 27pt;"><span style=";font-family:Arial;font-size:11;" >You will need to create a support group among friends and family members who can support your resolve to change for the better. Your best bet would be your best buddy or a sibling or daughter/son so that you can motivate each other.<o:p></o:p></span></p> <p class="MsoNormal" style="margin-left: 27pt; text-indent: -27pt;"><!--[if !supportLists]--><span style=";font-family:Arial;font-size:11;" ><span style="">5. <span style=""></span></span></span><!--[endif]--><span style=";font-family:Arial;font-size:11;" >Seek out Resources<o:p></o:p></span></p> <p style="margin-left: 27pt;"><span style=";font-family:Arial;font-size:11;" >You can do some research by looking up resources on the Internet if you are lazy like me to go to the library. Your local dailies and magazines could be other sources of information. Or you can always inquire and discuss with friends or family members to explore resources to educate yourself on approaches that can assist you in reaching your goals. <o:p></o:p></span></p> <p class="MsoNormal" style="margin-left: 27pt; text-indent: -27pt;"><!--[if !supportLists]--><span class="bodytext"><span style=";font-family:Arial;font-size:11;" ><span style="">6. </span></span></span><span class="bodytext"><span style=";font-family:Arial;font-size:11;" > Monitor your Progress</span></span><span class="bodytext"><span style=";font-family:Arial;font-size:11;" ><o:p></o:p></span></span></p> <p class="MsoNormal" style="margin-left: 27pt;"><span style=";font-family:Arial;font-size:11;" >Monitoring your progress can keep you focus on your goals. Keep track of each small success you make when following the steps you have laid down. It is the small accomplishments that will help keep you motivated.<o:p></o:p></span></p> <p class="MsoNormal" style="margin-left: 27pt; text-indent: -27pt;"><!--[if !supportLists]--><span class="bodytext"><span style=";font-family:Arial;font-size:11;" ><span style="">7. </span></span></span><span class="bodytext"><span style=";font-family:Arial;font-size:11;" > Reward Yourself</span></span><span class="bodytext"><span style=";font-family:Arial;font-size:11;" ><o:p></o:p></span></span></p> <p class="MsoNormal" style="margin-left: 27pt;"><span style=";font-family:Arial;font-size:11;" ><o:p></o:p>Make a decision to reward yourself for the small accomplishments you have made; make it something personal and special. It does not need to be luxurious or expensive; maybe something simple like a one-hour massage, or a weekend getaway. Pamper yourself; treat yourself with little rewards every time for sticking to your resolutions.<span class="bodytext"><o:p></o:p></span></span></p> <p class="MsoNormal" style="margin-left: 27pt; text-indent: -27pt;"><span class="bodytext"><span style=";font-family:Arial;font-size:11;" ><o:p>8. </o:p></span></span><span style=";font-family:Arial;font-size:11;" > Never Give up<o:p></o:p></span></p> <p class="MsoNormal" style="margin-left: 27pt;"><span style=";font-family:Arial;font-size:11;" ><o:p></o:p>If you run out of steam couple of months in the New Year, don’t despair. Refresh yourself on your resolutions. Recap why you even bother to list those goals as your resolutions; your earlier enthusiasm could motivate you on. The resolutions are for the whole year long; you can always pick up where you left off on your steps of action. Stay positive and, more importantly, remain grateful that you still have the resources and capability to pursue your goals towards your own success in life.</span></p> <p class="MsoNormal" style="margin-left: 27pt;"><span style=";font-family:Arial;font-size:11;" ><o:p> </o:p></span></p><img src="" height="1" width="1" alt=""/>aljo Ethics: Of Bad Blogging Practices, Blog Libel and Cyber Bullying<o:p></o:p>I started to blog when I saw that blogs can enrich humans – both the mind and the pocket. The attractive part was how you can monetize your blog; blogging to riches, everyone says. But as in everything else in life there are two sides to everything: the Good and the Bad. Guess blogging is no exception. There in blogosphere, slowly but surely, things negative began unfolding, from mild but irresponsible paid reviews, blog libels to cyber bullying and its tragic consequence. <p class="MsoNormal"><o:p> </o:p>It is good to be kept informed of these matters so that one would not stumble into dangerous territory.</p> <p class="MsoNormal"><o:p></o:p><b style="">Cyber bullying<o:p></o:p></b></p> <p class="MsoNormal"><o:p> </o:p>It is observed that although online bullying especially involving teenagers may be mild but some say it is on the rise.<span style=""> </span>It is raising concerns especially on the heels of a widely publicised case in <st1:state><st1:place>Missouri</st1:place></st1:state> that led to the suicide death of a 13-year-old girl, Megan Meier, in October 2006. What’s troubling is that it is a story of an internet hoax, a blog impersonation it seems, that ended in a tragic teen suicide.<o:p></o:p></p> <p class="MsoNormal"><o:p> </o:p>According to a <st1:date3<sup>rd</sup> December 2007</st1:date> report on eSchool News.com:<o:p></o:p></p> <p class="MsoNormal"><o:p> </o:p><i style="">“Last month, officials in the </i><st1:state><st1:place><i style="">Missouri</i></st1:place></st1:state><i style=""> town of </i><st1:city><st1:place><i style="">Dardenne Prairie</i></st1:place></st1:city><i style=""> made internet harassment a misdemeanor, in the wake of public outrage over the suicide of a 13-year-old resident there last year.<br /><br /.”<o:p></o:p></i></p> <p class="MsoNormal"><o:p></o:p>The twist to the story was that the teenage boy, Josh, never existed; he was created by the mother of one of Megan’s former friends who live down the street. The hoax was created by the 47 year mother, Lori Drew, who by now has earned every vilest label a mom can ever have. The even bizarre twist to this is that this most hated mom in the world has allegedly set up a blog<span style=""> </span><a href="">meganhaditcoming</a><span style=""> </span>recently to explain her actions, causing another outpouring of rage and venom.<o:p></o:p></p> <p class="MsoNormal"><o:p></o:p>Problem is, people are not sure if this blog is a fake. Looks like another blog impersonation because I would like to believe that no mother in her right mind would go publish a blog after the fact and remain remorseless. It just baffles the mind. But then again, we don’t know what a human mind, worse an insane mind at that, is capable of doing. </p> <p class="MsoNormal"><o:p></o:p>A scary thought now crosses my mind: Blogs can actually become powerful, it can kill.</p> <p class="MsoNormal"><o:p></o:p><b style="">Blog Libel<o:p></o:p></b></p> <p class="MsoNormal"><o:p></o:p>In <st1:country-region><st1:place>Malaysia</st1:place></st1:country-region>, blogsites owned by Malaysians are being investigated by the authorities. The <i style=""><span style="">Dewan Rakyat</span></i> (literally "People's Hall") or House of Representatives which is the lower House of the Parliament of Malaysia in its 5<sup>th</sup> December 2007 sitting discussed the issue of blog libel. The House was informed that the “Malaysian Government takes a serious view of blogs which twist facts and pose a threat to public order” (as reported widely in local dailies the following day). House members were also updated of an arrest made in connection with the investigation by local police of five cases of alleged libel involving blogs. As reported, Malaysian “bloggers who abused their blogsites to disseminate libel or twist facts can be subjected to action under the Sedition Act 1948, Penal Code and the Communications and Multimedia Act 1998”.</p> <p class="MsoNormal"><o:p></o:p>‘Twist facts’? What if the bloggers were merely <i style="">untwisting twisted facts</i>? Okay, enough of that one. I’d like to say more …but suffice to say, as long as one doesn’t ‘disseminate libel and twist facts’, I guess one is safe.</p> <p><b style="">Paid Review Dilemma, Blogging Ethics, <span style="">Blog Etiquette</span></b><o:p></o:p></p> <p>Doing paid reviews has become a tricky area for bloggers. Who doesn’t want to get paid and get freebies? But it’s hard after that to remain totally objective and be critical of the hand that feeds you. In the travel industry, with so many offers of freebies or free travel junkets, it is easy to see why many said that the judgment of travel bloggers who accept freebies are compromised. Problogger posts an a good article <a href="">blogging-ethics-and-sponsored-reviews</a> by Melissa Petri <em><span style="font-style: normal;">who talked about staying ethical despite the dilemma. </span></em></p> <p class="MsoNormal">On blog etiquette, <a href="">sueblimely</a> wrote quite a bit on what she call ‘Betiquette’ about the relevant behaviour in attracting and maintaining readers, which is worth reading. But I particularly like the excellent and sharp pointers Chris from <a href="" target="_blank" title="Blog Op"><span style="text-decoration: none;">Blog-Op</span></a> gave on blog etiquette posted on <a href=""><span style="text-decoration: none;">destyonline</span></a> :<o:p></o:p></p> <ul type="disc"><li class="MsoNormal" style="">Never, ever steal content, period.</li><li class="MsoNormal" style="">Don’t be afraid to give credit - Even if another blogger only gave you the basic idea for your 4000 word original post, it doesn’t hurt to link back.</li><li class="MsoNormal" style="">Link often, but only when relevant. Don’t feel you have to get hitched onto a link train if you don’t want to.</li><li class="MsoNormal" style="">Don’t write for Google, write for humans.</li><li class="MsoNormal" style="">Don’t hotlink images.</li><li class="MsoNormal" style="">Never write in a comment, what you wouldn’t say to someone’s face.</li><li class="MsoNormal" style="">Don’t accuse another blogger of anything without rock hard evidence.</li><li class="MsoNormal" style="">Don’t use the email address you gather for comments, for spam purposes - A personal message is fine, but when I get a ‘Dear friend - please Digg my blog’ generic type email it gets marked as spam and deleted.</li><li class="MsoNormal" style="">Treat others as you like to be treated.</li></ul> <p class="MsoNormal">I listed Chris’ pointers in total as I intend to keep them here as refresher for me to visit every now and then, to keep on the straight and narrow, in blogging at least.</p><p class="MsoNormal"><br /><o:p></o:p></p><img src="" height="1" width="1" alt=""/>aljo's Wish - A Tribute to Parents EverywhereWith our busy schedules, we very often lose touch, forget or simply ignore our parents. At times, we just hate them. I'd like to take time out here from talking about what I normally talk about here and make a gentle reminder to us all to remember and pay tribute to our parents, be they both parents (in which case, you are among the luckiest), single dad or single mom. There no special event, really. We do not need any special occasion or special day to pay tribute to our parents. Pay tribute to parents everyday, if we can, for their time with us is short.<br /><br />I am actually prompted to post this after reading an email a dear friend send with a beautiful powerpoint presentation about Parent's Wish. It touches so deep that I had to post a link to the site:<br /><br /><a href=""></a><br /><br />Please take time to visit the site, listen to the presentation so you will not easily feel irritated or angry with your parents. I know, we are all guilty, at some point or another, of feeling irritated, angry, and even ashamed of our parents. I know I did, many times that I won't talked to my mom for months. But every single time, I am drawn back to her, we make peace, and it's back to the parent-child 'love-hate' thing again. But , it's good, at least we talk and listen to each other as much as we can.<br /><a href=""></a><br />It is very relevant to everyone, yes just about everyone, irrespective whether you have (both) parents or just a single dad or single mom. So do find the time to visit the site and send an email to anyone you know. I can be sure that the presentation will bring tears to your eyes, unless or course your heart is made of stone. And parents please forward to your kids, too, just as a gentle reminder for them to respect not only their own parents but parents everywhere. My fervent hope is that, after reading it and living it, this world will be a much better place to live.<img src="" height="1" width="1" alt=""/>aljo I Make Me Feel Good Today<span style="font-family:Arial;">There are days when I wake up in the morning and just don’t feel like getting out of bed. <span style=""> </span>It is going to be another day at a job that I am beginning to hate. Worse, the bank just called the previous day to demand last month’s payment for the house. My credit card debts are piling higher and higher. I am down to my last 20 on which I have to survive for the next 2 weeks.<span style=""> </span>I just want curl up in bed and die a painless death. </span> <p class="MsoBodyText" style=""><!--[if !supportLists]--></p><span style="font-family:arial;">But the kids need breakfast before going to their daily activities, school and what not. Dragging myself out of bed, Robert Frost’s rhyme came to mind. </span><span style="font-family:arial;"> </span><span style="font-family:arial;">‘...The woods are lovely, dark and deep. But I have promises to keep and miles to go before I sleep’.</span><span style="font-family:Arial;"> So I will make myself feel good today...feel good about me, about people around me, about things around me. Just feel good about everything under the sun. So how do I make me feel good today so I can go on with my day? I have a few daily mantras which kept me going. I followed through these five mantras as much as I can each day, and they have worked for me:<br /><br /></span><span style="font-family:Arial;"><o:p></o:p></span><span style="font-family:Arial;"><o:p> </o:p><span style="">1.<span style=""> </span></span></span><!--[endif]--><span style="font-family:Arial;"> Be Grateful </span> <p class="MsoBodyText" style="margin-left: 45pt; text-indent: -0.25in;"><!--[if !supportLists]--><span style="font-family:Symbol;"><span style="">·<span style=""> </span></span></span><!--[endif]--><span style="font-family:Arial;">Be grateful that I am alive and healthy – I can breathe, walk, run. I am healthy and the good old heart is pumping great today. I am thankful that I am capable of working and earn money for my loved ones.<o:p></o:p></span></p> <p class="MsoBodyText" style="margin-left: 45pt; text-indent: -0.25in;"><!--[if !supportLists]--><span style="font-family:Symbol;"><span style="">·<span style=""> </span></span></span><!--[endif]--><span style="font-family:Arial;">Be thankful for my family and friends – I try to see the wonder and miracle beyond my little urchin’s face as he goes through his daily ritual of refusing to brush his teeth and eat his breakfast. My friend just had her first baby and another just got married, I will call and congratulate them.<o:p></o:p></span></p> <p class="MsoBodyText" style="margin-left: 45pt; text-indent: -0.25in;"><!--[if !supportLists]--><span style="font-family:Symbol;"><span style="">·<span style=""> </span></span></span><!--[endif]--><span style="font-family:Arial;">Thank God for his glorious creation all around us. This is the easiest to do. I just look around me, the sun is just showing its first rays and the morning wind blows in fresh and sweet. And I see in my mind’s eye some of the favorite scenery pictures that I treasure of God’s</span><span style="font-family:Arial;"> glorious creation.</span></p> <p class="MsoBodyText" style="margin-left: 27pt; text-indent: -27pt;"><!--[if !supportLists]--><span style="font-family:Arial;"><o:p> </o:p><span style="">2.<span style=""> </span></span></span><!--[endif]--><span style="font-family:Arial;"> Put Forth My Intentions <o:p></o:p></span></p> <p class="MsoBodyText" style="margin-left: 27pt;"><span style="font-family:Arial;">I take about 5 - 10 minutes just as the sun is rising, in the quiet of my bedroom, sitting in a relaxed state, and I put forth my intentions to the universe. It’s like a prayer.<span style=""> </span>Usually it works for matters that needed to be resolved urgently, like I need to pay up an outstanding payment to the bank by a certain date. So I announced that to the universe.<span style=""> </span>And somehow, from somewhere, someone pays up some money owed to me, or some claims get approved. Usually it is just enough to make a particular payment. It works each time. Coincidence? Maybe. No matter, what's important is that warm feeling of gratitude inside as I say my thank you(s). However, I find that it does not work when I ask for extras…like striking that million dollar lottery. Hell, I tried; it just doesn’t work that way. No way will it work if I start getting greedy.<o:p></o:p></span></p> <p class="MsoBodyText" style="margin-left: 27pt; text-indent: -27pt;"><!--[if !supportLists]--><span style="font-family:Arial;"><o:p> </o:p><span style="">3.<span style=""> </span></span></span><!--[endif]--><span style="font-family:Arial;"> Stay Positive<o:p></o:p></span></p> <p class="MsoBodyText" style="margin-left: 27pt;"><span style="font-family:Arial;">Having announced my intentions to the universe, I endeavor to stay positive. It is going to be tough the minute I walk out the bedroom door. But I focus on the positive. I find it easier to be positive if I hold on to that feeling of gratitude. I try not to get derailed when the going gets tough. I know it is easier said than done. But this is crucial. From my own experience, I find that if I am angry or I stay mad at somebody, my intentions or prayers are never answered. And I could stay in that bad patch for months, even years, until I blessed the person whom I thought had caused me misery.<o:p></o:p></span></p><!--[if !supportLists]--><span style="font-family:Arial;"><span style="">4. </span></span><span style="font-family:Arial;">Do Good and Keep Busy<o:p></o:p></span> <p class="MsoBodyText" style="margin-left: 27pt;"><span style="font-family:Arial;">Just do good each day, no matter how big or small. I am a firm believer of karma and 'What goes around come around', and also in the universal law: “Do unto others what you would that they do unto you”. I know a man who tried to molest his young sister-in-law. Years later, his own son-in-law tried to molest his younger daughter. Bad karma, it hits you back in exactly the same manner and where it hurts the most.<o:p></o:p></span></p> <p class="MsoBodyText" style="margin-left: 27pt;"><span style="font-family:Arial;">And I keep busy. Weekends, I tend my small orchard. My job is becoming boring…so I blog. I now look forward to tomorrow.<o:p></o:p></span></p> <p class="MsoBodyText" style="margin-left: 27pt; text-indent: -27pt;"><!--[if !supportLists]--><span style="font-family:Arial;"><o:p> </o:p><span style="">5.<span style=""> </span></span></span><!--[endif]--><span style="font-family:Arial;"> Believe and Receive<o:p></o:p></span></p> <p class="MsoNormal" style="margin-left: 27pt;"><span style="font-family:Arial;">Having released to the universe my intentions, I <b style="">believe</b> that I will receive one way or another. I have faith that what I have asked for is on its way to me. I believe and I receive.<o:p></o:p></span></p> <p class="MsoNormal"><span style="font-family:Arial;"><o:p> </o:p>These are the five simple steps I follow to make me feel happy. Except when I get derailed, and that could be for months. But more often than not, they have worked for me. I hope they will for you, too.</span></p><p class="MsoNormal"><br /><span style="font-family:Arial;"><o:p></o:p></span></p><img src="" height="1" width="1" alt=""/>aljo Tips for Beginners - Steps Closer to Making Money<div id="articleInfoBox"> <div class="articleTitle">Hordes of wannabe bloggers around the globe are now venturing into blogging as a business either full-time or part-time. The buzzwords on the current trend are increasing as we speak: 'blogging to riches', 'monetize your blog', 'blogging to the bank', 'blog & make money online', and so on and so forth. By the look of it, one can generalize that blogs are moving away from being purely personal journal or diaries and are now increasingly becoming money making machines.<br /><br />For newbies trying to break into the biz, especially those not too IT savvy, the starting line can be a scary place to be. But the money is just too tempting! Luckily, there are hundreds of sites out there sharing and give out tips and guidelines for beginners for free. Not purely out of the goodness of the heart but more to lure in traffic, of course, because that is the bloodline for this type of business. Irrespective, beginners can't be choosers and have to start from scratch... somewhere. I found a good starting point on Wikibooks which I would recommend for beginners:<br /><br /><a href="">Click here </a><br /><br />Adding on to your wealth of knowledge especially on how bloggers can earn money, Problogger gives helpful tips:<br /><br /><a href="">HelpingBloggersEarnMoney</a><br /><br />I'd like to particularly mention a very helpful website - Blogger Tips and Tricks - by Peter Chen who gives a very easy to follow instructions. Beginners might find it easy to follow:<br /><br /><a href="">Blogger Tips and Tricks</a><br /><br />There are hundreds other sites to learn from and purchase information from. But newbies should take it slow. Learn one thing at a time and just enjoy the process of learning, knowing that at the end of the day, we can sit back and watch the money flow in.<br /><br /></div></div><img src="" height="1" width="1" alt=""/>aljo with MoneyEveryone I know is obsessed with money. Except for my parish priest (s), of course. But then again, they can afford not to worry about money. They get so much donations from the faithful, and have more than enough from Sunday church collections for the their upkeep and expenses of the church. You bet I've been counting how much they get in weekly collections - they publish it in their weekly bulletin. Holy cow! those guys get about the same in a month as 20 lowly paid civil servants put together! Tax free some more. Talk about vocation! If only I'd known...<br /><br />Still on money. Growing up, many of us are told 'Money can't buy everything', 'Money can't buy happiness' or 'Money is the root of all evil'. Yeah, over and over, they stuffed it down our throats and pound it into our tiny brains. And we believe them (whoever the authorities over us were then, parents, grandparents, teachers, priests, nuns, the whole lot). At least, I did, believed them. Money became something that I should never have much of or seek or ask for because money can make me a bad person. But growing up, I realise that the exact opposite is true. Money simply became more and more important and very,very much needed. I saw my father worked himself to his grave just to get money to feed us. My mother scrimp every extra dollar she can and keep them under her bed, inside her pillowcase (even to this day) or behind pictures on the wall. (This became such a habit to her so much so that when the many times she forgot about her hidden stash, my siblings and some neighborly kids have such a thrill finding lost treasures under her bed!)<br /><br />Contrary to what we were told about the 'evils' of money, money soon came to mean almost everything in life. Money means food, clothings, schooling, going to work, curing the body of illnesses, and buy you things that make you healthy. These are the basic necessities that money could bring to our simple lives when I was growing up.<br /><br />Today. Oh, today, I can no longer go through a single day without the thought of money tripping me up! The minute you open your eyes each day: oh what's for breakfast, you asked, and that's money spent; you turned on the bathroom lights, that's money spent; turn on the water, money spent...and so on and so forth, the car, the house , the kids' education; it just doesn't stop, does it? Then some smart Alec comes by and say it right to your face..."well, that's life! So get on with it or stay in your cave!"<br /><br />So, what do I tell me today? That Life is all about making money so I can live a good life and be happy. Well, for now, I believe that much is true. So, Universe, tell me otherwise...<img src="" height="1" width="1" alt=""/>aljo Money and Buy Happiness?<o:p></o:p><i style="">Today<o:p></o:p></i> <p class="MsoNormal"> Today, I begin to document my journey to finding my success and riches in life. I am told that it is my birthright to be rich. All I have to do is ask and receive. I have listed down all my goals of being wealthy. I have written affirmations, set the time frame, and ask the universe, and I am ready to receive. I waited...and waited. Well…nothing. Nothing seemed to work for me. I am sinking more and more into debt, all stressed out and close to penniless and depression.</p> <p class="MsoNormal"><o:p> </o:p>We live today in a world without boundaries, the global village where so much information can be passed around in a blink of an eye via the internet and other ICT devices man has created. In today’s virtual world, I am inundated with an avalanche of systems, books, and e-book on the secrets of success, how to make money and be really, really rich and happy that now I am as confused as ever and nowhere even close to living my dreams of being rich. Through all the confusion, the scams, the truths, the lies, the jungle of information to finding my success, I remain today, as depressed and penniless as I was when I first started out on my own.</p> <p class="MsoNormal"><o:p> </o:p><br /><i style="">The Exposure<o:p></o:p></i></p> <br /><p class="MsoNormal"><i style=""><o:p> </o:p></i>I had traveled a bit: studied in the US of A, holiday in the Gold Coast and <st1:place><st1:city>Sydney</st1:city>, <st1:country-region>Australia</st1:country-region></st1:place>, traveled to <st1:country-region><st1:place>Thailand</st1:place></st1:country-region>.<span style=""> </span>Life is great traveling, learning about people and places. Otherwise, it’s all work, work, work…pay the bills and work, work, work, some more. Don’t even have time to check my email at times. Then, suddenly I have more time on my hands. I am still working though but I now have more time on the computer, traveling the virtual world. But that’s the only thing I have more of now…time. Oh, I forget…my debts, the other thing that I have more of. Still not much money. I just gotta do something about this. Maybe, this online thing can help...<span style=""> </span></p> <p class="MsoNormal"><span style=""> </span><o:p></o:p>Ahh…the Internet. The Internet has created so much yearning and dreams for people like me. It has caused me to see that life is more than this slow comfortable paced, day in-day out working from 8 to 5, waiting for end of the month salary to pay the bills. The Internet bombarded our lives with so much information about anything on the face of the earth. I can read and see much more of what’s happening out there …from the rich and famous to the hardcore poor and downright ugly. I now see that there is more to life than just sitting at work in front of this computer, creating some nonsensical action plans for my local government telling them how best to do their jobs. There should be more to life than this! And I’ll be damn if I want to retire, just simply noted on my employment record as a so-called expertise for local decision-makers and politicians, assisting them in their job to do good for the people …whilst in reality, I remain heavily in debt and still close to being penniless except for some retirement funds which could be gone in 60 seconds the day I retire. Armed with curiosity (hope I don’t get killed like the cat!), actually more of a hunger in wanting to get rich and live my rich dreams, I had started on this journey to find the answers to the question, “Can I really get rich, live my rich dreams and find happiness?”</p> <p class="MsoNormal"><o:p> </o:p><br /><i style="">The Search<o:p></o:p></i></p> <p class="MsoNormal"><o:p> </o:p>Along the way, I am told that there is a science of getting rich, a science of being well, that there exist a universal law of attraction, that the universe will manifest all that you want if you only ask for it, and that the secrets of success and happiness can easily be found. Specifically on money, I read about how you can easily be a money magnet, about secrets of a millionaire mind, making money online, multiple streams of income, passive income, and so on and so forth.</p> <p class="MsoNormal"><o:p> </o:p>In trying to find out which are genuine and which are scams, I am further bombarded by hundreds of books, ebooks, ezines, newsletters and sites telling me how to get rich and make money online if I buy their cash machine packages, their ‘business in a box’, their how-to guides. Get this special offer, this one time offer, they say, and you will be rich beyond your wildest dreams!<br /></p> <p class="MsoNormal"><o:p> </o:p><br /><i style="">Today Still<o:p></o:p></i></p> <p class="MsoNormal"><o:p></o:p>Today, here I am still, lost in this jungle of ‘make money’ offers but very much obsessed with making money. After all the questioning and searching, here I am, still heavily in debt, even closer to penniless, and worst still now, I am very much lost and even more confused!</p><p class="MsoNormal"><br /></p> <p class="MsoNormal"><o:p> </o:p>Will I ever get out of this, I wonder? Will I ever get out of this jungle, filthy but rich and smelling of success, and happily living my rich dreams? Is money equals success? I wonder still. I am nowhere close to getting the answer to the big question above. So my journey continues…</p><img src="" height="1" width="1" alt=""/>aljo
http://feeds.feedburner.com/blogspot/IWRu
CC-MAIN-2017-26
refinedweb
18,713
62.88
Today a new Sublime Text plugin. You can try this alpha out today by installing the new compiler available on npm. Richer ES6 experience In TypeScript 1.5, we’re adding a number of new ES6 features. These features work together with the TypeScript type system to give you helpful tooling when working with the new ES6 code patterns. Modules The module syntax of ES6 is a powerful way of working with modules. You can interact with modules by importing whole modules or by working with individual exports directly. import * as Math from “my/math”; import { add, subtract } from “my/math”; ES6 also supports a range of functionality in specifying exports. You can export declarations, such as classes or functions. You can also export a ‘default’ to import the module directly. For’ve been using TypeScript, you may notice that this is similar to TypeScript external modules. This is no accident. When we created external modules for TypeScript, we were working on the same problems. The ES6 design takes the capabilities even further, showing a powerful, mature design. We will continue to support external modules, but we will begin encouraging developers to use the more capable ES6 module syntax. Destructuring Destructuring is a handy new feature that comes as part of our ES6 support. With it, you can pull apart, or destructure, objects and arrays. var [x, y] = [10, 20]; [x, y] = [y, x]; // a simple swap You can also use destructuring to handle function parameters: var myClient = {name: “Bob”, height: 6}; function greetClient({name, height: howTall}) { console.log(“Hello, “ + name + “, who is “ + howTall + ” feet tall.”); } greetClient(myClient); In the above, greetClient takes in a single object that has a name and height property. Using the ‘height: howTall’ syntax, we can rename the height property to howTall inside of greetClient. And more We’ve also added for-of support for better iteration, let/const compiling to ES5, unicode support, an ES6 output mode, and better support for computed properties. Decorators We’ve also worked with the Angular, Ember, and Aurelia (from the makers of Durandal) teams on a decorator proposal for ES7, which we’re previewing in TypeScript 1.5 Alpha. Decorators allow you to create a clean separation of concerns. In this example, we see how the @memoize decorator could be used to note that a getter/setter pair can be memoized: class Person { @memoize get name() { return `${this.first} ${this.last}` } set name(val) { let [first, last] = val.split(‘ ‘); this.first = first; this.last = last; } } Developers will be able to write new decorators and mix-and-match them to work with the type system. Sublime Text plugin Along with TypeScript 1.5 Alpha, we’re also releasing a preview of the Sublime Text plugin for TypeScript to enable more developers to get editor support when authoring TypeScript. This plugin works with both Sublime Text 2 and Sublime Text 3 and shows some of what is possible with the TypeScript type system. Sublime Text and the TypeScript plugin are available for OSX, Linux, and Windows. TypeScript commands available in Sublime Text The Sublime Text plugin allows you to easily navigate, refactor, format, and investigate TypeScript code. Those who tried the Sublime plugin that came with the ng-conf demo may also notice that this updated plugin is snappier, especially with larger files. We’re excited to hear your feedback. If you’d like to leave a comment, you can fill out an issue on the issue tracker. Also, feel free to jump in and send us your pull requests to help make the Sublime plugin even better. What’s next This alpha release shows what will be possible in TypeScript 1.5 when it’s released, and we want to hear from you. We’re working hard on TypeScript 1.5, and you can help us make it a strong release by trying it out and sending us any issues you find. Join the conversationAdd Comment Nice work on the Sublime plug-in. Great! Many, many thanks! P.S. I think you have one little typo in Person class: @memorize instead of @memoize. @Harris Thanks. Re: memoize, you can read more about memoization here: en.wikipedia.org/…/Memoization It's a cool trick for optimization. But looks like I typo'd in the sample. Will fix. Thanks guys great job! Will check it out asap! Can't wait for the stable version with VS support! BTW: the date is a bit off. Blog post says it is created Mar 27 2015 but it was definitely not here a few hours ago 😉 Great!! Assimilation started. Decorators look quite interesting: smellegantcode.wordpress.com/…/typescript-1-5-get-the-decorators-in "Let/const compiling to ES5" has major positive implications for how we code! Deserves its own section in the announcement, IMO. 🙂 Awesome stuff! I've been waiting for this release for years! Looks really good. Looking forward to Visual Studio integration. Regarding destructuring function parameters, is it possible to define the variable types? For example: function greetClient({name, height: howTall}) both 'name' and 'howTall' are any, presumably. I imagine you can do: function greetClient({name, height: howTall}: { name: string, howTall: number}) But can this be done more succinctly? Thanks. @Jamie – I believe the type talks about the original shape, rather than with the renames, but yeah. Something like: function greetClient({name, height: howTall }: { name: string, height: number }) { … } @Jamie Alternatively, there is alway the option of a separately defined interface: interface IPerson { name: string; height: number; } function greetClient({name, height: howTall }: IPerson) { … } This is going to be great. I think TypeScript has become the precursor of ES6/7/next. More compelling to adopt now with all these ES6/7 features! Can you tell anything about how this version will relate to the upcoming Visual Studio release? Will VS 2015 ship with TypeScript 1.5 or 1.4? Decorators/Attributes in JavaScript are going to open alot of doors. Looking forward to using them. Keep up the great work guys. 2+ years in with TypeScript and it gets better and better. I have managed to get the npm package into a VS 2013 (ASP.NET MVC project) using Package Intellisense tool. What do I need to do, so that this project now uses the 1.5 compiler? Looks great! I've been waiting for this. The one issue I'm having is using existing tsd files with es6 compilation. Any suggestion? @Ben Tesser what specific issues are you running into? can you log them in github.com/…/issues And what about yields? It wasn't easy for me to port them to my VS. Still waiting for official support 🙂 Btw, Great work 😉 @Fixer – we're currently thinking generators (yields and generator functions) will be part of 1.6. import … from xxx , I prefer %S:space[…] ,using“%” ,we see "space" first, abbr. as S, then import some marks "…" prefer "@" to "public" and "export" if fact , i think assign variables, function, class by same means, as : assign classA{} // this is class assign funA(){} // this is function assign varA // this is variable at last "assign" can be killed === there's another idea, why thread program is so ugly, can it be as follows? doA(); &! doC(); doB(); waitfor(doC); here, doC runs in background thanks! @hubee – the syntax we show comes from the ES6 module syntax that is part of the JavaScript standard. With TypeScript being a superset of JS, we follow its syntax. @hubee – better version: doA(); var c = doC(); doB(); await c; That's what TypeScript 1.6 is probably going to have (see prototypeAsync branch). On this page, something named Telligent_CallbackManager is presenting an alert every time the page is reloaded. The alert states "The target of the callback could not be found" This has been present for a couple of weeks now. I'm thinking about this language these days. Can it be more simple,simplely. 1, the constructed function can be replaced by"set(para1,para2){}" commonly. when we assign a new variable , varA:ClassA = (para1,para2),that's enough. 2, class convertor can be writed "get<class name>{}" if varB:classB, varA:classA, we type varB = varA,what's happened? which properties' value of varA are given to those of varB, refer to calssA's "get<classB>{}" function. 3, How about designning three logical operational values: True,False,NULL NULL stands for undefine or nothing, all operations with NULL return NULL, no error occurs. under the help of NULL, code can be writed arbitrarily.Therefor,Optional Properties may be useless. 4, Can interface be mergered into class? Even though class confines the variable,the variable can be adopted for special use. as below: triangleA:{lineA:num;lineB:num;lineC:num}; // assign class triangleA var varA:triangleA = {lineA:3,lineB:4,lineC:5}; //also varA:triangleA = (3,4,5) var varL:float; if(varA.lineA > 4) varL = varA.square(); // return NULL varA:{function square(){formular sentences}}; // add proterty function"square()" if(varA.lineA > 4) varL = varA.square(); // return 6 5, For for,while,foreach sentences ,can be write as one sentence: loop<>[](){} eg. loop<this,that,group[]>[index,it](index >10 || it.value < 0){dosome()} here,<this,that,group[]> constructs a list, waiting for being operated, the number's turn is "index","it" stands for the number, () contains condition whether if loop "it". for(int i = 0; i< 10; i++){} vs loop[int i,](i <10){} while(;){} vs loop(){} foreach(char ch in strings){if(ch>10)continue;else do()} vs loop<strings>[,ch](ch < 10){do()} — Think about the above. thanks! @hubee – for more in-depth syntax discussion, the best place is the TypeScript github site. That'll let us break down the idea and talk about it more easily: You can file feature requests here: github.com/…/issues Does it have support for Visual Studio Code?
https://blogs.msdn.microsoft.com/typescript/2015/03/27/announcing-typescript-1-5-alpha/
CC-MAIN-2017-30
refinedweb
1,636
66.64
MQ_UNLINK(3P) POSIX Programmer's Manual MQ_UNLINK(3P) This manual page is part of the POSIX Programmer's Manual. The Linux implementation of this interface may differ (consult the corresponding Linux manual page for details of Linux behavior), or the interface may not be implemented on Linux. mq_unlink — remove a message queue (REALTIME) #include <mqueue.h> int mq_unlink(const char *name); The). Upon successful completion, the function shall return a value of zero. Otherwise, the named message queue shall be unchanged by this function call, and the function shall return a value of −1 and set errno to indicate the error. The mq_unlink() function shall fail if: EACCES Permission is denied to unlink the named message queue. ENOENT The named message queue does not exist. The mq mq_unlink() with a name argument that contains the same message queue name as was previously used in a successful mq_open() call shall not give an [ENAMETOOLONG] error. The following sections are informative. None. None. None. A future version might require the mq_open() and mq_unlink() functions to have semantics similar to normal file system operations. mq_close(3p), mq_open(3p), msgctl(3p), msgget(3p), msgrcv(3p), msgsnd(3p) The Base Definitions volume of POSIX.1‐2008, mqueue_UNLINK(3P) Pages that refer to this page: mqueue.h(0p), mq_close(3p), mq_open(3p), msgctl(3p), msgget(3p), msgrcv(3p), msgsnd(3p)
http://man7.org/linux/man-pages/man3/mq_unlink.3p.html
CC-MAIN-2017-47
refinedweb
224
56.86
If you look at the EDM and in particular the metadata it considers important, one thing is clear: Persistence is the Priority. For example this: <Property Name=”Firstname” Type=”String” Nullable=”False”/> Tells us that the Firstname property can’t be null when persisted. If however the EDM Type System is used to describe the signature of a function, the Nullable constraint may or may not apply. You may be able to call the function with an Entity with its’ Firstname property set to NULL, or … maybe not. Essentially, in hindsight, it might have been better to have something like this instead: <Property Name=”Firstname” Type=”String” ssdl:Nullable=”False”/> Here the ssdl namespace qualifies the nullable constraint. The ssdl is simply shorthand for the storage model or context. The natural implication is that in order to persist the Entity to storage, the Firstname can’t be null. Which in turn further implies, a guarantee, that when materializing entities from storage, the Firstname will never be null. I wonder if when we look at evolving and growing the EDM, we should be thinking about other contexts too. Now we’ve taken the first step to supporting other contexts with Annotations, but I wonder if that is enough. This idea of context seems more fundamental to me. Its not necessarily (as I think we all thought) just about adding addition information / constraints / whatever, it may also involve, re-defining the same information for a different context. What do you think?
http://blogs.msdn.com/b/alexj/archive/2009/01/07/nullable-false-but-when-exactly.aspx
CC-MAIN-2014-10
refinedweb
249
52.9
Default values + Generics = Better together Default values would be nice... but I think it would be cool if we could have something nicer than what C++ has. Here's a snippet of how I imagine it.... public class Foo { public Foo(int x=1,int y=2,int z=4,Class c=T.class) { .. } public static void main(String[] args) { // this constructor... Foo f1 = new Foo(z=>2,y=>3); // does the same as this Foo f2 = new Foo(1,3,2,4,String.class); } }. We could get the type information into the class (if it wants it). If, for some reason, the compiler could not figure out the type to put in an expression it would put in a null. The great thing about this mechanism is that you would not need to use it in the constructor. Sure you could use it there so that you could remember your type info, but you could also use it as follows... import java.lang.reflect.Array; public class MyList { T[] data; public MyList(T[] data) { this.data = data; } // wish I could say here instead of ... X[] toArray(Class c=X.class) { X[] xa = (X[])Array.newInstance(c,data.length); for(int i=0;i m = new MyList(da); // the compiler fills in the Number.class default arg Number[] na = m.toArray(); } } The major use case for this is constructors. Here is a current technology solution that takes a bit of coding in the classdeclaration, but provides a pretty nice mechanism where you call the constructor. The idea extends from the StringBuffer idiom of methods return "this" so you can chain the method calls together. To make this work in a Constructor (& with final fields), you define a separate static inner class to contain the configuration, and pass one of these in to the constructor. You need a static method on the outer class to return a default configuration object. here is an example with 4 final fields. [code] public class SparseObj { final private int height, width; final private String name; final private Alignment alignment; private enum Alignment { left,right,centre } public SparseObj(Config c) { this.height = c.height; this.width = c.width; this.name = c.name; this.alignment = c.alignment; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append("SparseObj: size=").append(width).append(',').append(height); sb.append(", name='").append(name).append("', alignment=").append(alignment); return sb.toString(); } public static Config defaults() { return new Config(); } public static class Config { private int height=100, width=100; private String name=""; private Alignment alignment=Alignment.centre; private Config() {} public Config height(int h) { height = h; return this; } public Config width(int w) { this.width = w; return this; } public Config name(String n) { name = n; return this; } public Config left() { alignment = Alignment.left; return this; } public Config centre() { alignment = Alignment.centre; return this; } public Config right() { alignment = Alignment.right; return this; } } } class UseCase { public static void main(String[] args) { System.out.println( new SparseObj( SparseObj.defaults().height(200).left() ) ); System.out.println(new SparseObj(SparseObj.defaults())); System.out.println(new SparseObj( SparseObj.defaults().right().name("Bruce"))); System.out.println( new SparseObj( SparseObj.defaults().centre().name("Bruce").height(10).width(20) ) ); } } [/code]running this gives[code] U:\java>java -cp . UseCase SparseObj: size=100,200, name='', alignment=left SparseObj: size=100,100, name='', alignment=centre SparseObj: size=100,100, name='Bruce', alignment=right SparseObj: size=20,10, name='Bruce', alignment=centre [/code]Its quite a lot of work, but potentially worthwhile when there are lots of final fields that all need to be set, but many have commonly acceptable default values, and where the overhead of writing the class is justified because there are many points in the code where the constructor is called. If you want to write even more code in the declaration, and simplify the constructor calls even further, you add a static method on the outer for each final field, and return a Config, like this one (all the others follow the same pattern).[code]public Config width(int w) { return new Config().width(w); }[/code] then the invocation can be written thus [code] new SparseObj(SparseObj.width(200).left());[/code]This gets pretty close to being as elegant as the call with the proposed new syntax.[code]new SparseObj(width:200,alignment:SparseObj.Alignment.left)[/code] and allows you to do things like hide the Alignment enum with individual methods as I have done (but didn't need to). That is a smart solution indeed. Though a bit too complicated for day-to-day use for smallish immutable objects (IMO). Default values, resolvable at compile time, would be a good simple solution, again IMO. Cheers, Mikael Certainly the benefits seems to go up exponentially with the number of fields, but also the benefits come from being invoked from many different places. I am still processing this myself, I had roughed out the solution in the past, but never got around to implementing it. That code I posted above was the first time I had used it in anger (ahh - confession time). Thinking about this a little further, I am pretty sure I could generate the Config class with "apt", not as an inner class, but as one in the same package. All you would need to code would be[code] public class SparseObj { final private int height, width; final private String name; final private Alignment alignment; private enum Alignment { left,right,centre } public SparseObj(@GeneratedConfigurator SparseObjConfig c) { height = c.getHeight(); width = c.getWidth(); name = c.getName(); alignment = Alignment.valueOf(c.getAlignment()); } public String toString() { StringBuilder sb = new StringBuilder(); sb.append("SparseObj: size=").append(width).append(',').append(height); sb.append(", name='").append(name).append("', alignment=").append(alignment); return sb.toString(); } public static SparseObjConfig defaults() { return new SparseObjConfig(); } } [/code] and make sure you didn't declare the same Class name (in this case SparseObjConfig) as an argument with the annotation more than once per package. Now that's rockin' ( am I allowed to say that myself, or should I implement it first then let someone else say it :) ) This may not be as easy as it seems. For this feature to work, names of the parameters would need to be present in the bytecode otherwise compiler has nothing to validate your call against. (Imagine you have only compiled JAR). Furthermore, you have to specify how conflicts would be resolved. Consider this: [code] String name = "John"; String surname = "Doe"; call(name:name, surname:surname); [/code] This can be unambiguous because part before colon refers to parameter name and part after colon refers to local variable. But it seems confusing on the other hand, this can make code even more verbose, so let's be careful. It definitely increases clarity and understandability of the code, especially when constructing large immutable objects with huge amount of constructor arguments. As for syntax, I would also prefer ':' notation ('=' cannot be used due to conflict with assignment) call(name:"John", surname:"Doe"); Anyway, I would welcome this feature as an option, not requirement, but it is not on my hotlist :-) Basically, I think what you want is a support for named parameter similar to that available in Python (it also support default values). There are other languages (Smalltalk, Objective C) that support them, but I am not sure if they also support default values. Maybe the Java development team can look into these languages for inspiration. I also would like to see this in Java. It makes the code much more readable. map.put(key:"item", value:"radio"); //Personally, I prefer 'z:2' to 'z=>2'. This is much more understandable than the current Java equivalent. +100 (All of my family and friends concurr) ;) I must say this is the most creative and new(?) suggestion I've read for a very long time regarding language changes. I'm usually not that keen on language changes and I've always found default values in C++ to be a bit half baked. I hate chained constructors, yet they are necessary epsecially for immutable objects (which I like) since they tend to have quite a few arguments. I'd [b]really[/b] like Sun to take this up for further discussion. Cheers, Mikael Grev I think it would be preferable to resolve the default values at run time (when the classes are loaded) and not at compile time. Otherwise it is potentially very confusing if you have different classes compiled against different versions of the class declaring default versions. The existing inlining of constant strings and primitives declared in other classes is already annoying. It was an optimisation which no longer seems worthwhile.
https://www.java.net/node/643691
CC-MAIN-2014-15
refinedweb
1,432
55.34
Writing. Image Read Write Example using ImageIO Code Example Image Read and Write in Java In this code Exmaple of javax.imageio.ImageIO class we will see: How to read Buffered Image in Java from File or URL How to write JPG images to file in Java How to write PNG images to file in Java How to write BMP images to file in Java How to write GIF images to file in Java import javax.imageio.ImageIO; import java.io.File; import java.io.IOException; import java.awt.image.BufferedImage; public class ImageIOExample { public static void main( String[] args ){ BufferedImage image = null; try { //you can either use URL or File for reading image using ImageIO File imagefile = new File("C://Documents and Settings/Javin/My Documents/My Pictures/loan.PNG"); image = ImageIO.read(imagefile); //ImageIO Image write Example in Java ImageIO.write(image, "jpg",new File("C:\\home_loan.jpg")); ImageIO.write(image, "bmp",new File("C:\\credit_card_loan.bmp")); ImageIO.write(image, "gif",new File("C:\\personal_loan.gif")); ImageIO.write(image, "png",new File("C:\\auto_loan.png")); } catch (IOException e) { e.printStackTrace(); } System.out.println("Success"); } } Apart from seemless support of reading and writing images in Java, ImageIO class also contains lot of other utility methods for locating ImageReaders and ImageWriters and performing encoding and decoding. That's all on this Reading and Writing Image File in Java using javax.imageio.ImageIO. Let me know if you face any issue while trying these examples of ImageIO. Related Java Tutorials 6.
http://javarevisited.blogspot.com/2011/12/read-write-image-in-java-example.html?showComment=1361537316765
CC-MAIN-2013-48
refinedweb
250
51.14
0 Ok, this has got me banging my head against a wall. I have a structure defined in a header file. It get initialized in my "main.cpp" file, then later in a separate file "readconfig.cpp" it gets accessed to store information. I haven't been able to get it to compile except by using the following code, which segfaults. I was wondering if anyone here could assist me in this problem. Here is the revelant main.h code: #ifndef _MAIN_H #define _MAIN_H ... struct _aline { //Admin Line std::string provider; std::string serverdesc; std::string admin; }; ... #endif main.cpp: #include "main.h" int main() ... _aline *aline = new _aline; aline->provider = "HURR DURR"; ... and readconfig.cpp: bool ReadConfig() ... _aline *aline; cout<<"Aline: \n"; cout<<aline->provider<<"\n"; ... I've tried to get this code to compile, but so far this is the only way I can get it to. If I try to move the statement in readconfig.cpp to main.h I get linker errors like there's no tomorrow. Any help is greatly appreciated.
https://www.daniweb.com/programming/software-development/threads/298163/accessing-a-struct-across-multiple-files
CC-MAIN-2017-09
refinedweb
176
80.38
Base class for popup widgets. More... #include <Wt/WPopupWidget.h>. Before Wt 4, WPopupWidget had a setDeleteWhenHidden(bool) function, causing the WPopupWidget to be deleted when it's hidden. This function has been removed. To achieve the same effect, the following code can be used: Constructor. You need to pass in a widget that provides the main contents of the widget (e.g. a WTemplate or WContainerWidget). Unlike other widgets, a popup widget is a top-level widget that should not be added to another container. Returns the auto-hide delay. Signal emitted when the popup is hidden. This signal is emitted when the popup is being hidden because of a client-side event (not when setHidden() or hide() is called). (in ms). Signal emitted when the popup is shown. This signal is emitted when the popup is being shown because of a client-side event (not when setHidden() or show() is called).
https://webtoolkit.eu/wt/doc/reference/html/classWt_1_1WPopupWidget.html
CC-MAIN-2021-31
refinedweb
153
67.76
[PATCH v6 1/2] signal: add pidfd_send_signal() syscall From: Christian Brauner Date: Sat Dec 29 2018 - 17:29:07 EST ] The kill() syscall operates on process identifiers (pid). After a process has exited its pid can be reused by another process. If a caller sends a signal to a reused pid it will end up signaling the wrong process. This issue has often surfaced and there has been a push to address this problem [1]. This patch uses file descriptors (fd) from proc/<pid> as stable handles on struct pid. Even if a pid is recycled the handle will not change. The fd can be used to send signals to the process it refers to. Thus, the new syscall pidfd_send_signal() is introduced to solve this problem. Instead of pids it operates on process fds (pidfd). /* prototype and argument /* long pidfd_send_signal(int pidfd, int sig, siginfo_t *info, unsigned int flags); In addition to the pidfd and signal argument it takes an additional siginfo_t and flags argument. If the siginfo_t argument is NULL then pidfd_send_signal() is equivalent to kill(<positive-pid>, <signal>). If it is not NULL pidfd_send_signal() is equivalent to rt_sigqueueinfo(). The flags argument is added to allow for future extensions of this syscall. It currently needs to be passed as 0. Failing to do so will cause EINVAL. /* pidfd_send_signal() replaces multiple pid-based syscalls */ The pidfd_send_signal() syscall currently takes on the job of rt_sigqueueinfo(2) and parts of the functionality of kill(2), Namely, when a positive pid is passed to kill(2). It will however be possible to also replace tgkill(2) and rt_tgsigqueueinfo(2) if this syscall is extended. /* sending signals to threads (tid) and process groups (pgid) */ Specifically, the pidfd_send_signal() syscall does currently not operate on process groups or threads. This is left for future extensions. In order to extend the syscall to allow sending signal to threads and process groups appropriately named flags (e.g. PIDFD_TYPE_PGID, and PIDFD_TYPE_TID) should be added. This implies that the flags argument will determine what is signaled and not the file descriptor itself. Put in other words, grouping in this api is a property of the flags argument not a property of the file descriptor (cf. [13]). Clarification for this has been requested by Eric (cf. [19]). When appropriate extensions through the flags argument are added then pidfd_send_signal() can additionally replace the part of kill(2) which operates on process groups as well as the tgkill(2) and rt_tgsigqueueinfo(2) syscalls. How such an extension could be implemented has been very roughly sketched in [14], [15], and [16]. However, this should not be taken as a commitment to a particular implementation. There might be better ways to do it. Right now this is intentionally left out to keep this patchset as simple as possible (cf. [4]). For example, if a pidfd for a tid from /proc/<pid>/task/<tid> is passed EOPNOTSUPP will be returned to give userspace a way to detect when I add support for signaling to threads (cf. [10]). /* naming */ The syscall had various names throughout iterations of this patchset: - procfd_signal() - procfd_send_signal() - taskfd_send_signal() In the last round of reviews it was pointed out that given that if the flags argument decides the scope of the signal instead of different types of fds it might make sense to either settle for "procfd_" or "pidfd_" as prefix. The community was willing to accept either (cf. [17] and [18]). Given that one developer expressed strong preference for the "pidfd_" prefix (cf. [13] and with other developers less opinionated about the name we should settle for "pidfd_" to avoid further bikeshedding. The "_send_signal" suffix was chosen to reflect the fact that the syscall takes on the job of multiple syscalls. It is therefore intentional that the name is not reminiscent of neither kill(2) nor rt_sigqueueinfo(2). Not the fomer because it might imply that pidfd_send_signal() is a replacement for kill(2), and not the latter because it is a hassle to remember the correct spelling - especially for non-native speakers - and because it is not descriptive enough of what the syscall actually does. The name "pidfd_send_signal" makes it very clear that its job is to send signals. /* zombies */ Zombies can be signaled just as any other process. No special error will be reported since a zombie state is an unreliable state (cf. [3]). However, this can be added as an extension through the @flags argument if the need ever arises. /* cross-namespace signals */ The patch currently enforces that the signaler and signalee either are in the same pid namespace or that the signaler's pid namespace is an ancestor of the signalee's pid namespace. This is done for the sake of simplicity and because it is unclear to what values certain members of struct siginfo_t would need to be set to (cf. [5], [6]). /* compat syscalls */ It became clear that we would like to avoid adding compat syscalls (cf. [7]). The compat syscall handling is now done in kernel/signal.c itself by adding __copy_siginfo_from_user_generic() which lets us avoid compat syscalls (cf. [8]). It should be noted that the addition of __copy_siginfo_from_user_any() is caused by a bug in the original implementation of rt_sigqueueinfo(2) (cf. 12). With upcoming rework for syscall handling things might improve significantly (cf. [11]) and __copy_siginfo_from_user_any() will not gain any additional callers. /* testing */ This patch was tested on x64 and x86. /* userspace usage */ An asciinema recording for the basic functionality can be found under [9]. With this patch a process can be killed via: #define _GNU_SOURCE #include <errno.h> #include <fcntl.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/syscall.h> #include <sys/types.h> #include <unistd.h> static inline int do_pidfd_send_signal(int pidfd, int sig, siginfo_t *info, unsigned int flags) { #ifdef __NR_pidfd_send_signal return syscall(__NR_pidfd_send_signal, pidfd, sig, info, flags); #else return -ENOSYS; #endif } int main(int argc, char *argv[]) { int fd, ret, saved_errno, sig; if (argc < 3) exit(EXIT_FAILURE); fd = open(argv[1], O_DIRECTORY | O_CLOEXEC); if (fd < 0) { printf("%s - Failed to open \"%s\"\n", strerror(errno), argv[1]); exit(EXIT_FAILURE); } sig = atoi(argv[2]); printf("Sending signal %d to process %s\n", sig, argv[1]); ret = do_pidfd_send_signal(fd, sig, NULL, 0); saved_errno = errno; close(fd); errno = saved_errno; if (ret < 0) { printf("%s - Failed to send signal %d to process %s\n", strerror(errno), sig, argv[1]); exit(EXIT_FAILURE); } exit(EXIT_SUCCESS); } /* Q&A * Given that it seems the same questions get asked again by people who are * late to the party it makes sense to add a Q&A section to the commit * message so it's hopefully easier to avoid duplicate threads. * * For the sake of progress please consider these arguments settled unless * there is a new point that desperately needs to be addressed. Please make * sure to check the links to the threads in this commit message whether * this has not already been covered. */ Q-01: (Florian Weimer [20], Andrew Morton [21]) What happens when the target process has exited? A-01: Sending the signal will fail with ESRCH (cf. [22]). Q-02: (Andrew Morton [21]) Is the task_struct pinned by the fd? A-02: No. A reference to struct pid is kept. struct pid - as far as I understand - was created exactly for the reason to not require to pin struct task_struct (cf. [22]). Q-03: (Andrew Morton [21]) Does the entire procfs directory remain visible? Just one entry within it? A-03: The same thing that happens right now when you hold a file descriptor to /proc/<pid> open (cf. [22]). Q-04: (Andrew Morton [21]) Does the pid remain reserved? A-04: No. This patchset guarantees a stable handle not that pids are not recycled (cf. [22]). Q-05: (Andrew Morton [21]) Do attempts to signal that fd return errors? A-05: See {Q,A}-01. Q-06: (Andrew Morton [22]) Is there a cleaner way of obtaining the fd? Another syscall perhaps. A-06: Userspace can already trivially retrieve file descriptors from procfs so this is something that we will need to support anyway. Hence, there's no immediate need to add another syscalls just to make pidfd_send_signal() not dependent on the presence of procfs. However, adding a syscalls to get such file descriptors is planned for a future patchset (cf. [22]). Q-07: (Andrew Morton [21] and others) This fd-for-a-process sounds like a handy thing and people may well think up other uses for it in the future, probably unrelated to signals. Are the code and the interface designed to permit such future applications? A-07: Yes (cf. [22]). Q-08: (Andrew Morton [21] and others) Now I think about it, why a new syscall? This thing is looking rather like an ioctl? A-08: This has been extensively discussed. It was agreed that a syscall is preferred for a variety or reasons. Here are just a few taken from prior threads. Syscalls are safer than ioctl()s especially when signaling to fds. Processes are a core kernel concept so a syscall seems more appropriate. The layout of the syscall with its four arguments would require the addition of a custom struct for the ioctl() thereby causing at least the same amount or even more complexity for userspace than a simple syscall. The new syscall will replace multiple other pid-based syscalls (see description above). The file-descriptors-for-processes concept introduced with this syscall will be extended with other syscalls in the future. See also [22], [23] and various other threads already linked in here. Q-09: (Florian Weimer [24]) What happens if you use the new interface with an O_PATH descriptor? A-09: pidfds opened as O_PATH fds cannot be used to send signals to a process (cf. [2]). Signaling processes through pidfds is the equivalent of writing to a file. Thus, this is not an operation that operates "purely at the file descriptor level" as required by the open(2) manpage. See also [4]. /* References */ [1]: [2]: [3]: [4]: [5]: [6]: [7]: [8]: [9]: [10]: [11]: [12]: [13]: [14]: [15]: [16]: [17]: [18]: [19]: [20]: [21]: [22]: [23]: [24]: Cc: "Eric W. Biederman" <ebiederm@xxxxxxxxxxxx> Cc: Jann Horn <jannh@xxxxxxxxxx> Cc: Andy Lutomirsky <luto@xxxxxxxxxx> Cc: Andrew Morton <akpm@xxxxxxxxxxxxxxxxxxxx> Cc: Oleg Nesterov <oleg@xxxxxxxxxx> Cc: Al Viro <viro@xxxxxxxxxxxxxxxxxx> Cc: Florian Weimer <fweimer@xxxxxxxxxx> Signed-off-by: Christian Brauner <christian@xxxxxxxxxx> Reviewed-by: Kees Cook <keescook@xxxxxxxxxxxx> Acked-by: Arnd Bergmann <arnd@xxxxxxxx> Acked-by: Serge Hallyn <serge@xxxxxxxxxx> Acked-by: Aleksa Sarai <cyphar@xxxxxxxxxx> --- /* Changelog */ v6: - Given that it seems the same questions get asked multiple times it made sense to add a Q&A section to the commit message so it's hopefully easier to avoid duplicate threads. - Since we settled on adding flags when extending the syscalls to allow signaling to threads and process groups it doesn't make sense anymore to report EOPNOTSUPP when a file descriptor to /proc/<pid>/task/<tid> is passed. This means we can also remove the tgid_pidfd_to_pid() helper from proc_fs.h and simplify the code. We will now always return EBADF when a file descriptor is passed that does not refer to /proc/<pid>. - add CONFIG_PROC_FS ifdefs for pidfd_send_signal() and add COND_SYSCALL(pidfd_send_signal) definition as suggested by Andrew Morgan in [changelog-1]. v5: - s/may_signal_taskfd/access_taskfd_pidns/g - make it clear that process grouping is a property of the @flags argument Eric has argued that he would like to know when we add thread and process group signal support whether grouping will be a property of the file descriptor or the flag argument and he would oppose this until a commitment has been made. It seems that the cleanest strategy is to make grouping a property of the @flags argument. He also argued that in this case the prefix of the syscall should be "pidfd_" (cf. ). - use "pidfd_" as prefix for the syscall since grouping will be a property of the @flags argument - substantial rewrite of the commit message to reflect the discussion v4: - updated asciinema to use "taskfd_" prefix - s/procfd_send_signal/taskfd_send_signal/g - s/proc_is_tgid_procfd/tgid_taskfd_to_pid/b - s/proc_is_tid_procfd/tid_taskfd_to_pid/b - s/__copy_siginfo_from_user_generic/__copy_siginfo_from_user_any/g - make it clear that __copy_siginfo_from_user_any() is a workaround caused by a bug in the original implementation of rt_sigqueueinfo() - when spoofing signals turn them into regular kill signals if si_code is set to SI_USER - make proc_is_t{g}id_procfd() return struct pid to allow proc_pid() to stay private to fs/proc/ v3: - add __copy_siginfo_from_user_generic() to avoid adding compat syscalls - s/procfd_signal/procfd_send_signal/g - change type of flags argument from int to unsigned int - add comment about what happens to zombies - add proc_is_tid_procfd() - return EOPNOTSUPP when /proc/<pid>/task/<tid> fd is passed so userspace has a way of knowing that tidfds are not supported currently. v2: - define __NR_procfd_signal in unistd.h - wire up compat syscall - s/proc_is_procfd/proc_is_tgid_procfd/g - provide stubs when CONFIG_PROC_FS=n - move proc_pid() to linux/proc_fs.h header - use proc_pid() to grab struct pid from /proc/<pid> fd v1: - patch introduced /* Changelog references */ [changelog-1]: --- arch/x86/entry/syscalls/syscall_32.tbl | 1 + arch/x86/entry/syscalls/syscall_64.tbl | 1 + fs/proc/base.c | 9 ++ include/linux/proc_fs.h | 6 ++ include/linux/syscalls.h | 3 + include/uapi/asm-generic/unistd.h | 4 +- kernel/signal.c | 133 +++++++++++++++++++++++-- kernel/sys_ni.c | 1 + 8 files changed, 151 insertions(+), 7 deletions(-) diff --git a/arch/x86/entry/syscalls/syscall_32.tbl b/arch/x86/entry/syscalls/syscall_32.tbl index 3cf7b533b3d1..6804c1e84b36 100644 --- a/arch/x86/entry/syscalls/syscall_32.tbl +++ b/arch/x86/entry/syscalls/syscall_32.tbl @@ -398,3 +398,4 @@ 384 i386 arch_prctl sys_arch_prctl __ia32_compat_sys_arch_prctl 385 i386 io_pgetevents sys_io_pgetevents __ia32_compat_sys_io_pgetevents 386 i386 rseq sys_rseq __ia32_sys_rseq +387 i386 pidfd_send_signal sys_pidfd_send_signal __ia32_sys_pidfd_send_signal diff --git a/arch/x86/entry/syscalls/syscall_64.tbl b/arch/x86/entry/syscalls/syscall_64.tbl index f0b1709a5ffb..aa4b858fa0f1 100644 --- a/arch/x86/entry/syscalls/syscall_64.tbl +++ b/arch/x86/entry/syscalls/syscall_64.tbl @@ -343,6 +343,7 @@ 332 common statx __x64_sys_statx 333 common io_pgetevents __x64_sys_io_pgetevents 334 common rseq __x64_sys_rseq +335 common pidfd_send_signal __x64_sys_pidfd_send_signal # # x32-specific system call numbers start at 512 to avoid cache impact diff --git a/fs/proc/base.c b/fs/proc/base.c index ce3465479447..9b812b777faa 100644 --- a/fs/proc/base.c +++ b/fs/proc/base.c @@ -3038,6 +3038,15 @@ static const struct file_operations proc_tgid_base_operations = { .llseek = generic_file_llseek, }; +struct pid *tgid_pidfd_to_pid(const struct file *file) +{ + if (!d_is_dir(file->f_path.dentry) || + (file->f_op != &proc_tgid_base_operations)) + return ERR_PTR(-EBADF); + + return proc_pid(file_inode(file)); +} + static struct dentry *proc_tgid_base_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags) { return proc_pident_lookup(dir, dentry, diff --git a/include/linux/proc_fs.h b/include/linux/proc_fs.h index d0e1f1522a78..52a283ba0465 100644 --- a/include/linux/proc_fs.h +++ b/include/linux/proc_fs.h @@ -73,6 +73,7 @@ struct proc_dir_entry *proc_create_net_single_write(const char *name, umode_t mo int (*show)(struct seq_file *, void *), proc_write_t write, void *data); +extern struct pid *tgid_pidfd_to_pid(const struct file *file); #else /* CONFIG_PROC_FS */ @@ -114,6 +115,11 @@ static inline int remove_proc_subtree(const char *name, struct proc_dir_entry *p #define proc_create_net(name, mode, parent, state_size, ops) ({NULL;}) #define proc_create_net_single(name, mode, parent, show, data) ({NULL;}) +static inline struct pid *tgid_pidfd_to_pid(const struct file *file) +{ + return ERR_PTR(-EBADF); +} + #endif /* CONFIG_PROC_FS */ struct net; diff --git a/include/linux/syscalls.h b/include/linux/syscalls.h index 2ac3d13a915b..fd85b9045a9f 100644 --- a/include/linux/syscalls.h +++ b/include/linux/syscalls.h @@ -907,6 +907,9 @@); +asmlinkage long sys_pidfd_send_signal(int pidfd, int sig, + siginfo_t __user *info, + unsigned int flags); /* * Architecture-specific system calls diff --git a/include/uapi/asm-generic/unistd.h b/include/uapi/asm-generic/unistd.h index d90127298f12..b77538af7aca 100644 --- a/include/uapi/asm-generic/unistd.h +++ b/include/uapi/asm-generic/unistd.h @@ -740,9 +740,11 @@ __SC_COMP(__NR_io_pgetevents, sys_io_pgetevents, compat_sys_io_pgetevents) __SYSCALL(__NR_rseq, sys_rseq) #define __NR_kexec_file_load 294 __SYSCALL(__NR_kexec_file_load, sys_kexec_file_load) +#define __NR_pidfd_send_signal 295 +__SYSCALL(__NR_pidfd_send_signal, sys_pidfd_send_signal) #undef __NR_syscalls -#define __NR_syscalls 295 +#define __NR_syscalls 296 /* * 32 bit systems traditionally used different diff --git a/kernel/signal.c b/kernel/signal.c index 9a32bc2088c9..a108368905c7 100644 --- a/kernel/signal.c +++ b/kernel/signal.c @@ -19,7 +19,9 @@ #include <linux/sched/task.h> #include <linux/sched/task_stack.h> #include <linux/sched/cputime.h> +#include <linux/file.h> #include <linux/fs.h> +#include <linux/proc_fs.h> #include <linux/tty.h> #include <linux/binfmts.h> #include <linux/coredump.h> @@ -3286,6 +3288,16 @@ COMPAT_SYSCALL_DEFINE4(rt_sigtimedwait, compat_sigset_t __user *, uthese, } #endif +static inline void prepare_kill_siginfo()); +} + /** * sys_kill - send a signal to a process * @pid: the PID of the process @@ -3295,16 +3307,125 @@ SYSCALL_DEFINE2(kill, pid_t, pid,()); + prepare_kill_siginfo(sig, &info); return kill_something_info(sig, &info, pid); } +#ifdef CONFIG_PROC_FS +/* + * Verify that the signaler and signalee either are in the same pid namespace + * or that the signaler's pid namespace is an ancestor of the signalee's pid + * namespace. + */ +static bool access_pidfd_pidns(struct pid *pid) +{ + struct pid_namespace *active = task_active_pid_ns(current); + struct pid_namespace *p = ns_of_pid(pid); + + for (;;) { + if (!p) + return false; + if (p == active) + break; + p = p->parent; + } + + return true; +} + +static int copy_siginfo_from_user_any(kernel_siginfo_t *kinfo, siginfo_t *info) +{ +#ifdef CONFIG_COMPAT + /* + * Avoid hooking up compat syscalls and instead handle necessary + * conversions here. Note, this is a stop-gap measure and should not be + * considered a generic solution. + */ + if (in_compat_syscall()) + return copy_siginfo_from_user32( + kinfo, (struct compat_siginfo __user *)info); +#endif + return copy_siginfo_from_user(kinfo, info); +} + +/** + * sys_pidfd_send_signal - send a signal to a process through a task file + * descriptor + * @pidfd: the file descriptor of the process + * @sig: signal to be sent + * @info: the signal info + * @flags: future flags to be passed + * + * The syscall currently only signals via PIDTYPE_PID which covers + * kill(<positive-pid>, <signal>. It does not signal threads or process + * groups. + * In order to extend the syscall to threads and process groups the @flags + * argument should be used. In essence, the @flags argument will determine + * what is signaled and not the file descriptor itself. Put in other words, + * grouping is a property of the flags argument not a property of the file + * descriptor. + * + * Return: 0 on success, negative errno on failure + */ +SYSCALL_DEFINE4(pidfd_send_signal, int, pidfd, int, sig, + siginfo_t __user *, info, unsigned int, flags) +{ + int ret; + struct fd f; + struct pid *pid; + kernel_siginfo_t kinfo; + + /* Enforce flags be set to 0 until we add an extension. */ + if (flags) + return -EINVAL; + + f = fdget_raw(pidfd); + if (!f.file) + return -EBADF; + + /* Is this a pidfd? */ + pid = tgid_pidfd_to_pid(f.file); + if (IS_ERR(pid)) { + ret = PTR_ERR(pid); + goto err; + } + + ret = -EINVAL; + if (!access_pidfd_pidns(pid)) + goto err; + + if (info) { + ret = copy_siginfo_from_user_any(&kinfo, info); + if (unlikely(ret)) + goto err; + + ret = -EINVAL; + if (unlikely(sig != kinfo.si_signo)) + goto err; + +); + } + } else { + prepare_kill_siginfo(sig, &kinfo); + } + + ret = kill_pid_info(sig, &kinfo, pid); + +err: + fdput(f); + return ret; +} +#endif /* CONFIG_PROC_FS */ + static int do_send_specific(pid_t tgid, pid_t pid, int sig, struct kernel_siginfo *info) { diff --git a/kernel/sys_ni.c b/kernel/sys_ni.c index df556175be50..e0af0a166bac 100644 --- a/kernel/sys_ni.c +++ b/kernel/sys_ni.c @@ -163,6 +163,7 @@ COND_SYSCALL(syslog); /* kernel/sched/core.c */ /* kernel/signal.c */ +COND_SYSCALL(pidfd_send_signal); /* kernel/sys.c */ COND_SYSCALL(setregid); -- 2.19.1 ]
https://lkml.iu.edu/hypermail/linux/kernel/1812.3/02090.html
CC-MAIN-2022-21
refinedweb
3,136
55.84
DOM::HTMLTableSectionElement #include <html_table.h> Detailed Description The THEAD , TFOOT , and TBODY elements. Definition at line 906 of file html_table.h. Member Function Documentation Horizontal alignment of data in cells. See the align attribute for HTMLTheadElement for details. Definition at line 972 of file html_table.cpp. Alignment character for cells in a column. See the char attribute definition in HTML 4.0. Definition at line 987 of file html_table.cpp. Offset of alignment character. See the charoff attribute definition in HTML 4.0. Definition at line 1002 of file html_table.cpp. Delete a row from this section. - Parameters - Definition at line 1053 of file html_table.cpp. Insert a row into this section. The new row is inserted immediately before the current indexth row in this section. If index is -1 or equal to the number of rows in this sectino, the new row is appended. - Parameters - - Returns - The newly created row. Definition at line 1040 of file html_table.cpp. The collection of rows in this table section. Definition at line 1032 of file html_table.cpp. see align Definition at line 980 of file html_table.cpp. see ch Definition at line 995 of file html_table.cpp. see chOff Definition at line 1010 of file html_table.cpp. see vAlign Definition at line 1025 of file html_table.cpp. Vertical alignment of data in cells. See the valign attribute for HTMLTheadElement for details. Definition at line 1017 of file html_table.
https://api.kde.org/frameworks/khtml/html/classDOM_1_1HTMLTableSectionElement.html
CC-MAIN-2021-17
refinedweb
236
63.46
Fourmilab, where atom-smashing geeks dwell, has a cute toy in the basement. It generates true random numbers based on radioactive decay, and makes data available to the public. They have a Java package to programmatically access it, but I wanted to do it in Perl. So I wrote a simple Perl module to access the server. I don't know how useful this is for most folks, but hey, it's cool! —John (code follows) use strict; use warnings; use HotBits; my $x= new HotBits::; my $bits= $x->request (16); # parameter is bytes to fetch, up to 2048 +. print length($bits)," bytes: "; print unpack("H*", $bits), "\n"; [download] =head1 NAME B<HotBits> - download hardware random numbers =head1 AUTHOR John M. Dlugosz - john@dlugosz.com - +.com =head1 DESCRIPTION This module will access "genuine" random numbers via +lab.ch/hotbits/. This server at Fourmilab in Switzerland uses radioactive decay to offe +r the truest random number source possible. This module works the same as the site's Java + class for the same purpose: access the CGI program via HTTP. =cut package HotBits; use strict; use warnings; our $VERSION= v1.0; require LWP::UserAgent; use Carp; my $serverURL=''; sub new { my $class= shift; my $URL= shift || $serverURL; # optional argument my $ua = new LWP::UserAgent::; $ua->env_proxy(); my $self= bless { ua => $ua, URL => $URL }, $class; return $self; } sub request { my ($self, $count)= @_; $count ||= 128; my $request = HTTP::Request->new('GET', "$self->{URL}?nbytes=$count&f +mt=bin"); $request->proxy_authorization_basic($ENV{HTTP_proxy_user}, $ENV{HTTP_ +proxy_pass}) if $ENV{HTTP_proxy_user}; my $response = $self->{ua}->request($request); croak "Error from $self->{URL}", if ($response->code() != 200); croak "Unexpected return (not binary) from $self->{URL}" if $response +->headers()->content_type() ne "application/octet-stream"; return $response->content(); } 1; # module loaded OK. [download] This wins points in my book for one of the coolest applications of lava lamp technology. Update: They're defunct. Poo. If I were to build something, I think a radio tuned to no station, patched to the mic input on a sound card would be a good and cheap chaos sampler. How does the random number generator in Perl's rand work? It seems pretty good, and I remember years ago reading that they no longer use the C library's generator. —John Better pseudo-random number generator(). ~monk d4vis #!/usr/bin/fnord Also check out.
http://www.perlmonks.org/index.pl?node=Genuine%20Quantum%20Randomness
CC-MAIN-2015-18
refinedweb
391
54.73
Design Patterns in the Test of Time: Composite. public interface IVotingUnit { int Weight { get;set; } int CandidateId { get;set; } } public class Voter : IVotingUnit { [Obsolete("Racist")] string Id { get;set; } int Weight { get;set; } int CandidateId { get;set; } } public class WinnerTakesAllState : IVotingUnit { string StateCode { get;set; } int Weight { get;set; } int CandidateId { get;set; } public void AddVote(Voter vote){ // calculate } }. (Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.) Sebastian Mueller replied on Tue, 2012/11/20 - 3:23am Your example is probably the worst example one could give for the composite pattern. Please take the time and read more on the subject before posting. Did you actually read the wikipedia link you were posting? Don't give recommendations about using or not using the pattern unless you understand that pattern - and obviously you do not, since you seem to never have (knowingly) implemented that pattern yourself. Sorry for sounding harsh, but this "article" does way more harm than good. For those who don't know about the pattern you provide misleading advice and for those who know the pattern it's just garbage... Lund Wolfe replied on Thu, 2012/11/22 - 6:30pm You do need to use your judgement to determine when a design pattern fits your situation, and you need to have a good grasp of OO and some experience before you can appreciate the patterns.
http://java.dzone.com/articles/design-patterns-test-time-2
CC-MAIN-2014-35
refinedweb
241
57.4
RPi.GPIO – port function checker A few weeks ago I blogged about RPi.GPIO updates for the model B and updated my RPi.GPIO documentation and quick reference sheets. But there was one feature I held back on because I needed a bit more time to mess about with it. (And then got busy with other things.) So What Was It? gpio_function() Another RPi.GPIO feature that sneaked in while I wasn’t looking is gpio_function() This is a feature that’s been inserted in RPi.GPIO to enable you to query the setup status of a port to see how it’s configured. import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) port = 25 usage = GPIO.gpio_function(port) print usage The above code gives you the setup status of port 25 (or whatever port/pin you choose). The result will be a numerical return code, which will have one of the following values… 0 = GPIO.OUT 1 = GPIO.IN 40 = GPIO.SERIAL 41 = GPIO.SPI 42 = GPIO.I2C 43 = GPIO.HARD_PWM -1 = GPIO.UNKNOWN Why Is That Useful? So you’ll then be able to determine the setup status of a port from within a script. I’ve written a little Python script (for B+, but could be modified for other Pis) to query the status of all the ports, then translate the numerical return codes into something a little more ‘human readable’. It uses a simple dictionary, which is a really useful feature of Python (Line 20). #!/usr/bin/env python2.7 # demo of "gpio_function()" port test # script by Alex Eames import RPi.GPIO as GPIO # Offer the user a choice of Pin or Port numbers and set numbering scheme accordingly choice = raw_input("Type 1 for Pin numbers, anything else for BCM port numbers:\n") if choice == "1": GPIO.setmode(GPIO.BOARD) ports = [3,5,7,8,10,11,12,13,15,16,18,19,21,22,23,24,26,29,31,32,33,35,36,37,38,40] pin_type = "Pin" else: GPIO.setmode(GPIO.BCM) ports = [2,3,4,17,27,22,10,9,11,5,6,13,19,26,14,15,18,23,24,25,8,7,12,16,20,21] pin_type = "Port" print "%s mode selected..." % pin_type # Using a dictionary as a lookup table to give a name to gpio_function() return code port_use = {0:"GPIO.OUT", 1:"GPIO.IN",40:"GPIO.SERIAL",41:"GPIO.SPI",42:"GPIO.I2C", 43:"GPIO.HARD_PWM", -1:"GPIO.UNKNOWN"} # loop through the list of ports/pins querying and displaying the status of each for port in ports: usage = GPIO.gpio_function(port) print "%s %d status: %s" % (pin_type, port, port_use[usage]) What Does The Output Look Like? The script shows what each of the ports/pins is set up to do. The screen-shots show what the output looks like in each mode. I have spi and i2c enabled, Serial is enabled by default and all other ports are set up as inputs by default. It’s probably something you won’t use every day, but if you don’t know it exists, you can’t use it can you? Have fun. Click here to see the full index of my RPi.GPIO tutorials. Challenge For an ‘extra credit’ challenge, you could modify the above script to check what revision of Pi it’s running on and choose which ports/pins to test accordingly. RasPiO® GPIO Reference Aids Our sister site RasPiO has three really useful reference products for Raspberry Pi GPIO work... Any reason for the seemingly-random ordering of your BCM ports list? ;) Ooh. I’m surprised you haven’t worked that one out Andrew. :eek: (Or maybe you did but were hinting that an explanation might be a good idea?) Unless I’ve made a mistake, they should be in the order of “left column top to bottom, then right column top to bottom” i.e. according to the physical layout on the B+. Ah, so they are! ;-) I’d just assumed that you’d put them in the same order as BOARD numbers, so was surprised when you didn’t. (GPIO.I2C being the first two values in both output images is what caught me out) Alex How did you know about this function, is there an official list somewhere that tells you of any new functions etc. when there is an update. regards Derek I found it in the RPi.GPIO documentation over at sourceforge. But I had to check some stuff with Ben Croston before I understood it properly. I noticed it in the release notes. Hi.. It will be interesting to modify your code to show PIN Status with HIGH, LOW, Error? etc… Can you pls include that change as well so everything is there to see. The copy code to clipboard function doesnt work? Does for me. But you could also try “View Plain” and then copy it with your mouse. I keep getting the following when trying the above code in the python 2.7 shell Traceback (most recent call last): File “/home/pi/port test.py”, line 26, in usage = GPIO.gpio_function(port) RuntimeError: No access to /dev/mem. Try running as root! I have updated and upgraded using the ‘sudo apt-get’ routine but no difference! are you running the code with sudo python filename.py?
https://raspi.tv/2014/rpi-gpio-port-function-checker?replytocom=44740
CC-MAIN-2019-18
refinedweb
886
76.11
I’m trying to figure out how multiple shape keys can be created preferably by using bmesh, while also generating geometry by creating vertices. My goal is to have 10 shape keys and each generated vertex is controlled by just one of the shape keys, essentially assigning each vertex into one of the shape keys, depending on the index of the said vertex. This was my simplified attempt: import bpy import bmesh # Create mesh. me = bpy.data.meshes.new('TestMesh') # Create object. ob = bpy.data.objects.new('TestObject',me) # Bmesh. bm = bmesh.new() # Add default shape key. ob.shape_key_add('Basis') # List of shape keys to loop through after creation. ShapeKeys = [] # Base name for shape keys. KeyBaseStr = 'Shape' # Create 20 vertices. for iVert in range(1,21): # Index of shape key to add the vertex to. iGroup = (iVert-1) % 10 # Check if group shape key has already been created. if len(ShapeKeys) < (iGroup + 1): # Name of new shape key. SetName = KeyBaseStr + '_Set_' + str(iVert) # Create shape key and append to list. ShapeKeys.append(bm.verts.layers.shape.new(SetName)) # Shorthand for new key. sk = ShapeKeys[-1] print('created shape key #',len(ShapeKeys)) else: # Select existing shape key. sk = ShapeKeys[iGroup] print('using existing shape key #',iGroup+1) # Add vertex. bv = bm.verts.new(tuple([iVert, 0, 1])) # Assign vertex coordinates in selected shape key. bv[sk] = tuple([0, iVert, 2]) # Bind bmesh to mesh. bm.to_mesh(me) # Link object to scene. scene = bpy.context.scene scene.objects.link(ob) # Set as active and selected. scene.objects.active = ob ob.select = True However, running the code results in an object with just one shape key rather than 10. All ten still appear to be created, but seem to not get binded to the mesh or the object. Any suggestions appreciated!
https://blenderartists.org/t/problem-adding-multiple-shape-keys-with-bmesh/1122506
CC-MAIN-2020-24
refinedweb
298
68.87
gather¶ - paddle. gather ( x, index, axis=None, name=None ) [source] Output is obtained by gathering entries of axisof xindexed by indexand concatenate them together. Given: x = [[1, 2], [3, 4], [5, 6]] index = [1, 2] axis=[0] Then: out = [[3, 4], [5, 6]] - Parameters x (Tensor) – The source input tensor with rank>=1. Supported data type is int32, int64, float32, float64 and uint8 (only for CPU), float16 (only for GPU). index (Tensor) – The index input tensor with rank=1. Data type is int32 or int64. axis (Tensor|int, optional) – The axis of input to be gathered, it’s can be int or a Tensor with data type is int32 or int64. The default value is None, if None, the axisis 0. name (str, optional) – The default value is None. Normally there is no need for user to set this property. For more information, please refer to Name . - Returns The output is a tensor with the same rank as x. - Return type output (Tensor) Examples import paddle input = paddle.to_tensor([[1,2],[3,4],[5,6]]) index = paddle.to_tensor([0,1]) output = paddle.gather(input, index, axis=0) # expected output: [[1,2],[3,4]]
https://www.paddlepaddle.org.cn/documentation/docs/en/api/paddle/gather_en.html
CC-MAIN-2022-05
refinedweb
193
60.01
The Problem So, I want to use Bokeh to display some data. I’ve had a look at it and it seems like it could be a very powerful (and beautiful) tool to get to grips with. Right now though, I just want to see something on screen. I’ve decided to be topical and have grabbed this Pokemon Go dataset from Kaggle. While we’re on it, take this opportunity to explore Kaggle if you haven’t recently. They’ve got a whole load of user submitted datasets these days and there’s a lot of fun (and learning) to be had. The Data There are a few variables included in the dataset, however I just want a minimum viable solution. Why don’t we use the name and max CP fields. If we create a bar chart we could see the strongest Pokemon at a glance. Since there’s 151 of the critters in the data, we probably just want the best of the best too: let’s say anything over 3000 CP. pandas I’m not going to talk a lot about pandas because I don’t know enough. I do know that it’s widely used, especially in the data science community, and it makes working with Bokeh charts easier. My understanding of a pandas dataframe is it is a tabular data structure. It also has manipulation functions (e.g. filter and grouping) that can make it behave much like a database. Why is this useful? Apart from the fact that Bokeh accepts it as data input (among others), we can use the filtering capabilities to apply our CP restriction and also using pandas can specify which columns we’re interested in: import pandas as pd data = pd.read_csv('pokemonGo.csv', header=0, usecols=['Name', 'Max CP']) data = data[data['Max CP'] > 3000] Also note the read_csv() function that automatically creates a dataframe from a csv file; fecking awesome! Bokeh Now that we have the data in the right format, we need to display it. Bokeh seems to have a lot of layers to it, to allow for customisation and building your own components but since this is our first foray into the library, we’ll use the high level bar chart builder to do most of the work for us: bar = Bar(data, label='Name', xlabel='Pokemon', values='Max CP', ylabel='Max CP', legend=None) output_file('bar.html') show(bar) Hopefully it’s pretty self explanatory. This is idiomatic Python we’re talking about! label will be our x axis and values is our y. You’ll notice I removed the legend. I think for a chart this straightforward, the legend will only get in the way of simplicity. That parameter is optional and if not specified the legend will show. Alternatively, you can specify its position e.g. legend='top_right'. Result So what does it give us? We get an html file that displays the chart. The chart comes with a few option buttons for navigation as well as one to export the chart as a picture, which I’ve included below: Mewtwo kicks ass, although I guess we already knew that. Pretty straightforward and under 10 lines of code. Bokeh and I are off to a good start.
http://sherlock.codes/2016/08/30/basic-data-visualisation-bokeh/
CC-MAIN-2018-13
refinedweb
545
72.26
J. Clifford Dyer wrote: > On Fri, Oct 26, 2007 at 06:59:51AM -0700, korovev76 at gmail.com wrote regarding Re: tuples within tuples: > >>> Resolve *what*? The problem isn't clear yet; at least to me. Above you >>> say what you get. What exactly do you want? Examples please. >>> >>> >> Sorry for my poor english, but I meant: how can I obtain a list of A >> and C starting from something like this? >> >> (A,B,C,D) >> that could be >> ('tagA', None, [('tagB', None, ['bobloblaw], None)], None) >> but also >> ('tagA', None, description, None) >> when I don't know if C is a tuple or not? >> >> I guess that, at least, within the cicle I may test if C is a tuple >> or not.. And then apply the same cicle for C... and so on >> >> Am i right? >> >> >> ciao >> korovev >> > > So, to clarify the piece that you still haven't explicitly said, you want to keep the tag name and children of every element in your XML document. (which is different from keeping (A, C) from tuple (A, B, C, D), because you want to modify C as well, and it's decendants.) > > As a first solution, how about: > > def reduceXML(node): > if type(node) == str: > return node > else: > return (node[0], reduceXML(node[2]) > > N.B. Beware of stack limitations. > > Also, as noted elsewhere in the string, your C is actually a list of Cs. So replace my else statement with return [(child[0], reduceXML(child[2])) for child in node] I think that'll do what you need. However, I'm not sure why you need to. You're not getting any new information out of your data structure. Why not just ignore the attributes and the spare tuplet (or whatever you call tuple-items) when you do the real processing next time through? Cheers, Cliff -------------- next part -------------- An HTML attachment was scrubbed... URL: <>
https://mail.python.org/pipermail/python-list/2007-October/440874.html
CC-MAIN-2014-15
refinedweb
314
82.04
NAME ng_tcpmss -- netgraph node to adjust TCP MSS option SYNOPSIS #include <netgraph.h> #include . NGM_TCPMSS_CONFIG (config) This control message configures node to do given MSS adjusting on a particular hook. It requires the struct ng_tcpmss_config to be supplied as an argument: struct ng_tcpmss_config { char inHook[NG_HOOKSIZ]; char outHook[NG_HOOKSIZ]; uint16_t maxMSS; } This means: packets received on inHook would be checked for TCP MSS option and the latter would be reduced down to maxMSS if it exceeds maxMSS. After that, packets would be sent to hook outHook. NGM_TCPMSS_GET_STATS (getstats) This control message obtains statistics for a given hook. The statistics are returned in struct ng_tcpmss_hookstat: struct ng_tcpmss_hookstat { uint64_t Octets; /* total bytes */ uint64_t Packets; /* total packets */ uint16_t maxMSS; /* maximum MSS */ uint64_t SYNPkts; /* TCP SYN packets */ uint64_t FixedPkts; /* changed packets */ }; NGM_TCPMSS_CLR_STATS (clrstats) This control message clears statistics for a given hook. NGM_TCPMSS_GETCLR_STATS (getclrstats) This control message obtains and clears statistics for a given hook. EXAMPLES In the following example, packets are injected into the tcpmss node using the ng_ipfw(4) node. # Create tcpmss node and connect it to ng_ipfw node ngctl mkpeer ipfw: tcpmss 100 qqq # The ng_tcpmss node type was implemented in FreeBSD 6.0. AUTHORS Alexey Popov <lollypop@flexuser.ru> Gleb Smirnoff <glebius@FreeBSD.org> BUGS When running on SMP, system statistics may be broken.
http://manpages.ubuntu.com/manpages/precise/man4/ng_tcpmss.4freebsd.html
CC-MAIN-2013-48
refinedweb
214
54.12
73533/write-expression-confirms-email-python-expression-module Hi, @Team, Please help needed! How to a write reg expression that confirms an email id using the python reg expression module “re”? Explain? Hey, @Roshni, Python has a regular expression module “re.” Check out the “re” expression that can check the email id for .com and .co.in subdomain. import re print(re.search(r"[0-9a-zA-Z.]+@[a-zA-Z]+\.(com|co\.in)$","micheal.pages@mp.com")) Here's the logic. You have to add ...READ MORE Here's the code: check = input("Enter the character: ...READ MORE Hi@akhtar, In Python, you can use the os. remove() method to remove ...READ MORE Here is an easy solution: def numberToBase(n, b): ...READ MORE You can also use the random library's ...READ MORE Syntax : list. count(value) Code: colors = ['red', 'green', ...READ MORE Enumerate() method adds a counter to an ...READ MORE You can simply the built-in function in ...READ MORE FWIW, the multiprocessing module has a nice interface for ...READ MORE Hey, Web scraping is a technique to automatically ...READ MORE OR At least 1 upper-case and 1 lower-case letter Minimum 8 characters and Maximum 50 characters Already have an account? Sign in.
https://www.edureka.co/community/73533/write-expression-confirms-email-python-expression-module?show=73534
CC-MAIN-2022-40
refinedweb
209
62.14
in Victoria How can we sing in a strange land... when the warmth of Christmas is not from some domestic fire in an iron grate, but from the sun high overhead - 38 degrees celsius and rising? Or when the Spring festival of new life called Easter 'down under', comes in Autumn, the season of little deaths when leaves turn gold, fall, and the grass has turned from green to brown? Shaping a distinctive Australian liturgical theology is a recurring problem for us in Australia and New Zealand. Because it is not as simple as it sounds. For nearly 10 years I lived in Canberra ACT, a cool to cold climate, where our national fore mothers and mothers were keen to replicate the English/European countryside.. Spring, for instance, is not the land celebrating life from a winter-induced death, but rather the beginning of an intensification of colour. Australian poet Les Murray writes: Cameo 3:1 it can often seem that the seasons comprise essentially summer and nonsummer. A reign of heat, flies, snakes, beach culture and burgeoning growth is followed by a cooler time in which the discomforts disappear 1 and both beach-going and burgeoning tail off. And there is that bit of sniffling cold in the middle" (Quoted in Ranson 1992). Then there are the wild cards of drought, bush fire, and flood, upheavals that can happen at any time affecting and altering any of the seasons (Ranson 1992). So as we begin our look at both Advent and Christmas I invite you to visit the displays of cards on the tables, select one which appeals to you, and then briefly share the story of why you selected that card, with another. oo0oo ADVENT The church season that comes before Christmas we call Advent. It starts again next Sunday. It needs all the encouragement it can get if it is to be ReBirthed, because of the many counter claims for attention operative in our community at this time. Indeed, our fellow traveller Peter Gomes didnt like Advent much, and was pretty grumpy about it. He says the conventional wisdom is: that Advent is the season of hope, and we light our Advent candles, one more on each Sunday, not simply anticipating the light but increasing it. [But Advent] has become a month-long dress rehearsal for Christmas and a commercial phenomenon that is beyond the power of mere Christmas to defeat (Gomes 2007:214). So what is the spirit of this season? Listening to the storyteller we call Mark, the season is inviting all of us to stay alert, keep awake!ears tuned, eyes openbut to what? To the presence of the sacred (or God) in the ordinary. Cameo: 3.2 Mark 13: 33-37 (Inclusive Text) Jesus said to the disciples: Be on your guard, stay awake, because you never know when the time will come. It is like someone traveling abroad, who has gone from home, and left servants in charge, all with their own task, and has told the doorkeeper to stay alert. So stay awake, because you do not know 2 when the owner of the house is coming, evening, midnight, cockcrow, dawn. If the owner comes unexpectedly, you must not be found asleep. What I say to you I say to all: Stay awake! Not looking for some so-called spectacular and mythical supernatural end times Or in some Frosty the Snowman pop song imagination. But by ReBirthing the Godgiven incognito moments, in the ordinary. In the ordinary... as in flowering Wattle or Jacaranda or Christmas Bush In the ordinary like the click clack of two eucalypt tree branches knocking together in the hot Summer wind In the ordinary... like rain, and the realisation it is not a singular thing but made up of billions of individual drops of water, each with its own destination and timing... In the ordinary like a young woman called Mary or a bloke called John. Cameo 3:3 Mark 1: 4-7 (Inclusive Text, adapted) And so it was that John the Dipper appeared in the wilderness, proclaiming a baptism of repentance for the forgiveness of sins. All Judaea and all the people of Jerusalem made their way to John, and as they were baptised by him in the river Jordan, they confessed their sins. John wore a garment of camel-skin, and lived on locusts and wild honey. In the course of preaching John said, 'Someone is following me, someone who is more powerful than I am, and I am not fit to kneel down and undo the strap of his sandals In the ordinary... like the lovemaking songs of the Green Grocer cicadas... In the ordinary... Otherwise we may miss what actually is. So in this coming Season of Advent I invite you to consider a couple of things: For inside each one of us is a marvelous creature with multi-coloured wings. Consider the option of becoming a person infected or inspired by hope. But not just an optimistic hope. The more rugged hopethat says even if things dont turn out all right and arent all right we endure through and beyond the times that disappoint or threaten to destroy us This kind of hope requires work, effort, and expenditure without the assurance of an easy or ready return (Gomes 2007:220). It is Creativity God who acts in us. And God in other people who receive our actions. Consider the invitation to re-tune your senses to a watchful presence of God in the ordinary, in the every day, in the outsider, in the new. Advent is a time to be surprised by the ordinary and empowered by the symbolic as we re-imagine the world. oo0oo CHRISTMAS The Christmas Australians celebrate today might seem like a timeless weaving of customs and feelings. Yet the familiar mix of cards, carols, parties, presents, tree and Santa that have come to define 25 December is little more than 130 years old. As a pre-Christian festival, its traditions go way back in time to changes in the seasons and the affects these changes had on people, their social life and work situations. As a Christian celebration, the Feast of the Nativity of our Lord didnt make the church calendar of feasts until sometime in the 4th century and then only as a result of a series of mixed motives, including the take-over of a number of rival so-called pagan festivals, political expediency, and the removal of thinking tagged heresy. In 1788 when the First Fleet arrived in Australia from England, Governor Arthur Phillip not only established a penal colonya gaol for the 736 convicts and to a certain extent, the marines and officers who accompanied themhe also won the land for protestant Christianity (Breward 1988:2). In reality, Christianity was in the main rejected by the convicts and only slightly embraced by the free settlers in latter years. Which has led some to conclude that in Australia, Christianity has always been rather a casual affair. At best, the nation was only ever superficially christianised (Wilson 1982:6). In early days of the colony Christmas held little importance. Unless Christmas Day fell on a Sunday, a holiday was not declared. The day was usually celebrated with a compulsory Anglican Church parade. If punishment had to be administered to a convict, perhaps a reduction in the sentence was ordered. Much later, when Christmas did begin to influence the social and religious life of the colony, in the latter part of the 1800s, it was mostly through secular nostalgia rather than religious leanings. Old customs and symbols were yearned for, and the arrival of food stuffs and other items were eagerly awaited as ships from England docked in December. These old traditions were never totally abandoned, but aspects of the festival were Australianised and became increasingly nationalistic. While American artist Thomas Nast introduced a winter Santa Claus to the world in the 1860s, some enterprising Australian artists a few years later attempted a rebirthing by giving him a cooler summer outfit, complete with kangaroo driven sleigh. oo0oo In popular belief it is said the foundational stories of Christmas can be found in the nativity stories by the anonymous storytellers we call Matthew and Luke, in the Bible. That is, early Christianities felt something novel had occurred with the birth of Jesus. So let me spend a brief moment on these stories. Both stories are very different from each other in general shape, atmosphere and content 5 Cameo 3:4 Luke 2:1-7 (Inclusive Text) Judea, to the town of David called Bethlehem, since he was of David's House and line, in order to be registered place for them at the inn Matthew 2:1-3 (Scholars Edition) Jesus was born at Bethlehem, in Judea, when Herod was king. Astrologers from the East showed up in Jerusalem just then. Tell us, they said, where the newborn king of the Judeans is. We have observed his star in the east and have come to pay him homage. When this news reached King Herod, he was visibly shaken, and all Jerusalem with him Both came rather later in the biblical traditionprobably anything from around 85 CE 125 CE. And in spite of the modern tendency to homogenise them into one classic tale, they are very different. As a former theological seminary professor of mine has written: ... Lukes account is full of strong, vibrant, bright colours with just a hint of umbers in the background. The other, Matthews account, is rich but sombre, darkly hued, and strangely shaded. Luke tells a cheerful tale, a buoyant, hopeful, joyous tale. Matthew tells a gothic tale, fascinating, disturbing, disquieting (Griffin 1982:55). Of these two stories (or fairytales as another calls them (Ranke-Heinemann 1994)), one, Lukes birth story of Yeshua bar Yosef has had an enormous influence on the Christian imagination. For many Christians Lukes story is the Christmas story, even though the birth itself is only briefly mentioned and is not really the focus of the story. The story brings together the imperial power of the divine saviour Augustus, lowly shepherds, and angels from heavenall around the birth of a baby in makeshift accommodation far from home. The humble physical setting and the supernatural splendour of a chorus of angels are strong storyteller clues as to how the storys listeners are to make sense of this story. Why these stories? Scholars suggest there are two possible ways of accounting for the creation of these stories. I will only mention one: the comparative study of Hellenistic biographies. To account for Jesus unusual life and noble death in terms that enhance his comparison with other famous people, the nativity stories mimic the pattern of Hellenistic biography where the stories of their heroes lives were read and interpreted backwards. Each biography followed a set structure of at least five elements: (i) a genealogy revealing illustrious ancestors, (ii) an unusual, mysterious, or miraculous conception, (iii) an annunciation by an angel or in a dream, (iv) a birth accompanied by supernatural portents, and (v) praise or forecast of great things to come, or persecution by a potential competitor (McGaughy 1992). In general terms these elements can be found in the biblical infancy stories. Yet it wasnt until after Emperor Constantine consciously chose Christianity as his Empires new civil religion (Kennedy 2006:221) in 313 CEthat there was a significant change in both attitude and authority surrounding Christianity, its stories and developing doctrines. Having been oppressed and persecuted by Rome for some 300 years, Christianity suddenly came into imperial favour, even becoming the official religion of the empire: ... bishops, once targets for arrest, torture, and execution, now received tax exemptions, gifts from the imperial treasury, prestige, and 7 even influence at court, [while] their churches gained new wealth, power, and prominence (Pagels 1988:xxv). Then another extraordinary event happened 12 years laterin 325 CE, when Emperor Constantine stepped in to resolve an internal church dispute threatening civil strife. Constantine took the unprecedented step of calling what was to be the first general council meeting of the church, in Nicea. Representatives came from all over: Antioch, North Africa, Alexandria, Jerusalem, Constantinople, Rome and Northern Italy. The Council of Nicea was about merging the Jesus of history with the Christ of faithor as it has been called, implementing the divinity test. It was also about solidifying or standardising the beliefs and liturgies of the church. And of course, its flip side: excluding those who taught or believed or did, something different. Also worth noting: the establishment of the Christmas feast first appears on the liturgical calendar in Rome in 336 CE, 10 years after Nicea. Prior to that Epiphany (or old Christmas celebrated on 6 January) was seen as more important than Nativity (celebrated on 25 December). The conflict was finally smoothed over with a decision to combine Christmas with Epiphany, which liturgically became know as the Twelve days of Christmas. So the development goes like this: from birth of a human person, a brother; to the transcendence and distance of God modelled after an exalted royal emperor (Roll 1995:177)Jesus of history to Christ of faith. Or as one of my mentors has put it: Jesus the iconoclast to Christ the icon (Funk 1996:44). Now thats some shift! oo0oo As storytellers, interpreters, poets, composers, liturgists and artists, how can we approach the ReBirthing of Christmas down under in the 21st century? Cameo 3:5 Christmas is loud cacophony in the symphony of my year. the sound of crass cash registers beep-beeping in my ears 8 and all day long in every place no matter where I go relentless sentimental songs that keep on mentioning snow. and the clash of garish glitter and tawdry tinsel-shine and buy! buy! buy! buy! on every second sign. I wish it was a simple tune played on a flute or fiddle, that could slip past my defences and touch me in my middle like the sweetness of a baby born all fresh and soft and whole to light a lamp of wonder in the midnight of my soul (Fay White). Fiddle we may or may not have. But some simple down under tunes and songs we do. Back in the late 1940s when Australia was not long out of the Second World War but still under the influence of the British Empire, Australian John Wheeler penned this now popular song "Christmas Day" 322 TiS The north wind is tossing the leaves, The red dust is over the town; The sparrows are under the eaves, And the grass in the paddocks is brown; And we lift up our voices and sing To the Christ-Child, the Heavenly King (JWheeler). But it is to New Zealand we turn for some of the best of the more modern of them, and the creative genius of Shirley Erena Murray. "Carol our Christmas" (Tune: Reversi) 9 AA (SEMurray) Star-Child, earth-Child 40(ii) COC Star-Child, earth-Child go-between of God, love Child, Christ Child, heaven's lightning rod, Refrain: This year, this year, let the day arrive, when Christmas comes for everyone, everyone alive! 10 Street child, beat child no place left to go, hurt child, used child, no one wants to know, Refrain: This year, this year, let the day arrive, when Christmas comes for everyone, everyone alive! Grown child, old child, mem'ry full of years, sad child, lost child, story told in tears, Refrain: This year, this year, let the day arrive, when Christmas comes for everyone, everyone alive! Spared child, spoiled child, having, wanting more, wise child, faith child knowing joy in store, Refrain: This year, this year, let the day arrive, when Christmas comes for everyone, everyone alive! Hope-for-peace Child, God's stupendous sign, down-to-earth Child, star of stars that shine, Refrain: This year, this year, let the day arrive, when Christmas comes for everyone, everyone alive! (SEMurray) On the song Star Child Shirley Murray writes: Cameo 3:6 11 The whole thrust of Star-Child is for the entire world to experience Christmas, from street kids to the forgotten elderly, and this has to be expressed in language we now relate to. Hence [such language] represents an attempt to make our imaginations work in the present world rather than the unreal past. And again: Cameo 3:7 Maybe our re-awareness of the full humanity of Jesus, rather than his divinity, is the point which allows us to move from Church language to secular language Im thinking of the impact of the parables (people stuff, everyday language), as well as the fierce arguments of Jesus with the religious lot in more religious language. Telling the story is a secular thing, while preaching the doctrine the Church thing. oo0oo While the religious infancy stories around the birth of Jesus of Nazareth may have come to provide the fundamental rationale for the festival within the Christian Church, for the most part and for most people, they no longer function as determinative. Christmas is a global and hybrid celebration, which weaves together religion-media-culture, creating a legitimacy of its own. And for many people today Christmas is just that... Christmas! Something to be entered into and enjoyed, if possible. Christmas has always been an extremely difficult festival or holiday to christianise! No matter how vehemently preachers or theologians or ordinary churchgoing folk might decry the fact, or stage mock assassinations of Santa Claus, or try to establish who influenced whom for what purposes, the Christian feast integrated certain originally non-Christian elements, and that has remained precisely the case down to the present moment... Christmas is firmly established in its socio-cultural environment, in terms of that environment (Roll 1995:257, 269). Christmas is the most human and loveable, and easily the most popular, festival of the year involving nearly all the population. It would never have achieved the level of importance which it enjoys today 12 unless it had struck deep folk roots... and called forth a natural, spontaneous human response (Roll 1995:271). Why? Both the pre-Christian folk-festivals and our modern popular culture celebrations are essentially life-affirming. They say yes to life. For life is not a great ready-made thing out there. Life is ourselves, and what we make it. Life is a buzz that we generate around ourselves. It includes everything and excludes nothing (Cupitt 2003). Such a view stands in shape contrast to many church-going Christians with their unchanging Sky God, and who still are pessimistic as regards this earth, and value it only as a place of discipline for the life to come (Miles 1912/76:25). No wonder popular culture wins out all the time! At its best, Christmas is a mirror in which we see reflected the very best life can be. Where we see ourselves moved by generosity, inspired by hope, and uplifted by love, not only for ourselves but for the whole evolving universe. Not only a celebration of the birth of Jesus, but also an invitation to assume responsibility for this sacred birth happening in and through us (Sanguin 2010: 18). Likewise, I suggest, the problem with Christmas is not commercialisation. The problem is, there is no longer any surprise. Both the church and the business world encourage us to celebrate but their messages are rehashed and blatant. There can be no surprise, for there is no subtlety. As one scholar has suggested: The dynamic is similar to the difficulty we have seeing rainbows and smelling roses. Rarely do we experience beauty in depth. Instead we move on to something else, distracted just enough to miss that which is most important and immediate (Frazier 1992:71). Both Advent and Christmas through a southern hemisphere lens, are best seen as we are open and receptive to their simple mystery: being sensitive to and surprised by, opportunities from the present moment when an incognito God is in the midst of ordinary daily events. When both are parables, in which everyday, ordinary events, take completely unexpected turns. 13 (As an aside it is interesting that both Christmas and Easter are related to the cycles of the earth rather than to any actual dates of Jesus birth and death. We do not know when in the year Jesus was born. We do know when he died. Christianity tied his birth to the northern hemisphere winter solstice, and his death to the northern hemisphere spring equinox, the latter being a moveable feastanywhere between 22 March and 25 Apriltied to the moon cycle as well as that of the earth. Christianity is a latecomer to the elemental rituals and celebrations of humanity!) Notes: Blainey, G. 1987. Sydney 1877 in (ed.) D. J. Mulvaney, J. P. White. Australians. To 1788. NSW: Broadway. Fairfax, Syme and Weldon Associates. Breward, I. 1988. Australia. The Most Godless Place under Heaven. VIC: Mitcham. Beacon Hill Books. Cupitt, D. 2003. Life, Life. CA: Santa Rosa. Polebridge Press. Frazier, R. T. 1992. Christmas should be softly spoken in Quarterly Review 12, 4, 69-74. 14 Funk, R. W. 1996. Honest to Jesus. Jesus for a New Millennium. NY: New York. HarperSanFrancisco. Funk, R. W.; R. W. Hoover (ed.). The Five Gospels: The Search for the Authentic Words of Jesus. NY: New York. McMillan. Geering, L. G. 1998. Does Society Need Religion? NZ: Wellington, St Andrews Trust for the Study of Religion and Society. Gomes, P. J. The Scandalous Gospel of Jesus: Whats So Good About the Good News? New York: HarperOne, 2007. Griffin, G. 1982. The colour of joy in Nigel Watson. (ed.) Jesus Christ for Us. Reflections on the Meaning of Christ appropriate to Advent and Christmas. VIC: Melbourne. JBCE. Inclusive Readings. Year C. 2007. QLD: Toombul. Inclusive Language Project. In private circulation. Kaufman, G. D. 1993. In Face of Mystery. A Constructive Theology. MA: Cambridge. Harvard University Press. Kennedy, J. 2006. The Everything Jesus Book. His Life, his Teachings. MA: Avon. Adams Media. McGaughy, L. 1992. Infancy narratives in the ancient world in The Fourth R 5, 5, 1-3. Miles, C. A. 1912/76. Christmas Customs and Traditions. Their History and Significance. NY: New York. Dover Publications. Pagels, E. 1988. Adam, Eve, and the Serpent. NY: New York. Vintage Books/Random House. Rank-Heinmann, U. 1994. Putting Away Childish Things. Translated by Peter Heinegg. NY: New York. HarperCollins. Roll, S. K. 1995. Toward the Origins of Christmas. The Netherlands: Kampen. Kok Pharos Publishing House. Sanguin, B. 2010. If Darwin Prayed. Prayers for Evolutionary Mystics. Canada: Vancouver. ESC Publishing. Wilson, B. 1982. The church in a secular society in D. Harris, D Hynd, D Millikan. (ed.) The Shape of Belief. Christianity in Australia Today. NSW: Homebush. Lancer Books. 15
https://www.scribd.com/document/73271758/NBS-Gathering-Keynote-Address-3-Christmas
CC-MAIN-2019-35
refinedweb
3,803
61.26
> Actually, scratch that part of my response. *Existing* namespace > packages that work properly already have a single owner How so? The zope package certainly doesn't have a single owner. Instead, it's spread over a large number of subpackages. > With PEP 402, those owning packages are the only ones that would have > to change. No. In setuptools namespace packages, each portion of the namespace (i.e. each distribution) will have it's own __init__.py; which of them gets actually used is arbitrary but also irrelevant since they all look the same. So "only those" is actually "all of them". > With PEP 382, all the *other* distro packages have to > change as well What's a "distro package"? Which are the other ones? They don't need to change at all. The existing setuptools namespace mechanism will continue to work, and you can add PEP 382 package portions freely. > It seems I now remember at least some of the reasons why we didn't > like the "directory extension" idea the first time it was suggested :) Please elaborate - I missed your point. Regards, Martin
https://mail.python.org/pipermail/import-sig/2011-November/000368.html
CC-MAIN-2014-15
refinedweb
184
67.15
[SOLVED][QHttp] qhttp->get("/index.html?text=AAA",file) Doesn't work correctly Hello everyone I want to write simple program that would collect links from one website I've found. I decided to use QHttp as the simplest way to make it work. From what I've already wrote I've got program that downloads index.html file, but I need to send GET data to collect various links, depending on program input. Here's my code: @ file = new QFile("local.html", this); http = new QHttp(this); file->open(QIODevice::ReadWrite); http->setHost("website.info"); http->get("/index.html?text=some+text", file); QTextStream data(file); text = data.readAll(); file->close(); QDebug()<<"File size = "<<plik->size()<<"\n"; QDebug()<<text; @ Program compiles without any errors and using QDebug i can see that file has some size (so it's created and page was downloaded), but when i look at the content of 'text' variable i can see it is /index.html itself but not formated and without data which /index.html?text=some+text should have. Is there any special way i should send GET request? "QHttp": [quote]This class is obsolete. It is provided to keep old source code working. We strongly advise against using it in new code.[/quote] Use QNetworkAccessManager instead! However, your problem might be that you don't use "QUrl::toPercentEncoding": . Since the docs say QHttp is deprecated, and without testing: Can't you use the QNetworkAccessManager? Like so: @ QUrl myURL(QString("")); myURL.addQueryItem(QString("text"), QString("some+text")); QNetworkRequest myRequest(myURL); QNetworkAccessManager myManager(this); QNetworkReply * pMyReply = myManager.get(myRequest); // now use pMyReply to get the data, which is a subclass of IODevice! // don't know if the device is already open, if not, use ->open() // then read QByteArray byteData = pMyReply->readAll(); // and convert to string! // be careful, take care of encoding here: QString stringData(byteData); // and clean up delete pMyReply; @ Thank you for quick answer. I'm already trying to use this suggestions in my code, I'll write when I'll finish.. - sierdzio Moderators Possible cause of the problem may be that ::get() call is asynchronous, so you should wait for requestFinished() signal to be emitted before reading. Also, I assume that "text" variable is a QString? And, in first QDebug() you should probably use "file->size()" instead of "plik->size()". And indeed, QHttp is deprecated, try QNAM, it's fun! :D That's not where problem is because /index.html without GET is being downloaded correctly. Only the one with GET (/index.html?text=some+text) causes problems. [quote author="jaszczomb" date="1312299549".[/quote] Hm, since "Variable 'QNetworkRequest myReques' has initializer but incompatible type" looks like a typo (myReques vs myRequest), could you please post your code and the exact error message with line number, please? As I said, I didn't even compile this code, just gave a rough idea how to use QNetworkAccessManager. It's all in the docs. @ ui->setupUi(this); connect(ui->przycisk,SIGNAL(clicked()),this,SLOT(pobieranie())); QUrl url(QString("")); url.addQueryItem(QString("text"), QString("some+text")); QNetworkRequest request(url); //12 line in my cpp file QNetworkAccessManager manager(this); QNetworkReply * pReply = manager.get(request); QByteArray byteData = pReply->readAll(); QString stringData(byteData);@ Message: "12: error:variable ‘QNetworkRequest request’ has initializer but incomplete type" That's all in constructor of an application. Until it's not working I won't write anything more because next step is to find links from the document with .indexOf (that's why I'm converting site to QString). I'll search the Docs to find an answer but any of your suggestions is very helpful. You need an #include. @#include <QMainWindow> #include <QUrl> #include <QFile> #include <QTextStream> #include <QDebug> #include <QNetworkAccessManager>@ Here is my Include section. Should I include something more? Peppe you were right, it's because I had to place one more include. Now i have one more problem with QByteArray byteData = pReply->readAll() but I hope I can make it on my own since now. Thank you everyone :] [quote author="jaszczomb" date="1312309394"] Now i have one more problem with QByteArray byteData = pReply->readAll() but I hope I can make it on my own since now. [/quote] I could imagine you might have to call @ if (!pReply->open(QIODevice::ReadOnly)) { // Error: something went wrong, } // you can also check pReply->isOpen() now pReply->readAll(); @ See docs of QIODevice. - mlong Moderators Be sure and take note of sierdzio's post above. If you call readAll() immediately after the get(), then there more than likely won't be anything to read yet. You probably want to look at either "QNetworkRequest::finished()": or "QNetworkAccessManager::finished()": - sierdzio Moderators Just a quick additional note on my last post - if you don't want to make your class asynchronous, too, you can wait for the signal right in your constructor, with something like this: @forever { if (/* Check for reply here /) { / Do reading here */ } else { // This ensures that your application will respond to events while waiting for the reply qApp->processEvents(); } } @ Although doing it in the constructor might be dangerous. Also, it will wait for an answer indefinitely... be careful :)
https://forum.qt.io/topic/8191/solved-qhttp-qhttp-get-index-html-text-aaa-file-doesn-t-work-correctly
CC-MAIN-2018-05
refinedweb
852
57.47
Egg... google has a Swedish Chef language tranlation page: With enough beer in me I sound like the Swedish Chef. It’s a very straightforward solution but no one has ever called it elegant. Rob Mine is elegant because it leverages the power of SOA. Just kidding, it’s a nasty hack that I thought you might find amusing. 🙂 using System; using System.Net; using System.Text; using System.IO; class Chef { public static string Convert(string text) { WebRequest request = HttpWebRequest.Create(""); request.Method = "POST"; string postData="dialect=bork&text=" + text; ASCIIEncoding encoding = new ASCIIEncoding(); byte[] bytes = encoding.GetBytes(postData); request.ContentType="application/x-www-form-urlencoded"; request.ContentLength = postData.Length; Stream requestStream = request.GetRequestStream(); requestStream.Write(bytes, 0, bytes.Length); requestStream.Close(); HttpWebResponse objResponse = (HttpWebResponse) request.GetResponse(); string result = String.Empty; using (StreamReader sr = new StreamReader(objResponse.GetResponseStream())) { result = sr.ReadToEnd(); sr.Close(); } int start = result.IndexOf("</h2></center><p>") + "</h2></center><p>".Length; int end = result.IndexOf("<p><br><hr>", start); return result.Substring(start, end – start); } } class App { [STAThread] static void Main(string[] args) { string value = Chef.Convert("This is the greatest hack ever!"); Console.WriteLine(value); } } The specification for the language conversion is annoying in its ambiguousness. Taking just one example, the word "the", fits several rules, "5. If there is an e at the end of the word, replace it by e-a.", and "7. Replace all occurrences of the by zee.". So while their example shows that "Do you know the way to San Jose?" translates into "Du yuoo knoo zee vey tu Sun Juse-a? Bork bork bork!" then "zee" should rather have been "zee-a", if we presume all fitting rules are to be applied. I am sure it shouldn’t be too difficult to find other ambiguities if one is fluent in English. Furthermore, a slight oversight, most likely, is the fact that they say that all paragraphs or sentences should end with "Bork bork bork." and yet in their examples they write "Bork bork bork!". While I do enjoy occasional programming contests, this one seems to have been specified without giving much thought to the actual specification. It rather feels like some of the software projects at work, really. Otherwise a solution could elegantly be made using the visitor pattern or the poorly named pattern for those who read the conversations articles by Hyslop and Sutter in the C/C++ User Journal. Thanks for the heads-up though, but the hurt of "thees" ambiguousness is too much for my fragile compiler implementor heart. 🙂 The ambiguities are galore. With multiple rules applying to the same set of characters, what is the sequence in which we apply them? I really invested some serious time before I came to the conclusion that I would have to make some real heavy assumptions on the sequencing of the rules, the priorities in case of ties (such as the rules that apply to the character ‘e’) etc. I wasn’t trying to do it for the money obviously, but it seemed challenging until I got down to organizing the rule set. C’mon guys…define it correctly. Another thing is .. the winner is the first solution that is "correct" .. okay how does one know correct simply by looking at that ambiguous example that itself can have multiple translations. I feel the same about the rules. And provide some decent examples – like paragraphs. The examples they provide don’t even exercise a lot of their rules. I’m glad to see some interest in our concept. The key here is not to sweat the small stuff. What we’re looking for is elegance of code, quality OOP oriented principals, and innovation. Obviously, a hack to somebody’s elses webservice won’t cut it… Thanks, Eric for the mention. peter [][][][][][][][][][][][][][][][][][][] PingBack from PingBack from
https://blogs.msdn.microsoft.com/ericgu/2004/12/01/programming-contest-at-eggheadcafe/
CC-MAIN-2018-26
refinedweb
636
60.11
Has anyone tried compiling rootwrap under Cython? Even with non-optimized libraries, Cython sometimes sees speedups. Best Regards, Solly Ross ----- Original Message ----- From: "Vishvananda Ishaya" <vishvana...@gmail.com> To: "OpenStack Development Mailing List (not for usage questions)" <openstack-dev@lists.openstack.org> Sent: Wednesday, March 5, 2014 1:13:33 PM Subject: Re: [openstack-dev] [neutron][rootwrap] Performance considerations, sudo? On Mar 5, 2014, at 6:42 AM, Miguel Angel Ajo <majop...@redhat.com> wrote: > > Hello, > > Recently, I found a serious issue about network-nodes startup time, > neutron-rootwrap eats a lot of cpu cycles, much more than the processes it's > wrapping itself. > > On a database with 1 public network, 192 private networks, 192 routers, > and 192 nano VMs, with OVS plugin: > > > Network node setup time (rootwrap): 24 minutes > Network node setup time (sudo): 10 minutes > > > That's the time since you reboot a network node, until all namespaces > and services are restored. > > > If you see appendix "1", this extra 14min overhead, matches with the fact > that rootwrap needs 0.3s to start, and launch a system command (once > filtered). > > 14minutes = 840 s. > (840s. / 192 resources)/0.3s ~= 15 operations / resource(qdhcp+qrouter) > (iptables, ovs port creation & tagging, starting child processes, etc..) > > The overhead comes from python startup time + rootwrap loading. > > I suppose that rootwrap was designed for lower amount of system calls > (nova?). > > And, I understand what rootwrap provides, a level of filtering that sudo > cannot offer. But it raises some question: > > 1) It's actually someone using rootwrap in production? > > 2) What alternatives can we think about to improve this situation. > > 0) already being done: coalescing system calls. But I'm unsure that's > enough. (if we coalesce 15 calls to 3 on this system we get: 192*3*0.3/60 ~=3 > minutes overhead on a 10min operation). > > a) Rewriting rules into sudo (to the extent that it's possible), and live > with that. > b) How secure is neutron about command injection to that point? How much is > user input filtered on the API calls? > c) Even if "b" is ok , I suppose that if the DB gets compromised, that > could lead to command injection. > > d) Re-writing rootwrap into C (it's 600 python LOCs now). This seems like the best choice to me. It shouldn’t be that much work for a proficient C coder. Obviously it will need to be audited for buffer overflow issues etc, but the code should be small enough to make this doable with high confidence. Vish > > e) Doing the command filtering at neutron-side, as a library and live with > sudo with simple filtering. (we kill the python/rootwrap startup overhead). > > 3) I also find 10 minutes a long time to setup 192 networks/basic tenant > structures, I wonder if that time could be reduced by conversion > of system process calls into system library calls (I know we don't have > libraries for iproute, iptables?, and many other things... but it's a > problem that's probably worth looking at.) > > Best, > Miguel Ángel Ajo. > > > Appendix: > > [1] Analyzing overhead: > > [root@rhos4-neutron2 ~]# echo "int main() { return 0; }" > test.c > [root@rhos4-neutron2 ~]# gcc test.c -o test > [root@rhos4-neutron2 ~]# time test # to time process invocation on this > machine > > real 0m0.000s > user 0m0.000s > sys 0m0.000s > > > [root@rhos4-neutron2 ~]# time sudo bash -c 'exit 0' > > real 0m0.032s > user 0m0.010s > sys 0m0.019s > > > [root@rhos4-neutron2 ~]# time python -c'import sys;sys.exit(0)' > > real 0m0.057s > user 0m0.016s > sys 0m0.011s > > [root@rhos4-neutron2 ~]# time neutron-rootwrap --help > /usr/bin/neutron-rootwrap: No command specified > > real 0m0.309s > user 0m0.128s > sys 0m0.037s > > _______________________________________________ > OpenStack-dev mailing list > OpenStack-dev@lists.openstack.org > _______________________________________________ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org _______________________________________________ OpenStack-dev mailing list OpenStack-dev@lists.openstack.org
https://www.mail-archive.com/openstack-dev@lists.openstack.org/msg18430.html
CC-MAIN-2019-39
refinedweb
640
69.38
Before I get to the good parts of this post (the technical content), let me take care of a few marketing issues. First, as I mentioned in my last post, I gave my “Making Java Groovy” presentation at JavaOne last week. If you were there and you haven’t completed your Session Surveys, please do so. I really want to Party Like a (JavaOne) Rock Star, Party Like a (JavaOne) Rock Star, etc., though I expect in reality that would involve sharing a quiet dinner at home with my wife. She probably wouldn’t appreciate it if I trashed the room, too, at least not more than it’s already trashed*. *Yeah, my 21 year old son still does live at home, why do you ask? That did give me the opportunity to see my book on the shelf of a book store for the first time: I should also mention that as of 9/30, if you buy the book at Manning, you can now get all the electronic formats (pdf, mobi, and epub). Finally, I got my first Amazon review today, and was so good I walked around with a smile all day. Now on to the real content. In my Groovy presentations, I often like to access a RESTful web service and show (1) how easy it is to make a GET request using Groovy, and (2) how to use a JsonSlurper to parse a JSON response to get the information inside it. For this purpose my default site is ICNDB, the Internet Chuck Norris Database. That site has caused me problems, though. First, it resulted in my first ever take down notice from a lawyer, which I’ll show in a moment. Seriously. As part of my Android presentations at No Fluff, Just Stuff conferences I build a simple app to access that site, parse the results (using a GSON parser, since I don’t have Groovy available) and update the display. When running, the app looks like: To make it easy for the attendees of my Android talks to play with, I uploaded the app to the Google Play store. That was fun until I received the following email, from an address I’ll leave out: Dear Sir/Madam: Patton Boggs LLP represents Carlos Ray Norris, aka Chuck Norris, the famous actor and celebrity. We are contacting you because we recently learned that you have developed and are distributing a software application that uses Mr. Norris’s name and/or image without authorization on Google Play. Mr. Norris appreciates all of his fans. However, the unauthorized use of his name and/or image severely harms my client and jeopardizes his existing business relationships. Mr. Norris owns legal rights in his name and image which includes copyright, trademark, and publicity rights (the “Norris Properties”). He uses the Norris Properties regularly in his own business endeavors. Therefore we have asked Google to remove your application from Google Play because it violates Mr. Norris’s intellectual property rights. We request that you (1) immediately stop developing and distributing “Chuck Norris” applications; (2) remove all “Chuck Norris” applications that you have developed or control from all websites under your control; and (3) do not use Mr. Norris’s name or image, or any cartoon or caricature version of Mr. Norris’s name or image for any endeavor, including in connection with software applications, without Mr. Norris’s permission. Thank you for honoring Mr. Norris’s legal rights. Please contact me if you have questions. Sincerely, … A few points immediately come to mind: - Carlos Ray Norris? Seriously? I had no idea. - Does it matter that my app is free and only consumes data from a publicly available web site? Apparently not. - If I changed the icon and replaced the words “Chuck” and “Norris” everywhere with the words “Patton” and “Boggs” (the name of the law firm :)), could I upload it again? I’m still not exactly sure what I was doing wrong, but of course I did not want to cross Carlos Ray “Chuck” Norris, to say nothing of his lawyers. But after talking to a few people, I decided to ignore the letter, at least until any money was involved. I haven’t heard anything since, but about a week later Google Play took down my app. So be it. If you want the source code, though, check out the ICNDB project in my GitHub repository. It’s mostly just a demonstration of how to Spring’s RestTemplate, Google’s GSON parser, and an Android AsyncTask together. In the repo is another branch that uses a Java Timer to refresh the joke every 10 seconds. The real question is, why haven’t the barracudas lawyers gone after the original ICNDB site? Worse, what happens to my poor app (and, more importantly, my presentation) when they do? I decided my best course of action was to download as many of the jokes as possible and be ready to serve them up locally in case I need them. That, at long last, brings me to the technical part of this blog post. The original web site returns jokes in JSON format. That means storing them in a MongoDB database is trivial, because Mongo’s native format is BSON (binary JSON) and I can even query on the joke properties later. How do I grab all the jokes? There’s no obvious query in the API for that, but there is a work around. If I first access, I can get the total number of jokes. Then there is a URL called, which fetches num random jokes. According to the web site, it returns them in the form: { "type": "success", "value": [ { "id": 1, "joke": "Joke 1" }, { "id": 5, "joke": "Joke 5" }, { "id": 9, "joke": "Joke 9" } ] } The value property is a list containing all the individual jokes. To work with MongoDB, I’ll use the driver from the GMongo project. It follows the typical Groovy idiom, in that it takes an existing Java API (in this case, the ugly and awkward Java driver for Mongo) and wraps it in a much simpler Groovy API. As a beautiful illustration of the process, here’s an excerpt from the com.gmongo.GMongo class: [sourcecode language=”groovy”] class GMongo { @Delegate Mongo mongo // … lots of overloaded constructors … DB getDB(String name) { patchAndReturn mongo.getDB(name) } static private patchAndReturn(db) { DBPatcher.patch(db); return db } } [/sourcecode] Note the use of the @Delegate annotation, which exposes all the methods on the existing Java-based Mongo class through the GMongo wrapper. Based on that, here’s my script to download all the jokes and store them in a local MongoDB database: [sourcecode language=”groovy”] import groovy.json.* import com.gmongo.GMongo GMongo mongo = new GMongo() def db = mongo.getDB(‘icndb’) db.cnjokes.drop() String jsonTxt = ‘’.toURL().text def json = new JsonSlurper().parseText(jsonTxt) int total = json.value.toInteger() jsonTxt = "{total}".toURL().text json = new JsonSlurper().parseText(jsonTxt) def jokes = json.value jokes.each { db.cnjokes << it } println db.cnjokes.find().count() [/sourcecode] Note the nice overloaded left-shift operator to add each joke to the collection. I’ve run this script several times and I consistently get 546 total jokes. That means the entire collection easily fits in memory, a fact I take advantage of when serving them up myself. My client needs to request a random joke from the server. I want to do this in a public forum, so I’m not interested in any off-color jokes. Also, the ICNDB server itself offers a nice option that I want to duplicate. If you specify a firstName or lastName property on the URL, the joke will replace the words “Chuck” and “Norris” with what you specify. I like this because, well, the more I find out about Carlos Ray the more I wish I didn’t know. Here’s my resulting JokeServer class: [sourcecode language=”groovy”] package com.kousenit import java.security.SecureRandom import com.gmongo.GMongo import com.mongodb.DB @Singleton class JokeServer { GMongo mongo = new GMongo() Map jokes = [:] List ids = [] JokeServer() { DB db = mongo.getDB(‘icndb’) def jokesInDB = db.cnjokes.find([categories: [$ne : ‘explicit’]]) jokesInDB.each { j -> jokes[j.id] = j.joke } ids = jokes.keySet() as List }] MongoDB has a JavaScript API which uses qualifiers like $ne for “not equals”. The Groovy API wrapper lets me add those as keys in a map supplied to the find method. I added the @Singleton annotation on the class, though that may be neither necessary or appropriate. I may want multiple instances of this class for scaling purposes. I’ll have to think about that. Let me know if you have an opinion. I’m sure there’s an easier way to get a random joke out of the collection, but I kept running into issues when I tried using random integers. This way works, though it’s kind of ugly. The getJoke method uses Groovy’s cool optional arguments capability. If getJoke is invoked with no arguments, I’ll use the original version. If firstName and/or lastName are specified, I use the replaceAll method from the Groovy JDK to change the value in the joke. Strings are still immutable, though, so the replaceAll method returns a new object and I have to reuse my joke reference to point to it. I actually missed that the first time (sigh), but that’s what test cases are for. Speaking of which, here’s the JUnit test (written in Groovy) to verify the JokeServer is working properly: [sourcecode language=”groovy”] package com.kousenit import static org.junit.Assert.* import org.junit.Before import org.junit.Test class JokeServerTest { JokeServer server = JokeServer() { assert server.joke } } [/sourcecode] I can invoke the getJoke method with zero, one, or two arguments. The basic testGetJoke method uses zero arguments. Or, rather, it accesses the joke property, which then calls getJoke() using the usual Groovy idiom. Now I need to use this class inside a web server, and that gave me a chance to dig into the ratpack project. Ratpack is a Groovy project and I’ve checked out the source code from GitHub, but there’s a simpler way to create a new ratpack application based on the Groovy enVironment Manager (gvm) tool. First I used gvm to install lazybones: > gvm install lazybones Then I created my ratpack project: > lazybones create ratpack icndb That creates a simple structure (shown in the ratpack manual) with a Gradle build file. The only modification I made to build.gradle was to add “ compile 'com.gmongo:gmongo:1.0'” to the dependencies block. Here’s the file ratpack.groovy, the script that configures the server: [sourcecode language=”groovy”] import static org.ratpackframework.groovy.RatpackScript.ratpack } } } [/sourcecode] I configured only a single “ get” handler, which is invoked on an HTTP GET request. I check to see if either a firstName or lastName query parameter is supplied, and, if so, I invoke the full getJoke method. Otherwise I just access the joke property. I made sure to set the Content-Type header in the response to indicate I was returning JSON data, and sent the message. If I type ./gradlew run from the command line, ratpack starts up its embedded Netty server on port 5050 and serves jokes on demand. Here’s a picture of the default request and response (using the Postman plugin in Chrome): Here is the response if I specify a first and last name: There you have it. I wanted to write a test inside ratpack to check my hander, but the infrastructure for that appears to still be under development. I tried to imitate one of the samples and extend the ScriptAppSpec class, but that class isn’t in my dependent jars. I also tried to follow the Rob Fletcher’s mid-century ipsum example, but while I was able to create the test, it failed when running because it couldn’t find the ratpack.groovy file inside the ratpack folder, since it expected it to be in the root. The right approach would probably be to turn the contents of my get block into a separate Handler, because the manual talks about how to test them, but I haven’t done that yet. As they say, if you live on the cutting edge, sometimes you get cut. I expect that will all settle down by 1.0. For my presentations, I now need to update my Android client so that it accesses and understands that the JSON coming back is a bit simpler than that served up by the original server. That’s beyond the scope of this (way too long) blog post, however. I haven’t yet committed the application to GitHub, but I will eventually. In the meantime I just have to hope that my new app also doesn’t run afoul of Carlos, Ray, Patton, and Boggs, Esq. 2 replies on “Making Java Groovy: ratpack, MongoDB, and Chuck Norris” […] Making Java Groovy: ratpack, MongoDB, and Chuck Norris | Stuff I … I get to the good parts of this post (the technical content), let me take care of a few marketing issues. First, as I mentioned in my last post, I gave my "Making Java Groovy" presentation at JavaOne last week. If you were … […] […] two previous posts, I discussed applications I created that were simple client-side front ends for the […]
https://kousenit.org/2013/10/02/making-java-groovy-ratpack-mongodb-and-chuck-norris/
CC-MAIN-2020-16
refinedweb
2,228
64
/* Machine independent variables that describe the core file under GDB. Copyright 1986, 1987, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,. */ /* Interface routines for core, executable, etc. */ #if !defined (GDBCORE_H) #define GDBCORE_H 1 struct type; #include "bfd.h" /* Return the name of the executable file as a string. ERR nonzero means get error if there is none specified; otherwise return 0 in that case. */ extern char *get_exec_file (int err); /* Nonzero if there is a core file. */ extern int have_core_file_p (void); /* Read "memory data" from whatever target or inferior we have. Returns zero if successful, errno value if not. EIO is used for address out of bounds. If breakpoints are inserted, returns shadow contents, not the breakpoints themselves. From breakpoint.c. */ /* NOTE: cagney/2004-06-10: Code reading from a live inferior can use the get_frame_memory methods, code reading from an exec can use the target methods. */ extern int deprecated_read_memory_nobpt (CORE_ADDR memaddr, gdb_byte *myaddr, unsigned len); /* Report a memory error with error(). */ extern void memory_error (int status, CORE_ADDR memaddr); /* Like target_read_memory, but report an error if can't read. */ extern void read_memory (CORE_ADDR memaddr, gdb_byte *myaddr, int len); /* Read an integer from debugged memory, given address and number of bytes. */ extern LONGEST read_memory_integer (CORE_ADDR memaddr, int len); extern int safe_read_memory_integer (CORE_ADDR memaddr, int len, LONGEST *return_value); extern int safe_read_memory_unsigned_integer (CORE_ADDR memaddr, int len, ULONGEST *return_value); /* Read an unsigned integer from debugged memory, given address and number of bytes. */ extern ULONGEST read_memory_unsigned_integer (CORE_ADDR memaddr, int len); /* Read a null-terminated string from the debuggee's memory, given address, * a buffer into which to place the string, and the maximum available space */ extern void read_memory_string (CORE_ADDR, char *, int); /* Read the pointer of type TYPE at ADDR, and return the address it represents. */ CORE_ADDR read_memory_typed_address (CORE_ADDR addr, struct type *type); /* This takes a char *, not void *. This is probably right, because passing in an int * or whatever is wrong with respect to byteswapping, alignment, different sizes for host vs. target types, etc. */ extern void write_memory (CORE_ADDR memaddr, const gdb_byte *myaddr, int len); /* Store VALUE at ADDR in the inferior as a LEN-byte unsigned integer. */ extern void write_memory_unsigned_integer (CORE_ADDR addr, int len, ULONGEST value); /* Store VALUE at ADDR in the inferior as a LEN-byte unsigned integer. */ extern void write_memory_signed_integer (CORE_ADDR addr, int len, LONGEST value); extern void generic_search (int len, char *data, char *mask, CORE_ADDR startaddr, int increment, CORE_ADDR lorange, CORE_ADDR hirange, CORE_ADDR * addr_found, char *data_found); /* Hook for `exec_file_command' command to call. */ extern void (*deprecated_exec_file_display_hook) (char *filename); /* Hook for "file_command", which is more useful than above (because it is invoked AFTER symbols are read, not before). */ extern void (*deprecated_file_changed_hook) (char *filename); extern void specify_exec_file_hook (void (*hook) (char *filename)); /* Binary File Diddlers for the exec and core files. */ extern bfd *core_bfd; extern bfd *exec_bfd; /* Whether to open exec and core files read-only or read-write. */ extern int write_files; extern void core_file_command (char *filename, int from_tty); extern void core_file_attach (char *filename, int from_tty); extern void exec_open (char *filename, int from_tty); extern void exec_file_attach (char *filename, int from_tty); extern void exec_file_clear (int from_tty); extern void validate_files (void); extern CORE_ADDR register_addr (int regno, CORE_ADDR blockend); #if !defined (KERNEL_U_ADDR) extern CORE_ADDR kernel_u_addr; #define KERNEL_U_ADDR kernel_u_addr #endif /* The target vector for core files. */ extern struct target_ops core_ops; /* The current default bfd target. */ extern char *gnutarget; extern void set_gnutarget (char *); /* Structure to keep track of core register reading functions for various core file types. */ struct core_fns { /* BFD flavour that a core file handler is prepared to read. This can be used by the handler's core tasting function as a first level filter to reject BFD's that don't have the right flavour. */ enum bfd_flavour core_flavour; /* Core file handler function to call to recognize corefile formats that BFD rejects. Some core file format just don't fit into the BFD model, or may require other resources to identify them, that simply aren't available to BFD (such as symbols from another file). Returns nonzero if the handler recognizes the format, zero otherwise. */ int (*check_format) (bfd *); /* Core file handler function to call to ask if it can handle a given core file format or not. Returns zero if it can't, nonzero otherwise. */ int (*core_sniffer) (struct core_fns *, bfd *); /* Extract the register values out of the core file and store them where `read_register' will find them. CORE_REG_SECT points to the register values themselves, read into memory. CORE_REG_SIZE is the size of that area. WHICH says which set of registers we are handling: 0 --- integer registers 2 --- floating-point registers, on machines where they are discontiguous 3 --- extended floating-point registers, on machines where these are present in yet a third area. (GNU/Linux uses this to get at the SSE registers.) REG_ADDR is the offset from u.u_ar0 to the register values relative to core_reg_sect. This is used with old-fashioned core files to locate the registers in a large upage-plus-stack ".reg" section. Original upage address X is at location core_reg_sect+x+reg_addr. */ void (*core_read_registers) (char *core_reg_sect, unsigned core_reg_size, int which, CORE_ADDR reg_addr); /* Finds the next struct core_fns. They are allocated and initialized in whatever module implements the functions pointed to; an initializer calls deprecated_add_core_fns to add them to the global chain. */ struct core_fns *next; }; /* NOTE: cagney/2004-04-05: Replaced by "regset.h" and regset_from_core_section(). */ extern void deprecated_add_core_fns (struct core_fns *cf); extern int default_core_sniffer (struct core_fns *cf, bfd * abfd); extern int default_check_format (bfd * abfd); #endif /* !defined (GDBCORE_H) */
http://opensource.apple.com/source/gdb/gdb-1344/src/gdb/gdbcore.h
CC-MAIN-2015-27
refinedweb
904
54.12
Spinner is a view that displays items in a dropdown fashion, allowing user to pick one at a time. Spinner is an AdapterView. This means that it relies on an Adapter for its data. Adapters act as the bridge between adapterviews and the underlying data source. This makes Spinner like other adapterviews decoupled from data source. Hence we can customize the views shown in the spinner without affecting data. Spinner is a concrete public class residing in the android.widget package. package android.widget; Spinner is a public class that's why we can access and use it. public class Spinner{} Public classes are visible even from other packages apart from those they've been defined. Spinner class inherits from an abstract class called AbsSpinner. This class also resides in the android.widget package. AbsSpinner provides to Spinner much of the capabilities it has. For example, Spinner is an adapterview since it derives from the AbsSpinner. This allows Spinner to set and return a SpinnerAdapter. We can use the Spinner object to specify the spinner in an xml Layout. This pattern of specifyng an Object in the Layout resource then referencing from the Java/Kotlin code is common in android as a platform and is also the one recommended. Here are some of it's advantages: <Spinner android: Then in our java code we can first reference the Spinner from our Layout specification using the findViewById() method our activity class. Spinner spinner = (Spinner) findViewById(R.id.mySpinner); We can then instantiate a SpinnerAdapter(e.g ArrayAdapter). We use the default spinner Layout( android.R.layout.simple_spinner_item). We are using a static method called createFromResource(). This method is provided by the ArrayAdapter class and it returns us an ArrayAdapter instance from the external resource we provide it as our data source. ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.galaxies_array, android.R.layout.simple_spinner_item); You have to make sure you've added string array into your strings.xml file: <?xml version="1.0" encoding="utf-8"?> <resources> <string-array <item>Milky Way</item> <item>Andromeda</item> <item>Whirlpool</item> <item>Sombrero</item> <item>Cartwheel</item> <item>StarBust</item> <item>Pinwheel</item> <item>Leo</item> </string-array> </resources> ArrayAdapter provides us the createFromResource() method which gives us an instance of the ArrayAdapter from the string array we provided. After that: adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); This method allows us specify the Layout the adapter will use to display the list of spinner choices. We use the one provided by the Android Platform. Finally we set the adapter: spinner.setAdapter(adapter); Let's look at some examples. Hello guys.How do you do? This is what we do: A spinner is an android widget that basically displays items in dropdown. Thus allowing ussers to select only one item at a time. The parent class of the inbuilt android spinner is the AbsSpinner, a an abstract adapterview. However, sometimes we are not so much attracted to the inbuilt or default spinner, due to functionality limitations or we just want something nicer. In that case we can look at GitHub and obtain a third party library. Material Spinner is such library. It was first created by Jared Rumler more than 2 years ago. Since then it's been receiving updates.: In this top-list tutorial, we explore some of the top material spinner libraries that you can easily use in your project. These are open source libraries have several advantages that we will explore in a short while. Best Regards, Oclemy.
https://camposha.info/android/spinner
CC-MAIN-2019-04
refinedweb
587
58.69
sections are included: Oracle reserved words have a special meaning to Oracle and so cannot be redefined. For this reason, you cannot use them to name database objects such as columns, tables, or indexes. Keywords also have a special meaning to Oracle but are not reserved words and so can be redefined. However, some might eventually become reserved words, so care should be taken when using them as variable or function names in an application. The following table lists the Oracle reserved words and keywords: For information about PL/SQL reserved words and keywords, refer to the PL/SQL User's Guide and Reference. Table C." The list in Table C-2 is not a comprehensive list of all functions within the Oracle Reserved Namespaces. For a complete list of functions within a particular namespace, refer to the document that corresponds to the appropriate Oracle library.
http://docs.oracle.com/cd/A58617_01/server.804/a58234/vol2_wor.htm
CC-MAIN-2014-52
refinedweb
146
50.87
The software which drives this wiki web. For more documentation & discussion, see . ZWiki was inspired by the original Wiki Wiki Web and runs on the zope web application server (see Zope Dot Org). Developed by Simon Michael. Remote Wiki U R L: Old class diagram: ZWiki:ImplementationClassDiagram Lots of page types: ZWiki:QuickReference, ZWiki:AllAboutPageTypes Here's my log of activities in upgrading ZWiki to a new version (while upgrading ZoPe). (This was for a company Intra Net.) (Sept'01) We have some bugs in ZWiki right now. Some are rendering of Regular Expression-s. But the biggest problem is that Recent Changes doesn't work since we turned on authentication. This is related to having old code. Was considering jumping to [CMF] and [CMFWiki], but that's smelling dangerous. So trying straight ZWiki upgrade (while also upgrading Zope to 2.4.x, so that we're current and ready for [CMF]... A bit concerned about how to migrate content, so posted question at bottom of Did basic install did it on my machine additional confusion in my mind as to whether I need to do separate import of [Z Wiki Webs].zexp. Posted question about that as well. dotorg-format [Zwiki Web] doesn't work, so posted message at Simon recommended I just install new code right over the current Zope and content (after backing up). Said he hadn't tested with Zope2.4. What the heck... I installed old ZWiki on my local Zope2.4, then imported copy of ZWiki content. It works. (Including Recent Changes! At least once I tweaked the permissions on that page...) Installed ZWiki 0.9.5 code, and old pages still work. And can make new [Z Wiki Web] in dotorg style. Excellent. Will try this process on live server next week. But still have problems with alpha names for aname sections. Maybe I should install the vanilla Structured Text object here, and test that... But whoa, the Structured Text Rules page on the ZWiki site doesn't even note those features! Now I'm really confused. In the old system square brackets did that job. But now (which is where I posted a question about this) square brackets seem to be used for Wiki Name creation. ????? Ugh, never mind. Thought 0.9.5 code worked, but it did only for viewing. Can't edit. Going to start over and test more carefully. purged product and its code, deleted zope folders. re-installed 0.6.1 zwiki code (unzipped, copied .zexp into import folder, restarted server; imported zwiki.zexp to get zwiki_examples folder) import our wiki content; note that it blows away modification_time and history. Also note doesn't seem to matter whether I take over ownership during import (though I don't understand much about those issues). Change security settings for folder to give staffer Access, View, Add Zwiki, Change Zwiki. Try to view Front Page; damn, getting that rejection from title_prefix. This is why I'm supposed to log this stuff, I always forget the little tricks I've done in the past... to simplify: make a new folder secure_test, turn off anonymous rights and turn on staffer rights. Can't view index_html! Go back and turn on rights for Authenticated, and now it works! turn on Authenticated rights for zwiki folder, but still getting rejected by title_prefix! grasping at straws, add rights for search zcatalog (which I think may become relevant for Recent Changes). But doesn't make viewing of Front Page work. try to access title_prefix directly. That works fine. per, gave Anonymous the Access rights on the zwiki folder. No difference. hmmm, let's review that import/ownership setting more carefully. delete zwiki folder, reimport with take ownership checked. Turn on rights just for View for staffer. That was it! now turn on others for 'staffer': Access (leave on for anonymous), Add Wiki, Change Wiki. I can make changes. But I can't do Recent Changes. I can search. add rights for Search zcatalog, but it doesn't help, so turn it off. Select Recent Changes object, note it doesn't come set to acquire permissions, to add Access/View rights for staffer. Now it works! add new Wiki Name to a page, follow link to make page, edit it so there's something there. All work! Next step, install the upgraded code again. Upgrade to zwiki 0.9.5pre1. unzip, overwrite files (didn't delete old code first). Don't do any new importing. Restart server. Viewing pages works fine. Recent Changes work fine. Search works fine. editing does not work! Object is not callable hmm, could it be a migration issue? Make a new wikiweb, tweak the rights. Now I can edit a page, make new page, etc. maybe it's related to that "delete your DTML methods" message associated with crossing the 0.7 upgrade divide? Simon recommends copying my old zwiki content pages into a new empty zwiki. but I seem to lose parent info when I try that. Maybe it's because I did a subset of pages. But it was inconsistent (the first time, some pages had parent info, and others didn't). also, just noticed the structured subfolder of the new empty wiki. Should the content go down in there? instead, I copied the methods from the subfolder up a level (after deleting the original ones). That didn't seem to help. try copying all pages from old wiki to new wiki at one time or try copying some (or all) into subfolder tried copying just some. View a page which should have a parent. It didn't show one. Clicked the Back Links, and it showed the parent page, with the parent checkbox turn on! Went to the mgmt interface and viewed the child properties, and parents was empty. Viewed the child page again, still didn't show parent. Went to Back Links page, and now it shows the parent page, but the parent checkbox is turned off! Hmm, maybe permissions could be an issue? Start over create new wiki web (folder). Oh weird, now there's no structured subfolder! give lots of rights to staffer (just noticed some new ones, like Reparent and Send to Recycle Bin, etc.). select all old pages (except "standard" pages like Help Page and Recent Changes), copy, then paste. Oops, too many objects for browser, paste fails. So can't do them all at one time. hmm, maybe the problems comes up when you view a page when its full ancestry isn't there yet. So [OK] to copy in pieces as long as I don't view any until done? Yes, that did it! What's left to test? new page: write Wiki Name, follow, edit, save: [OK] Recent Changes, search: [OK] check Back Links, reparent: [OK] do an append to a page: [OK] Known/outstanding issues: ???? can't set User Options: Simon says this appears to be a zope2.4 issue ([Standard Text N G]), which I confirmed via lists. So it will hopefully get fixed soon; or I may try a hack someone submitted. in-page section names and hrefs a cancelled feature? (square brackets) (see above) Try new approach to fixing "object not callable" problem: import legacy content, then dump DTML pages, and copy in new versions from fresh wiki web. rename zwiki folder to zwiki1 reimport zwiki content set rights: confirm can read, search, but not edit delete Recent Changes, Jump Search, etc. plus all DTML methods copy all objects (except Front Page) from raw new zwiki. Can now edit! (still can't set User Options) Rolled out on live (Axiom) server with even shorter process exported content; turned off old server, renamed folder installed zope2.4.1 added users/rights installed zwiki product; created new zwikiweb to confirm working imported content; set rights deleted old core pages (e.g. Help Page); renamed old DTML pages copied core/DTML documents from zwikitest test, looks fine so far. Also set up this fresh ZWiki for person use. For that, see Zwiki Customizations. Hi Bill: Which of the permissions are implicated by search and recentchanges such that they will not work without authentication. John fdgsdgsdg --2003/06/18 18:09 [GMT] sdg sg dgsdg Excuse --2003/06/18 18:35 [GMT] the above thing was a test, and it worked. cool, excuse for the work of uncommenting... charles. Need [HELP] --2003/07/16 08:08 [GMT] sometime ago I could access a wiki hosted in [ZOPE] to test what a wiki was. I would like to go back there and try new things but I can't find the page, anybody knows what I'm talking about..? annoying bug --Bill Seitz, 2003/10/16 19:27 [GMT] related to viewing/copying history: ZWiki:IssueNo0208
http://webseitz.fluxent.com/wiki/ZWiki
crawl-002
refinedweb
1,463
77.03
I currently have the following code in a helper within rails, which allows me to set a start date and end date and return true based on whether the current date is between the predefined range. My problem is with this code it'll only work for the current year, however I want to change it so it'll return true if the date is within the range, ignoring the year. def is_christmas? start_date = Date.parse('01-12-2016') end_date = Date.parse('25-12-2016') today = Date.today today.between?(start_date, end_date) end unsure of how to eliminate the year and only check for the day/month date.day.between?(1, 25) date.month == 12 And to check for both: date.day.between?(1, 25) && date.month == 12 Wrapped in a method: def is_christmas?(date = Date.today) date.day.between?(1, 25) && date.month == 12 end
https://codedump.io/share/e9WhCMt25liC/1/how-to-find-out-if-the-current-date-in-rails-is-between-a-predefined-date-range-without-the-year
CC-MAIN-2018-22
refinedweb
146
77.53
Important: Please read the Qt Code of Conduct - ListView contentY changes on move When clicking an item in the ListView, it should be moved to the first implementation. I wanted to animate the opacity, but it seems not to be possible. Then I saw that the contentY of the listView changes, the moved item is at contentY -105. Am I doing something wrong, is this the desired behaviour or is it a bug? @ import QtQuick 2.0 ListView { id: listView width: 300; height: 350 model: ListModel { ListElement{borderColor: "red"} ListElement{borderColor: "blue"} ListElement{borderColor: "green"} ListElement{borderColor: "yellow"} ListElement{borderColor: "purple"} ListElement{borderColor: "pink"} ListElement{borderColor: "red"} ListElement{borderColor: "grey"} } onContentYChanged: console.log("contentY: " + contentY) spacing: 5 delegate: Rectangle { width: 200 height: 100 border.width: 2 border.color: borderColor MouseArea { anchors.fill: parent onClicked: listView.model.move(index, 0, 1) } } cacheBuffer: 150*count } @ Hi, Sorry, but can you elaborate the problem clearly ? When you move the item, i think it's obvious that the y position would change. On the side note, Can you try "PathView": ? I think it fits your requirement. It is clear for me that the contentY will change, but I am wondering why it changes to a negative value. I would think that the move operation always moves it to 0 or a positive pixel position Hi, I think it does actually set it to 0. I tested it as follows: @ onClicked: { listView.model.move(index, 0, 1); currentIndex = index; positionViewAtIndex(index,ListView.Beginning); console.log("C.Y:",contentY) } @ The negative value is seen when you move the item by mouse by clicking on it and then dragging down. This i think is due to the boundsBehavior which has Flickable.DragAndOvershootBounds as default and hence it overshoots a little bit. Try setting it to Flickable.StopAtBounds and contentY would always be > 0 Thank you for your answer! I also tried your code, but for me it still shows contentY < 0 when I scroll up. I just tried setting the Flickable.StopAtBounds, but sadly the contentY is still < 0 Ok. Not sure then. I'd suggest you to ask this at the Qt developer mailing list. Hi, yes this is documented behaviour : The top postion of a flickable is defined by originY and this can be a negative number : check it out here : originX : real originY : should use the originY value as the start position, instead of 0. OriginY can be negative, but should work fine as long as you take that into account in your calculations.
https://forum.qt.io/topic/43992/listview-contenty-changes-on-move/1
CC-MAIN-2021-49
refinedweb
420
58.38
How to deal with multiple Object classes Jon Swanson Ranch Hand Joined: Oct 10, 2011 Posts: 206 posted May 15, 2012 17:58:43 0 I am using some code that has a series of classes like Line, Text, Box which all extend Object. The have the same methods like setPosition() and write(). I don't have any control over the classes or the methods in them, other than the fact I can extend them. I will be using the same set of them repeatedly (for example, a specific set of Text, Text, Line, Box), I am trying to implement something of the form: class Block { private ArrayList<Object> block = new ArrayList<Object>(); add(Object component) { block.add(component); } setPosition(double x, double y) { for (Object component : block) component.setPosition(x, y); } write() { for (Object component: block) component.write(); } } The compile complains that component does not have methods like setPosition and write (well, says it can't find the symbol). I am not quite sure which direction to go. I can add a bunch of instanceof statements (I think)- public void setPosition(Object component, double x, double y) { if (component instanceof Line) Line tmp = (Line) component; else if (component instanceof Block) Block tmp = (Block) component; tmp.setPosition(x, y); } But there is the maintainability of keeping track of what the objects might be that have the write and setPosition methods. I may use more in the future. Am I thinking about this problem the right way? Before I start adding a lot of code to make the program work, could someone comment on how something like this should be structured? I think basically the classes should have an interface that has the common methods and my ArrayList should start from there, but I can't change those classes. Greg Charles Sheriff Joined: Oct 01, 2001 Posts: 2867 11 I like... posted May 15, 2012 18:51:52 2 There are certain languages that are "duck typed". That means if you're sure the method exists in a class, you can call it. The compiler won't complain, but you'll get a big runtime exception if the method doesn't actually exist. Java isn't duck typed. You have to call a method that the compiler can see exists in the class you're calling it on, or in an interface the class implements. Your classes don't extend from or implement anything that contains those methods so you're out of luck. However, you said you can extend those classes. If you make an interface, say Common, with your two methods and do something like: public class CommonBlock extends Block implements Common { } Then assuming you can instantiate CommonBlocks, CommonLines, etc., you can cast everything to Common and work with them like that. Jon Swanson Ranch Hand Joined: Oct 10, 2011 Posts: 206 posted May 16, 2012 08:14:01 1 Here is a simple test implementation (I've actually got the classes in separate files). Have I understood you correctly? It all seems to work quite nicely. // Original classes class Line { public void printMe() { System.out.println("I'm a line"); } } class Box { public void printMe() { System.out.println("I'm a box"); } } // The interface to implement interface PrintObject { void printMe(); void showMe(); } // The new classes, which extend the original classes and implement the interface class LineObject extends Line implements PrintObject { public void showMe() { System.out.println("Really a line object"); } } class BoxObject extends Box implements PrintObject { public void showMe() { System.out.println("Really a box object"); } } // The class to hold these difference classes import java.util.*; class PrintBlock { private ArrayList<PrintObject> printBlock = new ArrayList<PrintObject>(); public void add(PrintObject component) { printBlock.add(component); } public void printMe() { for (PrintObject component: printBlock) component.printMe(); } public void showMe() { for (PrintObject component: printBlock) component.showMe(); } } and I tested it with class TestPrintBlock { public static void main(String[] args) { PrintBlock printBlock = new PrintBlock(); printBlock.add(new LineObject()); printBlock.add(new BoxObject()); printBlock.add(new LineObject()); printBlock.printMe(); printBlock.showMe(); } } Greg Charles Sheriff Joined: Oct 01, 2001 Posts: 2867 11 I like... posted May 16, 2012 11:34:22 0 Looks good to me. I'm glad you got it working! I agree. Here's the link: subject: How to deal with multiple Object classes Similar Threads Problems moving shapes when set up own Shapes class extending Path2D.Double Problem with instanceof Please explain these answers Thread Synchrinization Traps to be aware of in any SCJP test !!!!! :) All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter JForum | Paul Wheaton
http://www.coderanch.com/t/581136/java/java/deal-multiple-Object-classes
CC-MAIN-2015-14
refinedweb
760
55.84
Its the newest book ive found :P . And i cant get getline to worki cant get getline to work i type cin.getline(string) and getline( cin, string) and it says no matching functions for call to some gibberish83424ujrfh candidates are more giberish getline std giberuish Nvm looked it up and copy pasted code and it worked but my code looked the sameNvm looked it up and copy pasted code and it worked but my code looked the sameCode:#include <iostream> #include <string> #include <windows.h> using namespace std; int main() { string theWord = ""; // do not need an array at all cout << "Enter a word to print 1 character at a time: "; cin.getline (theWord); for ( int i = 0; i < theWord.size(); i++ ) { cout << theWord[ i ] << ""; Sleep(40); } return 0; } dont no why it didnt work :Pdont no why it didnt work :P
http://cboard.cprogramming.com/cplusplus-programming/112314-cant-use-function-4.html
CC-MAIN-2014-41
refinedweb
142
74.02
#include <YTreeItem.h> Item class for tree items. This class implements children management. Constructors for toplevel items. Constructors for items that have a parent item. They will automatically register this item with the parent item. The parent assumes ownership of this item and will delete it in its (the parent's) destructor. Destructor. This will delete all children. Add a child item to this item. Note that the constructors that accept a parent pointer will automatically add themselves to their parent, so applications will normally not have to call this function. Delete all child items. Return 'true' if this tree item should be displayed open (with its children visible) by default. Notice that this will always return 'false' for tree items without children. Change the 'isOpen' flag.
https://doc.opensuse.org/projects/libyui/HEAD/classYTreeItem.html
CC-MAIN-2018-05
refinedweb
127
70.19
You can subscribe to this list here. Showing 4 results of 4 On Thu, 25 Jul 2002 pagliar@... wrote: > That's because you don't have the code I checked into CVS about an hour ago :). That bug is fixed. BTW, you may need to prefix the registers with an underscore e.g. _STATUS -- I don't recall at the moment (and I'm not at my development box to verify). Scott WARNING: unable to assemble line: BSF TXSTA,BRGH Bad mnemonic WARNING: unable to assemble line: BCF STATUS,RP0 No registers saved on this pass No registers saved on this pass This is the source code: _______________________________ #include "p16f877.h" #define __16F877 typedef unsigned int word; word at 0x2007 __CONFIG = _CP_OFF & _WDT_OFF & _BODEN_ON & \ _PWRTE_ON & _XT_OSC & _WRT_ENABLE_ON & \ _LVP_OFF & _DEBUG_OFF & _CPD_OFF; void main(void) {//....... _asm BSF STATUS,RP0 BSF TXSTA,BRGH BCF STATUS,RP0 _endasm; //...... } _________________________________ I have same errors compiling Dattalo's "inline.c" source code examples in /src/regressions... Anybody could help? By, Onny. Hi, i have small project with z84c15. I have not found in doc, how to write interrupt handler for z80 cpu. I want use z80 core in mode 2. It is may I am blind... Can anybody help me ?? Thanks Vladimir Holy On Wed, Jul 24, 2002 at 06:17:54AM -0700, Scott Dattalo wrote: > On Wed, 24 Jul 2002, Terry Porter wrote: > > > I've got a problem compiling, and was wondering > > if anyone could please give me a pointer ? > > > > It's been a while since I did any PIC programming, and I'm rusty, especially > > with the Trisb command. > > > > The version is the latest SDCC from CVS and has Scotts most recent (ISR) > > fix. gpsim-0.20.14, and gputils-0.10.3. > > > > I must say that Gpsim has come so far since last I looked, and it > > really rocks! > > Thanks Terry. gpsim, btw for others, is the gnupic simulator. Most of the > "it rocks" part is due to Ralf Forsberg enhancements in the gui. Scott is too humble, for a start I can now compile without readline probs, and gpsim is the coolest without the GUI, otherwise how could we poor PIC designers simulate our unworthy code :) > > <snip led.c> > > > > > This is Scott's standard example file, and its unmodified. > > > > I get the following error :- > > > > > > > > sh-2.05a$ make sim > > sdcc -S -mpic14 led.c > > printIvalChar > > No registers saved on this pass > > No registers saved on this pass > > gpasm -c led.asm > > led.asm:500:Message [302] Register in operand not in bank 0. > > Ensure bank bits are correct. > > This is no bug. It's a nuisance warning from gpasm (which in this case is > immitating exactly the nuisance warning you get from MPASM). > > I personally ignore these. However, there is a command line switch in > gpasm that will allow you to warning messages. You can individually select > which message to ignore. I don't recall the command line option off > hand... Warnings don't bother me, as I get a lot when compiling my C code for x86. > > > > > ........................... led.asm............................ > > ; TRISB = 0; > > CLRF _TRISB << line 500 > > BCF _STATUS,5 > > And there's probably a "BSF _STATUS,5" a few lines up. So there is:- _main ;Function start ; 2 exit points BSF _STATUS,5 ;#CSRC led.c 64 ; TRISB = 0; CLRF _TRISB BCF _STATUS,5 > The BSF/BCF are > switching the register banks. Take a look at the 'f877 memory map in the > data sheet. You'll see that TRISB and PORTB have the same lower 7-bits in > their addresses. The upper two bits are selected by RP0 and RP1 in the > status register. You (or SDCC in this case) need to set these upper bits > appropriately so that the proper register is accessed! What gpasm is > telling you in the warning, is that the address of _TRISB (which is 0x86) > is greater than the 7-bits allotted in the CLRF instruction. I thought that was the case, however gpsim wouldnt run, and like a moron I assumed that the code wasnt compiled. Sometimes when I don't get something I *really* don't get something. I've just run the code in gpsim manually without using your "led" example makefile and its working perfectly! Thanks again Scott, I must say the SDCC PIC support has a rock solid feel to it. Does its support the PIC16C/F84 at all ? Although the chip is depreciated, I've a couple here and would like to try some test code on my r&d setup. -- Kind Regards from Terry My Desktop is powered by GNU/LinuX, Sorcerer kernel 2.4.17 Free Micro burner: ** Linux Registration Number: 103931, **
http://sourceforge.net/p/sdcc/mailman/sdcc-user/?viewmonth=200207&viewday=25
CC-MAIN-2015-40
refinedweb
774
74.9
Mark Brown Tuition Physics, Mathematics and Computer Science Tuition & Resources Random numbers, order and choices Posted on 01-10-18 in Computing Python has many useful standard libraries - Today we will look at the random module. Whether it's generating data to test our code or creating a machine player for a simple game, random numbers end up being rather useful. In this article we'll look at three uses of randomness. Random numbers, randomising order and random choices. Randomness Firstly we need to point out that computers do not generate random numbers! Consider the following example from random import seed, randint repeats = 3 for _ in range(repeats): seed(1) # arbitrary bad seed for _ in range(20): print(randint(1, 20), end=", ") print("") For me this outputs >>> 5, 19, 3, 9, 4, 16, 15, 16, 13, 7, 4, 16, 1, 13, 14, 20, 1, 15, 9, 8, 5, 19, 3, 9, 4, 16, 15, 16, 13, 7, 4, 16, 1, 13, 14, 20, 1, 15, 9, 8, 5, 19, 3, 9, 4, 16, 15, 16, 13, 7, 4, 16, 1, 13, 14, 20, 1, 15, 9, 8, What's important to spot here, is the repetition each time the seed is reset. This is worth bearing in mind if you desire greater randomness than what is essentially a weird sequence. In Python if no seed is specified then an OS-dependent value is taken. In short - bear in mind there are no true random numbers here but they are typically good enough for many cases we come across! Random Numbers To begin let us generate a random number using random(). This will create a random number between 0 and 1. from random import random value = random() print(f"The value to two decimal places is {value:.2f}" If you're unsure how the format argument works have a look at my post on formatting. Note how we import the function random from the library random. If we wish to see what the library contains we can use import random help(random) This will output a lot of helpful text! If we only want help on a specific function we can import random help(random.random) This will give us the output >>> Help on built-in function random: random(...) method of random.Random instance random() -> x in the interval [0, 1). Let's use a different function from random. For example, let's create a random bearing from random import uniform random_bearing = uniform(0, 360) print(f"{random_bearing:05.1f} Degrees") This may print out >>> 004.6 Degrees Let's say we don't want all numbers, just integers. For that we can use randrange. The arguments are the same as range, so from random import randrange randrange(10) # random integer between 0 and 10 randrange(0, 100, 25) # chooses randomly from 0,25,50,75 Another similar function is randint. This includes the end value and does not allow us to perform steps. For example from random import randint def sum_of_dice_rolls(n=1, lower=1, upper=6): """ Sum of n dice rolls """ if n > 0: return sum([randint(lower, upper) for _ in range(n)]) else: raise ValueError('Invalid number of dice rolls!') for n in (1,2,3): print(f"From {n} rolls you rolled a total of {sum_of_dice_rolls(n)}") may give >>> From 1 rolls you rolled a total of 5 From 2 rolls you rolled a total of 10 From 3 rolls you rolled a total of 17 Picking Items Randomly Let's say we want to pick other things randomly, like say names out of a hat. For this we can use the choice function. from random import choice names = ('Bob', 'Jerry', 'Mary', 'Francis', 'Jill', 'Barbara') random_name = choice(names) print(f"It is {random_name}'s turn!") Will potentially give >>> It's Barbara's turn! If we wish to choose multiple cases we can use from random import choices names = ('Bob', 'Jerry', 'Mary', 'Francis', 'Jill', 'Barbara') for random_name in choices(names, k=6): print(f"It is {random_name}'s turn!") this (potentially!) outputs >>> It is Jerry's turn! It is Bob's turn! It is Mary's turn! It is Jill's turn! It is Jerry's turn! It is Mary's turn! Here we can see that some names are repeated. This might be okay for our use case but it won't be helpful if we wish to pick everyone just once! Therefore we can use the sample function. This will pick k options as before but won't repeat. from random import sample names = ('Bob', 'Jerry', 'Mary', 'Francis', 'Jill', 'Barbara') for random_name in sample(names, k=6): print(f"It is {random_name}'s turn!") For further reading, go to the Random reference page. For the remaining part of this article, we will out list a few example uses of the random library. A Random Password One common example is to generate random strings. Here we import four groups of symbols and we will randomly select from these. We will randomly choose a group and then randomly choose a symbol from that group. Here is our code. from string import ascii_lowercase, ascii_uppercase, punctuation, digits from random import choice options = (ascii_lowercase, ascii_uppercase, punctuation, digits) length = 12 new_password = '' while len(new_password) < length: new_password += choice(choice(options)) print(new_password) will produce something like >>> 3}z(vvmeO~L3 extension - Alter the above code to select a specific number of each kind of characters. Eg 3 uppercase, 3 lowercase, 2 numbers and 2 punctuation. - Alter the code to produce passwords based on a pattern. Eg nu3p5* would mean number, uppercase, 3 punctation and 5 anything. Turtle - Random Motion Turtle is a great little tool for using Python to move a virtual turtle about. Here's a couple of simple programs! import turtle from random import choices dim = 100 turtle.setworldcoordinates(-dim, -dim, dim, dim) bob = turtle.Turtle() while True: x,y = choices(range(-dim, dim), k=2) bob.goto(x,y) turtle.exitonclick() will produce something like Here we have generated random coordinates for the turtle to move to each step. Another example! import turtle from random import random turtle.speed(10) prob = 0.5 step = 10 angle = 60 while True: turtle.forward(step) if random() > prob: turtle.left(angle) else: turtle.right(angle) produces Here we have used random() to ensure that we turn left the same number of times as turning right. In this way we produce a randomised honeycomb pattern. Rock Paper Scissors I'll discuss implementations of this game in further detail in another post, for now let's look at getting input. We need methods of getting player and computer choices for the game. Here's one way to this from random import choice moves = ('rock', 'paper', 'scissors') def computer_choice(): global moves return choice(moves) def player_choice(): global moves while True: print("Valid moves are", *moves, sep="\n", end="") player_move = input("Please enter your move >>").lower() if player_move in moves: return player_move else: print(f"{player_move} is an invalid option, try again!") Here there a few things to note. Firstly see how we have used the choice function to select a random move for the computer. Secondly we have kept moves outside both functions. This is so if we wish to expand the game later, we only have one variable to change. Finally note that we have written the player_choice() function to prevent an invalid option being presented! Battleships As a final demonstration, I include a crude example of a computer playing batteships. In battleships we want the computer to find all the ships we have hidden. Ideally we want the computer to visit every tile just once. Furthermore we want the computer to guess adjacent tiles if the computer does in fact get a hit Here's a gif showing my implementation Here red squares indicate misses and green indicate hits. Extensions - Get the computer to focus on a particular axis (horizontal or vertical) once its clear what direction the ship is facing. - Prevent the code from generating ships that overlap. - Add a human player! import turtle from random import shuffle, choice, random dim = 250 # dimension of our screen L = 25 # size of a box turtle.setworldcoordinates(-dim, -dim, dim, dim) def draw_square(tl, x, y, L, fill=False, col='red'): """ Draws filled square at x,y location with side of L if fill is True the box is filled with colour 'col' """ tl.penup() tl.goto(x, y) tl.pendown() if fill: tl.color("black", col) tl.begin_fill() for side in range(4): tl.forward(L) tl.left(90) if fill: tl.end_fill() tl.penup() tl.goto(x,y) bob = turtle.Turtle() bob.speed(10) ## Generate all possible box locations locations = [] for x in range(-dim, dim, L): for y in range(-dim, dim, L): locations.append((x,y)) shuffle(locations) # Computer will visit all locations randomly def new_ship(length=3): """ Generate location of ships Code checks if both front and end of randomly placed ship is on screen if so it returns this TODO : does not currently check if intersection with existing ships """ ship = [] global locations x,y = choice(locations) # Front of ship! while len(ship) < length: step = choice((-1, 1)) if random() > 0.5: # randomly choice horizontal or vertical ship end_x = x + length * step * L if (end_x, y) in locations: # Only allow valid end position for loc in range(x, end_x + 1, step*L): ship.append((loc, y)) else: end_y = y + length * step * L if (x, end_y) in locations: for loc in range(y, end_y + 1, step*L): ship.append((x, loc)) return ship ships = [] for j in range(2, 8): ships += new_ship(j) while locations: x,y = locations.pop(0) # get next guess from front of queue if (x,y) in ships: col = 'green' to_shift = [] for index, (new_x, new_y) in enumerate(locations): if new_x in range(x-L, x+2*L, L) and new_y in range(y-L, y+2*L, L): to_shift.append(index) # Places all adjacent tiles at the front of the queue for index in to_shift: locations.insert(0, locations.pop(index)) else: col = 'red' draw_square(bob, x, y, L, True, col) turtle.exitonclick() Enjoy!
https://markbrowntuition.co.uk/computing/2018/10/01/random-numbers-order-and-choices/
CC-MAIN-2022-33
refinedweb
1,689
64.51
Demise of C++? 271 fashla writes "Several somber and soul searching threads have been recently posted to the USENET newsgroup comp.lang.c++ such as "C++ is Dead" and "A Dying Era". The reason for this reflective mood is the sudden demise of the magazine C/C++ Users Journal (CUJ) that had been published by CMP Media. Participating in the posts have been such C++ luminaries such as Bjarne Stroustrup and P.J. Plauger. While some contributers think that CUJ's demise is due to the general trend away from print, others think something else is afoot..." Balkanization (Score:5, Interesting) Though it were hard for me to imagine, for instance, Unreal [wikipedia.org]'s engine being ported to Java, Quake [wikipedia.org] seems to have fared well with feral C. Re:Balkanization (Score:3, Informative) Re:Balkanization (Score:3, Insightful) Is that the same C# that a friend uses, which apparently requires 12 bytes of memory to store a single 32-bit integer? If that's accurate, then I don't think C++ has much to fear from C# in its natural areas of strength... Re:Balkanization (Score:2, Interesting) Of course I always figured this was just my weirdness, I never realized anyone else felt this way about it. I sure don't miss those retarded C++ references and stream operator overloads. Re:Balkanization (Score:3, Insightful) Re:Balkanization (Score:2) Re:Balkanization (Score:5, Informative) Re:Balkanization (Score:2, Insightful) Re:Balkanization (Score:3, Insightful) My personal opinion has always been one of pragmatism instead of zealotry; pick a language based on the task. It has been said by knowledgeable people that the benefit of OO over procedural is not theoretical performance but rather the practical performance. OO techniques typically allow one to better understand large problems and thereby create better solutions. Ofcourse, ree Re:Balkanization (Score:5, Insightful) But v-tables are only created when virtual functions are used in classes, and only then. If no virtual functions are used then a C++ program can use static linking the same as for a C compiler. Given that C++ compilers are also defined to be C compilers, then for any given C++ compiler (and no virtual functions in the C++), C and C++ code should run at the same speed. Now if you want to compare *different* C and C++ compilers, that is a seperate matter. If you are interested in the inner C++ workings I can suggest any of the Scott Meyers books. Other people can probably suggest other authors as well. Re:Balkanization (Score:2, Informative) So what is going on here? cout << "Hello World!" << endl; The above code uses V-tables, and the above code is what is recommended by C++'s "inventor". The above is slower and produces more machine code than: puts("Hello World"); Period. Supporters love to say that's a bad use of C++, or that the compiler could recognize this special code, or that the compiler should do some kinds of deep inlining at compile-tim Re:Balkanization (Score:4, Informative) What I was saying was that the C code will run the same if it is compiled under a c++ or c compiler, whereas a lot of people thought that c++ automatically inserted v-tables and hence was presumed to be slower. You example is flawed as you are comparing apples to oranges. The use of stream insertion will bring in all sorts of crap into the equation while "puts" will not. Hence your "puts" will run faster. (But try and overload your puts example to output custom data on a generic class by class basis and see how much extra code you have to add). Once you start using feaures of one language that are not implemented in the other, then simple speed comparisions go out the window. Re:Balkanization (Score:2) I effectively started talking about the speed of C and C++ statically linked code being the same with all things being equal. But (as I saw from another of your posts) you actaully were ripping Bjarne for stating that stream insertion is the same speed as puts. Now that is something I totally agree with. But it is still apples vs oranges as puts only has a fraction of the funct Re:Balkanization (Score:2) Absolutely not. I am comparing two distinctly similar things: The accepted authoritative methodology that is C++ versus the accepted authoritative methodology that is C. That difference methodology has produced rumor mills similar to the ones you have heard (about all functions being invoked through indirection)- but it isn't the difference in implementation. Consider that Objective-C uses a large amount of message passing, but there's no confusion what Re:Balkanization (Score:3, Interesting) No matter what else it does the slow part is entering kernel mode and printing characters to the screen. You are discussing a 20ns optimization on a 1ms call. Re:Balkanization (Score:2) argument. You should apply to work at Microsoft. Re:Balkanization (Score:2, Interesting) Re:Balkanization (Score:2) justification in saying "well the API/syscall is slower than anything I can write so I won't bother" because what happens if 2 years down the road someone speeds that API up 10x and then your code is recompiled and *it* becomes the bottleneck? Re:Balkanization (Score:2) Rules of optimisation: 1. Don't 2. (Experts Only) Don't Yet! This is the path of true wisdom (Score:2) Re:Balkanization (Score:2) Re:Balkanization (Score:2, Redundant) puts() isn't a system call on UNIX. I don't know what Operating System you're referring to. What's being compared and discussed is the authority of C++: Bjarne repeatedly states this is the way to go, and that it is not slower nor larger than in C. Bjarne is extremely confused on that point. No matter what else it does the slow part is entering kernel mode and printing characters to the screen. No it isn't. Profile it and see for yourself. You are discussin Re:Balkanization (Score:4, Interesting) OK. puts is faster. But I hate to break it to you, compared to cout, puts sucks. puts is error prone in a way that cout is not. More appropriately, cin is far, far superior to get and all those derivatives. cin, cout and cerr, are slower, have more overheads, take more space,etc, etc. I still prefer them. Why? Because they're safer. Not totally safe, but leauges safer than the equivilent c functions. On top of that you can overload cin. Some people do screw this up, but being able to write: while(cin >> Big_Complicated_Object){ } Is very sweet. C can only offer me this with hacks that will freeze thy young blodd etc, etc, etc. I don't find C++ too bad. The compilers are OK, and I don't abuse the language features. I'm an OO kind of guy, and I like decomposing my programs. C++ lets me do this in a way C cannot. Re:Balkanization (Score:2) Accepted. compared to cout, puts sucks. You've admitted puts is better than cout in at least one way. In any event, this thread is not about whether C++ is better or worse than C, it's about whether rumors about performance and size penalties in C++ are justified, and in many cases it appears the answer is yes. On top of that you can overload cin. No you cannot. std::cin is a global variable. You can overload >> in the class istream but that's not the same thing at all. I like decomposing Re:Balkanization (Score:2) That's what's known as overloading streams, which is what cin is. I have no idea what you mean by "decomposing" your programs. Specifically, using object orientation and functional blocks to make everything simpler. i.e. not having a 40,000 line app in one file. C++'s big advantage is that I can do all this without using macros. C++'s big disadvantage is having to use pointers to d Re:Balkanization (Score:2, Insightful) Re:Balkanization (Score:5, Informative) No, it doesn't (or at least shouldn't with a decent compiler). I have compiled the following code: #include <iostream> int main() { std::cout << "Hello, World!" << std::endl; return 0; } with G++ 3.3.1 on x86 (and pretty standard options: "-ansi -fomit-frame-pointer -O2") and the results for the "main" function where the following: main: .LFB1550: pushl %ebp .LCFI0: movl %esp, %ebp .LCFI1: pushl %edx pushl %edx andl $-16, %esp pushl %eax pushl %eax pushl $_ZSt4endlIcSt11char_traitsIcEERSt13basic_ostrea subl $12, %esp pushl $.LC0 pushl $_ZSt4cout .LCFI2: call _ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_E addl $20, %esp pushl %eax .LCFI3: call _ZNSolsEPFRSoS_E leave xorl %eax, %eax ret [".LC0" is the string "Hello World"; warning: As you can see it's exactly what you can expect, with only two *direct* calls. Granted the "puts" version requires only a single call, but only because here the output is split in two parts, first the "Hello World" and then the newline. Hope this helps the discussion. Re:Balkanization (Score:3, Informative) Sorry to reply to myself, but if anyone finds the above x86 assembly code difficult to understand, the equivalent C source code is: where f1 and f2 are provided by the standard library, in the basic_ostream class (f1 returns its first argument, cout). Re:Balkanization (Score:2, Informative) Note the jumps into the plt pages looks like this: 0003afb0 <_ZNSo3putEc@plt>: 3afb0: ff a3 0c 02 00 00 jmp *0x20c(%ebx) 3afb6: 68 00 04 00 00 push $0x400 3afbb: e9 e0 f7 ff ff jmp 3a7a0 <CXXABI_1.3+0x3a7a0> Disassembly below: 0007d9f2 <_ZSt4endlIcSt11char_trai Re:Balkanization (Score:3, Informative) The above code uses V-tables, and the above code is what is recommended by C++'s "inventor". The above is slower and produces more machine code than: No, the above does not use virtual functions/operators, and hence it does not use a v-table. After all cout is not a pointer anyway!! So even if operator << would be virtual, it would be called directily without v-table. The above is slower and produces more machine code than: puts("Hello World"); If its to slow on y Re:Balkanization (Score:3, Insightful) Re:Balkanization (Score:4, Funny) I love it... when will GCC be supporting it? Java is dying too (Score:2) The thing we are shifting twords doesn't exist, but is being created slowly as we advance our programming languages. We need a nice pla Re:Java is dying too (Score:2) Re:Balkanization (Score:5, Interesting) And just a few days ago I was reading on slashdot about Java/C# falling in between C/C++ for low-level systems programming and the "dynamic and/or scripting" languages for highest productivity (e.g Perl, JavaScript, Python, PHP, Ruby, Haskell). Re:Balkanization (Score:2, Informative) Unreal's engine being ported to Java? (Score:2) Anm Re:Balkanization (Score:2) From my point of view (Score:4, Insightful) The problem with C++ is that it is neither as simple as C nor has it the benefits of Java and C# as they allow for code that is easier to read and understand. The available tools are also better for the competing environments on the upper side. C is still developing features at a slow but steady pace and it has inherited a few from C++. There will probably be more features inherited in the future, which will cut more into the area of C++. The difference between C and C++ is that C isn't object-oriented while C++ supports object-oriented design. But object-oriented design is not necessarily needed at the low-level programming that is used when accessing devices and similar operations, and hence C will be the choice of such programming. Re:From my point of view (Score:5, Insightful) You're way off. So far that I'd say you've never read or written modern C++ code. There's a lot of metaprogramming. Look into templates sometime. Try out the STL and the boost libraries [boost.org]. There are significant C++ programs that are not object-oriented and would be nearly impossible to duplicate in C with the same kind of efficiency. I find C++ to be an ugly, ugly language, but it's also a lot more than the "C + classes" that it used to be. Re:From my point of view (Score:2) Don't talk to me about Boost (Score:2) language. If I wanted a different language I'd use one. Plus it tends to be a solution for problems that don't exist. "would be nearly impossible to duplicate in C with the same kind of efficiency" BS. Unless you think theres some sort of magical assembly language that a C++ compiler can generate than a C compiled couldn't. Re:From my point of view (Score:2, Informative) I think "sharp" is not too appropriate... (Score:3, Funny) Re:I think "sharp" is not too appropriate... (Score:3, Funny) I could go for some hashbrowns. Re:From my point of view (Score:2, Insightful) Also, just because C doesn't "support" OO design doesn't mean you can't do it anyway with some discipline. (And no, I'm not talking about rolling your own vtables everywhere. That's OO implementation, no Re:From my point of view (Score:5, Insightful) My experience with C++ and Java is that Java is simpler to get your head around, but can really get annoying once you get going, because of the number of gross hacks and workarounds required to avoid excessive heap allocation. Compared to C, C++ often results in dramatically clearer code, simply because it offers the ability to wrap things with enough syntactic sugar that it makes source code much more concise. However, taking advantages of C++'s strengths requires some discipline, and requires programmers to understand what's going on to some degree, and as we all know, the great majority of programmers are idiots. I suppose in the end, the best progamming language for idiots will win... Re:From my point of view (Score:5, Interesting) I got over my dislike of C++ about two days ago when I decided to use Qt to do some programming, which pretty much forces you into C++. I was really shocked at how unpleasant it *wasn't*. I've had some really bad experiences with Java - a lot of "model" is forced down your throat. Using C++ felt very natural, and I noticed a huge number of really nice touches that are quite cheap, because they're done by the compiler, but that (a) make your coding less error-prone, and (b) are just horribly convenient. So my point here is that if you've been hearing for years that C++ isn't worth your time because it's object oriented or because it's just C warmed over, neither of these statements is true. I'm embarrassed to have ever repeated them (sad to say, I have done so in the past). I really don't think C++ is on the way out. My main complaint about it at this point is that g++ is too verbose when I use an overloaded function that doesn't exist - it prints a list of all the possible candidates, which can get quite long. I don't think that's a capital crime, though. Re:It will be a happy day... (Score:2) do low level programming I want memory to be free'd when *I* request it, not when the runtime (which would be extra overhead too) thinks it should be done. The problem is C++ is trying to be all things to all men, as low level as C and as high level as something such as python. Problem is what you end up with is a rather unsatisfying smelly stew. Re:It will be a happy day... (Score:2) Re:It will be a happy day... (Score:3, Interesting) While D certainly has some good points, I'm not entirely certain that even Walter Bright is certain it's entirely ready to take over as the premier language. Since you posted as AC I don't know if you read or participate on comp.lang.c++[.moderated] on a regular basis, but if you've been following all the threads, you'll notice where DbC is being discussed, and D is being used as a prime example of how to completely screw thin C++ Dying? (Score:5, Funny) Nah (Score:5, Insightful) What we are noticing today is that programming languages alone just don't cut it anymore. The software is so advanced, that standard language constructs and libraries are way too raw to be applied to something useful for the average application programmer. Knowing frameworks, APIs and libraries is becoming a lot more important than using all the language paradigms and hidden tricks. I think C++'s user base is splitting: On one hand there are the library and API developers, for whom the standard and the language are wholy. On the other hand, there are the application programmers, who care about the practical side of the language; they use it because it has advantages over other languages and has lots of libraries written for it. My belief is that C++ is more alive today than ever. It is more powerful than ever. And it will be for a long time (in technology terms, indeed). Of course, in 10 years time it won't be recognizable. But it's wrong to say that C++ is dying. Widely used languages don't die quickly (Score:3, Insightful) ge_economics.html [dedasys.com] ( although my hosting provider's network seems to be running a bit slow:-/ ) Re:Widely used languages don't die quickly (Score:2) We just got tired of being insulted (Score:5, Insightful) translation: LA LA LA LA, LA LA LA LA (Score:3, Insightful) C++ is kind of a monster of a language (almost as bad as Perl), but it is one of the few I'd choose for the niche where speed/space really count. Unfortunately for C++, there are very few programs for which this is the appropriate niche. Most of the C++ that crosses my desk should have been written in an appropriate scripting language (insert your favorite, Python's currently mine). I even heard a tale of someone writing a "makefile" in C++ (gawd). These mistakes cost a lot of time and money. My b Re:translation: LA LA LA LA, LA LA LA LA (Score:5, Insightful) The RAND corporation says that more than 70% of all software is embedded software. Embedded as an industry is almost universally C++. Please do not confuse being in a different branch of the industry with a branch of industry simply not existing. Re:We just got tired of being insulted (Score:2) You, you use C++, which may be on somewhat of a decline thanks to its children Java and C#, but is still considered a "real language". Re:We just got tired of being insulted (Score:5, Insightful) We're just plain tired of giving the same answers to the same people who never listen and carry on regurgitating the same crap they heard from some uninformed idiot. There's one thing that's very obvious from the numerous appearances of C++ on Slashdot recently: very few of the readers here have actually used C++ in any serious way. You're only hurting yourselves when you dismiss C++ out-of-hand for uninformed reasons. Magazine quality (Score:4, Informative) I don't know about any subversive anti C++ group that is plotting the downfall of this language, but I was taken aback last week when I received the next issue in my C/C++ Users Journal subscription that had a letter attached to it saying that it was the last issue ever. This pissed me off as you don't just dump a magazine like a hot potato, you track the way it is selling and you say "well What also annoyed me about it was that the publishing company will transfer my exisiting subscription over to Dr Dobbs (though I can get my money back). Personally I feel that Dr Dobbs took a major nose dive years ago and is in no way of the same quality as the C/C++UJ. The transfer from glossy to newsprint style paper showed that they were needing to make cost cutbacks which implies to me that they were losing it in general. But what really took the cake was an article printed in the Dec 2005 issue where in a DB app, presentation was confused with storage in a manner befitting a failed CS101 assignement. While I gagged at the article itself, what shocked me even more was that the Dr Dobbs editors actually included it for publication. (As I blame the editors, I am not directly pointing to the article itself). C/C++UJ said in their cover letter that they will be expanding Dr Dobbs to take on a lot of the content from the C/C++UJ. Personally I think that Dr Dobbs may be too far gone for this sort of recovery, and that I have lost a magazine that I liked, was to the point and generally full of quality (though other people may say I am blind about this). I may give Dr Dobbs the chance to show that it has improved, but I won't be holding my breath for very long. [/rant] C++ : to remove yet another sucky java app. (Score:2, Insightful) The initial Java implementation had too large a system footprint (we required it to run on fairly low spec machines with limited resources). The rewrite in C++ ran smaller, faster, and without the Java "slow to load and start" TM. The trade-off for the re-write was the longer development cycle. Overall, we don't see C++ dying, but as a great tool, which still has it's place. Netcraft (Score:5, Funny) Less C++, more Ruby (Score:4, Interesting) I feel sad about not using C++ more often though, because it really was my favorite language for a long time. I just can't think of any project idea I have where C++ would be better suited than Ruby. Print is in a coma... (Score:2, Insightful) Re:Print is in a coma... (Score:2) A print magazine is better suited. Consider how many minutes you spend there. If you don't spend long periods of time there, then a general print magazine (Newsweek, Time, etc.) may be the best. I'm certianly not planning to read something that is lengthy, or requires really deep thinking for an extended period. Hint: I don't even use a print magazine. I pull out my... depends on who you work for... (Score:2, Insightful) The clearest sign that C++ is a dead end: (Score:3, Funny) Anything Apple uses - *must* be a dead end. Video Games (Score:3, Interesting) Re:Video Games (Score:2) Well, Java is getting faster with each release, and game engines keep on getting more complex. At the same time the mainstream PC world is slowly starting to mov C++ not dead, but it is a dead end (Score:2) Call it what you will - the need is there and Re:C++ not dead, but it is a dead end (Score:2) It didn't need to be, though. Objective-C is simple enough that a C programmer can learn it in a weekend, yet it also allows object oriented programming, and supports dynamic programming better than C++ does. In todays hasty world... (Score:5, Funny) Death by subscription? Please. (Score:5, Insightful) So, I don't think that C++ is going anywhere because the journal is going away... I think instead people who are using C++ will go elsewhere for information about C++. No story here... move along. Re:Death by subscription? Please. (Score:2) And if you dig into one of the threads thats excatly what P.J.Plaugher says he does more and more now C/C++ dying? What are they smoking? (Score:3, Insightful) IMHO, C/C++ is far from dying. It's getting stronger than ever atleast in the realm of software engineering. I see it finding it's nitch closer to the hardware and in core of advanced software where speed and optimization is important. Like, you wouldn't write a 3D game engine in java, atleast not yet anyway. Look at KDE what is it written in? and Unreal? What is the JVM itself written in? and I still see that software engineers are still using it heavily where as the rest of us mortals in the business realm, develop in other interpreted languages that can offer faster development time. Cost is everything, we programmers are no longer seen as an asset but more as a cost. Java and Lamp programmers are just cheaper. I find it very unfortunate that schools are no longer teaching C++ and switching to Java. The end result is a more limited amount of advanced C++ programmers out there working on very important advanced applications. Re:C/C++ dying? What are they smoking? (Score:3, Informative) Dunno what you mean by "advanced software", but C has its place when programming near hardware. C++ will hopefully die and take buffer overflows and memory leaks with it. Quake 2 [sourceforge.net] remade in Java Re:C/C++ dying? What are they smoking? (Score:5, Informative) BWA hahahahah That's pretty funny, pointing out that C++ has buffer overflows and memory leaks when compared with C. Especially since C++ has vastly better techniques for dealing with those particular problems. Ahem. But seriously, there is absolutely no reason why properly-written C++ can't be precisely as efficient as straight C, and as an added bonus, you get a more strongly-typed language with extra features. I've been writing in C and C++ for close to 20 years, and C++ is just plain a better language than C. Sure, it has some crazy warts and dangerous bits, and things that can be problematic if you don't know what you are doing... but I submit to you that if you don't know what you are doing, you need to find another line of work. Sure, other languages are definitely better in some scenarios -- it's all about using the right tool for the job! -- but for "close to the machine" work, you need a language like C or C++, and frankly, I can't understand why anyone with sufficient programming experience, and a real working knowledge of both languages, would voluntarily choose plain C over C++. Re:C/C++ dying? What are they smoking? (Score:3, Insightful) In an anecdotal way, a relatively mature and competent C programmer could take a good shot at implementing a C compiler and come away with something pretty close to the real thing, because C is, well, simple, and consistant. C++ on the other hand -- it's so Re:C/C++ dying? What are they smoking? (Score:3, Informative) The compiler allocates memory behind your back, and as a result the programmer has no direct means by which they can free that memory. Buffer overflows are trivially avoided in C, and in my experience (of looking at other peoples' C++ code) they seem to be as common, if not more common. But seriously, there is absolutely no reason why properly-written C++ can't be precisely as effi C++ is more like Perl... (Score:5, Insightful) But what I've told people again and again is that *you* don't have to write it that way. Don't understand multiple inheritence? Fine...*don't use it*. Don't get templates? Fine...*don't use them*. We still use VC6 and its template functionality isn't even complete! The truth is, you can have bizzare WTF moments in *any* language. A lot of what people attribute to the failure of a language is the failure of a programmer to properly explain what his/her code does in a straightforward way *using the code itself*. The best code is clean and concise and C++ gives you as much opportunity to do this as any language. Sure you can have multi-thousand line functions in C++, but this isn't a failure of the language to somehow magically break it apart for you into better organized bits, it's a failure to understand that a language, *any* language, whether purely written or even spoken, is to convey a message, a story, and without careful attention to detail, can become an unholy mess (like this post). Whatever. (Score:5, Insightful) Among all the programming languages I've used over the last 25 years (6502/6809/m68k/... assembly, Prolog/Miranda/... functional, Perl/Tcl/Python/Lisp/Java/... interpreted, C/C++/PL-1/... compiled), only 2 really stand out as "excellent" tools: C++ and Python. I really have to struggle picking which one I love to write programs in more. They both have their place, and they are both lovely in their own way. As far as C++ goes, since it exposes all the "knobs and dials" of the underlying computing architecure, it does have a very long learning curve. However, Template Metaprogramming is unlike anything, available anywhere, in any other language. Listening to all these Java/C# fanboys flame C++ templates, and compare them to "Generics" etc., is like listening to guys compare their cool Ox-Cart wheel mods, while saying how much that new-fan-dangled "ferr-ar-eee" Sucks... Yes, it took *years* for me to master C++. Someone smarter, and/or with better (read: any) instruction would -- and should -- do better. But, being able to express an algorithm purely, which will compile efficiently to process *any* type(s), stored in *any* container, accross *any* architecture, with full static type checking and bare-metal hand-coded assembly language efficiency, is something truly unique in the programming language world today. When some other language comes out with something better and more efficient than Template Metaprogramming, let me know. 'Til then, its C++, baby! Re:Whatever. (Score:3, Informative) Re:Whatever. (Score:2, Insightful) However, Template Metaprogramming is unlike anything, available anywhere, in any other language. Thank god for small favors. Templates are great, they do what they are supposed to, which is to all for more generic programming. Template meta-programming otoh is an evil movement to half-ass add features to a language that doesn't have them. If you want Lisp macros, please by all means use Lisp. But don't take something good (type-safe generic programming) and turn it into a tool for evil. Yech, you're proba What's really wrong with C++: denial (Score:4, Insightful) C++ is the only remaining major language which has hiding without safety. C has neither. Java, C#, the Pascal/Modula/Ada/Eiffel family, and all the scripting languages have both hiding and safety. That lack of safety is responsible for most of the crashes and exploits in today's software. When a virus takes over your machine due to a buffer overflow, it's probably because of that bad design decision in C++. Every day, hundreds of millions of people must suffer because of that mistake. The largest single problem comes from the decision in C to treat a pointer and an array as the same thing. This seemed convenient thirty years ago, but created a language in which the size of an array is not permanently associated with the array. In particular, the fact that arrays are passed to functions without size information is a huge source of trouble. This, of course, is why we have buffer overflows. Attempts were made in the STL to fix this problem, but it didn't really work out. Trying to retrofit strings to the language via the template mechanism was not all that successful, since so many libraries and system calls required the old-style strings. Safety is not a performance issue. It's possible to do checking very efficiently, if the compiler knows what to check. Subscript checks can usually be hoisted out of inner loops at compile time. But this is not possible for C++, because the subscript checking, when enabled, is in the STL, not the language. The second big problem in C++ is the need to obsess on "who owns what". Memory allocation is the nightmare of C++. Again, the STL tried to address this, and again, it was botched. The auto_ptr debacle illustrates the limitations of the language. There have been many, many attempts to implement "smart pointers", and they're all unsafe. At some point, you have to extract a C-type pointer to get something done, which introduces a hole in reference counting. If you don't extract raw pointers, you spend too much time updating reference counts. Again, this is something that a compiler could optimize if the compiler knew more about what was going on. But with reference counting implemented at the macro level of templates, that's not possible. Garbage collection is occasionally proposed as a panacea, but it's not compatible with the concept of destructors. In a garbage collected language, what destructors and finalizers do must be severely limited. This is contrary to the C++ concept of "resource allocation as initialization". You don't want to close a window from the garbage collector. Also, introducing garbage collection introduces a form of concurrency, in a language that doesn't handle concurrency well. There are workarounds for this, but like most workarounds, they're painful. Take a good look at how Microsoft's "Managed C++" approached the problem. It's wierd; read about "resurrection [c-sharpcorner.com], where an object comes back to life during garbage collection. Those are the two elephants in the living room of C++. Denying them will not make them go away. This is harsh. But it's not wrong. Leadership (Score:4, Interesting) talking about them being dead and that was one of the better moves I've made in the stock market... I imagine all the Sun people are really concerned too; they're as good as dead. I suspect redbull is killing coke too, they are probably dead. I like C++, I like the idea and the intent. After spending like 10 years going through standards processes, I actually like the end product and the STL and what have you, it's substantially more clean that it was in 1991. I think they got a good 80% of the way there. There is still some jankiness though. I think the thing with C++ that is larger is that they are still old world. There is no quick movement and there still isn't any "21st century" development style in the standards group. Java has warts but one of the great things it has going for it is Sun produced a lot of standards and then the jakarta group did the same and there tends to be a lot of similarity between "high quality" java products and components. There is a ton of java stuff to reuse and the code tends to be be laid out in a similar way, built in a similar way, javadoc is used, xdocklet is used, etc.. C++ doesn't have any of these standards working for it and there aren't any major projects (maybe KDE and QT) that are really sort of laying out the guidelines and building reusable components. In short, nobody is really showing everyone else "how to do it." I think that alone has accellerated java at a remarkable rate. Beacuse of all of that, I don't know of a lot of good high quality C++ reuse. There are some knickknacks that might be reused. Then there is kind of this whole-world style framework, like QT which includes tons and tons of stuff. Simple little libraries don't seem to be popular because there are so many different ways you can use them, different conventions, etc.. Every time you start a C++ project, you're starting over from scratch. The other thing java has helping it is the class library. You cna buy Roguewave or something but there isn't a good opensource alternative. Boost is kind of filling the gap but it's still a little project and I think the scope has stayed fairly small for a lot of reasons, many of which are political. Part of this is the C legacy and the C++ attitude, it let's you do things "your way." And the languages tries not to do "too much" yet it's supposed to compete with higher level languages that are totally tricked out with features and libraries. I think if you were starting a new large scale application project and Java wasn't an option and mono/.net wasn't an option and you were looking at C++, GNAT would also have to be considered (as radical a thought as that is) because I think there might be as much or more high quality reusable componets that you could harvest for it. It just needs a really strong leader and some community built up around it. Define some common framework rules. Write a couple frameworks, if I could just instantiate a socket class (with SSL as a yes/no flag) and create a high performance and high quality C++ server network server in a small chunk of code, in a standard like way, that'd be cool. Imagine that it had some template based policy stuff that allowed me to plugin validators and crap like that and we created a nice reusable network component and started to make some of the security holes in that stuff go away... Simple and clean, reusable. WOuld you write your own server everytime now or would you use this one? Re:C++ has its place (Score:2) I would love Re:C++ has its place (Score:5, Interesting) C++ remains as the only proper object-oriented language. Despite all the years of continuous development in languages, there has yet arisen an overall better object-oriented language. Yes it's ugly. Yes it's cryptic. Yes, it explodes often. But there isn't another language that does things better. C++ the "only proper object oriented language"?!? It started life as a kludged on Modula extension to C. It has evolved into an overly complex language that includes elements of many programming paradigms, but implements all but the procedural ones poorly. The procedural stuff came from C anyway. Objective C is far closer to a "proper" object-oriented language, adding the minimum to C to give it OOP features. Smalltalk itself is the purest OOP language. Java - Oh wow, a language that inherited the syntax from C++. Also completely controlled by a useless business committee. Tack on the JVM and you have yourself a C++ killer! Oh wait... It inherited procedural syntax from C, not C++. The OOP aspects were inherited from Objective C and SmallTalk, along with a class library that owes much to NeXTstep/OpenStep. Gosling and other Sun engineers must have been exposed to NeXT's development platform during the brief Sun dalliance with OpenStep. As for being controlled by a "business" committee, my experience of Java's evolution is that it was largely driven byb engineers at Sun. Anyway, Stroustrup and the ISO committees haven't done a great job with C++. As for being a C++ killer, it seems to be exactly that at my current employer. Our content delivery systems have been rewritten in Java and C, replacing a C++ monstrosity. Our only outsourced application is in the process of being rewritten in Java rather to replace the current C++ version from the same vendor. C++ ain't just dying, it's dead here. C# - Like Java, but worse. Switch the Java committee for a Microsoft one. Switch JVM for .NET. Stupidity for everyone! Although it's just Java for Windows, C# is a much more elegant language than C++. Objective-C - Is it used ever outside of Apple development? Why's that, doesn't development for MacOS X amount to much then? Plus, the Cocoa APIs are far more elegant than the hideous STL abomination. Smalltalk - Nice and pretty. And unheard of outside of the niche. It was ahead of it's time, but obscurity doesn't mean it's a poorer language than C++. Python, Ruby, etc. - Often considered too slow. Only in urban myths. Re:C++ has its place (Score:3, Interesting) Only in urban myths. No, in practical use. Try doing something like image processing in those languages; or (perhaps more realistic) parsing a large XML file with native Python or Ruby code. Now try it in a C++ or Java parser. The difference in speed is phenomenal. Re:C++ has its place (Score:3, Insightful) I've done a lot of XML (and SGML) parsing using toolkits written in C, Perl and Java. The C ones (expat, libxml2 and several commercial packages) were quick, although the nature of XML means that a lot memory allocation goes on. The Java and Perl toolkits behave well because memory is pooled at the userlevel, rather than requiring many malloc calls. Image processing on the other hand, is why the system I mentioned above has some parts coded in C. ImageMagick, using the raw C API, narrowly beats a similar pr Re:C++ has its place (Score:2, Interesting) Stuff like the JVM, Re:C++ has its place (Score:2) Why's that, doesn't development for MacOS X amount to much then? Plus, the Cocoa APIs are far more elegant than the hideous STL abomination. Shouldn't be using STL (Think you meant MFC?) anymore... use Re:C++ has its place (Score:2) Shouldn't be using STL (Think you meant MFC?) anymore... Nope, I meant STL, the standard template library not Microsoft Fried Chicken which is a horrible OOP API on top of a horrible procedural API for an even worse operating system. Besides why would we compare a language that is available on what, 5% of end user machines out there (I think I am being generous) whereas every other language is operating system independant (except for c# - but Microsoft windows has what, 90%+ market share? And the compi Re:C++ has its place (Score:2) Re:C++ has its place (Score:2) Re:C++ has its place (Score:2) Re:C++ has its place (Score:2) Python, Ruby, etc. - Often considered too slow. Only in urban myths. Huh? You had me until you said this. What I meant was, that while on paper interpeted languages like Perl, Python or Ruby should be slower (plenty of runtime type resolution, higher level constructs, etc), in practice things like memory pooling and sophisticated JIT-style interpreters means they are often faster than the equivalent application written in C or C++. To make the most of the potential of C/C++ means expending Re:C++ has its place (Score:2) Rubbish. Nobody ever claimed that Java was the right tool for the same niche as C, ie OSs, device drivers and speed-critical apps. C++ is in this niche, Java isn't. C# - Like Java, but worse I'd be interested to see why you think everyone else is wrong, and C# is worse then Java. Re:C++ has its place (Score:2) C++ remains as the only proper object-oriented language. Really? Lets ask someone else's opinion on the matter:Hmm, I think I'll beg to disagree with your quote. Re:C++ has its place (Score:3, Informative) Common Lisp - Fast nowadays, powerful, flexible, but everyone ignores it.
http://developers.slashdot.org/story/06/01/09/1152215/demise-of-c?sdsrc=prevbtmprev
CC-MAIN-2014-49
refinedweb
7,344
71.44
#include <Kokkos_OskiVector.hpp> Inheritance diagram for Kokkos::OskiVector< OrdinalType, ScalarType >: At this time, the primary function provided by Kokkos::DenseVector is wrapping an oski_vecview_t object and providing access to its entries. Returns a pointer to an array of values in the vector. Extract a pointer to the values in the vector. Note that the values are not copied by this method. Memory allocation is handled by the vector object itself. The getInc() method should be used to access values, especially if getInc() != 1. Reimplemented from Kokkos::OskiMultiVector< OrdinalType, ScalarType >. Initialize using a pointer. This is the only way to initialize a Kokkos::OskiVector object.
http://trilinos.sandia.gov/packages/docs/r8.0/packages/kokkos/doc/html/classKokkos_1_1OskiVector.html
crawl-003
refinedweb
104
51.85
Imagine to signal certain states without polling the device. Well, this article will show you how you can achieve this. A possible solution to this problem is implementing a Web Service on the Windows CE device, but the disadvantage of this technology is that you can�t signal asynchronous events directly from the device (server) back to the client (as long as WS eventing is not supported). Another technology well known today is .NET remoting. However, this technology is currently not available in Windows CE 5.0 and .NET CF 2.0. If you are familiar with COM, you could consider DCOM. Since COM interop is available in .NET CF 2.0, and DCOM is available under Windows CE 5.0, this could be a viable solution. Agreed, the server needs to be implemented as a COM server, but all clients � typically User Interface - can be written in .NET. Another fact to know is that when writing a real time application, .NET cannot be used because of its unpredictable garbage collector, which brings us back to native C++. If designed carefully, the COM server can execute the real time tasks and at the same time expose a COM interface to the outside world. This said, the COM server will be written in C++, and the client(s) in C#. As a bonus, we will use the same C# source code for the remote client running under Windows XP and the .NET framework, as well as for the local client running under Windows CE and the .NET Compact Framework, showing the real power of running .NET on several OS platforms. Whoever used DCOM under Windows CE knows that COM rich error information is not propagated properly from the server back to the client. The sample program will also implement this missing functionality. Unfortunately, Pocket PC 2003 and 2005 do not support DCOM. Understanding this, we will need to build our own Windows CE image by means of Platform Builder 5.0, the tool for creating, configuring, and building your own Windows CE 5.0 image. First, download from the Microsoft website the .NET CF 2.0 CEC installer for Platform Builder 5.0, and install it so it is available for selection from the catalog within Platform Builder. We need the Compact Framework 2.0, because it allows COM interop functionality that is not present in previous versions of the Compact Framework. Create a Windows CE image that has full DCOM support and .NET CF 2.0 added to it. How to create a Windows CE image is explained best in other places, so I will not go into the details here. As we will use Visual Studio 2005 for creating and debugging our code, it is advisable to add the necessary executables and DLLs for debugging applications with Visual Studio 2005 as well, to your image. Check the online Help on how to do this. Other useful applications to be added to your image are: All these tools are available in the download package too in the source code. Note: All Windows CE sample projects in this article will reference the DSM52 SDK. This is the name of the image I created and that you need to install prior to creating/using any smart device project in Visual Studio 2005. If you give your SDK another name, you will need to replace all �DSM52� references in the vcproj files with your SDK name in order to open and load the sample code projects. Windows CE (5.0 and before) does not support the Automation Marshaler, sometimes also referred to as the Type Library Marshaler. Therefore, we have to create our own proxy/stub marshaling code to accompany with our COM server and client, to make sure our COM calls are properly marshaled across process boundaries. However, if we stick to OLE automation compatible data types in our COM methods, we don�t need to provide the proxy/stub DLL on the Windows XP/2000 client side as the Automation Marshaler is always present there (as part of ole32.dll and oleaut32.dll). If you still need to use other data types, you are obliged to compile the proxy/stub code also for Windows XP/2000 and register it there too. For the same reason, we have to modify the event sink�s dispinterface inside the LIBRARY block in the IDL file (as generated by the Visual Studio ATL COM project Wizard for event notification) and change it to an interface section outside the LIBRARY block. For all interfaces defined outside the LIBRARY section of our IDL file, the MIDL compiler will create proxy/stub code that needs to be added to your proxy/stub DLL. Doing this, marshaling code for your events firing back to the client will also be created in the proxy/stub DLL. Note that this interface is marked as dual and derives from IDispatch, simulating dispinterface functionality. #ifdef UNDER_CE /* Windows CE does not support Type Library Marshaling, so we need to make it a custom interface that can be Proxy/Stub Marshalled */ [ object, uuid(8DC5953F-FBE6-4CF5-9FB5-4FF8A7B15530), dual, helpstring("_IGateEvents Interface"), pointer_default(unique) ] interface _IGateEvents : IDispatch { [id(1), helpstring("method Opened")] HRESULT Opened([in] VARIANT Destination); }; #endif //UNDER_CE ... LIBRARY StarGateLib { ... #ifndef UNDER_CE [ uuid(8DC5953F-FBE6-4CF5-9FB5-4FF8A7B15530), helpstring("_IGateEvents Interface") ] dispinterface _IGateEvents { properties: methods: [id(1), helpstring("method Opened")] HRESULT Opened([in] BSTR Destination); }; #endif //UNDER_CE ... coclass Gate { ... [default, source] dispinterface _IGateEvents; }; }; Now that we are talking about marshaling, I would like to address another problem in using COM under Windows CE. It is a common procedure to return an error code ( HRESULT) from your COM method call if a problem occurred during the method call. It is advisable to foresee a rich error description also to help the user to resolve the problem. Currently, Windows CE does not propagate this rich error information across process boundaries (through the GetErrorInfo() and SetErrorInfo() APIs). Later on in this article, we will show how this missing functionality can be added to your code as well. As part of determining whether a COM�s server implements and foresees rich error information, the ISupportErrorInfo interface needs to be marshaled too. The marshaling code for this interface is also not available in Windows CE. For that reason, proxy/stub marshaling code is manually generated and added to the proxy/stub DLL too. The ISupportErrorInfo interface is copied from oaidl.idl. Figure 1. DCOM marshalling Note: Before we can use Visual Studio 2005 to create our smart device sample code, the SDK of our own created image (platform with DCOM support in it) needs to be installed so that it can be selected in Visual Studio 2005 for use with our own projects. We use Visual Studio 2005 to create a C++ ATL smart device project. The server will be an ATL COM EXE server. The sample program I�ve created is inspired by the famous TV series �Stargate�, and allows you to dial in to other planets in our galaxy and even far beyond, provided you know how to deal with the bad guys. Ever wanted to meet Thor and visit Atlantis? Check it out. By means of the wizard, we can add a few methods to our interface and implement it in our COM object. Mind you, we do add support for ISupportErrorInfo and connection points, and we use the free-threading model. This is normal procedure when creating COM objects. One thing I�ve added on top of the wizard generated code is that the COM events are not fired to the client synchronously from the same thread as where the �incoming� interface methods are called, but they are fired from a separate worker thread to avoid potential dead locks with .NET. This code is implemented in the CNotifier class. The ThrowCOMError() function is responsible for taking the rich error description from the embedded resource file and storing the error info in the current thread context where later on the IChannelHook interface will pick it up and send it to the client�s process and thread context. How does the rich error information get transported to the client? When an out of process COM method is executed, the COM library will send out of band (hidden) information along with the marshaled method parameter data, as explained in the article of Don Box in Microsoft Systems Journal. It uses the IChannelHook interface, provided that you have installed your own hook with CoRegisterChannelHook. I have chosen to install my own hook that implements the missing functionality to transport the rich error object from the server back to the client. I have added this code in the proxy/stub DLL so that whenever the interface is called, this hook gets installed auto-magically as well. Of course, if you have multiple interfaces to be marshaled in different proxy/stub DLLs, the channel hook is better implemented in a separate DLL and registered in an early stage of the Windows CE image boot process so that it is available when needed. The following figure explains what actually happens when a COM method call returns with an error condition set in the returned HRESULT. Figure 2. Program flow of COM rich error info This solution allows to transport rich error information between two out-of-process COM applications, either both client and server running on Windows CE, or even one of them running on Windows XP/2000 (through DCOM). As of .NET CF 2.0, Microsoft added COM interop support that was missing in CF 1.0. This great new feature brought me to the idea of creating a C# user interface client that could be compiled and used for both the .NET Compact Framework as well as the desktop .NET Framework. Of course, in the Compact Framework, not all functionality is available as in the desktop variant, but if you are aware of this limitation and if you write your Compact Framework version first, with a little bit of luck, your code compiles without problems on both frameworks just like that. The only thing you need to do is add a reference to the TLB file that was generated while compiling the COM EXE server. And now look, you can write your own C# or VB client and run them both on Windows XP/2000 and Windows CE connecting to the same COM server, that at the same time is executing real time C++ code on Windows CE. Isn�t that great? Imagine that one day this would be possible in Pocket PC as well� Controlling your house robot from your Pocket PC� One small remark about rich error information, though. In the .NET framework, the COMException object immediately gives you the error description in the Message property, but not in the Compact Framework. Therefore, I created a static wrapper class - named ComError - around the COM API GetErrorInfo() function that retrieves this information for you when available. This code uses P/Invoke and manual marshaling to present the error object information to the application in a managed class. When your Windows CE image is started properly on your hardware and when you can connect Visual Studio 2005 to this image, it is time to get the code started. First, deploy both the COM EXE server as well as your proxy/stub DLL onto your device. Next, make sure the proxy/stub DLL is registered. You can run �RegSvrCE.exe /StarGatePS.dll� for this, or have Visual Studio do this for you automatically when deploying. The EXE server will not be registered automatically, so from the command shell in Windows CE, you need to register it yourself. Run �StarGate.exe /RegServer�. This will add the necessary entries in the registry. At this point, you can start your Windows CE C# user interface and test this part already. Open ControlRoomCE.csproj, build, deploy, and run. If you press the �Enter Control room� button, the Gate object is created and you can call the �Dial gate� method on it. If you do this more than seven times, the server will fire an event mentioning the gate is opened. If you �Dial gate� more than eight times, an error message will be returned. As soon as our COM EXE server is registered, we can fire up DCOMCnfg.exe on the Windows CE device. This is the place to setup authentication, access, and launch permission. Just for this test, we disable some security checks that makes life a bit easier for now. Although we have disabled most of the default security checks, we still need to do one more thing. Prior to making the DCOM call from the Windows XP/2000 client to the Windows CE server, DCOM will try to authenticate the client on the CE device. It uses NTLM for that. There are two possibilities: SetNTLMUserInfo()API function for that. Enter the same username and password as the (logged on) user that will run the client. Make sure both solutions (the DefaultDomain registry key or the local NTLM account) are not set simultaneously as this will not work. Consult the Windows CE Platform Builder help for more information. It is also useful, but not required, to specify on the Windows CE device the same username and password in the Control Panel | Owner | Network ID tab. This information is merely used by Windows CE to authenticate you when accessing remote directories, for example, a shared drive on your XP/2000 system. Don�t confuse these credentials with the NTLM credentials. Both serve different purposes. The domain parameter is only required if you are really part of a domain. As our interfaces only use automation compatible data types, we don�t have to register a proxy/stub DLL on the Windows XP/2000 side. Remember from our discussion earlier that this functionality is already provided by oleaut32.dll and ole32.dll. We rely on the built-in Type Library Marshaler to do the work. For ease of use, we register the type library so that it can be queried immediately in Visual Studio. Run the RegTlb.bat tool to do that. How does the Windows XP/2000 C# client know about the whereabouts of our remote COM EXE server? The answer is the registry. If we enter the Gate class information in the registry, we can specify its location in the registry by means of the DCOMCnfg.exe tool on Windows XP/2000. Run RegRGS.bat first to enter this info in the registry. Next, run DCOMCnfg.exe on Windows XP/2000 and search for the Gate class entry. Right-click and set the location to the IP address of your Windows CE device. Note that no COM server code whatsoever is present on the Windows XP/2000 side, only registry info and the Universal OLE Automation Marshaler. One other point of interest with DCOM is that, when you have a firewall enabled somewhere, make sure ports 135, 137-139 are opened. The DCOM RPC SCM is listening on port 135, and NETBIOS name resolving is required to make DCOM working properly. Also, DCOM requires ports open above 1023. To see the code in action, we will run the components in their respective Visual Studio debugger. To learn about how the IChannelHook interface works, start the debugger from the proxy/stub DLL and set a breakpoint in IChannelHook::ServerGetSize(). On each out-of-process method call returning inside the server, this hook is called allowing you to shuffle in some out-of-band information. On the receiving (client) side, the IChannelHook::ClientNotify() is the place to extract this information again. The same mechanism is also available in the other direction, but not required for returning rich error information, But could easily be used for other DCOM debugging purposes. Good luck! General News Question Answer Joke Rant Admin
http://www.codeproject.com/KB/mobile/WindowsCE_DCOM.aspx
crawl-002
refinedweb
2,642
62.38
After starting my new job in Core OS, it became clear that I would need to brush up on my old COM-programming skills, which I haven’t used in about, oh, eight years. It’s been all .NET Framework since I hired on as a full-time employee at MSFT. A good place to get acquainted with the COM world is the excellent ATL Tutorial topic on MSDN, which shows how to build a simple ActiveX control and host it in a web page. It comprises seven hefty steps and a fair amount of C++ code. I have to admit that it was a bit of a shock to revisit the old skool world of native Windows programming after being spoon-fed .NET Framework sugar for so many years. My idea is to perform the same task in other frameworks and compare the ease of implementation. I hear people claim that Microsoft doesn’t know what “modern programming” is about, so let’s put this claim to the test. For reference, here’s what the project looks like once you’ve performed all the steps in the ATL Tutorial topic. Solution Explorer view of the completed ATL Tutorial project, in Visual Studio 2010. Here’s the Polygon ActiveX control, hosted in Internet Explorer 8. The completed Polygon ActiveX control from the ATL Tutorial project, hosted in Internet Explorer 8. The overall experience for implementing the Polygon ActiveX control isn’t too bad, although I found myself getting lost among the .h, .cpp, and .idl files, especially when connection points entered the picture – all that IDispatch business feels needlessly complicated nowadays. In fact, the experience is completely unchanged since the last time I implemented COM objects in the previous millennium; the ATL dialogs in Visual Studio 2010 appear to be identical to those used in Visual Studio 6. The ATL Control Wizard in Visual Studio 2010. Because Visual Studio 2010 is a managed application with a WPF user interface, I wouldn’t be at all surprised if these are, in fact, the original comctl32.dll-based dialogs running in an HwndHost control. This is both comforting and disturbing, as if ATL development had been frozen in amber for the last decade. Debugging was not entirely convenient, requiring the discovery, download, and build of a semi-supported external test application, named TstCon. I was reduced to message-box debugging when the control was running on the web page. UPDATE: Franci Penov points out in comments: .” Thanks, Franci! From the perspective of “modern” software development, here are the important observations: - The ATL/COM implementation has a large ratio of framework files to user files. Depending on how you count, it’s about 5 or 6 to 1. - The implementation is distributed across 3 files with arbitrary locations for code in .h or .cpp. - There is no support for declarative layout. - There is no visual designer support. - The implementation uses lower-level abstractions, such as HDC and WPARAM. - Analysis tools are not readily available. - Several hours to implement and debug. With the unmanaged ActiveX implementation in hand, I turned to Silverlight for a comparison to a “modern” framework. This turned out to be immensely simpler to implement; the hardest part was converting the core C++ code to C#. Here’s what the Silverlight project looks like. Solution Explorer view of the completed Silverlight control project in Visual Studio 2010, adapted from the ATL Tutorial topic. Here’s the PolygonControl implementation in Silverlight, hosted in an autogenerated page on Internet Explorer 8. The completed Polygon Silverlight control, adapted from the ATL Tutorial project, hosted in Internet Explorer 8. I added a slider control to change the number of sides in the polygon, just because it was easy. I briefly considered doing the same thing with a comctl32 slider in the ATL/COM implementation, but the thought made me hyperventilate. From the perspective of “modern” software development, here are the important observations: - The Silverlight implementation has a small ratio of framework files to user files, about 1 to 2. - The implementation is in 1 or 2 files (code-behind plus optional XAML). - Declarative and imperative layout are supported. - There is full visual designer support. - Silverlight provides free graphics and layout sugar. - The implementation uses high-level abstractions, such as data binding and events. - The debugging environment is fully integrated. - Analysis tools are fully supported. - Two hours to implement and debug. For the modern programmer, Silverlight is the clear winner. But what of other frameworks? In particular, modern programmers want to author mobile apps. I happen to own an HTC Droid Eris, which I like very much, so it seemed natural to explore the Android Development Tools (ADT). It’s been awhile since I’ve done any serious Java programming, so it took a few hours to install Eclipse and get the ADT to play with it. Once that was done, it was a simple matter to port the C# code to Java and run it in the device emulator. Happily, the core code that calculates the polygon vertices ported from C# to Java with no tweaking necessary. Here’s what the Android project looks like in the Eclipse IDE. Package Navigator view of the completed Android control project in Eclipse, adapted from the ATL Tutorial topic. The project structure is comparable to the Silverlight project in simplicity, which is nice. Deployment to an Android Virtual Device (AVD) emulator is straightforward and supports full debugging in the IDE. Devs who are worried about Java VM performance can rest easy: starting with Android 2.2 (“Froyo”) the Dalvik runtime engine (Google’s bytecode interpreter) now supports just-in-time (JIT) compilation, like the .NET Framework. Here’s the Java-based implementation of the PolygonApp running in an Android Virtual Device. The PolygonView control running in an Android Virtual Device emulator, adapted from the ATL Tutorial topic. Touch events and gestures come free with the ADK framework. The downside is that there’s no visual designer in Eclipse. UPDATE: Spence corrects me in comments – there is visual design support in Eclipse. My bad. Here it is: The PolygonView implementation running in the Eclipse visual designer. From the perspective of “modern” software development, here are the important observations: - The Android implementation has a small ratio of framework files to user files, about 2 to 1. - The implementation is in 1 or 2 files (code-behind plus optional XML). - Declarative and imperative layout are supported. - There is novisual designer support. - The Android framework provides free graphics and layout sugar. - The implementation uses mid-level abstractions, such as layout views and Java graphics. - The debugging environment is fully integrated. - Analysis tools are supported but not as fully featured as Visual Studio 2010. - Two hours to implement and debug. This post was going to be a “tale of three frameworks,” but after success with Android, it seemed obvious to compare with the new Windows Phone 7 framework. Installing the Phone 7 development environment turns out to be painless: there’s a special Express SKU of Visual Studio 2010 that you download from the Windows Phone developer site. Fortunately, the Visual Studio Express SKUs install side-by-side with the other Visual Studio SKUs, so you can have Visual Studio 2010 Express for Windows Phone on the same machine that has your main Visual Studio installation. The biggest win for Windows Phone development is that it’s based on the .NET Framework, with Silverlight providing the user interface for your apps. I was able to lift my PolygonControl implementation and drop it directly into my Windows Phone project with zero changes – well, one: I used Visual Studio’s refactoring support to change the namespace for the control to the default namespace of the Windows Phone project, and it even refactored into the XAML. Thank you, Cider team. Here’s what the Windows Phone 7 project looks like. Solution Explorer view of the completed Silverlight control project in Visual Studio 2010 Express for Windows Phone, adapted from the ATL Tutorial topic. And here’s what the Windows Phone development environment looks like. The completed Silverlight control project in Visual Studio 2010 Express for Windows Phone, adapted from the ATL Tutorial topic. The big win here is the visual designer support, which looks exactly like what you get with the WPF and Silverlight Designer for Visual Studio. You drag and drop controls from the Toolbox onto the design surface, which represents your target device’s display, and you set properties on controls by using the familiar Properties window. The XAML view automatically updates to reflect these changes. VS automatically added my PolygonControl to the Toolbox, so I was able to drag it from the Toolbox and drop it onto the design surface. This is what we used to call RAD – Rapid Application Development. Here’s the Silverlight implementation of PolygonControl, hosted in the Windows Phone Emulator. The PolygonApp running in the Windows Phone Emulator, adapted from the ATL Tutorial topic. The most exciting feature is the Windows Phone compatibility with Silverlight – I could hardly believe my eyes when the same PolygonControl implementation ran both in the browser and in the phone emulator. Potentially, this is a huge win for Windows apps developers and may be the single strongest argument for favoring Silverlight over the other frameworks. Here are the running apps, shown side-by-side for comparison. The Polygon control, adapted from the ATL Tutorial topic, running as an ActiveX control (left), a Silverlight control running in Firefox, a Windows Phone control, and an Android Virtual Device emulator (right). What’s a modern programmer to make of all this? The following table summarizes what we’ve discovered. It’s a toss-up between Android and Silverlight, but for my money, the possibility of authoring Silverlight controls that also run – with no XAML changes – on Windows Phone makes Silverlight the more compelling story. Conceivably, modern developers can double their income from a single code base, by selling the usual desktop/browser apps as well as corresponding Windows Phone apps. What of the claim that Microsoft is oblivious to modern programmers? To my mind, it doesn’t hold water – it’s hard to imagine a more modern framework than Silverlight. Once Windows Phones start to ship, Microsoft will have complete parity with Android in the developer story. The code for all four projects is posted at my Code Gallery site. Check it out and tell me if you agree with my conclusion. UPDATE: Don Burnett compares iPhone development to Windows Phone development here: iPhone versus Windows Phone 7 Coding Comparison. Digging deeper, there are huge advantages on the Microsoft stack with lambdas, linq, and extension methods to name a few. The readability of code is remarkable using declarative linq syntax. Also, the ability to extend types with methods that express logic more fluently (i.e. 15.Minutes().FromNow();) is proof that software development on the Microsoft stack is indeed "modern". Word. LINQ and the others you mention are awesome, also the new dynamic keyword holds lots of promise. Just out of curiosity, why did you drop the slider from the WP7 app? Thanks, great article, but, after two years, I'm having second thoughts about SL. The only thing keeping me from going back to Java/Eclipse is the two years that would be wasted. I really don't like xaml (it is a copy then change technology) but I must use it because classes like ControlTemplate are sealed and its Content property is private (so, I can't use C# to do any OO styling). Yes, there is a lot of very cool technology in SL/.net (eg. dynamic) but it is like having a $300K car that you are not licensed to drive (I need ControlTemplate). Once you get past "Hello World" kind of examples you'll need expensive tools: Blend and Visual Studio 2010. (Then there's problems with Microsofts attidude toward the world: Linux, Html 5. Plus, I need to worry about what Microsoft is going to allow in xaml that they won't allow in C#, eg. ControlTemplate.) So, if you like expensive tools and the NEED to know two languages hands down go with SL. Hi Misha, Just laziness. It should be a simple matter to drop the slider onto the design surface and wire it up with a data binding. Jim The android development suite using eclipse has a visual designer. More so, you only show the package manager in Eclipse. Lots and lots missing in this post. You should provide a iPhone iOS4 comparison as well! I'd be interested in seeing how that stacks up with the others. Hi Spence, Thank you for the feedback. I looked all over for a designer view, so I've gotta say that it's not very discoverable. Can you point me to it? That's why this blog is named "Learning Curve"! Jim. Hi Brett, I considered that but was too lazy to install Cocoa on my wife's Mac! Jim Hi Franci, Thank you for the help — I'll forward that to the author of the ATL Tutorial topic. Jim Jim, Sounds like you're quite unfamiliar w/ Eclipse at all. When you have a file open, there's tabs on there to show representations, much like any other file in eclipse (html, xml, etc) Click the tab. Right you are, Spence — I'm a total n00b. I've corrected the post but ran into this horrible bug:…/main-xml-error-t7506.html So the onboarding experience has been less than ideal. ^_^ Jim In your example, your layout is missing. I'm surprised you ran into this problem. Then again, you're complaining about Eclipse after a short time of usage. Something here isn't right. Silverlight generally has a language and development environment advantage over the competition. Unfortunately, NONE of it's advantages mean anything if it doesn't translate into some benefit for the customer that is more than 20% better than the competition. IMO, the biggest advantages I see currently are the development environment, much better video, threading, and a robust language. HTML5 will be good enough for 80-90% of applications, once the tooling and controls are there, so if Silverlight(and Flash) are to survive, we will need to translate these advantages into a real customer benefit that will be hard for HTML5 to reproduce. Nice post Jim. I wrote a blog post a while back that shows how to do something similar on the iPhone using MonoTouch. Here's the link in case you're interested: mikebluestein.wordpress.com/…/drawing-with-coregraphics-in-monotouch-2 Cheers WP7's dev story is strong, but would be stronger if we had the following:- a) The ability for developers to load their skunkworks code out of the box, and not because they ponied $90 to MS b) Actual phones to play with c) Some excitement in the _designer_ (and not just developer) world WP7 will attract all the old WPF/ Silverlight developers no doubt, and truly, the three-screens-one-codebase paradigm is beautiful, but none of this will matter unless there's some critical mass in apps, or at least apps that will draw people away from at least the major ones in the iPhone or Android app store. I have major concerns whether that can happen with what we have now. Kevin P, I love XAML. I didn't like it when I started to learn it, but once you do, it is a very powerful tool. I can change the look of ANY control in just a few minutes – something I could not do before in Windows Forms. With XAML, I can lay out an extremely sphosticated design layout that again, just wasn't possible before. That said, you do have to get by the oh my god, I have to learn yet another language why doesn't somebody just shoot me now barrier. Greg Being able to run a Silverlight app on a Windows Phone is a real plus. I've heard that there are more Nokia phones than both iPhones and Android phones combined so now that Microsoft has released Silverlight for Symbian phones we have yet one more reason to develop in Silverlight. As a new developer, I saw the light (very same argument of this blog post) of using Silverlight after considering all my options. Microsoft does have the "ideal" mulit-platform solution for developers. However, I believe MS has gotten there very slowly and feel sorry for the developers who have had to wait. Also, as a student, I get the Visual Studio and Expression Blend products for free. I can certainly say I wouldn't be using MS if it was not free. If my develpment work pans out, then I'll buy the software for commercial use, but I think MS will need to offer all of these products for free to everyone to compete in the developer market. spence: After spending over a year working with eclipse, I certainly was complaining about it. Now whether that had more to do with J2EE or the design of the IDE itself … IDEs generally optimize for a particular platform, so at some point the distinction just doesn't matter. I will freely admit I preferred eclipse to VC6's or VB's IDE. But everything from VS2k5 onward I'm definitely more productive with.
https://blogs.msdn.microsoft.com/jgalasyn/2010/07/07/modern-programming-a-tale-of-four-frameworks/
CC-MAIN-2017-13
refinedweb
2,906
63.39
Component-Based Page Layoutsby Didier Martin February 16, 2000 Printed newspapers and magazines are created by a team of content authors, editors, and people whose task it is to aggregate and lay out the content in a coherent and pleasing way. Let's take the example of a magazine and simplify the workflow a little: authors deliver their content to the editor, who (obviously) edits the content. Subsequently, the content is ready to be positioned in the magazine's page layout. Content is not necessarily limited to text, but may also contain illustrations. An electronic magazine is also an assemblage of text and image content. Moreover, other kinds of components can be included in a web page, including interactive components like applets, plug-ins, or ActiveX objects. Each component may be produced by a different author. Let's examine how the assembly of such a site can be done with XHTML. XHTML is part of the next generation of publishing languages for the Web. One main advantage of XHTML is that, in contrast to its predecessor HTML, it can be extended with new elements. This article will demonstrate how, by using new elements and XSLT transformation sheets, you can aggregate content coming from external documents into a single XHTML document. A Basic XHTML Page Layout Well-structured web sites have an integrated look and feel. If each individual component author created his or her own vision of the site, it would end up very disorganized and visually confusing. Looking at the structure of most web sites, we notice that they have a similar visual layout. At the top, a header; at the bottom, a footer; at the left, a navigation area or table of contents; and, at the right, the content. This visual structure is illustrated in figure 1. In the XHTML world, one way to create a layout like that shown in Figure 1 is to use either a frameset or a table. (In order to support the widest range of browsers, we must use both in the same page.) In XHTML, as well as in HTML 4.01, the <frameset> element should be used in tandem with the <noframe> element. The <noframe> element's content is used by browsers that do not support frames. This element can contain a table, and the table's cells can contain the components of the frameset. "But wait a minute," you ask, "How can I still use the components as separate documents in the <noframe> section?" Indeed, a good question. Expand XHTML with a component Element We know it is possible to include components as separate documents in a <frameset> element, but not in the <noframe> section. Let's then include in the <noframe> section elements of our own invention named <xscript:component>, and use a bit of XSLT magic to obtain the same effect we get with the <frameset> construct. The key to XHTML is the letter X, which indicates that it is eXtensible. This means we can add our own elements when we need to. So, to obtain the same layout in the <noframe> section that we get in the <frameset> section, we add to our XHTML a new element that is used to include external document content in cells of the table. Inheriting Attributes From xlink:simple The new element, component, is basically a link to a resource. The latest XLink working draft makes it possible for an element to inherit the linking behavior from one of the XLink elements. XLink proposes two kind of links: - a one-to-one link - a one-to-many link Since we need our <xstyle:component> element to link to a single resource, we then use the xlink:type="simple" attribute that will transform our element into a link. Several other attributes from the XLink language (like xlink:href, xlink:title, xlink:show) are also useful, so let's integrate them into our element's list of attributes. Using XSLT as an XLink Interpreter An important thing to mention here is that we are using the XSLT engine as an XLink interpreter. More specifically, it interprets the link behavior indicated by the xlink:show attribute. When this is set to the "embed" value, the content of the linked resource is included in a table cell. Otherwise an error message is included. To the xlink attributes we add xstyle attributes to indicate the component's MIME type, its height, its width, and the role it plays in the layout. The xstyle prefix denotes that the attributes are of our invention; we will associate the prefix xstyle with the namespace URI of our choice (in this case). We do not use the xlink:role attribute because we want to indicate the semantic meaning of the element in a layout context, not in a linkage context. So, our element is a link to an external resource, and its basic properties are described by the following attributes: xlink:type = "simple" xlink:href = "URI" xlink:title = "string" xlink:show = "embed" xstyle:type = "MIME type, e.g., image/svg or text/xhtml" xstyle:height = "numerical value or percentage" xstyle:width = "numerical value or percentage" xstyle:role = "header|footer|table-of-content|content" For instance, the <xstyle:component>, which links our web site template to the header component (in this case, a vector graphics SVG document), looks like this: <xstyle:component xlink: Our XSLT transformation sheet must interpret the <xstyle:component> element by first looking for the xlink:show attribute. If this is set to the embed value, then the xstyle:type attribute is used as a switch to select the appropriate behavior. For instance, in our example XSLT transformation sheet, every component of type "image/svg" is converted into an <embed> element, which can then be displayed in a web browser using the Adobe SVG plug-in (now freely available from Adobe's site). In cases where the xstyle:type attribute is set to "text/xhtm", the referred document's content is inserted in the table cell. Examining the XSLT Transformation Sheet The template performing the XLink interpretation is the one that matches the <xstyle:component> elements: <xsl:template <xsl:choose> <!-- we embed the component's content only if the xlink:show attribute is set to 'embed' --> <xsl:when <xsl:choose> <xsl:when <embed type="image/svg"> <xsl:attribute <xsl:value-of </xsl:attribute> <xsl:attribute <xsl:value-of </xsl:attribute> <xsl:attribute <xsl:value-of </xsl:attribute> </embed> </xsl:when> <xsl:when <xsl:apply-templates </xsl:when> <!-- put here other xstyle formats identified by the xstyle:type attribute. the attribute's value is the component MIME type. For example, if the component is an SVG document, then its MIME type is "image/svg". --> </xsl:choose> </xsl:when> <xsl:otherwise> <!-- We include an error message in the output document if the intended behavior is not to embed the content --> <p>Error: the <xstyle:component> elements only support the xlink:show attribute set to the value "embed".</p> </xsl:otherwise> </xsl:choose> </xsl:template> When an <xstyle:component> is matched by the template and the xstyle:type is equal to "text/xhtm", then the external document's content is loaded, parsed, and the resultant node set included in the current node set. In our case, the external document content replaces the <xstyle:component> element. Thus, each time an <xstyle:component> element is encountered by the XSLT engine, it is replaced by the external document's content. This magic is accomplished with the document() function. However, we do not want to include the entire external document's content in each table cell. For example, the XHTML <head> element has no place in a table! We only want to include the content of each external document <body> element. This is accomplished by the following expression. <xsl:apply-templates (Note that html prefix is associated with the namespace URI for XHTML,). Now that we have extracted the right node set, we simply want to copy its content as a replacement for the <xstyle:component> node. The following template does just that: <xsl:template <xsl:copy> <xsl:apply-templates </xsl:copy> </xsl:template> Now, Let's Go to the Lab.... If you are tempted to do some exploration of your own, here is my proposal for this week's lab experiment.But first, to do this experiment, you'll need an XSLT engine that is as compliant as possible with the 1999 W3C XSLT Recommendation. I used James Clark's XT processor. - Place the following documents in the same directory: toc.htm, content.htm, footer.htm, header.svg, template.htm, template.xsl. - Go get the Adobe SVG Viewer; you'll need it to view the SVG drawing (and also for a future lab experiment...). - Process the template.htm document with the template.xsl transformation sheet in order to replace all <xstyle:component>elements with the appropriate content extracted from the external components (i.e., documents). - Try it with your own components. You can also simply look at the template document, the transformation sheet, and the resultant document. Because the template.htm document is an XHTML document, your browser should immediately interpret and render it. Use the "View Source" option to examine its source.
http://www.xml.com/pub/a/2000/02/16/style/index.html
crawl-002
refinedweb
1,529
52.8
Displaying an Image file inside the BorderLayout GUI I have a quick question regarding the use of image files (.png) in Java's GUI. I'm working on a public class that extends JPanel, which uses the BorderLayout to display a window. I know how to add sliders, buttons, etc to my BorderLayout window, but what I'm trying to do is display an image. How can I do this? Thanks for reading this. edit: Or is there any other way to display some sort of image in BorderLayout? Message was edited by: lucas27 Hi, JLabel is able to host images, so this is probably the shortest way, without creating a image-display widget: ImageIcon icon = createImageIcon("images/middle.gif"); label3 = new JLabel(icon); Found here: lg Clemens
https://www.java.net/node/684529
CC-MAIN-2015-22
refinedweb
128
66.44
What's Wrong in Java 8, Part V: Tuples What's Wrong in Java 8, Part V: Tuples In part 5 of our "What's Wrong in Java 8" series, we turn to Tuples. Join the DZone community and get the full member experience.Join For Free Sensu is an open source monitoring event pipeline. Try it today. The first time a programmer is missing tuples is often when he feels the need to return multiple values from a method. As we all know, Java methods may take as many arguments as needed, but they can only return a single value. With most functional programming languages, this problem is somewhat different. Functions may only take one argument and return one value, but this argument and this value may be tuples. What are tuples At first sight, tuples looks like ordered collections of values of different types. Unlike arrays or lists, which may contain several values of the same type, tuples may “contain” values of mixed types. Most often used tuples are generally given specific names: a tuple of two elements is generally called a pair (or double, couple, dual, twin) and a tuple of three elements is generally called a triple. There are also such names as quadruple, quintuple and so on. Note that there are also tuples of 0 and 1 element. A tuple of one element is rarely used as such, since the element itself may be used instead. However, for theoretical discussion, it may be useful to consider such tuples. A tuple of one element is sometimes called a single. The Optional class in Java 8, is in fact a tuple of one element. It is sometimes easier to use the name tuplen with n being the number of elements. In programming languages, tuples are generally noted with parenthesis: (3, 5) is a tuple composed of two integer values and: (“age”, 42) is a tuple composed of one string an one integer. Does Java has tuples Without any doubt, Java has tuples. It has implicit and explicit ones. Implicit tuples are the argument of what we called multi-argument methods: int mult(int x, int y) { return x * y; } int z = mult(3, 5); In this example (3, 5) may be seen as a tuple, which in turn make the mult method appear as a single argument one! This is important if we think about functions. A function is an application of one set (the function's domain) into another set (the function's codomain). It is important to note that the domain is ONE set. It can't be two sets, nor three sets, nor anything else. It may however be a multidimensional set, that is a set of tuples! So, a function may take only one argument. Having functions of two or more arguments is only syntactic sugar for functions of pairs, triples, and so on. And what looks like a function of two arguments, as the following lambda in Java 8: (int x, int y) -> x * y is in fact a function form int x int (a Cartesian product) to int. And the result of the Cartesian product int x int is a single set of tuples. So it is clear that Java has tuples, but we can use them only as function's arguments and not for function's return values. Note: function's of two arguments are not always syntactic sugar for functions of tuples. They may also be used for functions of one argument to functions. This is related to arguments evaluation. For more details, see the first article in this series: What's Wrong in Java 8, Part I: Currying vs Closures Creating our own tuples Should we need to return tuples, it is however very easy to create some. For example, if we need to create a function from double to (int, double) taking a double as argument and returning its integer and decimal parts, we can write: public class TupleExample { public static class Tuple { public final int integerPart; public final double decimalPart; public Tuple(int integerPart, double decimalPart) { super(); this.integerPart = integerPart; this.decimalPart = decimalPart; } @Override public String toString() { return String.format("(%s, %s)", integerPart, decimalPart); } } private static Tuple split(Double x) { int integerPart = x.intValue(); return new Tuple(integerPart, x - integerPart); }; public static void main(String[] args) { System.out.println(split(5.3)); System.out.println(split(-2.7)); } } This program will display: (5, 0.2999999999999998) (-2, -0.7000000000000002) Now, we see that most objects in Java are, in fact tuples! Of course, it would be simpler to create a generic class for tuples, which is as easy (some methods such as equal and hashcode have been omitted): public class TupleGenericExample { private static Tuple<Integer, Double> split(Double x) { int integerPart = x.intValue(); return new Tuple<>(integerPart, x - integerPart); }; public static void main(String[] args) { System.out.println(split(5.3)); System.out.println(split(-2.7)); } } public static class Tuple<T, U> { public final T _1; public final U _2; public Tuple(T arg1, U arg2) { super(); this._1 = arg1; this._2 = arg2; } @Override public String toString() { return String.format("(%s, %s)", _1, _2); } } So, once again, since it is so easy to implement tuples, what is the problem? There are many problems: - We can write our own tuples, but we can't use them in a public API. To do so, we should have all Java developers to agree upon a common Tupleimplementation. We can't do this, unless a Tupleimplementation is added to the Java API. Of course, we would probably need Tuple3, Tuple4and so on for small numbers of elements. (Although it is possible to define Tupleof more than two elements in terms of pairs, such as Tuple<T, Tuple<U, V>>, using structures like linked lists or binary trees, it would not be very practical.) - We can't check the type of a tuple with instanceof. So, if we want to check if an object is an instance of tuple, we would have to do the check for the raw type, and then as many checks as there are elements in the tuple. - To make Tupleeasy to use, we would need the same syntactic sugar offered for arguments in lambda notation, that is we would need literals. - And there is the ubiquitous problem of primitives. Dealing only with four primitive types ( int, long, double, boolean) would give 25 different types of pairs, 125 different types of triples, and so on. We may rely upon auto boxing/unboxing for this. Much better, we would again need value types. In the meantime, we can use our own tuples internally. We can create, the tuples for primitives we need, or, better, we can use the corresponding object types and rely on auto boxing/unboxing as long as performance is not an issue. What's next? In the next article, we will talk in more details about the differences between function of “several arguments” being in reality functions of tuples, and those being function of functions. Previous articles What's Wrong in Java 8, Part I: Currying vs Closures What's Wrong in Java 8, Part II: Functions & Primitives What's Wrong in Java 8, Part III: Streams & Parallel Streams What's Wrong in Java 8, Part IV: Monads Sensu: workflow automation for monitoring. Learn more—download the whitepaper. Opinions expressed by DZone contributors are their own. {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/whats-wrong-java-8-part-v
CC-MAIN-2018-47
refinedweb
1,243
62.48