Crashed in try! realm.write - realm

My Project Crashed in RealmUtil.swift line 16, the codes are shown below.
Is this mean that realm return nil?
I was quite confused. Hoping to get your help.
Great Thanks!
RealmUtil.swift
15 let realm = try! Realm()
16 try! realm.write {
17 write()
18 }
detail log are as below.
It's shown in firebase, and I wasn't able to debug this in debug mode.
Crashed: com.apple.main-thread
0 libsystem_kernel.dylib 0x1978b5ec4 __pthread_kill + 8
1 libsystem_pthread.dylib 0x1977d5724 pthread_kill$VARIANT$armv81 + 216
2 libsystem_c.dylib 0x197725844 abort + 100
3 Realm 0x1041bfe30 please_report_this_error_to_help_at_realm_dot_io + 10
4 Realm 0x1041c00fc realm::util::terminate_internal(std::__1::basic_stringstream<char, std::__1::char_traits<char>, std::__1::allocator<char> >&) + 264
5 Realm 0x1041c0270 realm::util::terminate(char const*, char const*, long, std::initializer_list<realm::util::Printable>&&) + 324
6 Realm 0x103eed0f4 realm::_impl::RealmCoordinator::advance_schema_cache(unsigned long long, unsigned long long) + 182
7 Realm 0x103fc0c2c realm::Realm::cache_new_schema() + 100
8 Realm 0x103fc1510 realm::Realm::begin_transaction() + 176
9 Realm 0x103f900e0 -[RLMRealm beginWriteTransaction] + 20
10 RealmSwift 0x10477004c $s10RealmSwift0A0V5write16withoutNotifying_xSaySo20RLMNotificationTokenCG_xyKXEtKlF + 136
11 Ig Followers 0x102da91c8 specialized static HomeViewModel.engagementAnalysis(media:) + 16 (RealmUtil.swift:16)
12 Ig Followers 0x102da9408 specialized static HomeViewModel.analysisLTS() + 4301886472 (<compiler-generated>:4301886472)
13 Ig Followers 0x102c84b2c closure #1 in closure #1 in HomeVC.getLTSData() + 4300688172 (<compiler-generated>:4300688172)
14 Ig Followers 0x102dab644 partial apply for closure #1 in closure #1 in static HomeViewModel.getLTSData2(pk:completeHandler:) + 4301895236 (<compiler-generated>:4301895236)
15 Ig Followers 0x102c9f454 thunk for #escaping #callee_guaranteed () -> () + 4300797012 (<compiler-generated>:4300797012)
added image about detail function about this problem.
crashed_function_image_click_to_see

The problem is how the optionals are being handled. The issue is here
let lts = HVMlts()!
as that code force unwraps the return value guaranteeing HVMlts will never be nil.
However if you look at the associated functions, it can in fact, return nil.
if results.count == 1 {
return results[0]
} else {
return nil
}
If the Realm filter
let results = realm.objects(HomeViewModel.self)...
returns two or more results, then that function would return nil. Likewise if there were no results then it would also return nil
In either case that nil would cause your code to crash.
It's best to safely unwrap optionals or provide default values using a nil coalescing operator. I see you've done that in other parts of your code but here are two more options.
if let lts = HVMlts() then {
//do something with lts as it's not nil
}
or
guard let lts = HVMlts() else { return }
//do something with lts

Related

Sending pointers over a channel

