w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Extract non-main diagonal from scipy sparse matrix?
When the sparse array is in dia format, the data along the diagonals is recorded in the offsets and data attributes: import scipy.sparse as sparse import numpy as np def make_sparse_array(): A = np.arange(ncol*nrow).reshape(nrow, ncol) row, col = zip(*np.ndindex(nrow, ncol)) val = A.ravel() A = sparse.coo_matrix( (val, (row, col)), shape=(nrow, ncol), dtype='float') A = A.todia() # A = sparse.diags(np.ones(5), 1) # A = sparse.diags([np.ones(4),np.ones(3)*2,], [2,3]) print(A.toarray()) return A nrow, ncol = 10, 5 A = make_sparse_array() diags = {offset:(diag[offset:nrow+offset] if 0<=offset<=ncol else diag if offset+nrow-ncol>=0 else diag[:offset+nrow-ncol]) for offset, diag in zip(A.offsets,

Categories : Python

Extract x items from array (slice) but continue from beginning if end is reached
Its not much, but looks fine JS Bin: function overSlice(arr, start, count, dir){ if(dir==='backward'){ arr = arr.reverse(); start = arr.length-start-1; } var lastIndex = start+count; return arr.slice(start, lastIndex>arr.length?arr.length: lastIndex) .concat(arr.slice(0, lastIndex>arr.length?lastIndex-arr.length: 0)); } var arr = [0,1,2,3,4,5,6,7,8,9]; alert(overSlice(arr,7,5,'backward'));

Categories : Javascript

How to properly slice an audio file using recorder.js, getUserMedia and blob.slice?
I am working also on it. This fork of recorder.js already do this: creating a blob to be downloadable by a link. https://github.com/mattdiamond/Recorderjs This other fork do upload to server trought an api call, this is modifiable for your needs. The other goodies of this fork is a swf recorder version which allow all browser to record easily. https://github.com/jwagener/recorder.js So they need to be merged^^

Categories : Javascript

How to remove an item from a slice by calling a method on the slice
You were right the first time with Remove1(). Remove gets a copy of the slice and therefore cannot change the length of the slice. The issue in your remove function is that according to order of operations in Go, slicing comes before dereferencing. The fix is to change *slc = append(*slc[:item], *slc[item+1:]...) to *slc = append((*slc)[:item], (*slc)[item+1:]...). However I would recommend the following for readability and maintainability: func (slc *mySlice) Remove1(item int) { s := *slc s = append(s[:item], s[item+1:]...) *slc = s }

Categories : Go

Parsing slice information from a slice object?
>>> slice(4,5).start 4 >>> slice(4,5).stop 5 >>> slice(4,5).step #None One particularly useful method of the slice object is the indices method: >>> slice(4,5).indices(12) (4, 5, 1) You might use it like this: for i in range(*my_slice.indices(len(self))): print self[i] Note that this really shines with negative indices or steps: >>> slice(4,-5).indices(12) (4, 7, 1) >>> print range(*slice(None,None,-1).indices(12)) [11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

Categories : Python

Use slice function to slice JSON object
Try var data = { programId:1, programName:'project1', programContent:'content1', programStartDate:'2012-01-01', templateId: '1' } var array = []; for(var key in data){ if(!data.hasOwnProperty(key)){ continue; } array.push(key, data[key]) } console.log(array, array.slice(0, 4))

Categories : Json

How do I extract the Selenium Element from a Capybara Element?
Ah, I found it. It was right in Capybara::Node::Element all along. The #native method returns the native element from the driver. This can then be passed into the Selenium Select's initialize method to successfully create the Select.

Categories : Ruby

Xpath: extract value from element using text outside of element
You want to locate the text node of interest first, rather than the div. From there, you can go to the preceding-sibling as you have tried. Try: //text()[normalize-space() = "Mobile"]/preceding-sibling::input/@name

Categories : HTML

Vectorized (partial) inverse of an N*M*M tensor with numpy
Update: In NumPy 1.8 and later, the functions in numpy.linalg are generalized universal functions. Meaning that you can now do something like this: import numpy as np a = np.random.rand(12, 3, 3) np.linalg.inv(a) This will invert each 3x3 array and return the result as a 12x3x3 array. See the numpy 1.8 release notes. Original Answer: Since N is relatively small, how about we compute the LU decomposition manually for all the matrices at once. This ensures that the for loops involved are relatively short. Here's how this can be done with normal NumPy syntax: import numpy as np from numpy.random import rand def pylu3d(A): N = A.shape[1] for j in xrange(N-1): for i in xrange(j+1,N): #change to L A[:,i,j] /= A[:,j,j] #change to U

