w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Constructing a specific regular expression
Does this regular expression work for what you need to do? String pattern = "([^ ]+) ([^ ]+) ([^ ]+) ([^ ]+) ([^ ]+) ([^ ]+) ([^ ]+) ([^ ]+)"; Alternatively, you could split the String using spaces. line.split(" "); Do note that in each of these cases, the value you are getting is a String. You'll need to convert them to integers or doubles using Integer.parseInt() or Double.parseDouble(). EDIT To ignore the first section - control.avgo String pattern = "[^ ]+ ([^ ]+) ([^ ]+) ([^ ]+) ([^ ]+) ([^ ]+) ([^ ]+) ([^ ]+)"; Matcher.group(0) specifically matches the entire pattern. So simply don't use it.

Categories : Java

How to use clpfd:automaton to restrict counter value in SICStus Prolog?
It may be best to formulate this with additional states. For example, for at most two consecutive 1s: :- use_module(library(clpfd)). at_most_two_consecutive_ones(Day) :- automaton(Day, [source(n),sink(n),sink(n1),sink(n2)], [arc(n, 0, n), arc(n, 1, n1), arc(n1, 1, n2), arc(n1, 0, n), arc(n2, 1, false), arc(n2, 0, n) ]). Example queries: ?- at_most_two_consecutive_ones([0,0,0,1,1,1]). false. ?- at_most_two_consecutive_ones([0,1,1,0,1,1]). true. ?- at_most_two_consecutive_ones([0,1,1,0,1,0]). true. For a more general solution, you have to build an automaton on demand when given the maximal length of a run.

Categories : Prolog

How to prove correctness of this algorithm?
The point of the exercise is that this recurrence can be proven with induction. Once it is proven, then we have proven that f(n,n) is the minimum cost for winding up with a solution where the nth value is at most bn. To finish proving the result there is one more step. Which is to prove that any solution where the nth value exceeds bn can be improved without increasing that maximum value. But that's trivial - just omit one of the +1s from the first value to exceed bn and you have a strictly better solution without a larger maximum. Therefore no solution winding up with a maximum greater than bn can be better than the best with a maximum at most bn. Therefore we have the optimal solution.

Categories : Algorithm

Why can't I prove that I need an AtomicReference in my code?
Your code is thread-safe, because the CountDownLatch guarantees that every change done before await() returns happens before everything done after. See http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/package-summary.html: Actions prior to "releasing" synchronizer methods such as Lock.unlock, Semaphore.release, and CountDownLatch.countDown happen-before actions subsequent to a successful "acquiring" method such as Lock.lock, Semaphore.acquire, Condition.await, and CountDownLatch.await on the same synchronizer object in another thread.

Categories : Java

How can i run perl "prove" using maven's pom.xml
The simplest way to run an external command may be through the exec-maven-plugin. See the example for how to bind execution to a phase of your build. A configuration like: <configuration> <executable>perl</executable> <arguments> <argument>src/main/bin/script.pl</argument> <argument>arg1</argument> ... </arguments> </configuration> will run a script through Perl.

Categories : Perl

Where can I find a U-Prove implementation for WS-Trust?
Although this isn't the implementation per-se, it is a document that describes the implementation http://research.microsoft.com/apps/pubs/default.aspx?id=166974

Categories : Wcf

Does unit testing prove functionality?
Unit tests are for testing each individual sub system. You have to write an integration test to ensure that all the different subsystems work in concert. You can not conclude that a program works just because the unit tests for its parts are passing. Mostly because unit tests typically abstract and simulate the integration points. You need the integration test to ensure proper integration between the different components. I think it's a judgement call to decide what needs testing. No two system are equal, and the testing requirements are also often different for different systems

Categories : Unit Testing

How can I prove or disprove the efficiency of compilation?
EDIT, okay that was fun... Folks that make the blanket statement that compilers outperform humans, are the ones that have not actually checked. Anything a compiler can create a human can create. But a compiler cannot always create the code a human can create. It is that simple. For projects anywhere from a few lines to a few dozen lines or larger, it becomes easier and easier to hand fix the optimizations made by a compiler. Compiler and target help close that gap but there will always be the educated someone that will be able to meet or exceed the compilers output. The claim I would like to prove or disprove is that compilers generate code that is 2-4X "fatter" (and therefore consume 2-4X times as much power) compared with hand written assembly code. Unless you are defining

Categories : C