I am trying to use channels to implement a kind of a worker pool. Please take a look at the code below
https://play.golang.org/p/g7aKxDoP9lf (The Go Playground)
package main
import (
"fmt"
"time"
)
func main() {
q1 := make(chan int)
fmt.Printf("worker 1\n")
go worker1(q1)
for i := 0; i < 10; i++ {
fmt.Printf("sending: %v\n", i)
q1 <- i
}
time.Sleep(time.Second)
fmt.Printf("\n\nworker 2\n")
q2 := make(chan *int)
go worker2(q2)
for i := 0; i < 10; i++ {
fmt.Printf("sending: %v\n", i)
q2 <- &i
}
time.Sleep(time.Second)
}
func worker1(qTodo <-chan int) {
var curr int
for {
select {
case curr = <-qTodo:
fmt.Printf("got: %v\n", curr)
}
}
}
func worker2(qTodo <-chan *int) {
var curr *int
for {
select {
case curr = <-qTodo:
fmt.Printf("got: %v\n", *curr)
}
}
}
Here is a sample output
worker 1
sending: 0
got: 0
sending: 1
sending: 2
got: 1
got: 2
sending: 3
sending: 4
got: 3
got: 4
sending: 5
sending: 6
got: 5
got: 6
sending: 7
sending: 8
got: 7
got: 8
sending: 9
got: 9
worker 2
sending: 0
got: 0
sending: 1
sending: 2
got: 2
got: 2
sending: 3
sending: 4
got: 4
got: 4
sending: 5
sending: 6
got: 6
got: 6
sending: 7
sending: 8
got: 8
got: 8
sending: 9
got: 10
It seems that at the time when the pointer is recieved by worker2, the value has already changed in the original variable which is reflected in the value printed.
The question is how can this be avoided? How can this be worked around?
This problem is covered in the Channels section of Effective Go. Here's a short excerpt, with the variable name changed to match your code:
The bug is that in a Go for loop, the loop variable is reused for each iteration, so the i variable is shared across all goroutines. That's not what we want. We need to make sure that i is unique for each goroutine.
It goes on to describe two solutions:
Pass the value of i as an argument to the function in the goroutine
Create a new variable in the loop and use that instead
Since your goroutine is started outside your loop, only #2 applies to your code.
The value that the received pointer points to is not what you expect because you're sending it a pointer to the same variable every time, so the worker sees whatever value that variable has at the time it dereferences the pointer. A typical way around this sort of problem is to make a copy of the variable inside the for loop and send a pointer to that. That way, you're sending a pointer to a different object every time. Try this:
for i := 0; i < 10; i++ {
fmt.Printf("sending: %v\n", i)
iCopy := i
q2 <- &iCopy
}

Efficient method for imposing (some cases of) periodic boundary conditions on floats?

