Lining up strings with list object lengths - python-3.x

I've got this function that compares stats that I pull from a txt file, so they are static. I was trying to think of a way to line up the stats of each race/subrace with the names. Here's the source :
def compare():
print('------ Compare Race Stats ------')
comp1 = query()
comp2 = query()
comp1 = stats(comp1[0],comp1[1])
comp2 = stats(comp2[0],comp2[1])
print('{} - {} | {} - {}'
.format(comp1[0][0],comp1[0][1],comp2[0][0],comp2[0][1]))
for i in range(len(comp1[1])):
print('{}{}{}{}'.format(' '*round(len(comp1[0][0])+len(comp1[0][1])/5),comp1[1][i],
' '*round(len(comp2[0][0])+2+len(comp2[0][1])/5),comp2[1][i]))
query() asks what race/subrace you want and returns strings for each. stats() takes race/subrace names, pulls from txt file and returns stats along with the names. The +2 in the second empty space calculation is my accounting for the first print statement (print('{} - {} | {} - {}'), that was a guess. The output doesn't look so bad and I thought the space calculation was kind of clever(I'm a noob) but I couldn't help but wonder what Stack Overflow would have to say. Are there certain accepted ways of lining up various outputs.
Here's some output, there are 10 different race/subraces:
Elezen - Duskwight | Hyur - Midlander
STR : 20 STR : 21
DEX : 20 DEX : 19
VIT : 19 VIT : 20
INT : 23 INT : 21
MND : 20 MND : 18
PIE : 18 PIE : 21
Mi'Qote - Seekers of the Sun | Mi'Qote - Keepers of the Moon
STR : 21 STR : 18
DEX : 22 DEX : 21
VIT : 20 VIT : 17
INT : 18 INT : 19
MND : 19 MND : 23
PIE : 20 PIE : 22

After a little research I found the rjust and ljust str functions:
def compare():
print("------ Compare Race Stats ------")
comp1 = query()
comp2 = query()
comp1 = stats(comp1[0], comp1[1])
comp2 = stats(comp2[0], comp2[1])
print("{} - {} | {} - {}"
.format(comp1[0][0], comp1[0][1], comp2[0][0], comp2[0][1]))
for i in range(len(comp1[1])):
print("{} {} {}".format(comp1[1][i].rjust(len(comp1[0][0]+comp1[0][1])+3),
"|", comp2[1][i]))
Here's the output:
Roegadyn - Hellsguard | Elezen - Duskwight
STR : 20 | STR : 20
DEX : 17 | DEX : 20
VIT : 21 | VIT : 19
INT : 20 | INT : 23
MND : 22 | MND : 20
PIE : 20 | PIE : 18
Mi'Qote - Keepers of the Moon | Roegadyn - Hellsguard
STR : 18 | STR : 20
DEX : 21 | DEX : 17
VIT : 17 | VIT : 21
INT : 19 | INT : 20
MND : 23 | MND : 22
PIE : 22 | PIE : 20
My apologies for asking a question I should have answered myself before posting, the least I can do it give an answer obviously.

Related

When tracing shared library functions with funclatency, no function names were displayed

