Realm Cocoa: skipped item when iterating through RLMArray - cocoa

I have a very strange issue when iterating through RLMArray. I do something like this:
let tickets = Ticket.objectsWhere("pendingSync = true")
for ticket in tickets {
print("1. " + ticket.id + ",")
}
realm.beginWriteTransaction()
for ticket in tickets {
let ticket = ticket as Ticket
ticket.pendingSync = false
print("2. " + ticket.id + ",")
}
realm.commitWriteTransaction()
Strangely enough, the output is
1. 125, 1. 127, 1. 123,
2. 125, 2. 123
and NOT
1. 125, 1. 127, 1. 123,
2. 125, 2. 127, 2. 123
Shortly, the second iteration skips one item. How is this possible? Any ideas?
Thanks!

Mutating items during enumeration is not currently supported in Realm, but will be supported in the upcoming 0.95 release.

Related

what to do to make shinyapp give me my output

The primary variable is AgeGroup which has 2 levels. I am trying to get the sample size to output, but for some reason the app either gives error or wont output anything. Can anyone help? The are some comments in the code to help with confusion
Code:
library(shiny)
library(shinyWidgets)
library(survival)
library(shinyjs)
library(survminer)
# Define UI for application that draws a histogram
ui <- fluidPage(
# Application title
titlePanel("ProMBA Haslam Ad Sample Size"),
#Put in all key5 inputs as numeric inputs that the user will type in and choose starting, default values for these inputs
tabPanel("Inputs",
div( id ="form",
column(4,
numericInput("power", label=h6("Power"), value = .9),
numericInput("alpha", label=h6("Alpha"), value = .05),
numericInput("precision", label=h6("Precision"), value =0.05),
numericInput("Delta", label=h6("Delta"), value=.3),
column(4,
numericInput("sample", label=h6("Starting Sample Size"), value = 40),
numericInput("reps", label=h6("Number of Replications"), value=1000)),
),
column(4,
#title of output
h4("Calculated Sample Size"),
verbatimTextOutput(("n"),placeholder=TRUE)),
#create action buttons for users to run the form and to reset the form
textOutput("Sample Size (n)"),
column(4,
actionButton("action","Calculate"))
)))
server = function(input,output,session){
buttonGo = eventReactive(input$action, {withProgress(message = "Running", {
#relist the key inputs and save them to be able to be used in the rest of the code
n<-input$sample/2
alpha<-input$alpha
power <- input$power
beta<-1-input$power
precision<-input$precision
delta <- input$Delta +1
rep <- input$reps
nincrease<-10
#manually5 load in the data from the baseline data .xlxs file
Reporting <- c("12/13/21","12/14/21","12/15/21","12/16/21","12/17/21","12/18/21","12/19/21","12/20/21","12/21/21","12/22/21","12/23/21","12/24/21","12/25/21","12/26/21","12/27/21","12/28/21","12/29/21","12/30/21","12/31/21","1/1/22")
AdSet <- "Status Quo"
Results <- c(70,52, 33, 84, 37, 41, 22, 53, 78, 66, 100, 110, 52, 43, 63, 84, 16, 64, 21, 69)
ResultIndicator <- "actions:link_click"
Budget <- 100
CostPerClick<- c(1.43, 1.92, 3.03, 1.19, 2.70, 2.44, 4.55, 1.89, 1.28, 1.52, 1.00, 0.91, 1.92, 2.33, 1.59, 1.19, 6.25, 1.56, 4.76, 1.45)
Impressions <- c(7020, 8430, 5850, 7920, 6890, 7150, 6150, 7370, 8440, 6590, 6750,8720, 6410,7720, 6940, 8010, 7520, 7190, 6540, 6020)
df <- data.frame(Reporting, AdSet, Results, ResultIndicator,Budget,CostPerClick,Impressions)
#define the standard deviation of the results as well as the mean for group 1 of the 2 level variable and the mean for group 2
mean1 = mean(df$Results)
sd1 = sd(df$Results)
mean2 = delta*mean1
click=rep(0,n)
#Create 2 level variable
AgeGroup <- rep(c("Age21-35","Age36-50"),each=n)
#create new data frame with 2 level variable and click repetitions
DataFrame2 <- data.frame(AgeGroup,click)
#create new data frame binding all of the input variables together
DataFrame3 <- data.frame(cbind(n,alpha,power,precision,delta,rep))
#create for loop to find the pvalue of the ttest run with click~AgeGroup
trials=function(){
for(i in 1:nrow(DataFrame2)){
if(any(DataFrame2$AgeGroup[i]=="Age21-35")){DataFrame2$click[i] =rnorm(1,mean1,sd1)}else{DataFrame2$click[i] =rnorm(1,mean2,sd1)}
}
pvalttest=t.test(click~AgeGroup, data=DataFrame2)
return(pvalttest$p.value)
}
p_values=replicate(200,trials())
p_values=replicate(input$rep,trials())
#find if the p value is significance
significance=p_values[p_values<alpha]
#find the power of the signifiance and the pvalue
power <- length(significance)/length(p_values)
print(c(power,n))
#run a while loop to find the n within the goal power limits
goalpower<-1-beta
lowergoal<-goalpower-input$precision
uppergoal<-goalpower+input$precision
while (power<lowergoal||power>uppergoal){
if (power<lowergoal){
n=n+nincrease
AgeGroup=c()
click=c()
AgeGroup=rep(c("Age21-35","Age36-50"), each=n)
click=rep(NA,2*n)
Dataframe2=data.frame(AgeGroup,click)
p_values=replicate(input$reps, trials())
significance=p_values[p_values<alpha]
power=length(significance)/length(p_values)
print(c(n, power))
}else{
nincrease=nincrease%/%(10/9) #%/% fixes issue of rounding
n=n-nincrease
AgeGroup=c()
click=c()
AgeGroup=rep(c("Age21-35","Age36-50"), each=n)
click=rep(NA,2*n)
DataFrame2=data.frame(AgeGroup,click)
p_values=replicate(input$reps, trials())
significance=p_values[p_values<alpha]
power=length(significance)/length(p_values)
print(c(n, power))
}
}
#n is defined as the sample size of one of the levels of the 2 level variable, so mulitply by 2 to get full sample size
n*2
})
}
shinyApp(ui, server)
i dont need the app to be pretty. I just want it to run whenever someone clicks the calculate button

How to calculate average for each tumbling window?

I’m new in kafka streams and I’m really going crazy. I have a stream of counter values represented by <counter-name, counter-value, timestamp>. I want to calculate the average value for each day, like this:
counterValues topic content:
“cpu”, 10, “2022-06-03 17:00”
“cpu”, 20, “2022-06-03 18:00”
“cpu”, 30, “2022-06-04 10:00”
“memory”, 40, “2022-06-04 10:00”
and I want to obtain this output:
“cpu”, “2022-06-03”, 15
“cpu”, “2022-06-04”, 30
“memory”, “2022-06-04”, 40
This is a snippet of my code that it doesn’t work (it seems to calculate count)…
Duration windowSize = Duration.ofDays(1);
TimeWindows tumblingWindow = TimeWindows.of(windowSize);
counterValueStream
.groupByKey().windowedBy(tumblingWindow)
.aggregate(StatisticValue::new, (k, counterValue, statisticValue) -> {
statisticValue.setSamplesNumber(statisticValue.getSamplesNumber() + 1);
statisticValue.setSum(statisticValue.getSum() + counterValue.getValue());
return statisticValue;
}, Materialized.with(Serdes.String(), statisticValueSerde))
.toStream().map((Windowed<String> key, StatisticValue sv) -> {
double avgNoFormat = sv.getSum() / (double) sv.getSamplesNumber();
double formattedAvg = Double.parseDouble(String.format("%.2f", avgNoFormat));
return new KeyValue<>(key.key(), formattedAvg) ;
}).to("average", Produced.with(Serdes.String(), Serdes.Double()));
But the aggregation result is:
“cpu”, 1, “2022-06-03 17:00”
“cpu”, 1, “2022-06-03 18:00”
“cpu”, 1, “2022-06-04 10:00”
“memory”, 1, “2022-06-04 10:00”
Note that I use a TimestampExtractor that use counter timestamp instead of kafka record. What am I doing wrong?

Is there a solution to this formula stopping an AutoSort script

I am attempting to learn to script as I develop a project so please forgive me if I ask this question incorrectly.
I have created an AutoSort script for a google sheets document to sort a list of players by "Weight". It works fine until I add the following formula. Once I add this formula, my data is to be sorted by Column 7, largest to smallest and doesn't completely. The odd part of this is that the players that are out of order are listed as Substitutes.
The way this sheet works.
The Match Tool tab is where players are selected from Data Validation cells.
The Data Validation list comes from the MR1 Tab.
The MR1 tab gets it list based on an importrange defined in the MRTool.
This comes from a larger document and I've extracted the vital parts to make the error happen. I've tried to run a bare-bones version with only text and the AutoSort script and it sorts correctly. I have also tried changing which column the AutoSort looks in and it works correctly.
The formula that stops the script from working:
=if(or(C10="",C10=". Blank"),"",iferror(index('MR1'!$B$8:$H$87,(match(C10,'MR1'!$N$8:$N$87,0))),"Player Not Found"))
The Script for the AutoSort:
var roster = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Match Tool");
var range1 = roster.getRange("B10:K59");
var range2 = roster.getRange("N10:W59");
range1.sort( [{ column : 7, ascending: false}, { column : 11, ascending: false}] );
range2.sort( [{ column : 19, ascending: false}, { column : 23, ascending: false}] );
}
function SortLeft() {
var roster = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Match Tool");
var range1 = roster.getRange("B10:K59");
range1.sort( [{ column : 7, ascending: false}, { column : 11, ascending: false}] );
}
function SortRight() {
var roster = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Match Tool");
var range2 = roster.getRange("N10:W59");
// It seems that column numbers are always sequential from the first one, even if you are addressing a range. Hence using 14/18 here instead of 4/8
range2.sort( [{ column : 19, ascending: false}, { column : 23, ascending: false}] );
}
function SortSelection() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var range = sheet.getActiveRange();
var firstcol = range.getColumn();
var lastcol = range.getLastColumn();
//Before sorting, this code checks to make sure that Clan through Combined heroes is selected on one side or the other. If not, an error appears.
if (firstcol == 2 && lastcol == 11 ) { range.sort( [{ column : 7, ascending: false}, { column : 11, ascending: false}] )} //&& lastcol == 11
else if ( firstcol == 14 && lastcol == 23 ) { range.sort( [{ column : 19, ascending: false}, { column : 23, ascending: false}] )} //&& lastcol == 23
else { SpreadsheetApp.getUi().alert('You can only sort selections that include all 8 data columns, from Clan to Notes.');}
}
function onEdit(e){
var roster = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Match Tool");
var autosort = roster.getRange(6, 13).getValue();
var range1 = roster.getRange("B10:K59");
var range2 = roster.getRange("N10:W59");
// if('B3' === GWL) {
// SpreadsheetApp.getActiveSheet().getRange('K2').setValue('40');
// }
// test if K2 (war size) was modified
if (e.source.getActiveSheet().getName() == "Match Tool" && e.range.rowStart === 6 && e.range.columnStart === 13) {
moveToSub();
}
//preform autosort if on
if ( autosort == "On" ){
range1.sort( [{ column : 7, ascending: false}, { column : 11, ascending: false}] );
range2.sort( [{ column : 19, ascending: false}, { column : 23, ascending: false}] );
}
}
I expect players to be sorted by column 7 (column G) descending and then column 11 (Column K) descending. What I'm getting is certain players not sorted correctly.
I am getting - 132, 131, 131, 113, 111, 132, 113, 90, 88, 87, 86.
I should see - 132, 132, 131, 131, 113, 113, 111, 90, 88, 87, 86.
Thank you for taking the time to help me.
After some help from a friend, we realized the problem wasn't anything to do with the script on this page, it was how the data was entered on the sheet the data was imported in from. Some numbers were entered as numerals while others were entered in as text. By changing the text to numerals, the script performed as expected.
So the moral of the story is, check to make sure the data being sort is of the same type.

