Menu
  • HOME
  • TAGS

C Flatten 2-D Array of Char* to 1-D

c,arrays,char,flatten

You have a one-dimensional array of type pointer-to-char, with 1000 such elements. It's already 1D as far as arrays go, though it could be interpreted as a "jagged 2D array". If you want to convert this into one massive character array, you could do something like so, which requires calculating...

numpy flatten - how to print output

python,numpy,flatten

You forgot parentheses. You need to call the method. You're only getting a handle to the method if you omit the parentheses: s1 = random.poisson(5,100).flatten() However, for completeness, you can do this... but probably shouldn't for code readability: s1 = random.poisson(5,100).flatten print(s1()) # <-- Calling the function s1 would contain...

How to flatten a list of tuples into a pythonic list

python,list,flatten

You could use a list comprehension: >>> INPUT = [(1,2),(1,),(1,2,3)] >>> [y for x in INPUT for y in x] [1, 2, 1, 1, 2, 3] >>> itertools.chain.from_iterable is also used a lot in cases like this: >>> from itertools import chain >>> INPUT = [(1,2),(1,),(1,2,3)] >>> list(chain.from_iterable(INPUT)) [1, 2,...

Flatten XML tree using XSLT - optional but repeating nodes

xml,xslt,tree,flatten

This produces the desired result, but to me, this looks rather ugly. Well, it's an ugly problem. Is the result really useful for anything? I would have thought a separate table (and hence a separate stylesheet) for each level would be more practical. Still, if that's the result you...

Flatten array with objects into 1 object

javascript,lodash,flatten

Use Object.assign: let merged = Object.assign(...arr); // ES6 (2015) syntax var merged = Object.assign.apply(Object, arr); // ES5 syntax Note that Object.assign is not yet implemented in many environment and you might need to polyfill it (either with core-js, another polyfill or using the polyfill on MDN). You mentioned lodash, so...

Flattening nested entities with ids in Clojure

dictionary,clojure,functional-programming,entity,flatten

tree-seq and for to the rescue! (for [m (tree-seq map? vals data) ;; traverse nested maps :when (map? m) ;; we only care about maps [k v] m ;; traverse key-value-pairs :when (not= k :id)] ;; ignore the ':id' key [(:id m) k (if (map? v) (:id v) v)]) ;;...

Python: Twitter API tweets/search: Flatten nested dictionary to columns

python,json,twitter,dictionary,flatten

You didn't make it quite clear what you wanted to do when you encounter an array, so leaving that alone: Given a variable user as the subset of your Twitter response you selected: user = {u'user': {u'lang': u'en', u'utc_offset': -18000, u'statuses_count': 58304, u'default_profile_image': False, u'friends_count': 373, u'profile_background_image_url_https': u'https://pbs.twimg.com/profile_background_images/457457546580602880/VxHBaVbH.jpeg', u'profile_use_background_image': False,...

Flatten multiple nested hierarchial array - d3.js

javascript,arrays,d3.js,flatten

Ok, after some help on which routes to explore I settled for a for-loop, mainly because the arrays are fixed and it was the easiest to get my head around. var tmparr = []; for ( var i = 0, len=values2.length; i < len; i++) { for ( var j...

Scala nested arrays flattening

arrays,scala,collections,flatten

If you have mixed Int and Array[Int], which is not a very good idea to begin with, you can do something like in.flatMap{ case i: Int => Array(i); case ai: Array[Int] => ai } (it will throw an exception if you've put something else in your array). You can thus...

Javascript flattening an array of arrays but I'm getting error in my for loop?

javascript,arrays,flatten

Here's the cut down version of the below code. This uses _.flatten from underscore which basically replaces the recurse function in my longer code. function toType(x) { return ({}).toString.call(x).match(/\s([a-zA-Z]+)/)[1].toLowerCase(); }; function flatten(arr) { var out = []; for (var i = 0, l = arr.length; i < l; i++) {...

prolog sum list using atomic

prolog,sum,atomic,flatten

In SWI Prolog (just not sure about ANSI) the atomic(X) predicate can tell you whether the X is list or a number (in your case). It can be used write the sum predicate by recursively calling itself when a list is encountered, or just add the element to a sum...

Flatten a named list in R

r,list,tags,data.frame,flatten

If you're just trying to remove the names of the object, just use unname. Here's a basic example: ctl <- c(4.17,5.58,5.18,6.11,4.50,4.61,5.17,4.53,5.33,5.14) trt <- c(4.81,4.17,4.41,3.59,5.87,3.83,6.03,4.89,4.32,4.69) group <- gl(2, 10, 20, labels = c("Ctl","Trt")) weight <- c(ctl, trt) lm.D9 <- lm(weight ~ group) fitted(lm.D9) # 1 2 3 4 5 6 7...

Flattening nested list pattern with sed/perl-like regex or awk

regex,perl,sed,nested-lists,flatten

Not bothering with a regex, but using perl perl -lne '$p=$_ if s/< //; print "$p.$_" if s/> //' file.txt Btw, the reason why using a single regex for this problem is silly, is because you're trying to do more than one transformation. You're wanting to prefix the children with...

loop over 2d subplot as if it's a 1-D

python,matplotlib,flatten,subplot

Rather than creating your subplots in advance using plt.subplots, just create them as you go using plt.subplot(nrows, ncols, number). The small example below shows how to do it. It's created a 3x3 array of plots and only plotted the first 6. import numpy as np import matplotlib.pyplot as plt nrows,...

Flatten Xml Using Xslt, Creating Nodes from Values, Dashes for Spaces

xml,xslt,flatten

Replace your second and third templates with these two: <xsl:template match="Restaurants"> <xsl:apply-templates/> </xsl:template> <xsl:template match="Restaurant"> <xsl:element name="{translate(Name,' ','-')}"> <xsl:value-of select="TimesEaten"/> </xsl:element> </xsl:template> The first one flattens the Restaurants tree. The second flattens each Restaurant tree replacing their children for one element. The {} are Attribute Value Templates that allow XPath...

Combine Two Properties From Entity In List And Flatten It With Linq

c#,asp.net,.net,linq,flatten

Uriil's answer may be even shorter: var result = games .SelectMany(game => new[] { game.AwayTeamId, game.HomeTeamId }) .Distinct() ; No need for additional .Select and lists creation for every Game record....

Laravel Flatten: Empty Cache by values in Saltshaker

php,caching,laravel-4,flatten

I discovered the hash is generated from the values in saltshaker Array with the additional information of HTTP Request Type and the Route. So this script worked for me, because i only have a single cached route: $pages = $cached = (array) $this->app['flatten.storage']->get('cached'); $hash = $this->app['flatten']->computeHash('/'); foreach ($pages as $key...

How to manually flatten a list in Racket (Scheme)

scheme,racket,flatten,list-processing

The first implementation shown is self-contained but incorrect, and it's not calling Racket's built-in flatten - it's simply calling itself recursively, rename it to see what I mean. Here's a fixed version: (define (my-flatten lst) (cond ((null? lst) empty) ; you wrote `list` instead of `lst` ((pair? (car lst)) ;...

flattening list if sublists are same length

python,python-2.7,flatten

A little timing suggest that the list comprehension is slightly faster than the itertools version (for short lists - Hackaholic's answer suggests the reverse is true for long lists): >>> import timeit >>> timeit.timeit("[item for sublist in a for item in sublist]", setup="import itertools; a = [[1, 2], [3, 4],...

Orika nested properties flattening

java,nested,flatten,orika

In fact Orika can handle this, but you should provide this automatic mapping policy by providing an implementation for DefaultFieldMapper In the Orika source code / tests, there is some examples....

LoDash - DeepFlatten array of objects

javascript,collections,lodash,flatten

Try: var data=[{"name":"John","age":24,"children":[{"name":"Jack","age":53,"children":[{"name":"Jenny","age":88}]}]},{"name":"George","age":45,"children":[{"name":"Chris","age":38,"children":[{"name":"Nick","age":35,"children":[{"name":"Maria","age":63}]}]}]}] function getPeople(persons){ var result = []; _.each(persons, function(person){ result.push({name: person.name, age: person.age}); person.children && (result = _.union(result,getPeople(person.children))) }); return result }...

Iseries SQL DBU Flatten Row into Columns

sql,ibm-midrange,flatten

Here's a way to manually pivot the data into five sequence columns. It assumes there are only five possible sequences. Also, if you have more than one row with a given sequence, the percentages will be added together. select ordn , ordl , sum(case when sequence=1 then percentage else null...

Error message when trying to flatten JSON file to CSV

json,unix,csv,flatten,jq

cat Filename.json | sed 1d | sed 's/},/}/' | jq --raw-output '. | [.Date, .Object, .ID, .Name ] | @csv'

Haskell - Flattening Objects of Lists

object,haskell,ghci,flatten

I'd go about this differently. flatten (And []) = Nil flatten (And (h:t)) = case (flatten h, flatten $ And t) of (Nil, t) -> t -- t is already flatten And t (h, Nil) -> h -- And [h] == h (And h, And t) -> And $ h++t...

Javascript fixing my flatten(array) function

javascript,recursion,flatten

Please see the refactored code below. The major change is that instead of creating new copies of results, we are passing it to subsequent calls to flatten as a reference. Please see the added comments //Helper methods function toType(obj){ return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase() } function each(collection, callback){ if (Array.isArray(collection)){ for (var i...

Schema in Pig after Flattening the String

schema,apache-pig,flatten

Can you try this? input: 2/23/2015 23:56:49 1/23/2014 23:56:49 9/23/2014 23:56:49 8/23/2014 23:56:49 PigScript: A = LOAD 'input' AS (date:chararray); B = FOREACH A GENERATE FLATTEN(REGEX_EXTRACT_ALL(date, '([0-9]+)/([0-9]+)/([0-9]+)\\s+([0-9]+):([0-9]+):([0-9]+)')) AS (month,day,year,hour,min,second); C = FILTER B BY (month==1) OR (month==2) OR (year==2015); D = FOREACH C GENERATE month,day,year,hour,min,second; DUMP D; Output: (2,23,2015,23,56,49) (1,23,2014,23,56,49)...

Flattening only one level of a list in Prolog

list,prolog,flatten

You need 3 simple clauses, I will show just the most complex one flat([H|T],R) :- is_list(H), flat(T,T1), append(H,T1,R). other two clauses are the base recursion case, and a copy as is of head to result. You should also place a cut in the clause I've shown, otherwise on backtracking you'll...

Flattening a JSON multi depty array in PHP

php,arrays,json,multidimensional-array,flatten

Not very hard: function flatten(array $array) { $branch = []; foreach ($array as $item) { $children = []; if (isset($item['children']) && is_array($item['children'])) { $children = flatten($item['children']); unset($item['children']); } $branch = array_merge($branch, [$item], $children); } return $branch; } ...

Collapse data with rules for a list of data frames

r,max,collapse,flatten

Here is the solution based on data.table: library(data.table) setDT(data)[,lapply(.SD,function(cl) {z<-table(cl);z.max<-which(z==max(z));ifelse(length(z.max)>1,"NA",names(z)[z.max])}),Group] # Group Loc1 Loc2 Loc3 Loc4 #1: Group1 NA A/A NA NA #2: Group2 B/B A/A C/C B/B #3: Group3 B/B B/B NA NA By modifying ifelse, you can set the desired rules for treating ties and NAs. PS: You...

Casting the output from Flatten and Strsplit in Pig

apache-pig,flatten,strsplit

Your problem is how you use the as clause. Since you place the as after the sixth parameter, it assumes you are trying to specify that schema only for that sixth parameter. Therefore, you are assigning a schema of six fields to only one, hence the error. Do it like...

FLATTEN On bag NOT working as expected

apache-pig,flatten,bag

The problem here is that when you do not specify a schema for a map, it defaults to bytearray, as you can see in the official documentation: A = LOAD 'a.csv' AS (bank_details:map[]); B = FOREACH A GENERATE FLATTEN(bank_details#'banks') AS bank_name; describe B; B: {bank_name: bytearray} Therefore, when you try...

List structure size function, difficulty with code

python,list,python-3.x,flatten

You can do something much simpler, like: def size(lst): if type(lst) == int: return 1 else: return 1 + sum(size(e) for e in lst) print size([[[14],[23,[14]]]]) ...

How to convert a deep multi dimensional array to a single dimensional array - Javascript

javascript,flatten

You can write a walker function: function walkLeaves(arr, fn) { for (var i = 0; i < arr.length; ++i) { if (typeof arr[i] == 'object' && arr[i].length) { // simple array check walkLeaves(arr[i], fn); } else { fn(arr[i], i); // only collect leaves } } } And then use that...