Categories : Python

Fast way to "down-scale" a three-dimensional tensor index
does it meet your requirements? #include <cstdint> #include <iostream> uint32_t to_q_from_p(uint32_t p, uint32_t N, uint32_t S) { uint32_t mask = ~(~0 << N); uint32_t k = p &mask; uint32_t j = (p >> N)& mask; uint32_t i = (p >> 2*N)&mask; return ((i>>S)<<(2*(N-S))) + ((j>>S)<<(N-S)) + (k>>S);; } int main() { uint32_t p = 240407; uint32_t q = to_q_from_p(p, 8, 4); std::cout << q << ' '; } if you assume that N always is 8 and integers are little endian then it can be uint32_t to_q_from_p(uint32_t p, uint32_t S) { auto ptr = reinterpret_cast<uint8_t*>(&p); return ((ptr[2]>>S)<<(2*(8-S))) + ((ptr[1]>>S)<<(8-S)) + (ptr[0]>>S); }

Categories : C++

Calculating Rigid body Inertia Tensor world coordinates
I found that multipling m_inverseInertiaTensorL by m_worldTransform is the right way; only the rotation part of m_worldTransform is needed, so you can multiply m_inverseInertiaTensorL by the 3x3-sub-matrix of m_worldTransform.

Categories : C++

Checking if a tensor is rectangular at compile-time (i.e. all extents of a multidimensional array are equal)
The only way to do this is to make the values of the class templates as well (i used a different example) template <typename T, typename U, T t, U u> void blah() { static_assert(t==u,"sizes must be equal"); printf("foo"); } int main() { blah<int,int,10,10>(); //blah<int,int,10,15>();error C2338 (Visual Studio): "sizes must be equal" } I recently made a matrix class this way: template <size_t M,size_t N> class Matrix { double values_[M][N]; ... }; and than the operators worked like this instead: template <size_t M, size_t N> operator +(const Matrix<M,N>& lhs,const Matrix<M,N>& rhs){...} Because the size was part of the type, it made it easy to make the operator only available for valid cases like that. However, an

Categories : C++

Extract list element in Python
a) Use indexes: >>> [(1, 2, 3)][0][0] 1 b) I don't 100% understand this question, but instead of using a list comprehension as you have done, you can use list(itertools.combinations(...)) c) I think you are misunderstanding what map() does. map(str, [1, 2, 3]) is equivalent to: [str(i) for i in [1, 2, 3]] If you want to give [(0, 1)] a value, you can use a dictionary, but you have to use (0, 1) instead of [(0, 1)] because you would otherwise get TypeError: unhashable type: 'list'. If you want a "random value", I guess you can use the random module: import random {(0, 1) : random.randint(1,10)} # This is just an example, of course To store all the outputs in one list, you can use a massive list comprehension: >>> [list(itertools.combinations(range(x, i), i-x)

Categories : Python

extract tag inside text element of an xml tag
You can also try something like this, which iterates in all nested tags automatically: foos = doc.find('foos') for foo in foos: for text in foo.itertext(): print text.strip(), print

Categories : Python

Unable to extract XML element's value using Nokogiri
You can find the first expression because Nokogiri found the XML namespace where it expected one. The ns2 namespace isn't where we'd normally find it so Nokogiri doesn't know what to do. There are multiple ways to deal with this. The first is to gather the namespaces in the document and pass them to Nokogiri when you do your search. Nokogiri does this automatically for namespaces in the XML root, but not if they're sprinkled throughout the document, so we have to tell it to search everywhere, then pass them in: namespaces = doc.collect_namespaces namespaces # => {"xmlns:ns1"=>"http://www.opengis.net/xls", "xmlns:ns2"=>"http://www.opengis.net/gml"} pos = doc.xpath('//ns2:Point/ns2:pos', namespaces); pos # => [#<Nokogiri::XML::Element:0x3fe8c608ab30 name="pos" namespace=#&l

Categories : Ruby

How do I extract an HTML element based on its class?
I'm using excellent (but a bit slow sometimes) HTML::TreeBuilder::XPath module: my $tree = HTML::TreeBuilder::XPath->new_from_content( $mech->content() ); my @data = $tree->findvalues('//table[ @class = "winsTable" ]//td[@class = "wins"]');

Categories : HTML

