Insert sections at the beginning of UICollectionView - ios

I want to add some sections to UICollectionView. insertSections at the index zero didn't work for me. So my idea was to insertSections at the end and then use moveSection:toSection: to move the elements from the end to the beginning. Here I get
NSInternalInconsistencyException Reason: attempt to move section 36, but there are only 36 sections before the update
I can only provide C# code, but you can also post Objective-C/Swift.
this.controller.CollectionView.PerformBatchUpdatesAsync (
delegate() {
nint sectionsBefore = this.controller.CurrentNumberOfSections;
this.controller.CurrentNumberOfSections += 12;
this.controller.CollectionView.InsertSections(NSIndexSet.FromNSRange(new NSRange(sectionsBefore,12)));
for(nint i=sectionsBefore; i<=this.controller.CurrentNumberOfSections; i++){
this.controller.CollectionView.MoveSection(i,0);
}
}
);
Edit:
Here is an output of the variables:
sectionsBefore: 36
CurrentNumberOfSections: 48
Range: <NSIndexSet: 0x7a77b9b0>[number of indexes: 12 (in 1 ranges), indexes: (36-47)]
36
37
38
39
40
41
42
43
44
45
46
47

If you have 36 sections then then your valid section indexes are 0-35, but your loop will end up calling MoveSection(36, 0). You should use < instead of <=.

Related

Multiplying character-separated numbers in a cell with another cell (Distributive Property)

I have numbers in one cell that are separated by "-" and I want to multiply them by another number in another cell.
Example:
A: 12 - 6 - 8
B: 83
Doing MULTIPLY(SUM(SPLIT(A,"-")),B) is not mathematically correct. How can I do 12 * 83 + 8 * 83 + 8 * 83?
Thanks a lot.
Here's what you can try:
=INDEX(LAMBDA(ζ,JOIN("-",ζ*SEQUENCE(1,COLUMNS(ζ))))(SPLIT(A1,"-")))
Update
=PRODUCT(SPLIT(A1,"-"))
Update 2
Let's say you have 83 in B1 and 12 - 6 - 8 in A1. Here's what you can try:
=LAMBDA(ζ,SUMPRODUCT(ζ,IF(ζ,B1)))(SPLIT(A1,"-"))

Decode UDP message with LUA

