I'm new to this language and I'm suppose to create a graph, so far I've done very basic structure (nodes). I'd like to assign a different value to each node, this value should be taken from a list (like [1 2 3 4]) and this list should be made automaticly.
I've read this command somewhere else [n-values <number> [self]] But i don't really understand what [self] stands for. What I'd like my program to do is to create n nodes (n is taken from the slider value) and then for each node assign values (1 2 3 4 5...n) respectively.
My code so far:
breed [nodes node] ;;Hacemos 'especies'(Clases) de tortugas, el objeto nodes será de una especie node.
nodes-own [info]
to setup
ca ;clear all shortage
ask patches [set pcolor white] ;;hacemos todas las parcelas blancas
create-nodes num-nodes [ ;creamos tantos nodos como el slider diga
set shape "circle" ;con forma de circulo
setxy random-pxcor random-pycor ;;en cualquier lugar.
]
ask nodes [set info 9] ;;<<<ALL nodes have value 9 I'd like to change this!!!
reset-ticks
end
to layout
layout-spring nodes links .5 .5 .5
end
Thanks in advice!
Also: is there a better way to make a graph? (I'm going to work with flow networks!)
I am not sure why you need n-value <number> self
what N-value does is to repeat the reporter in brackets n times , for example if you :
ask nodes [print n-values info [self]]
each node will print its own name for example (node 1) info times.
best place to start is NetLogo Models Library examples there are plenty examples which use nodes and links for graphs such as Small Worlds, Team Assembly, virus network and ...
http://ccl.northwestern.edu/netlogo/models/
or just from netlogo choose file / Models library
This is your code with a few changes, by adding a list to choose the value of info from, however , if you think info should be assigned to the link not to the node you can add it to link-own
breed [nodes node] ;;Hacemos 'especies'(Clases) de tortugas, el objeto nodes será de una especie node.
nodes-own [info]
globals
[My-Num-List]
links-own [msg]
to setup
ca ;clear all shortage
ask patches [set pcolor white] ;;hacemos todas las parcelas blancas
set My-Num-List [ 1 2 3 4 5 6 7 8 9 10] ; or any other list you need
create-nodes num-of-nodes [ ;creamos tantos nodos como el slider diga
set shape "circle" ;con forma de circulo
setxy random-pxcor random-pycor ;;en cualquier lugar
set label-color black
set info one-of My-Num-List
set label info
]
;;<<<ALL nodes have value 9 I'd like to change this!!!
reset-ticks
end
to layout
crtlinks
layout-spring nodes links .5 .5 .5
end
to crtlinks
ask turtles
[
create-links-with n-of 2 other turtles
[
set msg one-of [ "C" "A" "B"]
set label msg
set label-color black
set thickness 0.2
]
]
Related
How do I extract a specific word after keyword in R.
I have the following input text which contains details about policy. I need to extract specific words value like FirstName , SurName , FatherName and dob.
input.txt
In Case of unit linked plan, Investment risk in Investment Portfolio is borne by the policyholder.
ly
c I ROPOSAL FORM z
Insurance
Proposal Form Number: 342525 PF 42242
Advisor Coe aranch Code 2
Ff roanumber =F SSOS™S™~™S~S rancid ate = |
IBR. Code S535353424
re GFN ——
INSTRUCTION FOR FILLING THES APPLICATION FORM ; 1. Compiets the proocsal form in CAPITAL LETTERS using = Black Ball Point P]n. 2. Sless= mark your selection by marking “X" insides the
Boe. 3. Slnsse bases 2 Blank soece after eect word, letter or initial 4. Slssse write "MA" for questions whic are not apolicatie. 5.00 NOT USE the Sor") to identify your initial or seperate the sddressiiine.
6. Sulmissson of age proof ie mandatory along wall Ge propel fonm.
IMPORTANT INSTRUCTIONS WITH REGARD TO DISCLOSURE OF INFORMATION: Inturance it a contract of UTMOST GOOD FAITH and itis required by disclose all material and nelevant
fach: complebehy, DO) NOT suppress any fac: in response by the questions in the priposal form. FAILURE TO PROVIDE COMPLETE AND ACCURATE INFORMATION OR
MISREPRESENTATION OF THE FACTS COULD DECLARE THES POLICY CONTRACT NULL AND VOID AFTER PAYMENT OF SURRENDER VALUE, IF ANY, SUBJECT TO SECTION 45 OF
INSURANCE ACT, 1998 As AMENDED FROM TIME TO TIME,
Section I - Details of the Life to be Assured
1. Tite E-] Mr. LJ Mrs. LJ Miss [J Or. LJ Others (Specify)
2. FirstName PETER PAUL
3. Surname T
44. Father's Name
46, Mother's Name ERIKA RESWE D
5. Date of Birth 13/02/1990 6, Gender E] Male ] Female
7. Age Proof L] School Certificate [] Driving License [] Passport {Birth Certificate E"] PAN Card
3, Marital Status D) Single EF] Married 0 Widower) 0 Civorcee
9, Spouse Name ERISEWQ FR
10. Maiden Name
iL. Nationality -] Resident Indian National [J Non Resident Indian (MRI) L] Others (Specify)
12, Education J Postgraduate / Doctorate Ee) Graduate [] 12thstd. Pass [J 10thstd. Pass [J Below 10th std.
OO Dliterate / Uneducated CJ Others (Specify)
13. Address For No 7¥%a vaigai street Flower
Communication Nagar selaiyur
Landmark
City Salem
Pin Code BO00 73: State TAMIL NADU
Address proof [] Passport ([] Driving License [] Voter ID [] Bank Statement [] Utility Bill G4 Others (Specify) Aadhaar Card
14, Permanent No 7¥a vaigai street Flower
Address :
Nagar selaiyur
Landmark
City Salem
Pin Code 5353535 state (TAMIL NADU
Address proof CJ] Passport [9 DrivingLicense [J Voter ID [ Bank Statement [ Utility Bill B] Others (Specify) Aadhaar Card
15. Contact Details Mobile 424242424 Phone (Home)
Office / Business
E-mail fdgrgtr13#yahoo.com
Preferred mode: ((] Letter EF) E-Mail
Preferred Language for Letter {other than English): [] Hindi [] Kannada [-] Tamil J Telugu C] Malayalam C) Gujarati
Bengali GOriya =D] Marathi
16. Occupation CL] Salaried-Govt /PSU ( Salaried-other [9 Self Employed Professional [J Aagriculturist {Farmer [Part Time Business
LJ Retired ] Landlord J Student (current Std) -] Others (Specify) Salaried - MNC
17. Full Name of the Capio software
Employers Businnes/
School/College
18, Designation & Exact nature of Work / Business Manager
19. AnnualIncomein 1,200,000.00 20. Annual Income of Husband / Father = 1,500,000.00
Figures (%) (for female and minor lives)
21. Exact nature of work / business of Husband / Father for female and minor lives Government Employee
Page 10fé
The below code works for me but the problem is if line order changes everything get changed. Is there a way to extract keyword value irrespective of line order. ?
Current Code
path <- getwd()
my_txt <- readLines(paste(path, "/input.txt", sep = ""))
fName <- sub('.*FirstName', '', my_txt[7])
SName <- sub('.*Surname', '', my_txt[8])
FatherNm <- sub(".*Father's Name", '', my_txt[9])
dob <- sub("6, Gender.*", '',sub(".*Date of Birth", '', my_txt[11]))
You can combine the text together as one string and extract the values based on pattern in the data. This approach will work irrespective of the line number in the data provided the pattern in the data is always valid for all the files.
my_txt <- readLines(paste(path, "/input.txt", sep = ""))
#Collapse data in one string
text <- paste0(my_txt, collapse = '\n')
#Extract text after FirstName till '\n'
fName <- sub('.*FirstName (.*?)\n.*', '\\1', text)
fName
#[1] "John Woo"
#Extract text after Surname till '\n'
SName <- sub('.*Surname (.*?)\n.*', '\\1', text)
SName
#[1] "T"
#Extract text after Father's Name till '\n'
FatherNm <- sub(".*Father's Name (.*?)\n.*", '\\1', text)
FatherNm
#[1] "Bill Woo"
#Extract numbers which come after Date of Birth.
dob <- sub(".*Date of Birth (\\d+/\\d+/\\d+).*", '\\1', text)
dob
#[1] "13/07/1970"
I have a task to create 4 blinking divs in an Angular project. The colors come from an API in an array with 16 elements and each element is an array with 4 elements (string).
ColorPatterns[
Pattern1["Color1", "Color2", "Color3", "Color4"],
Pattern2["Color1", "Color2", "Color3", "Color4"],
...
Pattern16["Color1", "Color2", "Color3", "Color4"],
]
Color1 is for the first div, Color2 is for the second div and so on.
The sequence of 16 must change per 1 second and after the last element (Pattern16) the sequence should start over: Pattern1 -> Pattern2 -> ... -> Pattern16 -> Pattern1 -> ... .
How should this problem be solved in Angular?
Use an Observable to do the timing stuff. If we can to it for one div then others can be repeated.
Observable.interval(1000) //emit every 1 sec with values = 0 then 1 them 2 ..
.map(value=>ColorPaterns[value%16][0]) // 0 for 1st color
.subscribe((firstColor)=>{
// set 1st div color here
})
I have been tasked to make a figure with two stacked bar charts on the same axis.
While this is generally easy enough, I have run into trouble since the two bar charts do not have a set of common values (like year for instance) that they share in common.
The dataset I am using can be found below:
clear
input str42 outcomes perct str42 highcred hperct
"Certificate & Diploma Only" 8.33 "Certificate & Diploma" 8.33
"Associate Only" 2.93 "Associate" 14.29
"Bachelor Only" 11.36 "Bachelor" 6.93
"Certificate + AA" 2.2 "" .
"Associate + Bachelor" 4.33 "" .
end
My code is the following:
*B. Create a seperate variable for each value of outcomes
levelsof outcomes, local(out)
tokenize "1 2 3 4 5"
foreach level of local out {
gen outcome`1' = .
replace outcome`1' = perct if outcomes=="`level'"
mac shift
}
*C. Create a seperate variable for each value of highgred
levelsof highcred, local(high)
tokenize "1 2 3"
foreach level of local high {
gen highcred`1' = .
replace highcred`1' = hperct if highcred=="`level'"
mac shift
}
//2: Create Bar graphs
*A. Bar 1
graph bar outcome1-outcome5, stack saving(bar1)
*B. Bar 2
graph bar highcred1-highcred3, stack saving(bar2)
*C. Combine graphs
graph combine bar1.gph bar2.gph, ycommon
The ycommon option works as intended. However, your solution for stacking the bars in separate graphs and then combining them is problematic in the sense that the two graphs share the same colors, which makes it impossible to distinguish the different categories. An additional challenge is how these categories can be incorporated in a single legend.
Below you can find a solution that addresses both of these problems:
levelsof outcomes, local(out)
levelsof highcred, local(high)
local highcopy "`high'"
local c1: word count `out'
local c2: word count `high'
local colors1 ebblue pink brown
local colors2 `colors1'
forvalues i = 1 / `= `c1' + `c2'' {
generate outcome`i' = .
gettoken outc out : out
if `i' <= `c1' replace outcome`i' = perct if outcomes == "`outc'"
if `i' > `c1' {
gettoken color colors1 : colors1
local bars1 `bars1' bar(`i', color(`color'))
}
if `i' <= `c2' {
generate highcred`i' = .
gettoken highcc highcopy : highcopy
replace highcred`i' = hperct if highcred == "`highcc'"
gettoken color colors2 : colors2
local bars2 `bars2' bar(`i', color(`color'))
}
if `i' <= `c1' local legend `legend' label(`i' "`outc'")
else {
gettoken highc high : high
local legend `legend' label(`i' "`highc'")
}
}
order outcome* high*
graph bar outcome1-outcome8, stack ///
ylabel(, nogrid) ///
graphregion(color(white)) ///
`bars1' ///
name(bar1, replace) ///
legend(`legend')
graph bar highcred1-highcred3, stack ///
ylabel(, nogrid) ///
yscale(off) ///
graphregion(color(white)) ///
`bars2' ///
name(bar2, replace)
grc1leg bar1 bar2, ycommon graphregion(color(white)) legendfrom(bar1)
Adding the option blabel(bar, position(base)) in each graph bar command will produce:
Note that the community-contributed command grc1leg is used to create the combined graph.
I don't really understand the data. I guess that the order of values is worth preserving, although I don't think your code does that. I suggest that you will be much, much better off with a different data structure, horizontal bars and no stacking. graph bar (asis) is a better idea to avoid nonsense about means in the legend if you have a legend, but you don't need a legend at all.
For this, you would need to install labmask from the Stata Journal (search labmask to get a link).
You should be able to use better text than outcomes highcred.
clear
input str42 outcomes perct str42 highcred hperct
"Certificate & Diploma Only" 8.33 "Certificate & Diploma" 8.33
"Associate Only" 2.93 "Associate" 14.29
"Bachelor Only" 11.36 "Bachelor" 6.93
"Certificate + AA" 2.2 "" .
"Associate + Bachelor" 4.33 "" .
end
rename (outcomes-hperct) (x1 p1 x2 p2)
gen id = _n
reshape long x p , i(id) j(which)
sort which id
replace id = _n
drop in 9/10
labmask id, values(x)
label def which 1 "outcomes" 2 "highcred"
label val which which
graph hbar (asis) p, over(id) over(which) nofill scheme(s1color) ytitle(percent) ///
bar(1, bfcolor(none)) blabel(total, pos(base) format(%3.2f)) yla(none) ysc(alt)
I originally had a jsonL file that I imported line by line and am now trying to get into the Pandas dataframe. One entry looks something like the following:
*[{u'country': u'denmark',
u'gender': u'F',
u'item_type': u'user',
u'location': u'Denmark',
u'name': u'Mona',
u'profile_text': u'',
u'reviews': [{u'company_id': u'stylepit.dk',
u'date': u'2013-10-06T18:54:49.000+00:00',
u'rating': u'4',
u'text': [u'Altid glad for at handle hos Smartkids - stort sortiment af mange m\xe6rker nemt og hurtigt'],
u'title': u'Som altid kommer varerne hurtigt - super fint'},
{u'company_id': u'www.coolshop.dk',
u'date': u'2012-10-28T19:00:56.000+00:00',
u'rating': u'5',
u'text': [u'F\xf8rste gang jeg har handlet hos Coolshop, det var super nemt og hurtigt og de har et fint udvalg, hjemmesiden har flotte fotos af varen s\xe5 jeg var ikke i tvivl om hvad jeg bestilte. Jeg k\xf8ber gerne igen hos Coolshop.',
u'med venlig hilsen',
u'Mona Pedersen Ulstrup'],
u'title': u'Super hurtig ekspedering'},
{u'company_id': u'www.yourkids.dk',
u'date': u'2010-09-26T19:47:51.000+00:00',
u'rating': u'5',
u'text': [u'Har k\xf8bt rigtig mange cars via yourkids, nok den eneste side i Danmark hvor du bare kan f\xe5 alle de sidste nye biler.',
u'Lige sagen for en cars samler. Der er altid rigtig meget service, min bedste anbefaling'],
u'title': u'Super super service'}]*
So, I have a bunch of users that may have one or more reviews as a list of dictionaries. I need to match the list of reviews with each user in pandas. I just did the following:
dataframe = pd.DataFrame(reviews)
sub_data = []
for i in dataframe['reviews']:
for j in i:
sub_data.append(j)
subdata_frame = pd.DataFrame(sub_data)
subdata_frame
Which gives me two individual dataframes which, when concatenated, do not, obviously match the user with a review, but rather does add the new columns to the mutual dataframe, and just adds the extra reviews at the bottom with no user information.
How do I associate the reviews data with my users?
I answered this before over here Creating pandas dataframe from list of dictionaries containing lists of data. However, I've seen similiar questions like this and the past and decided to post a more generalized solution
Typically for nested data types like this, I merge the inner data with the outer. In your case your inner data is reviews, which is something by itself can be represented nicely with a DataFrame.
def fixInnerData(df,innerDataCol,cols = False):
if cols: f = lambda x:pd.DataFrame(x.iloc[0],columns = cols)
else: f = lambda x:pd.DataFrame(x.iloc[0])
fix = df.groupby(level=0)[innerDataCol].apply(f)
fix = fix.reset_index(level=1,drop=True)
df = pd.merge(fix,df.drop([innerDataCol],1),how='inner',left_index=True,right_index=True)
return df
df = pd.DataFrame(data)
innerDataCol = 'reviews'
fixInnerData(df,innerDataCol)
This method is great because you can use it with a loop and pull out all levels of a dictionary
I have a file .txt with 3 columns: ID-polygon-1, ID-polygon-2 and distance.
When I import my file into Netlogo, I obtain 3 lists [[list1][list2][list3]] which corresponds with the 3 columns.
I used table:from-list list to create a table with the content of 3 lists.
I obtain {{table: [[1 1] [67 518] [815 127]]}} (The table displays the first two lines of my dataset).
For example, I would like to get the value of distance (list3) between ID-polygon-1 = 1 (list1) and ID-polygon-2 = 67 (list1), that is, 815.
How can I use table:get table key when I have need of 2 keys (ID-polygon-1 and ID-polygon-2) ?
Thanks very much your help.
Using table:from-list will not help you there: it expects "a list of two element lists, or pairs" where the "the first element in the pair is the key and the second element is the value." That's not what you have in your original list.
Furthermore, NetLogo tables (and associative arrays in general) cannot have two keys. They are always just key-value pairs. Nothing prevents the value from being another table, however, and in your case, that is what you need: a table of tables!
There is no primitive to build that directly, however. You will need to build it yourself:
extensions [ table ]
globals [ t ]
to setup
let lists [
[ 1 1 ] ; ID-polygon-1 column
[ 67 518 ] ; ID-polygon-2 column
[ 815 127 ] ; distance column
]
set t table:make
foreach n-values length first lists [ ? ] [
let id1 item ? (item 0 lists)
let id2 item ? (item 1 lists)
let dist item ? (item 2 lists)
if not table:has-key? t id1 [
table:put t id1 table:make
]
table:put (table:get t id1) id2 dist
]
end
Here is what you get when you print the resulting table:
{{table: [[1 {{table: [[67 815] [518 127]]}}]]}}
And here is a small reporter to make it convenient to get a distance from the table:
to-report get-dist [ id1 id2 ]
report table:get (table:get t id1) id2
end
Using get-dist 1 67 will give the 815 result you were looking for.