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
Yang Jiang java javac compiler antlr tools compiler front end 2011-02-16T22:01:15+00:00 Apache Roller Generating java byte code by building AST trees Yang Jiang 2008-10-20T20:24:29+00:00 2008-10-21T03:27:19+00:00 <p> There are several ways to generate byte code to run on JVM. You can write a .java file then compile it with javac, or write ASM similar code directly then compile it with tools like <a target="_blank" href="">JASML</a>, or with tools like <a target="_blank" href="">BCEL</a> it is even possible to generate your own class in runtime. Aside from these, a quite interesting approach is to construct AST nodes representing the structure of the java code, then generate byte code from that. Actually, this is what the javac does.<br /> <br /> When javac compiles .java files into .class files, there is a two step process involved. <br /> First is parsing. Javac reads in the source code, parses it, builds a tree structure representing the source code.<br /> Second is code generation. The code generator takes the tree, acts upon it, produces the .class file.<br /> <br /> These two steps are quite independent from each other, which makes it possible to replace either of the two without affecting the other.<br /> So, to achieve our goal, we can create a tree ourself, then hand it to the code generator to generate code. <br /> This is actually not a difficult task. The javac is very decently implemented, with a very clear separation between the two steps. <br /> <br /> The javac source is located on the OpenJDK langtools repository, which hosts a series of tools like javadoc, javah etc.. Go to <a target="_blank" href="">this link</a> for more detail about langtools. If you have Mercurial installed, check out the code from <i><a href="" target="_blank"></a></i>, or if not, you can download an archived copy from <a target="_blank" href="">this link</a> as well. After you get the source, try to build and run it to make sure it works properly. Refer to this <a target="_blank" href="">link</a> for how to do this.<br /> <br /> After getting the code, let's try to make a very simple javac tree for this file [<a href="/yj/resource/Test.java">Test.java</a>]</p> <p><br /> <i>public class Test{<br /> public static void main(String[] args){<br /> System.out.println("Hello!");<br /> }<br /> }</i><br /> <br /> The code we are interested in are located located at:<br /></p> <ul> <li><i>src/share/classes/com/sun/tools/javac/parser/</i>, which contains the parser related code. </li> </ul> <ul> <li> <i>src/share/classes/com/sun/tools/javac/main/</i>, which contains main controller that calls and integrates the two steps.</li> <li><i>src/share/classes/com/sun/tools/javac/tree</i>/, which contains all the tree related classes.<br /></li> </ul> <p> <br /> There are four major types of node for our Test.java file:<br /></p> <ul> <li> .java file, which may contain more than one classes, that is parsed as <i>com.sun.tools.javac.tree.JCTree.JCCompilationUnit</i></li> </ul> <ul> <li> class, that is parsed as <i>com.sun.tools.javac.tree.JCTree.JCClassDecl</i></li> </ul> <ul> <li> method, this is parsed as <i>com.sun.tools.javac.tree.JCTree.JCMethodDecl</i></li> </ul> <ul> <li> And the System.out.println("Hello!") method call, which is a combination of <i>com.sun.tools.javac.tree.JCTree.JCFieldAccess</i> and <i>com.sun.tools.javac.tree.JCTree.JCMethodInvocation</i>.</li> </ul> <p> <br /> These classes all represent complicated data structures, to create instance of these them you need an instance of<br /> com.sun.tools.javac.tree.TreeMaker.<br /> <br /> For example, to create an instance of JCClassDecl, call this method</p> <p><i><br /> public JCClassDecl ClassDef(JCModifiers mods,<br /> Name name,<br /> List<JCTypeParameter> typarams,<br /> JCTree extending,<br /> List<JCExpression> implementing,<br /> List<JCTree> defs)</i> </p> <p><br /> The names of the parameters are quite self explanatory. And most of them are not really needed here, like the third one- the type parameters. We are not using generics, so just leave it to be a blank list.</p> <p><br /> Two things worth noting here are:<br /></p> <p> First, the List here is not of java.util.List. It's instance of com.sun.tools.javac.util.List.<br /> </p> <p>Second, the parameter name is a special class for storing identifiers string in the parser. Refer to the attached source file for how to constructing it. For now, just think it as a String representing the name of the class.<br /> </p> <p>So, as you can see, it is pretty easy to builds a tree for our simple class. I won't dwell on how to make the rest of the tree nodes, refer to <a href="/yj/resource/DummyTreeMaker.java">DummyTreeMaker.java</a> for details, which creates the tree matches <a href="src/share/classes/com/sun/tools/javac/parser/DummyTreeMaker.java">Test.java</a>.<br /> <br /> Then after building the tree, next thing to do is to make the code generator to generate code for us.<br /> </p> <p>However, javac is not designed to let you do this and there is no easy way to achieve this without some inelegant hacking. <br /> </p> <p.<br /> <br /> All this can be done by switching two lines of code in </p> <p><i>src/share/classes/com/sun/tools/javac/main/JavaCompiler.java.</i><br /> </p> <p>Find the method <br /> <br /> <i>protected JCCompilationUnit parse(JavaFileObject filename, CharSequence content)</i><br /> <br /> Then look for the following two lines:</p> <p><br /> <i> Parser parser = parserFactory.newParser(content, keepComments(), genEndPos, lineDebugInfo);<br /> tree = parser.parseCompilationUni</i>t();<br /> <br /> That's the only place the compiler interacts with the parser. All we need to do is to trick the compiler to take our tree in the second line.<br /> Replace the two lines with </p> <p><br /> <i> if (Options.instance(context).get("xtest") != null) {<br /> DummyTreeMaker maker = new DummyTreeMaker(parserFactory);<br /> tree = maker.getTree();<br /> } else {<br /> Parser parser = parserFactory.newParser(content, keepComments(), genEndPos, lineDebugInfo);<br /> tree = parser.parseCompilationUnit();<br /> }</i><br /> <br /> Then build the workspace, create a blank file called Test.java, try to compile it with the javac you just built, like<br /><i></i></p> <p><i> javac -XDxtest=true Test.java</i><br /> <br /> Run the generated file and you'll see "Hello!" printed on the screen. <br /> As you can see, javac takes a blank java file, but uses our tree to generate code.</p> <p>This is a pretty simple example, and is pretty much how javac parses your source file, although the real process is a little more complicated because the javac parser also has to generate line-info, process javadoc, do error report etc.. </p> <p>Now imagine we have a grammar, like this <a target="_blank" href="">one</a> in the Java Language Specification, and we embed java code into the grammar calling different method in TreeMaker to build different AST nodes as the grammar recognize different constructs. Then we have an automated parser doing the same thing as the javac. This is how the <a target="_blank" href="">Compiler Grammar</a> project works -- with the help of <a href="" target="_blank">Antlr</a>, a automatically grammar-generated parser building the same kind of AST trees as javac does. Refer to my previous post on how to build and run the <a target="_blank" href="">Compiler Grammar</a> project. What's more interesting, once we have this grammar, it can be used more than building trees -- code formatting, code translation etc. all made possible, just use some imagination :)<br /></p> <p> </p> <p> </p> <p> </p> <p> </p> <p> </p> <p><br /></p> <p> </p> <p> </p> <p><br /> </p> <p> </p> <p> </p> <p> </p> <p><b><font size="1">Download the source files:</font></b></p> <p><a href="/yj/resource/DummyTreeMaker.java">DummyTreeMaker.java</a> This need to be put under <i>src/share/classes/com/sun/tools/javac/parser/DummyTreeMaker.java</i></p> <p><a href="/yj/resource/JavaCompiler.java">JavaCompiler.java</a> Replace this one with the file with the same name located under <i>src/com/sun/tools/javac/main</i>. This file may not compile in the future, as the langtool source code is changed very often. If so, just locate the file and make changes as decribed above.<br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /></p>
http://blogs.oracle.com/yj/feed/entries/atom?cat=%2FPersonal
CC-MAIN-2013-20
refinedweb
1,466
56.15
Numba is a compiler for Python array and numerical functions that gives you the power to speed up your applications with high-performance functions written directly in Python. What makes python slow? Python has been used for scientific computing for a long period of time. Though Python is a great language for prototyping, the barebone python lacks the cutting edge for doing such huge computations. What makes python inherently slow are ironically the features that make Python so popular as a language. Let us review them one by one: - Dynamically Typed: Python is a dynamically typed language i.e. users need not specify the data type associated with the variable. Although this makes things a lot simpler on the upper surface, the inner mechanisms become complicated by many folds as the interpreter needs to check the data type and associated conversion every time an operation is done. These increased and complicated instructions are mainly responsible for the speed of python. - Memory Overheads: Due to the flexible nature of Python, individual memory needs to be allocated for every small object like int in a list (unlike C which takes a contiguous chunk of memory for an array). This means the objects in the list are not placed near each other in memory, which affects the time cost for each fetch operation. - Non-Compiled: Compilers like LLVM, GCC can have a look ahead on the program and make some high-level optimizations, which saves both memory and speed. Python Interpreter on the other hand is unaware of the next line of execution, so it fails to apply any time-saving optimizations. - GIL Lock: The Global Interpreter Lock(GIL) does not allow multithreading. It ensures only one thread executes Python byte code. This simplifies the CPython implementation by making the object model implicitly safe against concurrent access. In this article, we will see how numba overcomes these difficulties, and how it can be used to speed up our code to the likes of C/C++ and FORTRAN. What is Numba? According to the official documentation, “Numba is a just-in-time compiler for Python that works best on code that uses NumPy arrays and functions and loops”. The JIT compiler is one of the proven methods in improving the performance of interpreted languages. During the execution of the program, the LLVM compiler compiles the code to native code, which is usually a lot faster than the interpreted version of the code. As discussed earlier the compiler can add some high-level optimizations, which can benefit the user both in terms of memory and speed. Numba comes with Anaconda distribution and also on wheels, so it can be installed by conda install numba or, pip install numba Note: Linux users might need to use pip3 instead of pip. Using Numba in Python Numba uses function decorators to increase the speed of functions. It is important that the user must enclose the computations inside a function. The most widely used decorator used in numba is the @jit decorator. Using this decorator, you can mark a function for optimization by Numba’s JIT compiler. Let’s see a use case for a trivial function. from numba import jit import numpy as np @jit # Placing the @jit marks the function for jit compilation def sum(a, b): return a + b Numba will hold the compilation until the first execution. During the first execution, numba will infer the input type and compile the code based on that information. The compiler also adds some optimizations specific to that input data type. A direct consequence of this is, the function will have different execution code for different type of variables. User can experience some delay in executing the function for the first time. This apparent time gap is due to the compilation of the function. After the compilation, the user can expect the normal speed of numba compiled functions. One common trick is to use a small dummy variable for executing the code for the first time. Note: Don’t change the data type of the variable inside a function. Changing the data type means numba can no longer infer the data type and optimize the function properly. 1. Eager mode One downside of this above approach is we must wait until the first execution for the compilation. We can overcome it by eager mode. In eager mode, we specify the data type of the input, so the compiler need not infer from the input and compiles the function one the go. This is called eager execution and here is how we can do that, @jit(int32(int32, int32)) def sum(a, b): return a + b The compiler no longer waits for first execution, and compiles the code applying specializations for given type. It allows the user more and more control over the type of variables to used. 2. No GIL mode Compiling the code sets us free from the python Global Interpreter Lock. We can specify not use the GIL using nogil=True @jit(nogil=True) def sum(a, b): return a + b 3. No-python mode There are two modes of execution- nopython and object mode. In nopython mode, the compiler executes the code without the involvement of the interpreter. It is the best way to compile using numba.jit(). @jit(nopython=True) def sum(a, b): return a + b Numba works best with numpy arrays and functions. Here is an example from the official doc using numpy function. from numba import jit import numpy as np x = np.arange(100).reshape(10, 10) @jit(nopython=True))) Conclusion Numba offers speed compared to the likes to C/C++, FORTRAN, Java, etc. without affecting any of the syntactic sugar of python. One of the downsides of numba is, it makes the python code less flexible, but allowing fine-grained control over variables. Numba can make your life easier if you are doing heavy scientific simulations (which require fast processing and parallelization capabilities) using python. References - -
https://www.askpython.com/python-modules/numpy/numba
CC-MAIN-2021-31
refinedweb
996
53.71
- Training Library - Google Cloud Platform - Courses - Deploying Applications on GCP - Compute Deploying Applications and Services on Google Kubernetes Kubernetes Engine. The exam guide for the Pro Developer certification says that there are some things you'll need to know about GKE, specifically deploying a GKE cluster, deploying a containerized application to GKE, configuring GKE application monitoring and logging, creating a load balancer for GKE instances and building a container image using Cloud Build. Now, if you're familiar with Kubernetes, then you know it is a non-trivial system. So, when looking at these bullet points, it seems deceptively simple, however, let's examine each of these a bit further and we'll start with the topic of deploying a GKE cluster. Deploying a GKE cluster is a reasonably simple process. It's one command with gcloud and it's just a form if you're inside of the console. Though, for a professional-level certification, high-level requirements such as being able to deploy a GKE cluster aren't often trying to ensure that you've memorized a few key commands. So, when Google says that before you take the exam you should know how to deploy a GKE cluster, they're likely saying something such as, "You should have deployed a GKE cluster or two," probably more like 10 or 15. You should be thinking about automated deployments, which means you should be familiar with the gcloud command line. You should also be familiar with the functionality of Kubernetes. When they say you should be familiar with deploying containerized applications they are saying you should have built docker container images. You should have pushed images to a container registry. You should also be comfortable with the kubectl binary. Each bullet point is abstracting away a lot of information here. So, let's try and unpack as much as we can. This is a command you should be familiar with before the exam: gcloud container clusters create. One more time, that's gcloud container clusters create. Why not, gcloud Kubernetes cluster create? Why, container, singular? I'm guessing that's because it used to be called container engine and so the container namespace just didn't change. Why is it plural? I don't know, I am fairly certain that's just a sub-command naming convention. Now, all of these arguments are fairly self-descriptive. So, this command will create a GKE cluster. It's a pretty vanilla deployment. It's a single zone cluster using a small machine type and it's running COS. In a real-world application we'd likely have a cluster with more nodes running in multiple zones for increased availability and ideally we'd use autoscaling here to help make sure that we hit that ideal utilization range so that we're not over or under-provisioning. Recall that talking about Stackdriver with Kubernetes is one of the exam objectives so let's kick off that discussion now and talk about the now-legacy Stackdriver monitoring and logging, which has been replaced by Stackdriver Kubernetes Engine Monitoring, which centralizes the functionality and is supposed to be like a single pane of glass for GKE. Currently, you can use any of these options or none of them at all. To enable the newest incarnation of Stackdriver, you use the --enable-stackdriver-kubernetes flag. All right, now let's circle back to Stackdriver later, for now let's talk about deployment of containers. The results of the clusters create command is a three-node cluster of small instances with Stackdriver enabled. If not specified, the default number of nodes is three because three is the smallest effective cluster size that offers redundancy. Kubernetes is all about running containers and it's often necessary to run multiple containers together, which is why Kubernetes abstracts this concept into a concept of a pod. A pod is just one or more containers that will always be co-located. It's the smallest unit of deployment. It's just a simple wrapper for containers and creating pods directly is kind of like us as developers manually starting a web server process on a remote server. There's just nothing there to ensure that it stays running. So, it will run until it stops and then that's it. Kubernetes has higher-level abstractions, which they call controllers, which help. A ReplicaSet is a type of controller that can ensure a specified number of pods are always running. ReplicaSets aren't something recommended for direct use unless you understand a specific use case for it. And the reason is: ReplicaSets are really just still too low-level. They can ensure that you have the number of pods that you want though they don't have any sort of control over the deployments. If you wanted to update the pods to use a new image, you'd have to figure out how to do that for yourself and deploy those new pods without interrupting the service. So, Kubernetes provides higher level controllers such as deployments. Deployments can deploy either pods or ReplicaSets and they have built-in functionality for rolling updates. Deployments define the pods that should be running with a pod template specification. Kubernetes will compare what currently exists against the pod template and roll out new pods without downtime. Up to this point, the concepts that we've covered would allow us to deploy our container images, though it's still not clear how we would interact with them over the network. Every pod gets an ephemeral IP address. It's something that we can use to interact with the pods directly and for debugging that could be effective if we wanted to do that. However, Kubernetes has a concept called a service which can become an entry point for a group of pods. Services get an IP address and distribute traffic to a specific group of pods. The default service type is called a clusterIP which creates an entry point for these specified pods for the entire cluster. NodePort services create an entry point that directs traffic to a specified port on Nodes, and load balancer services build on a cluster or NodePort to add additional functionality of load balancing. The primary interface for actually using Kubernetes is the kubectl binary. It's part of Kubernetes, not just GKE and you can download it for yourself through the Kubernetes website or you could also install it as a gcloud component. Kubernetes uses desired state configuration which means you specify what you want Kubernetes to make and it's going to do that. Kubectl has the ability to manage resources directly on the command line or by defining the desired state in YAML files. Both work, though YAML allows for configuration to be version controlled which is always good. Let's perform two deployments. The first will create an actual deployment, the deployment will use a ReplicaSet to create three copies of a pod. The pod includes one container, it's just going to run engine X and after that, we'll create a service so that we can load balance traffic to the pods in our deployment. Here's a look at the YAML for the deployment. And we're telling Kubernetes that we want three replicas of a pod with one container running nginx, which pulls from the public Docker registry. The command here is kubectl apply. Apply expects a YAML file and for that we use the -f flag. And once we have this complete, we can view our resources with the kubectl get and kubectl describe commands. Get deployments actually lists all of the deployments and describe will inspect an individual deployment. With these pods being available, we can now interact with them over the network if we use a pod's IP address, that's that ephemeral IP address I mentioned previously. However, services allow us to have a single entry point for a group of pods. So, let's create one and we can do that in the same file as our deployment, though we could also create a separate file. The resource kind here is a service of type load balancer and it maps port 80 to port 80 on the pods. Again, this is created with kubectl apply just like everything else that's specified in YAML. This will create the service in Kubernetes fairly quickly. Though behind the scenes it's actually creating a load balancer for us so that we can make this accessible to the outside world. So by creating this in Kubernetes, we're telling Kubernetes this is what we want. Kubernetes has said, "I understand," and it's up to Kubernetes to go figure that out. So, these sorts of commands, even if they respond and say that it was created, may take a little while to actually implement whatever it is that we've asked of it. So, I'm going to jump a few minutes ahead and here is our created service. The external IP address is the IP of the load balancer for this service which will route traffic from the internet to our service. A service knows which pods to include based on the selector provided. In this case, it's using the label from the deployment of run with the value of web server and it found our replicas. Because of the way that Kubernetes is label based, it allows us to have really interesting deployment options so that we could have similar labels for certain things and then differentiate based on maybe a canary would get its own label so that we could roll a canary out, see how it performs inside of a deployment. So, when you're thinking about deployments with Kubernetes just remember how powerful selectors are in allowing us to target specific pods that should all receive traffic from the same front-end source. Alright, with all of the moving parts in a Kubernetes cluster, there is a lot to monitor and it's not just about applications, we also need to keep tabs on the cluster. So, let's finish our earlier discussion about Stackdriver. Stackdriver Kubernetes Engine Monitoring is a single pane of glass that displays cluster-level metrics and from inside Stackdriver on the Kubernetes resource, we get details of all the cluster. Infrastructure details show metrics for the system processes, which run as pods and we get workload details including basic logs from a container's standard error and standard output. We can still use the log viewer to further inspect the logs and there's a kubectl command that allows you to inspect the logs of current and previous pods and this assumes of course that you're writing to standard out or standard error. If you have a pod that is using more than one container and you need to see the logs for just the container, you can actually filter the logs by container name as well. If you don't yet have a lot of experience with Kubernetes or the logging of applications from pods then I recommend checking out the documentation on Kubernetes website (), especially the logging architectures section. If terms such as DaemonSet or Sidecar are new to you then it probably is worth giving it a read. Alright, the container image that we deployed is from the docker registry. In production we'll probably end up using our own images. GKE has some complementary services, namely Cloud Build and Container Registry. Cloud Build, as the name suggests, is a build service in the cloud and Docker container images are one type of resource that it knows how to build. Here is a Dockerfile for this demo. It uses a minimal alpine base and it creates a shell script that just loops every second and echos to standard out. The gcloud build submit command takes a tag name input and it takes the current contacts for Docker and it uploads the contacts in Dockerfile. It builds the images and then pushes it to the Container Registry. Now, this is really just a thin wrapper around Docker allowing us to have images built in the cloud. Besides building Docker images from a Dockerfile, we can also create a build config where we specify the steps that should be taken for each phase of the build. Rather than specifying the Dockerfile, we could provide Cloud Build with the config file and it will run through each of the steps and produce an artifact. With this built we could use it as the image for our pod. So, let's use it in the console and actually deploy it. And using the select button we can select the image and version, of course we only have the one version in this case and once the instance is running, it's going to echo some text to standard out and because it's just piping that to standard out that means Stackdriver logging can actually pick this up without any additional configuration. Alright, that's gonna wrap this up. This isn't easy for everyone to pick up quickly. Kubernetes, no matter how well-engineered, is a complex system and it's ever changing. Before taking the exam, make sure you're comfortable with deploying applications, creating services not just load balancers but clusterIPs and NodePorts for internal traffic. Deploy containerized services, break stuff and try and diagnose it and then fix it. Thank you so much for watching and I will see you in another lesson.
https://cloudacademy.com/course/deploying-applications-on-gcp-compute/deploying-applications-and-services-on-google-kubernetes-engine/
CC-MAIN-2021-17
refinedweb
2,268
60.55
Error Running Flask latest beta Guys, I am having a problem getting the minimal flask app running on the latest beta, iOS11.2.1. The code below. It works under py 2.7 in the beta. I remember an error I had before was with the debug param. But this is correct now. I did a pip install of fllask(full restart etc) to see if that would help. But the same error. I always seem to have problems getting started with flask :( Any help appreciated from flask import Flask app = Flask(__name__) @app.route('/') def entry_point(): return 'Hello World!' if __name__ == '__main__': app.run(debug=False) Traceback - Traceback (most recent call last): File "/private/var/mobile/Library/Mobile Documents/iCloud~com~omz-software~Pythonista3/Documents/FlaskTesting/flask__testing.py", line 1, in <module> from flask import Flask File "/var/containers/Bundle/Application/F132DFB7-BD77-4096-ADA6-D8CA8F4468F2/Pythonista3.app/Frameworks/Py3Kit.framework/pylib/site-packages/flask/init.py", line 19, in <module> from jinja2 import Markup, escape File "/private/var/mobile/Containers/Shared/AppGroup/3533032E-E336-4C25-BBC4-112A6BF2AF75/Pythonista3/Documents/site-packages/jinja2/init.py", line 37, in <module> from jinja2.environment import Environment, Template File "/private/var/mobile/Containers/Shared/AppGroup/3533032E-E336-4C25-BBC4-112A6BF2AF75/Pythonista3/Documents/site-packages/jinja2/environment.py", line 575 info.external_attr = 0755 << 16L ^ SyntaxError: invalid token @Phuket2 Any particular reason you're not using the bundled version of Flask? There's no need to install anything to run the script you've posted, and it works fine here... @omz , As far as I can tell I am using the pre installed version of Flask. When it failed, I just tried to pip install it. It didn't work so I pip remove 'ed it. I have looked though my site packages folder and I have no folder named flask, si I am assuming it's using the shipped version. I have done hard restarts on Pythonista also @Phuket2 It seems that Flask is importing jinja2, and you have a version of that in your site-packages, possibly one that only works on Python 2. Try removing jinja2from your site-packages, then restart Pythonista. @dgelessus , thanks that was the problem.....Not sure why my brain goes blank. I should have looked for that @dgelessus , oh I can see where it all went wrong now. I pip installed flask-restful, that also installs flask and jinta. I have been able to re-install flask-restful and delete the folders in the site-packages and have it working now. Thanks again.
https://forum.omz-software.com/topic/4567/error-running-flask-latest-beta/2
CC-MAIN-2022-33
refinedweb
426
60.11
Build Server Side Authentication in Grails with OAuth 2.0 and Okta What is Grails, what is Groovy, and why would we choose them over Spring Boot? In this post I’ll walk you through implementing server-side authentication in Grails using OAuth 2.0 and Okta. Before we dive in, however, I want to talk a little bit about why you’d be using Grails + Groovy in the first place, and how it can make your life easier in specific situations. Grails is an open source “convention over configuration” web application framework built on Groovy. It’s essentially a JVM version of Ruby on Rails. It’s opinionated and full-featured and has a strong emphasis on ORM, templating, and plugins. Grails is built on Spring Boot. Groovy is a superset of Java that compiles down to JVM bytecode and interoperable with pure Java, but adds tons of great meta-programming and functional programming features, while also slashing the ceremony code that can plague pure java. Update: See part two of this series which flushes which adds additional controllers and authorization. Why Use Grails Over Spring Boot? If Grails is built on Spring Boot, why not just use that? Good question! The answer depends on your goals and your background (ie, do you already know and love Spring?). Let’s look at Grails + Groovy: - Grails and Groovy may be easier to dive into if you’re not already familiar with Spring - Grails has a great templating system and full-featured ORM - Grails is built on Spring Boot, so (theoretically, at least) you can get the best of both worlds. In practice this might be easier said than done. - Grails has super easy JSON conversion and test-driven development - Groovy is a super awesome language that’s a pleasure to develop in - Grails may be waning in popularity. The upgrade from 2.x to 3.x was bumpy and caused a lot of grumbling in the community. Let’s look at Spring: - Spring Boot is great for simple REST API services - Spring Data is super powerful but correspondingly complicated - Templating in Spring is pretty old-fashioned these days - Spring has a HUGE community and massive enterprise support. - Spring also has easy JSON conversion and TDD - The larger Spring architecture is incredibly powerful once you wrap your head around it So what’s the verdict? My suggestions are: - If you’re not already into Spring, and you want to develop a web application quickly, go with Grails. It’s easy and developer friendly by design. - For simple REST services, Spring Boot or Apache Jersey + Shiro might be good alternatives. There’s really no point in using Grails if you’re not going to use the ORM and/or templating capabilities. - If you’re building a large enterprise app or API system and require a guarantee of long term support (many years), or are already deep into Spring, then Spring Boot may be your best bet. Let’s start by installing Grails. Groovy and Grails use an install/update manager called SDKMAN. The install is super easy, and we’ll walk you through it below, but if you’d like to see the complete instructions, look here. Install SDKMAN: # follow instructions to install SDKMAN! curl -s get.sdkman.io | bash Load SDKMAN into your shell: source "$HOME/.sdkman/bin/sdkman-init.sh" Install the latest stable version of Grails: sdk install grails Test the install (should look something like this): grails -version | Grails Version: 3.3.3 | Groovy Version: 2.4.14 | JVM Version: 1.8.0_102 Create Your New Grails Application Grails uses a command-line shell similar to Ruby or React. We will be creating a simple app called “OktaCameraKit” that we uses can use to organize their camera lenses. In the shell, move to a directory in which you would like the new project generated and enter the following. grails create-app OktaCameraKit | Application created at /okta/grails/OktaCameraKit This should have created your application in the “OktaCameraKit” subdirectory with the following directory structure: Test Your New Grails App “cd” into the “OktaCameraKit” directory and run: grails run-app You should see something like this: | Running application... :compileJava NO-SOURCE :compileGroovy UP-TO-DATE :buildProperties UP-TO-DATE :processResources :classes :findMainClass :bootRun Grails application running at in environment: development <===========--> 85% EXECUTING Open your browser to and you should see the Grails welcome screen. NOTE: I heartily suggest downloading and trying out the Community Edition of IntelliJ IDEA. JetBrains products are fantastic, and the free Community Edition of their premier Java development IDE is a godsend. Check it out! Some Basics on Grails The basic idea in Grails is that Controller classes have Action methods that load data from Models and map the data that is presented in Views. Grails is opinionated and expects controllers to be in the “controllers” directory and “views” to be in the views directory. DO NOT, UNDER ANY CIRCUMSTANCES, PUT FILES IN THE WRONG PLACE. You will hurt Grails’ feelings and it may not work for you. But seriously, if you’re used to more contemporary Javascript frameworks, you may not be used to the well-defined structure that Grails expects. If you surrender to it, you may learn to love it! A good structure can free you to worry about more important things, like writing your app! You certainly end up with fewer lines of code like this: import ../../../../../../app/module/resources/blah.js Don’t Forget About Gradle What’s with all the “G”s? Yep. There’s a lot of them: Groovy, Grails, Gradle. It’s been scientifically proven that alliteration increases the performance of programming toolkits at developer conferences. Gradle is a super powerful build system that “eclipsed” Maven as the build tool of choice in the JVM world. It’s built on Groovy and uses a Domain Specific Language that makes it infinitely powerful. If the universe had been built with Maven, the earth would not be revolving around the sun because we’d still be resolving dependencies. Fortunately, Gradle was invented, and all is well. Add Authentication with Spring Security and Okta We are going to use the Spring Security Core Plugin and the Spring Security OAuth 2.0 plugin to connect with Okta OAuth. There are, however, a few other options. Apache Shiro has a plugin that integrates nicely with Grails. Shiro is a fine alternative that is worth examining. If you are building an API service that will have client-side authentication, then you might want to look at the Okta Spring Boot Starter, which makes authentication super simple, and Zachary Klein’s Grails + React + Okta demo. Because we will be using a purely server-side authentication flow, we can’t use the authentication filter method implemented in the Spring Boot Starter. Now, you may be tempted to think: “Hey! Grails is just Spring Boot with some bells and whistles. Why can’t I just use Spring authentication, like in this great Okta tutorial?” I know I did. That was what I tried first. Let me save you some time, it doesn’t work. Spring Security does a funny thing and uses thrown exceptions to handle the OAuth redirects. These are supposed to propagate up to the Spring servlet context, where they are caught and handled. Unfortunately, Grails has it’s own custom GrailsDispatcherServlet that overrides this behavior, catching the exceptions before they can be handled by the Spring filters. You could potentially create a subclass of the GrailsDispatcherServlet that checks for the OAuth exceptions and re-throws them, but Grails 3.0 made this more complicated – and anyway the whole scheme starts to feel pretty “hacky” fighting the framework instead of doing it the “right” way. Okta Provider Plugin for Grails Spring Security OAuth 2.0 What’s the “right” way? Writing a provider plugin for the Grails spring-security-oauth2 plugin that tells Grails how to “talk” to Okta as an OAuth 2.0 provider. Fortunately for you, I’ve already done this. If you don’t already have an account with Okta, now would be a great time to sign up for a free developer account. Don’t forget to note your Okta URL as we’ll need it in a minute. Create Your Okta Application Once you’ve logged into your Okta dashboard, you need to create an Application. You also need an Authorization Server, but fortunately for the purposes of this tutorial we can just use the default one. From your Okta admin panel, click on Applications in the top menu and then click “Add Application” Select the web application icon and then click Next. Next, we need to update the “Login redirect URIs”. OAuth 2.0 requires a whitelisted redirect URI that the OAuth server can direct the app to after successful login. The URL we’ll be using is:. Enter that into the field and then hit “Done!” You’ll need to copy your Client ID and Client Secret to a safe place for later. That’s it for Okta setup for our purposes. You can certainly dig MUCH deeper into the OAuth rabbit hole with tons of configuration options. Take a look here to get started. Dive Back Into Grails! We need to install three dependencies: - Grails Spring Security Core Plugin (adds core Spring Security features) - Grails Spring Security OAuth2 plugin (adds OAuth 2.0 features) - Okta OAuth 2.0 Provider Plugin (tells the OAuth plugin how to talk to Okta) Edit your build.gradle file, adding the new Maven repository and the three compile dependencies, as seen below. repositories { ... maven { url "" } } dependencies { compile 'org.grails.plugins:spring-security-core:3.2.1' compile 'org.grails.plugins:spring-security-oauth2:1.1.0' compile 'spring.security.oauth2.okta:spring-security-oauth2-okta:0.1' ... } The plugins come with a quickstart script that we need to run to generate some domain files and set up some configurations. From your main project directory, run the following command: grails s2-quickstart com.oktacamerakit User Role This creates your User and Role domain classes and adds some authentication configuration entries in the “grails-app/conf/application.groovy” file. Now run the OAuth 2.0 quickstart script: grails init-oauth2 com.oktacamerakit User OAuthID The starter script creates an OAuthID domain class that links the OAuth 2.0 authenticated identities to your local User domain classes, and adds a configuration line to your application.groovy file. These install scripts did a pretty good job of setting things up, be we still need to make some changes. You need to add the following line to you User.groovy domain class. It doesn’t matter where you put it as long as it’s within the class definition. static hasMany = [oAuthIDs: OAuthID] We also need to edit the UserRole.groovy class slightly. Find the create method and change the default value for the flush param to true. (This particular tip cost me about three hours of my life. You get it for free.) static UserRole create(User user, Role role, boolean flush = true) { def instance = new UserRole(user: user, role: role) instance.save(flush: flush) instance } Finally, we need to add some configuration to the application.yml file. You need to fill in your Client ID for the api_key and your Client Secret for the api_secret, as well as your Okta URL in the three URLs. grails: ### other grails config settings ### plugin: springsecurity: oauth2: active: true registration: roleNames: ['ROLE_USER'] providers: okta: api_key: '<Okta Client ID>' api_secret: '<Okta Client Secret>' userInfoUrl: 'https://{yourOktaDomain}/oauth2/default/v1/userinfo' authorizeUrl: 'https://{yourOktaDomain}/oauth2/default/v1/authorize' tokenUrl: 'https://{yourOktaDomain}/oauth2/default/v1/token' scopes: 'email profile openid' Run the App Again Whew! Lets test all that. Run the app again using grails run-app. You should see the following. Notice particularly the three new controllers listed below the “Available Controllers” heading. Add A Grails Home Controller Let’s add a Home controller for the app. Use the Grails CLI to add the controller. grails create-controller Home Open the HomeController.groovy file and edit it to match the following. We need to do two things: 1) define our authentication requirement using the @Secured annotation, and 2) add some output text. import grails.plugin.springsecurity.annotation.Secured class HomeController { @Secured('ROLE_USER') def index() { render "Success!!!" } } If you re-start the app and navigate to now you should see the Home controller listed below the authentication related controllers. If you click on the oktacamerakit.HomeController link at the bottom of the screen, you’ll be taken to a login page. Currently this is a “local” login based on the User domain objects. Since there are no local users, there’s no way to authenticate. To fix this, one option would be to add a “Login with Okta” link to the bottom of the login page. This is pretty simple and would require creating a custom login page template and adding the link. We might get back to this in Part II of this tutorial. For the moment, we’re going to configure Okta to always redirect to the Okta login page when a user needs to log in. Add the following to you application.groovy file: grails.plugin.springsecurity.auth.loginFormUrl = '/springSecurityOAuth2/authenticate?provider=okta' Give Your New App a Whirl! That’s it! You should be all set. Go ahead and log into your developer.okta.com admin panel and sign out. This will force you to log in again through the Grails app instead of automatically being authenticated via OAuth. Re-start the app, using grails run-app, and this time navigate to. The first screen you’ll see (if you signed out) is the Okta login screen: After logging in, you’ll be redirected back to your Grails app, where you’ll see the screen that allows you to either register a new account or link your OAuth account to an existing user account. Fill in the top form to register a new user account. Congrats! You Built a Grails App with Okta for Authentication Success! We did it! Pretty simple. Obviously there’s a lot we can do from here. We’ll look at building out the app more completely in Part 2 of this tutorial. We need to create some domain and controller classes to model our data, set up some views, and hook our authenticated users into a authorization system. I’ll also show you how to run the remote debugger in IntelliJ, configure logging, and set up the database so development data is persisted between sessions (right now it’s recreated every time the app is run, which is why the app will never remember who you are if you restart). Learn More about Grails, Gradle, Groovy, and Okta If you’d like to learn more about Grails to get ready for Part 2 check out the documentation and Groovy Language Documentation. While you’re in the Grails docs, make sure to familiarize yourself with the basic folder structure of the Grails application. As we saw, it can be touchy. You may also want to take a look at Understanding Controllers and Actions. And finally, you can check out the Gradle docs. If you’d like to learn more about Okta, you should definitely be following our team on Twitter @oktadev. You can also check out these other cool Java posts:
https://developer.okta.com/blog/2018/04/19/okta-with-grails
CC-MAIN-2018-51
refinedweb
2,567
65.22
Type: Posts; User: loves_oi 3 processes run this task. When process A runs wait(), does process A blocked until both B and C run wait() and semaphore becomes zero ? Hi, i'm wondering the bahaviour of the following code fragment. Assume that, firstly process A will invoke wait(), then B, and then C. semaphore s=3; while(1) { s.wait(); Hello, i need to write such a code that, three processes will run concurrently, namely all 3 of them should be at the same region at the same time. The task looks like something like that: Task... I'm using cout to print lots of lines. But i want to put together them in one variable etc. Then , i want to print it. I think i can do it with ostream but I cant do it . Is there anybody to give... template<class T> class Convert { T data; public: Convert(const T& tData = T()) : data(tData) { } template<class C> bool IsEqualTo( const C& other ) const I have the below main . int main(void) { try{ Product p1("makarna", "gida", 1,9 ); Product p2("peynir", "gida", 3,4 ); Product p3("peynir", "gida", 3,10 ); Product p4("cif",... this is my header file #ifndef HW1_H #define HW1_H #include <iostream> #include <string> #include <vector> using namespace std; i spend one hour for it . But i forgot a small point :( i found thanks to God. I forgot including Product class. After including, it worked. Thanks for your interest Product Store::getProduct(int index) { int indexim=0; vector<Product>::iterator it; for ( it=(this->availableProducts.begin()) ; it < (this->availableProducts.end()); it++,indexim++ ) {... This is the header and it's forbidden to make any change in header. class Product { private: no,there arent. all is mutator Ok. second option is worked. BUt now i want to reach shoppingList vector.It's type of productClass and Product class is class Product { private: string productName; class Order /* It is forbidden to change here*/ { private: string orderID; int orderDate; string customerID; string storeName; vector<Product> shoppingList; ok. then how can i print the items which exist in the vector with the help of a function? #include <vector> #include <iostream> class Product { private: string productName; string productType; ok. I understand. Thanks a lot. Interestingly , No it is not a mistake .When i compile and run with this: memcpy(snacks.ncandy[0].bar_name, &MyChocolate, sizeof(candybar)); outputs is: ?? I study the code which is Paul McKenzie's last post and add only couts at last. That's it: #include <cstring> #include <iostream> int main() { using namespace std; struct candybar Thanks for all replies . You informed me very well. No , it shouldn't because in my first thread(i copy paste below) , p is an allocated pointer and q is not an allocated pointer. Both of them doesn't equal Null when i run the program.The output is... I am trying to understand this code.I find it from the web and copy paste directly. The comments are not mine. I want you to focus on insert function firstly. int create(struct node *p, int... I understand in this way from your words: We take space from memory randomly. Thus p is most probably Not NULL but it can be Null ( the possibility of being Null is very low) . We don't... #include <stdio.h> #include <conio.h> struct node { int num; struct node *next; }; the first one doesn't change the value of myKnap.W . i have tried the second one and fixed some deficient point in your code. It should be correct. #include<iostream> using namespace std;...
http://forums.codeguru.com/search.php?s=40d1357b50f817e79c9d6860c9d08a68&searchid=7648295
CC-MAIN-2015-35
refinedweb
597
77.33
globally unique identifier for your project. A project ID is a unique string used to differentiate your project from all others in Google Cloud. You can use the Google. The project ID is used in the name of many other Google Cloud resources, and any reference to the project or related resources exposes the project ID and resource name. Creating a project To create a project, you must have the resourcemanager.projects.create permission. This permission is included in roles like the Project Creator role ( roles/resourcemanager.projectCreator). The Project Creator role if applicable based on the user account's domain. You can create a new project using the Google Cloud console, the Google Cloud CLI, or the projects.create() method. Console To create a new project, do the following: - Go to the Manage resources page in the Google Cloud console. Go to the Manage Resources page - On the Select organization drop-down list at the top of the page, select the organization resource resource in the Location box. That resource will be the hierarchical parent of the new project. If No organization is an option, you can select it to create your new project as the top level of its own resource hierarchy. - CLI or the projects.create() method. Managing project quotas If you have fewer than 30 projects remaining in your quota, a notification displays fully delete after 30 days. To request additional capacity for projects in your quota, use the Request Project Quota Increase form., do the following: Go to the Dashboard page in the Google Google Cloud console or the projects.get() method. Console To view a project using the Google Cloud console, do the following: -())) project = crm.projects().get(name="projects/"+projectId).execute() ... Listing projects List all projects under a resource To list all projects that are direct children of a resource, use the v3 projects.list method, with the parent resource specified in the query: Request: GET { "parent": "folders/662951040570" }=" } ] } To search for projects matching the specified query, use gcloud alpha resource-manager projects search, passing the query in the --query flag. The scope of search is all the projects for which the user has projects.get permission. gcloud To get the list of all projects use gcloud alpha projects search command: gcloud alpha projects search --query="displayName=rek*" <table output showing the projects with display names starting from rek eg. rekey-project-2, rekha-project> gcloud alpha projects search --query="state:DELETE_REQUESTED" <table output showing the projects for which delete has been requested> API Google Cloud console or the projects.patch() method. The only fields that can be updated are the project name and labels. For more information about updating projects, see the project API reference page. To move a project within your resource hierarchy, see Moving a project. To migrate a project from one organization to another, see Migrating projects. Console To update a project's name or labels using the Google Cloud console, do the following: - Google Cloud CLI=PROJECT": "red" }, } ] } Python from googleapiclient import discovery from oauth2client.client import OAuth2Credentials as creds crm = discovery.build( 'cloudresourcemanager', 'v3', http=creds.authorize(httplib2.Http())) project = crm.projects().get(projectId=flags.projectId).execute() project['name'] = 'myproject' project = crm.projects().update( projectId=flags.projectId, body=project).execute() Shutting down (deleting) projects You can shut down projects using the Google Cloud console or the projects.delete method in the API. A project must have a lifecycle state of ACTIVE to be shut down in this way. This method immediately marks a project to be deleted. A notification email is sent to the user who initiated the delete operation and the Technical category contacts that are listed in Essential Contacts on a best effort basis; if the notification fails to send, the project is still marked to be deleted. If there's no contact in the Technical category, the fallback contact isn't notified. A project that is marked for deletion is not usable. If the project has a billing account associated with it, that association is broken, and isn't reinstated if the project delete operation is canceled. After 30 days, the project is fully deleted. To stop the project delete process during the 30-day period, see the steps to restore a project. You can verify the number of days left in the 30-day period by using the gcloud projects describe Google Cloud CLI method. At the end of the 30-day period, the project and all of its resources are deleted and cannot be recovered. Until it is deleted, the project counts - In the Google Cloud console, go to the IAM & Admin Settings page. - On the IAM & Admin Settings page, click Select a project. - Select Google Cloud console, you need the following permissions: resourcemanager.projects.list resourcemanager.folders.list resourcemanager.projects.get To restore a project using the Google:
https://cloud.google.com/resource-manager/docs/creating-managing-projects?utm_source=codelabs&utm_medium=et&utm_campaign=CDR_sar_aiml_vertexio_&utm_content=-&hl=ru
CC-MAIN-2022-40
refinedweb
807
55.34
dat-gui Browserified dat-gui library Want to see pretty graphs? Log in now!Want to see pretty graphs? Log in now! npm install dat-gui =dat.GUI= A lightweight graphical user interface for changing variables in JavaScript. =. If you're making changes to the source and want to see the effects of your changes without building, use require js. In your {{{head}}} tag, include the following code: {{{ }}} Then, in {{{path/to/main.js}}}: {{{ require([ 'path/to/gui/module/GUI' ], function(GUI) { // No namespace necessary var gui = new GUI(); }); }}} ==Directory Contents== - build: Concatenated source code. - src: Modular code in [ require.js] format. Also includes css, [ scss], and html, some of which is included during build. - tests: [ QUnit] test suite. - utils: [ node.js] utility scripts for compiling source. ==Building your own dat.GUI== In the terminal, enter the following: {{{ $ cd utils $ node build_gui.js }}} This will create a namespaced, unminified build of dat.GUI at {{{build/dat.gui.js}}} To export minified source using Closure Compiler, open {{{utils/build_gui.js}}} and set the {{{minify}}} parameter to {{{true}}}. ==Change log== ===0.5=== - Moved to requirejs for dependency management. - Changed global namespace from DAT to dat (lowercase). - Added support for color controllers. See [ Color Controllers]. - Added support for folders. See [ Folders]. - Added support for saving named presets. See [ Presets]. - Removed heightparameter from GUI constructor. Scrollbar automatically induced when window is too short. dat.GUI.autoPlaceparameter removed. Use new dat.GUI( { autoPlace: false } ). See [ Custom Placement]. gui.autoListenand gui.listenAll()removed. See [ Updating The Display Manually]. dat.GUI.loadremoved. See [ Saving Values]. - Made Controller code completely agnostic of GUI. Controllers can easily be created independent of a GUI panel. ===0.4=== - Migrated from GitHub to Google Code. ==Thanks== The following libraries / open-source projects were used in the development of dat.GUI: - [ require.js] - [ Sass] - [ node.js] - [ QUnit] / [ jquery]
https://www.npmjs.org/package/dat-gui
CC-MAIN-2014-15
refinedweb
305
56.11
Question Studies show that massage therapy has a variety of health benefits and it is not too expensive (The Wall Street Journal, March 13, 2012). A sample of 10 typical one-hour massage therapy sessions showed an average charge of $59. The population standard deviation for a one-hour session is σ = $5.50. a. What assumptions about the population should we be willing to make if a margin of error is desired? b. Using 95% confidence, what is the margin of error? c. Using 99% confidence, what is the margin of error? a. What assumptions about the population should we be willing to make if a margin of error is desired? b. Using 95% confidence, what is the margin of error? c. Using 99% confidence, what is the margin of error? Answer to relevant QuestionsAARP reported on a study conducted to learn how long it takes individuals to prepare their federal income tax return (AARP Bulletin, April 2008). The data contained in the file named TaxReturn are consistent with the study ...Consumption of alcoholic beverages by young women of drinking age in the United Kingdom, the United States, and Europe was reported (The Wall Street Journal, February 15, 2006). Data (annual consumption in liters) consistent ...According to statistics reported on CNBC, a surprising number of motor vehicles are not covered by insurance (CNBC, February 23, 2006). Sample results, consistent with the CNBC reports showed 46 of 200 vehicles were not ...A well-known bank credit card firm wishes to estimate the proportion of credit card holders who carry a nonzero balance at the end of the month and incur an interest charge. Assume that the desired margin of error is .03 at ...Annual starting salaries for college graduates with degrees in business administration are generally expected to be between $30,000 and $45,000. Assume that a 95% confidence interval estimate of the population mean annual ... Post your question
http://www.solutioninn.com/studies-show-that-massage-therapy-has-a-variety-of-health
CC-MAIN-2017-09
refinedweb
320
55.54
SIGTERM ignored when process has been detached from terminal I've tried to write a simple Unix daemon that reacts to signals. Here is the reduced source code sample: import Control.Concurrent import Control.Monad import System.Exit import System.IO import System.Posix.Signals loop = forever $ threadDelay 1000000 main = do ppid <- myThreadId mapM (\sig -> installHandler sig (Catch $ trap ppid) Nothing) [ lostConnection, keyboardSignal, softwareTermination, openEndedPipe ] loop trap tid = do hPutStrLn stderr "Signal received.\n" throwTo tid ExitSuccess Such daemons usually run in background without a terminal attached. I verified that I can kill the process after being started on the terminal: > ./daemon Signal received. With: > killall daemon in other terminal. Other test, when I run it in background: > ./daemon (press Ctrl+Z) > bg > killall daemon Signal received. This case is also ok. Now the third test which is also OK: > ./daemon > log 2>&1 (press Ctrl+Z) > bg > exit In second terminal: > cat log > killall daemon > cat log Signal received. > killall daemon No matching processes belonging to you were found Now the fourth test which is simply without a log file and this one fails: > ./daemon (press Ctrl+Z) > bg > exit On some other terminal try to kill the process: > killall xxx > killall xxx > killall xxx > killall -9 xxx > killall xxx No matching processes belonging to you were found Signal 9 (SIGKILL) kills the process hard without the signal trap. That's why it works, of course, but SIGTERM is being ignored for some reason. Maybe I am forgetting something, but in my opinion this should end the process properly, too.
https://gitlab.haskell.org/ghc/ghc/issues/10081
CC-MAIN-2020-24
refinedweb
261
67.35
I'm trying to use return in a ternary operator, but receive an error: Parse error: syntax error, unexpected T_RETURN Here's the code: $e = $this->return_errors(); (!$e) ? '' : return array('false', $e); Is this possible? Thanks! It doesn't work in most languages because return is a statement (like if, while, etc.), rather than an operator that can be nested in an expression. Following the same logic you wouldn't try to nest an if statement within an expression: // invalid because 'if' is a statement, cannot be nested, and yields no result func(if ($a) $b; else $c;); // valid because ?: is an operator that yields a result func($a ? $b : $c); It wouldn't work for break and continue as well. No it's not possible, and it's also pretty confusing as compared to: if($e) { return array('false', $e); } This is the correct syntax: return !$e ? '' : array('false', $e); No, that's not possible. The following, however, is possible: $e = $this->return_errors(); return ( !$e ) ? '' : array( false, $e ); Hope that helps. Close. You'd want return condition?a:b No. But you can have a ternary expression for the return statement. return (!$e) ? '' : array('false', $e); Note: This may not be the desired logic. I'm providing it as an example. Similar Questions
http://ebanshi.cc/questions/617467/using-return-in-ternary-operator-php
CC-MAIN-2017-09
refinedweb
214
66.84
by Charlee Li The best way to bind event handlers in React Binding event handlers in React can be tricky (you have JavaScript to thank for that). For those who know the history of Perl and Python, TMTOWTDI (There’s More Than One Way To Do It) and TOOWTDI (There’s Only One Way To Do It) should be familiar words. Unfortunately, at least for event binding, JavaScript is a TMTOWTDI language, which always makes developers confused. In this post, we will explore the common ways of creating event bindings in React, and I’ll show you their pros and cons. And most importantly, I will help you find the “Only One Way” — or at least, my favorite. This post assumes that you understand the necessity of binding, such as why we need to do this.handler.bind(this), or the difference between function() { console.log(this); } and () => { console.log(this); }. If you get confused about these questions, Saurabh Misra had an amazing post explaining them. Dynamic binding in render() The first case commonly used is calling .bind(this) in the render() function. For example: class HelloWorld extends Component { handleClick(event) {} render() { return ( <p>Hello, {this.state.name}!</p> <button onClick={this.handleClick.bind(this)}>Click</button> ); }} Of course this will work. But think about one thing: What happens if this.state.namechanges? You might say that changing this.state.name will cause the component to re- render() . Good. The component will render to update the name part. But will the button be rendered? Consider the fact that React uses the Virtual DOM. When render occurs, it will compare the updated Virtual DOM with the previous Virtual DOM, and then only update the changed elements to the actual DOM tree. In our case, when render() is called, this.handleClick.bind(this) will be called as well to bind the handler. This call will generate a brand-new handler, which is completely different than the handler used when render() was called the first time! As in the above diagram, when render() was called previously, this.handleClick.bind(this) returned funcA so that React knew onChange was funcA. Later, when render() is called again, this.handleClick.bind(this) returned funcB (note it returns a new function every time being called). This way, React knows that onChange is no longer funcA, which means that button needs to be re-rendered. One button may not be a problem. But what if you have 100 buttons rendered within a list? render() { return ( {this.state.buttons.map(btn => ( <button key={btn.id} onChange={this.handleClick.bind(this)}> {btn.label} </button> ))} );} In the above example, any button label change will cause all the buttons to be re-rendered, since all buttons will generate a new onChange handler. Bind in constructor() An old school way is to do the binding in the constructor. Nothing fancy: class HelloWorld extends Component { constructor() { this.handleClick = this.handleClickFunc.bind(this); } render() { return (<button onClick={this.handleClick}/>); }} This way is much better than previous one. Calling render() will not generate a new handler for onClick, so the <button> will not be re-rendered as long as the button does not change. Bind with the Arrow Function With ES7 class properties (currently supported with Babel), we can do bindings at the method definition: class HelloWorld extends Component { handleClick = (event) => { console.log(this.state.name); } render() { return (<button onClick={this.handleClick}/>) }} In the above code, handleClick is an assignment which is equivalent to: constructor() { this.handleClick = (event) => { ... };} So once the component is initialized, this.handleClick will never change again. This way, it ensures that <button> won’t get re-rendered. This approach is probably the best way of doing bindings. It’s simple, easy to read, and most importantly, it works. Dynamic binding with the Arrow Function for multiple elements Using the same arrow function trick, we can use the same handler for multiple inputs: class HelloWorld extends Component { handleChange = name => event => { this.setState({ [name]: event.target.value }); } render() { return ( <input onChange={this.handleChange('name')}/> <input onChange={this.handleChange('description')}/> ) }} At first glance, this looks pretty amazing due to its simplicity. However, if you consider carefully, you’ll find that it has the same problem as the first approach: every time render() is called both <input> will be re-rendered. Indeed I do think this approach is smart, and I don’t want to write multiple handleXXXChange for each field either. Luckily, this type of “multi-use handler” is less likely to appear inside a list. This means that there will be only a couple of <input> components that get re-rendered, and there probably won’t be a performance issue. Anyway, the benefits it brings to us are much greater than the performance loss. Therefore, I would suggest that you use this approach directly. In case those performance issues becoming significant, I would suggest caching the handlers when doing the bindings (but this will make the code less readable): class HelloWorld extends Component { handleChange = name => { if (!this.handlers[name]) { this.handlers[name] = event => { this.setState({ [name]: event.target.value }); }; } return this.handlers[name]; } render() { return ( <input onChange={this.handleChange('name')}/> <input onChange={this.handleChange('description')}/> ) }} Conclusion When doing event bindings in React, we must check very carefully whether the handlers are generated dynamically. Usually this is not a problem when the affected components appear only once or twice. But when event handlers appear in a list, this can results in severe performance issues. Solutions - Use Arrow Function binding whenever possible - If you must generate bindings dynamically, consider caching the handlers if the bindings become a performance issue Thanks for reading! I hope this post was helpful. If you find this post useful, please share it with more people by recommending it. Update: Omri Luzon and Shesh mentioned lodash-decorators and react-autobind packages for more convenient bindings. Personally I am not a big fan of automatically doing anything (I am always trying to keep things such bindings minimal) but auto bind is absolutely a great way of writing clean code and saving more efforts. The code would be like: import autoBind from 'react-autobind';class HelloWorld() { constructor() { autoBind(this); } handleClick() { ... } render() { return (<button onClick={this.handleClick}/>); }} Since autoBind will handle the bindings automatically, it is not necessary to use arrow function trick ( handleClick = () => {} ) to do the binding, and in t he render() functio n, this.handleClick can be used directly.
https://www.freecodecamp.org/news/the-best-way-to-bind-event-handlers-in-react-282db2cf1530/
CC-MAIN-2020-24
refinedweb
1,066
58.69
Here we apply binary search on a 2D array in which every row is increasingly sorted from left to right, and the last number in each row is not greater than the first number of the next row. However, the the primitive solution for this problem is to scan all elements stored in the input matrix to search for the given key. This linear search approach costs O(MN) time if the size of the matrix is MxN. But, as we can see each row in the matrix is sorted and the first element of a row is greater than or equal to the last number of the preceding row; therefore, the matrix can be viewed as a sorted one dimensional array. If all rows in the input matrix are concatenated in top down order, it forms a sorted one dimensional array. And, in that case binary search algorithm is suitable for this 2D array. #include <stdio.h> #define ROWS 3 #define COLS 4 int binSearchOnMatrix(int matrix[][COLS], int value); int main() { int twodarr[ROWS][COLS]; //two dimensional array int key; //search key int i, j; //counter variable int searchStatus; //1 if key is found, 0 otherwise. //read array printf("Enter %d x %d matrix in ascending order: ", ROWS, COLS); for (i = 0; i < ROWS; i++) for (j = 0; j < COLS; j++) scanf("%d", &twodarr[i][j]); printf("\nEnter search key: "); scanf("%d", &key); searchStatus = binSearchOnMatrix(twodarr, key); printf("Key (%d) is found: %d\n", key, searchStatus); } int binSearchOnMatrix(int matrix[][COLS], int key) { int start = 0; int mid, row, col, value; int end = ROWS * COLS - 1; while (start <= end) { mid = start + (end - start) / 2; row = mid / COLS; col = mid % COLS; value = matrix[row][col]; if (value == key) return 1; if (value > key) end = mid - 1; else start = mid + 1; } return 0; } OUTPUT ====== Enter 3 x 4 matrix in ascending order: 1 2 3 4 5 6 7 8 9 10 11 12 Enter search key: 5 Key (5) is found: 1 The above piece of code develops a function binSearchOnMatrix that takes a two dimensional array and search key as input and returns either 1 or 0 depending upon the success or failure of search key found. The function binSearchOnMatrix applies binary search on two dimensional matrix. It calculates row and col by dividing mid by COLS and mid modulo COLS respectively. Hope you have enjoyed reading C program for binary search on two dimensional arrays.
http://cs-fundamentals.com/tech-interview/dsa/binary-search-on-two-dimensional-array.php
CC-MAIN-2017-17
refinedweb
408
52.46
MediaObject Class Reference(Phonon::MediaObject) The MediaObject class provides an interface for media playback. More... #include <Phonon/MediaObject> Inherits: QObject and MediaNode. This class was introduced in Qt 4.4. Properties - prefinishMark : qint32 - tickInterval : qint32 - transitionTime : qint32 Public Functions - 29 public functions inherited from QObject - 3 public functions inherited from Phonon::MediaNode Public Slots Signals Additional Inherited Members Detailed Description The MediaObject class provides an interface for media playback. The media object manages a MediaSource, which supplies the media object with multimedia content, e.g., from a file. A playback in Phonon is always started by calling the play() function. The state of play (play, pause, stop, seek) is controlled by the media object, and you can also query the current state(). It keeps track of the playback position in the media stream, and emits the tick() signal when the current position in the stream changes. Notice that most functions of this class are asynchronous, so you cannot rely on that a state is entered after a function call before you receive the stateChanged() signal. The description of the State enum gives a description of the different states. Before play() is called, the media object should be connected to output nodes, which outputs the media to the underlying hardware. The output nodes required are dependent on the contents of the multimedia file that is played back. Phonon has currently two output nodes: the AudioOutput for audio content and VideoWidget for video content. If a MediaSource contains both audio and video, both nodes need to be connected to the media object.); mediaObject->play(); The media object can queue sources for playback. When it has finished to play one source, it will start playing the next in the queue; the new source is then removed from the queue. The queue can be altered at any time. media->setCurrentSource(":/sounds/startsound.ogg"); media->enqueue("/home/username/music/song.mp3"); media->enqueue(":/sounds/endsound.ogg"); You can also make use of the aboutToFinish() signal, which is guaranteed to be emitted in time for altering the queue. media->setCurrentSource(":/sounds/startsound.ogg"); connect(media, SIGNAL(aboutToFinish()), SLOT(enqueueNextSource())); } void enqueueNextSource() { media->enqueue("/home/username/music/song.mp3"); } When playback is finishing, i.e., when a media source has been played to the end and the queue is empty, several signals are emitted. First, the media object will emit aboutToFinish() - shortly before the playback has finished - and then finished(). The stateChanged() signal will also be emitted with PausedState, which is the state the media object takes when the playback is finished. If you wish to enter another state, you can connect a slot to finished() and set a new state there. The media object resolves the meta information, such as title, artist, and album. The meta data is not resolved immediately after a new source is provided, but will be resolved before the object leaves the LoadingState. The data is queried by string keys - which should follow the Ogg Vorbis specification - or by using the MetaData enum. The data available will depend on the type and content of the individual media files. metaDataChanged() will be emitted when the media object has resolved new meta data. Errors encountered during playback and loading of media sources are reported by emitting a state changed signal with ErrorState. The severity of the error can be queried by the ErrorType. With a NormalError, it might be possible to continue the playback, for instance, if only audio playback fails for a media source which also has video. A FatalError indicates that Phonon cannot continue playback of the current source, but it is possible to try with a different one. A user readable error message is given by errorString(). See also Symbian Platform Security Requirements, Phonon::MediaSource, Phonon::AudioOutput, VideoWidget, Music Player Example, Phonon Overview, Phonon::VideoPlayer, Phonon::createPlayer(), and Phonon Module. Property Documentation prefinishMark : qint32 This property holds the time when the prefinishMarkReached signal is emitted before playback ends. This property specifies the time in milliseconds the prefinishMarkReached() signal is emitted before the playback finishes. A value of 0 disables the signal. The signal is only emitted for the last source in the media queue. behavior because the backend might have more information available than your application does through totalTime() and currentTime(). Access functions: See also prefinishMarkReached(). tickInterval : qint32 This property holds the time interval in milliseconds between two ticks. The tick() signal is emitted continuously during playback. The tick interval is the time that elapses between the emission of two tick signals. If you set the interval to 0 the tick signal gets disabled. The tick() signal can, for instance, be used to update widgets that show the current position in the playback of a media source. Defaults to 0 (disabled). Warning: The back-end is free to choose a different tick interval close to what you asked for. This means that the following code may fail: int x = 200; media->setTickInterval(x); Q_ASSERT(x == producer->tickInterval()); On the other hand the following is guaranteed: int x = 200; media->setTickInterval(x); Q_ASSERT(x >= producer->tickInterval() && x <= 2producer->tickInterval()); Access functions: transitionTime : qint32 This property defines the time between playback of two media sources in the media queue. A positive transition time defines a gap of silence between queued media sources. A transition time of 0 ms requests gapless playback (i.e., the next source in the media queue starts immediately after the playback of the current source finishes). A negative transition time defines a crossfade between the queued media sources. Defaults to 0 (gapless playback). Warning: This feature might not work reliably with every backend. Access functions: Member Function Documentation MediaObject::~MediaObject () Destroys the MediaObject. void MediaObject::aboutToFinish () [signal] Emitted before the playback of the whole queue ends. When this signal is emitted you still have time to enqueue() a new MediaSource, so that playback continues. If you need a signal to be emitted at a specific time before playback is finished, you should use the prefinishMarkReached() signal instead. See also enqueue(), prefinishMark, and prefinishMarkReached(). void MediaObject::bufferStatus ( int percentFilled ) [signal] Provides information about the status of the buffer. When a MediaObject is in the BufferingState, it will send this signal regularly. percentFilled is a number between 0 and 100 telling you how much the buffer is filled. You can use this signal to show a progress bar to the user when in BufferingState: progressBar->setRange(0, 100); // this is the default connect(media, SIGNAL(bufferStatus(int)), progressBar, SLOT(setValue(int))); Note that the BufferingState is commonly used when waiting for data over a network connection, but this might not be true for all backends. void MediaObject::clear () [slot] Stops and removes all playing and enqueued media sources. See also setCurrentSource(). void MediaObject::clearQueue () Clears the queue of media sources. See also queue() and enqueue(). MediaSource MediaObject::currentSource () const Returns the current media source, i.e., the media source that is being played back. The current source is either set with setCurrentSource() or taken from the media queue() when a media source has finished playing. See also setCurrentSource(). void MediaObject::currentSourceChanged ( const Phonon::MediaSource & newSource ) [signal] Emitted when the MediaObject fetches a new MediaSource from the queue() and before it enters the LoadingState for the new source. The media object will take a new source from the queue() when it has finished the playback of the current source. newSource is the source that starts to play at the time the signal is emitted. qint64 MediaObject::currentTime () const Returns the current time (in milliseconds), i.e., position in the media stream, of the file currently being played. See also tick(), totalTime(), and remainingTime(). void MediaObject::enqueue ( const MediaSource & source ) Appends source to the queue. You can use this function to provide the next source after the aboutToFinish() signal has been emitted. See also aboutToFinish(), setQueue(), and clearQueue(). void MediaObject::enqueue ( const QList<MediaSource> & sources ) Appends multiple sources to the queue. See also setQueue() and clearQueue(). void MediaObject::enqueue ( const QList<QUrl> & urls ) Appends the URLs in urls to the media source queue. The function will create MediaSources from the QUrls, and append these to the queue. See also setQueue() and clearQueue(). QString MediaObject::errorString () const Returns a human-readable description of the last error that occurred. The strings given may vary between backends. The error description can be used to give a message to the user - and the developer - when the stateChanged() signal is emitted with ErrorState. Qt Backends On Windows, Qt fetches its error messages from the DirectShow backend. This usually includes an error number, which can be looked up in the DirectShow documentation:. On Linux and Mac, the error strings are not fetched directly from the backend, but are created in the backend. See also Phonon::ErrorState and stateChanged(). ErrorType MediaObject::errorType () const Tells your program what to do about the last error that occurred. Use this function after receiving a stateChanged() signal with ErrorState. See also Phonon::ErrorType, Phonon::ErrorState, and stateChanged(). void MediaObject::finished () [signal] Emitted when the object has finished playback. It is not emitted if you call stop(), pause() or load(). It is emitted only when the current media source has finished playing and the media queue() is empty, or when a fatal error occurs. Warning: This signal is not emitted when the current source has finished and there's another source in the queue. It is only emitted when the queue is empty. See also currentSourceChanged(), aboutToFinish(), and prefinishMarkReached(). bool MediaObject::hasVideo () const Check whether the current media source includes a video stream. Warning: This information is not resolved immediately after a media object gets a new source. Listen to the hasVideoChanged() signal instead. connect(media, SIGNAL(hasVideoChanged(bool)), hasVideoChanged(bool)); media->setCurrentSource("somevideo.avi"); media->hasVideo(); // returns false; } void hasVideoChanged(bool b) { // b == true media->hasVideo(); // returns true; } Returns true if the media contains video data; otherwise, returns false. See also hasVideoChanged(). void MediaObject::hasVideoChanged ( bool hasVideo ) [signal] Emitted whenever the return value of hasVideo() changes, i.e., the media source being played back contains video. Normally you'll check hasVideo() first and then let this signal tell you whether video is available now or not. That way you don't have to poll hasVideo(). hasVideo is true when the stream contains video and adding a VideoWidget will show a video, and false if there is no video data in the stream and adding a VideoWidget will show an empty (black) VideoWidget. bool MediaObject::isSeekable () const Check whether it is possible to seek, i.e., change the playback position in the media stream. Warning: This information is not solved immediately after the media object gets a new media source. The hasVideoChanged() signal is emitted after this information is available. connect(media, SIGNAL(hasVideoChanged(bool)), hasVideoChanged(bool)); media->setCurrentSource("somevideo.avi"); media->hasVideo(); // returns false; } void hasVideoChanged(bool b) { // b == true media->hasVideo(); // returns true; } Returns true if the current media may be seeked; otherwise, returns false. See also seekableChanged(). QStringList MediaObject::metaData ( const QString & key ) const Returns the strings associated with the given key. Backends should use the keys specified in the Ogg Vorbis documentation: Therefore the following should work with every backend: Note that meta data is not resolved before the metaDataChanged() signal is emitted.")); QStringList MediaObject::metaData ( Phonon::MetaData key ) const Returns the strings associated with the given key. Same as above except that the keys are defined in the Phonon::MetaData enum. See also metaDataChanged(). QMultiMap<QString, QString> MediaObject::metaData () const Returns all meta data in a multi map. See also metaDataChanged(). void MediaObject::metaDataChanged () [signal] This signal is emitted when the media object has resolved new meta data. This will happen before the media object leaves the LoadingState after a new source has been set. This signal is not emitted when the media object removes the current data, i.e., when a new source is set or an error has occurred. If you need to know this, you can listen for the ErrorState, and connect to the currentSourceChanged() signal. You can get the new meta data with the metaData methods. See also metaData(), currentSourceChanged(), stateChanged(), and Phonon::State. void MediaObject::pause () [slot] Requests playback to pause, and the media object to enter the PausedState. If it was paused already, nothing changes. This function is asynchronous and the media might not be paused immediately. See also play(), stop(), and stateChanged(). void MediaObject::play () [slot] Requests playback of the media data to start. Playback starts when the stateChanged() signal is emitted with PlayingState. If the media object is already in a PlayingState, nothing happens. See also stop(), pause(), and stateChanged(). void MediaObject::prefinishMarkReached ( qint32 msecToEnd ) [signal] Emitted when there are only msecToEnd milliseconds left of playback. Warning: This signal is not emitted when there is another source in the queue. It is only emitted when the queue is empty. See also setPrefinishMark(), prefinishMark(), aboutToFinish(), and finished(). QList<MediaSource> MediaObject::queue () const Returns the queued media sources. This does list does not include the current source, returned by currentSource(). See also setQueue() and enqueue(). qint64 MediaObject::remainingTime () const Get the remaining time (in milliseconds) of the file currently being played. Returns the remaining time in milliseconds. See also totalTime(), currentTime(), and totalTimeChanged(). void MediaObject::seek ( qint64 time ) [slot] Requests a seek to the time indicated, specified in milliseconds. You can only seek if state() is. If the current source of the media object is not seekable, calls to this functions do nothing. See also SeekSlider and tick(). void MediaObject::seekableChanged ( bool isSeekable ) [signal] This signal is emitted when the media object's ability to seek in the media stream changes. isSeekable is true if it is possible to seek(); otherwise, it is false. Change in the ability to seek in the stream usually happens when the current source changes or when an error occurs. Normally you'll check isSeekable() after setting a new media source, and then let this signal tell you when seeking is possible. That way you don't have to poll isSeekable(). void MediaObject::setCurrentSource ( const MediaSource & source ) Set the media source the MediaObject should use. After the media object receives a new source, it will enter the LoadingState. When it is ready to play, it enters the StoppedState unless another state has been requested, e.g., by calling play(). source is the MediaSource object to the media data. You can just as well use a QUrl or QString (for a local file) here. We show an example: QUrl url(""); media->setCurrentSource(url); See also currentSource() and MediaSource. void MediaObject::setQueue ( const QList<MediaSource> & sources ) Set the sources to play when the current source has finished. This function will overwrite the current queue. See also clearQueue() and enqueue(). void MediaObject::setQueue ( const QList<QUrl> & urls ) Set the urls to play when the current media has finished. This function overwrites the current queue. See also clearQueue() and enqueue(). State MediaObject::state () const Returns the current Phonon::State of the object. See also Phonon::State and stateChanged(). void MediaObject::stateChanged ( Phonon::State newstate, Phonon::State oldstate ) [signal] This signal is emitted when the state of the MediaObject has changed. The oldstate and newstate parameters indicate the previous state and current state of the media object. If you are only interested in the new state of the media object, you can connect this signal to a slot that accepts only one State argument. void MediaObject::stop () [slot] Requests playback to stop, and the media object to enter the StoppedState. If it was stopped before nothing changes. This function is asynchronous and the media might not be stopped immediately. See also play(), pause(), and stateChanged(). void MediaObject::tick ( qint64 time ) [signal] This signal is emitted in intervals defined by the tickInterval property. The current position of the media object in the stream is given by the time parameter. The time is specified in milliseconds. See also tickInterval. qint64 MediaObject::totalTime () const Get the total time (in milliseconds) of the file currently being played. Returns the total time in milliseconds. Warning: The total time is not defined before the media object enters the LoadingState. See also totalTimeChanged(). void MediaObject::totalTimeChanged ( qint64 newTotalTime ) [signal]. newTotalTime is the length of the media file in milliseconds. No notes
http://qt-project.org/doc/qt-4.8/phonon-mediaobject.html
CC-MAIN-2014-42
refinedweb
2,700
58.08
Buy this book at Amazon.com chapter we will see programs that write them. An alternative is to store the state of the program in a database. In this chapter I will present a simple database and a module, pickle, that makes it easy to store program data.: 'w' >>>() The argument of write has to be a string, so if we want to put other values in a file, we have to convert them to strings. The easiest way to do that is with str: >>> x = 52 >>> fout.write(str(x)) An alternative is to use the format operator, %. When applied to integers, % is the modulus operator. But when the first operand is a string, % is the format operator. The first operand is the format string, which contains one or more format sequences, which specify how the second operand is formatted. The result is a string. For example, the format sequence '%d' means that the second operand should be formatted as an integer (d stands for “decimal”): '%d' >>> camels = 42 >>> '%d' % camels '42' The result is the string '42', which is not to be confused with the integer value 42. . Each format sequence is matched with an element of the tuple, in order. The following example uses '%d' to format an integer, '%g' to format a floating-point number (don’t ask why), and '%s' to format a string: '%g' '%s' >>> it can be difficult to use. You can read more about it at.name): for name in os.listdir(dirname): path = os.path.join(dirname, name) if os.path.isfile(path): print path else: walk(path) os.path.join takes a directory and a file name and joins them into a complete path. The os module provides a function called walk that is similar to this one but more versatile. Read the documentation and use it to print the names of the files in a given directory and its subdirectories. Solution:.. Write a function called sed that takes as arguments a pattern string, a replacement string, and two filenames; it should read the first file and write the contents into the second file (creating it if necessary). If the pattern string appears anywhere in the file, it should be replaced with the replacement string. If an error occurs while opening, reading, writing or closing files, your program should catch the exception, print an error message, and exit. Solution:.. 'c' >>>1 == t2 True >>> t1 download my solution to Exercise 4 from, you’ll see that it creates a dictionary that maps from a sorted string of letters to the list of words that can be spelled with those letters. For example, ’opst’ maps to the list [’opts’, ’post’, ’pots’, ’spot’, ’stop’, ’tops’]. Write a module that imports anagram_sets and provides two new functions: store_anagrams should store the anagram dictionary in a “shelf;” read_anagrams should look up a word and return a list of its anagrams. Solution: anagram_sets store_anagrams read_anagrams program. For example, the Unix command ls -l normally displays the contents of the current directory (in long format). You can launch ls with os.popen1: >>>>> fp = os.popen(cmd) The argument is a string that contains a shell command. The return value is an object). For example, most Unix systems provide a command called md5sum that reads the contents of a file and computes a “checksum.” You can read about MD5 at. This command provides an efficient way to check whether two files have the same contents. The probability that different contents yield the same checksum is very small (that is, unlikely to happen before the universe collapses). You can use a pipe to run md5sum from Python and get the result: >>>>> cmd = 'md5sum ' + filename >>> fp = os.popen(cmd) >>> res = fp.read() >>> stat = fp.close() >>> print res 1e0033f0ed0656636de0d75144ba32e0 book.tex >>> print stat None In a large collection of MP3 files, there may be more than one copy of the same song, stored in different directories or with different file names. The goal of this exercise is to search for duplicates. Solution:.. __name__ __main__. \n \r For most systems, there are applications to convert from one format to another. You can find them (and read more about this issue) at. Or, of course, you could write one yourself. The urllib module provides methods for manipulating URLs and downloading information from the web. The following example downloads and prints a secret message from thinkpython.com: import urllib conn = urllib.urlopen('') for line in conn: print line.strip() Run this code and follow the instructions you see there. Solution:. Think Bayes Think Python Think Stats Think Complexity
http://greenteapress.com/thinkpython/html/thinkpython015.html
CC-MAIN-2017-43
refinedweb
764
74.39
). Add XML::Compile::Schema::Instance objects to the internal knowledge of this object. Returns a list of all known schema instances. Returns true when EXTTYPE extends BASETYPE. Lookup the definition for the specified KIND of definition: the name of a global element, global attribute, attributeGroup or model group. The ADDRESS is constructed as {uri}name or as separate URI and NAME. -Option --Default include_used <true> Lookup the definition for the specified id, which is constructed as uri#id or as separate URI and ID. Lookup the substitutionGroup alternatives for a specific element, which is an TYPE (element full name) of form {uri}name or as separate URI and NAME. Returned is an ARRAY of HASHes, each describing one type (as returned by find()) This method can be quite expensive, with large and nested schemas. Returns the list of name-space URIs defined. Returns a list of XML::Compile::Schema::Instance objects which have the URI as target namespace. Show all definitions from all namespaces, for debugging purposes, by default the selected. Additional OPTIONS are passed to XML::Compile::Schema::Instance::printIndex(). -Option --Default include_used <true> namespace <ALL> Show also the index from all the schema objects which are defined to be usable as well; which were included via use().); We need the name-space; when it is lacking then import must help, but that must be called explicitly..34, built on May
http://search.cpan.org/~markov/XML-Compile-1.34/lib/XML/Compile/Schema/NameSpaces.pod
CC-MAIN-2017-30
refinedweb
232
56.86
John Lorenzen - Total activity 11 - Last activity - Member since - Following 0 users - Followed by 0 users - Votes 0 - Subscriptions 4 John Lorenzen created a post, Cannot resolve symbol asyncI'm working with Microsofts new Async CTP which adds two new keywords async and await. Even thought the application compiles and runs resharper is marking these two keywords as "Cannot resolve sym... John Lorenzen created a post, New to resharperI have an employee who is just starting to use resharper and has been getting the following warning "Split declaration and assignment." Her question is why is she getting this warning is there a do... John Lorenzen created a post, Unable to install ReSharper 3.02After installing Resharper 3.02 when I try and start VS2005 I get the attached message. I've uninstalled several times but keep getting this error.Attachment(s):resharpererror.JPG John Lorenzen commented, John Lorenzen created a post, Newbie NUnit HelpI have NUnit 2.4.1 installed and have a class with 2 test functions but the test runner lists only one test and does not show the function names of the tests. Here is the code.namespace KioskTests...
https://resharper-support.jetbrains.com/hc/en-us/profiles/2102775289-John-Lorenzen
CC-MAIN-2020-24
refinedweb
192
63.19
Chapter 1. What is a Zero-Sum Game. What do these two expressions mean? How would you describe international trade-Sum Game situation in which one participant's gains result only from another participant's equivalent losses. The net change in total wealth among participants is zero; the wealth is just shifted from one to another.Read more: Win-WinSituation guaranteeing a favourable outcome for everyone involved What percent of U.S. manufacturers sell overseas? ONLY 10% What is a surplus? export more than import What is a deficit? import more than export See p. 5 textbook See p. 6-7 textbook Find your country! Look at the charts. What surprises you? --------------------------------------- Glossary—p. 351-385 Look up harmonized code. Harmonized Code Integration
http://www.slideserve.com/chyna/chapter-1
CC-MAIN-2017-30
refinedweb
123
63.86
Deutsche Kurzbeschreibung - Paulina McDaniel - 1 years ago - Views: Transcription 1 Abstract Within recent years, mobile phones have become carriers of numerous smart applications and the potential of these mobile devices is even greater than it might look at first glance. Behind the combined pieces of information that many mobile devices possess lies hidden meta information that accounts for more than the mere sum of its parts, e.g. beginning and end of a traffic jam. Using our framework, researchers and scientists can create versatile requests for information and send them to mobile clients within a couple of minutes. For instance, environmental data could be sensed periodically without any user intervention. Prototype models of several information requests have been created to demonstrate the various aspects of possible public sensing scenarios, bearing in mind the users concerns regarding data security and privacy. Our framework does not only manage creating and sending of specifically designed tasks, it also dispatches their executions on the client side, sends back the response, and interprets it. Therefore developers can fully concentrate on the content of sensing information. 2 2 Deutsche Kurzbeschreibung In den letzten Jahren wurden mobile Telefone Träger verschiedenster intelligenter Anwendungen und das Potential dieser mobilen Geräte ist sogar größer als es auf den ersten Blick scheinen mag. Hinter den kombinierten Teilinformationen, die viele mobilen Geräte besitzen, liegen versteckte Metainformation, die größer sind als die bloße Summe ihrer Teile, z.b. Beginn und Ende eines Staus. Forscher und Wissenschaftler können mit unserer Rahmenarchitektur verschiedenartige Informationsanfragen erstellen und diese mobilen Clients innerhalb einiger Minuten schicken. Umweltdaten könnten z.b. ohne Benutzereingriff regelmäßig gesendet werden. Prototypmodelle verschiedener Informationsanfragen wurden erstellt um die unterschiedlichen Aspekte möglicher gemeinnütziger Messungsszenarien zu demonstrieren. Dabei hatten wir die Bedenken der Benutzer im Bezug auf Datensicherheit und Privatsphäre im Blick. Unsere Rahmenarchitektur koordiniert nicht nur das Erstellen und Versenden speziell designter Anfragen sondern verwaltet auch deren Ausführung auf dem Client, sendet die Antwort zurück und interpretiert sie. Deswegen können sich Entwickler völlig auf den Inhalt der aufgezeichneten Information konzentrieren. 3 3 Contents Abstract 2 Deutsche Kurzbeschreibung 3 Contents 4 1 Introduction Motivation Overview Related Work Contribution of this Thesis Thesis Outline General Remarks about Writing Style and Layout Examples of Applications Meeting in Town Sensing Environmental Data Baby Phone Playing Games Live Traffic Information Picking Someone up Just on Time Using a Mobile Device to Unlock Objects Do these Roads Cross? Fundamentals Converting Geographical Coordinates into Cartesian Ones Storing the Tasks Hardcode in the Source Code of the Server Class Read the Tasks from an XML File Write a Parser Outsource the Creation of Tasks to *.java File Privacy and Security Security Concerns Why? 4 Contents Data Collectors Specific Public Sensing Concerns Data Security Aware Public Sensing Implementation of Encryption Architecture General Precedent Thoughts Abstract Fundamental Architecture Tasks Server Client Implementation Why Android? Package Structure Shared Classes between Server and Client Message and Its Subclasses GUI Classes Input/Output Server s Classes The Core Class: Server CreateTasks TransferTasks Client s Classes The Core Class: Client Creating the Tasks The Life of a Task: An Exemplary Overview Creation Sending Reception Delay Due to Location or Time Execution Awaiting User Interaction Sending Back the Task Displaying the Sensed Data Using the Menu Practical Remarks USB Debugging Means of Information Exchange Usage Starting the Server Bundling the Required Packages in a *.jar File Adding Android and Google Maps to the Class Path Start the Programs of the Server Package 5 Contents Arguments Passed via Command Line Tests Connection Loss Field Test Introduction Setting up the Tasks Performing the Test Evaluation Usability Tests on People without Previous Android Knowledge Peek into the Future The Big Picture Extension Possibilities of Our Framework How to Shape the Future Bibliography 60 Nomenclature 62 6 Chapter 1 Introduction 1.1 Motivation Can you make phone calls with it as well? This sarcastic comment that an owner of a smart phone might hear while showing off the fancy features of his new device reveals a lot about the speedy evolution of so-called smart phones within recent years. Apps for all sorts of things can be downloaded so that the original functionality namely making phone calls and sending messages is reduced to merely one of many things that can be done. Since an ordinary home computer is still able to calculate faster, has access to more storage, is connected with more convenient input devices, a bigger screen and better sound system the question arises why smart phones are something that companies earn a fortune selling whereas PCs, which are superior to these phones in virtually all aspects, do not have sell growth rates nearly that high. Two key advantages of mobile devices are crucial to their success: ˆ First of all their mobility. Being able to have access to somewhat limited functionality right on demand wherever you are by just taking your phone out of your pocket is in a practical sense superior to having to wait till you are at home regardless of the advantages the home computer has. ˆ The second advantage is that these devices have inbuilt sensors, the most important one is position detection with GPS. The device knows where it is and therefore the work of acquiring that knowledge is shifted from the user to the device. For instance, I do not have to tell the software where the train station I want to travel from is, my phone knows where I am at. Of particular interest to not only the end user but also to scientific research groups and companies is the collected and combined information of numerous cell phones. They form a net of local sensors spread out all over the place which can be used to inexpensively gain e.g. current weather data which can be fed into forecast systems. Another application would be smooth traffic control which can be achieved by combining the collected information of many devices. According to the principles of distributed agent systems, behind a collection of many single bits of data there 7 7 Chapter 1. Introduction 8 lies hidden meta information that can be extracted with suitable algorithms whose results account for more than the mere sum of the single information bits. There exists a wide range of thinkable applications such as sensing all kinds of environmental data or querying the user to retrieve information that he has access to right now. One especially promising application is live traffic surveillance and control since knowing the more or less precise location of a traffic jam is more than any single car driver can know; a combined effort of several mobile devices in cars can achieve it, though. The ideas we will show are similar to a traffic jam reporting system which gives the user the chance to report a traffic jam [1]. We go beyond their ideas and envision a system without user interaction as will be demonstrated later on. This is just one of many possible applications for distributing sensing tasks to several mobile device users where the public reaps the benefit of it which is called public sensing. Looking at traffic sensing we see that public sensing has the potential to benefit society with negligible efforts for the individual which is characteristic for public sensing. Even though the efforts of the phone users are small compared to the advantages, one should nevertheless continue to strive toward highly efficient energy consumption and automatization without the required interference of users since computers ought to do their utmost to bridge the gap between machines and humans. Programmers of public sensing apps should stick to the principle that public sensing may not interfere with normal operation of a mobile phone, i.e., the energy consumption [... ] needs to be restricted. [2]. 1.2 Overview Related Work In the following, some key papers of several fields of mobile sensing will be shown. How they relate with our project will become obvious without further explanation during the course of this thesis. MobGeoSen [3] focuses on monitoring environmental data and provides the users with cartographic displays and gives them the opportunity to annotate with text and photos. NoiseTube [4] allows users to share measured noise data with others. Is a cell phone microphone only capable of detecting noise volume? The developers of SoundSense [5] convince us that even a standard cell phone microphone is capable of doing far more. This project uses the microphone input to distinguish between several kinds of sound. Once it can detect the sound of a car from within, it could automatically start sending its location to traffic surveillance systems on a regular basis, just to mention one example. Not only sound can be measured, however. With appropriate sensors, e.g. carbon monoxide pollution can be sensed and drawn on a map [6]. How a mobile object could be tracked and traced automatically while minimizing energy consumption of mobile nodes has been theoretically looked into already as 8 Chapter 1. Introduction 9 well [7]. The well-known OpenStreetMap [8] is one example of an already fairly developed and established result of numerous sensings. The MetroSense [9] architecture developers envision the future of public sensing and ask themselves how to propel sensor networks from their small-scale applicationspecific network origins, into the commercial mainstream of people s every day lives Contribution of this Thesis This thesis is part of the second version of the Spontaneous Virtual Networks project (SpoVNet 2.0) which creates overlay networks on top of the traditional IP-based network infrastructure to enable flexible and adaptive network communication. The goal of this thesis is to build an Android-based system that manages and disseminates context collection tasks to mobile phones which execute these tasks based on spatiotemporal constraints and coverage requirements. The results of the task execution are sent to an infrastructure-based central server. Using our framework drastically simplifies the process of public sensing and therefore enable researchers to work very efficiently since they can totally focus on the information of public sensing and do not have to bother about the means of transmission. Figuratively spoken, our system provides developers and users with forms and all they have to do is enter the parameters and return it to the postman who will transport the messages, schedule their execution, and return and interpret the answer Thesis Outline After having presented the motivation for using mobile devices for public sensing tasks, this thesis will show some diverse example applications in Chapter 2 on page 11. After having introduced some fundamental concepts in Chapter 3 on page 17, we will go beyond the theoretical technical possibilities of what can be done and will discuss the practical concerns of what should be done and what needs to be regarded with special sensitivity to users security and privacy issues, see Chapter 4 on page 21. Then we will design an architecture in Chapter 5 on page 26 bearing in mind the applications envisioned earlier. Next we will shown our implementation of the system in Chapter 6 on page 30 and go into detail explaining the applications that we wrote already. In Chapter 7 on page 48 we will demonstrate an exemplary use case. To wrap up our project, we will carry out some tests in Chapter 8 on page 50 and show a real life scenario. Finally, in Chapter 9 on page 56, we will first try to imagine the role of public sensing in the future and later on discuss ideas how we can shape it. For an explanation of abbreviations see the nomenclature on page 62. 9 Chapter 1. Introduction General Remarks about Writing Style and Layout For simplicity s sake the user of a mobile device and the developer of applications will sometimes be referred to as he which is to be read gender neutral not meaning to exclude females, of course. Java code, especially class names, will be written in typewriter style. Source code blocks, however, were deliberately not set with a monospace font for the sake of better legibility. References to literature are consecutively numbered and the number is displayed in squared brackets. 10 Chapter 2 Examples of Applications Even though we focus on public sensing we now want to demonstrate sensing applications not only from this field. Figure 2.1 shows the difference between personal, social, and public sensing. The adjectives denote who the collected data is for: an individual, a social group, or the general public. 2.1 Meeting in Town The most basic useful application thinkable would be the server s request to a client to reveal its current location. If a server knows the locations of several mobile devices, it can calculate a place in town that is about the same distance away from both where they can meet. Or the server can simply show both users locations on a map to leave it up to them where to meet. If the city is unknown to at least one of them so that they have no common knowledge to use to explain to the other one where they are, a calculated meeting point to which the navigation system can guide is especially helpful. 2.2 Sensing Environmental Data One of the most promising applications for public sensing is collecting real time information about noise volume, temperature, humidity, air pollution, atmospheric pressure, and the like. For weather forecasts the principle The more, the better is valid. The more detailed information one can supply a simulation program with, the more accurate results will come out of it. Therefore using mobile devices as numerous little sensors spread all over the place could first improve weather prediction and second reduce costs because the number of expensive weather measuring devices can be reduced. One has to bear in mind, though, that the collected data by mobile devices is less accurate: a phone could be in a pocket or the temperature sensor could be covered and the like which both influences the measured temperature significantly. The inpocket-case could be ruled out by making sure it takes the measurement only if the measuring time is framed by two user actions within a short period of time. The 11 11 Chapter 2. Examples of Applications 12 Figure 2.1: People-centric sensing applications can be thought of as having a personal, social, or public focus [10]. Figure 2.2: A noise map of Manchester [11]. The highly frequented roads stick out clearly. 12 Chapter 2. Examples of Applications 13 temperature sensor should furthermore be located in an area that is normally not covered when holding the device. The measuring can also be done with calibrated measuring devices and the collected data can be transmitted via RFID chips to a mobile device and from there to the server using standard telecommunication infrastructure [12]. The disadvantage of inaccurate measured data can so be omitted. Concerning the usage of noise level maps, Weinschrott et al. [12] write: City administrations need statistics to develop a city according to the behavior and the needs of its inhabitants. For example, a noise level map of a city supports decisions on traffic-reducing measures to increase the quality of living conditions. Figure 2.2 shows an example of a noise level map. 2.3 Baby Phone Once loudness can be sensed, it will be easy to define a threshold and notify the server or another phone if it is crossed. So the parents will know whether their baby is asleep or crying and will be notified in the latter case. Instead of sending a message that the threshold has been crossed, the system could also trigger livestreaming of audio or even video to the phone that is with the parents. To rule out other noise sources such as thunder or a train passing by one could only ring alarm if the high frequencies that are distinct of baby cries are loud enough. 2.4 Playing Games Somewhat similar to the board game Scotland Yard some people could play a game in real life. Everyone has a cell phone that communicates with the server. One person is chased by the others who play cops and every couple of minutes the absquatulator s 1 position on the map is revealed to the others. Whenever he has walked e.g. 100 meters this information is sent to the cops as well. The cops need to work together, ideally via cell phone calls, to find the person. Playing in a city taking the subway could be allowed as well, maybe for a limited number of stops. 2.5 Live Traffic Information We see this as one of the most promising and useful applications. In general, the more densely populated an area is, the more traffic jams occur and the more cell phones there are per square kilometer. Therefore it seems ideal to make these thousands of available cell phones in cars send their location and calculated speed to the server on a regular basis. All the server needs to do then is the following: 1. Find out if the cell phone is on a road. It should take several location snapshots for that to rule out people walking over a bridge and the like. 1 The one being chased. 13 Chapter 2. Examples of Applications Compare the reported speed with the speed limit or recommendation. The lower the ratio between reported speed and speed limit is, the stronger the advice to other drivers becomes to take another route. Give special attention to traffic lights, though, do not count speed reports in front of them. 3. Extrapolate the whole road given this speed information linked to several location points. Take into consideration that newer snapshots should play a more important role than older ones. 4. Feed the gathered traffic information into navigation systems. A light version of this traffic jam reporter [13] involves the user to tell the server that he has just reached the end of a traffic jam; end defined as his car being the last one in line. So this version has two disadvantages to the one we propose: First, it requires user involvement, and second, that it is only boolean either traffic jam or no traffic jam. 2.6 Picking Someone up Just on Time The problem is well-known to most of us: Often when someone picks up a number of people living in different places with the car, someone has to wait for the other one since in practice a precise pickup time can hardly be adhered to due to the unpredictable traffic situation or other unexpected delays. So either the car driver has to wait until the one to pick up is ready to go or this person is ready before and has to wait for the car to finally arrive. If both have a mobile device with appropriate software, though, the situation can look entirely different. The driver s location can be displayed on the other person s phone and he can either estimate for himself how long it will take the driver to arrive or the phone of the one being at home can send its location to the driver s phone whose navigation system will respond with an estimated time of arrival. As soon as this falls under a threshold, the person will be asked to get ready to be picked up. 2.7 Using a Mobile Device to Unlock Objects There are many objects that we lock and unlock every day: Our houses, cars, computers, bikes, and lockers. What if the cell phone could be turned into some sort of general key for numerous devices? As soon as I approach the door of my house, my cell phone will realizes that I have entered my property, sends a message to the server which passes it on to the house management computer that has 24/7 internet access and unlocks the door. Of course a number of questions arise: What if... ˆ... the battery of my cell phone is empty? ˆ... I cannot get GPS or other location information? ˆ... my phone gets stolen? 14 Chapter 2. Examples of Applications 15 ˆ... my house management computer looses internet connection or power or has another hardware or software failure? Even though the first two scenarios could be solved by supplying the password to the management system via another internet connection and loosing the phone is actually less of a tragedy with regards to unwanted intruders into the house than loosing the physical key since one can easily take away the access rights from the phone the need for a back door in the figurative or literal sense is obvious. This could be a fingerprint sensor or a number block where one has to enter a pass code or an ordinary physical key stored in the house of a friend or relative. One of the great advantages is that the phone has the potential to be the key for everything that has a computer with an internet connection attached to it. Door lock systems that already have permanent connection to a central server, using e.g. magnetic card readers, can easily be modified to grant access using the phone s location information. One issue arises, however, namely the unavailability of GPS information inside buildings. Several companies are constantly working towards eliminating this disadvantage by supplying location information based on cell tower locations and wireless LAN signal strength of geographically known senders. [14] [15]. Using GPS or other location providers might seem like an overkill if all we want to find out is whether a mobile device is within a certain range of something else; having a look at the big picture, however, convinces that using existing technology infrastructure is superior to establishing new systems and having to carry around only one device is more convenient than two. A drawback, however, is that GPS or another location finding system has to be switched on constantly which is fairly energy consuming. 2.8 Do these Roads Cross? Putting our feet back on the ground of reality, now we do not want to think visionary ideas any more but show an application that is actually already up and running, namely the question to the cell phone user whether the two roads he is very close to right now do actually cross or if one runs over the other. Especially for traffic routing this is essential information because if they do not cross, the navigation system better does not suggest users to drive from one to the other one. Google Maps relies heavily on satellite images and it is very hard to determine if two roads cross or do not cross looking down on them from a satellite. So whenever it is not known yet if two roads intersect, a question can be sent to the users in the area around. As soon as the cell phone is very close to the possible crossing, the task becomes flagged as executable. After the user has confirmed execution and after having clicked on Show Map he sees Figure 2.3. In Figure 2.4 he has just clicked to select the arrangement. In the course of this thesis we will have a detailed look at the different aspects which lie behind this application. 15 Chapter 2. Examples of Applications Figure 2.3: Now remember which street was A, hit back, and answer. 16 Figure 2.4: Hidden under the spinner is a text field to enter a comment, bridge, for instance. 16 Chapter 3 Fundamentals In the following we will discuss some concepts that we will rely on later on. 3.1 Converting Geographical Coordinates into Cartesian Ones If we want to show a map with overlaid text or graphics, e.g. distances, we have to be able to translate a length unit into geographical latitude and longitude. We will now look at calculating geographical points that are a given distance away from the origin. All points that fulfill this constraint are located on a circle. The position of a specific point on the circle is determined by an angle from the horizontal axis to the right defined as zero going in the mathematically positive direction. The distance between two degrees of latitude is always about 111 kilometers, but the distance between two degrees of longitude depends on the latitude of the position: On the equator it is also about 111 kilometers, on the poles it is 0. Using the formula below we can compute an approximate value of the distance between two degrees of longitude 1 : dist = cos(π currentlat ) 180 Then we divide the radius by this distance. The result is the distance in degrees. We would add 2 it to the value of the latitude to move this distance eastwards; since the point is normally not directly eastwards, however, we multiply it with the cosine of the angle and do respectively for the longitude distance using sine. 3.2 Storing the Tasks Several possible ways of telling the server which tasks to send to the client come to mind: 1 The cosine is set to radiant and the distance is in the SI standard unit meter. 2 Crossing the the prime meridian and the 180 th meridian have to be calculated with special care using modulus. 17 17 Chapter 3. Fundamentals Hardcode in the source code of the server class. 2. Read the tasks from an XML file. 3. Write a parser. 4. Outsource the creation of tasks to a *.java file. In the following we will give reasons why we opted for the last alternative. To comprehend this decision, one has to bear in mind that we are building a prototype and not a huge project funded by a company. Therefore rewriting classes such as Calendar was not an option since it might look easy at first glance, having a closer look at it, however, reveals many complex functionalities such as leap year algorithms, time zones and daylight saving times, just to mention a few Hardcode in the Source Code of the Server Class. Due to lacking flexibility this would be only a good idea while testing since the people who will send out tasks will not want to recompile the class whenever they have made some changes to the tasks they want to send. And changes will be rather frequent and be it only changing the time frame of execution a couple of minutes Read the Tasks from an XML File There are four methods of doing this that we have looked into: JDOM The big disadvantage here is that we would have to reprogram our tasks to make them ready for JDOM to put them into XML because it cannot just take objects and convert them to XML, every single variable needs to be converted to XML individually. On top of that, whenever a user creates a new task, he would have to do the same thing. This is why we looked into something that takes entire objects and puts them into XML files without our assistance. JAXB JAXB does have this functionality, it is not available for Android, however, since it depends on classes that Android does not provide. Even if it were available, though, we would still have to add an empty constructor to each class we have programmed and set up an initialization method to pass on the parameters. This would be a manageable effort but since we also use already existing classes such as Calendar and do not want to recode their use 3 to make it applicable for JAXB this is not the solution either. 3 We would need to use the standard constructor and pass the variables via set methods. 18 Chapter 3. Fundamentals 19 2 public class Example { 3 5 private String text; 6 8 private int index; 9 10 public Example() { 11 } public Example(String text, int index) { 14 this.text = text; 15 this.index = index; 16 } 17 } 18 } Listing 3.1: An annotated class for Simple Simple XML Serialization Simple XML Serialization [16] is available for Android and we can give it an object and tell it to serializ0 ite; there is drawback, however: We have to annotate the elements, that is add the words behind as demonstrated in Listing 3.1. This would be doable for our own classes yet not for the already existing classes we use and would be a burden on developers of future classes. Create XML Manually Even worse in terms of effort would be creating the XML file by hand. On top of that, one would have to implement workarounds for saving existing classes such as Calendar, for instance. Taking into consideration that so far we have been facing massive problems of inefficient effort when trying to create an XML file, we should try to find another method also since we have not even looked at creating Java objects from the XML yet which would make us face similar problems Write a Parser Whether the file format we want to store our objects in is XML or some other text based format, the problems mentioned above remain. 19 Chapter 3. Fundamentals Outsource the Creation of Tasks to *.java File This is how we solved the issue with the following advantages: ˆ No restrictions with regards to the use of existing classes. 4 ˆ No need to annotate the classes we created. ˆ No need to have an empty constructor and extra methods to set variables. ˆ A clear and straightforward way of modifying or creating a task. Something that can be written in one line in Java might take ten lines in XML. So despite of the disadvantage that the created files cannot be edited manually like XML, we decided to save them as serialized objects. If developers want to store them in a different kind of way they can do as they desire and set up a program that converts them to serialized objects and sends them to server. 4 One restriction is of course the requirement to be serializable, which is not a restriction after all because all messages have to be serializable anyway. If they were not they could not be sent as we will show in detail later on. 20 Chapter 4 Privacy and Security From a programmer s perspective it would be easiest if all phones would constantly broadcast their location to the server and to other phones and whoever wants to find out someone s location can simply search him in a huge database on the internet comparable with Google Maps. So why should this simple access be artificially restricted? 4.1 Security Concerns Why? Throughout history and all over the globe, common people have been subdued, observed, and controlled by authorities. Some leaders, kings, emperors, dictators, and even democratically elected politicians have at all times abused their power and misused their subjects for their own sakes. Some religious leaders and sect gurus have been and are still exploiting their followers and control their lives. One key aspect of successful control is information about the victim. Dictatorships like the former German Democratic Republic and the Nazi regime spanned a tight control net in order to find and isolate or eliminate enemies of the system. Gaining the same information about individuals has been simplified a lot with modern communication systems. Therefore the concerns about data security deserve to be taken very seriously, even in the democratic western world Data Collectors There are many companies that earn money by collecting, interpreting, and selling data. Even though this could be discussed in an abstract manner, we want to make this issue more tangible by exemplarily looking at the one outstanding company which also provides the OS for our applications: Google. Supplying mankind with great software for free on the one hand and on the other hand storing humongous amounts of information about every user mainly to show individually tailored advertisements on the internet. The more money they earn, the more and the better software they can provide to increase their coverage on the users. When someone is 21 21 Chapter 4. Privacy and Security 22 using Google Groups or GMail and is logged in, this finetunes this person s search preferences and interests profile. Obviously also Android is geared towards this aim with the inherent extra advantage of providing information about the user s location as discussed in the beginning. How far this forced subjection under Google s rules has gone already demonstrates the first commercial Android end device, HTC s G1 : Without creating a Google account it cannot even be used [13]. Here we see the strings attached to the free OS: The manufacturer does not pay with money, the user pays with his personal information, though Specific Public Sensing Concerns Who is actually bothered with data security? It is mainly the people who deal with it every day on a deeper level than the user level. We dare say that the majority of cell phone users do not think about who has knowledge about their location. These average phone users need to be told by the software providers which personal information is revealed to whom in the same way that users without native knowledge need to be made aware of e.g. how to create a safe password. Even though from a legal perspective the users have accepted the Terms of Service, most likely most of them still have no clue what they accepted. So exploiting users with below-average IT knowledge should not happen, even if it is legal. In the following paragraphs we will discuss how to reap the benefits of public sensing technology without broadcasting personal information to everyone according to the well-known principle As much as necessary, as little as possible Data Security Aware Public Sensing General Idealistic Guidelines One vital element of a privacy aware public sensing arrangement is a server whom the client trusts that his information is neither sold to a third party nor misused internally. For instance, location information that is sent for the purpose of traffic jam prevention is to be used for traffic jam prevention only, unless the user explicitly allows other usage. This also means that the user decides which personal information the server is allowed to disclose to other clients. Applied to the scenario where someone picks up someone else with the car, the default setting should be to only disclose the car driver s location within a small time frame around the estimated time of arrival. Google s Approach Latitude is Google s user location management system. You can reveal and disclose your location to friends on an individual basis. So are you on the safe side if you hand pick the friends who are allowed to know where you are? No, a glance at the Privacy Policy [17] shows you that big brother is still watching you. The privacy policy states that: 22 Chapter 4. Privacy and Security 23 If you use Google Latitude on a mobile device, in addition to other information, we collect battery life information and tie it to your Google Account. Why would I care about Google knowing about my battery life?, one may think, and continue reading. One should not read over in addition to other information, however, which loosens all restrictions with regards to what kind of information they collect. Thus everyone who uses Google Latitude allows Google to collect any information imaginable. It also does not come as a surprise that Google does not comply with the rules we postulated for data security aware public sensing which we made up before we read the legal documents. The default setting is not least disclosure of information and sometimes it is not even possible to restrict it: Certain of our products and services allow you to opt-out of certain information gathering and sharing or to opt-out of certain products, services, or features. Google s Terms of Usage [18] is far from only using the information for explicitly granted ends: By submitting, posting or displaying the content you give Google a perpetual, irrevocable, worldwide, royalty-free, and non-exclusive license to reproduce, adapt, modify, translate, publish, publicly perform, publicly display and distribute any Content which you submit, post or display on or through, the Services. In simple words, they can do with the collected data whatever they want, also selling to whoever they want: You agree that this license includes a right for Google to make such Content available to other companies, organizations or individuals with whom Google has relationships for the provision of syndicated services, and to use such Content in connection with the provision of those services. What if someone paid a lot of money to get the location of someone in order to kill him? Why should Google not disclose the information, assuming they are not told that the person will be killed? To put it in a nutshell, Google s Privacy Policy and Terms of Service state that, with regards to Google, the user has no privacy whatsoever. All kinds of information that exists can be collected by Google, they can do with it whatever they wish, shout it from the roof tops or sell it secretly to whosoever wants it. One has to keep in mind that the majority of smart phone users since that will become the vast majority of all people in developed countries are just users who do not read privacy policies because they do not have time, do not want to be bored, do not care, and want to start using their new phones. So legally it is clearly their fault. Time will show if awareness of privacy and data security will grow, if people will adapt to being comfortable with disclosing information about themselves, or if many will still reveal more private data than they actually want to. 23 Chapter 4. Privacy and Security 24 The Need for Encryption Personal information sent by a phone to a server, e.g. someone s location, can also be received by a third party. In order to prevent this, we need to encrypt all data sent from both server and client. Are mobile telecommunication signals not encrypted anyway? Normally they are, the GSM standard allows to switch off encryption at times with heavy net usage, though [1]. In terms of serious security this is as good as no encryption at all, so we have to implement our own encryption. On top of that we need to make sure that both server and client can be uniquely identified and that no one can fake being another client. If that were not the case, someone could send a big number of messages to the server saying there is a traffic jam on that road. The server would broadcast this information and the navigation systems would lead people around this road so that the traffic jam faker could drive on an empty road Implementation of Encryption To encrypt we should use the asymmetric RSA system that uses the fact that it is an extremely costly operation to undo the multiplication of two very high prime numbers if they are both unknown and can therefore be made extremely safe with high prime numbers. Every user has a public key that is shared and can be known by everyone. The sender encrypts the message with this public key and sends it. It can be only decrypted with the receiver s private key which he must keep secret. This ensures that the client s location information sent to server A can neither be decrypted by server B nor by any other client. Since the public key is known to everyone, though, the previously mentioned fake traffic jam scenario is still not prevented. We suggest to take a user s password or make him create a new one and compute a cryptographic hash value of this password using e.g. SHA-2 1. This SHA-2 value makes it impossible to get the password out of it without major brute force attacks which means that the password is not known to the server. Whenever a client or a server sends a message to someone, along with the serial number of the phone his personal SHA-2 code is sent with it encrypted with the counterpart s public RSA key. Therefore every user can be identified uniquely without any possibility to enable someone else to pretend to be him, assuming his password is not disclosed. A server and a client can either accept all incoming messages or they can require a previous external registration to prevent spam messages from both servers to clients and vice versa. If large quantities of data are sent from server to client or the other way round, we can apply a common trick. It might be reasonable to only encrypt the key of a symmetric encryption algorithm such as Twofish or AES using asymmetric encryption since this is way more costly to apply than its symmetric counterpart. The rest of the data is 1 The popular MD5 has been broken and SHA-1 has the same theoretical problems. Therefore the cryptographic hash algorithm of our choice would be SHA-2. It is crucial that the encryption is one-way so that there exists no function to retrieve the password given the hash code of it. Second, the probability that two passwords create the same hash code must be minimized to reduce the chance of brute force attacks [19]. 24 Chapter 4. Privacy and Security 25 encrypted using the relatively cheap symmetric algorithm which is nevertheless very secure due to the unavailability of the asymmetrically encrypted symmetric key. For an implementation of an anonymous public sensing system see AnonySense [20] which preserves users anonymity yet provides the server with sensed data. 25 Chapter 5 Architecture Hardware & Sensors Storage Screen Screen Storage Task Task Task Answer Sensing Plugins Answer Answer Interpreter Scheduler Task Sending Management Client Server Task Repository Task Elements Libraries Security OS Packages Figure 5.1: The main components of our public sensing system. Figure 5.1 shows the general structure of our public sensing system. Public sensing is the process of distributing requests to gain information for the profit of the public and receiving the returned results. We called the requests tasks and the results answers. Obviously there has to be some kind of communication channel between the devices that request information and the ones that return them. A device that mainly sends out tasks is called a server and a device that mainly receives them and answers them is a client which is often mobile. The mainly indicates that even though this will be the setup in most of the cases, there is no restriction that a 26 26 Chapter 5. Architecture 27 client cannot send tasks or that a server cannot give answers. For simplicity s sake, throughout this thesis we will stick to the standard model of a server sending tasks and a client responding. Furthermore a client will be a mobile device, e.g. a cell phone. There are situations where it would be good if the client was capable of sending out tasks as well. The dashed line on the very left of Figure 5.1 means that a client can also send tasks to itself. A user refers to an end-user of a mobile device and a developer is someone who manages sending out tasks from the server, changes parameters of tasks, or creates new tasks. 5.1 General Precedent Thoughts The aim was to provide an architecture consisting of a server program and a client app that communicate with each other. The distinction between this foundational infrastructure and the actual public sensing task was deliberately drawn very sharply. The reason for this is that once the abstract communication structure is up and running, a programmer of another app does not need to understand the details of data transfer, he can simply use the provided classes and concentrate on the individual sensing task according to the well-known principle of encapsulation. On the other hand, the developer of the abstract infrastructure does not need to be bothered with details of how the precise sensing task looks like. This is why we want to provide a public sensing communications architecture that is completely independent of the tasks it supports to run. If we do not want the programmers of tasks to hit one wall after another and become frustrated because they cannot do the things they want to do, we have to design the architecture to cover the vast majority of possible requests. 5.2 Abstract Fundamental Architecture Tasks What Is a Task? On an abstract level, a task is one participant s attempt to gain knowledge the other one possesses or can acquire. We explicitly do not restrict it to a server requesting information from a client since we want to design the architecture to fulfill the needs of as many task developers as realistically possible. In public sensing most of the time the server will send out the task to the client to get the information, but it could also be the other way round, that a client requests information from the server about another client s position or about an RFID sensor s location, cf. [12]. 27 Chapter 5. Architecture 28 Tasks with and without User Interaction Public sensing tasks can be divided into two groups: One case involves the user to provide the data, e.g. Do these two roads that you see in front of you and that look on the map like an intersection do actually cross or does one run on top of the other?. In the other case, the device answers without user interaction (e.g. How loud is it where you are now? ). In this case the question is not supplied as text but in code which the device can understand. Common Execution Constraints What both have in common is that every task has an expiration date and an indication of whether it should be run once or periodically. To enable later extension, every task also sends the minimum number of required devices 1 in the area around needed for public sensing and a specification of how big and where this area is. On top of that, execution is restricted to a time frame in which it is allowed. Executing Tasks If we wanted to minimize transmission data regardless of the costs, we would only send a very small ID to the server which would then execute the code that belongs to this ID. Since the advantages of a different method outweigh the little additional data traffic, though, we opted for supplying a task with all the tools necessary for its execution. With tools we mean the code that carries the information of what to do when the task is executed. The huge advantage of having tasks that do not depend on a client that knows their ID and what is hidden behind it is that tasks unknown to the client can be run as well. If this was not the case, for each new and yet unknown task not only a new task class but also a new client class would have to be programmed and deployed to the mobile device. Not all theoretically acquirable information can be gained without changing the software on the client side, however. Tasks that need to access hardware like sensors may require an imported package or some method on the client side that they can attach to. This hardware could be present in the device or could be plugged into it. This concept is similar to the operator concept of smart homes, cf. [21], where an operator can be represented as a black box where some processing is effectuated on a set of inputs, giving as a result a set of outputs.. A sound operator, for instance, supplies raw sound data. A sound volume operator would then build on the sound operator s return values and calculate an average sound volume. Nevertheless many tasks, especially a theoretically infinite range of user interaction GUIs, can be executed by the client without prior knowledge. For implementation details see Chapter 6 on page For sending environmental data with imprecise sensors a minimum number of devices might be necessary to compute a fairly accurate average value, for example. 28 Chapter 5. Architecture Server Characteristic of public sensing is the fact that one server collects information from several attached mobile devices. Therefore we need to implement a multithreading system. The server should also be able to send several different tasks to the same client. Since the server does not know in what order the tasks were executed on the client or if some were lost due to bad connectivity, every answer or response to a task contains the ID of the task that was answered to tell the server which question was answered. So e.g. it is sufficient to send the index of a selected item, using the ID the server will find out the question. Attaching only an ID and not the whole task object to the answer reduces its size Client As mentioned before we want to enable several tasks to be executed on the same client and thus need multithreading here as well, also because we want to send and receive messages all the time in the background. Incoming tasks are put into a waiting list that is checked frequently for tasks to execute. Several parameters determine whether a task is executable or not. For details see Section on page 43. The final decision is up to the user, though. He can choose to run this type of task always or never or decide for each incoming task of this type individually. For a discussion of security aspects see Chapter 4 on page 21. 29 Chapter 6 Implementation 6.1 Why Android? Our reasons to choose Android are similar to the ones of end user device manufacturers [13]: ˆ Comprehensive software platform: Many key applications exist already and can be used. ˆ Free: No license fees have to be paid. ˆ Open source: Big parts of the Android platform are published under open source license so that programmers can dig deep into the source code and Android can tap the innovation power of the open source community. ˆ Equal rights for all apps: Third party apps and pre-installed programs are treated equally which enables new innovative apps to enter the market easily. ˆ Approved technologies: Programming is made easy with the provided plugin for the popular development environment Eclipse. ˆ Supported programming language: With Java a modern, wide-spread, and portable language has been chosen with all its advantages. 6.2 Package Structure Bearing in mind the wide range of applications, we are now about to implement a prototype with Java that supports the majority of thinkable distributed sensing scenarios. Everything is organized as follows: ˆ Java project LiteViewCollection Package answerlayouts Library: Several GUI elements that can be changed by the user to answer a task, e.g. text edit. 30 30 Chapter 6. Implementation 31 Package litegraphics Library: Geographical location and area elements. ˆ Java project PublicSensingServer Package publicsensingserver Application: This contains the applications that runs on the server. ˆ Android project PublicSensingClient Package android.publicsensingclient Application: Here we store the program that runs on the client and several classes needed by both server and client. Package android.publicsensingfinaltasks Library: All non-abstract tasks that can be sent are to be stored here. The two packages in italics contain the two classes Server and Client whose methods start the programs on server and client. The library packages are imported and PublicSensingServer imports android.publicsensingclient as well since some classes that are needed by both server and client are stored there. The source code is saved in Unicode (UTF-8). 6.3 Shared Classes between Server and Client Message and Its Subclasses Msg The abstract super class Msg is spelt in its abbreviated form to prevent confusion with other classes called Message and avoid the dragging along of the package names. Two likewise abstract classes are derived from Msg: Task and Answer. Task The following constrains are needed to create a new Task: ˆ Expiry date. null means it will never expire 1. ˆ How many seconds shall we wait until we execute it again? 1 signifies that it is not periodic and shall be executed only once. ˆ A TimeFrame that restricts the execution time. A TimeFrame takes start and end date and time. At the present stage, the period is set fix to daily which means that only the hours, minutes, and seconds will be looked at to determine executability. Still we give TimeFrame a full Calendar object to ease future extension to dynamically change it to e.g. hourly, weekly, or monthly. null means no time frame restriction 2. 1 There could still be a TimeFrame set that restricts execution, however. 2 That does not necessarily mean no timewise restriction, however. There could still be an expiry date set. 31 Chapter 6. Implementation 32 ˆ An array of geographical areas (AreaLite[]) in which execution is possible. 3 ˆ How many devices need to be in the area so that execution makes sense? 4 Task implements TaskRunnable and therefore every object derived from it has to have a method called run() which will be called for execution of the Task. TaskUserInteraction This class is derived from Task and takes an array of ViewLite elements 5 which are responsible for the interface displayed when the TaskUserInteraction is run. TaskUserInteraction has an empty method run() already so that its subclasses do not have to implement it since they are dealt with separately because we have to control the execution of tasks with user interaction to prevent unorganized popping up of new GUIs. A simple example of run that returns a new Answer object with only the location is shown in Listing 6.1. First it requests the current instance of Client, the private Client myclient, and then it gets the location of it. In Listing 6.2 we see the constructor of a subclass of TaskUserInteraction, Train- Lateness, which asks the user how late the train is. Several objects of subclasses of ViewLite are set up (lines 5-11). They will be shown in this order from top to bottom to the user. Duplicate Detection If the connection between server and client dies and comes alive again later on, at the present state the server does not know that the tasks it is about to send to the client are there already 6. For the server every new connection is the same and it starts sending tasks. In order to not litter the display of the client with duplicates and even worse have them execute more often than desired since each task manages its execution times on its own and therefore n tasks would be executed n times we allow only tasks that have not been received yet to be enlisted. This check is performed on the client side at the reception of each new Task. The server also uses the same kind of duplicate detection before sending tasks, cf. Section on page 38. This leads us to an equality check algorithm and therewith to the question: When are two tasks equal? Using the standard method firstobject.equals(secondobject ) is not possible because as shown in Section 6.6 on page 43 two objects with precisely the same initial parameters do not have to be the same object using this operator 3 Some developers assume that the context server stores the positions of the corresponding [RFID] sensors. [12], so an array of areas is required. 4 Not used yet but necessary if mobile devices are to decide autonomously without recheck with the server if execution shall take place or if a minimum number of sensors is required to get a reliable average value. 5 View elements such as text edit, time picker, etc. Cf. Section on page 34 6 For large quantities of tasks or big task objects a query from the server to the client about which tasks are there already would increase efficiency. 32 Chapter 6. Implementation 33 since they could have be created during two different calls of the creation class. Therefore we have to actually compare all relevant parameters on our own by overriding the equals methods. First we had to make sure that all initial parameters that is all non-abstract classes, pre-existing or self-written, that we use in constructors of any subclass of Task can be properly checked for equality with their counterparts, assuming both objects are instances of the same class. If this is not the case, we can return not equal without further checks. We allow the objects in the constructors to be null to indicate something special (e.g. no expiry date) and therefore have to check if they are null before we perform any other checks. We must not return not equal if one element is null, however, since obviously both being null means they are equal. Equality check for arrays like AreaLite[] is done with Arrays.deepEquals(firstArray,secondArray ). Task overrides the equals method and returns true if all variables are equal to their equivalents in the other Task. At the present stage, TaskUserInteraction overrides equal as well and returns the value of its super class (Task). The final tasks that is the classes derived from Task or TaskUserInteraction also pass the request for equality check down the line. If desired, an extra parameter check can easily be added, though. Future developers should note that they have to override the equals method to ensure proper comparison when creating a new final task. Our Prototype Tasks ˆ GetLoc: This simple task returns the location of the mobile device. The server can interpret it in several ways, open the door, for instance. ˆ SenseLoudness: Our application of loudness sensing takes the raw data from the microphone and calculates an average value which is then sent back 7. ˆ GetBluetooth: This senses for visible bluetooth devices and returns an array with the devices names, MAC addresses, and the signal strengths. The retrieved information can be used to communicate with other mobile devices. ˆ TrainLateness: Using this task, the user can report a belated train and supply additional information such as estimated time of arrival. ˆ RoadsCrossing: The user is asked about the arrangement of two specific roads that might cross. Answer In general, if a Task is sent out, an Answer is expected as response. These parameters are passed to an Answer object: 7 Since converting this value into decibel would require massive calibrating and is very different for different phones we leave this task for future developers that specify in this direction. 33 Chapter 6. Implementation 34 2 public Answer run() { 3 LocationLite loclite = Client.getCurrInstance().getCurrLocation(); 4 return new Answer( 1, loclite, null, getid()); 5 } Listing 6.1: The run method of the task that only gets the location. 1 public TrainLateness(Calendar expiry, int periodicsecs, TimeFrame timeframe, AreaLite[] area, int requireddevicesaround) { 2 super(expiry, periodicsecs, timeframe, area, requireddevicesaround, null); 3 4 ViewLite[] views = { 5 new TextViewLite( What is your destination? ), 6 new EditTextLite( Please enter destination., true), 7 new TextViewLite( When was the train scheduled to arrive? ), 8 new TimePickerLite(), 9 new TextViewLite( What is the estimated arrival time? ), 10 new TimePickerLite(), 11 new SpinnerLite(new String[] { Rough personal guess, Official estimation., No clue }) 12 }; 13 setviewslite(views); 14 } Listing 6.2: The constructor of TrainLateness ˆ The current location of the mobile device. This information is the very essence of public sensing and will be utilized for almost all sensing projects. ˆ An Object that may contain any additional information imaginable. ˆ A unique ID that tells the receiver to which question this is the answer. ˆ A time stamp of when it was executed. An overview of Msg and its subclasses is shown in Figure GUI Classes Views Shown to the User If a user is involved in supplying the server with information, a user interface is needed. It would have been best to be able to put together any GUI element imaginable on the server and send it to the client where it is displayed. However, since even the most basic bricks such as TextView are not serializable, the whole building made up of these bricks cannot possibly be. Furthermore it is not (yet) supported 34 Chapter 6. Implementation 35 GetLoc SenseLoudness GetBluetooth RoadsCrossing TrainLateness Task Answer Msg Figure 6.1: Msg and its subclasses. Abstract classes are in italics. TextViewLite MapViewLite TimePickerLite EditTextLite SpinnerLite ViewLiteAnswerable ViewLite Figure 6.2: The ViewLite classes. Abstract classes are in italics. to read external non-preprocessed XML files and display them. If it was, we could create an XML file on the server or an attached emulated client and send it to the mobile device. Due to these two restrictions, however, we thought it best to rewrite the relevant parts for our purposes in so-called light classes which are serializable. We called them like the Android original class with the suffix Lite. Customizability is currently restricted to necessities such as the text of possible items to select in a Spinner 8. For our needs it boiled down to five bare bone rewrites of GUI elements divided into two categories. Figure 6.2 shows a visual representation and below there are details for each class: ˆ Information to the user TextViewLite displays text. You can specify if you want the text to be a hint so that it disappears if clicked on it. MapLite creates a button that shows a full screen map when clicked on. ˆ Ways of answering. The following classes are not direct subclasses of ViewLite but of ViewLiteAn- 8 A way of selecting one element out of many, similar to radio buttons. 35 Chapter 6. Implementation 36 swerable which is a subclass of ViewLite. This means they implement the interface Answerable and therewith getanswer() SpinnerLite: The user can choose one from many text items. EditTextLite: Takes user-created String. TimePickerLite: Lets the user pick a time. These bricks can be combined in any order and number of occurances in a vertically scrollable LinearLayout. MapViewLite can only be used once due to complicated location object management if one wanted to display several locations 9. Showing only one map in one task should suffice all practical demands, however, since one task ought to be one straightforward question. At the very bottom there are always two buttons labeled quit and submit. Hitting submit the entered information is sent to the server together with the Task that has been answered and quit exits the program. public String[] getanswer(string index) returns a one-dimensional String array to avoid parsing in a possible future extension if several items can be chosen. In the tasks that show a GUI, additional methods should be written to make it easier to retrieve the needed information. Listing 6.3 shows an example. It uses a twodimensional String array because each ViewLite element returns a one-dimensional array already public static String getroadsarrangement(string[][] answ) { 2 return answ[2][0]; 3 } Listing 6.3: The answer of the third ViewLite element (index 2) is requested and the second index is 0 since all other ones are null. MapViewLite is different from all the other classes since it does not show a map but only a button that will show a full screen map if clicked at. This is better than a small map squeezed in between the other GUI elements since the user never has to see both the map and the rest at the same time. That is why MapViewLite creates only a button. MapViewLite is given several parameters at creation which are used for pointing the user to the streets the server is interested in. Most important is the center of the possible intersection. The position of the two labels A and B is determined by 9 When the ViewLite elements are inflated and the View elements are created, for MapViewLite a button is created and listener is added. If clicked it starts an Activity (A module of the whole program connected with one or many displays, called Views.) and passes e.g. the LocationLite of where the crossing is. This LocationLite has to be a global variable so that the listener can access it. Managing different locations with arrays would be possible but not necessary for our needs. 10 The one-dimensional array of ViewLite elements of which each returns a one-dimensional array results in a two-dimensional array. 36 Chapter 6. Implementation 37 three variables: The distance in meters how far from the center the labels are to be placed and two angles that determine in which direction from the center the two labels A and B shall be drawn. When the button is clicked, a new Activity will be started and these variables are passed along to ShowMap. Geographical Location For the same reason, namely lack of serializability, a new location class Location- Lite has been created. An object of it can be constructed with either two doubles as latitude and longitude or the original android.location.location. Geographical Area One determining factor whether a Task is executable or not is whether the mobile device is in a specified geographical area. Following the same convention that we introduced before, we added the suffix Lite. Both CircleLite and PolygonLite extend AreaLite. Both also have the method public boolean contains(locationlite l) that returns whether a geographical location is inside the area or not. The code for the polygon was taken from [22]. For the circle that is actually an ellipse if the latitude and longitude values are regarded as two orthogonal axes point (x, y) is within the ellipse if the following holds: x 2 a 2 + y2 b 2 1 a is the absolute value of the distance from the center to the point on the ellipse that is farthest east and b respectively north. These distances need to be in degrees of latitude and longitude, however, not in meters. Converting them is done using the formula shown in Section Input/Output The class IO is the foundation stone of our architecture. All the communication between server and client is dispatched by it. When the server is started, it creates two instances of ServerSocket with port numbers. When the client accepted both requests, both the server and the client create an object of IO. If the client could not automatically establish a connection with the preset IP and port numbers, the user will be asked to enter or change the IP address and port number and then hit connect. To keep it simple, the port number of client-to-server communication is one higher than the number of server-to-client communication and only the latter can be modified by the user. In order to get a better understanding of the underlying structure, the constructor and some of the public classes will now be looked at in detail. 37 Chapter 6. Implementation 38 The Constructor IO s constructor takes two Sockets (for ingoing and outgoing data) and sets up the ObjectOutputStream and its input equivalent. After that it starts a thread that regularly checks a queue for outgoing messages and sends them. public synchronized void tosendq(msg msg) Since send is a private method of IO, everything that shall be sent needs to be passed to tosendq. The internal SendThread of IO will then send it. All subclasses of Msg are serializable and can therefore be sent. public Msg receive() In contrast to its counterpart send, receive is public so that server and client can have a thread to directly fetch a received message without an extra thread and the resulting additional delays. If send could be called directly, it would stall the system if large amounts of data were sent since it is a blocking method. public synchronized boolean removefromrecq(msg msg) If a user explicitly chooses to never execute a task, it will removed from the list as if it was never received so that it does not litter the GUI any more. public synchronized Task getxtask() Whenever the client is connected to the server and is not busy with another task, it checks for auto-executable tasks in the background, that is, it calls this method and receives a Task to execute. For a precise definition of auto-executable in contrast to user-executable see Section on page 43. public synchronized LinkedList<Msg> getallmsg() This method returns all received messages. The client calls this method and filters out the Tasks to display them to the user who can then specifically pick one to run. 6.4 Server s Classes The Core Class: Server To avoid circular references in the build path, we store only the classes that only the server needs here and import all the rest. The main Method When this method is called, Server performs the following steps: 1. Set up the ServerSockets. 38 Chapter 6. Implementation Read in a text file which tasks to send to each client. Remove duplicates, cf. Section on page Create the Tasks using the information acquired in the previous step. 4. In an infinite loop do the following until interrupted: (a) Accept the Sockets. If there is no client or if it has not responded, wait until receiving a response. (b) Create an instance of IO called myio. So if the server serves multiple clients, it will create a new IO for communication with each client. (c) Start a new thread that continually checks for messages in the inbox. (d) Add the tasks to send to the send queue using e.g. myio.tosendq(roads) where roads is an instance of RoadsCrossing. 5. Close ServerSockets. The Receive Thread Every thread, that is, every connection with a client, has its own instance of IO, therefore it has to be given to the constructor of the ReceiveThread. If something is received that is not null, react2msg(msg) is called and the received message is passed along. If the received message is null, this is a signal that the connection has been lost. The receive thread breaks the loop then, kills the other socket as well, and dies. Since the method that returns the received messages is a blocking method we do not need any delay here. After one message has been received it will wait for the next one. React to Received Message Having received a message, this object Msg is given to private static Msg react2msg(msg msg). Here we first check if it is an instance of Answer since so far we have only sent Tasks from the server and received Answers from clients, not vice versa. If it is an Answer, we want to find out to which Task it is the Answer. This is done by checking if the ID String that belongs to the answer matches with known IDs of subclasses of Task. Let us assume we received an Answer to the task TrainLateness and have a closer look at what is done. Now as the next step a new dummy object 11 is created like this: TrainLateness train = new TrainLateness(-1, null, null, null, 0); Using this dummy object we can get the ViewLite array of our received Task because at creation of TrainLateness the GUI elements such as TimePickerLite or TextViewLite are set up. For instance, if the answer to the third ViewLite element 11 It is not possible to use a static method to retrieve the ViewLites since we want to access the different ViewLite elements which are unique for each TaskUserInteraction 39 Chapter 6. Implementation 40 1 System.out.println( The train from + a.getlocationlite() + to 2 + TrainLateness.getDestination(answ) + is 3 + TrainLateness.howLate(answ) 4 + mins late and will probably arrive around 5 + TrainLateness.getRealTime(answ) +. ); Listing 6.4: Displaying the received information to the user. is A below B then this third element could be theoretically a comment if the third element was EditTextLite. That is why we have to find out what kind of ViewLite element the third one actually is and that is what we need the dummy object for. The retrieved ViewLite array is then given to public static String[][] interpretanswer(answer answ, ViewLite[] views) together with the Answer. This method calls the methods getanswer() of each of the the ViewLite elements. Their return values are then saved in a two-dimensional String array and returned. Now we have a two-dimensional String array which contains the answer. Somewhere. We do not have to fiddle around with the indices, however, but can simply give this array to static methods of the class that filter out the bits and pieces of information we need. For TrainLateness the code listed in Listing 6.4 produces an output like this: The train from (lat= , lon= ) to Berlin main station is 5 mins late and will probably arrive around 12:05. Appropriate software would then be able to find out that this information is about the train from Stuttgart to Berlin that was scheduled to depart at noon and would feed it into the real time traffic surveillance system. But why this detour of first passing the Strings of the Answer to another method just to receive yet another String array? Can we not just read the Strings directly? For some ViewLite elements this is true. For others like the SpinnerLite, however, what is sent from client to server is 6, for instance, which means the seventh element has been chosen. The SpinnerLite s method getanswer() interprets it correctly though and returns the String of the seventh element. For the sake of simplicity and generality all Answers have to go through the method interpretanswer(...) even though some return unaltered CreateTasks As shown in detail in Section 6.6 on page 43, this class can be edited by the user, creates new tasks, and stores them on the harddrive in a serialized form. Since this class can be called independently from the core class Server, tasks can be supplied at runtime. 40 Chapter 6. Implementation 41 Figure 6.3: The background thread found a task to execute. Figure 6.4: We are not connected yet TransferTasks This class transfers serialized Tasks from a file system location via a socket connection to the Server. The parameters folder path, IP address, and port number are given in this order. The big advantage this class brings is that someone who wants to supply a task does not have to have access to the server but can simply establish a socket connection. Additional security measures can be set up on demand. 6.5 Client s Classes The Core Class: Client Initialization The method oncreate(bundle savedinstancestate) starts the LocationManager. We use the same LocationListener to check for both GPS and network provider location information. After that, it checks if the server with the preset IP and port number is available. If yes, it will show a list of received tasks but as soon as it finds an executable task, the user will be asked if he wants to execute it (see Figure 6.3). If no connection can be established with the given socket parameters, the user will be faced with a configuration screen where he can alter IP and port number (see Figure 6.4). Establishing the Connection Using the IP address and port number, the client now tries to establish the connection in connect(). It creates an instance of IO which other activities can access using public static IO getcurrioinstance() since it is crucial that all input and output is dispatched by the same instance of IO. Furthermore a thread that frequently checks for incoming messages is started. It also calls startnewtask() to make it ready for executing a new task. Whenever 41 Chapter 6. Implementation 42 this method is called, it means that the previous GUI is finished and a new one can start. Switching to the View that shows the received tasks concludes the initial setup of a client that has just been created. One GUI Task at a Time There are two ways a task can be executed: First, the program looks for an executable task in its queue and grabs the first one. Second, the user clicks on a task to explicitly execute this one. We want to have strictly non-parallel executions of tasks so that no task that is asked to be executed can push aside another task. This concept is important for tasks that require user interaction but right now we treat all tasks the same 12. The goal of this synchronous approach is to prevent the popping up of tasks whenever they become executable. The user might be busy answering one TaskUserInteraction and we have to give him the time he needs for that and prevent by all means that the task is gone all of a sudden. Neither an automatically called task can supersede a manually clicked one nor the other way round. We also want to forbid the thread that periodically executes tasks to do so if another task is running already. To clarify our non-parallel approach we have to say that it does not mean that the user has to wait until the data has been sent to the server until the next task can be executed. As soon as a task calls startnewtask() it tells the scheduler: I am off, the stage is free for another task! Note that this can be right after starting a thread that may continue sending data for a long time. This means that even though the task is not finished from the device s perspective it still needs to send the answer as soon as the user hits submit, a new task can be shown since the screen is ready to show a new GUI. Given this principle of giving each task the full attention until it is done, we thought the most elegant way of achieving this would be that whenever a task is about to finish (and only then!) it calls startnewtask() which starts a thread that checks for new executable tasks. It cannot just call the next task in the line since there might be none which can change all the time, however, with the reception of new tasks, with moving into an execution area, or with progression of time. Doing it this way, we do not need to set a flag whether tasks can be executed and have threads continually check this flag which would result in artificial and unnecessary delays. 12 If desired, the principle of non-parallel execution can be interpreted in a less strict way: All tasks that do not require user interaction and that have been given permission by the user to always execute, could be moved to another thread that runs in the background and frequently executes the appropriate tasks in parallel to the thread that deals with the other tasks that require user interaction. 42 Chapter 6. Implementation 43 Reacting to Received Message The method react2msg(msg msg, boolean allowx) 13 decides what to do with a received message. For now, only if the Msg is a Task we react to it. If the user set the execution permission for this task to always or if the task was explicitly clicked by the user, it will be directly executed. For tasks that require user interaction a new Activity is started which creates the GUI. For tasks without user interaction the run() method is called which takes care of all the rest and returns an Answer which is sent back to the server. If a task is set to be executed periodically it calls the run() method every time it executes and creates a new Answer. If the task that has been asked to execute does not have the permission to do so yet, shownewxtask is called which prompts the user to decide whether to execute it or not. If the task is then given the permission it will enter react2msg(...) again, this time with the permission required for execution. Auto-executable vs. User-executable We defined two kinds of executability because even when a task is flagged as not executable for the automatic periodic execution check, the user can still invoke it by clicking on it since it does make sense not to forbid the user to override his previous decision but also not to bother him by asking again to early. Therefore: set of auto-executable tasks set of user-executable tasks. In contrast to parameters like time and location which determine both executabilities, auto-executability is only granted if the user has not clicked no when asked to execute or his no is longer back than a specified period of time. If it is not a periodic task, that is, it is to be executed only once, it is only autoexecutable if it has never been executed. If it is a periodic task it may be run automatically if it has never been executed yet or if the last execution time dates back longer than the task s period of execution. 6.6 Creating the Tasks As mentioned before in Section 3.2, we simply serialize the objects that have been created and write them into a file. The file name is the class name followed by a dot, a time stamp, another dot, an index 14, and the extension.ser. We chose the dot to separate the class name from the time stamp because a dot is a legal character in a file system name but does not appear in class names. We could have also used the space character but spaces in file names should be avoided, especially when working with command terminals. Unambiguously separating the class name from the time stamp enables us to easily extract both of it for possible future usage. 13 allowx is true if execution is definitely allowed either because it was clicked by the user or because this task has been given the right to be always executed without further questioning. Note that there are two different methods called react2msg one in Server and one in Client. 14 The index ensures that two tasks will not have the same file name which could happen without the index if they were received in the same second. 43 Chapter 6. Implementation 44 This file is then read from the main program. Doing it this way, the main program can remain unaltered and whenever one needs to modify or create a task, all changes can either be written into the existing file CreateTasks.java or this file can be copied into another folder, modified, compiled, and executed. The server is given one folder which it frequently checks for new tasks. The server remembers which tasks were sent to each client 15 and checks this folder for new tasks and sends them to the client. Neither server nor client have to be restarted to supply the client with a new task which makes it very convenient for both users and developers. When a class is changed and there are still serialized objects of the old class there, the computer will realize it and throw an error. We catch it and print out a separate error message to the user and tell him the most probable reason for this error. The solution is to delete the old files and create the tasks anew. The source code of our class that creates the tasks is shown in Listing 8.1. If there is a parameter supplied when executed, this is interpreted as the folder path where to put the created serialized objects. Supplying Tasks via Another Socket On the server side, a third socket is opened through which serialized Tasks can be sent. This has the advantage that people who want to send out tasks do not need access to the server but can simply create the tasks on their device and send them to the server. Security and identity check measures can be applied if needed. Furthermore the server could be easily set up to receive tasks from multiple senders. 6.7 The Life of a Task: An Exemplary Overview Creation A new task is born when the required parameters have been entered into Create- Tasks, the *.java file has been compiled to the *.class file which is executed then. It creates a separate *.ser file with the serialized task Sending The Server class reads all *.ser files in the folder (either supplied via args[] or the the current directory) and sends them serialized to mobile devices if the connection has been established. The steps of deserialization and consequent serialization could be omitted, doing it this way ensures that the objects we have read are valid, though Reception The receive thread of the client checks for incoming tasks all the time, reads our task, and puts it into the queue. 15 Note that if the connection died and is revived again the server does not remember that it is now connected with the same client as before and treats it as if no tasks had been sent. 44 Chapter 6. Implementation Delay Due to Location or Time The task is not executable yet because the cell phone is not in the right location or we are not within the time frame of execution. This is shown by a grayed out task name next to the check box which does not react to clicks as well Execution The automatic check for executable tasks picks our task and proposes its execution to the user who agrees. The user could have also clicked on the task Awaiting User Interaction See Figures 6.5 and 6.6 for the screens shown to the user. Figure 6.5: The user entered the location and is about to change the estimated arrival time. Figure 6.6: The time entered in the previous screen is an official estimation. 45 Chapter 6. Implementation Sending Back the Task Hitting submit, the answer is extracted and sent back to the server and the user either sees a request to execute another task or a list of received tasks like in Figure Displaying the Sensed Data On the server side the task is examined and we can read the response: The train from (lat= , lon= ) to Berlin main station is 8 mins late and will probably arrive around 12: Using the Menu Every Android phone has a physical button labeled Menu which is very useful for buttons that should be present somewhere but are used fairly seldom and therefore should not fill up the screen all the time. The subsequent images will show all available menus of our application and how they could be used. The apparently endless stream of proposed tasks for execution wears the user out. So he clicks on the menu to end automatic execution proposal (see Figure 6.7). In Figure 6.8 we see that there are executable tasks but the user will not be asked any more. If he wants to receive proposals again, however, he can simply click on the menu and hit Configure to switch it on again. This leads him to Figure 6.9. As soon as he marks the check box ticked, a new suggestion pops up (Figure 6.10) if there are any tasks auto-executable right now. 6.9 Practical Remarks USB Debugging Using USB debugging with Eclipse is very convenient especially when testing functionalities such as microphone and bluetooth that are not supported by the emulator. After plugging the USB cord into the PC and the phone, Android will ask you to set the USB connection type. Normally one has to select USB debugging but on Debian squeeze 6.0.2, Kernel Linux amd64 it worked only when harddrive was selected. The phone we used is an HTC Desire. With this model, sensing of bluetooth devices often resulted in loss of wireless connection. Since it worked perfectly with HTC Hero we assume some hardware issue beyond our control Means of Information Exchange While testing, server and client communicated via wireless LAN since it was conveniently available with no extra costs. For practical use later on we assume a constant internet connection via UMTS of the mobile device. 46 Chapter 6. Implementation 47 Figure 6.7: The user wants to decide on his own which tasks to execute. Figure 6.8: After having changed his mind he hits Menu again. Figure 6.9: The user changed his previous automatic execution setting. Figure 6.10: Without intermediate click an executable task is shown. Security in Android apps Security in Android apps Falco Peijnenburg (3749002) August 16, 2013 Abstract Apps can be released on the Google Play store through the Google Developer Console. The Google Play store only allows apps TaleBlazer Documentation TaleBlazer Documentation HOW TO READ THIS DOCUMENTATION TaleBlazer specific terminology is denoted with italics. Example game functionality which is not intrinsic to the TaleBlazer software is denoted SCORPION TRACK.COM. Technologically Advanced Stolen Vehicle Tracking & Fleet Management System. Part of the Scorpion group SCORPION TRACK.COM Technologically Advanced Stolen Vehicle Tracking & Fleet Management System Award Winning Best Consumer Tracking System Best Security Product Best Fleet Management System Best British. Norton Mobile Privacy Notice Effective: April 12, 2016 Symantec and the Norton brand have been entrusted by consumers around the world to protect their computing devices and most important digital assets. This Norton Mobile Privacy. Developing Fleet and Asset Tracking Solutions with Web Maps Developing Fleet and Asset Tracking Solutions with Web Maps Introduction Many organizations have mobile field staff that perform business processes away from the office which include sales, service, maintenance, What Are Certificates? The Essentials Series: Code-Signing Certificates What Are Certificates? sponsored by by Don Jones W hat Are Certificates?... 1 Digital Certificates and Asymmetric Encryption... 1 Certificates as a Form Android Developer Applications Android Developer Applications January 31, 2013 Contact Departmental Privacy Office U.S. Department of the Interior 1849 C Street NW Mail Stop MIB-7456 Washington, DC 20240 202-208-1605 DOI_Privacy@ios.doi.gov A very short history of networking A New vision for network architecture David Clark M.I.T. Laboratory for Computer Science September, 2002 V3.0 Abstract This is a proposal for a long-term program in network research, consistent with FLEET MANAGEMENT & CAR SECURITY SYSTEM GPRS/GPS FLEET MANAGEMENT & CAR SECURITY SYSTEM FOR PROVIDERS AND CUSTOMERS The Tracker Server Communication Program for data collection The Tracker Client Map Program intended for dispatching desks The GSM/GPR Auditing a Web Application. Brad Ruppert. SANS Technology Institute GWAS Presentation 1 Auditing a Web Application Brad Ruppert SANS Technology Institute GWAS Presentation 1 Objectives Define why application vulnerabilities exist Address Auditing Approach Discuss Information Interfaces Walk Junos Pulse for Google Android Junos Pulse for Google Android User Guide Release 4.0 October 2012 R1 Copyright 2012, Juniper Networks, Inc. Juniper Networks, Junos, Steel-Belted Radius, NetScreen, and ScreenOS are registered trademarks, Privacy Policy Version 1.0, 1 st of May 2016 THIS PRIVACY POLICY APPLIES TO PERSONAL INFORMATION COLLECTED BY GOCIETY SOLUTIONS FROM USERS OF THE GOCIETY SOLUTIONS APPLICATIONS (GoLivePhone and GoLiveAssist) GPS Vehicle Tracking. The Complete Reference Guide GPS Vehicle Tracking The Complete Reference Guide GPS Vehicle Tracking: The Complete Reference Guide GPS vehicle tracking has gained popularity in many segments of the business world. Two main reasons Chapter 3 Safeguarding Your Network Chapter 3 Safeguarding Your Network The RangeMax NEXT Wireless Router WNR834B provides highly effective security features which are covered in detail in this chapter. This chapter includes: Choosing Appropriate ESET Endpoint Security 6 ESET Endpoint Antivirus 6 for Windows ESET Endpoint Security 6 ESET Endpoint Antivirus 6 for Windows Products Details ESET Endpoint Security 6 protects company devices against most current threats. It proactively looks for suspicious activity Verizon Wireless Family Locator 4.9 User Guide Contents Verizon Wireless Family Locator.9 User Guide Contents Let s get started... Sign up, then activate phones!... Use the Activation Wizard... Set Up an Android... Set Up a BlackBerry... 6 Set Up a Feature... An Overview of Embedded Computing Embedded Computing Introduction to Embedded Computing......................................-2 Software Tools for Embedded Computing An Overview of Embedded Computing Moxa Protocol Converter................................................. multifactor security Mobile multifactor security A revolution in authentication and digital signing Mobile multifactor security A revolution in authentication and digital signing Smartphones will continue to ship in high volumes, SECURE COMMUNICATIONS Crypto products FIG 1 The TopSec Mobile is an easy-to-use encryption device that is independent of the mobile phone. It can be connected to virtually any modern mobile phone via its Bluetooth interface. The mobile phone Smartphone Enterprise Application Integration WHITE PAPER MARCH 2011 Smartphone Enterprise Application Integration Rhomobile - Mobilize Your Enterprise Overview For more information on optimal smartphone development please see the Rhomobile White Common Facebook issues Common Facebook issues and how to resolve them Introduction Love it or loathe it, with over 28 million users in the UK alone, Facebook cannot be ignored. It is the social network of choice for many young INTERNATIONAL JOURNAL OF ADVANCES IN COMPUTING AND INFORMATION TECHNOLOGY An International online open access peer reviewed journal INTERNATIONAL JOURNAL OF ADVANCES IN COMPUTING AND INFORMATION TECHNOLOGY An International online open access peer reviewed journal Research Article ISSN 2277 9140 Virtual conferencing using Artificial CHAPTER 2: USING THE CAMERA WITH THE APP TABLE OF CONTENTS OVERVIEW... 1 Front of your camera... 1 Back of your camera... 2 ACCESSORIES... 3 CHAPTER 1: Navigating the Mobile Application... 4 Device List: How to Use this Page... 4 My Messages: Slide 1. Slide 2. Agenda Slide 1 Slide 2 Agenda American Messaging introduction IntelliMessage Mobile Application Registration and Welcome email Download the app Login, Password and PIN Settings and Screen Orientation Status Sending Big Data Analytics for United Security Big Data Analytics for United Security What Advantages Does an Agile Network Bring? (Issue 2) By Swift Liu, President Enterprise Networking Product Line Huawei Enterprise Business Group Agile means quick Mobile Banking Applications Premier Members Mobile User Guide Mobile Banking Applications Premier Members Mobile User Guide 1.0 P REMIER MEMBERS MOBILE BASICS Mobile Banking allows the user to access their account information via mobile smartphone or tablet either DETERMINATION OF THE PERFORMANCE DETERMINATION OF THE PERFORMANCE OF ANDROID ANTI-MALWARE SCANNERS AV-TEST GmbH Klewitzstr. 7 39112 Magdeburg Germany 1 CONTENT Determination of the Performance of Android Anti-Malware Scanners... Mobile App Testing Guide. Basics of Mobile App Testing 2015 Mobile App Testing Guide Basics of Mobile App Testing Introduction Technology is on peek, where each and every day we set a new benchmark. Those days are gone when computers were just a machine and BreezingForms Guide. 18 Forms: BreezingForms BreezingForms 8/3/2009 1 BreezingForms Guide GOOGLE TRANSLATE FROM: a_18_formulare_neu_001.htm#t2t32 18.1 BreezingForms 18.1.1 Installation and configuration Nipper Studio Beginner s Guide Nipper Studio Beginner s Guide Multiple Award Winning Security Software Version 2.1 Published March 2015 Titania Limited 2014. All Rights Reserved This document is intended to provide advice and assistance SNMP Test er Manual 2015 Paessler AG SNMP Test er Manual 2015 Paessler AG All rights reserved. No parts of this work may be reproduced in any form or by any means graphic, electronic, or mechanical, including photocopying, recording, taping, Understanding Margins Understanding Margins Frequently asked questions on margins as applicable for transactions on Cash and Derivatives segments of NSE and BSE Jointly published by National Stock Exchange of India Limited GPS Tracking Implementation Kit GPS Tracking Implementation Kit 1 2 Table of contents Best Practice Implementation... 3 Frequently Asked Questions... 4 How to tell your staff... 7 3 Best Practice Implementation Firstly, the matter has Spreadsheet Programming: Spreadsheet Programming: The New Paradigm in Rapid Application Development Contact: Info@KnowledgeDynamics.com Spreadsheet Programming: The New Paradigm in Rapid Application Development 7 Questions to Ask Video Conferencing Providers 7 Questions to Ask Video Conferencing Providers CONTENTS Introduction...3 1. How many people can participate in your video conferences?...3 2. What kind of endpoints does the solution support or require?.. Securing your Online Data Transfer with SSL Securing your Online Data Transfer with SSL A GUIDE TO UNDERSTANDING SSL CERTIFICATES, how they operate and their application 1. Overview 2. What is SSL? 3. How to tell if a Website is Secure 4. What does WAIT-TIME ANALYSIS METHOD: NEW BEST PRACTICE FOR APPLICATION PERFORMANCE MANAGEMENT WAIT-TIME ANALYSIS METHOD: NEW BEST PRACTICE FOR APPLICATION PERFORMANCE MANAGEMENT INTRODUCTION TO WAIT-TIME METHODS Until very recently, tuning of IT application performance has been largely a guessing Milestone Federated Architecture TM Milestone Systems White Paper Milestone Federated Architecture TM Prepared by: John Rasmussen, Product Manager, Milestone XProtect Corporate Milestone Systems 30 November 2010 Page 1 of 15 Table of Contents) Step Following statistics will show you the importance of mobile applications in this smart era, There is no second thought about the exponential increase in importance and usage of mobile applications. Simultaneously better user experience will remain most important factor to Storing Encrypted Plain Text Files Using Google Android Storing Encrypted Plain Text Files Using Google Android Abstract Jared Hatfield University of Louisville Google Android is an open source operating system that is available on a wide variety of smart phones Future Cloud Services: Ricoh s Perspective White Paper Future Cloud Services: Ricoh s Perspective Under current unstable business conditions, where to provide management resources is important to a company s future. In such an environment, cloud Cacti-ReportItv0.6.1. A small introduction to the use of ReportIt Cacti-ReportItv0.6.1 A small introduction to the use of ReportIt Copyright (c) 2009 Andreas Braun Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation 1.5.3 Project 3: Traffic Monitoring 1.5.3 Project 3: Traffic Monitoring This project aims to provide helpful information about traffic in a given geographic area based on the history of traffic patterns, current weather, and time of the Workflow Templates Library Workflow s Library Table of Contents Intro... 2 Active Directory... 3 Application... 5 Cisco... 7 Database... 8 Excel Automation... 9 Files and Folders... 10 FTP Tasks... 13 Incident Management... 14 Android App User Guide Android App User Guide ZENworks Mobile Management 2.7.x August 2013 Legal Notices Novell, Inc., makes no representations or warranties with respect to the contents or use of Is Privacy A Cloud Illusion? Five Hidden Facts You Need to Know Is Privacy A Cloud Illusion? Five Hidden Facts You Need to Know 2014 StoAmigo. The information contained within these marketing materials is strictly for illustrative purposes, and the figures herein are Risk Analysis Overview What Is Risk? Uncertainty about a situation can often indicate risk, which is the possibility of loss, damage, or any other undesirable event. Most people desire low risk, which would translate to a high Princeton University Computer Science COS 432: Information Security (Fall 2013) Princeton University Computer Science COS 432: Information Security (Fall 2013) This test has 13 questions worth a total of 50 points. That s a lot of questions. Work through the ones you re Introduction to Computer Networks and Data Communications Introduction to Computer Networks and Data Communications Chapter 1 Learning Objectives After reading this chapter, you should be able to: Define the basic terminology of computer networks Recognize the Autos Limited Ghana Vehicle Tracking Business Proposal Autos Limited Ghana Vehicle Tracking Business Proposal Executive Summary Our Understanding of Your Goals We understand that you or your business needs to monitor all your vehicles or company's to minimize IoT Security Platform IoT Security Platform 2 Introduction Wars begin when the costs of attack are low, the benefits for a victor are high, and there is an inability to enforce law. The same is true in cyberwars. Today there, It is clear the postal mail is still very relevant in today's marketing environment. Email and Mobile Digital channels have many strengths, but they also have weaknesses. For example, many companies routinely send out emails as a part of their marketing campaigns. But people receive hundreds Authentication Part 4: Issues and Implications. People and Security Lecture 8 Authentication Part 4: Issues and Implications People and Security Lecture 8 The great authentication fatigue (1) 23 knowledge workers asked to keep a diary of all their authentication events for 24 hours F-SECURE SECURITY CLOUD Purpose, function and benefits F-SECURE SECURITY CLOUD Purpose, function and benefits October 2015 CONTENTS F-Secure Security Cloud in brief 2 Security Cloud benefits 3 How does Security Cloud work? 4 Security Cloud metrics 4 Security CareSentinel Set Up Guide for Android Devices CareSentinel Set Up Guide for Android Devices Compatible Devices: Only devices running Android 4.3 or newer support Bluetooth Smart. Any smart phone or tablet running an Android operating system older Deposit Identification Utility and Visualization Tool Deposit Identification Utility and Visualization Tool Colorado School of Mines Field Session Summer 2014 David Alexander Jeremy Kerr Luke McPherson Introduction Newmont Mining Corporation was founded in. Cable Access Q&A - Part One Cable Access Q&A - Part One Accessing the Internet using a Cable Network (and a cable modem) is becoming increasingly more popular due to the much greater speed than is available through telephone-modem Data Storage on Mobile Devices Introduction to Computer Security Final Project Data Storage on Mobile Devices Introduction to Computer Security Final Project Katina Russell Tufts University, Fall 2014 Abstract While people come up with ideas about a mobile application Remote control circuitry via mobile phones and SMS Remote control circuitry via mobile phones and SMS Gunther Zielosko 1. Introduction In application note No. 56 ( BASIC-Tiger sends text messages, in which we described a BASIC-Tiger sending text messages. Control4 Smart Home Safety and Security Guide Control4 Smart Home Safety and Security Guide Contents Safety and security overview 2 Using the Security menu 3 Accessing the Security menu 3 Arming your system 3 Disarming your system 4 Sending an emergency SuperValu Car Insurance FAQs SuperValu Car Insurance FAQs 1. What discounts are available? As well as offering you low cost car insurance from only 285*, we ll also give you a 10% discount for being a SuperValu Real Rewards customer,
http://docplayer.net/1857620-Deutsche-kurzbeschreibung.html
CC-MAIN-2017-04
refinedweb
17,074
50.46
sc_StateInText man page sc::StateInText — Reads state information written with StateOutText. Synopsis #include <state_text.h> Inherits sc::StateInFile. Public Member Functions StateInText (std::istream &s) StateInText (const char *) StateInText (const Ref< KeyVal > &) int getstring (char *&) This restores strings saved with StateOut::putstring. int get_array_char (char *, int) These restore data saved with StateOut's put. int get_array_uint (unsigned int *, int) int get_array_int (int *, int) int get_array_float (float *, int) int get_array_double (double *, int) int get (const ClassDesc **) This restores ClassDesc's. int get (char &r, const char *key=0) These restore data saved with StateOut's put. members. int get (unsigned int &r, const char *key=0) int get (int &r, const char *key=0) int get (float &r, const char *key=0) int get (double &r, const char *key=0) int get (char *&) These restore data saved with StateOut's put. int get (unsigned int *&) int get (int *&) int get (float *&) int get (double *&) Protected Member Functions void no_newline () void no_array () int read (char *) int read (unsigned int &) int read (int &) int read (float &) int read (double &) void newline () void start_array () void end_array () int getobject (Ref< SavableState > &) This is used to restore an object. void abort () Protected Attributes int newlines_ int no_newline_ int no_array_ Detailed Description Reads state information written with StateOutText. Member Function Documentation int sc::StateInText::get (const ClassDesc **) [virtual] This restores ClassDesc's. It will set the pointer to the address of the static ClassDesc for the class which has the same name as the class that had the ClassDesc that was saved by put(const ClassDesc*). Reimplemented from sc::StateIn. int sc::StateInText::get (char *&) [virtual] These restore data saved with StateOut's put. members. The data is allocated by StateIn. Reimplemented from sc::StateIn. int sc::StateInText::get_array_char (char * p, int size) [virtual] These restore data saved with StateOut's put. members. The data must be preallocated by the user. Reimplemented from sc::StateIn. int sc::StateInText::getobject (Ref< SavableState > &) [protected], [virtual] This is used to restore an object. It is called with the reference to the reference being restored. If the data being restored has previously been restored, then the pointer being restored is set to a reference to the previously restored object. Reimplemented from sc::StateIn. Author Generated automatically by Doxygen for MPQC from the source code.
https://www.mankier.com/3/sc_StateInText
CC-MAIN-2017-43
refinedweb
383
56.55
In this project we will use an existing FM radio which went repair a long time ago, to convert it into a Smart Wireless FM Radio controlled using Phone, with the help of Arduino and Processing. We can convert any manually operated electronic device into a Smart Device using the same procedure. Every electronic device operates with the help of signals. These signals might be in terms of voltages or currents. The signals can either be triggered manually with the help of user interaction directly or with the help of a wireless device. By the end of this project we will be able to convert most of our common electronic devices, like a Radio which works on buttons, into a Smart Wireless Gadget which can be controlled by Smart phone over Bluetooth. To achieve this we will have to do two main things. 1. Predict how the signals are generated in the existing mechanical button system. 2. Find out a way to trigger the same signal with help of a small add-on circuit. So, Let's get started... Components Required: For this project an old or unused electronic device like a radio, TV, CD player, or Home theatre can be selected. The actual components might vary based on the device you select. But to make it wireless we would need a microcontroller which is an Arduino here and a wireless medium which is a HC-05 Bluetooth module. Reverse Engineering: Okay, so now I have selected an old FM radio player which stopped working a long time ago. And when I opened it I found that the buttons on it have stopped working. This will be a perfect device for us to work because we won't need the buttons anymore as we are going to make it wireless completely. The below picture shows the Radio which I opened. This was the button setup of my radio (above picture). As you can see there are eight buttons from which the radio takes input. You can also notice that there are eight resistors on the board. What can you conclude from this…? Yes each resister is connected to a switch. Now let's take a look on the back side of the board: You can trace out the connection with the help of the PCB tracks, but if you are still confused you can use your millimetre in connectivity more and figure out the circuit. This board has three terminals (circled in red) which gives signals to the main FM radio board. These pins were marked as S1, S2, and 1.7V. This means that constant voltage of 1.7 Volts is sent form the main board to this board and as the user presses any button, there will be a voltage drop across the corresponding resistor and through the pins S1 and S2 a variable voltage will be sent back. This is how most of the buttons in our electronic devices work. Now since we have figured out how it worked, let’s make it wireless. Working Explanation: So now to make it wireless we just have to give a voltage between 0 - 1.7V across the S1 and ground out the main board. There are few ways, using which you can mimic these button setup using a microcontroller. We can use a Digital potentiometer and make it provide the resistance on the board as programmed and when required. But this will make things complicated and costly as working with Digipot requires SPI and Digipots are costly. We can also use a transistor resistor network in which each resistor of different values are activated by a transistor which in turn is controlled by the microcontroller itself. But again to do this for eight buttons the circuit will get complicated. The simple way of doing this is to directly generate the required variable voltage from the microcontroller and feed it to the signal pins. Sadly, Arduino only has ADC and doesn't have a DAC. But, luckily we have PWM in Arduino. This PWM can be made to act as a variable voltage with the help of a simple RC Low Pass Filter. A low pass filter is shown above, the key component here is the capacitor which will ground the entire pulsating signal and a pure DC is sent as output. So the PWM signals from the Arduino have to be sent through a low pass filter and then given to the signal board of the FM radio. The circuit is easy to build on a dot board as shown above. Here the Black wire is for ground and the Blue and Green wires on the left will be sent to our FM boards S1(Green) and S2(blue), and the wires to the right will receive PWM signals from Arduino’s Pin 9 & 10 (see picture above) and pass to the FM board via a Low pass filter. The Bluetooth module uses pins 11 and 12 as Rx and TX. Now we can generate PWM signals from 0 volt to 1.7 volt and find out how our Radio behaves for different voltage levels. The next step is to make this thing wireless. Circuit Connections: This schematic shows the entire setup of Low Pass Filter and HC-05 Bluetooth Module connected to Arduino Mega for Bluetooth Controlled FM Radio. Arduino Program: Program for the Arduino is given in the Code section below. You can also test the Variable Voltage range for your electronic device by using this program here. Before we start with building our own Android App for our Radio it is advisable to test the wireless feature with help of a Terminal Bluetooth Monitor App as shown in Video below. Check this Article to configuring Bluetooth Terminal App on Arduino. Once we are confident with its working, we can jump into making our own Android app. Using Processing to Make Android App: It is cool to make our device wireless, but we can also add some personal touch to our device by creating our own Android app. We can control the device on automatic scheduled times or control it based on your wake up alarms. You can even make your radio play your favourite channel when you get home. Imagination is your limit here. But for now we will create a simple user interface using processing, this app will only have few buttons using which you can control your FM radio. Processing is open source software which is used by artists for Graphics designing. This software is used to develop software and Android applications. The Processing Code for the Android App to control this Wireless FM Radio is given here: First we built this app on PC in JAVA mode, to test it properly, here is the Processing Code for the same. Right click on it and click on ‘Save link as..’ to download the code file. Then open the file in 'Processing' software and click on ‘Run’ button to check how it will look in the Phone. You need to install 'Processing' software to open *.pde files. Once we have tested out App in JAVA mode we can easily convert it into Android Mode by changing to Android tab on the top right corner of the Processing window. In order to make our Android Phone turn on its Bluetooth and connect to our HC-05 module automatically, we need to add the following codes to our existing Java program to make it an Android App. We have already provided the full Android Code in above link, so you can directly use it. Below are some Header files to enable Bluetooth functions: import android.content.Intent; import android.os.Bundle; import ketai.net.bluetooth.*; import ketai.ui.*; import ketai.net.*; import android.bluetooth.BluetoothAdapter; import android.view.KeyEvent; Below lines communicates with our phones Bluetooth adapter using Ketai library and we name our adapter as bt. BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter(); KetaiBluetooth bt; Below part of the code will trigger a request to the user asking them to Turn on the Bluetooth on app start up. //To start BT on start********* void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); bt = new KetaiBluetooth(this); } void onActivityResult(int requestCode, int resultCode, Intent data) { bt.onActivityResult(requestCode, resultCode, data); } //********** Here we instruct our Android App to which Bluetooth device we have to get connected with. The line bt.connectToDeviceByName(selection); expect a device name from our setup function. Since our Bluetooth device is named as 'HC-05’, below line is added in the setup. This name will differ based on your Bluetooth modules name. //To select bluetooth device********** void onKetaiListSelection(KetaiList klist) { String selection = klist.getSelection(); bt.connectToDeviceByName(selection); //dispose of list for now klist = null; } //********** bt.connectToDeviceByName("HC-05"); Either you can do these changes in Processing Code for PC (Java mode) or can directly use our Android Processing code given in above link. Then directly connect your phone to your laptop using the data cable and enable USB debugging on your phone. Now click on the Play button on the processing window in PC, the application will be directly installed on your Android Phone and will be launched automatically. It’s that easy, so go ahead and try it out. The below picture represents our Android Application UI along with its coding window. Check out the Video to understand and run the Code in Android Phone as well as in computer. That’s it we have turned our old FM radio into a wireless modern gadget that can be controlled by our Android Application. I hope this will help people to get to work but if you need any guidance as always you can use the comment section and we will be glad to help you. int outvalue =0;; const int GPWM = 9; const int BPWM = 10; int invalue; #include <SoftwareSerial.h>// import the serial library SoftwareSerial Genotronex(11, 12); // TX, RX int BluetoothData; // the data given from Computer void setup() { Serial.begin(57600); Genotronex.begin(9600); Serial.println("Enter Value to write (60-195)"); TCCR2B = (TCCR2B & 0xF8) | 0x01;// timer frequency is 4khz } void loop() { if (Genotronex.available()) { BluetoothData=Genotronex.read(); invalue= BluetoothData; if (invalue == 'u') { Serial.println("Volume up"); outvalue= 45; GreenDigibutton(); } if (invalue == 'd') { Serial.println("Volume down"); outvalue= 35; GreenDigibutton(); } if (invalue == 'm') { Serial.println("Mode change"); outvalue= 65; GreenDigibutton(); } if (invalue == 's') { Serial.println("Stop"); outvalue= 75; GreenDigibutton(); } if (invalue == 'p') { Serial.println("Prev. Channel"); outvalue= 35; BlueDigibutton(); } if (invalue == 'n') { Serial.println("Next Channel"); outvalue= 45; BlueDigibutton(); } } } void GreenDigibutton() { analogWrite(GPWM, outvalue); delay(200); analogWrite(GPWM, 0); delay(200); Serial.println("DONE"); } void BlueDigibutton() { analogWrite(BPWM, outvalue); delay(200); analogWrite(BPWM, 0); delay(200); Serial.println("DONE"); } the project is good Thanks Dinesh. Let us konw if you need something. Please sir, I am clement, a Nigerian. I want to start working with the 8051 Micro Controller but I dont know the way to go Please I need your help. Please email me at taryosky@gmail.com Please sir, I am clement, a Nigerian. I want to start working with the 8051 Micro Controller but I dont know the way to go Please I need your help. Hi Clement. We are glad to help you out. It would have been easy for us to guide you if you have mentioned your educational background. Assuming you are a newbie, the following things can be followed to get started with Micro controllers (8051). 1. Get a decent book that teaches you programming and Microcontroller concepts 2. A decent development board to try out your programs in hardware 3. A computer with internet access. First read this fat book called 8051 microcontroller by Majidi. It will give you everything you need. Your concepts about microcontroller will be cleared and you will know how things work and what is coding. Then grab that datasheet.Understand the particulars of the 8051. Admire its beauty. Read through the terms. If you don't understand the terms, surf the meaning on internet. Understand and admire their meanings. Read about their applications. Now its time for buying a development board for a start. You might fail or get stuck in lot of places. But not to worry, you can use our Forums and we will be there to help you out. Limitation of 8051 is lack of ADC which one has to interface and it takes time. (There are versions of 8051 with ADC, one is from Silicon Labs). For advance work you can move to Arduino which has everything especially analogous read. And yes AVR is inside arduino. HAPPY LEARNING!!! Interesting piece of work done. Wish you success in the following work. Ensure that proper wiring is done to avoid any mishap. Hi McDonald, Thanks, I will concentrate on the wiring. Your comments encourages me I think I'll learn more with you all! Sure Joseph, we are all learning to gather here........ Hi Aswinth Raj, Nice to see the interesting project you have presented. I have an idea to do a project regarding automatic emergency light. Bellow given description about project. Fit and Forget LED Backup Light Features: LED backup light should switch on only at dark when there is powercut. The battery of the backup light should stop charging automatically when it reaches the full charge and starts charging automatically when the battery is about to be over. Battery level Bargraph LED indicator should present. The brightness of the LED backup light should be controlled using two switches by PWM technique. Hi shiyam! Yes the project you mentioned can be very well done. If I were you I would use the following 1. A high power LED light 10W maybe 2. 18650 Lithium cell 3.TP4056 Lithium battery Module to charge and discharge the batteries in a safe way (This module will also indicate if the battery is charging and cuts of supply when fully charged) 4. An Arduino Mini to read the battery voltage and generate PWM signals 5. An ordinary LCD or segment battery indicator to indicate the battery level. 6. A potential divider arrangement to read the battery voltage. 7.A switch to toggle the brightness mode of the LED 8. A LDR sensor to detect if the surrounding is dark 9. An ordinary USB cable and AC-DC converter module (700mA - Switching converter) to charge the TP4056 Module. 10. Another potential divider setup to check if the 220V AC is active. So that we can know if there is a power failure I hope you got my Idea.. Also visit the following projects which might help you with your project 1.... 2.... ALL THE BEST, you can use the forum if you have any doubts. Thanks!!
https://circuitdigest.com/microcontroller-projects/smart-phone-controlled-fm-radio-using-arduino-and-processing
CC-MAIN-2018-17
refinedweb
2,451
65.12
C# Array C# array is a kind of variable that stores a list of addresses of variables and can store a set of data having the same data type. Declaring multiple variables with the same type and used for the same purpose can be exhausting. What if you want to store a thousand values with integers and they will be used, for example, a list of grades of students. It would be tedious to declare all of those one thousand variables. But with C# Array, you can declare them in one line. Below shows you the simplest way to declare a C# Array. datatype[] arrayName = new datatype[length]; The datatype is the type of variable that the array will store. The square brackets next to the data type tell that it is a C# Array. The arrayName is the identifier or the name of the variable. When naming a C# Array, it is a good practice to make it plural to indicate that it is a C# Array. For example, use numbers instead of number when naming a C# Array. The length tells the compiler how many data or values you are going to store in an array. We used the new keyword to allocate enough spaces for the C# Array in the memory depending on the value specified by the length. Each item in an array is called an array element. If we are to declare an array that can store 5 values of type integer, we would write: int[] numbers = new int[5]; This declaration reserves 5 addresses inside your computer’s memory waiting for a value to be stored. So how can we store values to each of the array elements? Array’s value can be accessed and modified by indicating their index or position. numbers[0] = 1; numbers[1] = 2; numbers[2] = 3; numbers[3] = 4; numbers[4] = 5; Index starts with 0 and ends with (length – 1) of the array. For example, we have 5 elements so the indices of our C# Array start from 0 and ends with 4 because length – 1 equates to 5 – 1 which is 4. That means that index 0 is the first element, index 1 is the second element and so on. Look at the image below to better understand this concept. Consider each square is an array element and the values inside them are the values they contain. Newbie programmers often get confused by the index resulting to errors such as starting the count from 1 to 5. If you access an array element with an index that’s not inside the range of valid indexes, then you will get an IndexOutOfRangeException which simply says that you are accessing an address that does not exist. Just remember the formula and you won’t have any problems. If you want to assign values immediately in the declaration of a variable, you can do a modified version of the declaration of an array. datatype[] arrayName = new datatype[length] { val1, val2, ... valN }; You can enumerate the values inside curly braces immediately after the declaration of the size of the array. You should separate the values with commas. The number of values inside the curly braces should exactly match the size of the array declared. Let’s look at an example. int[] numbers = new int[5] { 1, 2, 3, 4, 5 }; This will have the same results as the code in Figure 1 but it save us a lot of lines of code. You can still change the values of any element by accessing its index and assigning a new value. Our numbers C# Array requires 5 elements so we supplied it with 5 values. If we are to supply less or more than it requires, we will encounter an error. There is another way of declaring an array. You can supply an array with any number of values as long as you do not indicate the size. Here’s an example: int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; We are now giving 10 values to the C# Array. Notice that there’s no length indicated for the array. If this is the case, the compiler will count the number of values inside the curly braces and that will determine the length of the array. Note that if you do not give a length for the array, you need to supply values for it. If not, you will receive an error. int[] numbers = new int[]; //not allowed There is a shorter version for doing this: int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; We simply assign the values inside curly braces without using the new keyword and the data type. This will also assign all of the 10 values into the array and automatically counts the length that the array should have. Accessing C# Array Values Using for Loop The following is an example of using arrays. Our program will retrieve 5 values from the user and then calculate the average of those numbers. using System; namespace ArraysDemo { public class Program { public static void Main() { int[] numbersone = new int[5]; int total = 0; double average; for (int i = 0; i < numbersone.Length; i++) { Console.Write("Enter a number: "); numbers[i] = Convert.ToInt32(Console.ReadLine()); } for (int i = 0; i < numbersone.Length; i++) { total += numbersone[i]; } average = total / (double)numbersone.Length; Console.WriteLine("Average = {0}", average); } } } Example 1 – Using C# Array Enter a number: 90 Enter a number: 85 Enter a number: 80 Enter a number: 87 Enter a number: 92 Average = 86 Line 9 declares an array that can hold 5 integer values. Lines 10 and 11 declares variables that will be used on calculating the average. Note that total is initialized to 0 to avoid errors when adding values to it. Lines 13-17 uses a for loop that will repeat on getting input from the user. We used the Length property of the array to determine the number of elements it contains. Although we can simply specify the value 5 in the condition, using the Length property is more versatile as we can change the length of the array and the condition in the for loop will adjust to the new change. Line 16 retrieves input from the user, converts it to int, and stores it on an array element. The index uses the current value of i. For example, at the beginning of the loop, i is initialized to 0, so when Line 16 is first encountered, it will add the value retrieve by the user to numbers[0]. After the loop, i is incremented by 1, and one Line 16 is reached again, it will now assign the retrieved value to numbers[1]. It will continue as long as the for loop meets the condition. Lines 19-22 uses another for loop to access each value of the numbers array. We used the same technique of using the counter variable as the index. Each element of the numbers is added to the variable total. After the end of the loop, we can now calculate the average (line 24). We divide the value of total by the number of elements of the numbers array. To access the number of elements of numbers, we used again the Length property of the array. Note that we converted the value of the Length property to double so the expression will yield a double result which includes the fractional part of the result. If we don’t convert any of the operands of the division, then it will yield an integer result which does not include the fractional or decimal part of the result. Line 26 displays the calculated average. Array’s length cannot be changed once it was initialized. For example, if you initialize an array to contain only 5 elements, then you cannot resize the array to contain, for example, 10 elements. A special set of classes acts the same as the array but is capable of resizing the number of elements they can contain. Arrays are very useful in many situations and it is important that you master this concept and how they can be used.
https://compitionpoint.com/c-array/
CC-MAIN-2021-31
refinedweb
1,367
61.97
AnyEvent::XMPP::Parser - Parser for XML streams (helper for AnyEvent::XMPP) use AnyEvent::XMPP::Parser; ... This is a XMPP XML parser helper class, which helps me to cope with the XMPP XML. See also AnyEvent::XMPP::Writer for a discussion of the issues with XML in XMPP. This creates a new AnyEvent::XMPP::Parser and calls init. Sets the 'XML stanza' callback. $cb must be a code reference. The first argument to the callback will be this AnyEvent::XMPP::Parser instance and the second will be the stanzas root AnyEvent::XMPP::Node as first argument. If the second argument is undefined the end of the stream has been found. This sets the error callback that will be called when the parser encounters an syntax error. The first argument is the exception and the second is the data which caused the error. This method sets the stream tag callback. It is called when the <stream> tag from the server has been encountered. The first argument to the callback is the AnyEvent::XMPP::Node of the opening stream tag. This methods (re)initializes the parser. This methods removes all handlers. Use it to avoid circular references. This method checks whether the $cmptag matches the $tagname in the $namespace. $cmptag needs to come from the XML::Parser::Expat as it has some magic attached that stores the namespace. This method feeds a chunk of unparsed data to the parser. Robin Redeker, <elmex at ta-sa.org>, JID: <elmex at jabber.org> This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
http://search.cpan.org/~mstplbg/AnyEvent-XMPP/lib/AnyEvent/XMPP/Parser.pm
CC-MAIN-2016-44
refinedweb
268
77.03
Good evening everyone, I have posted my code below but am unable to determine what is causing a persistent “Dynamic constant assignment” error at “Console_Screen = Screen.new” and “SQ = Quiz.new” on line 144 and 146. Any help or insight at all would be great. I’ve had this issue before and it was fixed with “end”. I went through and to me it seems like all of the end statements are in the appropriate place. class Screen def cls puts ("\n" * 25) puts “\a” end def pause #Pauses the display until the player presses the enter key STDIN.gets end class Quiz def display_greeting Console_Screen.cls #Clears display print “\t\t Welcome to the SUperman Movie Trivia Quiz!” + “\n\n\n\n\n\n\n\n\n\nPress Enter to” + “continue.” Console_Screen.pause #Pauses the game end def display_instructions #Method to present quiz instructions Console_Screen.cls puts "INSTRUCTIONS:\n\n" #Displays a heading puts "You will be presented with a series of" + "multiple-choice" puts "questions. To answer a question, type in" + "the letter of" puts " the corresponding answer and press the" + "Enter Key. Your" puts "grade will be displayed at the end of the" + "test\n\n\n" puts "Good luck!\n\n\n\n\n\n\n" print "Press Enter to continue." Console_Screen.pause #Pause the game end def disp_q(question, q_A, q_B, q_C, q_D, answer) #loop until a valid answer is input loop do Console_Screen.cls #formats the display of the questions puts question + "\n\n" puts q_A puts q_B puts q_C puts q_D print "\nType the letter representing your answer:" reply = STDIN.gets #collect the answer reply.chop! #Analyze the input if answer == reply then $noRight += 1 end if reply == "a" or reply == "b" or reply =="c" or reply == "d" then break end end #Method for grading the quiz def determine_grade Console_Screen.cls #To pass they must answer 3 questions correctly if $noRight >= 3 then print "You correctly answered " + $noRight.to_s + " question(s)." puts "You have passed the \nSuperman Movie Trivia" + "Quiz!\n\n" puts "You have earned a rank of: Good Citizen" if $noRight == 3 puts "You have earned a rank of: Side Kick" if $noRight == 4 puts "You have earned the rank of: SuperHero" if $noRight == 5 print "\n\nPress Enter to continue." else #they failed print "You missed" + (5 - $noRight).to_s + "questions." puts "You have failed the Superman Movie Trivia Quiz." puts "Perhaps you should watch the movies again before returning to" puts "retake the quiz" print "\n\nPress Enter to continue" end Console_Screen.pause def display_credits Console_Screen.cls puts"\t\tThank you for taking the SUPERMAN MOVIE TRIVIA QUIZ!\n\n\n\n" puts "\n\t\t\t Developed by Glenn B Chamberlain\n\n" puts "\t\t\t\t Copyright 2017\n\n" puts "\t\t\tURL:\n\n\n\n" end #Main Script Logic---------------------------------------------------------------- #Keep track of the number of correct answers $noRight = 0 #Where the problem is shown when I try to run the code------------- Console_Screen = Screen.new SQ = Quiz.new #---------------------------------------------------------------- #Execute the display_greeting method SQ.display_greeting answer = "" #loop until the play enters y or n only loop do Console_Screen.cls print "Are you ready to take the quiz? (y/n): " answer = STDIN.gets answer.chop! break if answer == "y" || answer == "n" #analyze the players input if answer == "n" Console_Screen.cls puts "Okay, perhaps another time.\n\n" else SQ.display_instructions #executes the display_instructions method #execute the disp_q method and pass it arguments (questions, answers and correct answers) SQ.disp_q("What is the name of the Daily Planet's ace" + "photographer?", "a. Jimmy Olsen", "b. Clark Kent", + "c. Lex Luthor", "d. Lois Lane", "a") #Call upon the disp_q method and pass it the second questions SQ.disp_q("What is the name of Clark Kents home town?", "a. Metropolis", "b. Gotham City", "c.Smallville", "d. New York", "c") SQ.disp_q("In which movie did Superman battle" + "General Zod?", "a. Super", "b. Superman II", "c. Superman III", "d. Superman IV", "b") SQ.disp_q("What is the name of Superman's father?", "a. Nimo","b. Jarrell", "c. Lex Luthor", “d.Krypton”,“b”) SQ.disp_q("Where had Superman been at the start of " "Superman Returns?", "a. Moon", "b. Fortress of Solitude", "c. Earth's Core", "d. Krypton", "d") #call up the determine_grade method to display the grade SQ.determine_grade SQ.display_credits end
https://www.ruby-forum.com/t/dynamic-constant-assignment/245267
CC-MAIN-2018-43
refinedweb
720
68.47
Eric Brunson wrote: > However, I didn't actually answer your question. > > As Kent has already mentioned, eval is quite dangerous in python and to > be avoided when possible. I think it would be safer to do something > like this: > > l = locals() > for x, y in zip( varlist, data ): > l[x] = y > > or, more tersely: > > [ locals()[x] = y for x, y in zip( varlist, data ) ] > > > This will accomplish what you're trying to do, but a dict really gives > you greater functionality than assigning to local variables. This will only work at global scope where locals() is globals() and writable. In function scope assigning to locals()[...] does not change the local namespace: In [27]: def foo(): ....: locals()['x'] = 1 ....: print x ....: ....: In [28]: foo() ------------------------------------------------------------ Traceback (most recent call last): File "<ipython console>", line 1, in <module> File "<ipython console>", line 3, in foo <type 'exceptions.NameError'>: global name 'x' is not defined Kent
https://mail.python.org/pipermail/tutor/2007-October/057752.html
CC-MAIN-2018-05
refinedweb
152
69.82
19 March 2009 09:41 [Source: ICIS news] SINGAPORE (ICIS news)--India's Reliance Industries expects to restart its 150,000 tonne/year high-density polyethylene (HDPE) plant in Gandhar on Friday after a five-day outage, a source close to the company said on Thursday. "The unscheduled shutdown was caused by mechanical problems which are being resolved," the source said. It would result in a production loss of around 2,500 tonnes of PE, he added. "Although it's a small plant, the shutdown has unleashed supply concerns in the Indian market," said a trader. This is the second time the plant in the Indian state of ?xml:namespace> Reliance officials were not available for
http://www.icis.com/Articles/2009/03/19/9201466/reliance-to-restart-gandhar-hdpe-on-friday-after-repairs.html
CC-MAIN-2013-48
refinedweb
116
61.97
@dusty_nv I am trying to build the pytorch on jetson nano.when I try to download the wget link (wget -O torch-1.1.0a0+b457266-cp36-cp36m-linux_aarch64.whl) you have posted, but it occurs connection refused. could you share a google drive link or other available link. thank you. PyTorch for Jetson - version 1.6.0 now available @dusty_nv Hi Perry, what happens if you try (without HTTPS)? If that doesn’t work either, I will put it on Google Drive for you. thank you for quick reply @dusty_nv. this link is still unable to resolve. please put it on Google Drive, thx! I have a faster-rcnn.pytorch model. The repository address for this project is:. I want to port this model to jetson nano. Is there a tutorial for reference? . The jetson I bought has already installed python 3.6 and JetPack 4.2, so I didn’t build any wheels according to “Build Instructions”. I downloaded the swap partition just by following “Build Instructions”. I downloaded the “torch-1.1.0a0+b457266-cp36-cp36m-linux_aarch64.whl” offline, and then used “pip3 install .whl” to install pytorch1.1. I also used the following command to the torchvision: git clone cd vision $ sudo python setup.py install But when I install scipy with “pip3 install scipy” it always fails. Any help will be greatly appreciated. zcy@zcy-desktop:~/0_projects/faster-rcnn.pytorch$ pip install Cython Collecting Cython Downloading (2.0MB) 100% |████████████████████████████████| 2.0MB 45kB/s Building wheels for collected packages: Cython Building wheel for Cython (setup.py) ... done Stored in directory: /home/zcy/.cache/pip/wheels/79/b9/15/c589b51f4e91b37faa76362180166a2041e4286c38dbc45fc6 Successfully built Cython Installing collected packages: Cython Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/usr/local/lib/python3.6/dist-packages/cython.py' Consider using the `--user` option or check the permissions. Hi zcy, did you try installing this package with the --user flag to pip? And if that doesn’t work, by running pip with sudo permissions? @zcy I’m having trouble installing scipy as well. Here is a thread about it . thanks, it`s work. By the way, is there an example of porting the pytorch model to jetson nano ? Hi dusty, could you post the checksum for the wheel file ()? I download it multiple times and it’s still broken. (Got zipfile.BadZipFile: File is not a zip file error message). Connecting failed when downloading wheel for Python2.7. wget -O torch-1.1.0a0+b457266-cp27-cp27mu-linux_aarch64.whl Then it shows, Connecting to nvidia.app.box.com (nvidia.app.box.com)|243.185.187.39|:443... failed:Operation timed out I’ve tried to ping the IP address and always timed out. Anyone with the same problem? thx. The box.com is blocked by GFW. (box.com被墙了) For those from China (a.k.a behind the GFW), You may download the wheel from my shared link: Baidu NetDriver Link: Code : ribc MD5 (torch-1.1.0a0+b457266-cp36-cp36m-linux_aarch64.whl) = a08c545c05651e6a9651010c13f3151f Sorry I didn’t download python2 wheel. I prefer to use python3. Please email me if you insist to use python2 and can’t find a VPN to download the wheel from box.com Hi fengbo, here are the SHA256 and MD5 checksums for this file: SHA256: 0e998c886be9d5e4f4d721053330d7da478baa1648e52c8a02da11d6251e7e73 MD5: a08c545c05651e6a9651010c13f3151f Have you tried downloading it from a different browser, or without HTTPS? torch-1.1.0a0+b457266-cp36-cp36m-linux_aarch64.whl.sha256.txt (118 Bytes) torch-1.1.0a0+b457266-cp36-cp36m-linux_aarch64.whl.md5.txt (86 Bytes) Can you let me know if you can access box.com link without using HTTPS, or does HTTP/HTTPS not matter with the GFW? Hi Dusty, thank you. I’ve downloaded the wheel from a proxy in Hongkong, and verified with MD5 checksum. The box.com is blocked by China’s Great Fire Wall (GFW), either does Google driver (so can’t solve the problem even if you make a copy to Google driver). I put the python3’s wheel in Baidu driver and shared the link in this thread. Copy here: Baidu NetDriver Link: Code : ribc Neither way, w/o SSL. In general, all UGC alike websites are blocked by the GFW. In fact I’m using a VPN from Los Angeles, with access to Google, Twitter, etc. But it just somehow filed connecting to box.com. It would be so nice of you if you could down the wheel for python2 and upload to baidu driver. Big thanks. Hi, After I installed the PyTorch wheel for Python3, this is what I got. ( I am using Nano, and just flash it) ~$ python3 Python 3.6.7 (default, Oct 22 2018, 11:32:17) [GCC 8.2.0] on linux Type “help”, “copyright”, “credits” or “license” for more information. import numpy import torch Traceback (most recent call last): File “”, line 1, in File “/usr/local/lib/python3.6/dist-packages/torch/init.py”, line 79, in from torch._C import * ImportError: /usr/local/lib/python3.6/dist-packages/torch/lib/libtorch_python.so: undefined symbol: _Py_ZeroStruct Could you tell me is there other packages that I need to install? Thank you Torch wheel for Python2.7 @Baidu NetDriver: Code: j2eq MD5 (torch-1.1.0a0+b457266-cp27-cp27mu-linux_aarch64.whl) = 6515e05c0eb1437ca9fa187391df7505 For those behind the GFW who can’t download the wheel from box.com, please use the following Baidu NetDriver Linker: PyTorch for Python 2.7 Code: j2eq MD5 (torch-1.1.0a0+b457266-cp27-cp27mu-linux_aarch64.whl) = 6515e05c0eb1437ca9fa187391df7505 PyTorch for Python 3.6 Code : ribc MD5 (torch-1.1.0a0+b457266-cp36-cp36m-linux_aarch64.whl) = a08c545c05651e6a9651010c13f3151f Happy hacking :) As advised, I reflashed the Xavier with Jetpack 4.2. But it still is not working. I created a new virutal environment using virtual-env and installed the pre-built wheel for python 3 specified in the top post. >>> import torch Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/nvidia/python3/lib/python3.6/site-packages/torch/__init__.py", line 97, in <module> from torch._C import * ImportError: numpy.core.multiarray failed to import
https://forums.developer.nvidia.com/t/pytorch-for-jetson-version-1-6-0-now-available/72048?page=2
CC-MAIN-2020-40
refinedweb
1,021
78.55
Subject: [hwloc-devel] plugins inside plugin broken, as expected From: Brice Goglin (Brice.Goglin_at_[hidden]) Date: 2013-06-03 04:45:47 Hello, I recently got the first report of what we knew would happen one day or another: plugin namespace issues caused by somebody loading a plugin-enabled hwloc as a plugin. It comes from OpenCL (which uses plugins to select implementations) because one implementation depends on hwloc. What happens is that hwloc fails to load its plugins because they need some functions from the hwloc core, but they cannot find them because hwloc was loaded in a private namespace within a OpenCL plugin. What's annoying is that the program completely seems to load plugins fine but later aborts at use-time because of the missing symbol (and there's no portable/easy way to force load-time lookup from what I see in the ltdl documentation). One easy workaround is to set HWLOC_PLUGINS_PATH=/none in the environment, so that no hwloc plugin is found. But this may remove some features. The proper fix for now is to rebuild hwloc without plugins. So we don't have to hurry and fix this for v1.7.2, but we can still look at it for v1.8. Two solutions were envisioned earlier: * Have hwloc plugins depend on libhwloc. Jeff didn't like it because it will cause multiple instances of libhwloc to be loaded, which will break if we have internal/global state in libhwloc. I think we actually have no such internal state, but this way may still be dangerous. * Have the core tell plugins where core symbols are. Basically means doing our own symbol lookup manually. Possible issues: + We have maaaaaaany symbols, it's not easy to define which ones are available to plugins and which ones are not. Quick look [1]. + Plugins won't be able to call hwloc functions directly anymore, and they won't be able to use inline helpers anymore (since those often call hwloc core functions explicitly). + Need to implement that without causing future ABI breaks when extending to API that is available to plugins. Maybe have plugins pass an array of strings listing which symbols they need. Other ideas? Brice [1] Review of public symbols: Things that shouldn't be available to plugins: * init/load/destroy * topology_set_*() topology_ignore_*() topology_restrict() * XML export/import * cpubind/membind/last_cpu_location (as well alloc/free) * custom_insert_* Things that should be available: * hwloc/plugins.h * other insert() functions (not sure) * most of our get() functions * most stringification functions * minor other things (about 30 total). Brice
http://www.open-mpi.org/community/lists/hwloc-devel/2013/06/3768.php
CC-MAIN-2014-15
refinedweb
427
61.67
If nothing is hooked up to a GPIO pin, does the OS read it as HIGH or LOW. I am trying to run a python script to shut down the Pi safely when a GPIO is set to high. With no GPIO pins connected, pin 2 is reading HIGH. Is this the normal behavior? Code: Select all import RPi.GPIO as GPIO import time import os GPIO.setmode(GPIO.BCM) GPIO.setup(2, GPIO.IN) GPIO.setup(23, GPIO.OUT) print("Shutdown script started. Wait for shutdown request") while True: GPIO.output(23, GPIO.HIGH) // sent HIGH to arduino - lets arduino know PI is running if(GPIO.input(2)): print("Request from button to shutdown") os.system("sudo shutdown -h now") break time.sleep(1)
https://www.raspberrypi.org/forums/viewtopic.php?t=36800
CC-MAIN-2021-17
refinedweb
125
78.85
Finance plotting Project description Finance Plot Finance Plotter, or finplot, is a performant library with a clean api to help you with your backtesting. It's optionated with good defaults, so you can start doing your work without having to setup plots, colors, scales, autoscaling, keybindings, handle panning+vertical zooming (which all non-finance libraries have problems with). And best of all: it can show hundreds of thousands of datapoints without batting an eye. Features - Great performance compared to mpl_finance, plotly and Bokeh - Clean api - Works with both stocks as well as cryptocurrencies on any time resolution - Show as many charts as you want on the same time axis, zoom on all of them at once - Auto-reload position where you were looking last run - Overlays, fill between, value bands, symbols, labels, legend, volume profile, heatmaps, etc. - Can show real-time updates, including orderbook. Save screenshot. - Comes with a dozen great examples. What it is not finplot is not a web app. It does not help you create an homebrew exchange. It does not work with Jupyter Labs. It is only intended for you to do backtesting in. That is not to say that you can't create a ticker or a trade widget yourself. The library is based on the eminent pyqtgraph, which is fast and flexible, so feel free to hack away if that's what you want. Easy installation $ pip install finplot Example It's straight-forward to start using. This shows every daily candle of Apple since the 80'ies: import finplot as fplt import yfinance df = yfinance.download('AAPL') fplt.candlestick_ochl(df[['Open', 'Close', 'High', 'Low']]) fplt.show() Example 2 This 25-liner pulls some BitCoin data off of Bittrex and shows the above: import finplot as fplt import numpy as np import pandas as pd import requests # pull some data symbol = 'USDT-BTC' url = '' % symbol data = requests.get(url).json() # format it in pandas df = pd.DataFrame(data['result']) df = df.rename(columns={'T':'time', 'O':'open', 'C':'close', 'H':'high', 'L':'low', 'V':'volume'}) df = df.astype({'time':'datetime64[ns]'}) # create two axes ax,ax2 = fplt.create_plot(symbol, rows=2) # plot candle sticks candles = df[['time','open','close','high','low']] fplt.candlestick_ochl(candles, ax=ax) # overlay volume on the top plot volumes = df[['time','open','close','volume']] fplt.volume_ocv(volumes, ax=ax.overlay()) # put an MA on the close price fplt.plot(df['time'], df['close'].rolling(25).mean(), ax=ax, legend='ma-25') # place some dumb markers on low wicks lo_wicks = df[['open','close']].T.min() - df['low'] df.loc[(lo_wicks>lo_wicks.quantile(0.99)), 'marker'] = df['low'] fplt.plot(df['time'], df['marker'], ax=ax, color='#4a5', style='^', legend='dumb mark') # draw some random crap on our second plot fplt.plot(df['time'], np.random.normal(size=len(df)), ax=ax2, color='#927', legend='stuff') fplt.set_y_range(-1.4, +3.7, ax=ax2) # hard-code y-axis range limitation # restore view (X-position and zoom) if we ever run this example again fplt.autoviewrestore() # we're done fplt.show() Real-time examples Included in this repo are a 40-liner Bitfinex example and a slightly longer BitMEX websocket example, which both update in realtime with Bitcoin/Dollar pulled from the exchange. A more complicated example show real-time updates and interactively varying of asset, time scales, indicators and color scheme. finplot is mainly intended for backtesting, so the API is clunky for real-time applications. The examples/complicated.py was written a result of popular demand. MACD, Parabolic SAR, RSI, volume profile and others There are plenty of examples that show different indicators. For interactively modifying what indicators are shown, see examples/complicated.py. Snippets Background color # finplot uses no background (i.e. white) on even rows and a slightly different color on odd rows. # Set your own before creating the plot. fplt.background = '#ff0' # yellow fplt.odd_plot_background = '#f0f' # purple fplt.plot(df.Close) fplt.show() Unordered time series finplot requires time-ordered time series - otherwise you'll get a crosshair and an X-axis showing the millisecond epoch instead of the actual time. See my comment here and issue 50 for more info. It is also imperative that you either put your datetimes in your index, or in the first column. If your datetime is in the first column, you normally want to have a zero-based range index, df.reset_index(drop=True), before plotting. Restore the zoom at startup # By default finplot shows all or a subset of your time series at startup. To store/restore zoom position: fplt.autoviewrestore() fplt.show() # will load zoom when showing, and save zoom when closing Time zone # Pandas normally reads datetimes in UTC time zone. # finplot by default use the local time zone of your computer (for crosshair and X-axis) from dateutil.tz import gettz fplt.display_timezone = gettz('Asia/Jakarta') # ... or in UTC = "display same as timezone-unaware data" import datetime finplot.display_timezone = datetime.timezone.utc Scatter plot with X-offset To offset your scatter markers (say 0.2 time intervals to the left), see my comment here. Align X-axes See issue 27, and possibly (rarely a problem) issue 4. Disable zoom/pan sync between axes # finplot assumes all your axes are in the same time span. To decouple the zoom/pan link, use: ax2.decouple() Move viewport along X-axis (and autozoom) Use fplt.set_x_pos(xmin, xmax, ax). See examples/animate.py. Place Region of Interest (ROI) markers For placing ellipses, see issue 57. For drawing lines, see examples/line.py. (Interactively use Ctrl+drag for lines and Ctrl+mbutton-drag for ellipses.) More than one Y-axis in same viewbox fplt.candlestick_ochl(df2[['Open','Close','High','Low']], ax=ax.overlay(scale=1.0, yaxis='linear')) The scale parameter means it goes all the way to the top of the axis (volume normally stays at the bottom). The yaxis parameter can be one of False (hidden which is default), 'linear' or 'log'. See issue 52 for more info. Plot non-timeseries finplot is made for plotting time series. To plot something different use ax.disable_x_index(). See second axis of examples/overlay-correlate.py. Custom crosshair and legend S&P500 example shows how to set crosshair texts and update legend text+color as a result of mouse hover. Custom axes ticks To use your own labels on the X-axis see comment on issue 50. If you want to roll your own Y-axis, inherit fplt.YAxisItem. Saving screenshot See examples/line.py. To keep screenshot in RAM see issue 28. For creating multiple screenshots see issue 71. Scaling plot heights See issue 56. Changing the default window size can be achieved by setting fplt.winw = 900; fplt.winh = 500; before creating your plot. Threading Titles on axes See issue 41. To show grid and further adapt axes, etc: ax.set_visible(crosshair=False, xaxis=False, yaxis=True, xgrid=True, ygrid=True) Fixing auto-zoom on realtime updates Beep fplt.play_sound('bot-happy.wav') # Ooh! Watch me - I just made a profit! Keys Esc, End, g, Left arrow, Right arrow. Ctrl+drag. Missing snippets Plot valign on mouse hover, update an orderbook, etc. Coffee For future support and features, consider a small donation. BTC: bc1qk8m8yh86l2pz4eypflchr0tkn5aeud6cmt426m ETH: 0x684d7d4C52ed428AE9a36B2407ba909D896cDB67 Project details Release history Release notifications | RSS feed Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/finplot/
CC-MAIN-2021-39
refinedweb
1,235
59.5
Pyromancer 0.4 Simple framework for creating IRC bots Simple framework for creating IRC bots. Example init.py: from pyromancer.objects import Pyromancer p = Pyromancer('test.settings') p.run() test/settings.py: host = '1.2.3.4' port = 6667 nick = 'PyromancerBot' encoding = 'ISO-8859-1' Custom commands Writing own commands is fairly simple. Create a folder which will be the package name, with a file named commands.py in it to hold the commands. In commands.py, you can register functions to be a command with the built-in command decorator. Example File layout: test/ __init__.py commands.py settings.py init.py commands.py: from pyromancer.decorators import command @command(r'bye (.*)') def bye(match): return 'Bye {m[1]}!' On IRC: <User> !bye everyone <Bot> Bye everyone! Pyromancer scans automatically for functions decorated using the commands decorator, so all your commands in commands.py are used automatically. You can also create a directory named commands with submodules containing the commands. Just make sure that you import either the modules or all of the commands in the __init__.py file.. raw - a boolean which defaults to False. When true, the raw input line sent from the server is used for matching the pattern, instead of the message. Useful for matching lines which are not a message from an user, such as nick or topic changes.. Support Python 2.7 and 3.0 - 3.4 are supported. Note that development occurs on Python 3. To do - Figure out how to do translation of messages through the Match.msg function. - Add timers - Add a command module which keeps track of channels joined and users in them which other commands can use. Changelist 0.4 - 2014-03-30 - Add support for Python 2.7. - Add more tests. - Fix messaging with positional arguments given as a list not working. - Add ability to create commands for raw code lines by specifying a code to match. - Add ability to do easy message formatting for colored, underlined and bold text. 0.3 - 2014-03-22 - Change settings to be a Python module instead of a dictionary. - Change package loading. - Enable the commands from the package of which the settings are in by default. - Add ability to process raw input lines. - Add option to use precompiled regular expressions in the command decorator. - Add option to pass flags for compiling the regular expressions in the command decorator. - Fix returning message from command not working. - Categories - Intended Audience :: Developers - Intended Audience :: Information Technology - Programming Language :: Python - Programming Language :: Python :: 2.7 - Programming Language :: Python :: 3 - Programming Language :: Python :: 3.0 - Programming Language :: Python :: 3.1 - Programming Language :: Python :: 3.2 - Programming Language :: Python :: 3.3 - Programming Language :: Python :: 3.4 - Topic :: Communications - Topic :: Communications :: Chat - Topic :: Communications :: Chat :: Internet Relay Chat - Topic :: Internet - Topic :: Software Development - Topic :: Software Development :: Libraries - Topic :: Software Development :: Libraries :: Application Frameworks - Package Index Owner: Gwildor - DOAP record: Pyromancer-0.4.xml
https://pypi.python.org/pypi/Pyromancer/0.4
CC-MAIN-2017-34
refinedweb
486
53.37
Simple patch including the startup menu & replacing Guide with the map debug menu: (patch also includes essential fixes and 6C destruction fix because why not) (EA) Source: #include "Extensions/Hack Installation.txt" ORG 0x000AD8 // ORG somewhere in the startup routine (where the call to the GAMECTRL constructor was) BL(0x01C090) // Call the debug startup menu ORG 0x59CEC0 // ORG to guide routines POIN (0x04F448+1) // Always usable WORD 0 // No Fancy draw POIN (0x01BB1C+1) // Debug Map Menu The bootup menu seems to be fully functional. the map menu however seem to have quite a few missing features (in fact it will crash no$ because it tries to reference something that doesn't exist anymore (see notes below)). I found one smaller menu too (the "Charge" menu, located at 0859CFD4, routine to open it at 0801C2E4), but again it doesn't seem to work properly. I spent like 4 hours looking for something that could look like one of those nice character menus without much success... So I guess we still don't know if it isn't gone or not :/. Credits to lin for hooking me up with material on the prototype debug functions. Debug Functionnalities Restoration Patch ????? (probably not but maybe) FE8U DEBUG REMNANTS NOTES Routines related to debug seem to be located around 0x01C000 0801C090 is the Debug Startup routine, the following EA code will replace the standard one with it: ORG 0x000AD8 BL(0x01C090) Seems to work 100% well 0859D040: Map Debug Menu Def 0801BB1C calls that, but seems to also be a menu effect routine (takes Menu 6C as r0, returns 1 etc) 08033468 calls that, but seems to be for prep screen? This replaces the guide menu command with the map debug menu: ORG 0x59CEC0 POIN (0x04F448+1) // always usable WORD 0 // no fancy drawing POIN (0x01BB1C+1) // calls the map debug menu will not work in no$ because of the following: 6C at 0859AA5C (blank, deletes itself immediately) seems to be looked for by a bunch of debug routines, so I think it's safe to assume this used to be some "debug manager", but now is removed. Known 6C 0859AA5C Fields: 58 | word | weather id (0 => 0, 1 => 6, 2 => 1, 3 => 2, 4 => 4, 5 => 3, 6 => 5) imma slep now
http://feuniverse.us/t/fe8u-doc-leftover-stuff-from-the-prototype-debug-builds/2874
CC-MAIN-2018-47
refinedweb
379
54.6
30 April 2010 07:36 [Source: ICIS news] By Serena Seng ?xml:namespace> SINGAPORE Fatty acids, which are fractionated from derivatives of palm oil, have various downstream applications such as plastics and cosmetics. High feedstock costs were constraining supply at a time when demand for fatty acids was traditionally at its peak, market sources said. “Most Malaysian producers are currently sold out until June and July for C12-14 acids, C18 chains are tight in supplies now,” said a Malaysian trader. Some buyers had started to stock up on inventories in anticipation of higher prices in the coming weeks, market sources said. “Demand for C12-18 acid groups are strong, and if palm oil prices go up, acid prices will have to go up as well”, an Indonesian producer added. Over the past month, prices of C12-18 acid groups increased at an average of $20-100/tonne (€15-76/tonne) FOB (free on board) southeast Asia, while those of C8-10 acids were unchanged, based on data from global chemical market intelligence service, ICIS pricing. Crude palm oil (CPO) prices, meanwhile, were rising due to tight supply as the prolonged dry spell was adversely affecting harvest at major plantations in CPO futures traded on the Bursa Malaysia decreased by M$33/tonne ($10.3/tonne) at M$2,591/tonne from end-March to M$2,558/tonne on 28 April, although the past three months saw a clear uptrend in values. CPO prices rose about 6% from end-January, based on data available from the Malaysian stock exchange. The prices were moving in tune with the prediction of Dorab Mistry, an official at Indian major oleochemicals producer Godrej International and widely acknowledged as an industry expert, that palm prices would continue to rise in the second quarter, said a Mistry spoke about his bullish prospects on palm oil prices at a recent industry conference in Some market players, however, were not convinced that fatty acids prices would head north, given ample supply. “Malaysian producers may be sold out till June-July, but ($1 = €0.76 ; $1 = M$3
http://www.icis.com/Articles/2010/04/30/9353979/asian-fatty-acid-values-to-spike-on-strong-demand-volatile-cpo.html
CC-MAIN-2014-52
refinedweb
350
54.56
01-17-2016 05:42 AM Solved! Go to Solution. 02-07-2016 04:54 PM Good afternoon, I have a question about using Actor Framework. Deputy example, to better understand what I do. I have a parent class that inherits from the actor, and the various messages are defined for the class, in this case "Get state.vi". Now define a child class that inherits from the parent class. Whether messages that are to be used are the same as those of the parent class, you need to define all messages for the child class or the child class can inherit all messages? How I can do to make a child class run messages from a parent class, with references to the child class? Thanks. 02-08-2016 04:04 AM I'm not that familiar with the actor framework, but one of the best resources I found while learning it was here (at least, I think it was this): It takes a sample application built using a QMH and shows you the various steps / progression moving it from a QMH to an LVOOP implementation all the way through to the Actor Framework. It should help you see how you can adapt/modify your code to the actor framework. 02-08-2016 04:00 PM Thank you. The link has been helpful, but still have not managed to run the example. Deputy what I have done case anyone comes up with an idea. Thank. 02-11-2017 10:11 PM hello gentlemen.. i was just stuck again and again with actor framework usage in labview. here i try to pass the message of boolean and a numeric between parent and child but it not works anyone help me to solve this? 02-13-2017 12:10 AM 02-13-2017 01:11 AM Yes but... Problem is the numeric value not received between parent and child??? 02-13-2017 01:41 AM @mohamedtanveej17 wrote: Yes but... Problem is the numeric value not received between parent and child??? -You have to add first numeric control and indicator in same way as created for boolean control and indicator for both parent and child actors. -Create new vi from static dispatch template and follow the same steps followed for Get State from Parent and Child methods. -In parent inside event structure add new event for Numeric control and pass the value to the new method created. 02-13-2017 04:11 AM - edited 02-13-2017 04:14 AM Carlos, Firstly, just in case you haven't seen it, there is a subforum/group for Actor Framework questions - the people there are really helpful and the questions are all about Actor Framework problems. They also have some helpful materials stickied. Secondly, what are you trying to do? I opened the example project you uploaded (Example1.zip) and took a look but didn't see anything as the obvious goal. Regarding inheritance, child classes (not the same as nested actors) behave in the same way as with non-Actor Framework OOP code. That is, if you have a dynamic dispatch VI in the parent, you can override it in the child class to modify the behaviour of the VI. VIs in the parent (dynamic or static) can be used by the child, provided it has access to the VI (i.e. the VI is Public or Protected, or the child class is a friend of the parent class and the VI is Community scope.) If the VI called is implemented by the parent (because it is static, or because you don't have an override, or because your override uses 'Call Parent Node') then the private data available should be that of the parent - if you have a child implementation called via dynamic dispatch, the child's private data will be available to the override (but not the parent, during a 'Call Parent Node' VI call). Messages also have their own inheritance hierarchy, but in the simplest case, they inherit only from Actor Framework's 'Message' class. Typically, they are a class with private data, which might be empty, or contain the inputs to the VI that the 'Do.vi' calls, and two VIs, 'Send <MessageName>.vi' and 'Do.vi'. The Do.vi is an override of the Actor Framework's 'Message.lvclass:Do.vi' and the parent does nothing here - what is important is that when an Actor receives the message, it calls the 'Do' VI of the Message that you define. Usually, this calls some public class VI (for example, 'Set Indicator' might be an example that could be called by Message). Here, you will also see that data is often unbundled from the Message class' private data, and used as an input for the public VI of the class that you sent the message to, via the enqueuer. This site uses cookies to offer you a better browsing experience. Learn more about our privacy statement and cookie policy.
https://forums.ni.com/t5/LabVIEW/Actor-Framework-Basic-The-Message-Class/td-p/3239936?profile.language=en
CC-MAIN-2021-31
refinedweb
828
70.02
Windows Phone From Scratch #23 In yesterday’s posting we created an application that used a chooser to allow you to pick a name from the contacts list and to obtain the related phone number. Today we’ll use that information to launch the SMS service to send a message to the selected user. Today’s posting is very short, as the work of creating a launcher is nearly identical to that of calling a chooser, except that with a launcher you don’t get information back. You will remember that yesterday we created a private member variable of type PhoneNumberChooserTask. Today we’ll add a second private member of type SmsComposeTask private PhoneNumberChooserTask _choosePhoneNumber; private SmsComposeTask _smsCompose; This time we’ll initialize the Task in the call-back method for the phone number, thus creating a clear logic to the program: - Ask for the phone number - When you return with the phone number feed it to the SMS Task - Launch the SMS Task. The SmsComposeTask has two properties: the body of the message and the phone number. We’ll add these one by one (though we could just use member initialization) and then, as we did with the Chooser, we’ll call Show to start up the Launcher. The difference is that there is no call back, as Launchers do not return information. Here is the complete code behind – there are no changes to the Xaml: using System; using System.Windows; using Microsoft.Phone.Controls; using Microsoft.Phone.Tasks; namespace SMS { public partial class MainPage : PhoneApplicationPage { private PhoneNumberChooserTask _choosePhoneNumber; private SmsComposeTask _smsCompose; ) { _smsCompose = new SmsComposeTask(); _smsCompose.Body = "Sending SMS message..."; _smsCompose.To = e.PhoneNumber; _smsCompose.Show(); } } } The computer thinks these might be related: Given you either compose/show either an SMS or Call, is there a way to pickup the result of the task? I’d like to know that the message/call was sent/placed and possibly how long the call lasted (etc..). Perhaps I can deduce this by saving values of when tombstoned and when app reactivates? Is there a way to pickup the “Name/Number” being dialed rather than just the phone number. If the user doesn’t complete task (e.g. presses cancel), I’d like my program to perhaps use in logic. Pingback: iPhone Developer? How to move to Windows Phone 7! | I Love Windows Phone! Pingback: Tweets that mention Launchers & Choosers
http://jesseliberty.com/2011/01/25/launchers-chooserspart-2/?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+JesseLiberty-SilverlightGeek+%28Jesse+Liberty+-+Silverlight+Geek%29
crawl-003
refinedweb
398
55.03
Opened 7 years ago Closed 7 years ago Last modified 7 years ago #2733 closed Bug (No Bug) WM_SETCURSOR doesn't pass $wParam as handle after using GUICtrlSetCursor Description Here is an example that shows the problem: #include <GUIConstantsEx.au3> #include <WindowsConstants.au3> $hGui = GUICreate('Test ' & @AutoItVersion, 200, 150) $iLbl = GUICtrlCreateLabel('Test GUICtrlSetCursor', 20, 40, 160, 20) $hLbl = GUICtrlGetHandle($iLbl) GUISetState() GUIRegisterMsg($WM_SETCURSOR, 'WM_SETCURSOR') GUICtrlSetCursor($iLbl, 0) ;Comment this line to see the difference While 1 Switch GUIGetMsg() Case $GUI_EVENT_CLOSE Exit EndSwitch WEnd Func WM_SETCURSOR($hWnd, $iMsg, $wParam, $lParam) Switch $wParam Case $hLbl ConsoleWrite('$wParam = $hLbl? ' & ($wParam = $hLbl) & @LF) EndSwitch Return $GUI_RUNDEFMSG EndFunc Environment(Language:0419 Keyboard:00000409 OS:WIN_7/ CPU:X64 OS:X64) On AutoIt versions below 3.3.10.2 there was no problem. Attachments (0) Change History (3) comment:1 Changed 7 years ago by Jpm - Resolution set to No Bug - Status changed from new to closed comment:2 Changed 7 years ago by BrewManNH I think the point being made was that when you don't use GUICtrlSetCursor in the exact same script, $wParam will return the label's handle when the cursor is over it. When you use GUICtrlSetCursor you never see that information. comment:3 Changed 7 years ago by MrCreatoR if you rad the MSDN doc it is the handle to the Windows not to the control Then why this behaviour was changed only since 3.3.10.2, on earlier versions it was always the control handle, not the window. And why it should be the window handle, we have it in $hWnd parameter. I think something was changed in GUICtrlSetCursor because this affecting the wm_setcursor message. Guidelines for posting comments: - You cannot re-open a ticket but you may still leave a comment if you have additional information to add. - In-depth discussions should take place on the forum. For more information see the full version of the ticket guidelines here. In fact it does. But if you rad the MSDN doc it is the handle to the Windows not to the control
https://www.autoitscript.com/trac/autoit/ticket/2733
CC-MAIN-2021-25
refinedweb
342
60.04
14 August 2013 22:08 [Source: ICIS news] HOUSTON (ICIS)--US oxo-alcohols contracts for August – including those for n-butanol (NBA), iso-butanol (IBA) and 2-ethylhexanol (2-EH) – settled this week at a rollover from July prices. However, almost every major producer informed customers that September prices would likely include price increases of 3 cents/lb ($66/tonne, €50/tonne) for all three alcohols because of the rising cost of feedstock propylene, both for chemical grade propylene (CGP) and refinery grade propylene (RGP). Demand for 2-EH, NBA and IBA remained steady and strong, buyers said. The price increase was attributed solely to the increase in feedstock prices. Propylene August contracts settled up 5 cents/lb on rising petroleum costs. That has caused a chain reaction that has reached downstream to the oxo-alcohols and beyond. Dow Chemical sent customers a note Tuesday saying that it will raise the off-list prices for several derivatives of oxo-alcohols, including acrylates and acrylic acid, by 4 cents/lb on 1 September. That nomination includes prices for butyl acrylate (butyl-A), ethyl acrylate (ethyl-A) methyl acrylate (methyl-A), 2-ethyl hexyl acrylate (2-EHA) and glacial acrylic acid (AA). One large producer said that it had raised prices in July and did not want to nominate another so soon. That producer also expects a September price increase but hadn't decided its strategy on Tuesday. Buyers greeted the nominations with some resignation and scrutiny. One medium-sized buyer said he doubted that the increases would hold. He pointed out that some other feedstock prices were trending lower, including those for ethylene. A trader, though, said that the nominated increases would probably hold and that prices would be passed along to downstream customers. Trading in dioctyl phthalate was light with little trading heard and in line with recent months. Export demand for 2-EH continued to be strong with price increases of up to 2 cents/lb for large shipments to ?xml:namespace> A similar price increase for 2-EH exports to The demand for 2-EH for coatings, paint and inks was heard from moderate to strong, according to buyers, traders and sellers. (
http://www.icis.com/Articles/2013/08/14/9697500/us-oxo-alcohols-flat-for-aug-but-poised-to-rise-in-sept.html
CC-MAIN-2014-10
refinedweb
364
59.84
Introduction Istio, the upstream project for Red Hat OpenShift Mesh, has an interesting feature that allows you to extend the service mesh across multiple OpenShift clusters. The main requirement to implement this feature is that the IPs of the pods of the clusters that comprise the service mesh are all routable between each other. That is to say that a pod in cluster A should be able to communicate with a pod in cluster B, assuming the pod in cluster A knows the IP address of the pod in cluster B. This article shows a way to implement this requirement, though this is not yet officially supported by Red Hat. Potentially this capability will enable more use cases besides Istio Multicluster. Assumptions For the design that follows we are going to assume that the nodes of the clusters that we want to connect are not directly routable between each others. Instead we will assume that it is possible to create public VIPs that are reachable by the nodes, and that those VIPs can load balance connections to the nodes and services of the OpenShift cluster. Potentially these clusters could exists in different clouds. This setup should be realistic for both cloud and on premises deployments of OpenShift. The automation that sets up the SDN connectivity assumes that you can create LoadBalancer type services. If you don’t have this automation you can still build the described design, but you’ll have to develop a different automation. If your clusters do not support LoadBalancer services, it is possible to use NodePort services. In this case though, the nodes must be routable and therefore other/better mechanisms to build the network tunnel rather than what is proposed here may be available. Finally the pod’s CIDRs of all the clusters that we are trying to connect must not be overlapping. Tunnel Design For the rest of the document we will assume that we want to connect two clusters for simplicity, but the design can be generalized to multiple clusters. In order to connect the different SDNs we have to create a network tunnel between them. Because we can only use VIPs (a pair of IP and port) to connect from one cluster to the other the transport of the tunnel will have to be a layer 4 protocol. So we need a Layer 3 over Layer 4 (remember the tunnel needs to transport IP packets which are layer 3) tunnel. UDP, with its connectionless property, lends itself to this job. The tool the we can use in Linux to do this job is a tunnel device. A tunnel device is a network device that has one end attached to the network stack the other end managed by some software (it can be a kernel module or an user space application). It is a way to let an application manipulate network packets directly instead of through the abstraction of the socket API. In our case the application will put encapsulate these packets and forward them on a different type of transport layer to the other cluster. The Linux kernel provides two types of tunnel devices: tap devices for Layer 2 encapsulation and tun devices for layer 3 encapsulation. In our case, we are going to use a tun device. With this is mind, here is a possible design for our tunnel: A daemonset pod will create the tunnel and ensure that packets directed to the other cluster are correctly routed. packet to the VIP of the other cluster. RECEIVE PHASE: - A UDP encapsulated packet is received by the VIP and load balanced to one of the tunnel daemon set processes. - The tunnel daemon set process extracts the packet from the UDP envelope and puts in the tun device. - The packet ends up in the bridge. - The bridge examines the destination, if local to the node the packet is delivered immediately. Otherwise it is forwarded to the right node. Note: a sequence of IP packets belonging to the same TCP stream do not necessarily follow the same path because the load balancer may choose a different daemon set pod for each element of the sequence. Also return packets do not necessarily follow the same path a original packets. This is all fine with IP packet routing. This design creates a many-to-many mesh of connections with no single point of failure. It also better leverages the bandwidth that we have at our disposal relative to a solution with a single jump node that establishes the tunnel with the other cluster. We have no control over the latency of the communication, which mainly depends on what is between the two clusters. It turns out that the Linux kernel has the capability of creating IP over UDP tunnels via the fou module. Fou stands for Foo over UDP and implements a couple of generic encapsulation mechanisms over UDP. We are interested in the IP over UDP option. When I started implementing with fou I quickly realized that the fou module is not available in RHEL. It is possible to build a user-space surrogate of the IP over UDP tunnel using socat. This article explains how. Also this approach didn't work for me. Contributions to make it work are welcome. I didn’t spend much time on the solution based on socat because the more I thought about this problem and talked about it with my colleagues, the more I realized that I needed to build an encrypted tunnel. Encrypted Tunnel Design I believe that applications should be responsible for encrypting their own data if they need confidentiality in their communications. So that’s not the reason why we need an encrypted tunnel. The reason is that having a public VIP to which it’s possible to send packets that will then be routed inside the OpenShift SDN, creates an architecture that is vulnerable to denial of service attacks. We need a way to authenticate legitimate packets and drop the others as soon as they are received by the daemon set. In theory we just need to authenticate the packet with a cryptographic signature, such as, for the example, the one provided by the Authentication Header (AH) protocol. In practice most VPN software will not implement this feature in isolation and will always also add encryption. Encryption necessarily introduces statefulness to the communication, even if it occurs over UDP, therefore we need to adjust the tunnel design as showed in the below picture: Now each daemonset pod has a dedicated VIP that load balances only to it. and encrypted packet to the VIP connected to the correct node of the other cluster. RECEIVE PHASE: - A UDP encapsulated and encrypted packet is received by the VIP and sent to the corresponding tunnel ds process - The tunnel daemonset process extracts and decrypts the packet from the UDP envelope and puts it in the tun device. - The packet ends up in the bridge. - The bridge examines the destination, which will be local to the node, and delivers the packet immediately. We now have one VIP per node and one. Each VIP will forward the traffic only to the daemonset pod deployed on that node. Notwithstanding this change, our tunnel still retains the properties of not having a single point of failure and of fully leveraging the bandwidth at our disposal. With this design, we gain the fact that now the tunnel always delivers the packet to the node that houses the destination pod, and the SDN never has to route the packets across nodes, saving a hop. Not being a VPN expert, I started looking for VPN products that could be used to implement this VPN mesh. OpenVPN and IPSec were the obvious ones to start with. I found both of them to be not easy to configure in a mesh fashion, not very container friendly, and sometime they made too many assumptions on they way packets should be routed. Eventually I found Wireguard. This VPN of modern conception seems to have all that was needed. It is easy to configure for a mesh deployment, it is container friendly and it just creates a tunnel, leaving to the user the responsibility to configure routing for it. Note: when introducing a new security product one should make sure that all the needed security standards are met. I am not claiming that WireGuard is secure. You should make up your own mind on that. This article may be a good start, followed by this deeper and more technical description. Routing Packets We said a few times that the tunnel device was wired to the SDN bridge. In Openshift the SDN bridge is a logical bridge implemented with OpenVSwitch. This bridge is programmed to create the logical abstraction of the OpenShift SDN. Out-of-the box it is not configured to manage routing to other SDNs, so we will have to add this logic. In the OpenShift SDN bridge, routed packets go through a set of rules (not unlike what happens with iptables) and eventually they are either delivered to one of the ports attached to the bridge or they are dropped. The bridge contains several tables of rules in which different sets of actions are performed. At a high level, the first set of tables are about verifying that the packet is a legitimate packet or dropping spurious packets. The second set of rules (from table 30 up) are about analysing the destination of the packet and making the correct routing decision. Pods are attached to the bridge by means of virtual ethernet interface (veth) pairs. Veths are a Linux kernel mechanism to let packets traverse network namespaces. Whatever enters one end of the pair exits on the other side and one can put each of the veth pair in different namespaces. This setup is prepared for us by the OpenShift SDN when a pod is created. We can add a few rules to the bridge to make sure that the traffic to the other cluster is channeled through the pod’s veth device and then we can create the Wireguard tunnel in the pod and route the traffic coming from the veth device to the tunnel. Here is the design: In our MVP implementation we are going to be less meticulous in terms of packet validation and add two simple routing rules to the bridge that can be paraphrased as follows: - If you see a packet destined to the CIDR of the other cluster, route it to the daemonset pod. - If you see a packet coming from the daemonset pod and whose source IP falls into the CIDR of the other cluster jump, skip all the verifications steps and make the routing decision for this packet. In terms of routing rules inside the pod, we just need to add a rule that sends all the packets whose destination is the other cluster to the Wireduard tunnel. Once the packet is in the Wireguard tunnel, it will follow the flow described in the previous sections and when it lands in the daemonset pod it will be routed to the bridge and then to its destination pod. Installation I created an Ansible automation to connect the SDNs of multiple clusters through Wireguard as described above. You can find the Ansible playbook here, together with the instructions on how to use it. A word of warning: Wireguard installs an uncertified kernel module. This taints the kernel. You should proceed with caution when making that decision (see this knowledge base article on tainted kernels). Also the OpenVSwitch bridge and its internal routing rules are not part of the public OpenShift API, they are an implementation detail that can change from one release to another. This means that this design that works today may not work anymore in future releases of OpenShift (at the time of writing this article, this implementation was tested with OCP 3.9 and 3.10). Finally, this solution is currently not officially supported by Red Hat: at this stage it is just my individual effort, so the quality as we said is at MVP level and support will be best effort. Note: you need a real OpenShift SDN to make this tunnel work, so clusters such a Minishift that do not install the SDN components of OpenShift will not work. Conclusions As we saw in this article, we had to accept a couple of compromises to be able to create this solution. The fou module is not yet available in the RHEL kernel and the incumbent VPNs are not really suitable for building a VPN mesh. I think this indicates that the technology still needs to mature in this space and over time it will become much easier to implement these types of designs. Also it’s worth repeating that we assumed that there was no direct connectivity between the nodes of the clusters involved in this design. If you don’t have that constraint, other potentially simpler designs become possible (for example ip over ip tunneling). My hope is that with this article, we can start a conversation on how to build these types of topologies. Finally, I’d like to thank all the colleguages that have spent time with me explaining networking and helping me fix any issues. A thank to: Vadim Zharov, Brent Roscos, Matthew Witzenman, Øystein Bedin, Julio Villarreal Pelegrino, Qi Jun Ding, Clark Hale. Categories
https://www.openshift.com/blog/connecting-multiple-openshift-sdns-with-a-network-tunnel
CC-MAIN-2020-16
refinedweb
2,232
58.92
Hello! I’m an amateur regarding pytorch. I have a csv file with a column of text and a column of integer labels. How can I load this csv into the dataloader so that I can train a model for classification? This is my code which gives an exception. import torch import pandas as pd train = pd.read_csv("/content/Q_V_1.08.csv") train_tensor = torch.tensor(train.values) TypeError Traceback (most recent call last) <ipython-input-44-83fe164cf357> in <module>() 3 4 train = pd.read_csv("/content/Q_V_1.08.csv") ----> 5 train_tensor = torch.tensor(train.values) TypeError: can't convert np.ndarray of type numpy.object_. The only supported types are: float64, float32, float16, complex64, complex128, int64, int32, int16, int8, uint8, and bool.
https://discuss.pytorch.org/t/loading-a-csv-with-a-column-of-strings-and-a-column-of-integers/151080
CC-MAIN-2022-27
refinedweb
121
53.98
CodePlexProject Hosting for Open Source Software Why is it so difficult to find common libraries in Prism v4 that were once present in v2. I want to use the "Microsoft.Practices.Composite.Presentation.Regions" namespace but I can't seem to find the equivalent in Prism v4. The same goes for the "Microsoft.Practices.Composite.Modularity" namespace. Hi, As explained in this article from the Prism v4 MSDN documentation, the namespaces you're mentioning are now named Microsoft.Practices.Regions and Microsoft.Practices.Modularity. From the documentation: I hope you find this helpful. Guido Leandro Maliandi Thank you this direction answered all of my questions! 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.
https://compositewpf.codeplex.com/discussions/242033
CC-MAIN-2017-34
refinedweb
141
60.61
> That's a problem with any lisp that provides a reader-macro facility. > The onus is on the authors of macro packages to create macros that work > well with the existing emacs-lisp-mode parser. That's a good point. >>> So I'm currently against addition of CL style reader macros. > Stefan, is emacs-lisp-mode support your only objection? Yes and no. No in the sense that I expect that introducing such reader macros will have consequences that go further than just "emacs-lisp-mode support". Maybe we could introduce a more limited form of reader macros. E.g. allow #<letter><sexp> and make the reader return (funcall (cdr (assq <letter> reader-macro-alist)) <sexp>) So it would allow introducing a special regexp syntax #r"regexp" (which would for example swap the meaning of ( and \( and things like that), but it wouldn't allow defining "raw string" (backslashes would quote the " just as usual). > We already have plenty of libraries defining "control flow" structures; > look at all the anaphoric-if libraries out there. Agreed, and I think it's a good thing. Stefan
https://lists.gnu.org/archive/html/emacs-devel/2015-01/msg00724.html
CC-MAIN-2021-21
refinedweb
184
64.61
[Universal Windows Platform] Creating a Line-of-Business App with the UWP By Bruno Sonnino | January 2018 | Get the Code One day, your boss comes to you with a new assignment: You must create a new line-of-business (LOB) app for Windows. Web isn’t an option and you must choose the best platform for it, to ensure it will be available for at least 10 more years. That seems to be a difficult choice: You can select Windows Forms or Windows Presentation Foundation (WPF), which are mature technologies with a lot of components, and you, as a .NET developer, have a lot of knowledge and experience working with them. Will they be there in 10 years? My guess is yes; there’s no sign that Microsoft will discontinue any of them in the near future. But in addition to being a bit old (Windows Forms is from 2001 and WPF was created in 2006), these technologies have some other problems: Windows Forms doesn’t use the latest graphics cards and you’re stuck with the same old boring style, unless you use extra components or do some magic tricks. WPF, though it’s still being updated, hasn’t caught up with the latest improvements to the OS and its SDK. By using the Desktop Bridge to convert WPF applications to UWP, they can be deployed to the Microsoft Store and benefit from easy deployment and install/uninstall, worldwide discovery and distribution, and so on. On the other hand, the converted apps will only work for PCs and won’t be able to run on other form factors. Digging a little more, you discover the Universal Windows Platform (UWP) for developing for Windows 10 and see that it doesn’t have the downsides of Windows Forms and WPF. It’s being actively improved and can be used with no change in a wide range of devices, from the tiny Raspberry Pi to the huge Surface Hub. But everybody says that the UWP is for developing small apps for Windows tablets and phones; there’s no such thing as an LOB app using the UWP. And, besides that, it’s very difficult to learn and develop: all those new patterns, the XAML language, the sandbox that limits what can be done, and on and on. All that is far from the reality. Though in the past the UWP had some limitations, and could be difficult to learn and use, this is no longer true. There’s been aggressive development of new features—with the new Fall Creators Update (FCU) and its SDK you can even use .NET Standard 2.0 APIs, as well as access SQL Server directly. At the same time, new tools and components can give you the best experience to develop a new app. Windows Template Studio (WTS) is an extension to Visual Studio that provides a fast start to a full-featured UWP app and you can use the Telerik components for UWP for free, for the best UX. Not bad, no? Now you have a new platform for developing your UWP LOB apps! In this article, I’m going to develop a UWP LOB app using WTS, the Telerik components and direct access to SQL Server using .NET Standard 2.0, so you can see how everything works firsthand. Introduction to the Windows Template Studio As I said before, you need the FCU and its corresponding SDK to use .NET Standard 2.0. Once you have FCU installed on your machine (if you aren’t sure, press Win+R and type Winver to show your Windows version. Your version should be 1709 or newer). The support for .NET Standard 2.0 in the UWP is available only in Visual Studio 2017 update 4 or newer, so if you haven’t updated, you must do it now. You also need the .NET 4.7 runtime installed to use it. With the infrastructure in place, you can install WTS. In Visual Studio, go to Tools | Extensions and Updates and search for Windows Template Studio. After you download it, restart Visual Studio to finish the installation. You can also install it by going to aka.ms/wtsinstall, downloading the installer and then installing WTS. Windows Template Studio is a new, open source extension (you can get the source code from aka.ms/wts) that will give you a great quick start to UWP development: You can choose the type of project (a Navigation Pane with the hamburger menu, Blank, or Pivot and Tabs), the Model-View-ViewModel (MVVM) framework for your MVVM pattern, the pages you want in your project and the Windows 10 features you want to include. There’s a lot of development going on in this project, and PRISM, Visual Basic templates and Xamarin support are already available in the nightly builds (coming soon to the stable version). With WTS installed, you can go to Visual Studio and create a new project using File | New Project | Windows Universal and select the Windows Template Studio. A new window will open to choose the project (see Figure 1). Figure 1 Windows Template Studio Main Screen Select the Navigation Pane project and the MVVM Light framework, then select Next. Now, choose the pages in the app, as shown in Figure 2. Figure 2 Page Selection As you can see in the right Summary column, there’s already a blank page selected, named Main. Select a Settings page and name it Settings, and a Master-Detail page and name it Sales, then click on the Next button. In the next window you can select some features for the app, such as Live Tile or Toast, or a First Use dialog that will be presented the first time the app is run. I won’t choose any features now, except the Settings storage that’s selected when you choose the Settings page. Now, click on the Create button to create the new app with the selected features. You can run the app—it’s a complete app with a hamburger menu, two pages (blank and master-detail) and a settings page (accessed by clicking the cog icon at the bottom) that allows you to change themes for the app. If you go to Solution Explorer, you’ll see that many folders were created for the app, such as Models, ViewModels and Services. There’s even a Strings folder with an en-US subfolder for the localization of strings. If you want to add more languages to the app, you just need to add a new subfolder to the Strings folder, name it with the locale of the language (like fr-FR), copy the Resources.resw file and translate it to the new language. Impressive what you’ve been able to do with just a few clicks, no? But I’m pretty sure that’s not what your boss had in mind when he gave you the assignment, so let’s go customize that app! Accessing SQL Server from the App One nice feature that was introduced in the FCU and in Visual Studio update 4 is the support for .NET Standard 2.0 in the UWP. This is a great improvement, because it allows UWP apps to use a huge number of APIs that were unavailable before, including SQL Server client access and Entity Framework Core. To make SQL Server client access available in your app, go to the app properties and select Build 16299 as the Minimum Version in the application tab. Then right-click the References node and select “Manage NuGet packages” and install System.Data.SqlClient. With that, you’re ready to access a local SQL Server database. One note: the access isn’t made by using named pipes—the default access method—but by using TCP/IP. So, you must run the SQL Server Configuration app and enable TCP/IP connections for your server instance. I’ll also use the Telerik UI for UWP grid, now a free open source product that you’ll find at bit.ly/2AFWktT. So, while you still have the NuGet package manager window open, select and install the Telerik.UI.for.UniversalWindowsPlatform package. If you’re adding a grid page in WTS, this package is installed automatically. For this app, I’ll use the WorldWideImporters sample database, which you can download from bit.ly/2fLYuBk and restore it to your SQL Server instance. Now, you must change the default data access. If you go to the Models folder, you’ll see the SampleOrder class, with this comment at the beginning: There are a lot of comments throughout the project that give guidance on what you need to do. In this case, you need an Order class that’s very similar to this one. Rename the class to Order and change it to something similar to the one in Figure 3. public class Order : INotifyPropertyChanged { public long OrderId { get; set; } public DateTime OrderDate { get; set; } public string Company { get; set; } public decimal OrderTotal { get; set; } public DateTime? DatePicked { get; set; } public bool Delivered => DatePicked != null; private IEnumerable<OrderItem> _orderItems; public event PropertyChangedEventHandler PropertyChanged; public IEnumerable<OrderItem> OrderItems { get => _orderItems; set { _orderItems = value; PropertyChanged?.Invoke( this, new PropertyChangedEventArgs("OrderItems")); } } public override string ToString() => $"{Company} {OrderDate:g} {OrderTotal}"; } This class implements the INotifyPropertyChanged interface, because I want to notify the UI when the order items are changed so I can load them on demand when displaying the order. I’ve defined another class, OrderItem, to store the order items: The SalesViewModel, shown in Figure 4, must also be modified to reflect these changes. public class SalesViewModel : ViewModelBase { private Order _selected; public Order Selected { get => _selected; set { Set(ref _selected, value); } } public ObservableCollection<Order> Orders { get; private set; } public async Task LoadDataAsync(MasterDetailsViewState viewState) { var orders = await DataService.GetOrdersAsync(); if (orders != null) { Orders = new ObservableCollection<Order>(orders); RaisePropertyChanged("Orders"); } if (viewState == MasterDetailsViewState.Both) { Selected = Orders.FirstOrDefault(); } } } When the Selected property is changed, it will check whether the order items are already loaded and, if not, it calls the GetOrderItemsAsync method in the data service to load them. The last change in the code to make is in the SampleDataService class, to remove the sample data and create the SQL Server access, as shown in Figure 5. I’ve renamed the class to DataService, to reflect that it’s not a sample anymore. public static async Task<IEnumerable<Order>> GetOrdersAsync() { using (SqlConnection conn = new SqlConnection( "Database=WideWorldImporters;Server=.;User ID=sa;Password=pass")) { try { await conn.OpenAsync(); SqlCommand cmd = new SqlCommand("select o.OrderId, " + "c.CustomerName, o.OrderDate, o.PickingCompletedWhen, " + "sum(l.Quantity * l.UnitPrice) as OrderTotal " + "from Sales.Orders o " + "inner join Sales.Customers c on c.CustomerID = o.CustomerID " + "inner join Sales.OrderLines l on o.OrderID = l.OrderID " + "group by o.OrderId, c.CustomerName, o.OrderDate, o.PickingCompletedWhen " + "order by o.OrderDate desc", conn); var results = new List<Order>(); using (SqlDataReader reader = await cmd.ExecuteReaderAsync()) { while(reader.Read()) { var order = new Order { Company = reader.GetString(1), OrderId = reader.GetInt32(0), OrderDate = reader.GetDateTime(2), OrderTotal = reader.GetDecimal(4), DatePicked = !reader.IsDBNull(3) ? reader.GetDateTime(3) : (DateTime?)null }; results.Add(order); } return results; } } catch { return null; } } } public static async Task<IEnumerable<OrderItem>> GetOrderItemsAsync( int orderId) { using (SqlConnection conn = new SqlConnection( "Database=WideWorldImporters;Server=.;User ID=sa;Password=pass")) { try { await conn.OpenAsync(); SqlCommand cmd = new SqlCommand( "select Description,Quantity,UnitPrice " + $"from Sales.OrderLines where OrderID = {orderId}", conn); var results = new List<OrderItem>(); using (SqlDataReader reader = await cmd.ExecuteReaderAsync()) { while (reader.Read()) { var orderItem = new OrderItem { Description = reader.GetString(0), Quantity = reader.GetInt32(1), UnitPrice = reader.GetDecimal(2), }; results.Add(orderItem); } return results; } } catch { return null; } } } The code is the same you’d use in any .NET app; there’s no change at all. Now I need to modify the list items data template in SalesPage.xaml to reflect the changes, as shown in Figure 6. <DataTemplate x: <Grid Height="64" Padding="0,8"> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <StackPanel Grid. <TextBlock Text="{x:Bind Company}" Style="{ThemeResource ListTitleStyle}"/> <StackPanel Orientation="Horizontal"> <TextBlock Text="{x:Bind OrderDate.ToShortDateString()}" Margin="0,0,12,0" /> <TextBlock Text="{x:Bind OrderTotal}" Margin="0,0,12,0" /> </StackPanel> </StackPanel> </Grid> </DataTemplate><DataTemplate x: <views:SalesDetailControl </DataTemplate> I need to change the DataType so it refers to the new Order class and change the fields presented in the TextBlocks. I must also change the codebehind in SalesDetailControl.xaml.cs to load the Items for the selected order when it’s changed. This is done in the OnMasterMenuItemChanged method, which is transformed to an async method: Next, I must change SalesDetailControl to point to the new fields and show them, as shown in Figure 7. <Grid Name="block" Padding="0,15,0,0"> <Grid.Resources> <Style x: <Setter Property="HorizontalAlignment" Value="Right" /> <Setter Property="VerticalAlignment" Value="Center" /> <Setter Property="Margin" Value="0,0,12,0" /> </Style> </Grid.Resources> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <TextBlock Margin="12,0,0,0" Text="{x:Bind MasterMenuItem.Company, Mode=OneWay}" Style="{StaticResource SubheaderTextBlockStyle}" /> <StackPanel Orientation="Horizontal" Grid. <TextBlock Text="Order date:" Style="{StaticResource BodyTextBlockStyle}" Margin="0,0,12,0"/> <TextBlock Text="{x:Bind MasterMenuItem.OrderDate.ToShortDateString(), Mode=OneWay}" Style="{StaticResource BodyTextBlockStyle}" Margin="0,0,12,0"/> <TextBlock Text="Order total:" Style="{StaticResource BodyTextBlockStyle}" Margin="0,0,12,0"/> <TextBlock Text="{x:Bind MasterMenuItem.OrderTotal, Mode=OneWay}" Style="{StaticResource BodyTextBlockStyle}" /> </StackPanel> <grid:RadDataGrid <grid:RadDataGrid.Columns> <grid:DataGridTextColumn <grid:DataGridNumericalColumn <grid:DataGridNumericalColumn <grid:DataGridNumericalColumn </grid:RadDataGrid.Columns> </grid:RadDataGrid> </Grid> I display the sales data in the top of the control and use a Telerik RadDataGrid to show the order items. Now, when I run the application, I get the orders on the second page, like what’s shown in Figure 8. Figure 8 Application Showing Database Orders I still have the empty main page. I’ll use it to show a grid of all customers. In MainPage.xaml, add the DataGrid to the content grid: You must add the namespace to the Page tag, but you don’t need to remember the syntax and correct namespace. Just put the mouse cursor over RadDataGrid, type Ctrl+. and a box will open, indicating the right namespace to add. As you can see from the added line, I’m binding the ItemsSource property to Customers. The DataContext for the page is an instance of MainViewModel, so I must create this property in MainViewModel.cs, as shown in Figure 9. public class MainViewModel : ViewModelBase { public ObservableCollection<Customer> Customers { get; private set; } public async Task LoadCustomersAsync() { var customers = await DataService.GetCustomersAsync(); if (customers != null) { Customers = new ObservableCollection<Customer>(customers); RaisePropertyChanged("Customers"); } } public MainViewModel() { LoadCustomersAsync(); } } I’m loading the customers when the ViewModel is created. One thing to notice here is that I don’t wait for the loading to complete. When the data is fully loaded, the ViewModel indicates that the Customers property has changed and that loads the data in the view. The GetCustomersAsync method in DataService is very similar to GetOrdersAsync, as you can see in Figure 10. public static async Task<IEnumerable<Customer>> GetCustomersAsync() { using (SqlConnection conn = new SqlConnection( "Database=WideWorldImporters;Server=.;User ID=sa;Password=pass")) { try { await conn.OpenAsync(); SqlCommand cmd = new SqlCommand("select c.CustomerID, c.CustomerName, " + "cat.CustomerCategoryName, c.DeliveryAddressLine2, c.DeliveryPostalCode, " + "city.CityName, c.PhoneNumber " + "from Sales.Customers c " + "inner join Sales.CustomerCategories cat on c.CustomerCategoryID = cat.CustomerCategoryID " + "inner join Application.Cities city on c.DeliveryCityID = city.CityID", conn); var results = new List<Customer>(); using (SqlDataReader reader = await cmd.ExecuteReaderAsync()) { while (reader.Read()) { var customer = new Customer { CustomerId = reader.GetInt32(0), Name = reader.GetString(1), Category = reader.GetString(2), Address = reader.GetString(3), PostalCode = reader.GetString(4), City = reader.GetString(5), Phone = reader.GetString(6) }; results.Add(customer); } return results; } } catch { return null; } } } With that, you can run the app and see the customers on the main page, as shown in Figure 11. Using the Telerik grid, you get a lot of goodies for free: grouping, sorting and filtering are built into the grid and there’s no extra work to do. Figure 11 Customers Grid with Grouping and Filtering Finishing Touches I have now a basic LOB application, with a customers grid and a master-detail view showing the orders, but it can use some finishing touches. The icons in the lateral bar for both pages are the same and they can be customized. These icons are set in the ShellViewModel. If you go there, you’ll see these comments, which point to where to go to change the icons and the text for the items: // TODO WTS: Change the symbols for each item as appropriate for your app // More on Segoe UI Symbol icons: // // Or to use an IconElement instead of a Symbol see // projectTypes/navigationpane.md // Edit String/en-US/Resources.resw: Add a menu item title for each page You can use font symbol icons (as in the actual code) or images from other sources if you use IconElements. (You can use .png files, XAML paths, or characters from any other fonts; take a look at bit.ly/2zICuB2 for more information.) I’m going to use two symbols from Segoe UI Symbol, People and ShoppingCart. To do that, I must change the NavigationItems in the code: For the first item, there’s already a symbol in the Symbol enumeration, Symbol.People, but for the second there’s no such enumeration, so I use the hex value and cast it to the Symbol enumeration. To change the title of the page and the caption of the menu item, I edit Resources.resw and change Shell_Main and Main_Title.Text to Customers. I can also add some customization to the grid by changing some properties: Adding a Live Tile to the App I can also enhance the application by adding a live tile. I’ll do so by going to Solution Explorer, right-clicking the project node and selecting Windows Template Studio | New feature, then choosing Live Tile. When you click on the Next button, it will show the affected tiles (both new ones and those that have been changed), so you can see if you really like what you did. Clicking on the Finish button will add the changes to the app. Everything to add a Live Tile will be there, you just need to create the tile content. This is already done in LiveTileService.Samples. It’s a partial class that adds the method SampleUpdate to LiveTileService. As shown in Figure 12, I’ll rename the file to LiveTileService.LobData and add two methods to it, UpdateCustomerCount and UpdateOrdersCount, which will show in the live tiles how many customers or orders are in the database. internal partial class LiveTileService { private const string TileTitle = "LoB App with UWP"; public void UpdateCustomerCount(int custCount) { string tileContent = $@"There are {(custCount > 0 ? custCount.ToString() : "no")} customers in the database"; UpdateTileData(tileContent, "Customer"); } public void UpdateOrderCount(int orderCount) { string tileContent = $@"There are {(orderCount > 0 ? orderCount.ToString() : "no")} orders in the database"; UpdateTileData(tileContent,"Order"); } private void UpdateTileData(string tileBody, string tileTag) { TileContent tileContent = new TileContent() { Visual = new TileVisual() { TileMedium = new TileBinding() { Content = new TileBindingContentAdaptive() { Children = { new AdaptiveText() { Text = TileTitle, HintWrap = true }, new AdaptiveText() { Text = tileBody, HintStyle = AdaptiveTextStyle.CaptionSubtle, HintWrap = true } } } }, TileWide = new TileBinding() { Content = new TileBindingContentAdaptive() { Children = { new AdaptiveText() { Text = $"{TileTitle}", HintStyle = AdaptiveTextStyle.Caption }, new AdaptiveText() { Text = tileBody, HintStyle = AdaptiveTextStyle.CaptionSubtle, HintWrap = true } } } } } }; var notification = new TileNotification(tileContent.GetXml()) { Tag = tileTag }; UpdateTile(notification); } } UpdateSample was originally called in the initialization, in the StartupAsync method of ActivationService. I’m going to replace it with the new UpdateCustomerCount: At this point, I still don’t have the customer count to update. That will happen when I get the customers in MainViewModel: The orders count will be updated when I get the orders in SalesViewModel: public async Task LoadDataAsync(MasterDetailsViewState viewState) { var orders = await DataService.GetOrdersAsync(); if (orders != null) { Orders = new ObservableCollection<Order>(orders); RaisePropertyChanged("Orders"); Singleton<LiveTileService>.Instance.UpdateOrderCount(Orders.Count); } if (viewState == MasterDetailsViewState.Both) { Selected = Orders.FirstOrDefault(); } } With that, I have an app as shown in Figure 13. Figure 13 The Finished App This app can show the customers and orders retrieved from a local database, updating the live tile with the customers and order counts. You can group, sort or filter the customers listed and show the orders using a master-detail view. Not bad! Wrapping Up As you can see, the UWP isn’t just for small apps. You can use it for your LOB apps, getting the data from many sources, including a local SQL Server (and you can even use Entity Framework as an ORM). With .NET Standard 2.0, you have access to a lot of APIs that are already available in the .NET Framework, with no change. WTS gives you a quick start, helping you to quickly and easily create an application using best practices with the tools you prefer, and to add Windows features to it. There are great UI controls to enhance the appearance of the app and the app will run in a wide range of devices: on a phone, a desktop, the Surface Hub and even on HoloLens without change. When it comes to deploying, you can send your app to the store and have worldwide discovery, easy install and uninstall and auto updates. If you don’t want to deploy it through the store, you can do so using the Web (bit.ly/2zH0nZY). As you can see, when you have to create a new LOB app for Windows, you should certainly consider the UWP, because it can offer you everything you want for this kind of app and more, with the great advantage that it’s being aggressively developed and will bring you a lot of improvements for years to come. Bruno Sonnino has been a Microsoft Most Valuable Professional (MVP) since 2007. He’s a developer, consultant, and author, having written many books and articles about Windows development. You can follow him on Twitter: @bsonnino or read his blog posts at blogs.msmvps.com/bsonnino. Thanks to the following Microsoft technical expert who reviewed this article: Clint Rutkas Receive the MSDN Flash e-mail newsletter every other week, with news and information personalized to your interests and areas of focus. Universal Windows Platform - Creating a Line-of-Business App with the UWP s... Feb 21, 2018 Universal Windows Platform - Creating a Line-of-Business App with the UWP Time was developers were wary about building new line-of-business (LoB) applications for the Universal Windows Platform (UWP), due in part to challenges like lack of direct access to the database and its sandbox. Bruno Sonnino shows how these problem... Jan 2, 2018
https://msdn.microsoft.com/en-us/magazine/mt814994
CC-MAIN-2019-18
refinedweb
3,784
56.25
Here is the code: #include <cstdlib> #include <iostream> using namespace std; //Declare function int triangle(int num); int main() { int n; cout<<"Enter a number and press RETURN: "; cin>> n; cout<<"Function returned:"<<triangle(n)<<endl; return 0; } //define function int triangle(int n){ int i; int sum=0; for(i=1; i<=n; i++) sum=sum+i; return sum; } What my question is, why does this work if it's declared as triangle(int num) but defined as triangle(int n) I thought they had to be the same? When I put this in one compiler it works and in another I get an error? Can someone explain this to me please?
https://www.daniweb.com/programming/software-development/threads/292340/function-question
CC-MAIN-2020-24
refinedweb
113
55.61
An Automatic Automated Test Writer Who has time to write tests? This is a revolutionary tool to make them write themselves. There comes a day where you have this bullshit class RobotToTest. We need tests. :shipit: class RobotToTest def initialize(human_name, cv) @name = robot_name(human_name) end def robot_name(human_name) "#{self.class.prefix}_#{human_name}" end def cv { planets: planets } end def nested_fun_objects(fun_objects) 'It was fun' end def self.prefix 'Robot' end private def planets ['Mars', Human.home] end def fun_objects [%i(array in array), { hash: nested_hash }] end def nested_hash { in_hash: { in: array } } end def array %w(array) end end just another class to analyze class Human def initialize human_name = 'Emiliano' end def self.home 'Earth' end end You run zapata generate app/models/robot_to_test.rband pop the champagne. Zapata generated spec/models/robot_to_test_spec.rbfor you. describe RobotToTest do let(:robot_to_test) do RobotToTest.new('Emiliano', { planets: ['Mars', Human.home] }) end it '#robot_name' do expect(robot_to_test.robot_name('Emiliano')).to eq('Robot_Emiliano') end it '#cv' do expect(robot_to_test.cv).to eq({ planets: ['Mars', 'Earth'] }) end it '#nested_fun_objects' do expect(robot_to_test.nested_fun_objects([ [:array, :in, :array], { hash: { in_hash: { in: ['array'] } } } ])).to eq('It was fun') end it '#prefix' do expect(RobotToTest.prefix).to eq('Robot') end end It tries to write a passing RSpec spec off the bat. It does fancy analysis to predict the values it could feed to the API of a class. To be more specific: - Analyzes all vars and methods definitions in app/models- Checks what arguments does a testable method in app/models/robot_to_test.rbneed - Searches for such variable or method name in methods in analyzed - Selects the most probable value by how many times it was repeated in code - Runs the RSpec and fills in the expected values of the test with those returned by RSpec For more things it can currently do check test files Say you are writing some new feature on your existing project. Before writing that, you probably want to test out the current functionality. But who has time for that? You let Zapata create that quick spec for you. Think of it as a current functionality lock. Write more code and when you're happy with the result - lock it up again. Add zapatato your Gemfile. It currently only works if the library is added to the Gemfile. gem 'zapata', groups: %w(development test) To use run sh zapata generate app/models/model_name.rb To ignore other files and analyze a single model you want to generate a spec for: sh zapata generate app/models/model_name.rb --single It is encouraged by somehow managing to bring a cake to your house. I promise, I will really try. This is a great project to understand language architecture in general. A project to let your free and expressionistic side shine through by leaving meta hacks and rainbows everywhere. Thank you to everyone who do. I strongly believe that this can make the developer job less robotic and more creative. git checkout -b my-new-feature) git commit -am 'Add some feature') git push origin my-new-feature) To install, run: sh cd zapata script/bootstrap For specs: script/test or bundle exec rspec --pattern "spec/*_spec.rb" I am well aware that this is featured in Ruby Weekly 223. On that note I'd like to thank everybody who helped it shine through. Special thanks to my comrade @jpalumickas, with whom we share a vision of a better world. Also - thank you @edgibbs, for being the early contributor. @morron - for caring. Huge thanks to @marcinruszkiewicz for reviving this gem to life in 2019/2020. Also additional thanks to @jpalumickas for all the extra fixes and modernizing the codebase. This would not be done without you all. Copyright (c) 2014-2018 Justas, Andrew, Ed, Dmitry, Domas. See LICENSE for details.
https://xscode.com/Nedomas/zapata
CC-MAIN-2022-05
refinedweb
634
59.4
Redux is often criticized for requiring a lot of boilerplate code to make anything happen. One of the primary offenders is the action creator – a function that exists solely to return a plain object. They often seem like excessive abstraction for the sake of abstraction. This post will go over why action creators exist, why they’re worth using, and when you can skip them. Why Write Action Creators At All? It’s a fair question. In Redux, actions are plain objects, like this one: { type: USER_LOGGED_IN } An action usually represents some kind of event – like the beginning of an API call, or a user logging in. Because it can be error-prone and annoying to type out these action objects by hand whenever you need one (or, let’s be honest – copy and paste them), it’s common to hand off the creation to an action creator, like this one: function userLoggedIn() { return { type: USER_LOGGED_IN }; } An action creator is a plain function that returns an action object. Right about here is where the complaint of “boilerplate” comes up. A whole function, just to return a simple object? Do you really need an action creator for each and every tiny action? Well, no. You don’t really. If an action is extremely simple – just a type and nothing else – it might not be worth making an action creator for it. If you feel burdened by the boilerplate, don’t write the boilerplate. It’s your code, after all :) When Are Action Creators Useful? The example above was a very simple action. As simple as they come. Maybe your action is more complicated, though. Maybe it looks something like this: { type: USER_LOGGED_IN, payload: { username: "Somebody", email: "somebody@somewhere.com", eventDate: "2017-02-09T02:29:15.952Z" } } This action still represents a user logging in, but it’s more complex than before. It carries a payload of data related to the action. It’s up to you whether you put the data at the top level, or inside a payload key, or even follow the Flux Standard Action guidelines. The format doesn’t matter so much. This is what’s important: when you copy-and-paste an action in multiple places, change is harder. If the backend devs decide that loginDate is a better name than eventDate, you’ve gotta track down every occurrence and update it. Or, if keeping data under the payload key is causing you anguish, you have to find every usage and change its structure. This problem is what action creators exist to solve. Simply offload the creation to an action creator function: function userLoggedIn(username, email, loginDate) { type: USER_LOGGED_IN, payload: { username, email, loginDate }; } And now, any time you need to dispatch a USER_LOGGED_IN action, you just call this function. Want to refactor the action’s structure later? Easy – it’s only in one place. Want to change its type to USER_LOGIN_EVENT or something? Go for it. Mix and Match? Or Consistency Throughout? The choice to use action creators exists on a spectrum. Consistent & Maintainable You can create an action creator for every single action – even the tiny ones. This will give you the best maintainability, because everything is abstracted into a function. And, if you have a bit of an OCD streak like I do, you’ll enjoy the consistency from having everything using the same pattern. Least Boilerplate On the other hand, you can eschew action creators entirely. For simple apps, or those with simple actions, this is a perfectly reasonable option. Sometimes they’re just not worth the effort. If your app is something you’re going to eventually throw away, or it needs to be done yesterday (“refactor it later!”), skipping action creators could be a good option. Or, hell, if you just hate them. No shame. You can always refactor if you change your mind. Mix and Match There’s a middle ground, if you don’t mind some inconsistency. You can make action creators for the complex actions (anything with more than a type), and skip them for the simple actions. Or decide case-by-case: if an action will only ever be used in one place, maybe just don’t make an action creator for that one. Fourth Option: Outsource It There is a popular library called redux-actions which reduces the code required to make an action creator. It turns simple actions from this: function userLoggedIn() { return { type: USER_LOGGED_IN }; } Into this: import { createAction } from 'redux-actions'; const userLoggedIn = createAction('USER_LOGGED_IN'); The API for redux-actions is simple and terse. Its docs are straightforward and full of examples. Brush up on your ES6 knowledge before reading, though. If you’re looking for maintainability, consistency, and less boilerplate, check out redux-actions. Wrap Up We went over the pros and cons of action creators – how they make code easier to refactor at the expense of a bit more boilerplate. We also looked at some options for reducing the boilerplate, and how you don’t have to choose between “all action creators all the time” and “no action creators ever.” Mix and match as you see fit. It’s your code. If you found this helpful, sign up to my newsletter below. I write articles like this every week or so. For a step-by-step approach to learning React,
https://daveceddia.com/redux-action-creators/
CC-MAIN-2017-51
refinedweb
887
74.39
I tried to write a code that will look for a specific word inside a string and that will count it's place within the string . If the word doesn't exist inside the string, it should print that the word wasn't found. For example, for the sentence "I am late" , for "late" the result should be 3. int count=0,i=0,j=0,k; char word[30]; getchar(); gets); } The problem is that for every sentence entered, it prints: The word %s is not found. I assumed that it skips for some reason the first part, and goes straight into word is not found, but even after debugging I couldn't catch the moment and reason why it skips. Note that i++ appears twice in the main loop, once conditionally and once unconditionally. The fact that it appears twice means that when a matching letter is found, i is incremented twice. The intention behind your code could be realized by getting rid of the conditional i++. Making this change and getting rid of the getchar() (which seems pointless from my point of view since it just discards the first letter of the input) and replacing gets by a not-quite-perfect use of fgets yields (with removed lines commented out): #include <stdio.h> #include <string.h> int main(void){ int count=0,i=0,j=0,k; char * arr = "I am late"; char word[30]; //getchar(); fgets(word,30,stdin); strtok(word,"\n"); //trick for stripping off newline of nonempty); return 0; } When I run it and enter late I get the result: The word late is placed in the 2 place. Which seems to be almost what you want (there is an off-by-one error if you wanted the number 3). But, don't celebrate too soon since if you run it again with the input mate you get: The word mate is placed in the 2 place. Your code (once fixed this way) is really testing if the letters of the input word appear in order in arr, but doesn't check if the letters appear next to each other. You need to rethink your approach.
http://www.dlxedu.com/askdetail/3/f8b7f57a66f8493fc46f27a41b1d3979.html
CC-MAIN-2018-47
refinedweb
362
74.53
I'm becoming increasingly concerned that C++11's support for move semantics is leading some people to conclude that we no longer have to pay as much attention to the cost of copying objects as we used to. "Many copies will silently become moves," they exclaim, "and moves are cheap!" Such reasoning is invalid in a number of ways. First, not all copy requests can be replaced by moves. Only copy requests for rvalues are eligible for the optimization. Second, not all types support move operations that are more efficient than copying operations. An example is a std::array<double, 1000>. Third, even types that support efficient move operations may support them only some of the time. Case in point: std::string. It supports moves, but in cases where std::string is implemented using SSO (the small string optimization), small strings are just as expensive to move as to copy! What it means to be "small" is up to the implementation. Unless I'm misreading the source files, std::strings with a capacity of up to 15 are "small" in Visual C++ 11 beta, so std::string objects of up to that capacity will not benefit when copies become moves. (The SSO buffer size seems to be hardwired to be 16 bytes in VC11, so the maximum capacity of a std::wstring that fits in the SSO buffer is smaller: 7 characters.) gcc 4.7 seems to continue to use reference-counting instead of SSO for its std::string implementation. This is non-conforming in C++11 (reference-counting may no longer be used for std::string), and it looks like gcc is aware that it must be changed. However, gcc 4.7 offers the non-standard __versa_string with a std::basic_string-compatible interface (other than the name of the template and the namespace in which it's located), and __versa_string offers the SSO. In this case, the maximum capacity of "small" strings seems to be hardwired to 15 characters (not bytes). While googling around for a good page to link to for the term "small string optimization" above, I came across John Ahlgren's blog entry of March 30 on how SSO interacts with move semantics. He refers to the fact that short strings with the SSO move more slowly than longer strings as the "small string deterioration" :-) Scott Tuesday, April 10, 2012 11 comments: I mostly agree, but I think this point needs some clarification: > Case in point: std::string. It supports moves, but in cases where std::string > is implemented using SSO (the small string optimization), small strings are > just as expensive to move as to copy! I think the right thing to say here is, "small strings are just as cheap to copy as to move!" This is not a pedantic distinction -- the situation is that it does not benefit further from move because it is already optimized! There really is a difference between "copy is as fast as move" (correct here) vs. "move is as slow as copy" when copy is already not deep (i.e., not involving reallocations). @Herb: Your viewpoint is legitimate, of course, but the fact that the efficiency of move vis-a-vis copy is dependent on the value of the string is something that is likely to surprise many people, I think, especially in view of John Ahlgren's measurements showing that adding a single character to a string can increase the speed of moving it by a factor of three. It's a peculiar definition of "optimized" when adding data to the payload improves its performance significantly. Scott @Herb: If std::string was implemented without SSO, it would copy the pointer (usually 4 or 8 bytes) instead of the 16 bytes (in the worst case). It's not a huge difference, and it's always a constant time penalty since stack memory is fixed-sized (C++ doesn't support VLAs). So if I understand your argument, "small strings are almost as cheap to copy as to move"? It's easy to understand Scott's concern when programmers are dealing with objects that have a mix of large stack and free store memory - the penalty would still be the constant amount of stack that needs to be copied, but the move operation gives the illusion that it should happen much faster than what would be (I don't think this is a concern with any STL containers). I am wondering whether SSO is platform dependent or more precise, whether it also holds up on embedded devices like Smartphones (e.g. ARM) since the instruction set is different. @LCID Fire: The small string optimization (SSO) is a library-level optimization that's independent of machine architecture. Either the standard library that ships with your compiler implements it, or it doesn't. @all: Actually there are lots of tradeoffs here worth experimenting with. For example, if you have 8-byte pointers and can store 15 characters without dynamic allocation, once you do have to allocate memory, do you store the end() pointer in the local memory, which makes size() (and maybe some other things) faster, or in the dynamic memory, which makes move faster? @Scott: it's not that we don't have to pay attention to the cost of copies—the cost of copying hasn't changed. What's new is that lots of things that used to copy don't anymore, so we can stop reflexively distorting code (e.g. with "out parameters") to avoid copies in those cases where copies have become moves. @Dave: Regarding "What's new is that lots of things that used to copy don't anymore, so we can stop reflexively distorting code (e.g. with "out parameters") to avoid copies in those cases where copies have become moves.", such blanket reasoning is precisely my concern. I agree that this is valid reasoning if you know that the type supports efficient moving, but not all types support efficient moving (again I mention std::array<1000, int>), and if you are writing a template, you typically don't know if the types involved support move at all. The prospective guideline I've been kicking around is "Assume that move operations are neither present nor cheap." If you know that the assumption does not hold for the types you are using, great, take advantage of that knowledge. But in the same way that we generally assume that copying is expensive unless we have specific information to the contrary, we should assume that moving is no cheaper than copying unless we somehow know better. @Scott: I think you should re-read what I wrote before you call it "blanket reasoning." It was qualified in at least two ways. I have never told anyone, "don't worry, be happy, copies are fast now" or "all copies have turned into moves." And I don't believe that anything I've said even sounds remotely like that. Also, allow me to quote an argument from Martin B. that showed up on comp.lang.c++.moderated today, one that I often forget to make myself: "You should consider the issue of aliasing. It may be cheaper to pass a 4-int rectangle by const reference, but using it may be more expensive because it's harder for the compiler to be sure it is not changed through an alias." The compiler doesn't generally optimize based on constness because of aliasing and separate compilation. It's actually not const but pass-by-value that lets the compiler make the optimizations that most people are hoping for in those circumstances. I you're looking for a description that I won't object to of my position, use this one: There were always good reasons to seriously consider value semantics—an approach whose benefits have been under-recognized, partly due to fear of copying costs—as a normal part of your programming practice, and there are even more good reasons to do so today. @Scott: 1. It should not be a surprise to anyone that the efficiency of copying a container depends on its content. 2. If they have done C++-level close-to-the-metal programming with performance concerns for a while, they will be familiar with the idea that such correlations might be nonlinear and counterintuitive. 3. Copying those 15 bytes is still the fasted you get without move semantics, so — as Herb already said — you haven't lost anything. There's just an area (which is already fast) where you might haven't gained something. 4. If copying 15 bytes (that's just 2 doubles!) is of a performance concern to someone, they should not rely on guesses anyway, but profile and measure. If it then turns out that adding a '\0' to the string makes it faster, that's on par with strange things like adding NOPs into code making it faster. (see #2) 5. On 64bit machines, copying a pointer and a std::size_t might be 16 bytes, too. std::array< 1000,double > should be std::array< double,1000 >? @Marmot: Yes, of course, thanks for pointing this out. I've fixed it in the post. Scott
http://scottmeyers.blogspot.com/2012/04/stdstring-sso-and-move-semantics.html
CC-MAIN-2019-18
refinedweb
1,528
67.89
⚠️ To use with Swift 2.3 please ensure you are using == 0.4.1 ⚠️ ⚠️ To use with Swift 3.x please ensure you are using >= 0.5.0 ⚠️ ⚠️ To use with Swift 4.x please ensure you are using >= 0.6.1 ⚠️ ⚠️ To use with Swift 4.2 please ensure you are using >= 0.7.1 ⚠️ ⚠️ To use with Swift 5.0 please ensure you are using >= 0.8.0 ⚠️ PurposePurpose It's just started for my personal app for iPhone. Though, it can not be customized as much as you want, you can use Smooth Freehand Drawing View easily. I made Palette and ToolBar for using Canvas, so you don't have to use Palette and ToolBar. NXDrawKit is a set of classes designed to use drawable view easily. This framework consists of 3 kinds of views. Canvasproviding redo, undo, clear, save and load image is a view for drawing. Palettecalls delegate with color, alpha and width when user clicks the button. ToolBarrepresents the features of Canvas, and can show the status of Canvas. ScreenshotScreenshot InstallationInstallation CocoaPodsCocoaPods You can use CocoaPods to install NXDrawKit by adding it to your Podfile: platform :ios, '8.0' use_frameworks! pod 'NXDrawKit' To get the full benefits import NXDrawKit wherever you import UIKit import UIKit import NXDrawKit CarthageCarthage Create a Cartfile that lists the framework and run carthage bootstrap. Follow the instructions to add $(SRCROOT)/Carthage/Build/iOS/NXDrawKit.framework to an iOS project. github "nicejinux/NXDrawKit" ManuallyManually - Download and drop /NXDrawKitfolder in your project. - Congratulations! ComponentsComponents CanvasCanvas - Delegate- Delegate Canvas will call the delegate when user draw or save image. - Delegate provides user stroke image, background image and merged image. - User should provide the Brushto Canvasfor drawing. // optional func canvas(canvas: Canvas, didUpdateDrawing drawing: Drawing, mergedImage image: UIImage?) func canvas(canvas: Canvas, didSaveDrawing drawing: Drawing, mergedImage image: UIImage?) // required func brush() -> Brush? - Model- Model public class Drawing: NSObject { public var stroke: UIImage? public var background: UIImage? public init(stroke: UIImage? = nil, background: UIImage? = nil) { self.stroke = stroke self.background = background } } public class Brush: NSObject { public var color: UIColor = UIColor.blackColor() public var width: CGFloat = 5.0 public var alpha: CGFloat = 1.0 } - Public Methods- Public Methods - User can set background image. - User can undo, redo or clear the Canvas. (Maximum history size is 50) - User can save current stroke and background internally, then Canvascalls didSaveDrawing: delegate func update(backgroundImage: UIImage?) func undo() func redo() func clear() func save() PalettePalette Palettehas 12 buttons for color, 3 buttons for alpha and 4 buttons for width of brush. - You can customize color, value of alpha and width of brush with delegate, - You can't customize number of buttons. - Delegate- Delegate Palettewill call the delegate when user clicks the color, alpha or width button. - You can customize the color, alpha or width with delegate. (all delegates are optional) func didChangeBrushColor(color: UIColor) func didChangeBrushAlpha(alpha: CGFloat) func didChangeBrushWidth(width: CGFloat) - tag can be 1 ... 12 - If you return nil, the color of tag will set with default color provided by NXDrawKit. - If you return clearColor, the color of tag will be Eraser. func colorWithTag(tag: NSInteger) -> UIColor? - tag can be 1 ... 3 - If you return -1, the alpha of tag will set with default alpha provided by NXDrawKit. func alphaWithTag(tag: NSInteger) -> CGFloat - tag can be 1 ... 4 - If you return -1, the width of tag will set with default width provided by NXDrawKit. func widthWithTag(tag: NSInteger) -> CGFloat - Public Method- Public Method func currentBrush() -> Brush ToolBarToolBar - Public Properties- Public Properties - All buttons are set with default values without #selector. - If you want to use buttons on the ToolBar, you have to add #selector for each buttons. var undoButton: UIButton? var redoButton: UIButton? var saveButton: UIButton? var loadButton: UIButton? var clearButton: UIButton? UIImage ExtensionUIImage Extension - This extension can make you get PNG or JPEG format image directly for sharing or saving from what you draw. - All methods can return nil, so you should check before use whether it's nil or not. public extension UIImage { @objc public func asPNGData() -> Data? { return self.pngData() } @objc public func asJPEGData(_ quality: CGFloat) -> Data? { return self.jpegData(compressionQuality: quality); } @objc public func asPNGImage() -> UIImage? { if let data = self.asPNGData() { return UIImage(data: data) } return nil } @objc public func asJPGImage(_ quality: CGFloat) -> UIImage? { if let data = self.asJPEGData(quality) { return UIImage(data: data) } return nil } } Version HistoryVersion History - 0.8.0 - UPDATE: Support Xcode10, Swift 5.0 - 0.7.1 - UPDATE: Support Xcode10, Swift 4.2 - 0.6.1 - UPDATE: Support Xcode9, Swift 4.0 - 0.5.1 - UPDATE: Support Xcode8, Swift 3.0 - 0.4.1 - UPDATE: Support Xcode8, Swift 2.3 - 0.3.4 - FIX: Removing background image issue - 0.3.0 - ADD: Eraser added - 0.2.0 - CHANGE: Data model renamed Paperto Drawing - 0.1.0 - Release Will be improvedWill be improved - Swift style code - There is no Eraser, so user can't erase stroke. - added v0.2.0 - User can't remove background image after it's set. Paletteand ToolBarcan't customize easily. AuthorAuthor This is Jinwook Jeon. I've been working as an iOS developer in Korea. This is my first Swift project, so there can be lots of weird things in this framework. I'm waiting for your comments, suggestions, fixes, everything what you want to say. Feel free to contact me. MIT LicenseMIT License Copyright (c) 2016 Jinwook Je.
http://cocoapods.org/pods/NXDrawKit
CC-MAIN-2020-34
refinedweb
896
53.27
I meet a problem about system function. If I run echo -e '\x2f' / int main(int argc, char* argv[], char** envp) { printf("The command is :%s\n",argv[1]); system( argv[1] ); return 0; } The command is :echo -e '\x2f' -e \x2f system -e \x2f / # I used \\ because python will transfer \x2f to / automatially command="echo -e '\\x2f'" p=process(executable='/home/cmd2',argv= ['/home/cmd2',command]) print (p.readall()) Firstly, echo command can output differently between sh and bash. Ref: bash -c "echo -e '\x2f'" # Output : / sh -c "echo -e '\x2f'" # Output : -e / In order to have Python spit out the same, something like below should work. (For your reference, included the same implementation with subprocess) import os import subprocess command = "echo -e '\\x2f'" os.system( command ) # Output : -e / subprocess.call( command , shell=True ) # Output : -e / bashcmd = "bash -c \"echo -e '\x2f'\"" os.system( bashcmd ) # Output : / subprocess.call( bashcmd , shell=True ) # Output : / I am uncertain of how you got -e \x2f as your output though.
https://codedump.io/share/nQW1XfTACm6c/1/why-can39t-the-39system39-function-in-linux-run-this-shellscript
CC-MAIN-2017-09
refinedweb
166
63.59
KDL This is a Dart implementation of the KDL Document Language Usage import 'package:kdl/kdl.dart'; main() { var document = Kdl.parseDocument(someString); } You can optionally provide your own type annotation handlers: KDL.parseDocument(someString, typeParsers: { 'foo': (value, type) { return Foo(value.value, type: type) }, }); The foo function will be called with instances of KdlValue or KdlNode with the type annotation (foo). Parsers are expected to take the KdlValue or KdlNode, and the type annotation itself, as arguments, and is expected to return either an instance of KdlValue or KdlNode (depending on the input type) or null to return the original value as is. Take a look at the built in parsers as a reference. Run the tests To run the full test suite: dart test To run a single test file: dart test test/parser_test.dart Contributing Bug reports and pull requests are welcome on GitHub at. License The gem is available as open source under the terms of the MIT License.
https://pub.dev/documentation/kdl/latest/
CC-MAIN-2022-33
refinedweb
163
64.51
#include <unistd.h> #include <fcntl.h> int fcntl(int fd, int cmd); int fcntl(int fd, int cmd, long arg); int fcntl(int fd, int cmd, struct flock *lock);. The.) Advisory locks are not enforced and are useful only between cooperating processes. Mandatory locks are enforced for all processes., unless the O_NONBLOCK flag was specified to open(), in which case the system call will return with the error EWOULDBLOCK.. On error, -1 is returned, and errno is set appropriately. Since kernel 2.0, there is no interaction between the types of lock placed by flock(2) and fcntl(2). POSIX 1003. SVr4 documents additional EIO, ENOLINK and EOVERFLOW error conditions.
http://www.linuxmanpages.com/man2/fcntl.2.php
crawl-002
refinedweb
110
68.47
I have a vector/array of n elements. I want to choose m elements. The choices must be fair / deterministic -- equally many from each subsection. With m=10, n=20 it is easy: just take every second element. But how to do it in the general case? Do I have to calculate the LCD? Here is a quick example: from math import ceil def takespread(sequence, num): length = float(len(sequence)) for i in range(num): yield sequence[int(ceil(i * length / num))] math.ceil is used because without it, the chosen indexes will be weighted too much toward the beginning of each implicit subsection, and as a result the list as a whole.
https://codedump.io/share/SLHf0F88TZoz/1/choose-m-evenly-spaced-elements-from-a-sequence-of-length-n
CC-MAIN-2016-44
refinedweb
114
66.84
Installation¶ Kiwi can be found at the Python Package Index (PyPI) . Requirements¶ Kiwi was developed in Python 2.7 but should work also with Python 3. Other than Python, it depends on the following packages: - matplotlib >= 1.3.1, <=1.4.3 - mygene >= 2.1.0 - networkx >= 1.8.1 - numpy >= 1.8.0 - pandas >= 0.13.1 - scipy >= 0.13.3, <=0.16.0 - six >=1.5 Package installation¶ There a three ways to install packages from PyPI. More information can be found in PyPI. Pip¶ This way is recommended to install dependencies automatically, if the Python path is set correctly in your system. Get to the command prompt and type: > pip install KiwiDist Distutils¶ This package comes in bundle with Python. Download the package, extract it, get to the command prompt, navigate to the root directory, and type: > python setup.py install The distribution will be installed into site-packages directory of the Python interpreter used to run the setup.py install command. No dependencies will be installed! Also, make sure to have admin privilege for installation, otherwise act as root user: > sudo python setup.py install To check if the installation worked correctly, open the Python interpreter and type: > import kiwi If no error is raised, then you are good to go! To get started, open the Python interpreter and type: > import kiwi > ?kiwi.plot Source¶. Package update¶ There are two recommended ways to check for updates, depending on which environment was used to install Kiwi. Canopy¶ If Kiwi was first installed in Canopy, to update the library in this environment, issue the following commands in the prompt window: %system pip install KiwiDist --upgrade (-U --no-deps, if no dependencies should be upgrade) To check the current version: %system pip show KiwiDist To check the current path: import kiwi; kiwi.__path__
https://pythonhosted.org/KiwiDist/installation.html
CC-MAIN-2019-04
refinedweb
304
59.19
Disgusted! edited December 1969 in Technical Help (nuts n bolts) Are all the technical support on vacation?! I submitted a ticket THREE DAYS AGO because the DAZ Horse 2 starter package will not work and your 1-800 number isn't even available! I am appalled and irate to put it nicely! Order # 100390622 I can't get Horse 2 to load, it says: Traceback (most recent call last): File "C:\Users\Public\Documents\Poser Pro 2012 Content\Runtime\libraries\Character\DAZ Horse 2\DAZ Horse 2.py", line 1, in import dson.dzdsonimporter ImportError: No module named dson.dzdsonimporter This is the last time I purchase anything from this website. I'll start by saying I'm guessing here as I don't use Poser Pro (and therefore don't use Genesis) I only use Poser8. The Horse you purchased is based on Gensis and the file that your Poser can't find looks like the Genesis DSON Import plug-in... Which you will need for Poser to use Genesis based content. Are there two versions of the horse in your Runtime? a regular Poser native one and a Genesis version. The product page for the Horse does say it is Genesis and yet Poser Native, so I'm guessing you may get two versions when you buy. Also worth having a look at your downloads page to see if there were options to download two different versions for which programme you needed it for. Hope this helps. There's Poser companion and Daz version and I got the Dson importer when it was free. I installed everything yet still having this issue. What angers me more than anything is that I have not received assistance from a staff member and have had to come to this board regarding this matter. Well sorry i can't help you with the horse. I think that Daz say they'll try to address support tickets within 5 days, It's not like they have a big call center with lots of support staff. If you post your question down in the Poser forum there are several people down there who could help you more as I guess it's a Poser problem and not so much a Daz one. :) I wish the 1-800 numbers were working, but I appreciate the user replies. Some people are using the Horse in Poser, so it does work. I suggest you let me move this thread to the Poser Forum, where you are more likely to get some informed poser feedback and assistance. Would you like me to move it over there? BTW it does help us to help you if we know a few extra things, like are you using a PC or a Mac and which OS you are using. Also have you installed SR3.1 for Poser 2012 Frequently you will find that you will get enough helpful assistance from people in the forums that you will not even need to contact support. And another quick post to say that you will get more help if you edit your thread title to reflect the problem you are having instead of the one you have. I understand that you may so angry with purchasing something doesn't work as well as you hope. I'm here since 2004 and can tell you lot of peoples had the same reaction and I was one of them ... I don't know why i'm still here, maybe it's because i like the interface of daz studio either than my Poser Pro 2012 ... Anyway , in my case it's a hobby, so i hope this product will work better so far. I did not bought Horse 2 now, because i'm waiting that someone will put animated routine like " Go Figure ! " for Animate 2. If they, i will if not i wont ! They are supposed to have a 10 day return policy ... So ask for a refund or credit ! ( it means probably a credit ... ) Live long and Prosper my friend ! It's 30 days and if you ask for refund rather than credit they will oblige.
http://www.daz3d.com/forums/viewthread/12508/
CC-MAIN-2015-48
refinedweb
692
80.62
C++ program to convert infix to postfix Hello. In this tutorial, we are going to learn how to convert an infix notation to postfix notation using the stack data structure in C++ program. What are infix and postfix notations? Infix and postfix are different ways to write mathematical operations. In infix notation we write the first operand, then we write the operator and then we write the second operator. For example x + y, x * y etc. In postfix notation, we write the first operand, followed by the second operand and then we write the operator. For example xy+, xy*. There are two advantages of using a postfix notation over an infix notation. These are - Postfix notation does not require parentheses, precedence rules and associative rules. - We can evaluate the value of the expression in one traversal only. While converting infix to postfix we use the associative and precedence rule of the operators (BODMAS) which we are familiar with from our school days. Let us understand the problem statement. We are given a string denoting infix notation and we need to convert it to its equivalent postfix notation. We are going to use stack to solve the problem. Let us jump to the code and then we will understand the code. Code (Infix to Postfix) Below is our given C++ code to convert infix into postfix: #include<bits/stdc++.h> using namespace std; int precedence(char m) { if(m == '^') return 3; else if(m == '*' || m == '/') return 2; else if(m == '+' || m == '-') return 1; } void infix_to_postfix(string t) { stack<char> s; int l = t.length(); string ans; for(int i = 0; i < l; i++) { if((t[i] >= 'a' && t[i] <= 'z') || (t[i] >= 'A' && t[i] <= 'Z')) ans+=t[i]; else if(t[i] == '(') s.push('('); else if(t[i] == ')') { while(s.top() != '(') { char c = s.top(); ans += c; s.pop(); } if(s.top() == '(') { char c = s.top(); s.pop(); } } else{ while(s.empty()==false && precedence(t[i]) <= precedence(s.top())) { char c = s.top(); ans += c; s.pop(); } s.push(t[i]); } } while(s.empty() == flase) { char c = s.top(); ans += c; s.pop(); } cout << ans << endl; } int main() { string s = "a+b*c"; infix_to_postfix(s); return 0; } Output – abc*+ We use the stack to store the operators. We traverse the string characters one by one. Let x be the character we are traversing. If x is : - Operand: Directly add to the output string. - Left parenthesis[“(“]: Push to the stack. - Right parenthesis[“)”]: Pop the items one by one from the stack till we find left parenthesis. Output the popped characters. - Operator: If the stack is empty then push x else compare the precedence of x with stack top. (1). If the precedence of x > precedence of stack top then push x. (2). Precedence of x < precedence of stack top, pop the stack top one by one and output until a lower precedence operator is found. Then push x to stack. After this just pop the remaining items from stack one by one and append to the answer. Hope you understood the code. Any doubts are welcomed in the comment section. Thank you. Knuth-Morris-Pratt (KMP) Algorithm in C++
https://www.codespeedy.com/c-program-to-convert-infix-to-postfix/
CC-MAIN-2022-27
refinedweb
528
68.97
this is my javascript code and i am not understanding the mistake in this,please help me? this is my javascript code and i am not understanding the mistake in this,please help me? <html> <h2>Form Validation</h2> <script language = "Javascript"> function checkEmail java 2 d array program java 2 d array program write a program 2-d matrix addition through user's input? Hi Friend, Try the following code: import java.util.*; class MatrixAddition{ public static void main(String[] args struts struts <p>hi here is my code in struts i want to validate my...=0; //String d=daf.get("dob"); //DateFormat sdf=new SimpleDateFormat("dd-mm-yyyy"); //Date date=(Date)sdf.parse(d struts code - Struts struts code In STRUTS FRAMEWORK we have a login form with fields USERNAME: In this admin can login and also narmal uses can log...:// Thanks... to write code Java Glossary Term - D Java Glossary Term - D DecimalFormat java.text.DecimalFormat is the class... while loop is a control flow statement that allows a certain code to be executed code for this is code for this is a b c d c b a a b c c b a a b b a a a code Code Problem - Struts Code Problem Sir, am using struts for my application.i want to uses session variable value in action class to send that values as parameter to function.ex.when i login into page,i will welcome with corresponding user homepage struts - Struts struts Hi, I need the example programs for shopping cart using struts with my sql. Please send the examples code as soon as possible. please send it immediately. Regards, Valarmathi Hi Friend, Please the code in struts. when i click on the submit button. It is showing the blank page. Pls respond soon its urgent. Thanks in advance. public class LOGINAction extends Action.0 - Struts Struts 2.0 Hi ALL, I am getting following error when I am trying to use tag. tag 'select', field 'list': The requested list key 'day' could... mistake. Thanks, Niranjan struts pls review my code - Struts Java Compilation error. Hibernate code problem. Struts first example - Hibernate Java Compilation error. Hibernate code problem. Struts first example Java Compilation error. Hibernate code problem. Struts first example struts 2.1.8 Login Form Struts 2.1.8 Login Form  ... in Struts 2.8.1. The Struts 2 framework provides tags for creating the UI forms... application in Struts 2.8.1. In the next session we will also learn how logout - Struts logout how to make code in struts if i click the logout button then no body can back refresh the page , after logout nobody will able to check...(); //... ----------------------------------- Visit for more - Struts ); /** * Content-Disposition: form-data; name="file"; filename="D:\testing.xls... = sheet.getCell("C"+j).getContents(); String city = sheet.getCell("D"+j Java - Struts Java hello friends, i am using struts, in that i am using tiles framework. here i wrote the following code in tiles-def.xml in struts-config file i wrote the following action tag Properties File IN Struts - Struts the detail along with code and also entry about properties into configuration application struts application hi, i can write a struts application in this first i can write enter data through form sidthen it will successfully saved... not enter any data that time also it will saved into databaseprint("code sample
http://www.roseindia.net/tutorialhelp/comment/47923
CC-MAIN-2014-42
refinedweb
569
67.76
Algorithms can detect outliers, but how do you select algorithms? A common method for detecting fraud is to look for outliers in data. It’s a fair approach: even if the detection doesn’t immediately imply fraud it can be a good candidate for further investigation. Still, how might we go about selecting hyper-parameters (or even the algorithm)? The hard part is that we have very little to go on. Just like clustering there’s no label. It is incredibly though to argue if a certain model is appropriate for a use-case. Luckily there’s a small trick that can help. How about we try to find outliers that simply correlate with fraudulent cases? It might be surprise to find out that scikit learn has support for this but it occurs via a slightly unusual pattern. I will demonstrate an approach using this dataset from kaggle. It’s an unbalanced dataset meant for a fraud usecase. import numpy as np import pandas as pd import matplotlib.pylab as plt df = pd.read_csv("creditcard.csv").rename(str.lower, axis=1) X, y = df.drop(columns=["class", "time", "amount"]), df['class'] With the dataset loaded I’ll run an IsolationForest. Note that I am not labelling, I am merely looking for outliers. from sklearn.ensemble import IsolationForest forest = IsolationForest(contamination=0.1, behaviour="new").fit(X) We can look at the algorithm results but we’re mostly interested in finding a good value for the contamination parameter. One thing you could do manually is to calculate, say, the precision of the predictions. from sklearn.metrics import precision_score, recall_score converted = np.where(forest.predict(X) == 1, 0, 1) precision_score(y, converted) Note that we’re using np.where here because an outlier detector in scikit learn will output either -1 or +1 while the fraud label will be 0 or 1. We could now go and write a for-loop to consider all the values but this is a lazy hack. It is much more preferable to cross validate the hyperparamter in a gridsearch. You might be wondering how to write a gridsearch that might facilitate this though. After all, we need to manually convert the models output to something the precision score can use and we need to figure out a way to allow our y and X values to also be cross validated. Also, generally, scikit learn has a pattern of using sklearn.metrics.make_scorer that accepts functions of signature score(y_true, y_pred). So how on earth are we going to get this to work? The main trick is to recognise two things: score(model, X, y)and if you write a function this way you don’t need make_scorer. .fix(X)can also accept .fit(X, y). In this case the yvalue is ignored by the model but can be used for any other part of the pipeline. This includes metrics. These two facts combined give us a nice pattern: from sklearn.metrics import precision_score, recall_score from sklearn.model_selection import GridSearchCV df_subset = df.sort_values('class', ascending=False)[:80000] X_subset = df_subset.drop(columns=['amount', 'class', 'time']).values y_subset = df_subset['class'] def outlier_precision(mod, X, y): preds = mod.predict(X) return precision_score(y, np.where(preds == 1, 0, 1)) def outlier_recall(mod, X, y): preds = mod.predict(X) return recall_score(y, np.where(preds == 1, 0, 1)) forest = IsolationForest(contamination=0.1, behaviour="new", max_features=0.2) mod = GridSearchCV(estimator=forest, cv=5, n_jobs=-1, scoring={"precision": outlier_precision, "recall": outlier_recall}, refit="precision", param_grid={'contamination': np.linspace(0.0001, 0.02, 30)}) mod.fit(X, y) This gridsearch takes a while but afterwards we can visualise the following effect: The pattern works! Note that in this dataset there are 492 positive cases out of 284807. It’s pretty interesting to see that we can get near 10% precision/recall with just an outlier detection algorithm considering that the base rate should be near 0.17%. This is a useful pattern but I would warn against using this as a “one size fits all” approach. A better approach detecting outliers is to have multiple detectors that each focus on a different part. The pattern that is explained here is a great way to generate such a candidate but it should not be the only thing that is detecting. Think about it. Suppose that you are able to come up with 100 valid but alternative methods of detecting if something is “out of the ordinary” then it becomes a lot easier allocate the expensive investigative resources. When suspicion overlaps the odds of finding something that deserves discovery increases. Think about your case: Is there unexpected behavior on an account on the short term/long term? Is there unexpected behavior on a product on the short/long term? When lots of small systems detect something that deserves attention it becomes a effective proxy to determine on how to spend your investigative resources. If you’re interested in this field of thinking in the fraud space you might be interested in this pydata talk from Eddie Bell.
https://koaning.io/posts/outliers-selection-vs-detection/
CC-MAIN-2020-16
refinedweb
842
58.79
Any news on this? Can we still have .Net Core before Spring Challenge? Fun fact: we use almost 15 years old compiler in VB.NET Any news on this? Can we still have .Net Core before Spring Challenge? Fun fact: we use almost 15 years old compiler in VB.NET It was on hold for a while, but we should have it for the Spring Challenge, as announced. What about F#? If you can install dotnet core then compiling F# with it instead of mono should be a breeze. yes, F# too of course. Wrong title of the Trello card May happen this week! They specified the month, not the year. The famous Perl6 defense. But Perl6 Christmas did happen in 2015. How is it going with .NET Core? Business got in the way, but it’s still planned to have it before Thursday. So python has numpy and scipy while C++ has … no relevent libraries as far as I can tell. Which is quite an imbalance. Did nobody ask yet for libraries like Eigen or Boost? Or don’t you support C++ libraries because of linking/include path issues? In that case: Most of Eigen and Boost would work out of the box as soon as they are installed - no linking / include paths necessary. Or is it that C++ is just too powerful already? Hi, I take the opportunity to thank you for those regular updates. I’m an Ocaml fan, and the job done is very appreciated. So good job and thank you very much to all the staff involved. Only six hours left before the event We’re deploying a minimal implementation of .Net core for the challenge: I’m sorry we couldn’t do the complete implementation While C# coders already has full language expirience, VB not even have LINQ support, so what’s the point of such update? Great, now my Ocean of Code bot is broken CS1069: The type name ‘Bitmap’ could not be found in the namespace ‘System.Drawing’. This type has been forwarded to assembly ‘System.Drawing.Common, Version=4.0.2.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51’ Consider adding a reference to that assembly. When I change my code from using System.Drawing to using System.Drawing.Common, I get: CS0234: The type or namespace name ‘Common’ does not exist in the namespace ‘System.Drawing’ (are you missing an assembly reference?) Any schedule for Python 3.8? Thanks so much for all your efforts! VB.NET is now compiled/executed by .Net core (same minimal implementation as C#: only for solo/multi games, no hyperlinking of compilation/runtime errors) (ping @mihei ) also “DEBUG” is no longer defined by the compiler when in debug (IDE) mode for C# Great news, thank you very much! Maybe the link is not what was intended… And that’s the wayyyyyy the news goes!
https://forum.codingame.com/t/languages-update/1574?page=8
CC-MAIN-2022-05
refinedweb
477
77.33
After… The MWindowBlur (Multiple Window Blur) class: The Flash document class for a test ride: And a quick example: Very nice. A couple suggestions: 1) When two windows are layered, it would be nice if the front window blurred the one behind it. 2) Presently, the blur amount seems to be a global value. Can it be set for each window individually? Awesome job. I appreciate you taking the time to create this example. I am trying to build this, but, as a newbie to AS, I am having some trouble. I can’t seem to resolve the Background or GraphicWindow data type. Any suggestions? Hey Steve, Both items are MovieClips inside the .fla library. Once you have an object in the library, you can right click it and pick “linkage” from the context menu. Check the “Export for actionscript” box, leave the other boxes alone and in the Class textbox just put “Background” (for the image you want to be blurred) or “GraphicWindow” (for the window you want to drag around). Hope that helps out.. Devon, Could you please post a .ZIP with the ActiveBlur class, FLA, and its corresponding document class? Cheers! Well, there’s really no more than what’s posted above, but since so many are asking, you can get the .fla that created the above .swf here. You’ll also need the ui package mentioned in this post to create the value slider control above – but the package isn’t necessary for general usage of the MWindowBlur class. Hi, I’ve put together a really simple timeline example to try and get this working (before trying it on a more complicated project), but it doesn’t seem to be working… can you see any reason why? //////////////////////////////////////////////////////////////////////////////// import com.onebyonedesign.extras.*; var bg:Sprite = new Sprite(); var matr:Matrix = new Matrix(); matr.createGradientBox(200, 50, 20, -50, 200); bg.graphics.beginGradientFill(“linear”, [0xff0000, 0x00ff00], [1,1], [150,255], matr); bg.graphics.drawRoundRect(100,20,200,250,20); bg.graphics.endFill(); addChild(bg); var blur:MWindowBlur=new MWindowBlur(bg,100); var box:Sprite = new Sprite(); box.graphics.beginFill(0x0000ff, 0.5); box.graphics.drawRect(0,0,100,100); box.graphics.endFill(); addChild(box); box.addEventListener(MouseEvent.MOUSE_DOWN, drag); blur.addWindow(box); function drag(e:Event) { box.removeEventListener(MouseEvent.MOUSE_DOWN, drag); box.addEventListener(MouseEvent.MOUSE_UP, drop); box.startDrag(); }//drag function drop(e:Event) { box.addEventListener(MouseEvent.MOUSE_DOWN, drag); box.removeEventListener(MouseEvent.MOUSE_UP, drop); box.stopDrag(); }//drag Hey Chris. There’s a couple things causing the problem. For some reason, the blur windows cannot be created programmatically – they have to be exported from the library or on the stage. So, if you make your box a class in the library, that will take care of the biggest problem. The other thing is that the background object should be aligned to the origin (0,0). Do those two things and it should work fine. Hey Devon’! This is awesome, but I don’t understand how I can use this, in my document? Should I’ve two movieclips, one background and one window-route in the .fla project? And how do I use the actions you have posted? Should I paste it in a normal keyframe in “actions” (by pressing F9)? Would you please make a short video how you do this? :) I need same thing to be done in AS3 Pankaj Kumar really nice comment! Maybe you need someone to read this post for you. =P
http://blog.onebyonedesign.com/actionscript/active-windows-blur/
CC-MAIN-2019-39
refinedweb
576
67.76
Here's the discussion on this topic in the mailing list: I've checked the behavior of Toolkit.getLockingKeyState()/setLockingState() on Windows XP on RI and found that those methods work weirdly. Here's a simple test demonstrating RI behavior: import java.awt.Toolkit; import java.awt.event.KeyEvent; public class Test { public static void main(String[] args) { try catch (Throwable e){ e.printStackTrace(); } } } If CapsLock was OFF at the application start, the output is as follows (comments denote what happens at that point on the keyboard): false true false 1. Turning CapsLock ON // Light goes ON false 2. Turning CapsLock OFF false 3. Turning CapsLock ON // Light goes OFF false 4. Turning CapsLock OFF false If start CapsLock was ON at the application, the ouput is as follows: true true false 1. Turning CapsLock ON // Light goes OFF true 2. Turning CapsLock OFF true 3. Turning CapsLock ON // Light goes ON true 4. Turning CapsLock OFF true In other words, the following statements seem true about the RI operation: - getLockingKeyState() returns the state of the key at the application start, calls to setLockingKeyState() and pressing the key on the keyboard do not affect it. - If the key was OFF at the application start, setLockingKeyState(false) does nothing, and setLockingKeyState(true) toggles the actual state (light on the keyboard changes state and typing (in other window) indicates the state changes immediately). - If the key was ON at the application start, setLockingKeyState(true) does nothing, and setLockingKeyState(false) toggles the actual state. This behavior clearly contradicts the specification, but I suspect it's grounded by some Windows API peculiarities. I'm not sure if we should follow specification or RI behavior, but investigation of Windows API capabilities in this area is surely required before we could make the right decision. As far as I understood setLockingState works OK on RI but getLocking state returns the key state at the start up. Right? I've tried the test on Linux, it seems to throw UnsupportedOperationException on any call to getLockingKeyState()/setLockingState() - in other words, it seems RI doesn't support this functionality on Linux. In fact, the problem turns out to be much more complex. I searched the Java.Sun.Com site for related information and found a number of them that are useful. General idea is investigating the RI behavior to provide the proper compatibility in this area is a separate non-simple task. We can implement the spec. This is not complicated on Windows. I've not investigated the issue on Linux.. So what are the problems from Windows API and Linux API sides which are prevents us from getting the state of CAPS, NUM, SCROLL and KANA LOCK keys?. Here is Toolkit.getLockingKeyState/setLockingKeyState implementation for Windows. Toolkit class uses static LockingState.getInstance() method to get platform-specific successor of base class LockingState. Windows successor WinLockingState is implemented; LinuxLockingState is added also but its methods do nothing. Note: keybd_event function is used to generate keyboard events for toggling keys. MSDN says that SendInput should be used instead, but using SendInput involves raising minimal Windows version to 0x0500 and requires changes in build files. Patch was updated: removed some copy-paste errors from LinuxLockingState class. Some improvements were made in suggested patch. Calls to keybd_event were replaces with calls to obtained pointers Attached 4423_win_nosearch.patch - it's another version of patch in which native code doesn't look for Win32 API functions through user32 library, but relies on natural dynamic linking. Wow, Ilya, this patch is great! It seems to work even better than RI does! Thank you! Just a small note - when throwing UnsupportedOperationException (when Kana key is absent, for example), RI adds a detalization message, like this: java.lang.UnsupportedOperationException: Keyboard doesn't have requested key Probably we should do the same. Vasily, I thought about it, but as far as I can see AWT usually uses strings like "Messages.getString("awt.XXX"))" for exceptions. Unfortunately, I don't know where to add appropriate string. If so, and if you know where to add string into string table, you can prepare additional patch for Toolkit.java, which will apply over both '4423_win.patch' and '4423_win_nosearch.patch'. If adding simple string right into java code is acceptable, I'll update patches. Ilya, Messages.getString("awt.XXX")) reads the messages from awt/src/main/java/common/org/apache/harmony/awt/internal/nls/messages.properties. You can put all messages you need to this file. Attaching updated patches with added message in UnsupportedOperationException. The message added is awt.29A="Keyboard doesn't have KANA key", because this exception is thrown for KANA only. Ilya, please note that UnsupportedOperationException is also thrown if totally wrong key number is provided or the code is run in Headless mode. Probably in these cases the diagnostics should be different. Vasily, thanks. I'm going to provide updated patch for Windows in next few hours, I'll take your note into account With new improved implementation I've got wrong behavior So now I'm trying to locate an issue. Regarding exception throwing: by the spec, for wrong key these methods should throw IllegalArgumentException, and for headless mode they should throw HeadlessException. So I'll leave exception message as it, and I'll use string in code (not from table), because UnsupportedOperationException will be thrown from native code. Oh, I see, then it's fine. The only thing, after the patch is complete, we should not forget to file any non-bug differences our implementation would have with RI. Latest "4423_win.patch" is implementation for Windows with several performance and structure improvements. Ilya, thanks for the patch. I've slightly modified your patch... I've made WinWTK.getLockingState and WinWTK.setLockingState methods native. Vasily, please verify that the patch works as expected.. With the patch above applied, the additional workaround patch to java.awt.Toolkit that is used in jEdit automated GUI tests (see HARMONY-3633) becomes useless and may be removed. The attached Harmony-4423-jEdit.patch patch removes all extra stuff needed for that workaround from jEdit tests framework. The patch removes the bt-2/tests/jedit_test/src/patches/harmony directory and updates build.xml, build.properties and readme.txt accordingly. Oh, I've found that similar issue for Linux is filed as HARMONY-4636. As of obsolete workaround in jEdit automated GUI tests, I've created a new JIRA, HARMONY-4659, and moved the patch there. Now this issue may be closed. The attached patch unconditionally returns false, instead of throwing exception.
https://issues.apache.org/jira/browse/HARMONY-4423?page=com.atlassian.jira.plugin.system.issuetabpanels:all-tabpanel
CC-MAIN-2015-40
refinedweb
1,089
58.69
Latest Version: This document lists the document formats that will be used by the Java Platform, Enterprise Edition (Java EE) deployment descriptors described by Java EE, and must continue to be validated against the corresponding DTD. Note that several deployment descriptors have not been updated for Java EE 5. In particular, the J2EE 1.4 deployment descriptors connector_1_5.xsd and j2ee_jaxrpc_mapping_1_1.xsd are the current versions used for Java EE 5. This document describes how to use the Java EE schemas that are described as a set of modules and provides a list of XML Schemas for each deployment descriptor. All Java EE Deployment Descriptor Schemas share the namespace,. Each schema document contains a version attribute that contains the version of the specification. For example, the XML Schema document for the Servlet specification contains the version attribute value "2.5", a version attribute. For example, servlet Deployment Descriptor instances that must be processed with the servlet 2.5 version must indicate the version within the version attribute of the instance document, for example, "2.5".. javaee_<version>.xsd This table contains the XML Schema components for Java EE 5 schema. XML Schemas specified by the J2EE 1.4 specification are available at. DTDs specified by the J2EE 1.3 specification are available at. DTDs specified by the J2EE 1.2 specification are available at.
http://java.sun.com/xml/ns/javaee/
crawl-002
refinedweb
224
52.15
Issue Type: Bug Created: 2011-04-05T03:11:35.000+0000 Last Updated: 2011-04-05T07:42:56.000+0000 Status: Closed Fix version(s): Reporter: Anthony Shireman (ashireman) Assignee: Kai Uwe (kaiuwe) Tags: - Zend_Navigation Related issues: - ZF-6486 Attachments: Zend_Navigation_Page_Mvc method getRoute() doesn't take a default route into consideration. When URLs are constructed using the URL helper, the second parameter must be a route name or null. When using a route and viewing a page all helper constructed URLs must use 'default' as the route parameter. However, the Zend_Navigation_Page_Mvc component doesn't take this into consideration. Either all pages in the navigation configuration must define the (in xml form) as default or, the getRoute() method must return the following: return (is_null($this->_route)) ? 'default' : $this->_route; This takes a null route and turns it into the default route. Posted by Kai Uwe (kaiuwe) on 2011-04-05T07:33:01.000+0000 This is not a bug, this is the normal behaviour! <pre class="highlight"> public function assemble($userParams, $name = null, $reset = false, $encode = true) { if ($name == null) { try { $name = $this->getCurrentRouteName(); } catch (Zend_Controller_Router_Exception $e) { $name = 'default'; } } // … } […] Zend_Navigation uses the action helper and router as documented. It is not the task of Zend_Navigation to build a url or to change the behaviour from Zend_Controller_Router.
https://framework.zend.com/issues/browse/ZF-11261
CC-MAIN-2017-13
refinedweb
215
55.64
import a value from txt file shell scripts Login to Discuss or Reply to this Discussion in Our Community Thread Tools Search this Thread Top Forums Shell Programming and Scripting How to import a value from txt file # 1 03-26-2012 chris_euop Registered User 3, 0 Join Date: Mar 2012 Last Activity: 27 March 2012, 4:57 AM EDT Posts: 3 Thanks Given: 0 Thanked 0 Times in 0 Posts How to import a value from txt file Hello, I want to give a value from a txt file to my variable at my ksh script. I`ve searched on the net and I found the command variable < file.txt but it cannot see the file. The .txt file contains two values in the first and the second line. Is there any way to give the first-line value to one variable and the second-line value to another? Thanks in advance! chris_euop View Public Profile for chris_euop Find all posts by chris_euop # 2 03-26-2012 Franklin52 Registered User 7,747, 559 Join Date: Feb 2007 Last Activity: 20 April 2020, 11:28 AM EDT Location: The Netherlands Posts: 7,747 Thanks Given: 139 Thanked 559 Times in 520 Posts This should work if your file has 2 lines: Code : while read temp do a=$b b=$temp done < file.txt echo $a echo $b Franklin52 View Public Profile for Franklin52 Find all posts by Franklin52 Previous Thread | Next Thread Test Your Knowledge in Computers #223 Difficulty: Easy In September 2019, according to NetMarketShare, Windows had just over 87% of the global desktop market, followed by Mac OS at close to 10%, and Linux in third place at around 2%. True or False? True False Submit Answer 10 More Discussions You Might Find Interesting 1. Shell Programming and Scripting Desired output.txt for reading txt file using awk? Dear all, I have a huge txt file (DATA.txt) with the following content . From this txt file, I want the following output using some shell script. Any help is greatly appreciated. Greetings, emily DATA.txt (snippet of the huge text file) 407202849... (2 Replies) Discussion started by: emily 2 Replies 2. Windows & DOS: Issues & Discussions 2 Questions: replace text in txt file, add text to end of txt file so... Lets assume I have a text file. The text file contains multiple "#" symbols. I want to replace all thos "#"s with a STRING using DOS/Batch I want to add a certain TEXT to the end of each line. How can I do this WITHOUT aid of sed, grep or anything linux related ? (1 Reply) Discussion started by: pasc 1 Replies 3. Windows & DOS: Issues & Discussions SQL Server import csv or txt on a Solaris box New to using sql server and unix, but say I have here /home/foo/file.txt Can I use some kind of process to push that .txt into a sql server? Or Is there a sql server utility that can be configured to find a unix box and go into /home/foo/file.txt and slurp it up:) Or is there any PC and... (5 Replies) Discussion started by: sas 5 shellscript to read data from txt file and import to oracle db Hi all, Help needed urgently. I am currently writing a shellscript to read data/record from a flat file (.txt) file, and import/upload the data to oracle database. The script is working fine, but it takes too long time (for 18000 records, it takes around 90 mins). I guess it takes so long... (1 Reply) Discussion started by: robot_mas 1 Replies 6. Shell Programming and Scripting awk append fileA.txt to growing file B.txt This is appending a column. My question is fairly simple. I have a program generating data in a form like so: 1 20 2 22 3 23 4 12 5 43 For ever iteration I'm generating this data. I have the basic idea with cut -f 2 fileA.txt | paste -d >> FileB.txt ???? I want FileB.txt to grow, and... (4 Replies) Discussion started by: theawknewbie 4 Replies 7. Programming import .txt and split word into array C Hi, if I want to import .txt file that contain information and the number separate by space how can I split and put into array In C Example of .txt file 3 Aqaba 49789 10000 5200 25.78 6987 148976 12941 15.78 99885 35262 2501 22.98 Thank (3 Replies) Discussion started by: guidely 3 Replies 8. Shell Programming and Scripting command to list .txt and .TXT file Hi expersts, in my directory i have *.txt and *.TXT and *.TXT.log, *.txt.log I want list only .txt and .TXT files in one command... how to ?? //purple (1 Reply) Discussion started by: thepurple 1 Replies 9. Shell Programming and Scripting AWK CSV to TXT format, TXT file not in a correct column format HI guys, I have created a script to read 1 column in a csv file and then place it in text file. However, when i checked out the text file, it is not in a column format... Example: CSV file contains name,age aa,11 bb,22 cc,33 After using awk to get first column TXT file... (1 Reply) Discussion started by: mdap 1 Replies 10. Member Badges and Information Modal × Featured Tech Videos
https://www.unix.com/shell-programming-and-scripting/180045-how-import-value-txt-file.html?s=af0c16b905ab53d0ee8c0ee5dda5eb2e
CC-MAIN-2021-39
refinedweb
894
82.95
Belgium 🇧🇪 Get import and export customs regulation before travelling to Belgium. Items allowed to import are Medicines for personal use. Prohibited items are Counterfeit and pirated goods. Some of restricted items are Weapons such as firearms and ammunition require a permit. Belgium is part of Europe with main city at Brussels. Its Developed country with a population of 11M people. The main currency is Euro. The languages spoken are French, German and Dutch. 👍 Developed 👨👩👦👦 11M people chevron_left import export Useful Information Find other useful infromation when you are travelling to other country like visa details, embasssies, customs, health regulations and so on.
https://visalist.io/belgium/customs
CC-MAIN-2020-24
refinedweb
102
51.55
Researching to see if there is a way to use Python to export multiple tables in a File Geodatabase to a single Excel file. I would like for each sheet name to have the same name as the table. My current situation is that I ran a Python script to take all the domains a GDB and create a table within the GDB. The article referenced from: Batch export coded value domains to table def main(): import arcpy, os gdb = r"Z:\GIS_Projects\zUpdatesBrian\Scripts\ListDomains\ListDomains.gdb" arcpy.env.overwriteOutput = True for dom in arcpy.da.ListDomains(gdb): if dom.domainType == 'CodedValue': arcpy.DomainToTable_management(in_workspace=gdb, domain_name=dom.name, out_table=os.path.join(gdb, dom.name), code_field="item", description_field="descrip", configuration_keyword="") print " - domain '{0}' of type '{1}' exported to table".format(dom.name, dom.domainType) else: print " - domain '{0}' of type '{1}' skipped".format(dom.name, dom.domainType) if __name__ == '__main__': main() I'm in the same boat: I have multiple tables in a fgdb and would like to export them to a workbook as individual worksheets. Just moments ago, I installed the xlsxwriter module as a package in ArcGIS Pro. That's the easy part. Now I'm working on figuring it out. See: Getting Started with XlsxWriter — XlsxWriter Documentation ( I just create my Hello.xls...) Hey Dan, Joshua or Curtis- ever work with xlsxwriter? Dan Patterson Joshua Bixby Curtis Price
https://community.esri.com/thread/214857-export-multiple-tables-in-gdb-to-excel-with-a-new-sheet-for-each-table
CC-MAIN-2018-51
refinedweb
233
50.53
Test if a variable is a list or tuple Go ahead and use isinstance if you need it. It is somewhat evil, as it excludes custom sequences, iterators, and other things that you might actually need. However, sometimes you need to behave differently if someone, for instance, passes a string. My preference there would be to explicitly check for str or unicode like so: import typesisinstance(var, types.StringTypes) N.B. Don't mistake types.StringType for types.StringTypes. The latter incorporates str and unicode objects. The types module is considered by many to be obsolete in favor of just checking directly against the object's type, so if you'd rather not use the above, you can alternatively check explicitly against str and unicode, like this: isinstance(var, (str, unicode)): Edit: Better still is: isinstance(var, basestring) End edit After either of these, you can fall back to behaving as if you're getting a normal sequence, letting non-sequences raise appropriate exceptions. See the thing that's "evil" about type checking is not that you might want to behave differently for a certain type of object, it's that you artificially restrict your function from doing the right thing with unexpected object types that would otherwise do the right thing. If you have a final fallback that is not type-checked, you remove this restriction. It should be noted that too much type checking is a code smell that indicates that you might want to do some refactoring, but that doesn't necessarily mean you should avoid it from the getgo. There's nothing wrong with using isinstance as long as it's not redundant. If a variable should only be a list/tuple then document the interface and just use it as such. Otherwise a check is perfectly reasonable: if isinstance(a, collections.Iterable): # use as a containerelse: # not a container! This type of check does have some good use-cases, such as with the standard string startswith / endswith methods (although to be accurate these are implemented in C in CPython using an explicit check to see if it's a tuple - there's more than one way to solve this problem, as mentioned in the article you link to). An explicit check is often better than trying to use the object as a container and handling the exception - that can cause all sorts of problems with code being run partially or unnecessarily.
https://codehunter.cc/a/python/test-if-a-variable-is-a-list-or-tuple
CC-MAIN-2022-21
refinedweb
406
57.1
On Mon, Nov 23, 2009 at 01:49:09PM -0600, Anthony Liguori wrote: > Eduardo Habkost wrote: >> On Mon, Nov 23, 2009 at 12:28:16PM -0600, Anthony Liguori wrote: <snip> >>>> >>>? > > It's for migrating from an older qemu to a newer one. Normally, newer > qemu will happily support older formats but in this case, we broke > something and we need to blacklist the old format. This lets you > override that black list. Then we can already do that: just return an error on the load function if version_id is too low. Doing with a bitmap on qdev would be more flexible, but it is already possible today. > >> If so, even with this bitmap, how would the migration source process >> know which version it should use when generating the savevm data? >> > > To properly support this in -M pc-0.11, we'll need to be able to set the > version to migrate for each qdev device. Again, this is something that > could be overridden as a qdev property. The effect would be that we > force a newer qemu to generate the older savevm format. Right. Different from the bitmap, this is something we can't easily reproduce with current infra-structure. > >> (considering that the migration stream is unidirectional, today) We have >> been considering using a "set-savevm-version" monitor command that would >> be used by management if backward migration is forced by the user. >> > > qdev property is the right approach I think. It's really a per-device > setting. It needs to get tied to machine type too and that's a > convenient way to do that. > >>). >> > > In theory, a user can manually specify everything in a machine type. So the qdev magic would be used to provide input to this sytem. I see. > >>>. >> > > It doesn't because it's just as likely to get clashes in subsection > names. For instance, RHEL5.4 may call the pvclock msr subsection > "pvclock-msrs" and then upstream may call it "pvclock-msrs" and flip the > order of the fields. If we implemented this on RHEL before including it upstream, then we could have a "RHEL" subversion flag set (or simply call it "pvclock-msrs-rhel"). But if we backport it, there is no reason to make the version scheme incompatible. > > To support downstreams effectively, we need vendor specific versioning > so that we can separate the upstream qemu namespace from each of the > downstreams. The problem is that newer versions of downstream code will be branched off newer upstream versions, in the future. A mechanism that helps keeping the version numbers compatible where possible (not always) would facilitate code contribution on both directions. > >>. >> > > Downstream adds a "RHEL" subversion. This allows downstream to add a > subversion to each device if it modifies it. When it backports E, it > bumps the downstream version from 0->1. > > As long as the backported features aren't enabled, the migration will be > compatible to upstream. Once one of these backported features is > enabled, migration will fail gracefully. > >> >> > > The combinations blow up quickly. Just because A,B,C,E works for a > given downstream, doesn't mean that it would work with the upstream code > base. Features are rarely so independent of one another. > > It also doesn't address things like QXL which aren't just a simple > matter of a backported upstream feature. My point is that sometimes they are clearly independent, and when that happens, keeping the version schemes compatible is a good thing. The pvclock MSRs are an example: they are clearly independent from the other MSRs and it wouldn't hurt Qemu if they were added as a separated section. There would be other benefits, too: the pvclock MSR section could be disabled if pvclock support is disabled on the command-line or machine definition. We would even have an answer to the user that wanted backward migration: "yeah, if you were so sure the guest OS didn't use pvclock, you could have disabled pvclock when the VM was created, and migration would be possible". Yes, there are many cases where doing this won't be enough or won't be as simple, and we will need a "sub-version" field like you suggested for stuff that are too different from upstream. I am just suggesting that we encourage savevm features to be introduced in a more "modular" way where possible, to facilitate collaboration. -- Eduardo
http://lists.gnu.org/archive/html/qemu-devel/2009-11/msg01427.html
CC-MAIN-2013-48
refinedweb
729
62.78
Here's the question, THANKS FOR ANY HELP! -Driver class). Your job is to write the Piglatin class so that PigDriver works appropriately. import java.util.*; public class PigDriver{ public static void main(String[] args){ Scanner scan = new Scanner(System.in); String t = " "; Piglatin p = new Piglatin(); while(t.length() > 0){ t = scan.nextLine(); t = t.toLowerCase(); p.pigConvert(t); } p.pigReport(); } } On this input: Now is the time, for all good, and I mean very good men and women, to visit their grandmothers! The following output was produced: ownay isay hetay imetay orfay allay oodgay anday iay eanmay eryvay oodgay enmay anday omenway otay isitvay heirtay randmothersgay Some requirements, and tips: * make sure you comment all of your methods with one line that tells what that method does * Additional helper methods a surely useful; my solution has four methods. * You will need to use StringTokenizer in the Piglatin class
http://www.dreamincode.net/forums/topic/166160-writing-a-pig-latin-translator/
CC-MAIN-2016-30
refinedweb
150
64.41
I'm trying to learn how to use opencv in python and having some difficulties, and also I'm a newbie at python too. Here is my question : I want to convert a jpg file tp png. Simple and clear. But when I run this code : from opencv import _cv from opencv.highgui import cvSaveImage, cvLoadImage cvSaveImage("bet.jpg",cvLoadImage("bet.jpg")) if __name__ == '__main__': pass It gives this error which I don't understand : Traceback (most recent call last): File "convert.py", line 6, in <module> cvSaveImage("bet.jpg",cvLoadImage("bet.jpg")) File "/usr/lib/pymodules/python2.6/opencv/highgui.py", line 183, in cvSaveImage return _highgui.cvSaveImage(*args) RuntimeError: openCV Error: Status=Null pointer function name=cvGetMat error message=NULL array pointer is passed file_name=cxarray.cpp line=2780 I have my picture with the same folder of source code and the name of the image is bet.jpg Any idea ?? I solved the problem, the image I took randomly from the Google Images doesn't load. Maybe it's encrypted or something I don't know. I tried it with other images, and worked very well. So watch out while copying images : )
https://pythonpedia.com/en/knowledge-base/2462725/cv-saveimage-in-opencv
CC-MAIN-2020-29
refinedweb
195
69.68
I have the following code that calculates how much it costs to talk on the phone during the day evening and weekends for two plans. However the code malfunctions! What am I missing or need to add? Thank you for your help! Code:#include <iostream>using namespace std; int main () { int x; int y; int z; cout<<"Number of daytime minutes?: "; cin>>x; cout<<"Number of evening minutes?: "; cin>>y; cout<<"Number of weekend minutes?: "; cin>>z; // Do i need to do this?! //int a; //int s; //int d; //int totalw; // //int f; //int g; //int h; //int totalq; if(x>=100) int a=x*25; if(y>=1) int s=y*15; if(z>=1) int d=z*20; if(x>=100) int totalw=a+s+d; else int totalw=s+d; if(x>=250) int f=x*45; if(y>=1) int g=y*35; if(z>=1) int h=z*25; if(x>=250) int totalq=f+g+h; else int totalq=g+h; cout<<"Plan A will cost "<<totalq<<" cents."<<endl; cout<<"Plan B will cost "<<totalw<<" cents."<<endl; if(totalq>totalw) cout<<"Plan B is cheapest."<<endl; else cout<<"Plan A is cheapest."<<endl; if(totalq==totalw) cout<<"Plan A and B are the same price."<<endl; }
http://mathhelpforum.com/math-topics/213565-variable-not-initialized-code-help.html
CC-MAIN-2014-15
refinedweb
212
84.98
Hello, I'm new to this list, joined on account of a nagging problem. Advertising Web pages run through apache as local server are my favorite easy-interfaces for many utilities written in very rudimetary (clueless) perl over the years. They all work except a few involving gimp, which used to work with older versions though. I'm using Suse-11.1 (32 bit) on an amd64 machine with just about all related gimp (2.6.5) and perl (5.10) packages installed as far as I know. As I tried to 'reactivate' one of these scripts dormant for many years it refused to function. Looking at error messages has identified two immediate obstacles. 1 Script prepends like these do not work (neither web nor CLI) and I don't really know what they do exactly. use Gimp ":auto"; use Gimp::Fu; use Gimp::Net; use Gimp::Util; Can't locate Gimp.pm in @INC (@INC contains: unless changed to (single lines) like use lib '/usr/lib/perl5/site_perl/5.10.0/i586-linux-thread-multi'; use lib '/usr/lib/perl5/site_perl/5.10.0/i586-linux-thread-multi/Gimp'; This one seems to have been provisionally dealt with thanks to a helpful soul on usenet who suggested the paths to use instead but I'd like to get it done right i.e. make it work without the workaround. 2 Old 'register' lines like register "", "", "", "", "", "", "<None>", "*", "", don't work and neither do newer versions found in examples on the net. Unquoted string "register" may clash with future reserved word at ..test.pl line xx., String found where operator expected at ..test.pl line xx, near "register, Exactly what does 'register' do? Do I even need to register if all I want is for gimp to load or produce an image, manipulate it soemewhat and then save it so the srcipt can load it and erase it after use? I don't need gimp to store the script for future use. A sample extract is pasted below (I prefer such simple layout/formats appropriate to my minimal perl abilities). #!/usr/local/bin/perl -w &doasub; exit; doasub { print "Said I: Hellow World"; print "World: !Bang!"; } As I understood it the sript assembles the instructions and finaly exits handing them over to gimp for execution. I'd really like to find a short sample that works so as to have a solid departure point at least. Thank you. --------------------------------- #!/usr/local/bin/perl -w print"Content-type:text/html\n\n"; use Gimp qw (:auto); use Gimp::Fu; use Gimp::Net; use Gimp::Util; register "", "", "", "", "", "", "<None>", "*", "", &doit; exit main(); sub doit { $file1="/srv/www/htdocs/user/magi/filez/source.png"; $rotangle=-238; $radians = 2 * 3.141592654 * $rotangle/360.0; $image1 = gimp_file_load($file1, $file1); # later down, do some like .... $background=gimp_rotate($background,0,$radians); $final=gimp_image_flatten($image); $targr="/srv/www/htdocs/user/filez/target.png"; file_png_save($image, $final, $targr, $targr, 0,9,0,0,0,0,0); # what you want from gimp return $final; print"<img src=$final>"; return (); } --------------------------------- _______________________________________________ Gimp-user mailing list Gimp-user@lists.XCF.Berkeley.EDU
https://www.mail-archive.com/gimp-user@lists.xcf.berkeley.edu/msg16690.html
CC-MAIN-2017-17
refinedweb
517
57.77
<<Clean Code>> Quotes: 5. Formatting you should take care that your code is nicely formatted. The Purpose of Formatting Code formatting is important. Code formatting is about communication, and communication is the professional developer’s first order of business. The code style and readability set precedents that continue to affect maintainability and extensibility long after the original code has been changed beyond recognition. Vertical Formatting It appears to be possible to build significant systems out of files that are typically 200 lines long, with an upper limit of 500. The Newspaper Metaphor. Vertical Openness Between Concepts Each line represents an expression or a clause, and each group of lines represents a complete thought. Those thoughts should be separated from each other with blank lines. Vertical Density If openness separates concepts, then vertical density implies close association. So lines of code that are tightly related should appear vertically dense. Vertical Distance Concepts that are closely related should be kept vertically close to each other. Clearly this rule doesn’t work for concepts that belong in separate files. But then closely related concepts should not be separated into different files, unless you have a very good reason. For those concepts that are so closely related that they belong in the same source file, their vertical separation should be a measure of how important each is to the understandability of the other. Variable Declarations. Variables should be declared as close to their usage as possible. Because our functions are very short, local variables should appear at the top of each function. … Control variables for loops should usually be declared within the loop statement. Instance variables, on the other hand, should be declared at the top of the class. This should not increase the vertical distance of these variables, because in a well-designed class, they are used by many, if not all, of the methods of the class. Dependent Functions. If one function calls another, they should be vertically close, and the caller should be above the callee, if at all possible. This gives the program a natural flow. Conceptual Affinity. Certain bits of code want to be near other bits. They have a certain conceptual affinity. The stronger that affinity, the less vertical distance there should be between them. … this affinity might be based on a direct dependence, such as one function calling another, or a function using a variable. … Affinity might be caused because a group of functions perform a similar operation. Vertical Ordering In general we want function call dependencies to point in the downward direction. As in newspaper articles, we expect the most important concepts to come first, and we expect them to be expressed with the least amount of polluting detail. We expect the low-level details to come last. This allows us to skim source files, getting the gist from the first few functions, without having to immerse ourselves in the details. Horizontal Formatting The old Hollerith limit of 80 is a bit arbitrary, and I’m not opposed to lines edging out to 100 or even 120. But beyond that is probably just careless. Horizontal Openness and Density We use horizontal white space to associate things that are strongly related and disassociate things that are more weakly related. private void measureLine(String line) { lineCount++; int lineSize = line.length(); totalChars += lineSize(); lineWidthHistogram.addLine(lineSize, lineCount); recordWidestLine(lineSize); } On the other hand, I didn’t put spaces between the function names and the opening parenthesis. This is because the function and its arguments are closely related. … I separate arguments within the function call parenthesis to accentuate the comma and show that the arguments are separate. public class Quadratic { public static double root1(double a, double b, double c) { double determinant = determinant(a, b, c); return (-b + Math.sqrt(determinant) / (2*a); } private static double determinant(double a, double b, double c) { return b*b - 4*a*c; } } The factors have no white space between them because them are high precedence. The terms are separated by white space because addition and subtraction are lower precedence. Horizontal Alignment private Long requestParsingTimeLimit; protected Request request; private FitNesseContent context;this.context = context; input = s.getInputStream() requestParsingTimeLimit = 900; I have found, however, that this kind of alignment is not useful. The alignment seems to emphasize the wrong things and leads my eye away from the true intent. Indentation A source file is a hierarchy rather link and outline. Each level of this hierarchy is a scope into which names can be declared and in which declarations and executable statements are interpreted. To make this hierarchy of scopes visible, we indent the lines of source code in proportion to their position in the hierarchy. BreakingIndentation. It is sometimes tempting to break the indentation rule for short if statements, short while loops, or short functions. Whenever I have succumbed to this temptation, I have almost always gone back and put the indentation back in. Dummy Scopes I make sure that the dummy body is properly indented and surrounded by braces. Team Rules A team of developers should agree upon a single formatting style, and then every member of that team should use that style.
https://mosquitolwz.medium.com/clean-code-quotes-5-formatting-b7bdd4a828d6?source=post_internal_links---------3----------------------------
CC-MAIN-2022-21
refinedweb
859
55.44
Technical Support On-Line Manuals RL-ARM User's Guide (MDK v4) #include <rtl.h> int recv ( int sock, /* Socket descriptor */ char *buf, /* Pointer to a buffer for data */ int len, /* Size of data buffer in bytes */ int flags, /* Message flags */ SOCKADDR *from, /* Pointer to address structure */ int *fromlen); /* Length of address structure */ The recvfrom function is used to receive data that has been queued for a socket. It is normally used to receive messages on SOCK_DGRAM socket type, but can also be used to receive a reliable, ordered stream of data on a connected SOCK_STREAM socket type. It reads as much information as currently available up to the size of the buffer specified. In blocking mode, which is enabled if the system detects RTX environment, this functions waits for received data. In non blocking mode, you must call the recvfrom function again if the error code SCK_EWOULDBLOCK is returned. The argument sock specifies a socket descriptor returned from a previous call to socket. The argument buf is a pointer to the application data buffer for storing the data to. If the available data is too large to fit in the supplied application buffer buf, excess bytes are discarded in case of SOCK_DGRAM sockets. For socket types SOCK_STREAM, the data is buffered internally so the application can retrieve all data by multiple calls of recvfrom function. The argument len specifies the size of the application data buffer. The argument flags specifies the message flags: The argument from is a pointer to the SOCKADDR structure. If from is not NULL, the source IP address and port number of the datagram is filled in. The argument fromlen is a pointer to the address length. It should initially contain the amount of space pointed to by from. On return it contains the actual length of the address returned in bytes. The recvfrom function is in the RL-TCPnet library. The prototype is defined in rtl.h. note The recvfrom function returns the following result: ioctlsocket, recv, send, sendto #include <rtl.h> __task void server (void) { SOCKADDR_IN addr; int sock, res, addrlen; char dbuf[4]; while (1) { sock = socket (AF_INET, SOCK_DGRAM, IPPROTO_UDP); addr.sin_port = htons(1001); addr.sin_family = PF_INET; addr.sin_addr.s_addr = INADDR_ANY; bind (sock, (SOCKADDR *)&addr, sizeof (addr)); while (1) { addrlen = sizeof (addr); res = recvfrom (sock, dbuf, sizeof (dbuf), 0, addr, &addrlen); if (res <= 0) { break; } procrec ((U8 *)dbuf); printf ("Remote IP: %d.%d.%d.%d\n",addr.sin_addr.s_b1, addr.sin_addr.s_b2, addr.sin_addr.s_b3, addr.sin_addr.s_b4); printf ("Remote port: %d\n",ntohs (addr.sin_port)); }.
https://www.keil.com/support/man/docs/rlarm/rlarm_recvfrom.htm
CC-MAIN-2020-34
refinedweb
424
63.19
Question: Does sgRNA have to be complementary to DNA strand? 0 4.4 years ago by darkmatter1996 • 0 darkmatter1996 • 0 wrote: I have been analyzing the data from the Xu et. al (2015) paper (see Supplemental Table_1.xlsx here). However, it appears that many of the sgRNAs shown are not complementary to any part of the targeted gene indicated. For example, I downloaded the NCBI sequence data for the gene RPL17, and was not able to find the sgRNA strand TTTCTTCTGGGCAACCTCCTCTTCTGGTTTAGGAACAATC, which is inside the data set, complementary to anywhere inside the gene. I wrote the following python function for finding the position of the sgRNA in the gene, which returns -1 if no match is found: def guide_positional_features(guide_seq, gene, strand): guide_seq = Seq.Seq(guide_seq) f = open("data/sequences/{}.txt".format(gene), "r") gene_seq = f.read() gene_seq = Seq.Seq(gene_seq).reverse_complement() if strand == '+': # sense strand guide_seq = guide_seq.reverse_complement() ind = gene_seq.find(guide_seq) return ind Am I doing something wrong? Thanks. ADD COMMENT • link •written 4.4 years ago by darkmatter1996 • 0
https://www.biostars.org/p/192451/
CC-MAIN-2020-45
refinedweb
172
60.31
user LAI <!-- Location:latitude=45.30.38,longitude=-73.33.38 --> <!-- os:linux,W2K --> <!-- birthday:xxxx/11/16 --> <!-- email:y.LI.Jn.@pimpninja.org --> <p> [ password generator] </p> <p> Yeah, it's a shell script right now, but that's because I wrote it as a one-liner. I'll probably golf it. Yeah, I'm gonna golf it. Cool. I'll make it all perl first, though. Anyway, here's the code (also on [pad://LAI]): </p> <code> head -c 200 /dev/urandom | perl -e '$i=0;foreach (split //, <>) {s/[\s\W]//g;print}#$i++,$_,$/}' | head -c 8; echo </code> <hr /> <p> Ooh! Oh, it's so annoying. Grrrrr.... </p> <p> As anyone who's spoken to me much on the CB can guess, I'm talking about the friggin' VB crap I have to do for work. You know what I wound up doing at one point? Writing a sprintf, and m() and s() functions. How useless is VB, if it has no built-in capacity to perform these simple tasks? Argh! I did have the code here at one point, but realized that this was akin to walking into a monastery covered head to toe in blood and carrying the severed heads of a family of innocents in order to demonstrate the wrongness of murder. </p> <hr /> <p> Here's a recent monk: [Ella] ... and I'm still waiting for <a href="">Andy...</a> </p> <hr /> <p> Keep your eye on <a href="">this</a> ball. </p> <p> Okay, so that's not really moving along. It was supposed to; I had written a patch for it and everything! But seems like the author has a lot more on his plate, and the admins of CPAN want him to change his namespace, and stuff. Oh, well. </p> <p> I've been having fun with a little app on fsckme.com: my <a href="">Command Prompt</a>. The idea is to simulate a command prompt, with certain commands allowed and properly filtered arguments. So far I've enabled the following commands: <code> /^ls[ a-zA-Z\d\/\.~\-_\*\?]*$/ /^du[ a-zA-Z\d\/\.~\-_\*\?]*$/ /^df$/ /^uptime$/ </code> I figure this much is relatively safe. What with the inclusive filtering instead of exclusive. Like starting your access rules with <code>deny to all</code>. Especially since while testing I left it completely unfiltered... and on that box apache ran as the same user who owned all the files! </p> <p> Anyway, the original idea of this was to have some sort of shell access on my host's box. I had downgraded my plan with them and had lost the right to SSH in... so my hacker instinct took over and decided to find a way to circumvent that limitation. (I've since changed [] and now have full access to my box, but it's still a neat project.) It's still far from complete, as I have yet to implement proper login authentication (if you like, you can login as user:pass or uname:passwd; it doesn't really do anything yet). But it would be nice to eventually enable some user accounts with that. </p> <p> Maybe I'll eventually post it as a CUfP... </p> <pre>-----BEGIN PERL GEEK CODE BLOCK----- Version: 0.01 P++>++++$c--P6-R++M+>++O++MA+++>++++E PU >++++BD C++D+S+++$X WP+MO PP!n-CO--PO o+G+A->+++OL!OLJ--Ee---Ev+Eon!uL+++uB uS w-$m! ------END PERL GEEK CODE BLOCK------ ----- (<a href="">DECODE IT</a>|<a href="">GET YOUR OWN</a>) ----- </pre> 2012-09-10 09:55:33 1430 363783 205959 134 Montreal, People's Free Reformed Socialist Democratic Republic of Québec</td></tr><tr><td>Latest nickname:</td><td>querida ranita -4 80
http://www.perlmonks.org/index.pl?displaytype=xml;node_id=178898
CC-MAIN-2014-41
refinedweb
631
74.19
Java continue statement is used to skip the current iteration of a loop. Continue statement in java can be used with for, while and do-while loop. Table of Contents Java continue statement When continue statement is used in a nested loop, it only skips the current execution of the inner loop. Java continue statement can be used with label to skip the current iteration of the outer loop too. Let’s have a look at some continue java statement examples. Java continue for loop Let’s say we have an array of integers and we want to process only even numbers, here we can use continue loop to skip the processing of odd numbers. Copypackage com.journaldev.java; public class JavaContinueForLoop { public static void main(String[] args) { int[] intArray = { 1, 2, 3, 4, 5, 6, 7 }; // we want to process only even entries for (int i : intArray) { if (i % 2 != 0) continue; System.out.println("Processing entry " + i); } } } Java continue while loop Let’s say we have an array and we want to process only index numbers divided by 3. We can use java continue statement here with while loop. Copypackage com.journaldev.java; public class JavaContinueWhileLoop { public static void main(String[] args) { int[] intArray = { 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 }; int i = 0; while (i < 10) { if (i % 3 != 0) { i++; continue; } System.out.println("Processing Entry " + intArray[i]); i++; } } } Java continue do-while loop We can easily replace above while loop code with do-while loop as below. Result and effect of continue statement will be same as above image. Copydo { if (i % 3 != 0) { i++; continue; } System.out.println("Processing Entry " + intArray[i]); i++; } while (i < 10); Java continue label Let’s have a look at java continue label example to skip the outer loop processing. We will use two dimensional array in this example and process an element only if all the elements are positive numbers. Copypackage com.journaldev.java; import java.util.Arrays; public class JavaContinueLabel { public static void main(String[] args) { the array of all positive ints. " + Arrays.toString(intArr[i])); } allPositive = true; } } } Java continue important points Some important points about java continue statement are; - For simple cases, continue statement can be easily replaced with if-else conditions but when we have multiple if-else conditions then using continue statement makes our code more readable. - continue statement comes handy incase of nested loops and to skip a particular record from processing. I have made a short video explaining java continue statement in detail, you should watch it below. Reference: Oracle Documentation Janice says It is a “go to” statement, which was recommended to avoid in your code. I have not seen these statements in professional code in years?? Not sure we should bring them back?? Anurag Singh says great article nice very very nice thanks Raghuveer Kurdi says Hi Pankaj, Nice Tutorials. I think in the above example for processing all positive elements, we are assigning the allPositive value to true at line 33. I think its unnecessary. As we are assigning its value to true in the beginning of each iteration. Thanks.
https://www.journaldev.com/983/java-continue-statement
CC-MAIN-2019-13
refinedweb
525
54.83
Originally posted by Parameswaran Thangavel: i didn't get how equals print true 1) class SS { static public void main(String args[]) { Double a = new Double(Double.NaN); Double b = new Double(Double.NaN); if( Double.NaN == Double.NaN ) System.out.println("True"); else System.out.println("False"); if( a.equals(b) ) System.out.println("True"); else System.out.println("False"); } } Note that in most cases, for two instances of class Double, d1 and d2, the value of d1.equals(d2) is true if and only if d1.doubleValue() == d2.doubleValue() also has the value true. However, there are two exceptions: If d1 and d2 both represent Double.NaN, then the equals method returns true, even though Double.NaN==Double.NaN has the value false. If d1 represents +0.0 while d2 represents -0.0, or vice versa, the equal test has the value false, even though +0.0==-0.0 has the value true. Originally posted by Parameswaran Thangavel: 2)why the following code didn't get errors class R { void m() { } } class SS extends R { static public void main(String args[]) { Float b=new Float("12.12"); } } the float value is by default Double; even if i give 12.12d the compiler is not complaining. why?? Originally posted by Parameswaran Thangavel: 3)whts the o/p class Test { Test(int i) { System.out.println("Test(" +i +")"); } } public class Q12 { static Test t1 = new Test(1); Test t2 = new Test(2); static Test t3 = new Test(3); public static void main(String[] args) { Q12 Q = new Q12(); } } Originally posted by Parameswaran Thangavel: 4) class SS { static public void main(String args[]) { byte d=(byte)12; d=~d;//Throwiing error why??? System.out.println(d); } } 5) solve when i am using the byte in the place of char i able to get the full range b4 overflow occurs.but in case of char the chr ? is printed which shows that b is not incrementing why it so? class SS { static public void main(String args[]) { char b = 1; while ( ++b > 0 ) System.out.println(b); ; System.out.println("Welcome to Java"); } } 6) ans is b how : public void check() 2: { 3: System.out.println(Math.min(-0.0,+0.0)); 4: System.out.println(Math.max(-0.0,+0.0)); 5: System.out.println(Math.min(-0.0,+0.0) == Math.max(0.0,+0.0)); 6: } A) prints -0.0, +0.0 and false. B) prints -0.0, +0.0 and true. C) prints 0.0, 0.0 and false. D) prints 0.0, 0.0 and true. Unlike the the numerical comparison operators, this method considers negative zero to be strictly smaller than positive zero. -- API for the Math class Originally posted by Parameswaran Thangavel: hi joe thanx for ur reply still i had some doubt let me put it 1) i read that wrapper objeect are overridden like String obects is that true.. 2)i didn't get this point. though the valueOf() method are used to convert the string.. the floating point literal which is 12.12 is by default should be Double or even i gave the double d explicitly.my point here is while converting the string NumberFormat Exception should thrown but didn't why.... 5) i put this in other way why ? is printing always...There should be a value for 256 characters.
http://www.coderanch.com/t/248942/java-programmer-SCJP/certification/Codes
CC-MAIN-2015-32
refinedweb
560
69.99
I am creating a program in Python that will utilize object oriented programming to print the properties of a given rectangle. The project has these given constraints: The purpose of this lab is to give you practice creating your own object. You will be given a main function that expects an instance of the (yet undefined) Rectangle object. Your job is to determine what attributes and methods the Rectangle class requires and create a class that will satisfy the requirements. - Add only one feature at a time - You may need to comment out parts of the main function for testing - Constructor should take 0, 1, or 2 parameters (illustrating polymorphism) - Your class should be a subclass of something (illustrating inheritance) - Your class should have methods and properties (illustrating encapsulation) - Make your instance variables hidden (using the __ trick) - Add setter and getter methods for each instance variable - Use properties to encapsulate instance variable access - Not all instance variables are real... Some are derived, and should be write-only - You may not substantially change the main function (unless you're doing the blackbelt challenge) - Be sure to add the needed code to run the main function when needed Here is the rubric - Code: main() function is relatively unchanged 3 - Code: Rectangle class is declared with defaults so it supports 0, 1 and 2 parameters 3 - Code: Instantiates Rectangle(5,7) 2 - Code: Instantiates Rectangle() 2 - Code: Rectangle class defines __ instance variables 2 - Code: Defines getters and setters for each instance variable 2 - Code: Rectangle class include area and perimeter methods 4 - Code: Rectangle class inherits from something, even if it's object 2 - Code: Rectangle class defines width and length properties 4 - Code: Rectangle includes derived read-only instance variables 2 - Code: Invokes main when the python file is executed as main 2 - Code: Rectangle class defines getStats() method that returns a string 4 - Execution: prints Rectangle a: 1 - Execution: prints area: 35 1 - Execution: prints perimeter: 24 1 - Execution: prints Rectangle b: 1 - Execution: prints width: 10 1 - Execution: prints height: 20 1 - Execution: prints area: 200 1 - Execution: prints perimeter: 60 1 Score 40 I am given this code to start off with: def main(): print "Rectangle a:" a = Rectangle(5, 7) print "area: %d" % a.area print "perimeter: %d" % a.perimeter print "" print "Rectangle b:" b = Rectangle() b.width = 10 b.height = 20 print b.getStats() I am supposed to get this output: Rectangle a: area: 35 perimeter: 24 Rectangle b: width: 10 height: 20 area: 200 perimeter: 60 I have gotten this far but I can not get Rectangle B to print the width and height Can you please take a look? class Rectangle: def __init__(self, width=0, height=0): self.width = width self.height = height def area(self): return self.width * self.height def perimeter(self): return 2 * self.height + 2 * self.width def setWidth(self, width): self.width = width def setHeight(self, height): self.height = height def getStats(self): return "area: %s\nperimeter: %s" % (self.area(), self.perimeter()) def main(): print "" print "Rectangle a:" a = Rectangle(5, 7) print "area: %s" % a.area() print "perimeter: %s" % a.perimeter() print "" print "Rectangle b:" b = Rectangle() b.width = 10 b.height = 20 print b.getStats() print "" main() I am currently getting this output: Rectangle a: area: 35 perimeter: 24 Rectangle b: area: 200 perimeter: 60 Process finished with exit code 0
http://www.howtobuildsoftware.com/index.php/how-do/eZV/python-function-class-oop-methods-object-oriented-python-rectangle-using-classes-and-functions
CC-MAIN-2018-51
refinedweb
566
58.42
This is the mail archive of the libstdc++@gcc.gnu.org mailing list for the libstdc++ project. Note: Both replacement compile-time code paths in this patch were completely and independently rebuilt and checked on i386-unknown-freebsd4.2 in an already bootstrapped tree. As usual, I also hand-checked all important changes made to /usr/include/ctype.h over the years on this system to ensure no dumb assumptions were made by this new code. Although it produced no noticeable testsuite errors on this platform, the code to force all digit and xdigit mask lookups to occur in the C locale is not proper C++ and matches no other port. The primary bug: FreeBSD does indeed have 11 mask bits of interest. The problem is that those 11 bits actually start in position 8 not 0 and go to 18. There is the obvious fix of adding 8 to both __bitmasksize's and __i's initializer. However, I rewrote the code to rely only on the symbolic constants. Thus, the loop was unrolled but not for performance reasons, rather correctness reasons (one less thing to track against future system header changes). Recent versions of FreeBSD allow the lookup and masking of a table entry in one step, thus avoiding a loop or unrolled version of same. I also provide a code path which uses that interface, if available (found in FreeBSD 3.5+ and 4.0+), since it makes the inline code both smaller and faster. This FreeBSD configuration-only patch fixes: + + 22_locale/ctype_char_members.cc Remaining failures (thus it appears we are at parity with most ports again): -b -b 23_containers/map_operators.cc -b -b 23_containers/set_operators.cc -r -r 27_io/filebuf_members.cc [...]/egcs/libstdc++-v3/testsuite/27_io/filebuf_members.cc:58: failed assertion `close_num == 0' (which I think matches AIX.) FAIL: g++.jason/2371.C (test for excess errors) FAIL: g++.other/crash32.C (test for excess errors) FAIL: g++.other/loop2.C caused compiler crash Reminder: I don't have CVS write access so I can't apply if approved. Other libstdc++-v3 status: alpha-unknown-freebsd4.2 looks as good as i386-unknown-freebsd4.2 for -static; nothing works with -g shared; stripped shared looks better but still with many failures (I think I read another alpha user, different OS with a similar report where stripping reduced the number of failures). I will take a look at 27_io/filebuf_members.cc's failure next year. Regards, Loren 2000-12-28 Loren J. Rittle <ljrittle@acm.org> * config/os/bsd/freebsd/bits/ctype_inline.h (is): (Make right code path:) Remove magic constants and restructure to handle ctype.h bit mask layout changes more gracefully. (Make fast code path:) Use __maskrune (), if available. (is): Remove special case for digit and xdigit masks. Index: config/os/bsd/freebsd/bits/ctype_inline.h =================================================================== RCS file: /cvs/gcc/egcs/libstdc++-v3/config/os/bsd/freebsd/bits/ctype_inline.h,v retrieving revision 1.4 diff -c -r1.4 ctype_inline.h *** ctype_inline.h 2000/12/19 19:48:59 1.4 --- ctype_inline.h 2000/12/28 22:57:33 *************** *** 38,65 **** ctype<char>:: is(mask __m, char __c) const { ! if (__m & (digit | xdigit)) ! return __isctype(__c, __m); ! else ! return __istype(__c, __m); } const char* ctype<char>:: is(const char* __low, const char* __high, mask* __vec) const { - const int __bitmasksize = 11; // Highest bitmask in ctype_base == 10 for (;__low < __high; ++__vec, ++__low) { mask __m = 0; ! int __i = 0; // Lowest bitmask in ctype_base == 0 ! for (;__i < __bitmasksize; ++__i) ! { ! mask __bit = static_cast<mask>(1 << __i); ! if (this->is(__bit, *__low)) ! __m |= __bit; ! } *__vec = __m; } return __high; } --- 38,71 ---- ctype<char>:: is(mask __m, char __c) const { ! return __istype(__c, __m); } const char* ctype<char>:: is(const char* __low, const char* __high, mask* __vec) const { for (;__low < __high; ++__vec, ++__low) { + #if defined (_CTYPE_S) || defined (__istype) + *__vec = __maskrune (*__low, upper | lower | alpha | digit | xdigit + | space | print | graph | cntrl | punct | alnum); + #else mask __m = 0; ! if (this->is(upper, *__low)) __m |= upper; ! if (this->is(lower, *__low)) __m |= lower; ! if (this->is(alpha, *__low)) __m |= alpha; ! if (this->is(digit, *__low)) __m |= digit; ! if (this->is(xdigit, *__low)) __m |= xdigit; ! if (this->is(space, *__low)) __m |= space; ! if (this->is(print, *__low)) __m |= print; ! if (this->is(graph, *__low)) __m |= graph; ! if (this->is(cntrl, *__low)) __m |= cntrl; ! if (this->is(punct, *__low)) __m |= punct; ! // Do not include explicit line for alnum mask since it is a ! // pure composite of masks on FreeBSD. *__vec = __m; + #endif } return __high; }
http://gcc.gnu.org/ml/libstdc++/2000-12/msg00294.html
crawl-001
refinedweb
745
61.33
959/how-change-the-names-validating-peers-ibm-bluemix-blockchain I am using the Hyperledger Fabric V0.6 service provided in IBM Bluemix blockchain that is a starter developer plan beta. I want to do a demo implementation asset sharing among my application instances. But in the network tab ithe peers are being shown as Validating Peer 0, Validating Peer 1, Validating Peer 2 and Validating Peer 3. Will it be possible to rename these peers to some other name so that it gets easier for me to work with them? IBM Bluemix Blockchain service Hyperledger Fabric v0.6 will soon be removed. Instead, the new Blockchain service will be officially supported. So using a new version is recommended. Now, you can not rename the peers. But you can customize your channel names and also chaincode name and version You start with creating a new project. ...READ MORE f I understand well, you're looking for ...READ MORE I found the exact solution and syntax.. ...READ MORE Each Corda node individually advertises the services ...READ MORE Summary: Both should provide similar reliability of ...READ MORE This will solve your problem import org.apache.commons.codec.binary.Hex; Transaction txn ...READ MORE I know it is a bit late ...READ MORE Whenever a smart contract receives ether via ...READ MORE Either of the ways is acceptable but ...READ MORE OR Already have an account? Sign in.
https://www.edureka.co/community/959/how-change-the-names-validating-peers-ibm-bluemix-blockchain
CC-MAIN-2019-47
refinedweb
235
60.92
Bug Pattern In Java - The Broken Dispatch - Online Article Overview When you employ inheritance polymorphism—a feature of object-oriented languages that allows you to override methods—in combination with static overloading—a feature that allows you to overload methods based on the static types of the arguments—and an untouched method breaks, you may have come upon a Broken Dispatch. We discuss argument mismatches and practical and conceptual ways to eliminate the problem. Remember this adage: "The whole is greater than the sum of its parts." When single events are combined as an interacting unit, that unit can demonstrate many more results than the sum of results from each event on its own. Programs follow this rule. With each new method added to a program, the set of possible flows of control through the program grows dramatically. In large programs, it can quickly grow out of control. And like a perverse magic trick, sometimes the direction you expect is not where you go—it is similar to what can happen when you overload or override methods. Before we continue, notice that I am distinguishing method overriding (where a subclass redefines an inherited method) from method overloading (where a class defines two or more methods using the same name but different argument types). Method dispatch in an object-oriented language such as Java, in which methods can be overloaded and overridden, can cause difficulties of code management even in moderately complex programs. We will discuss the Broken Dispatch bug pattern, one of the more prominent patterns caused by these difficulties, outlining the symptoms that appear when argument mismatches cause the wrong method to be invoked, and offering a few solutions to combat the problem. Here's a summary of this bug pattern: - Pattern: Broken Dispatch. - Symptoms: A test case for code you haven't touched suddenly breaks, just after you've overloaded another method. - Cause: The overloading has caused the untouched method to invoke a method other than the one intended. - Cures and Preventions: Either put in explicit upcasts or rethink the set of methods you're providing on your various classes. One of the most powerful features of an object-oriented language is inheritance polymorphism. This feature allows us to override methods depending on the run-time type of the receiver. Another powerful feature is static overloading, which allows us to overload methods depending on the static types of the arguments. However, these two language features can introduce problems when used together. It can be easy in a large program to overload a method in one class and in the process break code that previously worked in another class. About This Bug Pattern Although Java programmers quickly learn the rules governing which method will be called on an invocation, it's not hard to accidentally break one method by overloading another method that it relies on. The Broken Dispatch pattern can be described as follows: - The arguments to an overloaded method (such as foo()) are passed to another method (such as bar()) that takes more general types. - bar() then invokes foo() with these arguments. - Because the static types of these arguments inside the scope of bar() are more general, the wrong version of method foo() might be invoked. Errors like these can be difficult to diagnose because they can be introduced simply by adding new methods (as opposed to modifying existing ones). Also, the program execution may continue for some time before problems are discovered. The Symptoms To illustrate the nature of this pattern, let's consider the following example code: Implementing the Immutable Lists interface List {}class Empty implements List { public boolean equals(Object that) { return (that != null) && (this.getClass() == that.getClass()); } } class Cons implements List { Object first; List rest; Cons(Object _first) { this.first = _first; this.rest = new Empty(); } Cons(Object _first, List _rest) { this.first = _first; this.rest = _rest; } public Object getFirst() { return this.first; } public List getRest() { return this.rest; } public boolean equals(Object that) { // The semantics for equals specified in the Sun JDK 1.3 API require that // we return false for x.equals(null), x non-null. if (that == null) { return false; } if (this.getClass() != that.getClass()) { return false; } else { // that instanceof Cons Cons _that = (Cons)that; return (this.getFirst().equals(_that.getFirst())) && (this.getRest().equals(_that.getRest())); } } } Recall that we implemented linked lists as containers for these immutable lists. But now let's suppose that we're implementing linked lists in a separate package in which we know that all instances of class LinkedList will be lists of Strings. We could write the constructors to enforce this invariant as follows: Defining Enforcement Parameters for Linked Lists public class LinkedList { private List value; /** * Constructs an empty LinkedList. */ public LinkedList() { this.value = new Empty(); } /** * Constructs a LinkedList containing only the given element. */ public LinkedList(String _first) { this.value = new Cons(_first); } /** * Constructs a LinkedList consisting of the given Object followed by * all the elements in the given LinkedList. */ public LinkedList(String _first, LinkedList _rest) { this.value = new Cons(_first, _rest.value); } public Object getFirst() { return this.value.getFirst(); } public LinkedList getRest() { return new LinkedList(this.value.getRest()); } public void push(String s) { this.value = new Cons(s, this.value); } public String pop() { String result = (String)this.value.getFirst(); this.value = this.value.getRest(); return result; } public boolean isEmpty() { return this.value instanceof Empty; } public String toString() { ... } ... } Suppose we write this code and all the test cases work. Or, more realistically, let's suppose that the code doesn't work at first, but that we manage to get it working after a few debugging cycles. Perhaps several months later you develop a new constructor on class Cons that takes a String representation of the list as its only argument (Appendix A contains some sample code that illustrates this). Such a constructor is quite useful—it allows us to construct new lists with expressions such as the following: New Constructor Takes Only String Representation of List as Argument // equivalent to new Cons("this", new Cons("is", new Cons("a", new Cons("list", //new Empty())))) new Cons("(this is a list)") // equivalent to new Cons("so", new Cons("is", new Cons("this", new Empty()))) new Cons("(so is this)") // equivalent to new Cons("this",// new Cons("list",// new Cons("contains",// new Cons("a",// new Cons(new Cons("nested",// new Empty()),// new Cons("list",// new Empty())))))) new Cons("(this list contains a (nested) list)") So, we write this constructor and all the test cases for it work. Great! But then we notice that some of the tests for methods on class LinkedList suddenly break. What's going on? The Cause The problem is with the constructor on class LinkedList that takes a single String as its argument. This constructor previously called the underlying constructor on class Cons. But now that we've overloaded that constructor with a more specific method, one that takes a String as an argument, this more specific method is invoked. Unless the String passed to the LinkedList constructor is a valid representation of a Cons, the program will crash when trying to parse it. Worse yet, if that String does happen to be a valid representation of a Cons, the program will continue to execute with corrupt data. In that case, we would have introduced a saboteur into the data. The Broken Dispatch bug, like other bug patterns, is easiest to diagnose in code that is test infested (to borrow from the terminology of extreme programming), in which all but the most trivial methods have corresponding unit tests. In such an environment, the most common symptom will be a test case for code you haven't touched that suddenly breaks. When this happens, it's possibly a case of the Broken Dispatch pattern. If the test case breaks immediately after you overload another method, it almost certainly is. If the code isn't loaded with tests, things become more difficult. The bug might produce symptoms such as method invocations that return much more quickly than expected (and with incorrect results). Alternatively, you might find that certain events that were supposed to occur never did (because the appropriate method was never executed). Remember that symptoms like these can also be attributed to other bug patterns. If you encounter such symptoms, your best bet is to begin writing more unit tests, starting with the methods in which the error was discovered and working back through the program execution. Cures and Preventions The nice thing about this bug pattern is that there are some simple solutions. The most straightforward cure is to upcast the arguments in the method invocation. In our example, this would mean rewriting the relevant LinkedList constructor as follows: Upcasting the Arguments in the Method Invocation public LinkedList(String _first) { this.value = new Cons((Object)_first); } Of course, this approach solves the problem only for this one call to the Cons constructor. There may be other calls where we have to upcast, and this technique might become cumbersome for clients of the Cons class. In cases like these, you have to weigh the advantage you gain from having this convenient constructor against the potential for errors it introduces. This dilemma is yet another example of the tension that exists between the expressiveness and the robustness of an interface. One way to get the best of both worlds would be to replace the String constructor on Cons with a static method that takes a String and returns a new Cons object. In fact, this is a strictly better solution in examples like this one, where we want to perform sophisticated object initialization based on the constructor arguments. Including static methods that return new instances of a class is a design pattern known as the Factory Method pattern. See Resources for more information on design patterns. A good preventative measure for this bug pattern is to avoid overloading methods entirely. Unlike method overriding, overloading is seldom needed or justified. A Brisk Walk Through the Problem Starting with our example, we've implemented LinkedLists as containers for immutable lists. We write a constructor to enforce the invariant that "all instances of class LinkedList will be lists of Strings." Later, we write a new constructor that takes a String representation of the list as its only argument. Test cases for the new constructor work, but some method tests on class LinkedList break. Why? We've overloaded the constructor with a more specific method. Results: If the String passed to the LinkedList constructor isn't a valid representation, it won't parse. If the String is coincidentally valid, the program will continue, but with corrupt data. What We've Learned In this atricle on the Broken Dispatch bug pattern we've learned the following: - Broken Dispatch can be described as follows: (1) The arguments to an overloaded method (method1) are passed to another method (method2) that takes more general types; (2) method2 invokes method1 with these arguments; (3) Because the static types of these arguments inside the scope of method2 are more general, the wrong version of method1 might be invoked. - Broken Dispatch errors can be difficult to diagnose because they can be introduced simply by adding new methods. Also, program execution may continue for some time before problems are discovered. - In a test-laden environment, the most common symptom will be a test case for code you haven't touched that suddenly breaks. If the test case breaks immediately after you overload another method, this bug pattern is almost certainly the culprit. - The most straightforward cure for this bug is to upcast the arguments in the method invocation. A good preventative measure is to avoid overloading methods. Remember, argument structure is a key component to assuring that when you overload or override a method, the call invokes the intended method. About the Author: No further information. Related Online Articles: - Bug Pattern in Java - The Impostor Type - Bug Patterns in Java - The Fictitious Implementation - Bug Pattern in Java - Agile Methods in a Chaotic Environment - Bug Pattern in Java - Other Obstacles to Factoring Out Code. - Bug Pattern in Java - Bug Specifications & Implementations - Bug Pattern in Java - Saboteur Data - Bug Pattern in Java - The Double Descent - Bug Pattern in Java - The Liar View - Design Patterns for Debugging - Maximizing Static Type Checking - Bug Patterns in Java - The Run-On Initialization
http://www.getgyan.com/show/2340/Bug_Pattern_in_Java_-_The_Broken_Dispatch
CC-MAIN-2017-30
refinedweb
2,048
52.9
This and DS3231) - Complete Guide for DHT11/DHT22 Humidity and Temperature Sensor With Arduino - Guide to SD Card module with Arduino Parts required Here’s a complete list of the parts required for this project: - Arduino UNO – read Best Arduino Starter Kits - SD card module - Micro SD card - DHT11 temperature and humidity sensor - RTC module - Breadboard - Jumper wires Note: alternatively to the SD card module, you can use a data logging shield. The data logging shield comes with built-in RTC and a prototyping area for soldering connections, sensors, etc.. You can use the preceding links or go directly to MakerAdvisor.com/tools to find all the parts for your projects at the best price! Schematics The following figure shows the circuit’s schematics for this project. Note: make sure your SD card is formatted and working properly. Read “Guide to SD card module with Arduino“. Installing the DHT sensor library For this project you need to install the DHT library to read from the DHT11 sensor. - Code Copy the following code to your Arduino IDE and upload it to your Arduino board. /* * Rui Santos * Complete Project Details */ #include <SPI.h> //for the SD card module #include <SD.h> // for the SD card #include <DHT.h> // for the DHT sensor #include <RTClib.h> // for the RTC //define DHT pin ); // change this to match your SD shield or module; // Arduino Ethernet shield and modules: pin 4 // Data loggin SD shields and modules: pin 10 // Sparkfun SD shield: pin 8 const int chipSelect = 4; // Create a file to store the data File myFile; // RTC RTC_DS1307 rtc; void setup() { //initializing the DHT sensor dht.begin(); //initializing Serial monitor Serial.begin(9600); // setup for the RTC while(!Serial); // for Leonardo/Micro/Zero if(! rtc.begin()) { Serial.println("Couldn't find RTC"); while (1); } else { // following line sets the RTC to the date & time this sketch was compiled rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); } if(! rtc.isrunning()) { Serial.println("RTC is NOT running!"); } // setup for the SD card Serial.print("Initializing SD card..."); if(!SD.begin(chipSelect)) { Serial.println("initialization failed!"); return; } Serial.println("initialization done."); //open file myFile=SD.open("DATA.txt", FILE_WRITE); // if the file opened ok, write to it: if (myFile) { Serial.println("File opened ok"); // print the headings for our data myFile.println("Date,Time,Temperature ºC"); } myFile.close(); } void loggingTime() { DateTime now = rtc.now(); myFile = SD.open("DATA.txt", FILE_WRITE); if (myFile) { myFile.print(now.year(), DEC); myFile.print('/'); myFile.print(now.month(), DEC); myFile.print('/'); myFile.print(now.day(), DEC); myFile.print(','); myFile.print(now.hour(), DEC); myFile.print(':'); myFile.print(now.minute(), DEC); myFile.print(':'); myFile.print(now.second(), DEC); myFile.print(","); } Serial.print(now.year(), DEC); Serial.print('/'); Serial.print(now.month(), DEC); Serial.print('/'); Serial.println(now.day(), DEC); Serial.print(now.hour(), DEC); Serial.print(':'); Serial.print(now.minute(), DEC); Serial.print(':'); Serial.println(now.second(), DEC); myFile.close(); delay(1000); }.close(); } void loop() { loggingTime(); loggingTemperature(); delay(5000); } In this code we create a loggingTime() function and a loggingTemperature() function that we call in the loop() to log the time and temperature to the DATA.txt file in the SD card. Open the Serial Monitor at a baud rate of 9600 and check if everything is working properly. Getting the data from the SD card Let this project run for a few hours to gather a decent amount of data, and when you’re happy with the data logging period, shut down the Arduino and remove the SD from the SD card module. Insert the SD card on your computer, open it, and you should have a DATA.txt file with the collected data. You can open the data with a text editor, or use a spreadsheet to analyse and process your data. The data is separated by commas, and each reading is in a new line. In this format, you can easily import data to Excel or other data processing software. Wrapping up This is a great project to learn how to use the SD card module with Arduino to build a data logger. You can apply this concept in pretty much any project you’d like. If you like Arduino projects, make sure you check our latest Arduino course: Arduino Step-by-step Projects – Build 23 Projects We hope you’ve found this project useful. Thanks for reading. 37 thoughts on “Arduino Temperature Data Logger with SD Card Module” Hi, Earlier I have uploaded temperature data to cloud but this one I never tried. Will follow your tutorial first with Arduino then will do that with ESP. Thanks for your excellent posts.- Anupam Hi Anupam. Thanks for your support. Regards Boa tarde poderia me ajudar a colocar os dados armazenados no sdcard na nuvem? Msolucoes at yahoo.com Rui, I could not get this sketch to work initially. After a lot of ‘head scratching’, I discovered that only the RTClib library from Adafruit would work. Other versions could not find the RTC module. can I also connect a DS1302 RTC-Module and if I can How? Hi. Yes, you can add an RTC. We don’t have any tutorial with that specific RTC. But you can take a look at DS1302 RTC module tutorial on the Arduino official website: playground.arduino.cc/Main/DS1302 I hope this helps 🙂 Regards, Sara 🙂 it was a great post, was just looking for something like this, can we get date & time as strings with a DS1307, thank u I don’t have any examples on that exact subject, but you can convert it to strings Hi. I tried it and everything works,but the temperature just shows 25 c and doesn’t change at all. Can you try with a different sensor? It looks like you’re sensor is fried or having problems… Works great! Thanks Rui and Sara. pls can you tell me how to add LCD into this code thnks Hi. You can follow our LCD tutorial and see if it helps: Regards, Sara Hello How can i read Temperature from 10 DS18B20 temperature sensors and create a .txt file from Sd card with arduino nano? Yes. I think you can do that. Regards, Sara Thanks Sara, i may joined late, but i tried it it give an error compiling for board arduino. please isthere any there solution thanks in advance. Hafid What’s exactly the compilation error? Regards, Sara Hi and Obrigado for your project! Inadvertently I purchased the DHT22 which only has 3 pins whereas the DHT 11 has 4. Is it possible to use the DHT22 and if so could you tell me what connections I should make? This is what I bought: amazon.de/DHT11-Digitaler-Temperatursensor-und-Feuchtigkeitssensor/dp/B07MN7TMXH Hi Michael. Yes, you can use that one. Usually those modules have the following pinout from left to right: VCC – Data – GND You can connect the data pin directly to an Arduino pin. You don’t need the resistor, because these modules already have a resistor built-in. Regards, Sara Hi Sara, Everything is working perfectly (including measuring humidity) although my 3-pin sensor still seems to need the resistor. I have now removed the Uno and installed a Nano Every as I would like to design a circuit board (with Fritzing) and make it completely stand-alone. But … for my project I need to add another two sensors. I will be measuring temperature inside and outside (2 sensors) and water temperature (3rd sensor, probably DS18b20 Waterproof Temperature Sensor). So I have a couple of questions: 1 – Can I add two extra sensors, and if so, which pins should I connect them to. Would 3 and 5 be OK? Is it critical? 2 – What would you suggest is the maximum length cable for the sensors? The board will be in a swimming pool area with the water sensor nearby, so no problem there. But how far away can I put the outside temperature sensor – is 5 metres too far? 3 – Would it be a good idea to use a 12v power supply (through VIN) rather than 5 volt through the USB port? Your project has inspired me and I’m learning a lot from it – thank you so much! Michael Hi Michael. You should have no problem adding more sensors. Those pins seem good to me. But you need to experiment and see how the board behaves. As for the maximum length, that is something that you have to try yourself. Very long cables introduce noise in your readings. But you really need to experiment to see the results. You can power the Arduino through the VIN pin using 6 to 12V power source. So, you should have no problem. I’m glad you’re learning from our tutorials. Thank you so much for following our work. Regards, Sara Thank you so much Sara – I’ll let you know how I get on 🙂 Best wishes, Michael Hello, I followed the tutorial and finf it exactly what I want. I went out and got the RTC you suggested as well but it kept on displaying some other times so I followed your tutorial on (I did the // to Retain the time in the Real Time Clock) which was working until I put the RTC back onto the above project. Its now displaying the incorrect time again. Any clues? Hi Paul. To retain the time on the RTC, it needs to be powered by its battery. Are you using a battery on the RTC? Regards, Sara Hi Sara. Yes I am using the battery on the RTC. I checked the battery and 3.7V so is good there. Do I need to alter any code in the Arduino Temp Logger sketch to prevent it from resetting the time when this sketch first boots up? These times seem all over the place. The RTC is brand new from an dedicated electronics store in Australia (Jcar) I’ve ran the RTC clock again and put it straight back into the powered down nano (but haven’t reloaded the sketch again) to see if this keeps the time up to date. The Nano pins are exactly the same which I’m really happy about – thanks for the additional instructions for those who don’t have a Uno’s. I really like these tutorials on this site as it gives additional info for those who have found other boards to explore on. Although I have had the RTC problem I love this project so much I have already made up a protoboard and am using the project already to monitor temps (soldered female headers in case I want to recycle any parts in the future) Although its pretty ugly to look at I am so happy. Hi Paul. That’s great what you’re doing with this project. You don’t need to change anything on the code. When you upload the code, the RTC adjust the date and time for the time you uploaded the sketch. I’m not sure what is happening because we created this tutorial a long time ago. But probably, it resets the time every time on boot or reset. I think you need to upload the code as it is the first time to adjust the RTC time. Then, upload the code again byt with this line commented like so: //rtc.adjust(DateTime(F(DATE), F(TIME))); I hope this helps. Regards, Sara //rtc.adjust(DateTime(F(DATE), F(TIME))); It worked. Hope this helps anyone else who liked the project and has had trouble with the RTC. I waited a few days to see if it would be consistent. Thank you. Hello, For my first Arduino project, I want to collect 1 year room temperature data. I was curious if this setup is build for this purpose (are the used components able to work for this long?), and what the amount of space one data point takes on the SD card. Thanks in advance! Hi. It depends how frequent you write data to the card. However, a .txt file doesn’t occupy much space. Regards, Sara Hello, Did this with a DS3231 RTC. Was ok but the library doesn’t do isrunning() for the DS_3231. Commented that out and reran, and all ran good. did you change RTC_DS1307 to RTC_DS3231? Hello, I am Ankit Marda, and I am getting the following issue: Arduino: 1.8.15 (Windows Store 1.8.49.0) (Windows 10), Board: “Arduino Uno” In file included from C:\Users\Ankit\Documents\Arduino\libraries\DHT\DHT_U.cpp:15:0: C:\Users\Ankit\Documents\Arduino\libraries\DHT\DHT_U.h:36:10: fatal error: Adafruit_Sensor.h: No such file or directory #include <Adafruit_Sensor.h> ^~~~~~~~~~~~~~~~~~~ compilation terminated. exit status 1 Error compiling for board Arduino Uno. This report would have more information with “Show verbose output during compilation” option enabled in File -> Preferences. Hi. You need to install the ADafruit_Sensor library. In your Arduino IDE, go to Sketch > Include Library > Manage Libraries and search for “Adafruit Unified Sensor” and then, install the library: Regards, Sara Great post and very well explained. Tried the project and worked like a charm. I believe that the DHT11 can also measure humidity. It will be great to use both features of the sensor. What code line do I need to apply to read and log the humidity? where in the code I should place the additional line? I am new in the coding but your feedback will greatly help to understand. Thanks again Hi. To learn how to get humidity from the DHT11 sensor, you can check this tutorial: – You can change the loggingTemperature() function to also display the humidity. See below:); float h = dht.readHumidity(); //--> gets humidity //.print(h); //--> saves humidity myFile.print(","); } myFile.close(); } I hope this helps, Regards, Sara Thank you ! I’ve a question, I should activate a relay every 20 minutes for 2 minutes, using real time, using rtc ds3231, would you be able to help?
https://randomnerdtutorials.com/arduino-temperature-data-logger-with-sd-card-module/
CC-MAIN-2022-40
refinedweb
2,329
75.71
Here's a programming challenge: Evaluate the following recurrence relation efficiently for a given array [x0, …, xn−1] and integer k. Hint: Use dynamic programming. In words: - If the array has only two elements, then the result is the average of the two elements. - If the array has more than two elements, then then the result is the sum of the following: - Half the value of the function evaluated on the array with the first element deleted and the second parameter incremented by one. - Half the value of the function evaluated on the array with the last element deleted and the second parameter incremented by one. - If the second parameter is even, then also add the average of the first and last elements of the original array. The traditional approach with dynamic programming is to cache intermediate results in anticipation that the values will be needed again later. The naïve solution, therefore, would have a cache keyed by the vector and k. My habit when trying to solve these sorts of recurrence relations is to solve the first few low-valued cases by hand. That gives me a better insight into the problem and may reveal some patterns or tricks. Even just doing this one computation, we learned a lot. (Each of which can be proved by induction if you are new to this sort of thing, or which is evident by inspection if you're handy with math.) First observation: The function is linear in the array elements. In other words, To save space and improve readability, I'm using vector notation, where adding two vectors adds the elements componentwise, and multiplying a vector by a constant multiples each component. The long-form version of the first of the above equations would be Since the result is a linear combination of the vector elements, we can work just with the coefficients and save ourselves some typing. ("Move to the dual space.") For notational convenience, we will write Second observation: The specific value of k is not important. All that matters is whether it is even or odd, and each time we recurse to the next level, the parity flips. So the second parameter is really just a boolean. That greatly reduces the amount of stuff we need to cache, as well as increasing the likelihood of a cache hit. (The naïve version would not have realized that f (x, k) can steal the cached result from f (x, k + 2).) Our previous hand computation can now be written as Now that we are working with coefficients, we don't need to deal with x any more! All that matters is the length of the vector. This makes our recurrences much simpler: Now we can carry out a few more hand computations. The interesting thing to observe here is that the recursion does not branch. When we reduce the size of the vector by one element, the recursive calls are basically identical. We have to shift the coefficients differently in order to build up the results, but the recursive call itself is unchanged. This means that we need to perform only n−2 recursive steps to compute f (n, k). Okay, now that we've studied the problem a bit, we can write the code. I'll write three versions of the function. The first computes according to the recurrence relation as originally written. We use this to verify our calculations. function f1(x, k) { if (x.length == 2) { return (x[0] + x[1]) / 2; } var term = 0; if (k % 2 == 0) { term = (x[0] + x[x.length - 1]) / 2; } return term + f1(x.slice(0,-1), k + 1) / 2 + f1(x.slice(1), k + 1) / 2; } Immediate window: f1([1,2,3], 0) = 4.0 Okay, that matches our hand calculations, ¾·1 + ½·2 + ¾·3 = 4. Now let's do the straight recursive version. function dotproduct(a, x) { var total = 0; for (var i = 0; i < a.length; i++) total += a[i] * x[i]; return total; } function f2a(n, k) { if (n == 2) return [1/2, 1/2]; var c = new Array(n); for (var i = 0; i < n; i++) c[i] = 0; if (k % 2 == 0) { c[0] = 1/2; c[n-1] = 1/2; } var inner = f2a(n-1, k+1); for (var i = 0; i < n - 1; i++) { c[i] += inner[i] / 2; c[i+1] += inner[i] / 2; } return c; } function f2(x, k) { return dotproduct(f2a(x.length, k), x); } Immediate window: f2([1,2,3], 0) = 4.0 Notice that there is no dynamic programming involved. The hint in the problem statement was a red herring! Finally, we can eliminate the recursion by iterating n up from 2. function f3(x, k) { var c = new Array(x.length); for (var i = 0; i < x.length; i++) c[i] = 0; c[0] = 1/2; c[1] = 1/2; for (var n = 3; n <= x.length; n++) { var carry = 0; for (var i = 0; i < n; i++) { var nextcarry = c[i]; c[i] = (carry + c[i]) / 2; carry = nextcarry; } if ((k + n + x.length) % 2 == 0) { c[0] += 1/2; c[n-1] += 1/2; } } return dotproduct(c, x); } I pulled a sneaky trick here in the place we test whether we are in the even or odd case. Officially, the test should be if ((k + (x.length - n)) % 2 == 0) { but since we are interested only in whether the result is even or odd, we can just add the components together, because subtraction and addition have the same effect on even-ness and odd-ness. (If I really felt like micro-optimizing, I could fold x.length into k.) Okay, now that we have our code, let's interpret the original problem. The expression ⟨f (n, k) / 2, 0⟩ + ⟨0, f (n, k) / 2⟩ takes the vector f (n, k) and averages it against a shifted copy of itself. (The word convolution could be invoked here.) If you think of the coefficients as describing the distribution of a chemical, the expression calculates the effect of diffusion after one time step according to the simple model "At each time step, each molecule has a 50% chance of moving to the left and a 50% chance of moving to the right." (Since the length of the vector varies with n, I'll visualize the vector drawn with center-alignment.) The base case ⟨½, ½⟩ describes the initial conditions of the diffusion, where half of the chemicals are on the left and half are on the right. This is one time step after one unit of the chemical was placed in the center. Let's get rid of the extra term in the recurrence and focus just on the diffusion aspect: If you compute these values, you'll see that the results are awfully familiar. I've pulled out the common denominator to avoid the ugly fractions. Yup, it's Pascal's Triangle. Notice that the sum across the row equals the amount we are dividing by, so that the sum of the row is always 1. (This is easy to see from the recurrence relation, since the base case establishes the property that the sum of the coordinates is 1, and the recurrence preserves it.) This means that we can calculate the coefficients of d(n) for any value of n directly, without having to calculate any of coefficients for smaller values of n. The coefficients are just row n of Pascal's triangle, which we know how to compute in O(n) time. Now we can also interpret the extra term we removed at the even steps. That term of the recurrence simulates adding a unit of chemical to the solution at every other time step, half a unit at the left edge and half at the right edge. And we can calculate these directly in the same way that we calculated the diffusion coefficients, since they basically are the diffusion coefficients, just with a time and location adjustment. I pulled a fast one here. Maybe you didn't pick up on it: I'm assuming that the two parts of the recurrence unrelated to the diffusion behavior (the base condition and the extra term at the even steps) are independent and can simply be added together. You can show this by noting that given the generalized recurrence then fG+H = fG + fH. (As before, induct on the recurrence relations.) Therefore, we can solve each of the pieces separately and just add the results together. If I had the time and inclination, I could work out the solution for or something similar to that. Like I said, I ran out of time and inclination. But if I could come up with an efficient way to compute that value for all values of i for fixed n (and I believe there is, I'm just too lazy to work it out), then I would have an O(n) solution to the original recurrence. (Okay, so the "If I had the time" bit is a cop-out, but I sort of lost interest in the problem.) Should I consider a career change if I fall asleep after reading the first few lines? @Mungo: If you were like me and started feeling drowsy, but able to understand what was going on, then don't worry about it. Mathematics does it to me all the time. If on the other hand you don't understand, then the I would urge you at the very least to learn. While you can get things done as a programmer by throwing code together, this post is all about gaining optimisation opportunities through understanding mathematically what is going on. It is surprising how much mathematics is involved with computing, which is why all of the decent computer science degree courses I know involve discrete mathematics, complexity and automata as modules. Having a pretty decent foundation in other areas is also rather important. (In the f3() solution) What do you actually gain by the "sneaky trick" of using (k + n + x.length) instead of (k + (x.length – n))? Is subtraction somehow less efficient than addition? Also, I would have instinctively removed the need for carry and nextcarry in this section var carry = 0; for (var i = 0; i < n; i++) { var nextcarry = c[i]; c[i] = (carry + c[i]) / 2; carry = nextcarry; } by going through the list in reverse order: for (var i = n-1; i > 0; i++) { c[i] = (c[i] + c[i-1]) / 2; } c[0] /= 2; Except that obviously that should be i– in my version of the loop. I always get that wrong the first time. @Crescens2k People often say these things, but don't provide concrete examples outside of gaming, data analysis, and specialised scientific/mathematics/development (e.g. writing my own compiler) applications. The core question is "What relevance is the conceptual example given, specifically, going to have to my software development career? I can only learn so many things, so why should I spend my time on Thing X rather than Thing Y?" @Anon I should add that the example may have no relevance at all, and simply be trivia or a brainteaser — in which case, the question is irrelevant. But for my comment, assume the larger issue of "Why do people ask 'Why do I need to know this?'" Here's a cute one someone taught me years ago: Simplify the following expression: (x-a)(x-b)(x-c)…(x-z) Myria: am I right in thinking you want the answer 0? @Smithers: "Is subtraction somehow less efficient than addition?" Actually, yes, sometimes it is. The x86 "lea" instruction is often used to do three-operand addition. The x86 can't normally do three-operand anything, but lea lets you use the specialized addressing modes. However, the x86 doesn't have subtraction in its addressing modes – only addition and optional multiplication by 2, 4, and 8. @Mark: =^-^= @Anon: One example is if you are comparing two lists of strings. If the lists are unsorted, how long would it take to compare? For both lists being unsorted for every item in one list you would have to start from the beginning of the other. You can stop early if you find the item you are looking for, but you can't stop early in any other case. For the string itself, again, you can compare as far as needed in the string but it is hard to do more than that. What happens if both lists are sorted? You can start after the start of one list if you have found an item already, you know that any item in the list you are comparing against will always come after the one you found. You are also able to make other optimisations, like only comparing as many letters as needed until you find a difference, even skipping blocks of the array by first letter comparison alone. While there are many things that be commented on in this example, the fact is that this kind of runtime analysis for even regular functions is in the area of complexity. Of course it is possible to make this kind of reasoning regardless, but learning the mathematics behind it not only formalises the knowledge, but as I often find, you start doing these things implicitly. This reminds me how few years ago I participated in a contest for young programmers. One of the tasks was to efficiently calculate 1+2+3+…+1978 in as many high-level programming languages as possible. This was my special hobby these days, so I quickly wrote the simple for loop in 20+ languages, ranging from COBOL to Lisp (have I mentioned that the year was 1978?). To my shame, this solution was rated second after the one that simply printed 1957231. To my understanding, your "iterating up from 2" example is dynamic programming; you are computing the result bottom up with a cache that lets you reuse previous results. This is no different than the first example usually given for dynamic programming the Fibonacci number N; which is O(2^N) for the recursive formulation: int f(int n) { if (n == 0 || n == 1) { return 1; } return f(n – 2) + f(n – 1); } but O(N) for the dynamic programming version: int f(int n) { int nMinusTwo = 1; int nMinusOne = 1; // This is the "cache" of dynamic programming for (int idx = 2; idx <= n; ++idx) { int currentN = nMinusTwo + nMinusOne; nMinusTwo = nMinusOne; nMinusOne = currentN; } return nMinusOne; } (Your recursive version indeed uses no dynamic programming and that's the point of the article; but people may be confused after seeing the second which does have it) int f(int n) {-Raymond] cache[0] = cache[1] = 1; for (int idx = 2; idx <= n; ++idx) { cache[idx] = cache[idx - 2] + cache[idx - 1]; } return cache[n]; } Wait. You're just numerically solving an initial-boundary value problem for the one-dimensional heat equation, aren't you? Or am I just seeing things at 2 AM? "To my shame, this solution was rated second after the one that simply printed 1957231." I would not have rated it second to that, but I would have rated it second to 1978 * (1978 + 1) / 2, assuming that the assignment was in fact "calculate the answer to" and not simply "print the answer to". @Anon: This question is exactly analogous to "People tell me I should lift weights, but what relevance does this have, specifically, to my career?". The reason you solve problems like this is that mental exercise builds mental muscles just like physical exercise builds physical muscles. You're not going to find yourself needing to lift a barbell in (nearly) any career, either. But you will need to do *analogous* things if you have a career where upper-body strength is important. Additionally, it will improve your general physical fitness, which will have beneficial effects on your overall well-being. Programming is a career where this kind of mental strength is extremely useful, if not actually absolutely vital. And it will improve your general mental fitness, which will have beneficial effects on your overall well-being. This problem is probably more complicated (mathematically) than most you will encounter in day-to-day programming, this is true. But you want those problems you do encounter to be *easy* for you to solve, not a huge struggle. Either way, it's just a oneliner: perl -le "$i += $_ and print $i for 1 .. 1978" @BOFH: And now in as may high-level programming languages as possible… @GregM: you are right, now I remember that the actual prize-winner did exactly as you said, writeln(1978*(1978+1)/2). I would have thought that merely printing "1957231" should be disqualified for a) the inefficiency in having the programmer calculate the result instead of the computer and/or b) not including the algorithm used to calculate the result as part of the submission. (I would accept a solution that moved the computation from the executable to the compiler or optimiser.) Finally, one that is correctly rendered using Internet Explorer, but not using Chrome This article should be re-named "The dangers of buffering up posted messages and then reposting them later". alegr1: itym articles Chrome fixed, many thanks from my Android device! This is still dynamic programming. You are computing values in a table and updating it (as a function of pre-existing values in the table) and arriving at the answer: dynamic programming. You did it bottom-up instead of top-down with memoization, that's all.
https://blogs.msdn.microsoft.com/oldnewthing/20140331-00/?p=1363
CC-MAIN-2017-26
refinedweb
2,935
60.24
Tax Have a Tax Question? Ask a Tax Expert Hi, Your W-2 and the end of the year should have the correct totals for earnings for the year The draw is part of your earnings (and any you have to return should reduce your earnings). Though considered salary and taxable, recoverable draws are much like no-interest loans and must be paid back. In pay periods when earned commissions are less than the contracted draw, the draw account is tapped to compensate for the difference. Draw tap debt accumulates through every pay period used. When sales commissions exceed the contracted minimum, paid draws are deducted from pay in increments that do not reduce remuneration below contract until there is a zero balance. Commissions are paid in full once the draw account is paid in full. At least that's the typical scenario If you've crossed over a year, you may need to get a corrected W-2 Make sense? Say only $10,000 of commissions were earned, so the recoverable draw is $90,000. The total $90,000 is owed correct? Income taxes withheld from the employee are irrelevant, correct? You'd either handle that in two ways (if you've already crossed over the year, and received a W-2 reflecting the withholding) the employer must issue a corrected W-2. OR if the company cannot or will not get it's own over-payment back and issue a corrected W-2 you can always do an amended return for the year and get the refund. I was told that taxes withheld are deducted from the draw owed. This makes no sense to me, since the amount loaned was really the $90,000 and personal income taxes would be my personal responsibility and have nothing to do with the amount I owe. If the employer can't go after the full $90,000, where could I find documentation on that? Does the employee owe $90,000 ($100,000 draw minus $10,000 commissions earned) or only $55,000 ($100,000 draw minus taxes withheld of $35,000 minus $10,000 commissions earned)? No, the way that works is that the company is simply paying the taxes to the government on your behalf ... they do that as part of their quarterly payroll reporting and payments ... It's tied to YOUR social security number ... it's simply a pre-payment of your taxes The company SHOULD , just as an individual, submit an amended 940 to get that back and only capture what you actually owe them the 55,000 in your example one of the biggest penalties out there is withholding from a payroll and not remitting it to the govt They should either make the adjustment on the final W-2 and only come after what they are owed bu YOU and get the rest back from the government OR I suppose if they refuse to do the amended return you could do your own... either they have remitted that to IRS in their quarterly payroll or their stealing... thats the way it works You can always get a transcript of your tax account here: and see if they've been remitting your withholdings as they should My question is what is the actual amount that I owe? Do I owe $90,000 (draw minus commissions earned) or do I owe $55,000? If it's only $55,000 it seems wrong that the company would have to pay for my personal taxes paid in. Again, the taxes paid in are just that a pre-payment of your taxes ... you'll need to talk to your employer about the mechanism for getting that back ... IF they've been keeping it legal, they've paid that to the government already on your behalf (It's YOUR money, but they don't have it any more) ... In my experience (I started out in commission sales as a stock broker MANY MOONS ago) they will only ask you to pay bad the 55,000 because they will amentheir own payroll tax return and get back the withholdings from IRS for themselves The only other two options are (1) They're incompetent, don't know how and you can get this overpayment back from the govt yourself, by doing an amended return showing that you did not actually earn that money or (2) they're stealing the money I think hat will happen is they will only ask you for the 55,000 and get their overpayment back from the IRS themselves ... THIS is the conventional way it's done I would assume I owe $90,000 (draw minus commissions). I would think my taxes withheld have nothing to do with the amount I owe. I ask, because I received advice that a company can only go after the net cash the employee received. I did not believe that advice, because it seems wrong that the company would be penalized and now not owe $35,000 that were simply sent in on my behalf. What is the legal amount the company go after me for? How can they get the overpayment of income taxes back? No, again the advice is correct Hang with me here... The advice is correct? Then how does the employer go about getting all of the taxes that were paid in refunded to them? Yes The have been paying in those taxes as a part of they quarteryly payroll taxes fling to the irs They simply do an amended filing and the IRS givrs them a refund, just as they wold an individual on a form 1040 who overpaid So a company can file an amended return asking for all the taxes back and then on my W-2 it would show no taxes paid in? Thats exactly right Your W-s will show only what you actually earned sorry "W-2" it will show the appropriate withholding for $10,000 in your example What if my termination was in 2013 and I already filed my 2012 income taxes using my draw amount as income and taking the taxes paid in off of my tax balance? You will file an amended return (1040x) showing the change in income amount, and using the explanation box to state that this income was paid back in the form of a recoverable draw so then the company can still file an amended return for 2012 asking for my taxes refunded to them? Don't do it until you've actually paid it back though ... it's pretty common in the industry for companies to write that off and take their OWN tax deduction, meaning that you DID actually receive the income ... IRS will tax SOMEONE Yes they can ... and if recoverable draw is something they've been doing for a while, this will be standard operating procedure Still with me? Questions? sorry. the company hasn't done any recoverable draws until me. sOK ... Sounds like you want to do the right thing .. Maybe you can educate THEM ... Again, if they've been paying in the taxes as they should, they simply cleect from you what YOU own them and from IRS what IRS owes them they don't seem to really know what they're doing regarding draws. They thought I owed $90,000, because they did not know they could get a refund of the taxes. :) looks like our posts crossed Again, there are only two possibilities here, they have been withholding and NOT paying the money into IRS (in which case there's nothing to recover there) and they still need to get that net 55,000 from you ... OR ... They file for a refund with IRS and get the 55,000 from you I do want to do the right thing. :) I should tell them to file amended taxes to get the taxes paid in back, amended my W-2, and my loan amount is only the net cash received. That's right .. that is how i's normally done Thank you!!!!! Now it makes sense. I couldn't understand why the company would be penalized for paying in my taxes, but I also didn't know they could recover them. Yep, in this scenario they are called a withholding agent, but they are entitled to any overpayments just as anyone else If this HAS helped, I'd appreciate positive rating here... that's the only way I get credit for my work But, come back here if you have other questions, so you won't be charged for another question Thanks, Lane Thank you! Where do I come back? Or rather how do I? once you've rate this all stays here ... You can see it on our account (Home) page OR you cna just come straight back this this Page: Some, copy that link into a word document OR you can just save this page as a favorite, bookmark it, in your browser Also, if you'd like to use me as your expert on a different, new, question, just say "For Lane only," at the beginning of the question or you can set me up as a preferred expert on your home page, as well ... hope this has helped Can I help with anything else today? (Sorry just would like to move on to help others) ... If you're done here thanks!!!! all done! Great ... have a good one .. enjoyed working with you Hi Nancy,
http://www.justanswer.com/tax/83kvc-say-recoverable-draw-100-000-paid-w-2-employee.html
CC-MAIN-2016-22
refinedweb
1,579
65.66
Deno is the new Node.js — well, sort of… Why did the guy that made Node.js make a new Node.js? It’s been three years since Ryan Dahl — the same guy behind Node.js — hatched Deno into the world wide web. This opensource and V8 runtime powered serverside has over 80k stars on GitHub, 42k followers on Twitter, and $4.9 million in seed capital from various investors and Mozilla Corporation for its commercialization. But what exactly is Deno? How is Deno different from Node.js? and will it take over as the new Node.js? What is Deno? When Ryan Dahl, the creator of Node.js, released Deno in May 2018 — you can’t help but ask the question: why? During the 2018 JSConf EU, Dahl admitted that lessons were learned from Node.js, especially in the realms of security, modules, and dependencies. Node.js was initially released in 2008 and the landscape of web development was different from what it is today. These things were not exactly at the forefront of design thinking when Node.js was created and JavaScript was still regarded as a gimmick than an actual and powerful programming language. Deno is, in essence, the rebirth of Node.js — better, faster, with better security, and all the lessons that Node.js did not have in its 10-year tenure as the foundation of serverside programming for JavaScript. But what is Deno? In a nutshell, Deno is a serverside engine that lets you write TypeScript code to create your backend. How is Deno different from Node.js? When it comes to Deno, it’s easy to see it as another Node.js. But it’s not. Deno is secure by default. This means that unless you explicitly enable it — all files, network, and environment access is locked. This follows the principle of least privilege, meaning that any security leaks that occur are due to the loosing of security protocols rather than not having it tight enough. Unlike Node.js, Deno restricts access to the file system, network, execution of other scripts, and environment variables by default. For example, if you are building an API, you will need to enable the --allow-net flag in order to open up network connections. Deno run --allow-net app.ts Here’s a quick list of the security flags for Deno: --allow-write: flag for file system access --allow-net: flag for network requests --allow-env: flag for access to the environment --allow-run: flag for running subprocesses Deno also supports TypeScript out of the box, ships as a single executable file and there’s no need to maintain dependencies. Third-party modules are imported directly from the source and then cached the first time it runs, meaning that you can say goodbye to package.json files and package managers. Here is an example of an app.ts code and how libraries are imported: import { Application } from ""; import router from "./routes.ts"; const HOST = "127.0.0.1"; const PORT = 8080; const app = new Application(); app.use(router.routes()); app.use(router.allowedMethods()); console.log(`Listening on port ${PORT} ...`); await app.listen(`${HOST}:${PORT}`); However, loading the external modules from urls can feel teadious and create issues if the link changes for whatever reason. You’d still need to create a centralized export file so that you can use it in multiple spaces. For example, if you have the export below located in a file called local-utils : export { test, assertEquals } from ""; You can use it again like this: import { test, assertEquals } from './local-utils.ts'; Deno also hosts caches releases of open source modules stored on GitHub to ensure uptime and easy-to-remember names that are structured as<moduleNameHere> . What about speed? Both Deno and Node.js uses the same Google V8 engine. So when it comes to performance, you are comparing almost the same thing. However, Deno is built on Rust. In contrast, Node.js is built on C++. This may impact performance as the application grows, but due to Deno’s relative infancy, there aren’t any enterprise reports that are readily available for us to compare. However, Deno does have a benchmark report that is often compared to Node.js that you may find interesting. When it comes to HTTP throughput, Deno comes with lower latency. But overall, Deno and Node.js seem to be almost on par with each other in terms of speed and performance. Deno and Promises Promises are now a pillar of serverside development, especially in JavaScript. Unlike Node.js, Deno uses promises at every level possible. This means that all asynchronous methods return Promises by default. So rather than writing long promise nests, you can just use await instead. Deno also comes with an in-built error failsafe. This means that your application will automatically fail if an API does not contain error handling. Final question — will Deno replace Node.js? There’s probably more that I can write about Deno but there’s only so much one can fit into one piece before it goes off tangent. Node.js is a cornerstone of JavaScript serverside development. It still works, the community is still strong, and it’s not too annoying to use. Deno wasn’t created to replace Node.js. Rather, it was created to provide an alternative solution to Node.js. So will Deno replace Node.js? Probably not. However, as the Deno community and advocacy grows, so will its support and general adoption. Deno is the new kid on the block and by age and design, it will always be easier to use. Deno is not a fork of Node. It’s its own implementation based on modern features of JavaScript. Node.js was created during a time when developing JavaScript didn’t have the features and functionalities that we enjoy today. It’s easy to take for granted things like ES Modules and TypeScript when you’ve been immersed in it long enough. While Node.js still carries the legacies of ye old JavaScript days and its various development quirks, it is also entrenched in startups and enterprises as cornerstone software. In short, Node.js will continue to stick around with Deno as a potential alternative for startups, solopreneurs, and enterprises to choose from. The rise of Deno doesn’t necessarily mean the death of Node.js. Rather, it provides healthy competition and encouragement for both Node.js and Deno to get better and easier to use, in addition to new ideas to flourish in the space known as serverside JavaScript.
https://www.dottedsquirrel.com/about-deno/
CC-MAIN-2022-33
refinedweb
1,097
67.35
Python is an object-oriented programming language, which means that it provides features that support object-oriented programming. It is not easy to define object-oriented programming, but we have already seen some of its characteristics: For example, the Time class defined in Chapter. Strictly speaking, these features are not necessary. For the most part, they provide an. We have already seen some methods, such as keys and values, which were invoked on dictionaries. Each method is associated with a class and is intended to be invoked on instances of that class. Methods are just like functions, with two 13, we defined a class named Time and you wrote a function named printTime, which should have looked something like this: class Time: pass def printTime(time): print str(time.hours) + ":" + \ str(time.minutes) + ":" + \ str(time.seconds) To call this function, we passed a Time object as an argument: >>> currentTime = Time() >>> currentTime.hours = 9 >>> currentTime.minutes = 14 >>> currentTime.seconds = 30 >>> printTime(currentTime) To make printTime a method, all we have to do is move the function definition inside the class definition. Notice the change in indentation. class Time: def printTime(time): print str(time.hours) + ":" + \ str(time.minutes) + ":" + \ str(time.seconds) Now we can invoke printTime using dot notation. >>> currentTime.printTime() As usual, the object on which the method is invoked appears before the dot and the name of the method appears after the dot. The object on which the method is invoked is assigned to the first parameter, so in this case currentTime is assigned to the parameter time. By convention, the first parameter of a method is called self. The reason for this is a little convoluted, but it is based on a useful metaphor. The syntax for a function call, printTime(currentTime), suggests that the function is the active agent. It says something like, "Hey printTime! Here's an object for you to print." In object-oriented programming, the objects are the active agents. An invocation like currentTime.printTime() says "Hey currentTime!. Let's convert increment (from Section 13.3)Time.increment(500) Again, the object on which the method is invoked gets assigned to the first parameter, self. The second parameter, seconds gets the value 500. As an exercise, convert convertToSeconds (from Section 13.5) to a method in the Time class. 1 if self.hour < time2.hour: return 0 if self.minute > time2.minute: return 1 if self.minute < time2.minute: return 0 if self.second > time2.second: return 1 return 0 We invoke this method on one object and pass the other as an argument: if doneTime.after(currentTime): print "The bread is not done yet." from Section 7.7:, it uses the default value and starts from the beginning of the string: >>> find("apple", "p") 1 If we provide a third argument, it overrides the default: >>> find("apple", "p", 2) 2 >>> find("apple", "p", 3) -1 As an exercise, add a fourth parameter, end, that specifies where to stop looking..Time = Time(9, 14, 30) >>> currentTime.printTime() 9:14:30 Because the arguments are optional, we can omit them: >>> currentTime = Time() >>> currentTime.printTime() 0:0:0 Or provide only the first: >>> currentTime = Time (9) >>> currentTime.printTime() 9:0:0 Or the first two: >>> currentTime = Time (9, 14) >>> currentTime.printTime() 9:14:0 Finally, we can make assignments to a subset of the parameters by naming them explicitly: >>> currentTime = Time(seconds = 30, hours = 9) >>> currentTime.printTime() 9:0:30 Let's rewrite the Point class from Section 12.1 operand B. arguments; argument also has to be a numeric value. A function like this that can take arguments with different types is called polymorphic. As another example, consider the method frontAndBack, which prints a list twice, forward and backward: def frontAndBack(front): import copy back = copy.copy(front) back.reverse() print str(front) + str(back) Because the reverse method is a modifier, we make a copy of the list before reversing it. That way, this method doesn't modify the list it gets as an argument. Here's an example that applies frontAndBack to a list: >>> myList = [1, 2, 3, 4] >>> frontAndBackAndBack: >>> p = Point(3, 4) >>> frontAndBack(p) (3, 4)(4, 3) The best kind of polymorphism is the unintentional kind, where you discover that a function you have already written can be applied to a type for which you never planned. Warning: the HTML version of this document is generated from Latex and may contain translation errors. In particular, some mathematical expressions are not translated correctly.
http://greenteapress.com/thinkpython/thinkCSpy/html/chap14.html
CC-MAIN-2017-47
refinedweb
752
58.28
28 August 2012 10:42 [Source: ICIS news] SINGAPORE (ICIS)--South Korea’s Hanwha Chemical shut its facilities in Yeosu for about two hours on Tuesday because of a power outage as Typhoon Bolaven swept through the western coast of the country, a company source said. Typhoon Bolaven has caused heavy rains and strong winds in southern and western parts of ?xml:namespace> Two of Hanwha Chemical’s polyethylene (PE) plants at Yeosu were shut at 6:30 The two plants produce linear low density PE (LLDPE) with a combined capacity of 224,000 tonnes/year, the source said. The PE plants were restarted after about two hours and their production has been raised back to 100%, the source said. Hanwha Chemical’s other PE plants at Yeosu, consisting of a 155,000 tonne/year LLDPE plant, and two low density PE (LDPE) plants with a combined capacity of 327,000 tonnes/year were not affected by the typhoon, he said. Among its other plants that were briefly shut by the power outage include a 680,000 dry metric tonne/year caustic soda; 430,000 tonne/year ethylene dichloride; 360,000 tonne/year vinyl chloride monomer, and; 350,000 tonne/year polyvinyl chloride plants, a source close to the company said. Production loss for the chlor-alkali and PVC units is minimal, the source said. Additional reporting by Feliana Widj
http://www.icis.com/Articles/2012/08/28/9590212/two-hour-outage-hits-hanwha-chemicals-yeosu-units-on-typhoon.html
CC-MAIN-2014-35
refinedweb
230
53.55
Your browser does not seem to support JavaScript. As a result, your viewing experience will be diminished, and you have been placed in read-only mode. Please download a browser that supports JavaScript, or enable it if it's disabled (i.e. NoScript). Hello guys! I know how to merge a scene with a current project. But i have no idea how to insert scene under parent with coordinats of this parent. I want to create custom nulls thats why i want to it. What should i add in this code if i want insert scene under object? import c4d def main(): doc.StartUndo() # Start recording undos path = "C:\Users\Jamaletdinov.r\Desktop\ArrowR.c4d" flags = c4d.SCENEFILTER_OBJECTS | c4d.SCENEFILTER_MATERIALS | c4d.SCENEFILTER_MERGESCENE c4d.documents.MergeDocument(doc, path, flags) c4d.EventAdd() doc.EndUndo() if __name__=='__main__': main() Hi, There's no direct way of doing that. I see two possibilities: The problem is, as you can see on this thread, that some parameters of the xref are not accessible with python. The problem with links can be handle with AliasTrans. Cheers, Manuel hi, hoo thanks a lot @mikeudin I somehow didn't though about this one xD Mike, thank you a lot!
https://plugincafe.maxon.net/topic/13462/insert-scene-under-object/?
CC-MAIN-2021-43
refinedweb
201
67.76
Important: Please read the Qt Code of Conduct - qtscxml: connect to signals I'm playing with qtscxml and I'm running into a problem - here is a simple state machine <?xml version="1.0" encoding="UTF-8"?> <!-- enable-qt-mode: yes --> <scxml xmlns="" xmlns: <state id="s1"> <onentry> <log expr="Now in s1" /> <send event="enter_state1"/> </onentry> <transition event="key_pressed" target="s2"/> </state> <state id="s2"> <onentry> <log expr="Now in s2" /> <send event="enter_state2"/> </onentry> <transition event="key_released" target="s1"/> </state> </scxml> I want to connect to the signals enter_state1 and enter_state2 on the c++ side. QObject::connect(machine, SIGNAL(enter_state1()), this, SLOT(keyLedOff())); QObject::connect(machine, SIGNAL(enter_state1()), this, SLOT(lkeyLedOon())); but I get an error: QObject::connect: No such signal KeyboardStateMachine::enter_state1() What I'm I doing wrong here? - mrjj Lifetime Qt Champion last edited by mrjj @larry104 said: Hi The normal cause for this error is 1: forgot Q_OBJECT macro in a QObject subclass ( your KeyboardStateMachine) 2: Using visual studio and qmake/moc.exe is not run. Update: Did you check the files generated by qscxmlc that they do in fact contain such signals? 1: is done #ifndef KEYBOARD_H #define KEYBOARD_H #include <QObject> #include <QHash> #include <QColor> #include <QDebug> #include "statemachine.h" class Keyboard : public QObject { Q_OBJECT public: explicit Keyboard(QHash<QString, QObject*> keys, QObject *parent = 0); signals: public slots: void ledOn(); void ledOff(); void keyPressed(); void keyReleased(); private: KeyboardStateMachine m_machine; QHash<QString, QObject> m_keys; }; #endif // KEYBOARD_H 2: I'm using qt5.7.0 on ubuntu with qtcreator. My .pro file looks like this: QT += qml quick scxml CONFIG += c++11 SOURCES += main.cpp keyboard.cpp STATECHARTS = statemachine.scxml load(qscxmlc) RESOURCES += qml.qrc QML_IMPORT_PATH = include(deployment.pri) HEADERS += keyboard.h It's interesting the statmachine.h gets only created if I run the compile from commandline. How can I tell qtcreator to run the compile of the statemachine so it finds the .h file - but that's a different issue. But to answer the question the statemachine.h file create when calling qscxmlc statemachine.scxml does not contain the signals - qscxmlc --version is: qscxmlc 1 (Qt 5.7.0) - mrjj Lifetime Qt Champion last edited by Hmm, seems to follow the docs closely so should be ok. STATECHARTS should make qmake run tool. ? I wonder how connect can possible work then if no signals generated. are they somehow exported from QML? Sorry, i have never used this new module so Im afraid we must hope for others to have better suggestions :) I found the problem - to create a qt signal I need to set the following: <send type="qt:signal" event="enter_state1"/> - mrjj Lifetime Qt Champion last edited by
https://forum.qt.io/topic/70538/qtscxml-connect-to-signals/5
CC-MAIN-2021-49
refinedweb
444
56.35
This chapter contains: About Privilege Management Guideline for Granting Privileges Guideline for Granting Roles to Users Guideline for Handling Privileges for the PUBLIC Role Controlling Access to Applications with Secure Application Roles Initialization Parameters Used for Privilege Security You can control user privileges in the following ways: Granting and revoking individual privileges. You can grant individual privileges, for example, the privilege to perform the UPDATE SQL statement, to individual users or to groups of users. Creating a role and assigning privileges to it. A role is a named group of related privileges that you grant, as a group, to users or other roles. Creating a secure application role. A secure application role enables you to define conditions that control when a database role can be enabled. For example, a secure application role can check the IP address associated with a user session before allowing the session to enable a database role. Because privileges are the rights to perform a specific action, such as updating or deleting a table, do not provide database users more privileges than are necessary. For an introduction to managing privileges, see "About User Privileges and Roles" in Oracle Database 2 Day DBA. Oracle Database 2 Day DBA also provides an example of how to grant a privilege. In other words, the principle of least privilege is that users be given only those privileges that are actually required to efficiently perform their jobs. To implement this principle, restrict the following as much as possible: The number of system and object privileges granted to database users The number of people who are allowed to make SYS-privileged connections to the database For example, generally the CREATE ANY TABLE privilege is not granted to a user who does not have database administrator privileges. A role is a named group of related privileges that you grant, as a group, to users or other roles. To learn the fundamentals of managing roles, see "Administering Roles" in Oracle Database 2 Day DBA. In addition, see "Example: Creating a Role" in Oracle Database 2 Day DBA. Roles are useful for quickly and easily granting permissions to users. Although you can use Oracle Database-defined roles, you have more control and continuity if you create your own roles that contain only the privileges pertaining to your requirements. Oracle may change or remove the privileges in an Oracle Database-defined role, as it has with the CONNECT role, which now has only the CREATE SESSION privilege. Formerly, this role had eight other privileges. Ensure that the roles you define contain only the privileges required for the responsibility of a particular job. If your application users do not need all the privileges encompassed by an existing role, then apply a different set of roles that supply just the correct privileges. Alternatively, create and assign a more restrictive role. Do not grant powerful privileges, such as the CREATE DATABASE LINK privilege, to regular users such as user SCOTT. (Particularly do not grant any powerful privileges to SCOTT, because this is a well known default user account that may be vulnerable to intruders.) Instead, grant the privilege to a database role, and then grant this role to the users who must use the privilege. And remember to only grant the minimum privileges the user needs. You should revoke unnecessary privileges and roles from the PUBLIC role. The PUBLIC role is automatically assumed by every database user account. By default, it has no privileges assigned to it, but it does have grants to many Java objects. You cannot drop the PUBLIC role, and a manual grant or revoke of this role has no meaning, because the user account will always assume this role. Because all database user accounts assume the PUBLIC role, it does not appear in the DBA_ROLES and SESSION_ROLES data dictionary views. Because all users have the PUBLIC role, any database user can exercise privileges that are granted to this role. These privileges include, potentially enabling someone with minimal privileges to access and execute functions that this user would not otherwise be permitted to access directly. A secure application role is a role that can be enabled only by an authorized PL/SQL package. The PL/SQL package itself reflects the security policies necessary to control access to the application. This section contains: About Secure Application Roles Tutorial: Creating a Secure Application Role A secure application role is a role that can be enabled only by an authorized PL/SQL package. This package defines one or more security policies that control access to the application. Both the role and the package are typically created in the schema of the person who creates them, which is typically a security administrator. A security administrator is a database administrator who is responsible for maintaining the security of the database. The advantage of using a secure application role is you can create additional layers of security for application access, in addition to the privileges that were granted to the role itself. Secure application roles strengthen security because passwords are not embedded in application source code or stored in a table. This way, the decisions the database makes are based on the implementation of your security policies. Because these definitions are stored in one place, the database, rather than in your applications, you modify this policy once instead of modifying the policy in each application. No matter how many users connect to the database, the result is always the same, because the policy is bound to the role. A secure application role has the following components: The secure application role itself. You create the role using the CREATE ROLE statement with the IDENTIFIED USING clause to associate it with the PL/SQL package. Then, you grant the role the privileges you typically grant a role. A PL/SQL package, procedure, or function associated with the secure application role. The PL/SQL package sets a condition that either grants the role or denies the role to the person trying to log in to the database. You must create the PL/SQL package, procedure, or function using invoker's rights, not definer's rights. An invoker's right procedure executes with the privileges of the current user, that is, the user who invokes the procedure. This user must be granted the EXECUTE privilege for the underlying objects that the PL/SQL package accesses. The invoker's right procedures are not bound to a particular schema. They can be run by a variety of users and enable multiple users to manage their own data by using centralized application logic. To create the invoker's rights package, use the AUTHID CURRENT_USER clause in the declaration section of the procedure code. The PL/SQL package also must contain a SET ROLE statement or DBMS_SESSION.SET_ROLE call to enable (or disable) the role for the user. After you create the PL/SQL package, you must grant the appropriate users the EXECUTE privilege on the package. A way to execute the PL/SQL package when the user logs on. To execute the PL/SQL package, you must call it directly from the application before the user tries to use the privileges the role grants. You cannot use a logon trigger to execute the PL/SQL package automatically when the user logs on. When a user logs in to the application, the policies in the package perform the checks as needed. If the user passes the checks, then the role is granted, which enables access to the application. If the user fails the checks, then the user is prevented from accessing the application. This tutorial shows how two employees, Matthew Weiss and Winston Taylor, try to gain information from the OE.ORDERS table. Access rights to this table are defined in the EMPLOYEE_ROLE secure application role. Matthew is Winston's manager, so Matthew, as opposed to Winston, will be able to access the information in OE.ORDERS. In this tutorial: Step 1: Create a Security Administrator Account Step 2: Create User Accounts for This Tutorial Step 3: Create the Secure Application Role Step 4: Create a Lookup View Step 5: Create the PL/SQL Procedure to Set the Secure Application Role Step 6: Grant the EXECUTE Privilege for the Procedure to Matthew and Winston Step 7: Test the EMPLOYEE_ROLE Secure Application Role Step 8: Optionally, Remove the Components for This Tutorial For greater security, you should apply separation of duty concepts when you assign responsibilities to the system administrators on your staff. For the tutorials used in this guide, you will create and use a security administrator account called sec_admin. To create the sec_admin security administrator account: Start Database Control. See Oracle Database 2 Day DBA for instructions about how to start Database Control. Enter an administrator user name (for example, SYSTEM) and password, and then click Login. For the SYSTEM user, connect as Normal. The Database Home page appears. Click Server to display the Server subpage. Under Security, select Users. The Users page appears. Click Create. The Create User page appears. Enter the following information: Name: sec_admin Profile: Default Authentication: Enter Password and Confirm Password: Enter a password that meets the requirements in "Requirements for Creating Passwords". Default Tablespace: SYSTEM Temporary Tablespace: TEMP Status: UNLOCKED Click Roles to display the Edit User: SEC_ADMIN page. Click Edit List. The Modify Roles page appears. In the Available Roles list, select the SELECT_CATALOG_ROLE role and then then click Move to move it to the Selected Roles list. Then click OK to return to the Edit User page. Click System Privileges to display the System Privileges subpage. Click Edit List. The Modify System Privileges page appears. In the Available System Privileges list, select the following privileges and then click Move to move each one to the Selected System Privileges list. (Hold down the Control key to select multiple privileges.) CREATE PROCEDURE CREATE ROLE CREATE SESSION SELECT ANY DICTIONARY Click OK. The Create User page appears. Under Admin Option, do not select the boxes. Click OK. The Users page appears. User sec_admin is listed in the UserName list. Matthew and Winston both are sample employees in the HR.EMPLOYEES schema, which provides columns for the manager ID and email address of the employees, among other information. You must create user accounts for these two employees so that they can later test the secure application role. To create the user accounts: In the Users page, click Create. The Create User page appears. Enter the following information: Name: mweiss (to create the user account for Matthew Weiss) Profile: DEFAULT Authentication: Enter Password and Confirm Password: Enter a password that meets the requirements in "Requirements for Creating Passwords". Default Tablespace: USERS Temporary Tablespace: TEMP Status: Unlocked Click System Privileges to display the System Privileges subpage. Click Edit List. The Modify System Privileges page appears. In the Available System Privileges lists, select the CREATE SESSION privilege, and then click Move to move it to the Selected System Privileges list. Click OK. The Create User page appears, with CREATE SESSION listed as the system privilege for user mweiss. Ensure that the Admin Option for CREATE SESSION is not selected, and then click OK. The Users page appears. Select the option for user MWEISS from the list of users, and then from the Actions list, select Create Like. Then, click Go. In the Create User page, enter the following information to create the user account for Winston, which will be almost identical to the user account for Matthew: Name: wtaylor Enter Password and Confirm Password: Enter a password that meets the requirements in "Requirements for Creating Passwords". You do not need to specify the default and temporary tablespaces, or the CREATE SESSION system privilege, for user wtaylor because they are already specified. Click OK. You do not need to grant wtaylor the CREATE SESSION privilege, because the Create Like action has done of this for you. Log out of Database Control. Now both Matthew Weiss and Winston Taylor have user accounts that have identical privileges. Now, you are ready to create the employee_role secure application role. To do so, you must log on as the security administrator sec_admin. "Step 1: Create a Security Administrator Account" explains how to create the sec_admin account. To create the secure application role: Start SQL*Plus and log on as the security administrator sec_admin. SQLPLUS sec_admin Enter password: password SQL*Plus starts, connects to the default database, and then displays a prompt. SQL> For detailed information about starting SQL*Plus, see Oracle Database 2 Day DBA. Create the following secure application role: CREATE ROLE employee_role IDENTIFIED USING sec_roles; The IDENTIFIED USING clause sets the role to be enabled (or disabled) only within the associated PL/SQL package, in this case, sec_roles. At this stage, the sec_roles PL/SQL package does not need to exist. Connect as user OE. CONNECT OE Enter password: password If you receive an error message saying that OE is locked, then you can unlock the OE account and reset its password by entering the following statements. For greater security, do not reuse the same password that was used in previous releases of Oracle Database. Enter any password that is secure, according to the password guidelines described in "Requirements for Creating Passwords". CONNECT SYS/AS SYSDBA Enter password: sys_password PASSWORD OE -- First, change the OE account password. Changing password for OE New password: password Retype new password: password Password changed. ALTER USER OE ACCOUNT UNLOCK; -- Next, unlock the OE account. Another way to unlock a user account and create a new password is to use the following syntax: ALTER USER account_name ACCOUNT UNLOCK IDENTIFIED BY new_password: Now you can connect as user OE. CONNECT OE Enter password: password Enter the following statement to grant the EMPLOYEE_ROLE role SELECT privileges on the OE.ORDERS table. GRANT SELECT ON OE.ORDERS TO employee_role; Do not grant the role directly to the user. The PL/SQL package will do that for you, assuming the user passes its security policies. You are almost ready to create the procedure that determines who is granted the employee_role role. The procedure will grant the employee_role only to managers who report to Steven King, whose employee ID is 100. This information is located in the HR.EMPLOYEES table. However, you should not use that table in this procedure, because it contains sensitive data such as salary information, and for it to be used, everyone will need access to it. In most real world cases, you create a lookup view that contains only the information that you need. (You could create a lookup table, but a view will reflect the most recent data.) For this tutorial, you create your own lookup view that only contains the employee names, employee IDs, and their manager IDs. To create the HR.HR_VERIFY lookup view: In SQL*Plus, connect as user HR. CONNECT HR Enter password: password If you receive an error message saying that HR is locked, then you can unlock the account and reset its password by entering the following statements. For greater security, do not reuse the same password that was used in previous releases of Oracle Database. Enter any password that is secure, according to the password guidelines described in "Requirements for Creating Passwords". CONNECT SYSTEM Enter password: password PASSWORD HR Changing password for HR New password: password Retype new password: password Password changed. ALTER USER HR ACCOUNT UNLOCK; CONNECT HR Enter password: password Enter the following CREATE VIEW SQL statement to create the lookup view: CREATE VIEW hr_verify AS SELECT EMPLOYEE_ID, FIRST_NAME, LAST_NAME, EMAIL, MANAGER_ID FROM EMPLOYEES; Grant the EXECUTE privilege for this view to mweiss, wtaylor, and sec_admin by entering the following SQL statements: GRANT SELECT ON hr.hr_verify TO mweiss; GRANT SELECT ON hr.hr_verify TO wtaylor; GRANT SELECT ON hr.hr_verify TO sec_admin; Now, you are ready to create the secure application role procedure. In most cases, you create a package to hold the procedure, but because this is a simple tutorial that requires only one secure application role test (as defined in the procedure), you will create a procedure by itself. If you want to have a series of procedures to test for the role, create them in a package. A PL/SQL package defines a simple, clear interface to a set of related procedures and types that can be accessed by SQL statements. Packages also make code more reusable and easier to maintain. The advantage here for secure application roles is that you can create a group of security policies that used together present a solid security strategy designed to protect your applications. For users (or potential intruders) who fail the security policies, you can add auditing checks to the package to record the failure. To create the secure application role procedure: In SQL*Plus, connect as user sec_admin. CONNECT sec_admin Enter password: password Enter the following CREATE PROCEDURE statement to create the secure application role procedure. (You can copy and paste this text by positioning the cursor at the start of CREATE OR REPLACE in the first line.) In this example: Line 1: Appends the AUTHID CURRENT_USER clause to the CREATE PROCEDURE statement, which creates the procedure using invoker's rights. The AUTHID CURRENT_USER clause creates the package using invoker's rights, using the privileges of the current user. You must create the package using invoker's rights for the package to work. Invoker's rights allow the user to have EXECUTE privileges on all objects that the package accesses. Roles that are enabled inside an invoker's right procedure remain in effect even after the procedure exits, but after the user exits the session, he or she no longer has the privileges associated with the secure application role. In this case, you can have a dedicated procedure that enables the role for the rest of the session. Because users cannot change the security domain inside definer's rights procedures, secure application roles can only be enabled inside invoker's rights procedures. See "About Secure Application Roles" for information about the importance of creating the procedure using invoker's rights. Line3: Declares the v_user variable, which will store the user session information. Line 4: Declares the v_manager_id variable, which will store the manager's ID of the v_user user. Line 6: Retrieves the user session information for the user logging on, in this case, Matthew or Winston. To retrieve user session information, use the SYS_CONTEXT SQL function with the USERENV namespace attributes (' userenv', session_attribute), and writes this information to the v_user variable. The information returned by this function indicates the way in which the user was authenticated, the IP address of the client, and whether the user connected through a proxy. See Oracle Database SQL Language Reference for more information about SYS_CONTEXT. Lines 7–8: Get the manager's ID of the current user. The SELECT statement copies the manager ID into the v_manager_id variable, and then checking the HR.HR_VERIFY view for the manager ID of the current user. This example uses the employees' email addresses because they are the same as their user names. Lines 9–13: Use an IF condition to test whether the user should be granted the sec_roles role. In this case, the test condition is whether the user reports to Matthew's manager, Steven King, whose employee number is 100. If the user reports to King, as Matthew does, then the secure application role is granted to the user. Otherwise, the role is not granted. The result is that the secure application role will grant Matthew Weiss the role because he is a direct report of Steven King, but will deny the role to Winston, because he is not a direct report of Steven King. Lines 10–12: Within the IF condition, the THEN condition grants the role by executing immediately the SET ROLE statement. Otherwise, the ELSE condition denies the grant. Lines 14–15: Use an EXCEPTION statement to set v_manager_id to 0 if no data is found. Line 16: Copies the manager's ID, which is now 0, into a buffer so that it is readily available. Tip:If you have problems creating or running PL/SQL code, check the Oracle Database trace files. The USER_DUMP_DESTinitialization parameter specifies the current location of the trace files. You can find the value of this parameter by issuing SHOW PARAMETER USER_DUMP_DESTin SQL*Plus. See Oracle Database Performance Tuning Guide for more information about trace files. At this stage, Matthew and Winston can try to access the OE.ORDERS table, but they are denied access. The next step is to grant them the EXECUTE privilege on the sec_roles procedure, so that the sec_roles procedure can execute, and then grant or deny access, when they try to select from the OE.ORDERS table. To grant EXECUTE privileges for the sec_roles procedure: In SQL*Plus, as user sec_admin, enter the following GRANT SQL statements: GRANT EXECUTE ON sec_admin.sec_roles TO mweiss; GRANT EXECUTE ON sec_admin.sec_roles TO wtaylor; You are ready to test the employee_role secure application role by logging on as Matthew and Winston and trying to access the OE.ORDERS table. When Matthew and Winston log on, and before they issue a SELECT statement on the OE.ORDERS table, the sec_roles procedure must be executed for the role verification to take place. To test the employee_role secure application role, as user MWEISS: Connect as user mweiss. CONNECT mweiss Enter password: password Enter the following SQL statement to run the sec_roles procedure: EXEC sec_admin.sec_roles; This statement executes the sec_roles procedure for the current session. (In a real world scenario, this statement would be automatically run when the user logs in to the application.) Perform the following SELECT statement on the OE.ORDERS table: SELECT COUNT(*) FROM OE.ORDERS; Matthew has access to the OE.ORDERS table: COUNT(*) ---------- 105 Now, Winston will try to access the secure application. To test the employee_role secure application role as user WTAYLOR: In SQL*Plus, connect as user wtaylor. CONNECT wtaylor Enter password: password Enter the following SQL statement to run the sec_roles procedure: EXEC sec_admin.sec_roles; This statement executes the sec_roles procedure for the current session. Perform the following SELECT statement on the OE.ORDERS table: SELECT COUNT(*) FROM OE.ORDERS; Because Winston does not report directly to Steven King, he does not have access to the OE.ORDERS table. He will never learn the true number of orders in the ORDERS table, at least not by performing a SELECT statement on it. ERROR at line 1: ORA-00942: table or view does not exist Remove the components that you created for this tutorial. To remove the components: In SQL*Plus, connect as user SYSTEM. CONNECT SYSTEM Enter password: password Enter the following DROP statements: DROP USER mweiss; DROP USER wtaylor; Do not drop user sec_admin. You will need this user for other tutorials in this guide. In SQL*Plus, connect as user sec_admin. CONNECT sec_admin Enter password: password Enter the following DROP SQL statements: DROP ROLE employee_role; DROP PROCEDURE sec_roles; Connect as user HR, and then drop the HR_VERIFY view. CONNECT HR Enter password: password DROP VIEW hr_verify; Exit SQL*Plus. EXIT Table 4-1 lists initialization parameters that you can use to secure user privileges. To modify an initialization parameter, see "Modifying the Value of an Initialization Parameter". For detailed information about initialization parameters, see Oracle Database Reference and Oracle Database Administrator's Guide.
http://docs.oracle.com/cd/E11882_01/server.112/e10575/tdpsg_privileges.htm
CC-MAIN-2014-41
refinedweb
3,892
54.22
Details - Type: Bug - Status: Open - Priority: Major - Resolution: Unresolved - Affects Version/s: 3.0-beta-1, 3.0-beta-2, 3.0-beta-3, 3.3 - - Component/s: inheritance, Maven 3 - Labels:None - Environment:3.0-beta-1-SNAPSHOT - Number of attachments :. Issue Links - depends upon - - is duplicated by - - is related to - - - relates to - Activity Updated patch, replaces mergePolicy. prefix with merge: xml namespace. In my testing you can specify whatever you want for the namespace URI since I don't actually have an XSD to go with it, I used xmlns:merge="" in my test pom. This patch should be complete, all integration tests pass and the copyright headers are correct. I do have an Apache ICLA on file and am an active committer in the portals project: I would love this to become a core feature of Maven itself for merging plugin configurations. I'm not sure where to go with getting that requested as a feature. I'm hoping that this this seems to affect the site plugin more than others it would be faster to get the fix in here so it could be used as soon as possible.. What you have to do is to add to indicate how to merge site plugin configuration when maven build the model in the child pom, you can change to ( attribute combine.children="append" ) btw this doesn't fix overriding configuration, with this trick some plugins can be executed more than one time
http://jira.codehaus.org/browse/MSITE-484?focusedCommentId=237713&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel
CC-MAIN-2015-11
refinedweb
245
61.36
Add Tilo example Change-Id: Idc3b0311891363630aa8ffc3667b2b8889f1ef36 This repository contains recipes for Fuchsia. A recipe is a Python script that runs a series of commands, using the recipe engine framework from the LUCI project. We use recipes to automatically check out, build, and test Fuchsia in continuous integration jobs. The commands the recipes use are very similar to the ones you would use as a developer to check out, build, and test Fuchsia in your local environment. A recipe will not run without vpython and cipd. Prebuilt versions of vpython and cipd are downloaded into the //buildtools subtree of a Fuchsia checkout, though they live in different directories. Where $FUCHSIA is the root of a Fuchsia checkout and $OSTYPE is linux or mac, add to your PATH: $FUCHSIA/buildtools(for cipd) $FUCHSIA/buildtools/$OSTYPE-x64(for vpython) depot_tools Chrome's depot_tools repository provides these binaries, along with other tools necessary for interacting with the Chrome source and infrastructure. See the depot_tools Tutorial for installation instructions. Recipes are parameterized using properties. The values for these properties can be set in the Buildbucket configuration. In the recipe code itself, they are specified in a global dictionary named PROPERTIES and passed as arguments to a function named RunSteps. The recipes engine automatically looks for these two objects at the top level of the Python file containing the recipe. When writing a recipe, you can make your properties whatever you want, but if you plan to run your recipe on the Gerrit commit queue, there will be some standard ones starting with patch_, which give information about the commit being tested, and which you can see in the existing recipe code. When a recipe executes, it interacts with the underlying machine by running steps. A step is basically just a command, represented as a Python list of the arguments. You give the step a name, specify the arguments, and the recipe engine will run it in a subprocess, capture its output, and mark the job as as failed if the command fails. Here's an example: api.step('list temporary files', ['ls', '/tmp']) This will execute the command ls /tmp on the machine where the recipe is running, and it will cause a failure if, for example, there is no /tmp directory. When the recipe gets run on Swarming (which is the scheduling system we use to run Fuchsia continuous integration jobs) this step will show up with the label “list temporary files” in a list of all the steps that ran. Code is reused across recipes in the form of modules, which live either in the recipe_modules directory of this repo, or in the same directory of the recipe engine repo. The recipe engine's modules provide general functionality, and we have some modules specific to Fuchsia in this repo, such as wrappers for QEMU and Jiri. The recipe engine looks for a list named DEPS at the top level of the Python file containing the recipe, where you can specify the modules you want to use. Each item in DEPS is a string in the form “repo_name/module_name”, where the repo name is “recipe_engine” to get the dependency from the recipe engine repo, or “infra” to get it from this repo. The reason it's important to only interact with the underlying machine via steps is for testing. The recipes framework provides a way to fake the results of the steps when testing the recipe, instead of actually running the commands. It produces an “expected” JSON file, which shows exactly what commands would have run, along with context such as working directory and environment variables. You write tests using the GenTests function. Inside GenTests, you can use the yield statement to declare individual test cases. GenTests takes an API object, which has functions on it allowing you to specify the properties to pass to the recipe, as well as mock results for individual steps. Here's an example test case for a recipe that accepts input properties “manifest”, “remote”, “target”, and “tests”: yield api.test('failed_tests') + api.properties( manifest='fuchsia', remote='', target='x64', tests='tests.json', ) + api.step_data('run tests', retcode=1) In this example: api.testsimply gives the test case a name, which will be used to name the generated JSON “expected” file. api.propertiesspecifies the properties that will be passed to RunSteps. api.step_datatakes the name of one of the steps in the recipe, in this case “run tests”, and specifies how it should behave. This is where you can make the fake commands produce your choice of fake output. Or, as in this example, you can specify a return code, in order to cover error-handling code branches in the recipe. To run the unit tests and generate the “expected” data, run the following command from the root of this repo: python recipes.py test train # Optionally specify a configuration file with --package # (default is infra/config/recipes.cfg) python recipes.py --package infra/config/recipes.cfg test train The name of the recipe is simply the name of the recipe's Python file minus the .py extension. So, for example, the recipe in recipes/fuchsia.py is called “fuchsia”. After you run the test train command, the JSON files with expectations will be either generated or updated. Look at diff in Git, and make sure you didn't make any breaking changes. To just run the tests without updating the expectation files: python recipes.py test run --filter [recipe_name] To debug a single test, you can do this, which limits the test run to a single test and runs it in pdb: python recipes.py test debug --filter [recipe_name].[test_name] When you write new recipes or change existing recipes, your basic goal with unit testing should be to cover all of your code and to check the expected output to see if it makes sense. So if you create a new conditional, you should add a new test case. For example, let‘s say you’re adding a feature to a simple recipe: PROPERTIES = { 'word': Property(kind=str, default=None), } def RunSteps(api, word): api.step('say the word', ['echo', word]) def GenTests(api): yield api.test('hello', word='hello') And let's say you want to add a feature where it refuses to say “goodbye”. So you change it to look like this: def RunSteps(api, word): if word == 'goodbye': word = 'farewell' api.step('say the word', ['echo', word]) To make sure everything works as expected, you should add a new test case for your new conditional: def GenTests(api): yield api.test('hello', word='hello') yield api.test('no_goodbye', word='goodbye') There will now be two generated files when you run test train: one called hello.json and one called no_goodbye.json, each showing what commands the recipe would have run depending on how the word property is set. Unit tests should be the first thing you try to verify that your code runs. But when writing a new recipe or making major changes, you'll also want to make sure the recipe works when you actually run it. To run the recipe locally, you need to be authorized to access LUCI services. If you've never logged in to any LUCI service (cipd, isolated, etc), login with: cipd auth-login Now you can run the recipe with: python recipes.py run --properties-file test.json [recipe_name] For this command to work, you need to create a temporary file called test.json specifying what properties you want to run the recipe with. Here's an example of what that file might look like, for the fuchsia.py recipe: { "project": "garnet", "manifest": "manifest/garnet", "remote": "", "packages": ["garnet/packages/default"], "target": "x64", "build_type": "debug", "run_tests": true, "runtests_args": "/system/test", "snapshot_gcs_bucket": "", "tryjob": true, "$recipe_engine/source_manifest": {"debug_dir": null} } The last line helps prevent an error during local execution. It explicitly nullifies a debug directory set by the environment on actual bots. If something strange is happening between re-runs, consider deleting the local work directory as is done on bots ( rm -rf .recipe_deps). To run a test under PDB (the Python DeBugger), run: python recipes.py test debug --filter [recipe_name] We format python code according to the Chrome team's style, using yapf. After committing your changes you can format the files in your commit by running this in your recipes project root: (Make sure yapf is in your PATH) git diff --name-only HEAD^ | grep -E '.py$' | xargs yapf -i --name-onlytells git to list file paths instead of contents. HEAD^specifies only files that have changed in the latest commit. -Eenables regular expressions for grep. -iinstructs yapf to format files in-place instead of writing to stdout. Occasionally you‘ll be confronted with the task of naming a step. It’s important that this name is informative as it will appear within the UI. Other than that, there are only two rules: See the generated documentation for our existing recipes and modules for more information on what they do and how to use them.
https://fuchsia.googlesource.com/infra/recipes/+/refs/heads/sandbox/kjharland/tilo
CC-MAIN-2020-05
refinedweb
1,505
62.27
I am currently writing a library, and this library currently has 1 Main game thread, and it gets started by creating an instance of a Room: Room room1 = new Room1(); Well, what other types and how many threads should a game have? package SpaceShooters; import JGame.Game.Game; import JGame.Room.Room; import SpaceShooters.Rooms.Room1; import javax.swing.JFrame; public class Main extends JFrame{ public static void main(String[] args){ Game game = new Game("Test Game"); game.startWindowed(800, 600); // This starts the main game thread by extending "Room" // It tests for key pressings mouse clicks, and repaints the screen Room room1 = new Room1(); game.setRoom(room1); } }
http://www.gamedev.net/topic/636366-game-multi-threading/?forceDownload=1&_k=880ea6a14ea49e853634fbdc5015a024
CC-MAIN-2016-30
refinedweb
108
74.79
appex loads code from icloud As far as I understand it is not possible to run an appex that lives inside the icloud folder. So I came to the idea of having a tiny appex wrapper script local that loads the main program from the icloud folder. The following code kinda works (not really): sys.path.append('/privat/var/mobile/Library/Mobile Documents/iCloud~com~omz~software~Pythonista3') from Documents import TheMainCode TheMainCode.doSomething() But it has some nasty side effects. For example changing anything in the icloud file only has effect on the iOS device after a complete restart. And some variables seem to survive subsequent calls. Can someone please help me to understand what's happening here and if there is a working way of programmatically importing code from icloud? @oliep if via share/Pythonista3/edit scripts you don't receive this It will appear in next version (I've the beta, thus no more able to test App Store version) @oliep If you want to share text to a Pythonista script, even on iCloud, you could write a shortcut in the IOS Shortcuts app which will be shared and will receive as "Shortcut input" the shared text. Your shortcut could then open url pythonista://your script.py?action=run&root=icloud&args=ShortcutInput Magic variable. Of course, instead of sharing to Pythonista, you will have to share to your shortcut. That's while waiting for the new version of Pythonista. @cvp Oh yeah. I've just figured that. To bad. The bug/missing feature in workflow is already a year old. Bummer. Let's hope for the best. @oliep The beta version contains the feature, if you need it urgently, ask @omz to be part of the test. The beta signup link is
https://forum.omz-software.com/topic/5493/appex-loads-code-from-icloud/1
CC-MAIN-2020-29
refinedweb
296
74.19
Idea is pretty simple, keep two pointers left and right. If s[left:right] has all chars in T, calculate distance and keep answer, then move left pointer. If s[left:right] doesn't have all chars in T, move right pointer. class Solution: # @param {string} s # @param {string} t # @return {string} # sliding window problem # count all chars in string T # left pointer point to string which has been processed # right pointer point to string, which has not been processed # 1.if all window from left to right contains all string T(counter values all less then or equal to 0) # calculate min window length, and keep answer # then move left pointer # 2.else there are missing string in current answer # move right pointer # update counter # repeat 1, 2 steps until right is equal to len(s), then break it def minWindow(self, s, t): left, right = 0, 0 # count T chars counter = collections.defaultdict(int) for a in t: counter[a] += 1 minwindow = len(s) + 1 answer = None while right <= len(s): # check all chars in T are in the current answer if all(map(lambda x: True if x<=0 else False, counter.values())): if minwindow > right-left: minwindow = right-left answer = s[left:right] char = s[left] if char in counter: counter[char] += 1 left += 1 else: if right == len(s): break char = s[right] if char in counter: counter[char] -= 1 right += 1 return answer if answer else '' I think this is not O(n) since ' all(map(lambda x: True if x<=0 else False, counter.values())):' takes len(counter) steps. answer = s[left:right] takes O(right - left) time. So it is better to keep index instead of string slice I used your idea and implement an O(n) solution import sys class Solution(object): def minWindow(self, s, t): """ :type s: str :type t: str :rtype: str """ required, min_len = [0] * 128, sys.maxint # record numbers of each character in t for ch in t: required[ord(ch)] += 1 left = right = min_start = 0 # count: number of characters that are still required count = len(required) - required.count(0) while right < len(s): while count > 0 and right < len(s): # move right till s[left : right] has all characters in t required[ord(s[right])] -= 1 if required[ord(s[right])] == 0: count -= 1 right += 1 # s[left : right] has all characters in t, move left pointer while count == 0: required[ord(s[left])] += 1 if required[ord(s[left])] == 1: # now s[left : right] misses one character, update min_len if necessary count = 1 if right - left < min_len: min_len, min_start = right - left, left left += 1 return s[min_start : min_start+min_len] if min_len != sys.maxint else '' Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.
https://discuss.leetcode.com/topic/13740/python-20-lines-ac-o-n-solution
CC-MAIN-2018-05
refinedweb
465
59.47
I am having difficulty importing a function from another script. Both of the scripts below are in the same directory. Why can't the function from another script handle an object with the same name ( arr def find_evens(): return [x for x in arr if x % 2 == 0] if __name__ == '__main__': arr = list(range(11)) print(find_evens()) from evens import find_evens if __name__ == '__main__': arr = list(range(11)) print(find_evens()) Traceback (most recent call last): File "C:\Users\user\Desktop\import_evens.py", line 7, in <module> find_evens() File "C:\Users\user\Desktop\evens.py", line 2, in find_evens return [x for x in arr if x % 2 == 0] NameError: name 'arr' is not defined Modules in python have separate namespaces. The qualified names evens.arr and import_evens.arr are separate entities. In each module, using just the name arr refers to the one local to it, so arr in import_evens is actually import_evens.arr. Since you are defining arr inside of if __name__ ..., the name arr is only the defined in the executed module. The name evens.arr is never defined. Further, there is no notion of truly global names. A name can be global to a module, so all entities inside it can use it. Any other module still has to address it as a_module.global_variables_name. It can also be imported as from a_module import global_variables_name, but this is just sugar for importing it and binding it to a new local name. # same as `from a_module import global_variables_name` import a_module global_variables_name = a_module.global_variables_name What you have shown is best done via parameters to the function: # evens.py def find_evens(arr): return [x for x in arr if x % 2 == 0] # import_evens.py if __name__ == '__main__': arr = list(range(11)) print(find_evens(arr)) If you think it's better to have global variables for this but don't understand how a language uses global variables, it's better not to have global variables.
https://codedump.io/share/4PlGsK4RF37H/1/nameerror-when-importing-function-from-another-script
CC-MAIN-2018-09
refinedweb
323
57.47
FoldFunctions Sublime Text plugin to fold functions. And it supports functions with arguments on more than one line! Details Installs - Total 993 - Win 550 - OS X 225 - Linux 218 Readme - Source - raw.githubusercontent.com FoldFunctions This package folds every functions in the current file, so that you can have a global view of it, and then unfold a few, so that you don't have to scroll a lot, skipping over the functions you're not interested in at the moment. For now, the following language are supported: - Python :heart: - JavaScript The good part is that it supports arguments on multiple lines, like so (in this case, it's python): def my_function(argument_number_one, argument_number_two, argument_number_three): print('It works!!') for i in range(10): print('It really does!') Installation Because it is not available on package control for now, you have to add this repo “manually” to your list. Using package control - Open up the command palette ( ctrl+shift+p), and find Package Control: Add Repository. Then enter the URL of this repo: the input field. - Open up the command palette again and find Package Control: Install Package, and just search for FoldFunctions. (just a normal install) Using the command line cd "%APPDATA%\Sublime Text 3\Packages" # on window cd ~/Library/Application\ Support/Sublime\ Text\ 3 # on mac cd ~/.config/sublime-text-3 # on linux git clone "" Which solution do I choose? It depends of your needs: - If you intend to just use FoldFunctions, then pick the first solution (Package Control), you'll get automatic update. - On the opposite side, if you want to tweak it, use the second solution. Note that, to get updates, you'll have to git pull Usage The command is accessible from the command palette. - ctrl+shift+p Fold Functions - hit enter Note: The caption will be the same, whichever supported language file you are editing, but the actual command will change. :wink: Adding a key binding It's up to you, but I prefer to have this command bound to this command, in my case, alt+f. So, here's what I've done: { "keys": ["alt+f"], "command": "fold_python_functions", "context": [ {"key": "selector", "operand": "source.python"} ] }, { "keys": ["alt+f"], "command": "fold_javascript_functions", "context": [ {"key": "selector", "operand": "source.js"} ] }
https://packagecontrol.io/packages/FoldFunctions
CC-MAIN-2018-17
refinedweb
371
61.77
Hi All, I am trying to create a 2D array of the "CString" MFC class, however it needs to be declared dynamically for my application. I have read up on numerous forums but I just cant seem to find what I am looking for. From what I have read the best way to do this would be to use a vector of CStrings. However, I am not to sure how to declare this dynamically (I am able to do it by specifying the row and column size, however these values are not known at compilation time and therefore i cannot do it this way). What I would like to be able to do is address any "CString" of a 2D array in the following way: MyArray[0][0]="Message ID in CString format" MyArray[0][1]="Message in CString format" MyArray[0][2]="Time in CString format" MyArray[1][0]="Message ID in CString format" MyArray[1][1]="Message in CString format" MyArray[1][2]="Time in CString format" and so on... As you can see the parts which are variable an therefore dynamic are the "Row" and "CString" values. The "column" value can be set to 3 at compilation time. Please could someone give me an example of how to do this without having to specify the row and column size. The following code which i found on another forum is exactly what i would want, using a vector of "CStrings" however although the poster claims it is dynamic the "Width" and "Height" still need to be declared and set at compilation time: #include <vector> std::vector<std::vector<CString> > your2darray(width, std::vector<CString>(height)); your2darray[x][y] = "asdf";
https://www.daniweb.com/programming/software-development/threads/242451/dynamic-array-of-cstring-mfc
CC-MAIN-2019-09
refinedweb
281
59.87
Does anyone know how to write a program in Python? Someone else wrote this is C++ but my teacher said that I did not use the Python code to write the program! I need the source code re-written using the Python program language. CSC 122-Section # - Program #1 By RyleyO Due: February 2nd, 2015 The purpose of the program is to provide the price, subtotal, sales tax, and total of various items for a customer. #include <iostream> using namespace std; int main(void) { //declarations double item1 = 0; double item2 = 0; double item3 = 0; double item4 = 0; double item5 = 0; double subtotal = 0; double total = 0; double tax = 0; //Enter Items cout << "Please enter the price of item 1"; cin >> item1; cout << "Please enter the price of item 2"; cin >> item2; cout << "Please enter the price of item 3"; cin >> item3; cout << "Please enter the price of item 4"; cin >> item4; cout << "Please enter the price of item 5"; cin >> item5; //Compute subtotal subtotal = (item1 + item2 + item3 + item4 + item5 + item6+); //Compute amount of tax tax = subtotal * (0.07); //Compute total total = subtotal + tax; #include "stdafx.h" #include <iostream> using namespace std; int main() { // here 5 diff. var. hold 5 diff. prices int item1=15.89; int item2=0.47; int item3=6.95; int item4=11.33; int item5=8.71; // Calculate the subtotal. int subtotal = item1 + item2 + item3 + item4 + item5; // Calculate the tax. double tax = subtotal *.07 ; // tax to be taken as double/float type because tax is in decimals // Calculate total by adding subtotal and tax double total = subtotal tax; // Display the subtotal. cout<< "The meal charge $" << subtotal <<endl; // Display the tax charge. cout<<"The tax charge $" << tax << endl; // Display the total. cout<<"The total amount spent $" << total << endl; system ("pause"); return 0; } //Display subtotal, total, and amount of tax cout < " The subtotal of the sale is: " << subtotal << endl; cout < " The amount of sales tax is: " << tax << endl; cout < " The total of the sale is: " << total << endl; return 0; Tutor Answer
https://www.studypool.com/questions/156635/does-anyone-know-how-to-write-a-program-in-python-1
CC-MAIN-2018-05
refinedweb
333
80.82
How to use a ESP32 development board to read temperature and humidity from a DH11 sensor When you have a DHT11 sensor, you will be able to get the temperature and humidity of your environment. Given that, this post shows how to use ESP32 development board to read temperature and humidity from a DHT11 sensor. Wiring your DHT11 sensor to your ESP32 development board When you look at your DHT11 sensor, you can see three pins labeled +/VCC, OUT/S/DATA and -/GND. Connect the: - +/VCC pin to a 3v3 pin on your board - OUT/s/DATA pin to GPIO27 on your board - -/GND pin to a GND pin on your board For example, this is how I had wired my DHT11 sensor to my ESP32 development board: Enabling ESP32 Development on Arduino IDE At this point in time, you are ready to flash a program into your ESP32 board to read from the DHT11 sensor.. Installing the DHT sensor library for ESPx to read temperature and humidity from DHT11 sensor After you had started your Arduino IDE, proceed to install a Arduino Library to read temperature and humidity from DHT11 sensor. In order to do so, first go to Tools -> Manage Libraries.... After you had done so, the Library Manager window will appear. Search for DHT11 and install the DHT sensor library for ESPx by beegee_tokyo: Arduino sketch example to read temperature and humidity from the DHT11 sensor Once you had installed the DHT sensor library for ESPx, upload the following sketch to your ESP32 board: #include "DHTesp.h" DHTesp dht; void setup() { Serial.begin(9600); dht.setup(27, DHTesp::DHT11);:
https://www.techcoil.com/blog/how-to-use-a-esp32-development-board-to-read-temperature-and-humidity-from-a-dh11-sensor/
CC-MAIN-2019-47
refinedweb
272
50.4