When using the bcc tool funclatency, there are unknown function names.
It would be helpful if I could track the entry and return values of a number of functions contained in the library ibverbs (Infiniband).
I use funclatency to print a histogram of the ibverbs functions called by perftest.
https://github.com/iovisor/bcc/tree/master/tools
To send packages between two nodes, I use the perftest.
https://github.com/linux-rdma/perftest
To compile the perftest application, I used the following compiler flags:
CFLAGS = -g -Wall -D_GNU_SOURCE -O3 -ggdb3 -O2 -fno-omit-frame-pointer
System:
Distributor ID: Debian
Description: Debian GNU/Linux 11 (bullseye)
Release: 11
Codename: bullseye
I use funclatency like this:
sudo funclatency-bpfcc ibverbs:ibv_get*
funclatency output:
Tracing 13 functions for "ibverbs:ibv_get*"... Hit Ctrl-C to end.
Function = b'[unknown]' [784402]
nsecs : count distribution
0 -> 1 : 0 | |
2 -> 3 : 0 | |
4 -> 7 : 0 | |
8 -> 15 : 0 | |
16 -> 31 : 0 | |
32 -> 63 : 0 | |
64 -> 127 : 0 | |
128 -> 255 : 0 | |
256 -> 511 : 0 | |
512 -> 1023 : 0 | |
1024 -> 2047 : 468 |**************************** |
2048 -> 4095 : 512 |****************************** |
4096 -> 8191 : 664 |****************************************|
8192 -> 16383 : 332 |******************** |
16384 -> 32767 : 14 | |
32768 -> 65535 : 3 | |
65536 -> 131071 : 6 | |
131072 -> 262143 : 0 | |
262144 -> 524287 : 0 | |
524288 -> 1048575 : 0 | |
1048576 -> 2097151 : 0 | |
2097152 -> 4194303 : 0 | |
4194304 -> 8388607 : 0 | |
8388608 -> 16777215 : 1 | |
Here is the source code for the translation of a memory address into a function name:
https://github.com/iovisor/bcc/blob/master/src/python/bcc/init.py
def sym(addr, pid, show_module=False, show_offset=False, demangle=True):
"""sym(addr, pid, show_module=False, show_offset=False)
Translate a memory address into a function name for a pid, which is
returned. When show_module is True, the module name is also included.
When show_offset is True, the instruction offset as a hexadecimal
number is also included in the string.
A pid of less than zero will access the kernel symbol cache.
Example output when both show_module and show_offset are True:
"start_thread+0x202 [libpthread-2.24.so]"
Example output when both show_module and show_offset are False:
"start_thread"
"""
#addr is of type stacktrace_build_id
#so invoke the bsym address resolver
typeofaddr = str(type(addr))
if typeofaddr.find('bpf_stack_build_id') != -1:
sym = bcc_symbol()
b = bcc_stacktrace_build_id()
b.status = addr.status
b.build_id = addr.build_id
b.u.offset = addr.offset
res = lib.bcc_buildsymcache_resolve(BPF._bsymcache,
ct.byref(b),
ct.byref(sym))
if res < 0:
if sym.module and sym.offset:
name,offset,module = (None, sym.offset,
ct.cast(sym.module, ct.c_char_p).value)
else:
name, offset, module = (None, addr, None)
else:
name, offset, module = (sym.name, sym.offset,
ct.cast(sym.module, ct.c_char_p).value)
else:
name, offset, module = BPF._sym_cache(pid).resolve(addr, demangle)
offset = b"+0x%x" % offset if show_offset and name is not None else b""
name = name or b"[unknown]"
name = name + offset
module = b" [%s]" % os.path.basename(module) \
if show_module and module is not None else b""
return name + module
How can I read the function name correctly? It should not just return b'[unknown]'!

mgcv::gam, Error in names(dat) <- object$term : attribut 'names' [2] as to be same length as vector [1]

I want to run a hieratchical GAM in the mgcv package using the gam function. I used the same form of model in brms without problem and I will eventually re-run the same model in brms, but the deadline for an abstract submission in Sunday so I want to try the model in mgcv to have quicker results.
My formula:
f = MDS1 ~ 1 + exposed + s(YEAR,bs = "tp")+ s(LEVEL, bs = "tp") +
t2(YEAR, SITE, bs = c("tp","re")) + s(INTERTIDAL_TRANSECT, bs = "re",
m = 1)
My data:
Classes ‘data.table’ and 'data.frame': 3992 obs. of 9 variables:
$ unique_id : chr "Babb's Cove-1-0-1988" "Babb's Cove-1-0-1989" "Babb's Cove-1-0-1990" "Babb's Cove-1-0-1992" ...
$ MDS1 : num -0.607 -0.607 -0.607 -0.607 -0.607 ...
$ MDS2 : num 0.19 0.19 0.19 0.19 0.19 ...
$ MDS3 : num 0.36 0.36 0.36 0.36 0.36 ...
$ SITE : chr "Babb's Cove" "Babb's Cove" "Babb's Cove" "Babb's Cove" ...
$ INTERTIDAL_TRANSECT: Factor w/ 21 levels "1","2","5","7",..: 1 1 1 1 1 1 1 1 1 1 ...
$ LEVEL : num 0 0 0 0 0 0 0 1 1 1 ...
$ YEAR : num 1988 1989 1990 1992 1994 ...
$ exposed : Factor w/ 2 levels "1","2": 2 2 2 2 2 2 2 2 2 2 ...
- attr(*, ".internal.selfref")=<externalptr>
- attr(*, "sorted")= chr "unique_id"
I have 2 questions:
a)
When I try to fit the model with fit_count <- gam(f, data = count_merge, method = "REML", family = gaussian()) I get :
Error in names(dat) <- object$term :
attribut 'names' [2] doit être de même longueur que le vecteur [1]
I think it's something with the t2() argument of the formula.
b)
I usually run GAM with brms and my formula for that model was :
MDS1 ~ 1 + exposed + s(YEAR,bs = "tp")+ s(LEVEL, bs = "tp") + t2(YEAR, SITE, bs = c("tp","re"), full = T) +(1|r|INTERTIDAL_TRANSECT),
family = gaussian()
Is my way to adapt the formula to mgcv::gam OK?
Q a)
Your SITE vector is a character vector and it is required to be a factor.
Q b)
That looks OK, but you don't need the m = 1 in the s(INTERTIDAL_TRANSECT, bs = "re") term.
You should also use the full = TRUE option on the t2() term if you want the parameterisation to be the same between your {brms} call the {mgcv} one.

Filter in PySpark/Python RDD