Prove big O of addition and subtraction of functions
Formal definition : f(n)=O(s(n)) if and only if two constants M>0 and N>0 exist such as for all n>N , |f(n)|<M|g(n)|. (equivalent definitions exist such as the one given by adi, you can find more in wikipedia) The two constants are not unique, but they cannot depend on the variable n, if they do there are not constant anymore and you will have proved nothing. I strongly recommend you to calculate and to manipulate the definitions by yourself. Only reading answers will not be sufficient to cope with future problems involving the notions described here a) is false : counter-example : let f(n)=n, s(n)=n, g(n)=1 and r(n)=n we have : f(n)=O(s(n)) (N=1, M=1 do the job for the definition) and g(n)=O(r(n)) (same, N=1, M=1) let suppose that f(n)-g(n) = O(s(n)-r(n)), we have the t

Categories : Algorithm

function to prove if file exists
$html.=sprintf("<td>%s</td> ",any_function()); means your taking the return value of any_function and insert that in your string, which later will be echoed. But if (file_exists($testPath)) { $path = $testPath; echo $path; break; } already echoes something ($path) which obviously will corrupt your output. Delete that echo line. same in the other function.

Categories : PHP

Scala Cannot prove type equality
this.type is the type of a specific instance. It is not compatible with any other instance, even if instances of the exact same type. So basically in this definition: def -[A](other: A)(implicit evidence: this.type =:= A): this.type your evidence tries to prove that other is the exact same instance as this, which is probably not what you has in mind. I think you'll want to rework your design. You might try to use F-bounded polymorphism instead: trait Operable[Self <: Operable[Self]] { def +(other: Self): Self def -(other: Self): Self def *(other: Float): Self } /** Position descriptions */ trait Pos[T <: Operable[T]] { def eval: T } def test[T <: Operable[T]](x1: Pos[T], x2: Pos[T]): T = { x2.eval - x1.eval }

Categories : Scala