Extract XML using PLSQL based upon child element value
I think you need to be a little more careful with XML namespaces. The XML fragment you've posted isn't well-formed, as it doesn't have a namespace binding for the soap nor the ns2 namespaces. Let's add them in and see what happens: SQL> SET SERVEROUTPUT ON SQL> SQL> DECLARE 2 p_xml_content VARCHAR2(32767) := '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns2="http://www.your-url.com/"> 3 <soap:Body> 4 <ns2:getAllIssueHistoriesResponse> 5 <return> 6 <eventDate>2013-08-02T11:45:58.013+02:00</eventDate> 7 <eventText>Test</eventText> 8 <issueEventType> 9 <id>10</id> 10 <value>Replied</value>

Categories : SQL

extract element name values from XSD and import into excel
The XPath 2.0 expression distinct-values(//xs:element/@name) will give you the distinct element names in the schema document. You need to ensure that the XPath processor is set up with the namespace binding xs=http://www.w3.org/2001/XMLSchema. In general the result is fairly meaningless. It excludes names of elements in included and imported schema documents, and there may be multiple local element declarations with the same name and different definitions. But it's what you wanted, and if it's not useful, that's your problem not mine.

Categories : Java

XPATH library for extract content of element (PROLOG)
Element holds the full page structure. What are you searching into ? For instance, to iterate over all paragraphs and display indented ... forall(xpath(Element, //p, Para), xml_show("", _, Para)) ... where xml_show it's an helper I wrote some time ago, attempting to inspect some real world data. %% xml_show(+Depth, +ElShow, +E) % % display xml tree indented % xml_show(Depth, ElShow, E) :- format('~s~@~n', [Depth, (ground(ElShow) -> call(ElShow, E) ; xml_elshow(E) )]), ( E = element(_, _, Xs) -> !, maplist(xml_show([0' |Depth], ElShow), Xs) ; true ). :- meta_predicate xml_show(+, 1, +). xml_elshow(E) :- E = element(D, A, _) -> write(D:A) ; write(E).

Categories : Prolog

Extract background-image from an HTML element in ruby
Nokogiri is not a web browser. It stands on top of libxml2 to provide fast and excellent parsing of XML and HTML, and manipulation and extraction of data from this. It only deals with the HTML in a web page. It does not run any JavaScript. It does not apply CSS to the DOM. There is no way to use Nokogiri to find a CSS style applied to an element unless it is directly on the style="..." attribute on that element. (And even then you would need to use something else, like regex, to parse the CSS therein.) You will want to use something else, like a headless browser controlled by Ruby, e.g. Watir or Selenium, if you want to process a web page and treat it like a web browser does.

Categories : Ruby On Rails

write a function to extract an element from a list in haskell
Alright let's start with what we have element :: [a] -> Int -> a element [] _ = error "list too short" element (_:xs) 7 = element7 xs (k - 1) Now that last case is when we're at 7, but we're really interested in any number greater than 0 element (x:xs) n | n > 0 = element xs (n-1) then if n is 1, we just return the head element (x:xs) n | n > 0 = element xs (n-1) | n == 0= x | otherwise = error "Index out of range" Now we just have to create a nice shortcut for finding the 7th element: seventh xs = element xs 6

Categories : Haskell

Use Ruby and nokogiri to extract poorly constructed content within an element
You can get at the p with: p = page.at('h2.lead + br + p') To break up the content, maybe it's good enough to do: p.children.map &:text

Categories : Ruby

How to parse and extract a specific element from a HTML document in Python?
To parse using a library - the best way is BeautifulSoup Here is a snippet of how it will work for you! from BeautifulSoup import BeautifulSoup src = "<html><body>...<div id=content>AAA<B>BBB</B>CCC</div>...</body></html>" soupy = BeautifulSoup( src ) content_divs = soupy.findAll( attrs={'id':'content'} ) if len(content_divs) > 0: # print the first one print str(content_divs[0]) # to print the text contents print content_divs[0].text # or to print all the raw html for each in content_divs: print each

Categories : Python

Can I be sure that array.slice() will always work the same as array.slice(0)?
All of these online references are mistaken. At least if we're talking about standards-complant browsers and runtimes. The ECMA-262 standard requires any conforming implementation to treat array.slice() identically to array.slice(0). Here is how we know this. First we look at Section 15.4.4.10, "Array.prototype.slice (start, end)": The slice method takes two arguments, start and end, and returns an array containing the elements of the array from element start up to, but not including, element end (or through the end of the array if end is undefined)… What is this? There's not even any mention of end being optional. Are both start and end required? Yes, they are. But we need to look elsewhere to understand what this means. Section 15, "Standard Built-in ECMAScript Objects

Categories : Javascript

d3 diagonal between two points
You're passing the entire lineData array into the lineFunction but it should just be an individual datum. Since you bound lineData to the selection, you could do .attr("d", lineFunction). There are some problems with your diagonal as well. The source and target accessors both need to return objects, where in your case they are returning scalar values. Then, the result objects returned from source and target will be subsequently fed into projection where each should be further converted into a 2 element array describing a point. If your source and target return an object with x and y defined ({x:, y:}) you don't need projection at all because the default will look for these properties.

Categories : D3 Js

Diagonal slash across page
You can try using some borders in css3 here's a good example: http://www.cssportal.com/css3-shapes/. See "Triangle Bottom Left".

Categories : CSS

Diagonal line through
Actually this is more of a question about geometry than coding. With squares this is easy, but with rectangles you'll have to do the math yourself. Remember those kids complaining that they'll never have to calculate a diagonal's length in "real life"? :P Here's what I did: div.container /*makes a square container (300x300)*/ { width: 300px; height: 150px; background-color: #aaa; padding-top: 150px; } div.line { position: relative; z-index: 1; left: -61px; /*this is something I don't understand but apparently is required*/ width: 423px; /*since container is a square this equals to its diagonal: 300*1.41*/ height: 1px; background-color: #000; transform: rotate(45deg); /*again, this is easy since its a square. In rectangle you'll have to find a tangent*/ -ms-transform: rotate(45deg); -webki

Categories : HTML

Diagonal Label layout
You can set axis limits with ylim: ?par barplot(graph.frame[1,], ylab = "AAA", col = terrain.colors(3), ylim="c(0,10), xaxt = "n") pdf("data_output.pdf", height = 8.5, width = 14) graph.frame <- cbind(c(1,2,3,4),c(5,6,7,8),c(9,10,2,2)) par(mfrow = c(1,3), mar = c(7.6, 4.1, 6.1, 2.1)) colnames(graph.frame) <- c("OneOneOne", "TwoTwoTwo", "ThreeThreeThree") labels <- colnames(graph.frame) temp1 <- barplot(graph.frame[1,], ylim=c(0,10),ylab = "AAA", col = terrain.colors(3), xaxt = "n") temp2 <- temp1[1:length(labels)] text(temp2, par("usr")[3] - 0.35, srt = 45, adj = 1, labels = labels, xpd = TRUE) box() temp1 <- barplot(graph.frame[2,], ylim=c(0,10),main = "Title", ylab = "BBB", col = terrain.colors(3), xaxt = "n") temp2 <- temp1[1:len

Categories : R

rounded diagonal line css
Try 3D transforms - something like this: demo Relevant CSS: body /* parent of .block in general */ { -webkit-perspective: 15em; perspective: 15em; } .block { -webkit-transform: rotateX(-5deg) rotateY(10deg); transform: rotateX(-5deg) rotateY(10deg); }

Categories : CSS

Drawing Diagonal Lines Across a Picture
range() assumes the first parameter is less than the second parameter, and it goes in an ascending order. You have: for y in range (y3,y4): where y3=h and y4=0 (on the first pass). Since y3 > y4, this loop does nothing. You can use either: for y in range(y4,y3): or for y in range(y3,y4,-1):

Categories : Python

Block-diagonal binding of matrices
adiag from a package magic does what you want: library(magic) adiag(a,b) [,1] [,2] [,3] [,4] [,5] [1,] 1 3 5 0 0 [2,] 2 4 6 0 0 [3,] 0 0 0 7 9 [4,] 0 0 0 8 10 Alternatively, you could use a package Matrix and function bdiag library(Matrix) bdiag(a,b) 4 x 5 sparse Matrix of class "dgCMatrix" [1,] 1 3 5 . . [2,] 2 4 6 . . [3,] . . . 7 9 [4,] . . . 8 10 that returns a sparse matrix and which might be more efficient. Use as.matrix(bdiag(a,b)) to get a regular one.

Categories : R

Drawing diagonal lines in html5
You can use an SVG: <svg style='width: 200px; height: 200px;'> <line x1="0" y1="200" x2="200" y2="0" style="stroke:rgb(255,0,0);stroke-width:2"/> </svg> With percentage coordinates, if needs be: <svg style='width: 100%; height: 100%;'> <line x1="0" y1="100%" x2="100%" y2="0" style="stroke:rgb(255,0,0);stroke-width:2"/> </svg> http://jsfiddle.net/qXKfN/2/ (Should work in FF, Chrome, Safari, and IE >= 9) At various sizes in various browsers, the SVG might be pushed out of its container. One solution is to set line-height: 0px;. Another solution, and probably the preferred solution, is to set position: relative; on the container and position: absolute; on the SVG. http://jsfiddle.net/qXKfN/3/

Categories : HTML

draw diagonal lines in div background with CSS
you can use a CSS3 transform Property: div { transform:rotate(Xdeg); -ms-transform:rotate(Xdeg); /* IE 9 */ -webkit-transform:rotate(Xdeg); /* Safari and Chrome */ } Xdeg = your value For example... You can make more div and use a z-index property. So,make a div with line, and rotate it.

Categories : CSS

How to display Non Diagonal 2D Array elements
The function skips all elements in the diagonal 5739 (i != j takes care of this), but, based on the desired output, you also wish to skip all elements in the diagonal 4902. To also check for the other diagonal, replace if (i != j) with if (i != j && i != size-j-1) Test.

Categories : C++

parsing diagonal double array
I would suggest that you make 4 passes, each one starting at a different corner. For example, given your array: intrepideg xtdcvmhgze yrwhoejkpn minusculet isnqdhivpi ntznyafhel ceamgnqgug erpoxtavrf gwaupsgwsd kyqtendrme Starting at the upper-left corner, you would search on the diagonal moving down from right to left. So: "i", "nx", "tty", "rdrm", etc. On the upper-right corner, search "g", "ee", "dzn", etc: the diagonal that moves down from left to right. Although that's more passes through the array, it makes for much simpler code than trying to search all four diagonals in a single scan of the array. You could potentially do it in two passes. After all, the search of the diagonal moving down from right to left is just a reversal of the diagonal moving up from left to right. So yo

Categories : C

Div with diagonal sides for parallax animation
Well... there's no such thing as a diagonal div. But you could rotate them to make it seem diagonal. You can do it with CSS 3 and rotation transform see this: http://www.w3schools.com/cssref/css3_pr_transform.asp and an example: http://www.w3schools.com/cssref/playit.asp?filename=playcss_transform_rotate sample code: #myDIV { transform:rotate(10deg); } PERSONAL NOTE: I think that your approach should be the use of a "normal" div with a "diagonal" background image and making the contents of your div appearing with some animation dependding of your scroll position to create the illusion that you are in fact using a diagonal div UPDATE 1: Here are a couple of links that I think will be of your interest http://unfold.no/ http://harvestcreative.com/ http://www.nike.com/jumpman23/aj

Categories : Javascript

Diagonal lines in OpenGL texture
I think the problem might be to do with the way you pass the byte array to the teximage2d function. The openTK documentation specifies that the data should be in the form of an IntPtr. You can get a pointer to a one dimensional array of bytes by using the code in this post, but i'm not entirely convinced that will work for a three dimensional array. (I guess it depends on how the runtime allocates memory). If it doesn't work, then you could convert your 3D array into a one dimensional array of bytes and try that.

Categories : C#

Diagonal matrix in opposite direction in C
Just reversing any loop, ie, iterating from n-1 should do.. Below is my version, #include<stdio.h> void main() { int n,m,a,b,c,d,i,j; int ar1[100][100]; printf("Enter value of n to create a square matrix of order n (odd no.): "); scanf("%d",&n); printf(" matrix in diagonal direction is - "); for(i=0;i<n;i++) { for(j=n-1;j>=0;j--) { //if(ar1[j]==ar1[i]){ // any two garbage values can be equal if(j==i) { ar1[j][i] = 2; printf("%d, ",ar1[j][i]); } else { ar1[j][i] = -1; printf("%d, ",ar

Categories : C

Mirroring an Image by its Diagonal in Jython
If by "mirroring", you meant "flip diagonally", this should work : def mirrorPicture(picture): height = getHeight(picture) width = getWidth(picture) newPicture = makeEmptyPicture(height, width) for x in range(0, width): for y in range(0, height): sourcePixel = getPixel(picture, x, y) targetPixel = getPixel(newPicture, y, x) # ^^^^ (simply invert x and y) color = getColor(sourcePixel) setColor(targetPixel, color) return newPicture Giving : ................................................................. Related answer about mirroring diagonally here.

Categories : Python

Calculate a point offset along a relative diagonal
You can do public static Point moveInDirection(Point a, Point b, Point c, double ratio) { return new Point( (int) Math.round(c.x + (b.x - a.x) * ratio), (int) Math.round(c.y + (b.y - a.y) * ratio)); }

Categories : Java



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