Select an Item from open check through isl code on micros 3700

Does anyone know how can I select an item from open check through isl code on micros 3700?
I want to select it and perform a discount on it.
VAR CheckItemIndex : N2
VAR DetailsRow : N2
VAR CheckItems[64] : N10
VAR CheckItemsCount : N2
CheckItemsCount = 0
CheckItemIndex = 1
DetailsRow = 1
WINDOW 8, 75, "TEST WINDOW"
DISPLAY DetailsRow, 2, "CHECK ITEMS"
//dtl_type I Info, M Item, D Discount, S ServiceCharge, T Tender/Media, R ReferenceNumber, C CA Detail
FOR i = 1 TO #numdtlt
IF #DTL_TYPE[i] = "M" //AND BIT(#DTL_STATUS[i], 5) = 0
DetailsRow = DetailsRow + 1
DISPLAY DetailsRow, 2, #DTL_NAME[i], " ", #DTL_OBJNUM[i], " ", #DTL_TYPE[i], " ", #DTL_TYPEDEF[i], " S: ", #DTL_STATUS[i]
CheckItems[CheckItemIndex] = #DTL_OBJNUM[i]
CheckItemIndex = CheckItemIndex + 1
CheckItemsCount = CheckItemsCount + 1
ENDIF
ENDFOR
//I want to select an item here (for example the 2nd one) and perform a discount
LOADDBKYBDMACRO 545 // this is a predefined macro for 100% discount
I have concluded that it is not possible to select an item in the check as a user makes with his hand. So i cant perform a discount on a selected item from check.
A solution for my problem is to calculate the discount amount and perform an open amount discount using a predefined macro.
...
LOADKYBDMACRO key(5, 217)//a predefined discount macro open amount
LOADKYBDMACRO makekeys(DiscountPrice)
LOADKYBDMACRO #KEY_ENTER
...
As far as I know it is not possible to select item from ISL, but you could use ItemDiscount command to discount check item:
var dtl_arr[2]: N10 //dtl indexes array
var disc_val_arr[2]: $10 // discount value array
dtl_arr[1] = 1 //...index of item to discount...
disc_val_array[1] = 50 // eg. 50% discount on item
ItemDiscount 1000053, 1, dtl_arr, disc_val_arr //1000053 is the discount obj num, 1 is the number of items to discount