Can one prove correctness of a function with side-effects
The answer is that, although there are no side effects in math, it is possible to mathematically model code that has side effects. In fact, we can even pull this trick to turn impure code into pure code (without having to go to math in the first place. So, instead of the (psuedocode) function: f(x) = { y := y + x return y } ...we could write: f(x, state_before) = { let old_y = lookup_y(state_before) let state_after = update_y(state_before, old_y + x) let new_y = lookup_y(state_after) return (new_y, state_after) } ...which can accomplish the same thing with no side effects. Of course, the entire program would have to be rewritten to explicitly pass these state values around, and you'd need to write appropriate lookup_ and update_ functions for all mutable variables, but i

Categories : Testing

How to prove the ownership of a public git/github repo?
How picky are they? I would think the first thing to try is to show them the very first commit. It's normally a git object you can't remove from the history so it should show your address email and/or name. If it's not enough, you can probably show the the public key on your machine and the public key registered on Github is the same? Third theory, maybe just ask Github support? They may have more internal history that may be useful.

Categories : GIT

How do I prove that Jetty 9 SelectChannelConnector timeouts work?
Jetty 9 does not have a SelectChannelConnector, nor is it under the org.mortbay package name...that is Jetty 6 code. Jetty moved to the Eclipse Foundation from Jetty 7 onward and there have been over 150 releases since Jetty 6. As for your test case, see this test code: http://git.eclipse.org/c/jetty/org.eclipse.jetty.project.git/tree/jetty-server/src/test/java/org/eclipse/jetty/server/ConnectorTimeoutTest.java

Categories : Sockets

How to prove that HashMap in java is not thread-safe
Is reading the API docs enough? There is a statement in there: Note that this implementation is not synchronized. If multiple threads access a hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with a key that an instance already contains is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the map. If no such object exists, the map should be "wrapped" using the Collections.synchronizedMap method. This is best done at creation time, to prevent accidental unsynchronized access to the map: The problem w

Categories : Java

How to take intersection of two Finite Autometas
The idea is pretty straightforward, although I can see where the confusion comes in. I will give a text/symbolic description of the process for making the intersection (union, difference) machines via the Cartesian Product Machine construction (same thing as you are talking about). A DFA is a 5-tuple (E, Q, q0, A, f) where E is the input alphabet, a non-empty finite set of symbols Q is the set of states, non-empty and finite q0 is the start state, an element of Q A is the set of accepting or final states, a subset of Q f is the transition function, taking pairs from Q x E to Q Say we have two machines M' = (E', Q', q0', A', f') and M'' = (E'', Q'', q0'', A'', f''). To make the discussion easier, we assume E' = E''. We will now construct M''' so that L(M''') = L(M') intersect (or union

Categories : Misc

Length of a finite generator
If you have to do this, the first method is much better - as you consume all the values, itertools.tee() will have to store all the values anyway, meaning a list will be more efficient. To quote from the docs: This itertool may require significant auxiliary storage (depending on how much temporary data needs to be stored). In general, if one iterator uses most or all of the data before another iterator starts, it is faster to use list() instead of tee().

Categories : Python

termination of finite lists
One way to prove that a recursive calculation will terminate if the size of its input is (a) finite and (b) decreasing. Let's look at pp pp :: [a] -> [a] pp list = case list of [] -> [] (x: _) -> x : (qq list) The last line returns x:qq list, but the input was list, so it calls qq with the same length list. Let's see what qq does: qq :: [a] -> [a] qq list = case list of [] -> [] (x: xs) -> (pp xs) ++ [x] Here, we call pp xs, where we've matched list with the pattern x:xs. This means x is the head (first element) and xs is the tail (rest-of-list), so xs is one element shorter than the input, list. This means that the length of the input decreases by one every time we call qq and doesn't decrease when we call pp. Hence you're right that there are a

Categories : Haskell

Finite State Machine in Lua and C++
Are you asking how to create two objects in the same state (behaviour), but have different properties (like start position). If so, you can take either a functional approach, where you assume that the States just represent a series of functions operating on your objects (like PatrolUnits) like: PatrolState = {} PatrolState.Start = function(unit) if(SomeChecker(unit.startPos)) then DoSomething() -- like unit.curPos = unit.startPos, for example end end PatrolState.Update = function(unit) if(IsNearSomething(unit.curPos)) then DoSomethingElse() -- like ChangeState(State2) end end , or an object oriented approach. In this case, you will have to make objects of type State1,2 ... and keep them around and you will be able to save properties like st

Categories : C++

Using paragraphs 8.5.3p4 and p5 in the C++11 Standard, how do I prove that the snippet below doesn't compile?
Firstly, a common mistake in reading 8.5.3p5 is to miss that it has two top level bullet points. You may have accidentally misread the final occurence of "Otherwise" as a third bullet point - but it is in fact a subpart of the second bullet point (also starting Otherwise). char a = 'a'; char* p = &a; OK const char* & r = p; So we have a lvalue-reference to cv1 T1 = pointer to const char being bound to an lvalue of type cv2 T2 = pointer to char The two types are not reference-related or reference-compatible. cv1 and cv2 are both empty. The initializer expression does not have a class type cv1 is not const. Therefore, neither of the two bullet points in 8.5.3p5 apply, and the code is ill-formed. The two bullet points are: If the reference is an lvalue reference an

Categories : C++

Did I just prove that sieve of Eratosthenes is less efficient than trial division?
In general: yes, but when you are down in the sub 1 second range, there is a lot of noise which could be confusing... Runs each test many many times and use some stats on the results (e.g. average or mean/deviation depending on how much you care) And/or make it do more work - like finding a larger number of primes

Categories : C

How to prove that finding a successor n-1 times in the BST from the minimum node is O(n)?
You are correct that any individual operation might take O(log n) time, so if you perform those operations n times, you should get a runtime of O(n log n). This bound is correct, but it's not tight. The actual runtime is Θ(n). One way to see this is to look at any individual edge in the tree. How many times will you visit each edge if you start at the leftmost node and repeatedly perform a successor query? If you look closely at how the operations work, you'll discover that every edge is visited exactly twice: once downward and once upward. Since all the work done is done traversing up and down edges, this means that the total amount of work done is proportional to twice the number of edges. In any tree, the number of edges is the number of nodes minus one, and so the total wo

Categories : Algorithm

Check finite line interception C
The vertical lines will cause challenges, recommend another approach: Parametrized lines L(t) = (Ax,Ay) + t*(Dx,Dy) // Pseudo code // D slope D1 = (L1[1].x - L1[0].x, L1[1].y - L1[0].y) D2 = (L2[1].x - L2[0].x, L2[1].y - L2[0].y) // Parametric line L1(t1) = (L1[0].x, L1[0].y) + t1*D1 L2(t2) = (L2[0].x, L2[0].y) + t2*D2 // Simultaneous equation // Solve the 2 equations with 2 unknowns t1, t2 (D1.x -D2.x)(t1) = (L2[0].x – L1[0].x) (D1.y -D2.y)(t2) = (L2[0].y – L1[0].y) // If determinant is 0, lines are parallel. Special handling // Else if 0.0 <= t0 & t1 <= 1.0, lines intersect Details L1[0] and L1[1] are 2 points that define a segment. (OP uses L1.vertex[0].x, I use the shorten L1..x notation.) L1(t1) is a function defines a line that goes t

Categories : C

Magento: Prove customer checked terms and condition checkbox
No. Logging the checkbox state is not standard with Magento and would need to be implemented using 3rd party customizations. The proof can be based on the fact that they placed the order. If the Terms & Condition checkbox is required, the only way for them to proceed to place the order would be to check the box.

Categories : Magento

Prove that the farthest point among a set of points(in 2-d plane) should lie on the convex hull
A point A is on the convex hull if there exists a line through it for which all points in your set of points are on the same side of this line. For the two points farthest away from each other in a set, A and B, you can prove that this holds for the lines perpendicular to A and B, through A and B.

Categories : Algorithm

Python multiplicative inverse in GF(2) finite field
The function worked when tested with base-10 because all of your conversions int("{0:b}".format(x)) have no effect on x: 37 == int("{0:b}".format(37), 2) # >>> True Number objects in python are all base-10. Converting your numbers to binary strings, then back to integers has no effect. Here is an alternative version of your function that should work on a and b as base-10 ints and return them in binary. You can remove the bin() function to return the numbers in base-10, or use something like lambda x: int("%d".format(x)) to convert a and b from binary to decimal in the first line of the function. def extendedEuclideanGF2(a, b): # extended euclidean. a,b are values 10110011... in integer form inita, initb = a, b # if a and b are given as base-10 ints x, prevx

Categories : Python

Scaling infinite value ranges to a finite interval
Let {x_i} be your set of values, and then min = min{x_i} , max = max{x_i}. You can now normalize every value on the set in the [0,1] interval, with: x_i = (x_i - min) / (max - min) As you can easily see, the max element will be 1, the min will be 0, and the itnermediate values will keep their proportion. You can scale this a bit adding a constant if you don't line the 0 value in the histogram, then the min will be alpha and the max 1 + alpha. In general, you can map every set in the interval [a,b] doing: x_i = a + (x_i - min) * ( b - a ) / (max - min)

Categories : Algorithm

Pattern recognition in finite array of numbers
Well, if those bytes were stored as characters, I believe you can match them with a regex pattern like this: [x1a-x1d][x03-x08]x7c[x3b-x3e] I'm not sure this is the most sensible approach, though.

Categories : Regex

Compile Finite State Machine to UML(-like) Diagram
GraphViz has a file format which can be written manually and compiled to different picture formats.

Categories : Misc

How to retry "try-catch" in a finite number and delay it?
Before you call run() in catch, you can do- Thread.sleep(1000); // 1000 milli second = 1 second This will make the thread sleep for a second before it calls run again. Also, you should not try forever as this leads to a bad recursive call and there will not be enough space in stack left to carry on with any more code execution including printing the error. Maybe you should try a maximum of 5 to 10 times with an interval of 3 seconds and give up. Stack overflow error happens when there's no virtual memory is left to carry on an execution. Say you are calling run from create method- private static final int MAX_TRY = 5; public void create(){ for(int i = 0; i < MAX_TRY; i++){ if(run()){ // if run call returns true, then get out of the loop break;

Categories : Android

Creating an extendable finite state machine
Basically, I want Car.ChangeState to accept only states which implement IState<Car>, Boat.ChangeState to accept only IState<Boat> and so on. The typical way to do this is to use a variation on the Curiously Recurring Template pattern. I describe the C# version of the pattern here: http://blogs.msdn.com/b/ericlippert/archive/2011/02/03/curiouser-and-curiouser.aspx I recommend that you not pursue this. This pattern makes your code hard to understand and the restriction that it actually makes is not the restriction you want. The type system is simply not good at representing the kind of constraint that you want. The type system cannot be all things to all people.

Categories : C#

Prolog's CLP over Finite Domains library performance
In general, CLP(FD) is a suitable and well-established way to solve such kinds of problems. Note however that there are many different ways to model your problem even within library(clpfd): You can for example use the global constraints serialized/2 or cumulative/1 to express it. Other Prolog systems will often give you much better performance than SWI-Prolog, but the way you model your problem and search for solutions typically affects performance much more than the optimizations of any specific implementation.

Categories : Performance

Modular arithmetics and NTT (finite field DFT) optimizations
First off, thank you very much for posting and making it free to use. I really appreciate that. I was able to use some bit tricks to eliminate some branching, rearranged the main loop, and modified the assembly, and was able to get a 1.35x speedup. Also, I added a preprocessor condition for 64 bit, seeing as Visual Studio doesn't allow inline assembly in 64 bit mode (thank you Microsoft; feel free to go screw yourself). Something strange happened when I was optimizing the modsub() function. I rewrote it using bit hacks like I did modadd (which was faster). But for some reason, the bit wise version of modsub was slower. Not sure why. Might just be my computer. // // Mandalf The Beige // Based on: // Spektre // http://stackoverflow.com/questions/18577076/modular-arithmetics-and-ntt

Categories : C++

Perl Prove TAP::Harness color (colour) output for windows (win32)
It appears to be a bug in TAP::Formatter::Color. It's attaching to the console's STDOUT handle but the messages that should be colored are on STDERR. This: my $console = Win32::Console->new( STD_OUTPUT_HANDLE() ); Should be this instead: my $console = Win32::Console->new( STD_ERROR_HANDLE() ); Also, despite what the documentation says, --color is not the default on Windows. App::Prove (which is what's behind the "prove" executable) explicitly sets the default to false for Windows: sub _color_default { my $self = shift; return -t STDOUT && !$ENV{HARNESS_NOTTY} && !IS_WIN32; }

Categories : Perl

General Finite State Machine (Transducer) in Scala
This is probably not what you are looking for, but I think it's an interesting concept. object TypicalFSM { sealed trait State final class State1 extends State final class State2 extends State sealed trait Message case class Message1(s: String) extends Message case class Message2(s: String) extends Message sealed trait ResultMessage object ResultMessage1 extends ResultMessage object ResultMessage2 extends ResultMessage } import TypicalFSM._ case class Transformation[M <: Message, From <: State, To <: State]( f:M => Seq[ResultMessage]) { def apply(m:M) = f(m) } object Transformation { implicit def `message1 in state1` = Transformation[Message1, State1, State2] { m => Seq(ResultMessage1, ResultMessage2) } implicit def `messag

Categories : Scala

Can a deterministic finite acceptor begin at the end of string and move toward the start?
Since your are dealing with deterministic finite automata, the answer is no. The main problem is that you may have two transitions (p, a, r) and (q, a, r) leading to the same state r, but with p different from q. Then if you start in r and try to read the letter a backwards, should you end up in p or in q?

Categories : Misc

Python -- polynomials in finite fields. Why does only __add__() work with super() in this case?
Your return GF2Polynomial(self.outFormat(self.bin/other.bin)) line results in the string 1, which is then passed to the GF2Polynomial.parsePolyVariable() method. This value has no letters, so the line: letter = [str(m.group(0)) for m in re.finditer(r'[a-z]', poly)] returns an empty list. The next line: degree = max(c); varmatch = True; key = letter[0] then fails because key = letter[0] gives a IndexError exception. Your code is hard to read because you use one-letter variables and put multiple statements on one line, so it is hard to make out what your expectations are in that function. The exception has otherwise nothing to do with super(). There is a simple bug in your own code somewhere.

Categories : Python

kruskal.test shows "All group levels must be finite" error. What is the problem?
It should work if you run data$Grp <- as.factor(data$Grp) Then (as before): kruskal.test(data$Val, data$Grp) This is because Grp is a character not a factor and is.finite applied to an object of character class is always false (see ?is.finite).

Categories : R

Matlab solution for implicit finite difference heat equation with kinetic reactions
It looks like you are using a backward Euler implicit method of discretization of a diffusion PDE. A more accurate approach is the Crank-Nicolson method. Both methods are unconditionally stable. The introduction of a T-dependent diffusion coefficient requires special treatment, best probably in the form of linearization, as explained briefly here. It would be useful to identify stability criteria to ensure that the time and distance step lengths are appropriate following introduction of T-dependent coefficients. Note that matlab offers a PDE toolbox which might be useful to you, although I have not checked how you might use it in detail.

Categories : Arrays

Constructing a DB for best performance
Generally when query time is directly proportional to the number of rows, that suggests a table scan, which means for a query like SELECT * FROM dle_playerFiles where post_id in ('7000') AND type='1' The database is executing that literally, as in, iterate over every single row and check if it meets criteria. The typical solution to this is an index, which is a precomputed list of values for a column (or set of columns) and a list of rows which have said value. If you create an index on the post_id column on dle_playerFiles, then the index would essentially say 1: <some row pointer>, <some row pointer>, <some row pointer> 2: <some row pointer>, <some row pointer>, <some row pointer> ... 100: <some row pointer>, <some row pointer>, <s

Categories : Mysql



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.