I have a list like this:
["Dhoni 35 WC 785623", "Sachin 40 Batsman 4500", "Dravid 45 Batsman 50000", "Kumble 41 Bowler 456431", "Srinath 41 Bowler 65465"]
After applying filter I want like this:
["Dhoni WC", "Sachin Batsman", "Dravid Batsman", "Kumble Bowler", "Srinath Bowler"]
I tried out this way
m = sc.parallelize(["Dhoni 35 WC 785623","Sachin 40 Batsman 4500","Dravid 45 Batsman 50000","Kumble 41 Bowler 456431","Srinath 41 Bowler 65465"])
n = m.map(lambda k:k.split(' '))
o = n.map(lambda s:(s[0]))
o.collect()
['Dhoni', 'Sachin', 'Dravid', 'Kumble', 'Srinath']
q = n.map(lambda s:s[2])
q.collect()
['WC', 'Batsman', 'Batsman', 'Bowler', 'Bowler']
Provided, all your list items are of same format, one way to achieve this is with map.
rdd = sc.parallelize(["Dhoni 35 WC 785623","Sachin 40 Batsman 4500","Dravid 45 Batsman 50000","Kumble 41 Bowler 456431","Srinath 41 Bowler 65465"])
rdd.map(lambda x:(x.split(' ')[0]+' '+x.split(' ')[2])).collect()
Output:
['Dhoni WC', 'Sachin Batsman', 'Dravid Batsman', 'Kumble Bowler', 'Srinath Bowler']

Alloy :Scope of Integers

I'm novice at Alloy (4.2) Sat Solver
I have a problem with the scope of Integers
I want to guarentee that the age of a given person is always more than 18 years
Exemple:
sig Customer {age : Int }
fact f { all c:Customer | c.age > 18 }
pred NewRule { all c:Customer | c.age = 15 }
run NewRule for exactly 1 Customer
The problem is that the Integers in Alloy take only values between [-8,+7]
If I change the fact & mak c.age >0
and change the pred & make c.age =7
so the system is concistant
thinks

Filtering a collection with LINQ to SQL, based on condition that involves other rows [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I am getting a dataset using LINQ to SQL. I need to filter this dataset such that:
If a field with a null SourceName exists and there's at least one other record for this field with a non-null SourceName, then it should be removed.
If it is the only row for that 'Field', then it should remain in the list.
Here's an example data: Data consists of 3 columns: 'Field', 'SourceName' and 'Rate'
Field | SourceName | Rate
10 | s1 | 9
10 | null | null
11 | null | null
11 | s2 | 5
11 | s3 | 4
12 | null | null
13 | null | null
13 | s4 | 7
13 | s5 | 8
8 | s6 | 2
9 | s7 | 23
9 | s8 | 9
9 | s9 | 3
Output should look like:
Field | SourceName | Rate
10 | s1 | 9
11 | s2 | 5
11 | s3 | 4
12 | null | null // <- (remains since there's only
13 | s4 | 7 // 1 record for this 'Field')
13 | s5 | 8
8 | null | null
9 | s8 | 9
9 | s9 | 3
How do I filter it?
What you are trying to achieve is not trivial and can't be solved with just a .Where() clause. Your filter criteria depends on a condition that requires grouping, so you will have to .GroupBy() and then flatten that collection of collections using .SelectMany().
The following code satisfies your expected output using LINQ to Objects, and I don't see any reason for LINQ to SQL not to be able to translate it to SQL, haven't tried that tough.
//Group by the 'Field' field.
yourData.GroupBy(x => x.Field)
//Project the grouping to add a new 'IsUnique' field
.Select(g => new {
SourceAndRate = g,
IsUnique = g.Count() == 1,
})
//Flatten the collection using original items, plus IsUnique
.SelectMany(t => t.SourceAndRate, (t, i) => new {
Field = t.SourceAndRate.Key,
SourceName = i.SourceName,
Rate = i.Rate,
IsUnique = t.IsUnique
})
//Now we can do the business here; filter nulls except unique
.Where(x => x.SourceName != null || x.IsUnique);
Use Linq's built in 'Where' clause with a lambda continuation:
Simple static example of using lambda's and a simple POCO class to store the data in a list like yours:
using System;
using System.Collections.Generic;
using System.Linq;
namespace Simple
{
class Program
{
class Data
{
public string Field { get; set; }
public string SourceName { get; set; }
public string Rate { get; set; }
}
static List<Data> Create()
{
return new List<Data>
{
new Data {Field = "10", SourceName = null, Rate = null},
new Data {Field = "11", SourceName = null, Rate = null},
new Data {Field = "11", SourceName = "s2", Rate = "5"}
};
}
static void Main(string[] args)
{
var ls = Create();
Console.WriteLine("Show me my whole list: \n\n");
// write out everything
ls.ForEach(x => Console.WriteLine(x.Field + "\t" + x.SourceName + "\t" + x.Rate + "\n"));
Console.WriteLine("Show me only non nulls: \n\n");
// exclude some things
ls.Where(l => l.SourceName != null)
.ToList()
.ForEach(x => Console.WriteLine(x.Field + "\t" + x.SourceName + "\t" + x.Rate + "\n"));
Console.ReadLine();
}
}
}

Resources