I'm relatively new to lua and programming in general (self taught), so please be gentle!
Anyway, I wrote a lua script to read a UDP message from a game. The structure of the message is:
DATAxXXXXaaaaBBBBccccDDDDeeeeFFFFggggHHHH
DATAx = 4 letter ID and x = control character
XXXX = integer shows the group of the data (groups are known)
aaaa...HHHHH = 8 single-precision floating point numbers
The last ones is those numbers I need to decode.
If I print the message as received, it's something like:
DATA*{V???A?A?...etc.
Using string.byte(), I'm getting a stream of bytes like this (I have "formatted" the bytes to reflect the structure above.
68 65 84 65/42/20 0 0 0/237 222 28 66/189 59 182 65/107 42 41 65/33 173 79 63/0 0 128 63/146 41 41 65/0 0 30 66/0 0 184 65
The first 5 bytes are of course the DATA*. The next 4 are the 20th group of data. The next bytes, the ones I need to decode, and are equal to those values:
237 222 28 66 = 39.218
189 59 182 65 = 22.779
107 42 41 65 = 10.573
33 173 79 63 = 0.8114
0 0 128 63 = 1.0000
146 41 41 65 = 10.573
0 0 30 66 = 39.500
0 0 184 65 = 23.000
I've found C# code that does the decode with BitConverter.ToSingle(), but I haven't found any like this for Lua.
Any idea?
What Lua version do you have?
This code works in Lua 5.3
local str = "DATA*\20\0\0\0\237\222\28\66\189\59\182\65..."
-- Read two float values starting from position 10 in the string
print(string.unpack("<ff", str, 10)) --> 39.217700958252 22.779169082642 18
-- 18 (third returned value) is the next position in the string
For Lua 5.1 you have to write special function (or steal it from François Perrad's git repo )
local function binary_to_float(str, pos)
local b1, b2, b3, b4 = str:byte(pos, pos+3)
local sign = b4 > 0x7F and -1 or 1
local expo = (b4 % 0x80) * 2 + math.floor(b3 / 0x80)
local mant = ((b3 % 0x80) * 0x100 + b2) * 0x100 + b1
local n
if mant + expo == 0 then
n = sign * 0.0
elseif expo == 0xFF then
n = (mant == 0 and sign or 0) / 0
else
n = sign * (1 + mant / 0x800000) * 2.0^(expo - 0x7F)
end
return n
end
local str = "DATA*\20\0\0\0\237\222\28\66\189\59\182\65..."
print(binary_to_float(str, 10)) --> 39.217700958252
print(binary_to_float(str, 14)) --> 22.779169082642
It’s little-endian byte-order of IEEE-754 single-precision binary:
E.g., 0 0 128 63 is:
00111111 10000000 00000000 00000000
(63) (128) (0) (0)
Why that equals 1 requires that you understand the very basics of IEEE-754 representation, namely its use of an exponent and mantissa. See here to start.
See #Egor‘s answer above for how to use string.unpack() in Lua 5.3 and one possible implementation you could use in earlier versions.

NSTableView binding + delegate causes array index error

I have a view-based NSTableView which uses bindings to an NSArrayController.
As soon as I add a delegate to the table view, I start getting:
Ignoring exception raised in void run_cocoa_block(void *): *** -[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array
and
MyApp[59144:25384659] *** -[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array
MyApp[59144:25384659] (
0 CoreFoundation 0x00007fff93410452 __exceptionPreprocess + 178
1 libobjc.A.dylib 0x00007fff9601af7e objc_exception_throw + 48
2 CoreFoundation 0x00007fff93327775 -[__NSArrayM objectAtIndex:] + 245
3 AppKit 0x00007fff9bd7ad31 -[NSTableRowData _addViewToRowView:atColumn:row:] + 535
4 AppKit 0x00007fff9bd7a98e -[NSTableRowData _addViewsToRowView:atRow:] + 184
5 AppKit 0x00007fff9bd791a7 -[NSTableRowData _initializeRowView:atRow:] + 390
6 AppKit 0x00007fff9bd77907 -[NSTableRowData _addRowViewForVisibleRow:withPriorView:] + 416
If I remove the delegate connection, everything works fine... the table fills properly from the NSArrayController that it is bound to, and the cells/columns get the correct data as well.
I need the delegate to use
-(BOOL)control:(NSControl *)control textShouldEndEditing:(NSText *)fieldEditor
What might be causing this?
Elsewhere in the app, I have a sheet that also uses a view-based NSTableView with bindings and it works fine with a delegate.
In awakeFromNib:, I was calling:
[[self itemsController] setContent:[[[NSMutableArray alloc] init] autorelease]];
this worked in a cell-based NSTableView but not in a view-based one. I'm not sure why, but giving it this empty array may have been happening after the binding took place but before the OS did something else with it and the empty array was confusing it.

tableView crashes on end up with more than 16 items

This is very confusing.
I have a UITableView, which updates and works fine until it gets more than 16 items then it crashes when trying to endUpdates after calling insertRowsAtIndexPaths.
The NSIndexPaths being added are all valid. -numberOfRowsInSection returns the correct number. It is not throwing an error related to the data set, rather it crashes with
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil'
when endUpdates is called on the tableView.
The data source is all there, the NSIndexPaths are fine. the code works fine between 0 and 16 rows, but when I add a 17th it crashes. Additionally if I start it with 22 items it works fine, when I add the 23rd it crashes... if I call reload data instead of doing the update and insert process it works fine, so it's nothing to do with the data itself, and it shouldn't be anything to do with how I'm inserting the rows since it works through 16...
I'm completely perplexed. Here is my update method. It is being called on the main thread at all times.
- (void)updateConversation:(NSNotification*)notification
{
NSDictionary *updateInfo = [notification userInfo];
//NSLog(#"Got update %#", updateInfo);
if ([[updateInfo objectForKey:#"success"] integerValue] == YES) {
[self updateConversationUI];
int addedStatementCount = [[updateInfo objectForKey:#"addedStatementCount"] intValue];
if (addedStatementCount > 0) {
//[self.tableView reloadData];
[self.tableView beginUpdates];
int previousStatmentCount = [[updateInfo objectForKey:#"previousStatmentCount"] intValue];
NSLog(#"owner %i, Was %i, now %i, change of %i", self.owner, previousStatmentCount, (int)self.conversation.statements.count, addedStatementCount);
NSMutableArray *rowPaths = [[NSMutableArray alloc] init];
for (int i = previousStatmentCount; i < previousStatmentCount + addedStatementCount; i++) {
NSIndexPath *path = [NSIndexPath indexPathForRow:i inSection:0];
[rowPaths addObject:path];
}
[self.tableView insertRowsAtIndexPaths:rowPaths withRowAnimation:UITableViewRowAnimationBottom];
[self.tableView endUpdates];
[self.tableView scrollToRowAtIndexPath:[rowPaths lastObject] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}
}
}
The rest of the crash past [self.tableView endUpdates] is UITableView
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil'
*** First throw call stack:
(
0 CoreFoundation 0x000000010189b795 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x00000001015fe991 objc_exception_throw + 43
2 CoreFoundation 0x0000000101852564 -[__NSArrayM insertObject:atIndex:] + 820
3 UIKit 0x0000000100317900 __46-[UITableView _updateWithItems:updateSupport:]_block_invoke691 + 173
4 UIKit 0x00000001002b5daf +[UIView(UIViewAnimationWithBlocks) _setupAnimationWithDuration:delay:view:options:factory:animations:start:animationStateGenerator:completion:] + 460
5 UIKit 0x00000001002b6004 +[UIView(UIViewAnimationWithBlocks) animateWithDuration:delay:options:animations:completion:] + 57
6 UIKit 0x00000001003174cb -[UITableView _updateWithItems:updateSupport:] + 2632
7 UIKit 0x0000000100312b18 -[UITableView _endCellAnimationsWithContext:] + 11615
8 Dev App 0x0000000100006036 -[ConversationViewController updateConversation:] + 998
9 CoreFoundation 0x00000001018f121c __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 12
10 CoreFoundation 0x000000010185370d _CFXNotificationPost + 2381
11 Dev App 0x00000001000055ac -[ConversationManager postNotification:] + 92
12 Foundation 0x0000000101204557 __NSThreadPerformPerform + 227
13 CoreFoundation 0x000000010182aec1 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
14 CoreFoundation 0x000000010182a792 __CFRunLoopDoSources0 + 242
15 CoreFoundation 0x000000010184661f __CFRunLoopRun + 767
16 CoreFoundation 0x0000000101845f33 CFRunLoopRunSpecific + 467
17 GraphicsServices 0x00000001039a23a0 GSEventRunModal + 161
18 UIKit 0x0000000100261043 UIApplicationMain + 1010
19 Dev App 0x0000000100003613 main + 115
20 libdyld.dylib 0x0000000101f2a5fd start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
This seems like a bug in the OS, the stack would indicate that it's something to do with the animation block but it happens no matter what I set the animation to, including none.
And to re-state. This works through 16 items, then inserting items past that causes a crash. It is also called at initial setup to load data, and it will load any number of items there, including well over 16. But when called again, purely as an update from 16 or more to something higher it will crash.
Most bizarre issue I've yet to encounter with table views...
under iOS 7 on device and simulator, latest Xcode for reference.
It seems that the problem is caused by my call of scrollToRowAtIndexPath (even though it crashes before it gets there...) combined with implementing tableView:estimatedHeightForRowAtIndexPath: by removing the row height estimate the crash went away... still seems like a bug in the animation system for tables to me. Thankfully I don't need the estimated row height, I had forgotten I had implemented it (trying to play nice by iOS 7 bites me again).
Place strategic breakpoints when you are incrementing the statement count, go through the loop of adding the rows as many times as you need to, and locate the statement that it's causing the crash, at that moment take a look at your objects and look for nil values as the error you are having it's trying to insert a nil object(or un-existent) from an Array.
I would personally recommend you to go through this loop entirely while keeping an exe for the path and previous statement count .
NSIndexPath *path = [NSIndexPath indexPathForRow:i inSection:0];
in my case the tableView:heightForHeaderInSection: method has been missing,
hadn't implemented the tableView:estimatedHeightForRowAtIndexPath method so this also could be solving the problem if you aren't using tableView:estimatedHeightForRowAtIndexPath:
Your problem is that you don't update the dataSource the tableView is using.
if you insert a row, you need to insert the appropriate object to the array the tableView is using.
Goodluck!

why is code not executing on return from Future in Dart program

Could someone please explain to me why in the following code (using r25630 Windows), the value of iInsertTot at line 241 is null, or more to the point, why is line 234 ("return iInsertTot;") not executed and therefore at line 241, iInsertTot is null. The value of iInsertTot at lines 231/232 is an integer. While I can and probably should code this differently, I thought that I would try and see if it worked, because my understanding of Futures and Chaining was that it would work. I have used “return” in a similar way before and it worked, but I was returning null in those cases (eg. line 201 below).
/// The problem lines are :
233 fUpdateTotalsTable().then((_) {
234 return iInsertTot;
235 });
While running in the debugger, it appears that line 234 “return iInsertTot;” is never actually executed. Running from command line has the same result.
The method being called on line 233 (fUpdateTotalsTable) is something I am just in the process of adding, and it consists basically of sync code at this stage. However, the debugger appears to go through it correctly.
I have included the method “fUpdateTotalsTable()” (line 1076) just in case that is causing a problem.
Lines 236 to 245 have just been added, however just in case that code is invalid I have commented those lines out and run with the same problem occurring.
218 /*
219 * Process Inserts
220 */
221 }).then((_) {
222 sCheckpoint = "fProcessMainInserts";
223 ogPrintLine.fPrintForce ("Processing database ......");
224 int iMaxInserts = int.parse(lsInput[I_MAX_INSERTS]);
225 print ("");
226 return fProcessMainInserts(iMaxInserts, oStopwatch);
227 /*
228 * Update the 'totals' table with the value of Inserts
229 */
230 }).then((int iReturnVal) {
231 int iInsertTot = iReturnVal;
232 sCheckpoint = "fUpdateTotalsTable (insert value)";
233 fUpdateTotalsTable().then((_) {
234 return iInsertTot;
235 });
236 /*
237 * Display totals for inserts
238 */
239 }).then((int iInsertTot) {
240 ogTotals.fPrintTotals(
241 "${iInsertTot} rows inserted - Inserts completed",
242 iInsertTot, oStopwatch.elapsedMilliseconds);
243
244 return null;
245 /*
192 /*
193 * Clear main table if selected
194 */
195 }).then((tReturnVal) {
196 if (tReturnVal)
197 ogPrintLine.fPrintForce("Random Keys Cleared");
198 sCheckpoint = "Clear Table ${S_TABLE_NAME}";
199 bool tClearTable = (lsInput[I_CLEAR_YN] == "y");
200 if (!tFirstInstance)
201 return null;
202 return fClearTable(tClearTable, S_TABLE_NAME);
203
204 /*
205 * Update control row to increment count of instances started
206 */
207 }).then((_) {
1073 /*
1074 * Update totals table with values from inserts and updates
1075 */
1076 async.Future<bool> fUpdateTotalsTable() {
1077 async.Completer<bool> oCompleter = new async.Completer<bool>();
1078
1079 String sCcyValue = ogCcy.fCcyIntToString(ogTotals.iTotAmt);
1080
1081 print ("\n********* Total = ${sCcyValue} \n");
1082
1083 oCompleter.complete(true);
1084 return oCompleter.future;
1085 }
Your function L230-235 does not return anything and that's why your iInsertTot is null L239. To make it work you have to add a return at line 233.
231 int iInsertTot = iReturnVal;
232 sCheckpoint = "fUpdateTotalsTable (insert value)";
233 return fUpdateTotalsTable().then((_) {
234 return iInsertTot;
235 });

Resources