use for loop to call multiple functions in lua

I want to call multiple methods in lua that are very similar except their parameters change by one character. The way I'm doing it now works but is extremely in efficient.
function scene:createScene(event)
screenGroup = self.view
level1= display.newRoundedRect( 50, 110, 50, 50, 5 )
level1:setFillColor( 100,0,200 )
level2= display.newRoundedRect( 105, 110, 50, 50, 5 )
level2:setFillColor (100,200,0)
--and so on so forth
screenGroup:insert (level1)
screenGroup:insert (level2)
screenGroup:insert (level3)
screenGroup:insert (level4)
end
I plan on extending the screenGroop:insert method to hundreds of levels, maybe up to (level300). As you can see the way I'm doing it now is inefficient. I tried doing
for i=1, 4, 1 do
screenGroup:insert(level..i)
end
but I get the error "table expected."
The best way in this case is to probably use a table:
local levels = {}
levels[1] = display.newRoundedRect( 50, 110, 50, 50, 5 )
levels[1]:setFillColor( 100,0,200 )
levels[2] = display.newRoundedRect( 105, 110, 50, 50, 5 )
levels[2]:setFillColor (100,200,0)
--and so on so forth
for _, level in ipairs(levels) do
screenGroup:insert(level)
end
For other alternatives check the SO answer from #EtanReisner's comment.
If your 'level' tables are global, which is appears they are, you can use getfenv to index them.
for i = 1, number_of_levels do
screenGroup:insert(getfenv()["level" .. i])
end
getfenv returns the environment, with all global variables, in the form of a dictionary. Therefore, you can index it like a normal table like getfenv()["key"]

Resources