Related
I am trying to get acc, accel and rx from below text only if accounting value is true.
dataRx: 21916 drx: 1743625
ota: 191791 orx: 74164489
dataDropped: 14 dropped:1134
id: 65535 waitress BE nginxid: 0 kbps: 0.000
accounting: false
drop : 1
rx : 48392 bytes: 483920
id: 65533 waitress BE nginxid: 1 kbps: 0.000
accounting: false
drop : 4
rx : 122914 bytes: 70081939
id: 4232 nginx BE nginxid: 3 kbps: 0.000
accounting: false
drop : 0
rx : 3084 bytes: 94357
id: 10482 server BE nginxid: 4 kbps: 0.000
accounting: false
drop : 0
rx : 15 bytes: 2477
id: 20344 serve BE nginxid: 10 kbps: 62914.560
accounting: true
drop : 2
rx : 2217 bytes: 309637
accel : 482 bytes: 264318
acc :349 bytes: 225181
Below python code gets accounting and accel values using below regex
accounting:\s*((?P<accounting>\S*)[\S\s]*?accel:[\S\s]*?bytes:\s*(?P<accel>\S*)[\S\s]*?)
for match in re.finditer(re_exp, text):
group = match.groupdict()
print group
Output:
{"accounting": false, "accel": 264318}
But, the expected output should be
{"accounting": true, "accel": 264318}
Need help with regex expression. Any help would be greatly appreciated.
Also, is there a regex way to group all the data fields under id?
Thanks
Try this
content = open("acc.txt",'r')
ar = content.read()
import re
getdata = re.findall(r"accounting: (true).+?accel.+?bytes:\s(\d+)",ar,re.S)
print getdata
Try as the follow for group the all data corresponding to their id
content = open("acc.txt",'r')
ar = content.readlines()
arv = []
flag = 0
m = ""
for j in ar:
if("id:"in j):
arv.append(m)
m = ""
flag = 1
if (flag == 1):
m+=j
for j in (arv):
print j
Iterate through lines one by one:
import re
rx = ""
accel = ""
acc = ""
lines = text.split("\n")
for i in range(len(lines)):
line = lines[i]
if line == "accounting: true":
match = re.search(r"rx\s*:\s+(\d*)", lines[i+2])
if match:
rx = match.group(1)
match = re.search(r"accel\s*:\s+(\d*)", lines[i+3])
if match:
accel = match.group(1)
match = re.search(r"acc\s*:\s*(\d*)", lines[i+4])
if match:
acc = match.group(1)
print("'accounting': true, 'rx': {}, 'accel': {}, 'acc': {}".format(rx, accel, acc))
I want to delete some rows in pandas dataframe.
ID Value
2012XY000 1
2012XY001 1
.
.
.
2015AB000 4
2015PQ001 5
.
.
.
2016DF00G 2
I want to delete rows whose ID does not start with 2015.
How should I do that?
Use startswith with boolean indexing:
print (df.ID.str.startswith('2015'))
0 False
1 False
2 True
3 True
4 False
Name: ID, dtype: bool
print (df[df.ID.str.startswith('2015')])
ID Value
2 2015AB000 4
3 2015PQ001 5
EDIT by comment:
print (df)
ID Value
0 2012XY000 1
1 2012XY001 1
2 2015AB000 4
3 2015PQ001 5
4 2015XQ001 5
5 2016DF00G 2
print ((df.ID.str.startswith('2015')) & (df.ID.str[4] != 'X'))
0 False
1 False
2 True
3 True
4 False
5 False
Name: ID, dtype: bool
print (df[(df.ID.str.startswith('2015')) & (df.ID.str[4] != 'X')])
ID Value
2 2015AB000 4
3 2015PQ001 5
Use str.match with regex string r'^2015':
df[df.ID.str.match(r'^2015')]
To exclude those that have an X afterwards.
df[df.ID.str.match(r'^2015[^X]')]
The regex r'^2015[^X]' translates into
^2015 - must start with 2015
[^X] - character after 2015 must not be X
consider the df
then
df[df.ID.str.match(r'^2015[^X]')]
I'm trying to read in a large file (~8Gb) using pandas read_csv. In one of the columns in the data, there is sometimes a list which includes commas but it enclosed by curly brackets e.g.
"label1","label2","label3","label4","label5"
"{A1}","2","","False","{ "apple" : false, "pear" : false, "banana" : null}
Therefore, when these particular lines were read in I was getting the error "Error tokenizing data. C error: Expected 37 fields in line 35, saw 42". I found this solution which said to add
sep=",(?![^{]*})" into the read_csv arguments which worked with splitting the data correctly. However, the data now includes the quotation marks around every entry (this didn't happen before I added the sep argument in).
The data looks something like this now:
"label1" "label2" "label3" "label4" "label5"
"{A1}" "2" "" "False" "{ "apple" : false, "pear" : false, "banana" : null}"
meaning I can't use, for example, .describe(), etc on the numerical data because they're still strings.
Does anyone know of a way of reading it in without the quotation marks but still splitting the data where it is?
Very new to Python so apologies if there is an obvious solution.
serialdev found a solution to removing the "s but the data columns are objects and not what I would expect/want, e.g. the integer values aren't seen as integers.
The data needs to be split at "," explicitly (including the "s), is there a way of stating that in the read_csv arguments?
Thanks!
To read in the data structure you specified, where the last element is an unknown length.
"{A1}","2","","False","{ "apple" : false, "pear" : false, "banana" : null}"
"{A1}","2","","False","{ "apple" : false, "pear" : false, "banana" : null, "orange": "true"}"
Change the separate to a regular expression using a negative forward lookahead assertion. This will enable you to separate on a ',' only when not immediately followed by a space.
df = pd.read_csv('my_file.csv', sep='[,](?!\s)', engine='python', thousands='"')
print df
0 1 2 3 4
0 "{A1}" 2 NaN "False" "{ "apple" : false, "pear" : false, "banana" :...
1 "{A1}" 2 NaN "False" "{ "apple" : false, "pear" : false, "banana" :...
Specifying the thousands separator as the quote is a bit of a hackie way to parse fields contains a quoted integer into the correct datatype. You can achieve the same result using converters which can also remove the quotes from the strings should you need it to and cast "True" or "False" to a boolean.
If need remove " from column, use vectorized function str.strip:
import pandas as pd
mydata = [{'"first_name"': '"Bill"', '"age"': '"7"'},
{'"first_name"': '"Bob"', '"age"': '"8"'},
{'"first_name"': '"Ben"', '"age"': '"9"'}]
df = pd.DataFrame(mydata)
print (df)
"age" "first_name"
0 "7" "Bill"
1 "8" "Bob"
2 "9" "Ben"
df['"first_name"'] = df['"first_name"'].str.strip('"')
print (df)
"age" "first_name"
0 "7" Bill
1 "8" Bob
2 "9" Ben
If need apply function str.strip() to all columns, use:
df = pd.concat([df[col].str.strip('"') for col in df], axis=1)
df.columns = df.columns.str.strip('"')
print (df)
age first_name
0 7 Bill
1 8 Bob
2 9 Ben
Timings:
mydata = [{'"first_name"': '"Bill"', '"age"': '"7"'},
{'"first_name"': '"Bob"', '"age"': '"8"'},
{'"first_name"': '"Ben"', '"age"': '"9"'}]
df = pd.DataFrame(mydata)
df = pd.concat([df]*3, axis=1)
df.columns = ['"first_name1"','"age1"','"first_name2"','"age2"','"first_name3"','"age3"']
#create sample [300000 rows x 6 columns]
df = pd.concat([df]*100000).reset_index(drop=True)
df1,df2 = df.copy(),df.copy()
def a(df):
df.columns = df.columns.str.strip('"')
df['age1'] = df['age1'].str.strip('"')
df['first_name1'] = df['first_name1'].str.strip('"')
df['age2'] = df['age2'].str.strip('"')
df['first_name2'] = df['first_name2'].str.strip('"')
df['age3'] = df['age3'].str.strip('"')
df['first_name3'] = df['first_name3'].str.strip('"')
return df
def b(df):
#apply str function to all columns in dataframe
df = pd.concat([df[col].str.strip('"') for col in df], axis=1)
df.columns = df.columns.str.strip('"')
return df
def c(df):
#apply str function to all columns in dataframe
df = df.applymap(lambda x: x.lstrip('\"').rstrip('\"'))
df.columns = df.columns.str.strip('"')
return df
print (a(df))
print (b(df1))
print (c(df2))
In [135]: %timeit (a(df))
1 loop, best of 3: 635 ms per loop
In [136]: %timeit (b(df1))
1 loop, best of 3: 728 ms per loop
In [137]: %timeit (c(df2))
1 loop, best of 3: 1.21 s per loop
Would this work since you have all the data that you need:
.map(lambda x: x.lstrip('\"').rstrip('\"'))
So simply clean up all the occurrences of " afterwards
EDIT with example:
mydata = [{'"first_name"' : '"bill', 'age': '"75"'},
{'"first_name"' : '"bob', 'age': '"7"'},
{'"first_name"' : '"ben', 'age': '"77"'}]
IN: df = pd.DataFrame(mydata)
OUT:
"first_name" age
0 "bill "75"
1 "bob "7"
2 "ben "77"
IN: df['"first_name"'] = df['"first_name"'].map(lambda x: x.lstrip('\"').rstrip('\"'))
OUT:
0 bill
1 bob
2 ben
Name: "first_name", dtype: object
Use this sequence after selecting the column, it is not ideal but will get the job done:
.map(lambda x: x.lstrip('\"').rstrip('\"'))
You can change the Dtypes after using this pattern:
df['col'].apply(lambda x: pd.to_numeric(x, errors='ignore'))
or simply:
df[['col2','col3']] = df[['col2','col3']].apply(pd.to_numeric)
It depend on your file. Did you check your data if there is comma or not, in cell ? If you have like this e.g Banana : Fruit, Tropical, Eatable, etc. in same cell, you're gonna get this kind of bug. One of basic solution is removing all commas in a file. Or, if you can read it, you can remove special characters :
>>>df
Banana
0 Hello, Salut, Salom
1 Bonjour
>>>df['Banana'] = df['Banana'].str.replace(',','')
>>>df
Banana
0 Hello Salut Salom
1 Bonjour
I have a data.frame in which certain variables contain a text string. I wish to count the number of occurrences of a given character in each individual string.
Example:
q.data<-data.frame(number=1:3, string=c("greatgreat", "magic", "not"))
I wish to create a new column for q.data with the number of occurence of "a" in string (ie. c(2,1,0)).
The only convoluted approach I have managed is:
string.counter<-function(strings, pattern){
counts<-NULL
for(i in 1:length(strings)){
counts[i]<-length(attr(gregexpr(pattern,strings[i])[[1]], "match.length")[attr(gregexpr(pattern,strings[i])[[1]], "match.length")>0])
}
return(counts)
}
string.counter(strings=q.data$string, pattern="a")
number string number.of.a
1 1 greatgreat 2
2 2 magic 1
3 3 not 0
The stringr package provides the str_count function which seems to do what you're interested in
# Load your example data
q.data<-data.frame(number=1:3, string=c("greatgreat", "magic", "not"), stringsAsFactors = F)
library(stringr)
# Count the number of 'a's in each element of string
q.data$number.of.a <- str_count(q.data$string, "a")
q.data
# number string number.of.a
#1 1 greatgreat 2
#2 2 magic 1
#3 3 not 0
If you don't want to leave base R, here's a fairly succinct and expressive possibility:
x <- q.data$string
lengths(regmatches(x, gregexpr("a", x)))
# [1] 2 1 0
nchar(as.character(q.data$string)) -nchar( gsub("a", "", q.data$string))
[1] 2 1 0
Notice that I coerce the factor variable to character, before passing to nchar. The regex functions appear to do that internally.
Here's benchmark results (with a scaled up size of the test to 3000 rows)
q.data<-q.data[rep(1:NROW(q.data), 1000),]
str(q.data)
'data.frame': 3000 obs. of 3 variables:
$ number : int 1 2 3 1 2 3 1 2 3 1 ...
$ string : Factor w/ 3 levels "greatgreat","magic",..: 1 2 3 1 2 3 1 2 3 1 ...
$ number.of.a: int 2 1 0 2 1 0 2 1 0 2 ...
benchmark( Dason = { q.data$number.of.a <- str_count(as.character(q.data$string), "a") },
Tim = {resT <- sapply(as.character(q.data$string), function(x, letter = "a"){
sum(unlist(strsplit(x, split = "")) == letter) }) },
DWin = {resW <- nchar(as.character(q.data$string)) -nchar( gsub("a", "", q.data$string))},
Josh = {x <- sapply(regmatches(q.data$string, gregexpr("g",q.data$string )), length)}, replications=100)
#-----------------------
test replications elapsed relative user.self sys.self user.child sys.child
1 Dason 100 4.173 9.959427 2.985 1.204 0 0
3 DWin 100 0.419 1.000000 0.417 0.003 0 0
4 Josh 100 18.635 44.474940 17.883 0.827 0 0
2 Tim 100 3.705 8.842482 3.646 0.072 0 0
Another good option, using charToRaw:
sum(charToRaw("abc.d.aa") == charToRaw('.'))
The stringi package provides the functions stri_count and stri_count_fixed which are very fast.
stringi::stri_count(q.data$string, fixed = "a")
# [1] 2 1 0
benchmark
Compared to the fastest approach from #42-'s answer and to the equivalent function from the stringr package for a vector with 30.000 elements.
library(microbenchmark)
benchmark <- microbenchmark(
stringi = stringi::stri_count(test.data$string, fixed = "a"),
baseR = nchar(test.data$string) - nchar(gsub("a", "", test.data$string, fixed = TRUE)),
stringr = str_count(test.data$string, "a")
)
autoplot(benchmark)
data
q.data <- data.frame(number=1:3, string=c("greatgreat", "magic", "not"), stringsAsFactors = FALSE)
test.data <- q.data[rep(1:NROW(q.data), 10000),]
A variation of https://stackoverflow.com/a/12430764/589165 is
> nchar(gsub("[^a]", "", q.data$string))
[1] 2 1 0
I'm sure someone can do better, but this works:
sapply(as.character(q.data$string), function(x, letter = "a"){
sum(unlist(strsplit(x, split = "")) == letter)
})
greatgreat magic not
2 1 0
or in a function:
countLetter <- function(charvec, letter){
sapply(charvec, function(x, letter){
sum(unlist(strsplit(x, split = "")) == letter)
}, letter = letter)
}
countLetter(as.character(q.data$string),"a")
You could just use string division
require(roperators)
my_strings <- c('apple', banana', 'pear', 'melon')
my_strings %s/% 'a'
Which will give you 1, 3, 1, 0. You can also use string division with regular expressions and whole words.
The question below has been moved here, but it seems this page doesn't directly answer to Farah El's question.
How to find number 1s in 101 in R
So, I'll write an answer here, just in case.
library(magrittr)
n %>% # n is a number you'd like to inspect
as.character() %>%
str_count(pattern = "1")
https://stackoverflow.com/users/8931457/farah-el
Yet another base R option could be:
lengths(lapply(q.data$string, grepRaw, pattern = "a", all = TRUE, fixed = TRUE))
[1] 2 1 0
The next expression does the job and also works for symbols, not only letters.
The expression works as follows:
1: it uses lapply on the columns of the dataframe q.data to iterate over the rows of the column 2 ("lapply(q.data[,2],"),
2: it apply to each row of the column 2 a function "function(x){sum('a' == strsplit(as.character(x), '')[[1]])}".
The function takes each row value of column 2 (x), convert to character (in case it is a factor for example), and it does the split of the string on every character ("strsplit(as.character(x), '')"). As a result we have a a vector with each character of the string value for each row of the column 2.
3: Each vector value of the vector is compared with the desired character to be counted, in this case "a" (" 'a' == "). This operation will return a vector of True and False values "c(True,False,True,....)", being True when the value in the vector matches the desired character to be counted.
4: The total times the character 'a' appears in the row is calculated as the sum of all the 'True' values in the vector "sum(....)".
5: Then it is applied the "unlist" function to unpack the result of the "lapply" function and assign it to a new column in the dataframe ("q.data$number.of.a<-unlist(....")
q.data$number.of.a<-unlist(lapply(q.data[,2],function(x){sum('a' == strsplit(as.character(x), '')[[1]])}))
>q.data
# number string number.of.a
#1 greatgreat 2
#2 magic 1
#3 not 0
Another base R answer, not so good as those by #IRTFM and #Finn (or as those using stringi/stringr), but better than the others:
sapply(strsplit(q.data$string, split=""), function(x) sum(x %in% "a"))
q.data<-data.frame(number=1:3, string=c("greatgreat", "magic", "not"))
q.data<-q.data[rep(1:NROW(q.data), 3000),]
library(rbenchmark)
library(stringr)
library(stringi)
benchmark( Dason = {str_count(q.data$string, "a") },
Tim = {sapply(q.data$string, function(x, letter = "a"){sum(unlist(strsplit(x, split = "")) == letter) }) },
DWin = {nchar(q.data$string) -nchar( gsub("a", "", q.data$string, fixed=TRUE))},
Markus = {stringi::stri_count(q.data$string, fixed = "a")},
Finn={nchar(gsub("[^a]", "", q.data$string))},
tmmfmnk={lengths(lapply(q.data$string, grepRaw, pattern = "a", all = TRUE, fixed = TRUE))},
Josh1 = {sapply(regmatches(q.data$string, gregexpr("g",q.data$string )), length)},
Josh2 = {lengths(regmatches(q.data$string, gregexpr("g",q.data$string )))},
Iago = {sapply(strsplit(q.data$string, split=""), function(x) sum(x %in% "a"))},
replications =100, order = "elapsed")
test replications elapsed relative user.self sys.self user.child sys.child
4 Markus 100 0.076 1.000 0.076 0.000 0 0
3 DWin 100 0.277 3.645 0.277 0.000 0 0
1 Dason 100 0.290 3.816 0.291 0.000 0 0
5 Finn 100 1.057 13.908 1.057 0.000 0 0
9 Iago 100 3.214 42.289 3.215 0.000 0 0
2 Tim 100 6.000 78.947 6.002 0.000 0 0
6 tmmfmnk 100 6.345 83.487 5.760 0.003 0 0
8 Josh2 100 12.542 165.026 12.545 0.000 0 0
7 Josh1 100 13.288 174.842 13.268 0.028 0 0
The easiest and the cleanest way IMHO is :
q.data$number.of.a <- lengths(gregexpr('a', q.data$string))
# number string number.of.a`
#1 1 greatgreat 2`
#2 2 magic 1`
#3 3 not 0`
s <- "aababacababaaathhhhhslsls jsjsjjsaa ghhaalll"
p <- "a"
s2 <- gsub(p,"",s)
numOcc <- nchar(s) - nchar(s2)
May not be the efficient one but solve my purpose.
I am tryng to build a link between my simulink model or just an m file and my C++ application but I'm having an issue. I don't really understand how matlab receives the data, and for simulink in which form should I send the data to the block? I would like to send coordinates like xyz to matlab and with matlab scatter3 the stream of coordinates in real time. Is it possible ?
Here is the C++ extract code : (sorry comments are in french)
/* Démarrage du listage (mode server) */
sock_err = listen(sock, 5);
printf("Listage du port %d...\n", PORT);
/* Si la socket fonctionne */
if(sock_err != SOCKET_ERROR)
{
/* Attente pendant laquelle le client se connecte */
printf("Patientez pendant que le client se connecte sur le port %d...\n", PORT);
csock = accept(sock, (SOCKADDR*)&csin, &recsize);
printf("Un client se connecte avec la socket %d de %s:%d\n", csock, inet_ntoa(csin.sin_addr), htons(csin.sin_port));
// double buff = 25;
mxArray *datasend;
datasend = mxCreateDoubleMatrix(1, 1, mxREAL);
mlfPrintmatrix(datasend);
sock_err = send(csock, T, 3*sizeof(double), 0);
if(sock_err != SOCKET_ERROR)
printf("Send : %s\n", buffer[0]);
//printf("send : [10 20 30]");
else
printf("Erreur de transmission\n");
/* Il ne faut pas oublier de fermer la connexion (fermée dans les deux sens) */
shutdown(csock, 2);
}
Simulink errors:
Error evaluating registered method 'Outputs' of M-S-Function 'stcpiprb' in 'trajectory2/TCP//IP Receive'. The specified amount of data was not returned within the Timeout period.
Please ensure that data is being sent to the specified port or specify a greater timeout value.
The specified amount of data was not returned within the Timeout period.
Please ensure that data is being sent to the specified port or specify a greater timeout value.
simulink model :
Model {
Name "trajectory2"
Version 7.4
MdlSubVersion 0
GraphicalInterface {
NumRootInports 0
NumRootOutports 0
ParameterArgumentNames ""
ComputedModelVersion "1.3"
NumModelReferences 0
NumTestPointedSignals 0
}
SavedCharacterEncoding "UTF-8"
SaveDefaultBlockParams on
ScopeRefreshTime 0.035000
OverrideScopeRefreshTime on
DisableAllScopes off
DataTypeOverride "UseLocalSettings"
MinMaxOverflowLogging "UseLocalSettings"
MinMaxOverflowArchiveMode "Overwrite"
MaxMDLFileLineLength 120
Created "Tue Feb 23 11:53:02 2010"
Creator "root"
UpdateHistory "UpdateHistoryNever"
ModifiedByFormat "%<Auto>"
LastModifiedBy "root"
ModifiedDateFormat "%<Auto>"
LastModifiedDate "Wed Feb 24 01:01:41 2010"
RTWModifiedTimeStamp 188862533
ModelVersionFormat "1.%<AutoIncrement:3>"
ConfigurationManager "None"
SampleTimeColors off
SampleTimeAnnotations off
LibraryLinkDisplay "none"
WideLines off
ShowLineDimensions off
ShowPortDataTypes off
ShowLoopsOnError on
IgnoreBidirectionalLines off
ShowStorageClass off
ShowTestPointIcons on
ShowSignalResolutionIcons on
ShowViewerIcons on
SortedOrder off
ExecutionContextIcon off
ShowLinearizationAnnotations on
BlockNameDataTip off
BlockParametersDataTip off
BlockDescriptionStringDataTip off
ToolBar on
StatusBar on
BrowserShowLibraryLinks off
BrowserLookUnderMasks off
SimulationMode "normal"
LinearizationMsg "none"
Profile off
ParamWorkspaceSource "MATLABWorkspace"
AccelSystemTargetFile "accel.tlc"
AccelTemplateMakefile "accel_default_tmf"
AccelMakeCommand "make_rtw"
TryForcingSFcnDF off
RecordCoverage off
CovPath "/"
CovSaveName "covdata"
CovMetricSettings "dw"
CovNameIncrementing off
CovHtmlReporting on
CovForceBlockReductionOff on
covSaveCumulativeToWorkspaceVar on
CovSaveSingleToWorkspaceVar on
CovCumulativeVarName "covCumulativeData"
CovCumulativeReport off
CovReportOnPause on
CovModelRefEnable "Off"
CovExternalEMLEnable off
ExtModeBatchMode off
ExtModeEnableFloating on
ExtModeTrigType "manual"
ExtModeTrigMode "normal"
ExtModeTrigPort "1"
ExtModeTrigElement "any"
ExtModeTrigDuration 1000
ExtModeTrigDurationFloating "auto"
ExtModeTrigHoldOff 0
ExtModeTrigDelay 0
ExtModeTrigDirection "rising"
ExtModeTrigLevel 0
ExtModeArchiveMode "off"
ExtModeAutoIncOneShot off
ExtModeIncDirWhenArm off
ExtModeAddSuffixToVar off
ExtModeWriteAllDataToWs off
ExtModeArmWhenConnect on
ExtModeSkipDownloadWhenConnect off
ExtModeLogAll on
ExtModeAutoUpdateStatusClock on
BufferReuse on
ShowModelReferenceBlockVersion off
ShowModelReferenceBlockIO off
Array {
Type "Handle"
Dimension 1
Simulink.ConfigSet {
$ObjectID 1
Version "1.6.0"
Array {
Type "Handle"
Dimension 9
Simulink.SolverCC {
$ObjectID 2
Version "1.6.0"
StartTime "0.0"
StopTime "10.0"
AbsTol "auto"
FixedStep "auto"
InitialStep "auto"
MaxNumMinSteps "-1"
MaxOrder 5
ZcThreshold "auto"
ConsecutiveZCsStepRelTol "10*128*eps"
MaxConsecutiveZCs "1000"
ExtrapolationOrder 4
NumberNewtonIterations 1
MaxStep "auto"
MinStep "auto"
MaxConsecutiveMinStep "1"
RelTol "1e-3"
SolverMode "Auto"
Solver "ode45"
SolverName "ode45"
ShapePreserveControl "DisableAll"
ZeroCrossControl "UseLocalSettings"
ZeroCrossAlgorithm "Nonadaptive"
AlgebraicLoopSolver "TrustRegion"
SolverResetMethod "Fast"
PositivePriorityOrder off
AutoInsertRateTranBlk off
SampleTimeConstraint "Unconstrained"
InsertRTBMode "Whenever possible"
}
Simulink.DataIOCC {
$ObjectID 3
Version "1.6.0"
Decimation "1"
ExternalInput "[t, u]"
FinalStateName "xFinal"
InitialState "xInitial"
LimitDataPoints on
MaxDataPoints "1000"
LoadExternalInput off
LoadInitialState off
SaveFinalState off
SaveCompleteFinalSimState off
SaveFormat "Array"
SaveOutput on
SaveState off
SignalLogging on
InspectSignalLogs off
SaveTime on
ReturnWorkspaceOutputs off
StateSaveName "xout"
TimeSaveName "tout"
OutputSaveName "yout"
SignalLoggingName "logsout"
OutputOption "RefineOutputTimes"
OutputTimes "[]"
ReturnWorkspaceOutputsName "out"
Refine "1"
}
Simulink.OptimizationCC {
$ObjectID 4
Version "1.6.0"
Array {
Type "Cell"
Dimension 7
Cell "BooleansAsBitfields"
Cell "PassReuseOutputArgsAs"
Cell "PassReuseOutputArgsThreshold"
Cell "ZeroExternalMemoryAtStartup"
Cell "ZeroInternalMemoryAtStartup"
Cell "OptimizeModelRefInitCode"
Cell "NoFixptDivByZeroProtection"
PropName "DisabledProps"
}
BlockReduction on
BooleanDataType on
ConditionallyExecuteInputs on
InlineParams off
UseIntDivNetSlope off
InlineInvariantSignals off
OptimizeBlockIOStorage on
BufferReuse on
EnhancedBackFolding off
StrengthReduction off
EnforceIntegerDowncast on
ExpressionFolding on
BooleansAsBitfields off
EnableMemcpy on
MemcpyThreshold 64
PassReuseOutputArgsAs "Structure reference"
ExpressionDepthLimit 2147483647
FoldNonRolledExpr on
LocalBlockOutputs on
RollThreshold 5
SystemCodeInlineAuto off
StateBitsets off
DataBitsets off
UseTempVars off
ZeroExternalMemoryAtStartup on
ZeroInternalMemoryAtStartup on
InitFltsAndDblsToZero off
NoFixptDivByZeroProtection off
EfficientFloat2IntCast off
EfficientMapNaN2IntZero on
OptimizeModelRefInitCode off
LifeSpan "inf"
BufferReusableBoundary on
SimCompilerOptimization "Off"
AccelVerboseBuild off
}
Simulink.DebuggingCC {
$ObjectID 5
Version "1.6.0"
RTPrefix "error"
ConsistencyChecking "none"
ArrayBoundsChecking "none"
SignalInfNanChecking "none"
SignalRangeChecking "none"
ReadBeforeWriteMsg "UseLocalSettings"
WriteAfterWriteMsg "UseLocalSettings"
WriteAfterReadMsg "UseLocalSettings"
AlgebraicLoopMsg "warning"
ArtificialAlgebraicLoopMsg "warning"
SaveWithDisabledLinksMsg "warning"
SaveWithParameterizedLinksMsg "warning"
CheckSSInitialOutputMsg on
UnderspecifiedInitializationDetection "Classic"
MergeDetectMultiDrivingBlocksExec "none"
CheckExecutionContextPreStartOutputMsg off
CheckExecutionContextRuntimeOutputMsg off
SignalResolutionControl "UseLocalSettings"
BlockPriorityViolationMsg "warning"
MinStepSizeMsg "warning"
TimeAdjustmentMsg "none"
MaxConsecutiveZCsMsg "error"
SolverPrmCheckMsg "warning"
InheritedTsInSrcMsg "warning"
DiscreteInheritContinuousMsg "warning"
MultiTaskDSMMsg "error"
MultiTaskCondExecSysMsg "error"
MultiTaskRateTransMsg "error"
SingleTaskRateTransMsg "none"
TasksWithSamePriorityMsg "warning"
SigSpecEnsureSampleTimeMsg "warning"
CheckMatrixSingularityMsg "none"
IntegerOverflowMsg "warning"
Int32ToFloatConvMsg "warning"
ParameterDowncastMsg "error"
ParameterOverflowMsg "error"
ParameterUnderflowMsg "none"
ParameterPrecisionLossMsg "warning"
ParameterTunabilityLossMsg "warning"
FixptConstUnderflowMsg "none"
FixptConstOverflowMsg "none"
FixptConstPrecisionLossMsg "none"
UnderSpecifiedDataTypeMsg "none"
UnnecessaryDatatypeConvMsg "none"
VectorMatrixConversionMsg "none"
InvalidFcnCallConnMsg "error"
FcnCallInpInsideContextMsg "Use local settings"
SignalLabelMismatchMsg "none"
UnconnectedInputMsg "warning"
UnconnectedOutputMsg "warning"
UnconnectedLineMsg "warning"
SFcnCompatibilityMsg "none"
UniqueDataStoreMsg "none"
BusObjectLabelMismatch "warning"
RootOutportRequireBusObject "warning"
AssertControl "UseLocalSettings"
EnableOverflowDetection off
ModelReferenceIOMsg "none"
ModelReferenceVersionMismatchMessage "none"
ModelReferenceIOMismatchMessage "none"
ModelReferenceCSMismatchMessage "none"
UnknownTsInhSupMsg "warning"
ModelReferenceDataLoggingMessage "warning"
ModelReferenceSymbolNameMessage "warning"
ModelReferenceExtraNoncontSigs "error"
StateNameClashWarn "warning"
SimStateInterfaceChecksumMismatchMsg "warning"
StrictBusMsg "Warning"
LoggingUnavailableSignals "error"
BlockIODiagnostic "none"
}
Simulink.HardwareCC {
$ObjectID 6
Version "1.6.0"
ProdBitPerChar 8
ProdBitPerShort 16
ProdBitPerInt 32
ProdBitPerLong 32
ProdIntDivRoundTo "Undefined"
ProdEndianess "Unspecified"
ProdWordSize 32
ProdShiftRightIntArith on
ProdHWDeviceType "32-bit Generic"
TargetBitPerChar 8
TargetBitPerShort 16
TargetBitPerInt 32
TargetBitPerLong 32
TargetShiftRightIntArith on
TargetIntDivRoundTo "Undefined"
TargetEndianess "Unspecified"
TargetWordSize 32
TargetTypeEmulationWarnSuppressLevel 0
TargetPreprocMaxBitsSint 32
TargetPreprocMaxBitsUint 32
TargetHWDeviceType "Specified"
TargetUnknown off
ProdEqTarget on
}
Simulink.ModelReferenceCC {
$ObjectID 7
Version "1.6.0"
UpdateModelReferenceTargets "IfOutOfDateOrStructuralChange"
CheckModelReferenceTargetMessage "error"
ModelReferenceNumInstancesAllowed "Multi"
ModelReferencePassRootInputsByReference on
ModelReferenceMinAlgLoopOccurrences off
}
Simulink.SFSimCC {
$ObjectID 8
Version "1.6.0"
SFSimEnableDebug on
SFSimOverflowDetection on
SFSimEcho on
SimBlas on
SimCtrlC on
SimExtrinsic on
SimIntegrity on
SimUseLocalCustomCode off
SimBuildMode "sf_incremental_build"
}
Simulink.RTWCC {
$BackupClass "Simulink.RTWCC"
$ObjectID 9
Version "1.6.0"
Array {
Type "Cell"
Dimension 6
Cell "IncludeHyperlinkInReport"
Cell "GenerateTraceInfo"
Cell "GenerateTraceReport"
Cell "GenerateTraceReportSl"
Cell "GenerateTraceReportSf"
Cell "GenerateTraceReportEml"
PropName "DisabledProps"
}
SystemTargetFile "grt.tlc"
GenCodeOnly off
MakeCommand "make_rtw"
GenerateMakefile on
TemplateMakefile "grt_default_tmf"
GenerateReport off
SaveLog off
RTWVerbose on
RetainRTWFile off
ProfileTLC off
TLCDebug off
TLCCoverage off
TLCAssert off
ProcessScriptMode "Default"
ConfigurationMode "Optimized"
ConfigAtBuild off
RTWUseLocalCustomCode off
RTWUseSimCustomCode off
IncludeHyperlinkInReport off
LaunchReport off
TargetLang "C"
IncludeBusHierarchyInRTWFileBlockHierarchyMap off
IncludeERTFirstTime off
GenerateTraceInfo off
GenerateTraceReport off
GenerateTraceReportSl off
GenerateTraceReportSf off
GenerateTraceReportEml off
GenerateCodeInfo off
RTWCompilerOptimization "Off"
CheckMdlBeforeBuild "Off"
Array {
Type "Handle"
Dimension 2
Simulink.CodeAppCC {
$ObjectID 10
Version "1.6.0"
Array {
Type "Cell"
Dimension 19
Cell "IgnoreCustomStorageClasses"
Cell "IgnoreTestpoints"
Cell "InsertBlockDesc"
Cell "SFDataObjDesc"
Cell "SimulinkDataObjDesc"
Cell "DefineNamingRule"
Cell "SignalNamingRule"
Cell "ParamNamingRule"
Cell "InlinedPrmAccess"
Cell "CustomSymbolStr"
Cell "CustomSymbolStrGlobalVar"
Cell "CustomSymbolStrType"
Cell "CustomSymbolStrField"
Cell "CustomSymbolStrFcn"
Cell "CustomSymbolStrFcnArg"
Cell "CustomSymbolStrBlkIO"
Cell "CustomSymbolStrTmpVar"
Cell "CustomSymbolStrMacro"
Cell "ReqsInCode"
PropName "DisabledProps"
}
ForceParamTrailComments off
GenerateComments on
IgnoreCustomStorageClasses on
IgnoreTestpoints off
IncHierarchyInIds off
MaxIdLength 31
PreserveName off
PreserveNameWithParent off
ShowEliminatedStatement off
IncAutoGenComments off
SimulinkDataObjDesc off
SFDataObjDesc off
IncDataTypeInIds off
MangleLength 1
CustomSymbolStrGlobalVar "$R$N$M"
CustomSymbolStrType "$N$R$M"
CustomSymbolStrField "$N$M"
CustomSymbolStrFcn "$R$N$M$F"
CustomSymbolStrFcnArg "rt$I$N$M"
CustomSymbolStrBlkIO "rtb_$N$M"
CustomSymbolStrTmpVar "$N$M"
CustomSymbolStrMacro "$R$N$M"
DefineNamingRule "None"
ParamNamingRule "None"
SignalNamingRule "None"
InsertBlockDesc off
SimulinkBlockComments on
EnableCustomComments off
InlinedPrmAccess "Literals"
ReqsInCode off
UseSimReservedNames off
}
Simulink.GRTTargetCC {
$BackupClass "Simulink.TargetCC"
$ObjectID 11
Version "1.6.0"
Array {
Type "Cell"
Dimension 17
Cell "GeneratePreprocessorConditionals"
Cell "IncludeMdlTerminateFcn"
Cell "CombineOutputUpdateFcns"
Cell "SuppressErrorStatus"
Cell "ERTCustomFileBanners"
Cell "GenerateSampleERTMain"
Cell "GenerateTestInterfaces"
Cell "ModelStepFunctionPrototypeControlCompliant"
Cell "CPPClassGenCompliant"
Cell "MultiInstanceERTCode"
Cell "PurelyIntegerCode"
Cell "SupportNonFinite"
Cell "SupportComplex"
Cell "SupportAbsoluteTime"
Cell "SupportContinuousTime"
Cell "SupportNonInlinedSFcns"
Cell "PortableWordSizes"
PropName "DisabledProps"
}
TargetFcnLib "ansi_tfl_table_tmw.mat"
TargetLibSuffix ""
TargetPreCompLibLocation ""
TargetFunctionLibrary "ANSI_C"
UtilityFuncGeneration "Auto"
ERTMultiwordTypeDef "System defined"
ERTMultiwordLength 256
MultiwordLength 2048
GenerateFullHeader on
GenerateSampleERTMain off
GenerateTestInterfaces off
IsPILTarget off
ModelReferenceCompliant on
ParMdlRefBuildCompliant on
CompOptLevelCompliant on
IncludeMdlTerminateFcn on
GeneratePreprocessorConditionals "Disable all"
CombineOutputUpdateFcns off
SuppressErrorStatus off
ERTFirstTimeCompliant off
IncludeFileDelimiter "Auto"
ERTCustomFileBanners off
SupportAbsoluteTime on
LogVarNameModifier "rt_"
MatFileLogging on
MultiInstanceERTCode off
SupportNonFinite on
SupportComplex on
PurelyIntegerCode off
SupportContinuousTime on
SupportNonInlinedSFcns on
SupportVariableSizeSignals off
EnableShiftOperators on
ParenthesesLevel "Nominal"
PortableWordSizes off
ModelStepFunctionPrototypeControlCompliant off
CPPClassGenCompliant off
AutosarCompliant off
UseMalloc off
ExtMode off
ExtModeStaticAlloc off
ExtModeTesting off
ExtModeStaticAllocSize 1000000
ExtModeTransport 0
ExtModeMexFile "ext_comm"
ExtModeIntrfLevel "Level1"
RTWCAPISignals off
RTWCAPIParams off
RTWCAPIStates off
GenerateASAP2 off
}
PropName "Components"
}
}
hdlcoderui.hdlcc {
$ObjectID 12
Version "1.6.0"
Description "HDL Coder custom configuration component"
Name "HDL Coder"
Array {
Type "Cell"
Dimension 1
Cell ""
PropName "HDLConfigFile"
}
HDLCActiveTab "0"
}
PropName "Components"
}
Name "Configuration"
CurrentDlgPage "Solver"
ConfigPrmDlgPosition " [ 280, 135, 1160, 765 ] "
}
PropName "ConfigurationSets"
}
Simulink.ConfigSet {
$PropName "ActiveConfigurationSet"
$ObjectID 1
}
BlockDefaults {
ForegroundColor "black"
BackgroundColor "white"
DropShadow off
NamePlacement "normal"
FontName "Helvetica"
FontSize 10
FontWeight "normal"
FontAngle "normal"
ShowName on
BlockRotation 0
BlockMirror off
}
AnnotationDefaults {
HorizontalAlignment "center"
VerticalAlignment "middle"
ForegroundColor "black"
BackgroundColor "white"
DropShadow off
FontName "Helvetica"
FontSize 10
FontWeight "normal"
FontAngle "normal"
UseDisplayTextAsClickCallback off
}
LineDefaults {
FontName "Helvetica"
FontSize 9
FontWeight "normal"
FontAngle "normal"
}
BlockParameterDefaults {
Block {
BlockType Demux
Outputs "4"
DisplayOption "none"
BusSelectionMode off
}
Block {
BlockType Inport
Port "1"
UseBusObject off
BusObject "BusObject"
BusOutputAsStruct off
PortDimensions "-1"
VarSizeSig "Inherit"
SampleTime "-1"
OutMin "[]"
OutMax "[]"
DataType "auto"
OutDataType "fixdt(1,16,0)"
OutScaling "[]"
OutDataTypeStr "Inherit: auto"
LockScale off
SignalType "auto"
SamplingMode "auto"
LatchByDelayingOutsideSignal off
LatchByCopyingInsideSignal off
Interpolate on
}
Block {
BlockType "S-Function"
FunctionName "system"
SFunctionModules "''"
PortCounts "[]"
SFunctionDeploymentMode off
}
Block {
BlockType SubSystem
ShowPortLabels "FromPortIcon"
Permissions "ReadWrite"
PermitHierarchicalResolution "All"
TreatAsAtomicUnit off
CheckFcnCallInpInsideContextMsg off
SystemSampleTime "-1"
RTWFcnNameOpts "Auto"
RTWFileNameOpts "Auto"
RTWMemSecFuncInitTerm "Inherit from model"
RTWMemSecFuncExecute "Inherit from model"
RTWMemSecDataConstants "Inherit from model"
RTWMemSecDataInternal "Inherit from model"
RTWMemSecDataParameters "Inherit from model"
SimViewingDevice off
DataTypeOverride "UseLocalSettings"
MinMaxOverflowLogging "UseLocalSettings"
}
Block {
BlockType Terminator
}
}
System {
Name "trajectory2"
Location [715, 251, 1295, 511]
Open on
ModelBrowserVisibility off
ModelBrowserWidth 200
ScreenColor "white"
PaperOrientation "landscape"
PaperPositionMode "auto"
PaperType "A4"
PaperUnits "centimeters"
TiledPaperMargins [1.270000, 1.270000, 1.270000, 1.270000]
TiledPageScale 1
ShowPageBoundaries off
ZoomFactor "100"
ReportName "simulink-default.rpt"
SIDHighWatermark 2
Block {
BlockType SubSystem
Name "Embedded\nMATLAB Function"
SID 1
Ports [1]
Position [305, 75, 375, 125]
LibraryVersion "1.30"
PermitHierarchicalResolution "ExplicitOnly"
MinAlgLoopOccurrences off
PropExecContextOutsideSubsystem off
RTWSystemCode "Auto"
FunctionWithSeparateData off
Opaque off
Array {
Type "Handle"
Dimension 0
PropName "AvailSigsLoadSave"
}
RequestExecContextInheritance off
MaskHideContents off
MaskType "Stateflow"
MaskDescription "Embedded MATLAB block"
MaskDisplay "disp('fcn');"
MaskSelfModifiable on
MaskIconFrame on
MaskIconOpaque off
MaskIconRotate "none"
MaskPortRotate "default"
MaskIconUnits "autoscale"
System {
Name "Embedded\nMATLAB Function"
Location [257, 457, 812, 717]
Open off
ModelBrowserVisibility off
ModelBrowserWidth 200
ScreenColor "white"
PaperOrientation "landscape"
PaperPositionMode "auto"
PaperType "A4"
PaperUnits "centimeters"
TiledPaperMargins [1.270000, 1.270000, 1.270000, 1.270000]
TiledPageScale 1
ShowPageBoundaries off
ZoomFactor "100"
SIDHighWatermark 11
SIDPrevWatermark 11
Block {
BlockType Inport
Name "data"
SID 1
Position [20, 101, 40, 119]
IconDisplay "Port number"
OutDataType "sfix(16)"
OutScaling "2^0"
}
Block {
BlockType Demux
Name " Demux "
SID 7
Ports [1, 1]
Position [270, 100, 320, 140]
Outputs "1"
}
Block {
BlockType "S-Function"
Name " SFunction "
SID 6
Tag "Stateflow S-Function trajectory2 2"
Ports [1, 1]
Position [180, 100, 230, 180]
FunctionName "sf_sfun"
PortCounts "[1 1]"
EnableBusSupport on
}
Block {
BlockType Terminator
Name " Terminator "
SID 9
Position [460, 111, 480, 129]
}
Line {
SrcBlock " SFunction "
SrcPort 1
DstBlock " Demux "
DstPort 1
}
Line {
SrcBlock "data"
SrcPort 1
DstBlock " SFunction "
DstPort 1
}
Line {
SrcBlock " Demux "
SrcPort 1
DstBlock " Terminator "
DstPort 1
}
}
}
Block {
BlockType Reference
Name "TCP/IP Receive"
SID 2
Ports [0, 1]
Position [55, 77, 165, 123]
LibraryVersion "1.84"
DialogController "instrumentcreatedialog"
DialogControllerArgs "DataTag0"
SourceBlock "instrumentlib/TCP//IP Receive"
SourceType "TCP/IP Receive"
Host "127.0.0.1"
Port "80"
DataSize "[1 3]"
EnableBlockingMode on
Timeout "10"
SampleTime "0.01"
DataType "double"
ByteOrder "BigEndian"
}
Line {
SrcBlock "TCP/IP Receive"
SrcPort 1
DstBlock "Embedded\nMATLAB Function"
DstPort 1
}
}
}
MatData {
NumRecords 1
DataRecord {
Tag DataTag0
Data " %)30 . : 8 ( 0 % \" $ ! 0 . . 8 ( ! "
" % \" $ ' 0 0 !P '1C<&EP<F( "
}
}
# Finite State Machines
#
# Stateflow Version 7.1 (R2009a) dated Jul 17 2009, 00:35:51
#
#
Stateflow {
machine {
id 1
name "trajectory2"
created "23-Feb-2010 11:53:03"
isLibrary 0
firstTarget 8
sfVersion 71014000.00001
}
chart {
id 2
name "Embedded\nMATLAB Function"
windowPosition [353.175 315 200.25 189.75]
viewLimits [0 156.75 0 153.75]
screen [1 1 1440 900 1.25]
treeNode [0 3 0 0]
firstTransition 5
firstJunction 4
viewObj 2
machine 1
toolbarMode LIBRARY_TOOLBAR
ssIdHighWaterMark 7
decomposition CLUSTER_CHART
type EML_CHART
firstData 6
chartFileNumber 2
disableImplicitCasting 1
eml {
name "fcn"
}
}
state {
id 3
labelString "eML_blk_kernel()"
position [18 64.5 118 66]
fontSize 12
chart 2
treeNode [2 0 0 0]
superState SUBCHART
subviewer 2
ssIdNumber 1
type FUNC_STATE
decomposition CLUSTER_STATE
eml {
isEML 1
script "function fcn(data)\n%#eml\neml.extrinsic('figure','scatter3','grid','hold','axis')\nfigure(1);\n%"
"hold on\n\nscatter3(data(1),data(2),data(3))\n%scatter3(data,10,10)\n%axis on\ngrid"
editorLayout "100 M4x1[205 142 1080 733]"
}
}
junction {
id 4
position [23.5747 49.5747 7]
chart 2
linkNode [2 0 0]
subviewer 2
ssIdNumber 3
type CONNECTIVE_JUNCTION
}
transition {
id 5
labelString "{eML_blk_kernel();}"
labelPosition [32.125 19.875 102.544 14.964]
fontSize 12
src {
intersection [0 0 1 0 23.5747 14.625 0 0]
}
dst {
id 4
intersection [7 0 -1 -1 23.5747 42.5747 0 0]
}
midPoint [23.5747 24.9468]
chart 2
linkNode [2 0 0]
dataLimits [23.575 23.575 14.625 34.575]
subviewer 2
drawStyle SMART
executionOrder 1
ssIdNumber 2
}
data {
id 6
ssIdNumber 4
name "data"
linkNode [2 0 0]
scope INPUT_DATA
machine 1
props {
array {
size "-1"
}
type {
method SF_INHERITED_TYPE
primitive SF_DOUBLE_TYPE
}
complexity SF_COMPLEX_INHERITED
}
dataType "Inherit: Same as Simulink"
}
instance {
id 7
name "Embedded\nMATLAB Function"
machine 1
chart 2
}
target {
id 8
name "sfun"
description "Default Simulink S-Function Target."
machine 1
linkNode [1 0 0]
}
}
I can't see creating socket and binding to it in your C code. Are you sure that you're binding on 127.0.0.1 and port 80? Are you sure that there's no some apache running on the server on port 80?
http://www.linuxhowtos.org/C_C++/socket.htm
Also:
sock_err = send(csock, T, 3*sizeof(double), 0);
I don't also see T in your code, which is probably not the issue, but it doesn't seem to be the datasend pointer to mxArray.