Some cases of periodic boundary conditions (PBC) can be imposed very efficiently on integers by simply doing:
myWrappedWithinPeriodicBoundary = myUIntValue & mask
This works when the boundary is the half open range [0, upperBound), where the (exclusive) upperBound is 2^exp so that
mask = (1 << exp) - 1
For example:
let pbcUpperBoundExp = 2 // so the periodic boundary will be [0, 4)
let mask = (1 << pbcUpperBoundExp) - 1
for x in -7 ... 7 { print(x & mask, terminator: " ") }
(in Swift) will print:
1 2 3 0 1 2 3 0 1 2 3 0 1 2 3
Question: Is there any (roughly similar) efficient method for imposing (some cases of) PBCs on floating point-numbers (32 or 64-bit IEEE-754)?
There are several reasonable approaches:
fmod(x,1)
modf(x,&dummy) — has the advantage of knowing its divisor statically, but in my testing comes from libc.so.6 even with -ffast-math
x-floor(x) (suggested by Jens in a comment) — supports negative inputs directly
Manual bit-twiddling direct implementation
Manual bit-twiddling implementation of floor
The first two preserve the sign of their input; you can add 1 if it's negative.
The two bit manipulations are very similar: you identify which significand bits correspond to the integer portion, and mask them (for the direct implementation) or the rest (to implement floor) off. The direct implementation can be completed either with a floating-point division or with a shift to reassemble the double manually; the former is 28% faster even given hardware CLZ. The floor implementation can immediately reconstitute a double: floor never changes the exponent of its argument unless it returns 0. About 20 lines of C are required.
The following timing is with double and gcc -O3, with timing loops over representative inputs into which the operative code was inlined.
fmod: 41.8 ns
modf: 19.6 ns
floor: 10.6 ns
With -ffast-math:
fmod: 26.2 ns
modf: 30.0 ns
floor: 21.9 ns
Bit manipulation:
direct: 18.0 ns
floor: 20.6 ns
The manual implementations are competitive, but the floor technique is the best. Oddly, two of the three library functions perform better without -ffast-math: that is, as a PLT function call than as an inlined builtin function.
I'm adding this answer to my own question since it describes the, at the time of writing, best solution I have found. It's in Swift 4.1 (should be straight forward to translate into C) and it's been tested in various use cases:
extension BinaryFloatingPoint {
/// Returns the value after restricting it to the periodic boundary
/// condition [0, 1).
/// See https://forums.swift.org/t/why-no-fraction-in-floatingpoint/10337
#_transparent
func wrappedToUnitRange() -> Self {
let fract = self - self.rounded(.down)
// Have to clamp to just below 1 because very small negative values
// will otherwise return an out of range result of 1.0.
// Turns out this:
if fract >= 1.0 { return Self(1).nextDown } else { return fract }
// is faster than this:
//return min(fract, Self(1).nextDown)
}
#_transparent
func wrapped(to range: Range<Self>) -> Self {
let measure = range.upperBound - range.lowerBound
let recipMeasure = Self(1) / measure
let scaled = (self - range.lowerBound) * recipMeasure
return scaled.wrappedToUnitRange() * measure + range.lowerBound
}
#_transparent
func wrappedIteratively(to range: Range<Self>) -> Self {
var v = self
let measure = range.upperBound - range.lowerBound
while v >= range.upperBound { v = v - measure }
while v < range.lowerBound { v = v + measure }
return v
}
}
On my MacBook Pro with a 2 GHz Intel Core i7,
a hundred million (probably inlined) calls to wrapped(to range:) on random (finite) Double values takes 0.6 seconds, which is about 166 million calls per second (not multi threaded). The range being statically known or not, or having bounds or measure that is a power of two etc, can make some difference but not as much as one could perhaps have thought.
wrappedToUnitRange() takes about 0.2 seconds, meaning 500 million calls per second on my system.
Given the right scenario, wrappedIteratively(to range:) is as fast as wrappedToUnitRange().
The timings have been made by comparing a baseline test (without wrapping some value, but still using it to compute eg a simple xor checksum) to the same test where a value is wrapped. The difference in time between these are the times I have given for the wrapping calls.
I have used Swift development toolchain 2018-02-21, compiling with -O -whole-module-optimization -static-stdlib -gnone. And care has been taken to make the tests relevant, ie preventing dead code removal, using true random input of different distributions etc. Writing the wrapping functions generically, like this extension on BinaryFloatingPoint, turned out to be optimized into equivalent code as if I had written separate specialized versions for eg Float and Double.
It would be interesting to see someone more skilled than me investigating this further (C or Swift or any other language doesn't matter).
EDIT:
For anyone interested, here is some versions for simd float2:
extension float2 {
#_transparent
func wrappedInUnitRange() -> float2 {
return simd.fract(self)
}
#_transparent
func wrappedToMinusOneToOne() -> float2 {
let scaled = (self + float2(1, 1)) * float2(0.5, 0.5)
let scaledFract = scaled - floor(scaled)
let wrapped = simd_muladd(scaledFract, float2(2, 2), float2(-1, -1))
// Note that we have to make sure the result is not out of bounds, like
// simd fract does:
let oneNextDown = Float(bitPattern:
0b0_01111110_11111111111111111111111)
let oneNextDownFloat2 = float2(oneNextDown, oneNextDown)
return simd.min(wrapped, oneNextDownFloat2)
}
#_transparent
func wrapped(toLowerBound lowerBound: float2,
upperBound: float2) -> float2
{
let measure = upperBound - lowerBound
let recipMeasure = simd_precise_recip(measure)
let scaled = (self - lowerBound) * recipMeasure
let scaledFract = scaled - floor(scaled)
// Note that we have to make sure the result is not out of bounds, like
// simd fract does:
let wrapped = simd_muladd(scaledFract, measure, lowerBound)
let maxX = upperBound.x.nextDown // For some reason, this won't be
let maxY = upperBound.y.nextDown // optimized even when upperBound is
// statically known, and there is no similar simd function available.
let maxValue = float2(maxX, maxY)
return simd.min(wrapped, maxValue)
}
}
I asked some related simd-related questions here which might be of interest.
EDIT2:
As can be seen in the above Swift Forums thread:
// Note that tiny negative values like:
let x: Float = -1e-08
// May produce results outside the [0, 1) range:
let wrapped = x - floor(x)
print(wrapped < 1.0) // false
// which may result in out-of-bounds table accesses
// in common usage, so it's probably better to use:
let correctlyWrapped = simd_fract(x)
print(correctlyWrapped < 1.0) // true
I have since updated the code to account for this.

Generating random math equation using tree - Avoiding Parentheses

Edit: This was originally on programmers.stackexchange.com, but since I already had some code I thought it might be better here.
I am trying to generate a random math problem/equation. After researching the best (and only) thing I found was this question: Generating random math expression. Because I needed all 4 operations, and the app that I will be using this in is targeted at kids, I wanted to be able to insure that all numbers would be positive, division would come out even, etc, I decided to use a tree.
I have the tree working, and it can generate an equation as well as evaluate it to a number. The problem is that I am having trouble getting it to only use parentheses when needed. I have tried several solutions, that primaraly involve:
Seeing if this node is on the right of the parent node
Seeing if the node is more/less important then it's parent node (* > +, etc).
Seeing if the node & it's parent are of the same type, and if so if the order matters for that operation.
Not that it matters, I am using Swift, and here is what I have so far:
func generateString(parent_node:TreeNode) -> String {
if(self.is_num){
return self.equation!
}
var equation = self.equation!
var left_equation : String = self.left_node!.generateString(self)
var right_equation : String = self.right_node!.generateString(self)
// Conditions for ()s
var needs_parentheses = false
needs_parentheses = parent_node.importance > self.importance
needs_parentheses = (
needs_parentheses
||
(
parent_node.right_node?.isEqualToNode(self)
&&
parent_node.importance <= self.importance
&&
(
parent_node.type != self.type
&&
( parent_node.order_matters != true || self.order_matters != true )
)
)
)
needs_parentheses = (
needs_parentheses
&&
(
!(
self.importance > parent_node.importance
)
)
)
if (needs_parentheses) {
equation = "(\(equation))"
}
return equation.stringByReplacingOccurrencesOfString("a", withString: left_equation).stringByReplacingOccurrencesOfString("b", withString: right_equation)
}
I have not been able to get this to work, and have been banging my head against the wall about it.
The only thing I could find on the subject of removing parentheses is this: How to get rid of unnecessary parentheses in mathematical expression, and I could not figure out how to apply it to my use case. Also, I found this, and I might try to build a parser (using PEGKit), but I wanted to know if anybody had a good idea to either determine where parentheses need to go, or put them everywhere and remove the useless ones.
EDIT: Just to be clear, I don't need someone to write this for me, I am just looking for what it needs to do.
EDIT 2: Since this app will be targeted at kids, I would like to use the least amount of parentheses possible, while still having the equation come out right. Also, the above algorithm does not put enough parentheses.
I have coded a python 3 pgrm that does NOT use a tree, but does successfully generate valid equations with integer solutions and it uses all four operations plus parenthetical expressions. My target audience is 5th graders practicing order of operations (PEMDAS).
872 = 26 * 20 + (3 + 8) * 16 * 2
251 = 256 - 3 - 6 + 8 / 2
367 = 38 * 2 + (20 + 15) + 16 ** 2
260 = 28 * 10 - 18 - 4 / 2
5000 = 40 * 20 / 4 * 5 ** 2
211 = 192 - 10 / 2 / 1 + 24
1519 = 92 * 16 + 6 + 25 + 16
If the python of any interest to you ... I am working on translating the python into JavaScript and make a web page available for students and teachers.

Groovy List of Lists or 2D Array

I am new to groovy and I am writing a program for reading numbers from an input file which has the following format
1
2 3
4 5 6
7 8 9 10
I wish to store them in a 2D array, how would I achieve it?
I have the following code so far for the read method
private read(fileName){
def count = 0
def fname = new File(fileName)
if (!fname.exists())
println "File Not Found"
else{
def input = []
def inc = 0
fname.eachLine {line->
def arr = line.split(" ")
def list = []
for (i in 1..arr.length-1) {
list.add(arr[i].toInteger())
}
input.add(list)//not sure if this is correct
inc++
}
input.each {
print it
//not sure how to reference the list
}
}
}
I am able to print the lists but I am not sure how to use the list of lists in the program (for performing other operations on it). Can anyone please help me out here?
On the input.each all you need is to iterate again in each item in the row. If it were a collection of unknown depth, then you'd need to stick to a recursive method.
Made a small change and removed the inc, since it is not needed (at least in the snippet):
fname = """1
2 3
4 5 6
7 8 9 10"""
def input = []
fname.eachLine { line->
def array = line.split(" ")
def list = []
for (item in array) {
list.add item.toInteger()
}
input.add list
}
input.each { line ->
print "items in line: "
for (item in line) {
print "$item "
}
println ""
}
Prints:
items in line: 1
items in line: 2 3
items in line: 4 5 6
items in line: 7 8 9 10
That is plain simple iteration. You can use #Tim's suggestion to make it more idiomatic in Groovy :-)

presentPopoverFromRect:inView:permittedArrowDirections:animated crashing in iOS 6.0 [duplicate]

This question already has answers here:
Crash on presenting UIImagePickerController under iOS 6.0
(5 answers)
Closed 8 years ago.
I just upgraded from iOS 5.1.1 to 6.0 and the following code path is crashing with SIGTRAP when it attempts to display a popover with an imagePickerViewController as its contentVC to allow the user to select an image or video from the photoLibrary.
It was working great with 5.1.1. I've been troubleshooting this for a couple of days with no headway.
Does anyone have a handle on this? Is there an alternative method to use for iOS6.0? I can add more code if needed...
I can capture images and video with the line:
[self presentViewController:self.imagePickerViewController.imagePickerController animated:YES completion:NULL];
Here is the method in full called after the user touches a UIButton.
- (void)showImagePicker:(UIImagePickerControllerSourceType)sourceType mediaType:(NSString *)mediaType
{
if (self.capturedMovies.count > 0)
[self.capturedMovies removeAllObjects];
if ([UIImagePickerController isSourceTypeAvailable:sourceType])
{
[self.imagePickerViewController setupImagePicker:sourceType mediaType:mediaType];
if (sourceType == UIImagePickerControllerSourceTypeCamera) { // WORKS
[self presentViewController:self.imagePickerViewController.imagePickerController animated:YES completion:NULL];
}
else if (sourceType == UIImagePickerControllerSourceTypePhotoLibrary) {
//else if ([mediaType isEqualToString:(NSString *)kUTTypeMovie] || [mediaType isEqualToString:(NSString *)kUTTypeImage]) {
if (!self.moviePickerPopoverController) {
self.moviePickerPopoverController = [[UIPopoverController alloc] initWithContentViewController:self.imagePickerViewController.imagePickerController];
}
UIView *uiViewObject = self.mediaTitleTextField;
CGFloat xLocation = uiViewObject.frame.origin.x;
CGFloat yLocation = uiViewObject.frame.origin.y;
CGFloat width = uiViewObject.bounds.size.width;
CGFloat height = uiViewObject.bounds.size.height;
// CRASHES HERE!!!
[self.moviePickerPopoverController presentPopoverFromRect:CGRectMake(xLocation, yLocation, width, height)
inView:self.view
permittedArrowDirections:UIPopoverArrowDirectionAny
animated:YES];
}
}
}
Here is what pops up in the code window:
Thread 1: signal SIGTRAP on line 3:
libsystemkernel.dylib`_kill:
0x394e7830: mov r12, #37
0x394e7834: svc #128
0x394e7838: blo 0x394e7850 ; __kill + 32 <<<<<<<<< Thread 1: signal SIGTRAP
0x394e783c: ldr r12, [pc, #4] ; __kill + 24
0x394e7840: ldr r12, [pc, r12]
0x394e7844: b 0x394e784c ; __kill + 28
0x394e7848: ldrdeq r6, r7, [r0], -r12
0x394e784c: bx r12
0x394e7850: bx lr
Here is the backtrace from the debugger:
(lldb) bt
* thread #1: tid = 0x2503, 0x394e7838 libsystem_kernel.dylib`__kill + 8, stop reason = signal SIGTRAP
frame #0: 0x394e7838 libsystem_kernel.dylib`__kill + 8
frame #1: 0x001275d4 MyAppName`TFHandleExceptions + 992
frame #2: 0x36bd357e CoreFoundation`__handleUncaughtException + 614
frame #3: 0x39313a64 libobjc.A.dylib`_objc_terminate() + 128
frame #4: 0x3363c07a libc++abi.dylib`safe_handler_caller(void (*)()) + 78
frame #5: 0x3363c114 libc++abi.dylib`std::terminate() + 20
frame #6: 0x3363d598 libc++abi.dylib`__cxa_rethrow + 88
frame #7: 0x393139d0 libobjc.A.dylib`objc_exception_rethrow + 12
frame #8: 0x36b19f20 CoreFoundation`CFRunLoopRunSpecific + 456
frame #9: 0x36b19d48 CoreFoundation`CFRunLoopRunInMode + 104
frame #10: 0x38ca82ea GraphicsServices`GSEventRunModal + 74
frame #11: 0x3701d300 UIKit`UIApplicationMain + 1120
frame #12: 0x000629b0 MyAppName`main + 96 at main.m:16
This is a duplicate of https://stackoverflow.com/a/12575058/1074338
Also, I should have touched the go button on the debugger...
which revealed the offending code:
*** Terminating app due to uncaught exception
'UIApplicationInvalidInterfaceOrientation',
reason: 'Supported orientations has no common orientation
with the application, and shouldAutorotate is returning YES'

Resources