问:
Do you make safe and unsafe version of your functions or just stick to the safe version? (Embedded System)
let's say you have a function that set an index and then update few variables based on the value stored in the array element which the index is pointing to. Do you check the index to make sure it is in range? (In embedded system environment to be specific Arduino)
So far I have made a safe and unsafe version for all functions, is that a good idea? In some of my other codes I noticed that having only safe functions result in checking conditions multiple time as the libraries get larger, so I started to develop both. The safe function checks the condition and call the unsafe function as shown in example below for the case explained above.

Safe version:

```<code>bool RcChannelModule::setFactorIndexAndUpdateBoundaries(factorIndex_T factorIndex)
{
    if(factorIndex < N_FACTORS)
    {
        setFactorIndexAndUpdateBoundariesUnsafe(factorIndex);
        return true;
    }

    return false;
}
</code>```

Unsafe version:

```<code>void RcChannelModule::setFactorIndexAndUpdateBoundariesUnsafe(factorIndex_T factorIndex)
{
    setCuurentFactorIndexUnsafe(factorIndex);
    updateOutputBoundaries();
}
</code>```

If I am doing it wrong fundamentally please let me know why and how I could avoid that. Also I would like to know, generally when you program, do you consider the future user to be a fool or you expect them to follow the minimal documentation provided? (the reason I say minimal is because I do not have the time to write a proper documentation)

```<code>void RcChannelModule::setCuurentFactorIndexUnsafe(const factorIndex_T factorIndex)
{
    currentFactorIndex_ = factorIndex;
}
</code>```

答:
Safety checks, such as array index range checks, null checks, and so on, are intended to catch programming errors. When these checks fail, there is no graceful recovery: the best the program can do is to log what happened, and restart.

Therefore, the only time when these checks become useful is during debugging and testing of your code. C++ provides built-in functionality for dealing with this through asserts, which are kept in the debug versions of the code, but compiled out from the release version:

```<code>void RcChannelModule::setFactorIndexAndUpdateBoundariesUnsafe(factorIndex_T factorIndex) {
    assert(factorIndex < N_FACTORS);
    setCuurentFactorIndexUnsafe(factorIndex);
    updateOutputBoundaries();
}
</code>```

Note: [When you make a library for external use] an argument-checking version of each external function perhaps makes sense, with non-argument-checking implementations of those and all internal-only functions. If you perform argument checking then do it (only) at the boundary between your library and the client code. But it's pointless to offer a choice to your users, for if you want to protect them from usage errors then you cannot rely on them to choose the "safe" versions of your functions. (John Bollinger)

Body:
let's say you have a function that set an index and then update few variables based on the value stored in the array element which the index is pointing to. Do you check the index to make sure it is in range? (In embedded system environment to be specific Arduino)
So far I have made a safe and unsafe version for all functions, is that a good idea? In some of my other codes I noticed that having only safe functions result in checking conditions multiple time as the libraries get larger, so I started to develop both. The safe function checks the condition and call the unsafe function as shown in example below for the case explained above.

Safe version:

bool RcChannelModule::setFactorIndexAndUpdateBoundaries(factorIndex_T factorIndex)
{
    if(factorIndex < N_FACTORS)
    {
        setFactorIndexAndUpdateBoundariesUnsafe(factorIndex);
        return true;
    }

    return false;
}

Unsafe version:

void RcChannelModule::setFactorIndexAndUpdateBoundariesUnsafe(factorIndex_T factorIndex)
{
    setCuurentFactorIndexUnsafe(factorIndex);
    updateOutputBoundaries();
}

If I am doing it wrong fundamentally please let me know why and how I could avoid that. Also I would like to know, generally when you program, do you consider the future user to be a fool or you expect them to follow the minimal documentation provided? (the reason I say minimal is because I do not have the time to write a proper documentation)

void RcChannelModule::setCuurentFactorIndexUnsafe(const factorIndex_T factorIndex)
{
    currentFactorIndex_ = factorIndex;
}

Body:
Safety checks, such as array index range checks, null checks, and so on, are intended to catch programming errors. When these checks fail, there is no graceful recovery: the best the program can do is to log what happened, and restart.

Therefore, the only time when these checks become useful is during debugging and testing of your code. C++ provides built-in functionality for dealing with this through asserts, which are kept in the debug versions of the code, but compiled out from the release version:

void RcChannelModule::setFactorIndexAndUpdateBoundariesUnsafe(factorIndex_T factorIndex) {
    assert(factorIndex < N_FACTORS);
    setCuurentFactorIndexUnsafe(factorIndex);
    updateOutputBoundaries();
}

Note: [When you make a library for external use] an argument-checking version of each external function perhaps makes sense, with non-argument-checking implementations of those and all internal-only functions. If you perform argument checking then do it (only) at the boundary between your library and the client code. But it's pointless to offer a choice to your users, for if you want to protect them from usage errors then you cannot rely on them to choose the "safe" versions of your functions. (John Bollinger)


来源: stackexchange

问:
Elegantly iterate over a CoreData relationship in swift?
I've got a ServiceGroup entity with a one-to-many relationship to ServiceItem called items. I want to iterate over the items but swift seems completely ignorant of the variable type because items is just defined as an NSOrderedSet?.

The only way I've found to be able to iterate over my items is that I have to cast them using the new case syntax added to for loops recently, but this seems ridiculous since the code -should- know what the type is already.

Anyone have suggestions so that I don't have to constantly case/coerce my relationship entities?

```<code>if let items = self.items {
    for case let item as ServiceItem in items {
        mins += item.calculateTotalMinutes()
    }
}
</code>```

答:
NSOrderedSet has a property array to get the backing array. As the property returns [Any] you have to cast the type. And for convenience you could use forEach

```<code>if let items = self.items {
    (items.array as! [ServiceItem]).forEach {
        mins += $0.calculateTotalMinutes()
    }
}
</code>```

or reduce

```<code>if let items = self.items {
    mins = (items.array as! [ServiceItem]).reduce(mins, { $0 + $1.calculateTotalMinutes() })
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've got a ServiceGroup entity with a one-to-many relationship to ServiceItem called items. I want to iterate over the items but swift seems completely ignorant of the variable type because items is just defined as an NSOrderedSet?.

The only way I've found to be able to iterate over my items is that I have to cast them using the new case syntax added to for loops recently, but this seems ridiculous since the code -should- know what the type is already.

Anyone have suggestions so that I don't have to constantly case/coerce my relationship entities?

if let items = self.items {
    for case let item as ServiceItem in items {
        mins += item.calculateTotalMinutes()
    }
}

Body:
NSOrderedSet has a property array to get the backing array. As the property returns [Any] you have to cast the type. And for convenience you could use forEach

if let items = self.items {
    (items.array as! [ServiceItem]).forEach {
        mins += $0.calculateTotalMinutes()
    }
}

or reduce

if let items = self.items {
    mins = (items.array as! [ServiceItem]).reduce(mins, { $0 + $1.calculateTotalMinutes() })
}


问:
Missing ) after argument list in jQuery
I'm a complete jQuery noob. I'm grabbing button_types and and div variables but this is giving me the error:

```<code><script>
    $(function(){
      $('div [button_type="'type'"]').addClass('active');
      $('div [image-var="'image'"]').addClass('active');
    });
    </script>
</code>```

I've tried putting the ) in a multitude of locations but I'm guessing there's a bigger issue with my syntax that's causing this.

Probably an easy solution for someone that knows jQuery.

答:
You're missing the + signs with your variables:

```<code>$('div [button_type="' + type + '"]').addClass('active');
$('div [image-var="' + image + '"]').addClass('active');
</code>```

Title: Missing ) after argument list in jQuery

Body:
I'm a complete jQuery noob. I'm grabbing button_types and and div variables but this is giving me the error:

I've tried putting the ) in a multitude of locations but I'm guessing there's a bigger issue with my syntax that's causing this.

Probably an easy solution for someone that knows jQuery.

Body:
You're missing the + signs with your variables:

$('div [button_type="' + type + '"]').addClass('active');
$('div [image-var="' + image + '"]').addClass('active');


问:
How to allow entry in NumericUpDown only via up and down arrow
I have a NumericUpDown  where up and down arrows are there to enter integer. All that is set up but I want to disable entering the value manually by clicking. I want the user to be able to change value only via up and down arrow. can someone guide me how to achieve that.

Currently I have added ValueChanged Event to handle some of the logic. But that event does not get triggered when the value is manualy changed. Please guide me.

答:
This will fire every time someone presses a key when the control has focus.

```<code>Private Sub NumericUpDown1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles NumericUpDown1.KeyPress
    e.Handled = True
End Sub
</code>```

All it does is effectively intercept the keypress, and tell the system that the keypress has been deal twith in your sub, and no further processing of the keypress will happen.

Body:
This will fire every time someone presses a key when the control has focus.

Private Sub NumericUpDown1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles NumericUpDown1.KeyPress
    e.Handled = True
End Sub

All it does is effectively intercept the keypress, and tell the system that the keypress has been deal twith in your sub, and no further processing of the keypress will happen.


答:
```<code>$('div [button_type="'type'"]')
</code>```

As soon as the parser hits the ' before type, it terminates the string.  But then you have it followed by more text which is invalid syntax.  It's not entirely clear if you meant type to be a variable or not, but if so, it would look like

```<code>$('div [button_type="'+ type +'"]')
</code>```

Title: Missing ) after argument list in jQuery

Body:
$('div [button_type="'type'"]')

As soon as the parser hits the ' before type, it terminates the string.  But then you have it followed by more text which is invalid syntax.  It's not entirely clear if you meant type to be a variable or not, but if so, it would look like

$('div [button_type="'+ type +'"]')


问:
Why bother using lambda expressions in logging APIs if the compiler can possibly inline the logging call
Many logging frameworks (e.g., log4j) allow you to pass lambda expressions instead of Strings to the logging API. The argument is that if the string is particularly expressive to construct, the string construction can be lazily executed via the lambda expression. That way, the string is only constructed if the system's log level matches that of the call.

But, given that modern compilers do much method inlining automatically, is there really a point to using lambda expressions in this way? I'll supply a simplified example below to demonstrate this concern.

Suppose our traditional logging method looks like this:

```<code>void log(int level, String message) {
    if (level >= System.logLevel)
        System.out.println(message);
}
// ....
System.logLevel = Level.CRITICAL;
log(Level.FINE, "Very expensive string to construct ..." + etc);
</code>```

Let's suppose that FINE is less than CRITICAL, so, although an expensive string is constructed, it's all for not since the message is not outputted.

Lambda logging APIs help this situation so that the string is only evaluated (constructed) when necessary:

```<code>void log(int level, Supplier<String> message) {
    if (level >= System.logLevel)
        System.out.println(message.apply());
}
// ....
System.logLevel = Level.CRITICAL;
log(Level.FINE, () -> "Very expensive string to construct ..." + etc);
</code>```

But, it's feasible that the compiler can just inline the logging method so that the net effect is as follows:

```<code>System.logLevel = Level.CRITICAL;
if (Level.FINE >= System.logLevel)
    System.out.println("Very expensive string to construct..." + etc);
</code>```

In this case, we don't have to evaluate the string prior to the logging API call (because there is none), and presumably, we would gain performance from just the inlining.

In summary, my question is, how do lambda expressions help us in this situation given that the compiler can possibly inline logging API calls? The only thing I can think of is that, somehow, in the lambda case, the string is not evaluate if the logging level is not a match.

答:
Your optimization hasn't just introduced inlining - it's changed ordering. That's not generally valid.

In particular, it wouldn't be valid to change whether methods are called, unless the JIT can prove that those methods have no other effect. I'd be very surprised if a JIT compiler would inline and reorder to that extent - the cost of checking that all the operations involved in constructing the argument to the method have no side effects is probably not worth the benefit in most cases. (The JIT compiler has no way of treating logging methods differently to other methods.)

So while it's possible for a really, really smart JIT compiler to do this, I'd be very surprised to see any that actually did this. If you find yourself working with one, and write tests to prove that this approach is no more expensive than using lambda expressions, and continue to prove that over time, that's great - but it sounds like you're keener on assuming that's the case, which I definitely wouldn't.

Body:
Many logging frameworks (e.g., log4j) allow you to pass lambda expressions instead of Strings to the logging API. The argument is that if the string is particularly expressive to construct, the string construction can be lazily executed via the lambda expression. That way, the string is only constructed if the system's log level matches that of the call.

But, given that modern compilers do much method inlining automatically, is there really a point to using lambda expressions in this way? I'll supply a simplified example below to demonstrate this concern.

Suppose our traditional logging method looks like this:

void log(int level, String message) {
    if (level >= System.logLevel)
        System.out.println(message);
}
// ....
System.logLevel = Level.CRITICAL;
log(Level.FINE, "Very expensive string to construct ..." + etc);

Let's suppose that FINE is less than CRITICAL, so, although an expensive string is constructed, it's all for not since the message is not outputted.

Lambda logging APIs help this situation so that the string is only evaluated (constructed) when necessary:

void log(int level, Supplier<String> message) {
    if (level >= System.logLevel)
        System.out.println(message.apply());
}
// ....
System.logLevel = Level.CRITICAL;
log(Level.FINE, () -> "Very expensive string to construct ..." + etc);

But, it's feasible that the compiler can just inline the logging method so that the net effect is as follows:

System.logLevel = Level.CRITICAL;
if (Level.FINE >= System.logLevel)
    System.out.println("Very expensive string to construct..." + etc);

In this case, we don't have to evaluate the string prior to the logging API call (because there is none), and presumably, we would gain performance from just the inlining.

In summary, my question is, how do lambda expressions help us in this situation given that the compiler can possibly inline logging API calls? The only thing I can think of is that, somehow, in the lambda case, the string is not evaluate if the logging level is not a match.


问:
Bootstrap fileinput plugin, icons not showing, how to fix that?
enter image description here
I used bootstrap fileinput plugin in my demo, now I can upload Multipartfiles to controller then store then in database, but icons are missing.

```<code><c:set var="contextPath" value="${pageContext.request.contextPath}" />
<link rel="stylesheet" type="text/css"
    href="${contextPath}/js/bootstrap.min.css">
<link rel="stylesheet" type="text/css"
    href="${contextPath}/js/fileinput.min.css">
<link rel="stylesheet" type="text/css"
    href="${contextPath}/js/font-awesome.min.css">
<script src="${contextPath}/js/jquery-3.2.1.min.js"></script>
<script src="${contextPath}/js/bootstrap.min.js"></script>
<script src="${contextPath}/js/fileinput.min.js"></script>
<script type="text/javascript">
    $(function() {
        $("#fileinput1").fileinput({
            uploadUrl : '${contextPath}/user/uploadnotes2',
            showPreview : false,
            maxFilePreviewSize : 30720,
            maxFileCount : 1,
            allowedFileExtensions : [ "rar", "zip", "7z", "jpg", "png", "bmp" ]
        });
        $("#fileinput2").fileinput({
            uploadUrl : '${contextPath}/user/addsample2',
            maxFileCount : 1,
            allowedFileTypes : [ "image" ]
        });
    });
</script>
</code>```

I googled but found no solution yet. Am i missing some .css files? Last time I used summernote the icons int it are missing too, but I imported font-awesome.min.css to fix that. This time in fileinput part, it didn't work.

I am not familiar with front-end skills, please help me. Thank you all.

答:
Still thank the two guys who posted comments. I fixed this by putting all the bootstrap package in my web project (in webapp) . Then import bootstrap.min.css using more detailed path.</p>

```<code><c:set var="contextPath" value="${pageContext.request.contextPath}" />
<link rel="stylesheet" type="text/css"
    href="${contextPath}/js/bootstrap-3.3.7-dist/bootstrap-3.3.7-dist/css/bootstrap.min.css">
</code>```

Body:
enter image description here
I used bootstrap fileinput plugin in my demo, now I can upload Multipartfiles to controller then store then in database, but icons are missing.

<c:set var="contextPath" value="${pageContext.request.contextPath}" />
<link rel="stylesheet" type="text/css"
    href="${contextPath}/js/bootstrap.min.css">
<link rel="stylesheet" type="text/css"
    href="${contextPath}/js/fileinput.min.css">
<link rel="stylesheet" type="text/css"
    href="${contextPath}/js/font-awesome.min.css">

I googled but found no solution yet. Am i missing some .css files? Last time I used summernote the icons int it are missing too, but I imported font-awesome.min.css to fix that. This time in fileinput part, it didn't work.

I am not familiar with front-end skills, please help me. Thank you all.

Body:
Still thank the two guys who posted comments. I fixed this by putting all the bootstrap package in my web project (in webapp) . Then import bootstrap.min.css using more detailed path.

<c:set var="contextPath" value="${pageContext.request.contextPath}" />
<link rel="stylesheet" type="text/css"
    href="${contextPath}/js/bootstrap-3.3.7-dist/bootstrap-3.3.7-dist/css/bootstrap.min.css">


问:
strncpy documentation question
At the following regarding strncpy: http://www.cplusplus.com/reference/clibrary/cstring/strncpy/, it mentions the following:

No null-character is implicitly appended to the end of destination, so destination will only be null-terminated if the length of the C string in source is less than num.

What is meant by this sentence?

答:
The string "foo" has 3 characters + 1 null-terminator (it's stored as "foo\0") giving a total length of 4. If you call strncpy with n=3 (or fewer) it won't append a null-terminator to the end of the target string, but will copy only "foo". Attempting to print the resulting string will result in undefined behaviour due to the lack of a null-terminator which signals the end of the string.

You have to be very careful of this and either pass n one greater than the maximum source or add the null-terminator yourself.

ContentLicense: CC BY-SA 2.5

Title: strncpy documentation question


问:
Plot CDF with GNUPLOT with data not being sorted

Hi I am trying to write a gnuplot script that produced CDF graph for the data produced from another program.

The data looks like this:

```<code>col1    col2    col3    col4    col5
ABCD11  19.8    1.13    129 2
AABC32  14.3    2.32    109 2
AACd12  19.1    0.21    103 2
</code>```

I want to plot CDF for the column 2. The point is that data in the col2 might not be sorted.

To compile the script I use online tool such as here

The script I tried is:

```<code>set output 'out.svg'
set terminal svg size 600,300 enhanced fname 'arial' fsize 10 mousing butt solid
set xlabel "X"
set ylabel "CDF"
set style line 2 lc rgb 'black' lt 1 lw 1
set xtics format "" nomirror rotate by -10 font ", 7"
set ytics nomirror

set grid ytics
set key box height .4 width -1 box right
set nokey
set title "CDF of X"

a=0
#gnuplot 4.4+ functions are now defined as:
#func(variable1,variable2...)=(statement1,statement2,...,return value)
cumulative_sum(x)=(a=a+x,a)
plot "data.txt" using 1:(cumulative_sum($2)) with linespoints lt -1
</code>```

答:
You can use the cumulative smoothing style to get a CDF from data, see help smooth cumulative:

```<code>plot "test.dat" u 2:(1) smooth cumulative w lp
</code>```

Body:
Hi I am trying to write a gnuplot script that produced CDF graph for the data produced from another program.

The data looks like this:

col1    col2    col3    col4    col5
ABCD11  19.8    1.13    129 2
AABC32  14.3    2.32    109 2
AACd12  19.1    0.21    103 2

I want to plot CDF for the column 2. The point is that data in the col2 might not be sorted.

To compile the script I use online tool such as here

The script I tried is:

set output 'out.svg'
set terminal svg size 600,300 enhanced fname 'arial' fsize 10 mousing butt solid
set xlabel "X"
set ylabel "CDF"
set style line 2 lc rgb 'black' lt 1 lw 1
set xtics format "" nomirror rotate by -10 font ", 7"
set ytics nomirror

set grid ytics
set key box height .4 width -1 box right
set nokey
set title "CDF of X"

a=0
#gnuplot 4.4+ functions are now defined as:
#func(variable1,variable2...)=(statement1,statement2,...,return value)
cumulative_sum(x)=(a=a+x,a)
plot "data.txt" using 1:(cumulative_sum($2)) with linespoints lt -1

Body:
You can use the cumulative smoothing style to get a CDF from data, see help smooth cumulative:

plot "test.dat" u 2:(1) smooth cumulative w lp


问:
Unable to source .profile in shell script
To start off, I am a complete noob to Debian, Python, and shell scripts, so please speak to me like I am a toddler.

I have a python script I am running through a virtualenv, and I want to execute it via a shell script. Here is what I'm typing in to the terminal to do so:

source .profile
workon cv
cd Desktop/Camera
python main.py

I tried turning this into a shell script, but I receive the error -- source: not found

I've found no answer to my problem, at least not in any terms I can understand. Any advice would be appreciated. Furthermore, before you answer, I also have no idea why it is I need to execute source .profile, I'm simply following a beginner guide for the project which can be found here: https://www.hackster.io/hackerhouse/smart-security-camera-90d7bd

Thanks in advance, and sorry if this is a dumb question.

答:
Add a hashbang at the top of your script (should be the first line):

```<code>#!/bin/bash
</code>```

This will ensure you are running your shell-script in bash. Having a shell does not mean it's bash. Not all shells have the source function that you are using (bash has it).

Some prefer the following:

```<code>#!/usr/bin/env bash
</code>```

Since you are a "beginner" I think it does not really matter. The first makes sure it's using the bash in /bin, the second is using the PATH variable to find bash, so the user of your script can provide it's own bash if he/she wants.

Body:
Add a hashbang at the top of your script (should be the first line):

#!/bin/bash

This will ensure you are running your shell-script in bash. Having a shell does not mean it's bash. Not all shells have the source function that you are using (bash has it).

Some prefer the following:

#!/usr/bin/env bash

Since you are a "beginner" I think it does not really matter. The first makes sure it's using the bash in /bin, the second is using the PATH variable to find bash, so the user of your script can provide it's own bash if he/she wants.


问:
How to get Number of bits from Hex
For example how do I get 8 from 0x01, or 16 from 0x0001.

I want to know the number of bits a variable has.

```<code>var someNumber = 0x123456;
var len = whatToDoHere(someNumber);
console.log(len); // => 24 for example
</code>```

答: A number is just a number, it does not have any particular representation attached to it. Even if you say that it would be formatted in base16 (as hex) or base256 (bytes), that doesn't say anything about the number of leading zeroes (as in 0x01 vs 0x0001). If you know that however, you'd already know how many digits your formatted number has.

Title: How to get Number of bits from Hex

Body:
For example how do I get 8 from 0x01, or 16 from 0x0001.

I want to know the number of bits a variable has.

var someNumber = 0x123456;
var len = whatToDoHere(someNumber);
console.log(len); // => 24 for example


问:
Leetcode Add Two Numbers Q: how to create a linkedlist from a number?
In this question: https://leetcode.com/problems/add-two-numbers/description/, I've figured out how to get sum of the digits (i.e. 807), but now I need to convert that number into a linked list (e.g. 7 -> 0 -> 8).

How do I create a linkedlist from a number?

Class function for creating a list node:

```<code>function ListNode(val) {
   this.val = val;
   this.next = null;
}
</code>```

Rest of my code:

```<code>var addTwoNumbers = function(l1, l2) {

    function findVal(linkedList) {
          return linkedList.next == null ? linkedList.val.toString() : linkedList.val.toString() + findVal(linkedList.next);

    }

    var l1num = parseInt(findVal(l1).split('').reverse().join(''));
    var l2num = parseInt(findVal(l2).split('').reverse().join(''));
    var sum = l1num + l2num;

// Create linked list from sum
</code>```

答:
Easier with recursion:

f = n => n ? { val: n % 10, next: f(n / 10 | 0) } : null

console.log( f(807) )```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>f = (a, b, c = 0) => a && b && { val: (c += a.val + b.val) % 10,
                                next: f(a.next, b.next, c > 9) } || null

console.log( f( { val: 2, next: { val: 4, next: { val: 3 } } },
                { val: 5, next: { val: 6, next: { val: 4 } } } ) )</code>```

Body:
In this question: https://leetcode.com/problems/add-two-numbers/description/, I've figured out how to get sum of the digits (i.e. 807), but now I need to convert that number into a linked list (e.g. 7 -> 0 -> 8).

How do I create a linkedlist from a number?

Class function for creating a list node:

function ListNode(val) {
   this.val = val;
   this.next = null;
}

Rest of my code:

var addTwoNumbers = function(l1, l2) {

    function findVal(linkedList) {
          return linkedList.next == null ? linkedList.val.toString() : linkedList.val.toString() + findVal(linkedList.next);

    }

    var l1num = parseInt(findVal(l1).split('').reverse().join(''));
    var l2num = parseInt(findVal(l2).split('').reverse().join(''));
    var sum = l1num + l2num;

// Create linked list from sum

Body:
Easier with recursion:

f = n => n ? { val: n % 10, next: f(n / 10 | 0) } : null

console.log( f(807) )

f = (a, b, c = 0) => a && b && { val: (c += a.val + b.val) % 10,
                                next: f(a.next, b.next, c > 9) } || null

console.log( f( { val: 2, next: { val: 4, next: { val: 3 } } },
                { val: 5, next: { val: 6, next: { val: 4 } } } ) )


问:
Could not autowire. No beans of 'MessagingPropertiesRefactor' type not found
I've seen other questions related to this issue but none of them actually helps with my issue.

I have these two properties defined in my test class.

```<code>  @Autowired
  private MessagingProperties messagingProperties;

  @Autowired
  private MessagingPropertiesRefactor messagingPropertiesRefactor;
</code>```

I am trying to create a new version of MessagingProperties.java. I basically copied this class and create a new file MessagingPropertiesRefactor.java (same package/dir) and pasted the same code. I changed the class definition, etc., but for the most part are the same.

I get an IntelliJ design time compiler error stating that "Could not autowire. No beans of 'MessagingPropertiesRefactor' type not found."

I then searched for every single Usage of the original class to double check if it has been declared somewhere but I have found nothing.

I am "new" to Java (and Spring). Has anyone run into the same issue before?

答:
If your new class MessagingPropertiesRefactor is not annotated with @Component you have got to declare it either in beans.xml like this:

```<code><beans>
    <bean name="messagingPropertiesRefactor" class="com.package.path.MessagingPropertiesRefactor"/>
</beans>
</code>```

or in your AppConfig.java like this:

```<code>@Configuration
public class AppConfig {
    @Bean
    public MessagingPropertiesRefactor messagingPropertiesRefactor() {
        return new MessagingPropertiesRefactor();
    }
}
</code>```

Source Reference

Body:
I've seen other questions related to this issue but none of them actually helps with my issue.

I have these two properties defined in my test class.

  @Autowired
  private MessagingProperties messagingProperties;

  @Autowired
  private MessagingPropertiesRefactor messagingPropertiesRefactor;

I am trying to create a new version of MessagingProperties.java. I basically copied this class and create a new file MessagingPropertiesRefactor.java (same package/dir) and pasted the same code. I changed the class definition, etc., but for the most part are the same.

I get an IntelliJ design time compiler error stating that "Could not autowire. No beans of 'MessagingPropertiesRefactor' type not found."

I then searched for every single Usage of the original class to double check if it has been declared somewhere but I have found nothing.

I am "new" to Java (and Spring). Has anyone run into the same issue before?

Body:
If your new class MessagingPropertiesRefactor is not annotated with @Component you have got to declare it either in beans.xml like this:

<beans>
    <bean name="messagingPropertiesRefactor" class="com.package.path.MessagingPropertiesRefactor"/>
</beans>

or in your AppConfig.java like this:

@Configuration
public class AppConfig {
    @Bean
    public MessagingPropertiesRefactor messagingPropertiesRefactor() {
        return new MessagingPropertiesRefactor();
    }
}

Source Reference


问:
read variable value from property block using key value pair using shell script
I am trying to read a environment property in .ini format and get different value for different environment

here is the file look like

```<code>[key_value1 env_value1]
TOMCAT_SERVER=abc
APP_URL_LIST=%TOMCAT_URL%TOMCAT_PORT%/EnterpriseMessaging/
TOMCAT_INSTANCE=ENT-SMS-env_value1
TOMCAT_PORT=8169

[key_value2 env_value2]
TOMCAT_SERVER=xyz
APP_URL_LIST=%TOMCAT_URL2%TOMCAT_PORT%/EnterpriseMessaging/
TOMCAT_INSTANCE=ENT-SMS-env_value2
TOMCAT_PORT=8177
</code>```

I want to read the underline dynamic variables that changed based on key pairs key_value and env_value pairs and read using a bash script

Can you please help??

答:
You can try this

```<code>thekey="value2";sed '/\[key_'"$thekey"'/,/^$/!d;/\[key_'"$thekey"'\|^$/d' infile
</code>```

You can subtitute value2 by valuen if you want to get environment property for valuen.

Body:
I am trying to read a environment property in .ini format and get different value for different environment

here is the file look like

[key_value1 env_value1]
TOMCAT_SERVER=abc
APP_URL_LIST=%TOMCAT_URL%TOMCAT_PORT%/EnterpriseMessaging/
TOMCAT_INSTANCE=ENT-SMS-env_value1
TOMCAT_PORT=8169

[key_value2 env_value2]
TOMCAT_SERVER=xyz
APP_URL_LIST=%TOMCAT_URL2%TOMCAT_PORT%/EnterpriseMessaging/
TOMCAT_INSTANCE=ENT-SMS-env_value2
TOMCAT_PORT=8177

I want to read the underline dynamic variables that changed based on key pairs key_value and env_value pairs and read using a bash script

Can you please help??

Body:
You can try this

thekey="value2";sed '/\[key_'"$thekey"'/,/^$/!d;/\[key_'"$thekey"'\|^$/d' infile

You can subtitute value2 by valuen if you want to get environment property for valuen.


问:
Mongoose .count not working when nested?
Maybe I'm overlooking something but I have a pretty simple setup.  What I'm trying to do is find all 'App' documents in my database and then for each App get the number of User documents associated with that App.

```<code>AppObject.find({}).exec((err, apps) => {
  if (err) {

  } else if (!apps) {

  } else {
    apps.forEach((app, index) => {

      (function (app) {
        console.log('app ID ' + app._id);
        User.find({ appId: app._id }).count((countErr, count) => {
          console.log('COUNT ERR ' + JSON.stringify(countErr));
          console.log('Number of docs: ', count);
          // do more things with the App and the count
        });
      }(app));

    });
  }
});
</code>```

When I look at the console logs, what I'm seeing is the line

```<code>console.log('app ID ' + app._id);
</code>```

correctly prints the app ID, but then

```<code>console.log('Number of docs: ', count);
</code>```

shows up as 0.

When I run the query outside of the forEach loop (and provide the app ID manually) it correctly returns the number of documents.

I'm kind of at a loss, any help is appreciated.

Thanks!

答:
You're running into the easy mistake of assuming lines in NodeJS are executed in order.

Checkout some async articles explaining NodeJS event loop https://blog.risingstack.com/node-hero-async-programming-in-node-js/

What you'll find is the call to the database is returning after the first for loop has completed iterating.

Body:
Maybe I'm overlooking something but I have a pretty simple setup.  What I'm trying to do is find all 'App' documents in my database and then for each App get the number of User documents associated with that App.

AppObject.find({}).exec((err, apps) => {
  if (err) {

  } else if (!apps) {

  } else {
    apps.forEach((app, index) => {

      (function (app) {
        console.log('app ID ' + app._id);
        User.find({ appId: app._id }).count((countErr, count) => {
          console.log('COUNT ERR ' + JSON.stringify(countErr));
          console.log('Number of docs: ', count);
          // do more things with the App and the count
        });
      }(app));

    });
  }
});

When I look at the console logs, what I'm seeing is the line

console.log('app ID ' + app._id);

correctly prints the app ID, but then

console.log('Number of docs: ', count);

shows up as 0.

When I run the query outside of the forEach loop (and provide the app ID manually) it correctly returns the number of documents.

I'm kind of at a loss, any help is appreciated.

Thanks!


问:
What is the clearest font on iphone device (3G/3GS/4)?

what is the font that is rendered perfectly on iphone, in particular 3G that is old...

I need to write text, but my Georgia don't satisfy me.

Some of text are very small, about 8/9 points. Is there a font type that don't pixelate on device?

Any suggestion?

thanks,

A

答:
Just use the system font. I can still read it at 6 point on my iPhone 4. </p>

<p>If you're really serious about this, you can render the fonts yourself using OpenGL. </p>

Body:
Just use the system font. I can still read it at 6 point on my iPhone 4.

If you're really serious about this, you can render the fonts yourself using OpenGL.


问:
How to query for a snapshot by field that had a specific value?
The following query returns changes to Subscription entities whose status field changed within the date range.

```<code> QueryBuilder.byClass(Subscription.class)
             .from(LocalDate.of(2017, 11, 1))
             .to(LocalDate.of(2017, 12, 1))
             .withChangedProperty("status")
</code>```

How can I write a query that finds historical versions of Subscription that had a certain status on a given date? I'm not looking for changes to status, but just want to find the snapshot of the entities who had a particular status on a given date.

Something like:

```<code>javers.findSnapshots(
     QueryBuilder.byClass(Subscription.class)
                 .on(LocalDate.of(2017, 11, 1))
                 .withProperty("status", "TRIAL"))
</code>```

This would return snapshots of Subscription where the status property was equal to TRIAL for the last commit starting from 2017-11-01 backwards.

答: For now, there is no such option, we have the open issue for that, see https://github.com/javers/javers/issues/556</p>

Body:
The following query returns changes to Subscription entities whose status field changed within the date range.

 QueryBuilder.byClass(Subscription.class)
             .from(LocalDate.of(2017, 11, 1))
             .to(LocalDate.of(2017, 12, 1))
             .withChangedProperty("status")

How can I write a query that finds historical versions of Subscription that had a certain status on a given date? I'm not looking for changes to status, but just want to find the snapshot of the entities who had a particular status on a given date.

Something like:

javers.findSnapshots(
     QueryBuilder.byClass(Subscription.class)
                 .on(LocalDate.of(2017, 11, 1))
                 .withProperty("status", "TRIAL"))

This would return snapshots of Subscription where the status property was equal to TRIAL for the last commit starting from 2017-11-01 backwards.


问:
How to send a “multipart/related” with requests in python?
I'm trying to send a multipart/related message using requests in Python. The script seems simple enough, except that requests only seems to allow multipart/form-data messages to be sent, though their documentation does not clearly state this one way or another.

My use case is sending soap with attachments. I can provide a dictionary with the two files whose contents are a test soap-message, and a test document that I'm trying to send. The first contains the soap message with all the instructions, the second is the actual document.

However, if I don't specify a headers value, requests only seems to use multipart/form-data when using the files option. But if I specify headers in an attempt to specify a different multipart type, requests does not seem to add in the mime boundary information.

```<code>url = 'http://10.10.10.90:8020/foo'
headers = {'content-type': 'multipart/related'}
files = {'submission': open('submission_set.xml', 'rb'), 'document': open('document.txt', 'rb')}
response = requests.post(url, data=data, headers=headers)
print response.text
</code>```

Is there a way to get this done using requests? Or is there another tool that I should be looking at?

答:
I'm working with requests and the Google Drive API "Multipart" upload.

The email.mime solution did not work with Google's API, so I dug into the requests source code to see how it implements multipart/form-data bodies.

requests uses the urllib3.filepost.encode_multipart_formdata() helper, which can be wrapped to provide multipart/related:

from urllib3.filepost import encode_multipart_formdata, choose_boundary

def encode_multipart_related(fields, boundary=None):
    if boundary is None:
        boundary = choose_boundary()

    body, _ = encode_multipart_formdata(fields, boundary)
    content_type = str('multipart/related; boundary=%s' % boundary)

    return body, content_type
```

<p>Now we can use <code>encode_multipart_related()</code> to create a <code>(body, content_type)</code> tuple that matches Google's requirements:</p>

<pre class="lang-py prettyprint-override"><code>import json
from urllib3.fields import RequestField

def encode_media_related(metadata, media, media_content_type):
    rf1 = RequestField(
        name='placeholder',
        data=json.dumps(metadata),
        headers={'Content-Type': 'application/json; charset=UTF-8'},
    )
    rf2 = RequestField(
        name='placeholder2',
        data=media,
        headers={'Content-Type': media_content_type},
    )
    return encode_multipart_related([rf1, rf2])
</code>```

Here is a full example that uses our encode_media_related() to upload a hello world file to Google Drive, using the google_auth library.

from google.oauth2 import service_account
import google.auth.transport.requests

credentials = service_account.Credentials.from_service_account_file(
    PATH_TO_SERVICE_FILE,
    scopes=['https://www.googleapis.com/auth/drive.file'],
)
session = google.auth.transport.requests.AuthorizedSession(credentials)

metadata = {
    'mimeType': 'application/vnd.google-apps.document',
    'name': 'Test Upload',
}
body, content_type = encode_media_related(
    metadata,
    '
Hello World!',
    'text/html; charset=UTF-8',
)
resp = session.post(
    'https://www.googleapis.com/upload/drive/v3/files',
    data=body,
    params={'uploadType': 'multipart'},
    headers={'Content-Type': content_type},
)

print 'Uploaded to file with id: %s' % resp.json()['id']
```

Body:
I'm trying to send a multipart/related message using requests in Python. The script seems simple enough, except that requests only seems to allow multipart/form-data messages to be sent, though their documentation does not clearly state this one way or another.

My use case is sending soap with attachments. I can provide a dictionary with the two files whose contents are a test soap-message, and a test document that I'm trying to send. The first contains the soap message with all the instructions, the second is the actual document.

However, if I don't specify a headers value, requests only seems to use multipart/form-data when using the files option. But if I specify headers in an attempt to specify a different multipart type, requests does not seem to add in the mime boundary information.

url = 'http://10.10.10.90:8020/foo'
headers = {'content-type': 'multipart/related'}
files = {'submission': open('submission_set.xml', 'rb'), 'document': open('document.txt', 'rb')}
response = requests.post(url, data=data, headers=headers)
print response.text

Is there a way to get this done using requests? Or is there another tool that I should be looking at?

Body:
I'm working with requests and the Google Drive API "Multipart" upload.

The email.mime solution did not work with Google's API, so I dug into the requests source code to see how it implements multipart/form-data bodies.

requests uses the urllib3.filepost.encode_multipart_formdata() helper, which can be wrapped to provide multipart/related:

from urllib3.filepost import encode_multipart_formdata, choose_boundary

def encode_multipart_related(fields, boundary=None):
    if boundary is None:
        boundary = choose_boundary()

    body, _ = encode_multipart_formdata(fields, boundary)
    content_type = str('multipart/related; boundary=%s' % boundary)

    return body, content_type

Now we can use encode_multipart_related() to create a (body, content_type) tuple that matches Google's requirements:

import json
from urllib3.fields import RequestField

def encode_media_related(metadata, media, media_content_type):
    rf1 = RequestField(
        name='placeholder',
        data=json.dumps(metadata),
        headers={'Content-Type': 'application/json; charset=UTF-8'},
    )
    rf2 = RequestField(
        name='placeholder2',
        data=media,
        headers={'Content-Type': media_content_type},
    )
    return encode_multipart_related([rf1, rf2])

Here is a full example that uses our encode_media_related() to upload a hello world file to Google Drive, using the google_auth library.

from google.oauth2 import service_account
import google.auth.transport.requests

credentials = service_account.Credentials.from_service_account_file(
    PATH_TO_SERVICE_FILE,
    scopes=['https://www.googleapis.com/auth/drive.file'],
)
session = google.auth.transport.requests.AuthorizedSession(credentials)

metadata = {
    'mimeType': 'application/vnd.google-apps.document',
    'name': 'Test Upload',
}
body, content_type = encode_media_related(
    metadata,
    '<html><body><p>Hello World!</body></html>',
    'text/html; charset=UTF-8',
)
resp = session.post(
    'https://www.googleapis.com/upload/drive/v3/files',
    data=body,
    params={'uploadType': 'multipart'},
    headers={'Content-Type': content_type},
)

print 'Uploaded to file with id: %s' % resp.json()['id']


答:
You're missing + when concatenating.  Should be     </p>

```<code>$(function(){
      $('div [button_type="' + type + '"]').addClass('active');
      $('div [image-var="' + image +'"]').addClass('active');
    });
</code>```

Title: Missing ) after argument list in jQuery

Body:
I'm a complete jQuery noob. I'm grabbing button_types and and div variables but this is giving me the error:

I've tried putting the ) in a multitude of locations but I'm guessing there's a bigger issue with my syntax that's causing this.

Probably an easy solution for someone that knows jQuery.

Body:
You're missing + when concatenating.  Should be

$(function(){
      $('div [button_type="' + type + '"]').addClass('active');
      $('div [image-var="' + image +'"]').addClass('active');
    });


问:
Apply a list of n functions to each row of a dataframe?
I have a list of functions

```<code>funs <- list(fn1 = function(x) x^2,
             fn2 = function(x) x^3,
             fn3 = function(x) sin(x),
             fn4 = function(x) x+1)
#in reality these are all f = splinefun()
</code>```

And I have a dataframe:

```<code>mydata <- data.frame(x1 = c(1, 2, 3, 2),
                     x2 = c(3, 2, 1, 0),
                     x3 = c(1, 2, 2, 3),
                     x4 = c(1, 2, 1, 2))
#actually a 500x15 dataframe of 500 samples from 15 parameters
</code>```

For each of i rows, I would like to evaluate function j on each of the j columns and sum the results:

```<code>unlist(funs)
attach(mydata)
a <- rep(NA,4)
for (i in 1:4) {
     a[i] <- sum(fn1(x1[i]), fn2(x2[i]), fn3(x3[i]), fn4(x4[i]))
}
</code>```

How can I do this efficiently? Is this an appropriate occasion to implement plyr functions? If so, how?

bonus question: why is a[4] NA?

Is this an appropriate time to use functions from plyr, if so, how can I do so?

答:
Why don't just write one function for all 4 and apply it to the data frame?
All your functions are vectorized, and so is splinefun, and this will work:

```<code>fun <-  function(df)
    cbind(df[, 1]^2, df[, 2]^3, sin(df[, 3]), df[, 4] + 1)

rowSums(fun(mydata))
</code>```

This is considerably more efficient than "foring" or "applying" over the rows.

Body:
I have a list of functions

funs <- list(fn1 = function(x) x^2,
             fn2 = function(x) x^3,
             fn3 = function(x) sin(x),
             fn4 = function(x) x+1)
#in reality these are all f = splinefun()

And I have a dataframe:

mydata <- data.frame(x1 = c(1, 2, 3, 2),
                     x2 = c(3, 2, 1, 0),
                     x3 = c(1, 2, 2, 3),
                     x4 = c(1, 2, 1, 2))
#actually a 500x15 dataframe of 500 samples from 15 parameters

For each of i rows, I would like to evaluate function j on each of the j columns and sum the results:

unlist(funs)
attach(mydata)
a <- rep(NA,4)
for (i in 1:4) {
     a[i] <- sum(fn1(x1[i]), fn2(x2[i]), fn3(x3[i]), fn4(x4[i]))
}

How can I do this efficiently? Is this an appropriate occasion to implement plyr functions? If so, how?

bonus question: why is a[4] NA?

Is this an appropriate time to use functions from plyr, if so, how can I do so?

Body:
Why don't just write one function for all 4 and apply it to the data frame?
All your functions are vectorized, and so is splinefun, and this will work:

fun <-  function(df)
    cbind(df[, 1]^2, df[, 2]^3, sin(df[, 3]), df[, 4] + 1)

rowSums(fun(mydata))

This is considerably more efficient than "foring" or "applying" over the rows.


问:
Error: memory exhausted (limit reached?) due to outer function

I developed a script where I processed two large arrays (both of thousands of rows), "parent" and "product"

The starting dataset is something like this:

```<code>parent<-sample(1:10000,3500)
product<-sample(1:7500,2500)
mztol<-0.0015
mzdiff<-sample(1:1000,31)
names(mzdiff)<-c("d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9",
             "d10", "d11", "d12", "d13", "d14", "d15", "d16", "d17", "d18",
             "d19", "d20", "d21", "d22", "d23", "d24", "d25",
             "d26","d27,"d28", "d29", "d30",
             "d31")
</code>```

For first I applied the outer function in order to get a matrix of the differences between the two arrays element by element.

```<code>tabdiff<-outer(product,parent,'-')
</code>```

Then I tried to subtract element by element the matrix tabdiff with a vector (mzdiff) in order to evaluate if there are elements <= a value (mztol). I did it by outer function.

```<code>subfun<-function(x,y) abs(x-y)<=mztol
vsubfun<-Vectorize(subfun)
vlogres<-outer(tabdiff,mzdiff,vsubfun)
</code>```

Here I got a vector whose each element is a logical matrix. Then I converted it in a list:

```<code>listres<-alply(vlogres,3,.dims=T)
</code>```

and put in evidence only the TRUE elements and counted them:

```<code>result<-sapply(listres, function(x) table(x)["TRUE"])
</code>```

Well, the point is the script works fine if I elaborate only small parent and product vectors, like:

```<code>parent<-sample(1:1000,150)
product<-sample(1:1500,500)
</code>```

If I consider large ones I got the error message "error: memory exhausted (limit reached?)" when it processes vlogres.
Consider I have a 16 Gb RAM workstation. But it fails anyway.

So how can I optimize this script in order to avoid the error message? Any hint?

答:
The easiest solution I can think of is to iterate through tabdiff as a 1d vector

```<code>tabdiff<-c(outer(product, parent, '-'))
result <- sapply(tabdiff, function(i) sum(abs(i-mzdiff) <= mztol))
</code>```

The sapply statement should perform what you want but you should double check it. This eliminates the task of saving  m * n * p sized data.

Another idea is to think of your problem backwards. You want product - parent values that are within a tolerance threshold (mztol) of each mzdiff. This means that you want product - parent values that are in the range of mzdiff +/- mztol. You can make vectors of upper- and lower-bound values for each mzdiff, and use dplyr::between or the faster data.table::inrange to find which values are in range.

Body:
I developed a script where I processed two large arrays (both of thousands of rows), "parent" and "product"

The starting dataset is something like this:

parent<-sample(1:10000,3500)
product<-sample(1:7500,2500)
mztol<-0.0015
mzdiff<-sample(1:1000,31)
names(mzdiff)<-c("d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9",
             "d10", "d11", "d12", "d13", "d14", "d15", "d16", "d17", "d18",
             "d19", "d20", "d21", "d22", "d23", "d24", "d25",
             "d26","d27,"d28", "d29", "d30",
             "d31")

For first I applied the outer function in order to get a matrix of the differences between the two arrays element by element.

tabdiff<-outer(product,parent,'-')

Then I tried to subtract element by element the matrix tabdiff with a vector (mzdiff) in order to evaluate if there are elements <= a value (mztol). I did it by outer function.

subfun<-function(x,y) abs(x-y)<=mztol
vsubfun<-Vectorize(subfun)
vlogres<-outer(tabdiff,mzdiff,vsubfun)

Here I got a vector whose each element is a logical matrix. Then I converted it in a list:

listres<-alply(vlogres,3,.dims=T)

and put in evidence only the TRUE elements and counted them:

result<-sapply(listres, function(x) table(x)["TRUE"])

Well, the point is the script works fine if I elaborate only small parent and product vectors, like:

parent<-sample(1:1000,150)
product<-sample(1:1500,500)

If I consider large ones I got the error message "error: memory exhausted (limit reached?)" when it processes vlogres.
Consider I have a 16 Gb RAM workstation. But it fails anyway.

So how can I optimize this script in order to avoid the error message? Any hint?

Body:
The easiest solution I can think of is to iterate through tabdiff as a 1d vector

tabdiff<-c(outer(product, parent, '-'))
result <- sapply(tabdiff, function(i) sum(abs(i-mzdiff) <= mztol))

The sapply statement should perform what you want but you should double check it. This eliminates the task of saving  m * n * p sized data.

Another idea is to think of your problem backwards. You want product - parent values that are within a tolerance threshold (mztol) of each mzdiff. This means that you want product - parent values that are in the range of mzdiff +/- mztol. You can make vectors of upper- and lower-bound values for each mzdiff, and use dplyr::between or the faster data.table::inrange to find which values are in range.


问:
Match values to specific field of rows in Dataframe Python
Consider two dataframes:
df 1:

```<code>ID    value1    value2    result
1     50        -50       1111
2     20        -20       2222
3     -75.50    25        3333
</code>```

df 2:

```<code>ID    value3    value4    result
101   20        -20
201   -75.50    25
756   50        -50
</code>```

How can I match the results to the right columns with Python?

Answer is :

```<code>ID    value3    value4    result
101   20        -20       2222
201   -75.50    25        3333
756   50        -50       1111
</code>```

答:
Look into merges
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html</p>

```<code>pd.merge( df1, df2,
          left_on = ["value1","value2"],
          right_on = ["value3","value4"] )
</code>```

Body:
Consider two dataframes:
df 1:

ID    value1    value2    result
1     50        -50       1111
2     20        -20       2222
3     -75.50    25        3333

df 2:

ID    value3    value4    result
101   20        -20
201   -75.50    25
756   50        -50

How can I match the results to the right columns with Python?

Answer is :

ID    value3    value4    result
101   20        -20       2222
201   -75.50    25        3333
756   50        -50       1111

Body:
Look into merges
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html

pd.merge( df1, df2,
          left_on = ["value1","value2"],
          right_on = ["value3","value4"] )


问:
UICollectionView not rendering all rows
I'm trying to create a simple app, where one can enter a number of columns and a number of rows for an UICollectionView. The collection view then calculates the size of possible squares that fit into it and draws them.
I want to allow a maximum of 32 in width and 64 in height. Scrolling is disabled as the whole grid should be shown at once.

For example, 4x8 looks like this

and 8x4 will look like this

So as one can see that works fine. The problems comes with a higher amount of columns and/or rows. Up to 30x8 everything is fine but starting with 31 only 6 of the 8 rows are drawn.

So I don't understand why. Following is the code I use to calculate everything:

Number of section and number of rows:

```<code>func numberOfSections(in collectionView: UICollectionView) -> Int
{
    let num = Int(heightInput.text!)
    if(num != nil)
    {
        if(num! > 64)
        {
            return 64
        }
        return num!
    }
    return 8
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
    let num = Int(widthInput.text!)
    if(num != nil)
    {
        if(num! > 32)
        {
            return 32
        }
        return num!
    }
    return 4
}
</code>```

Cell for item at indexPath

```<code>func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
    let size = calculateCellSize()
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
    var origin = cell.frame.origin
    origin.x = 1+CGFloat(indexPath.row) + size.width*CGFloat(indexPath.row)
    origin.y = 1+CGFloat(indexPath.section) + size.height*CGFloat(indexPath.section)
    cell.frame = CGRect(origin: origin, size: size)
    NSLog("Cell X:%@, Cell Y:%@",origin.x.description,origin.y.description)
    return cell
}
</code>```

The calculate size method

```<code>func calculateCellSize() -> CGSize
{
    //First check if we have valid values
    let col = Int(widthInput.text!)
    let row = Int(heightInput.text!)
    if(col == nil || row == nil)
    {
        return CGSize(width: 48.0, height: 48.0)
    }
    //If there are more or equal amount of columns than rows
    let columns = CGFloat(col!)
    let rows = CGFloat(row!)
    if(columns >= rows)
    {
        //Take the grid width
        let gridWidth = drawCollection.bounds.size.width
        //Calculate the width of the "pixels" that fit the width of the grid
        var pixelWidth = gridWidth/columns
        //Remember to substract the inset from the width
        let drawLayout = drawCollection.collectionViewLayout as? UICollectionViewFlowLayout
        pixelWidth -= (drawLayout?.sectionInset.left)! + 1/columns
        return CGSize(width: pixelWidth, height: pixelWidth)
    }
    else
    {
        //Rows are more than columns
        //Take the grid height as reference here
        let gridHeight = drawCollection.bounds.size.height
        //Calculate the height of the "pixels" that fit the height of the grid
        var pixelHeight = gridHeight/rows
        //Remember to substract the inset from the height
        let drawLayout = drawCollection.collectionViewLayout as? UICollectionViewFlowLayout
        pixelHeight -= (drawLayout?.sectionInset.top)! + 1/rows
        return CGSize(width: pixelHeight, height: pixelHeight)
    }
    return CGSize(width: 48.0, height: 48.0)
}
</code>```

For debugging reasons I put a counter into the cellforItemAtIndexPath method and in fact I can see that the last two rows are not called. The counter ends at 185 but in theory it should have been called 248 times and in fact the difference will show it is 2*32 - 1(for the uneven 31) so the last missing rows....

Several things came to my mind what the reason is but nothing of it seems to be:

the cells are not drawn at the right location (aka outside the grid) -> At least not correct as the method is only called 185 times.

The cells are calculated to be outside the grid therefore not tried to be rendered by the UICollectionView -> Still possible as I couldn't figure how to proof that.

There is a (if so hopefully configurable) maximum amount of elements the UICollectionView can draw and 31x8 already exceeds that number -> Still possible couldn't find anything about that.

So summary:

Is it possible to display all elements in the grid (32x64 max) and if so, what is wrong in my implementation?

Thank you all for your time and answers!

答:
You're doing a whole lot of calculating that you don't need to do. Also, setting the .frame of a cell is a really bad idea. One big point of a collection view is to avoid having to set frames.

Take a look at this:

```<code>class GridCollectionViewController: UIViewController, UICollectionViewDataSource {

    @IBOutlet weak var theCV: UICollectionView!

    var numCols = 0
    var numRows = 0

    func updateCV() -> Void {

        // subtract the number of colums (for the 1-pt spacing between cells), and divide by number of columns
        let w = (theCV.frame.size.width - CGFloat((numCols - 1))) / CGFloat(numCols)

        // subtract the number of rows (for the 1-pt spacing between rows), and divide by number of rows
        let h = (theCV.frame.size.height - CGFloat((numRows - 1))) / CGFloat(numRows)

        // get the smaller of the two values
        let wh = min(w, h)

        // set the cell size
        if let layout = theCV.collectionViewLayout as? UICollectionViewFlowLayout {
            layout.itemSize = CGSize(width: wh, height: wh)
        }

        // reload the collection view
        theCV.reloadData()

    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        // start with a 31x20 grid, just to see it
        numCols = 31
        numRows = 20

        updateCV()
    }

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return numRows
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return numCols
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = theCV.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)

        return cell
    }

    @IBAction func btnTap(_ sender: Any) {
        // example of changing the number of rows/columns based on user action
        numCols = 32
        numRows = 64
        updateCV()
    }

}
</code>```

Title: UICollectionView not rendering all rows

Body:
I'm trying to create a simple app, where one can enter a number of columns and a number of rows for an UICollectionView. The collection view then calculates the size of possible squares that fit into it and draws them.
I want to allow a maximum of 32 in width and 64 in height. Scrolling is disabled as the whole grid should be shown at once.

For example, 4x8 looks like this

and 8x4 will look like this

So as one can see that works fine. The problems comes with a higher amount of columns and/or rows. Up to 30x8 everything is fine but starting with 31 only 6 of the 8 rows are drawn.

So I don't understand why. Following is the code I use to calculate everything:

Number of section and number of rows:

func numberOfSections(in collectionView: UICollectionView) -> Int
{
    let num = Int(heightInput.text!)
    if(num != nil)
    {
        if(num! > 64)
        {
            return 64
        }
        return num!
    }
    return 8
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
    let num = Int(widthInput.text!)
    if(num != nil)
    {
        if(num! > 32)
        {
            return 32
        }
        return num!
    }
    return 4
}

Cell for item at indexPath

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
    let size = calculateCellSize()
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
    var origin = cell.frame.origin
    origin.x = 1+CGFloat(indexPath.row) + size.width*CGFloat(indexPath.row)
    origin.y = 1+CGFloat(indexPath.section) + size.height*CGFloat(indexPath.section)
    cell.frame = CGRect(origin: origin, size: size)
    NSLog("Cell X:%@, Cell Y:%@",origin.x.description,origin.y.description)
    return cell
}

The calculate size method

func calculateCellSize() -> CGSize
{
    //First check if we have valid values
    let col = Int(widthInput.text!)
    let row = Int(heightInput.text!)
    if(col == nil || row == nil)
    {
        return CGSize(width: 48.0, height: 48.0)
    }
    //If there are more or equal amount of columns than rows
    let columns = CGFloat(col!)
    let rows = CGFloat(row!)
    if(columns >= rows)
    {
        //Take the grid width
        let gridWidth = drawCollection.bounds.size.width
        //Calculate the width of the "pixels" that fit the width of the grid
        var pixelWidth = gridWidth/columns
        //Remember to substract the inset from the width
        let drawLayout = drawCollection.collectionViewLayout as? UICollectionViewFlowLayout
        pixelWidth -= (drawLayout?.sectionInset.left)! + 1/columns
        return CGSize(width: pixelWidth, height: pixelWidth)
    }
    else
    {
        //Rows are more than columns
        //Take the grid height as reference here
        let gridHeight = drawCollection.bounds.size.height
        //Calculate the height of the "pixels" that fit the height of the grid
        var pixelHeight = gridHeight/rows
        //Remember to substract the inset from the height
        let drawLayout = drawCollection.collectionViewLayout as? UICollectionViewFlowLayout
        pixelHeight -= (drawLayout?.sectionInset.top)! + 1/rows
        return CGSize(width: pixelHeight, height: pixelHeight)
    }
    return CGSize(width: 48.0, height: 48.0)
}

For debugging reasons I put a counter into the cellforItemAtIndexPath method and in fact I can see that the last two rows are not called. The counter ends at 185 but in theory it should have been called 248 times and in fact the difference will show it is 2*32 - 1(for the uneven 31) so the last missing rows....

Several things came to my mind what the reason is but nothing of it seems to be:

the cells are not drawn at the right location (aka outside the grid) -> At least not correct as the method is only called 185 times.

The cells are calculated to be outside the grid therefore not tried to be rendered by the UICollectionView -> Still possible as I couldn't figure how to proof that.

There is a (if so hopefully configurable) maximum amount of elements the UICollectionView can draw and 31x8 already exceeds that number -> Still possible couldn't find anything about that.

So summary:

Is it possible to display all elements in the grid (32x64 max) and if so, what is wrong in my implementation?

Thank you all for your time and answers!

Body:
You're doing a whole lot of calculating that you don't need to do. Also, setting the .frame of a cell is a really bad idea. One big point of a collection view is to avoid having to set frames.

Take a look at this:

class GridCollectionViewController: UIViewController, UICollectionViewDataSource {

    @IBOutlet weak var theCV: UICollectionView!

    var numCols = 0
    var numRows = 0

    func updateCV() -> Void {

        // subtract the number of colums (for the 1-pt spacing between cells), and divide by number of columns
        let w = (theCV.frame.size.width - CGFloat((numCols - 1))) / CGFloat(numCols)

        // subtract the number of rows (for the 1-pt spacing between rows), and divide by number of rows
        let h = (theCV.frame.size.height - CGFloat((numRows - 1))) / CGFloat(numRows)

        // get the smaller of the two values
        let wh = min(w, h)

        // set the cell size
        if let layout = theCV.collectionViewLayout as? UICollectionViewFlowLayout {
            layout.itemSize = CGSize(width: wh, height: wh)
        }

        // reload the collection view
        theCV.reloadData()

    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        // start with a 31x20 grid, just to see it
        numCols = 31
        numRows = 20

        updateCV()
    }

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return numRows
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return numCols
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = theCV.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)

        return cell
    }

    @IBAction func btnTap(_ sender: Any) {
        // example of changing the number of rows/columns based on user action
        numCols = 32
        numRows = 64
        updateCV()
    }

}


问:
In Pygame, how to give different attributes to a circle in a while loop?
I am creating a NBA simulator similar to Haxball, in which each circle should have a user name and be its own thing so that during the running of the program an indiviual circle could have its own attributes changed e.g a player gets slower but not everyone does.

I have used a few lines in the teams class to create the Player and put them in a team1players list. This does work in creating 5 circles all in different co-ords. However I need the playername attribute (from the Player class) to change for each circle as only certain players play certain positions. I have tried to use self.composition in the for loop but it wont allow me to use a dictionary as an int. I need each player created to be a different playername - with the playername deriving from the composition dictionary containing all positions. So far I have added 1 name (Jose Calderon) to the point guard slot in the composition and I have tried to use the point guard list in the creation of the circle however this results in all players being named Jose Calderon as opposed to just team1players[0] (being the point guard) called Jose.

Below is the section of code I need help with - there is plenty of other flaws but this is a basic prototype:

```<code>self.team1players = []
for i in range(numPlayers):
    self.team1players.append(Player('Ruari', 15, random.randint(0,470),random.randint(0,500), Team1Colour, 0, Team1Name, 0.01, 30))
self.team2players = []#
for i in range(numPlayers):
    self.team2players.append(Player(self.composition['point guard'], 15, random.randint(470,940),random.randint(0,500), Team2Colour, 0, Team2Name, 0.01, 30))
</code>```

Below is the full code as it will probably be needed for anyone to understand what is happening. Its a bit messy at the minute, sorry. :'(

```<code>import pygame
import random
import math
pygame.init()#initialising python

(width, height) = (940,500)#variables for screen
screen = pygame.display.set_mode((width, height)) #sets the screen size as "screen"
pygame.display.set_caption('Basketball Simulator') #sets the title of the window
background_image = pygame.image.load("bballcourt.jpg") #setting the background image as a variable to be used to display on the screen
icon_image = pygame.image.load("basketball-tiny.png") #setting the icon image

numPlayers = 5

class teams():

    def __init__(self, teamname = "unknown", wins = "0", losses = "0", team1player = "unknown", team2player ="unknown", colour = "255,255,255"):
        #above I have created all the attributes of teams
        self.teamname = teamname #sets teamname
        self.composition = {
            'point guard' : [],
            'shooting guard': [],
            'small forward': [],
            'power forward': [],
            'centre': []
        }
        self.wins = wins #number of wins
        self.losses = losses #number of losses
        self.team1player = team1player #holds a player and can be used to create players I have made this here so that the players are a part of the team
        self.team2player = team2player

        self.colour = colour #holds the rgb colour specific to the team

    def startTeam(self):
        validTeamChoice1 = False #creating a while loop to only allow valid inputs for the first team choice
        validTeamChoice2 = False #loop for second team choice
        userChoice1 = " "
        Team1Colour = userChoice1
        Team1Name = " "
        userChoice2 = " "
        Team2Colour = userChoice2
        Team2Name = " "
        while validTeamChoice1 == False:
            userChoice1 = self.teamname = input("Please select a team // GSW or CAVS: ") #allowing user input
            if userChoice1.upper() == "GSW":
                userChoice1 = self.teamname = ("Golden State Warriors")
                Team1Colour = self.colour = (0,107,182) #rgb colour for GSW yellow
                Team1Name = self.teamname
                if userChoice1 == self.teamname:
                    validTeamChoice1 = True
            else:
                validTeamChoice1 = False #continues loop
        while validTeamChoice2 == False:
            userChoice2 = self.teamname = input("Please select an opposing team // GSW or CAVS: ")
            if userChoice2.upper() == "CAVS":
                userChoice2 = self.teamname = ("Cleveland Cavaliers")
                Team2Colour = self.colour = (134,0,56) #rgb colour for CAVS red
                Team2Name = self.teamname
                self.composition['point guard'].append('Jose Calderon')
                if userChoice2 == self.teamname:
                    validTeamChoice2 = True
            else:
                validTeamChoice2 = False

        self.team1players = []
        for i in range(numPlayers):
            self.team1players.append(Player('Ruari', 15, random.randint(0,470),random.randint(0,500), Team1Colour, 0, Team1Name, 0.01, 30))
        self.team2players = []#
        for i in range(numPlayers):
            self.team2players.append(Player(self.composition['point guard'], 15, random.randint(470,940),random.randint(0,500), Team2Colour, 0, Team2Name, 0.01, 30))
    def displayPlayers(self): #displays the player using the player attributes and the display method from the Player class
        for n in range(numPlayers):
            self.team1players[n].displayCircle()
            self.team2players[n].displayCircle()
    def printPlayers(self):
        print(self.team2players[1].playername)

class Player(): #the player class holds information on the player symbol
    def __init__(self, playername, size, x, y, colour, thickness,teamname,speed, angle): #teamname is predetermined
        self.playername = playername
        self.size = size #size is a unit for the radius
        self.x = x #x, y are position on the court
        self.y = y
        self.speed = speed
        self.angle = angle
        self.colour = colour
        self.thickness = 0 #thickness is set to 0

    def displayCircle(self): #drawing the circle onto the screen using colour, co-ordinates and radii
            pygame.draw.circle(screen, self.colour, (self.x, self.y), self.size, self.thickness)

pygame.display.set_icon(icon_image)
screen.blit(background_image, [0,0]) #this sets the background court image (note: its outside all the classes)
myTeam1 = teams() #creates a myTeam1 object from the teams class
myTeam1.startTeam() #runs the startTeam method from the teams class
myTeam1.displayPlayers() #runs the displayPlayers method from the teams
pygame.display.flip() #updates the screen based on current events ("flip" is the same as "update()")
myTeam1.printPlayers()
#the below code monitors current on screen events should they be needed for movement etc. it also allows the window to be closed.
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
            pygame.quit()
            quit
</code>```

Any help is appreciated!

EDIT Below I have made it so that the relevant players are appended to their positions after the user has selected a team (each team has diff. players) and I have also created a new composition attribute in the teams class - now there's team1composition and team2composition so that both teams have a different point guard, shooting guard etc.   Is there a more efficient way? At first I planned to have both teams players in lists in the dictionary and I would use the array to select which player is for which team however I believe this is better?

```<code>class teams():

    def __init__(self, teamname = "unknown", wins = "0", losses = "0", team1player = "unknown", team2player ="unknown", colour = "255,255,255"):
        #above I have created all the attributes of teams
        self.teamname = teamname #sets teamname
        self.team1composition = {
            'point guard' : [],
            'shooting guard': [],
            'small forward': [],
            'power forward': [],
            'centre': []
        }
        self.team2composition = {
            'point guard' : [],
            'shooting guard': [],
            'small forward': [],
            'power forward': [],
            'centre': []
        }
        self.wins = wins #number of wins
        self.losses = losses #number of losses
        self.team1player = team1player #holds a player and can be used to create players I have made this here so that the players are a part of the team
        self.team2player = team2player

        self.colour = colour #holds the rgb colour specific to the team

    def startTeam(self):
        validTeamChoice1 = False #creating a while loop to only allow valid inputs for the first team choice
        validTeamChoice2 = False #loop for second team choice
        userChoice1 = " "
        Team1Colour = userChoice1
        Team1Name = " "
        userChoice2 = " "
        Team2Colour = userChoice2
        Team2Name = " "
        while validTeamChoice1 == False:
            userChoice1 = self.teamname = input("Please select a team // GSW or CAVS: ") #allowing user input
            if userChoice1.upper() == "GSW":
                userChoice1 = self.teamname = ("Golden State Warriors")
                Team1Colour = self.colour = (0,107,182) #rgb colour for GSW yellow
                Team1Name = self.teamname
                if userChoice1 == self.teamname:
                    validTeamChoice1 = True
            else:
                validTeamChoice1 = False #continues loop
        while validTeamChoice2 == False:
            userChoice2 = self.teamname = input("Please select an opposing team // GSW or CAVS: ")
            if userChoice2.upper() == "CAVS":
                userChoice2 = self.teamname = ("Cleveland Cavaliers")
                Team2Colour = self.colour = (134,0,56) #rgb colour for CAVS red
                Team2Name = self.teamname
                self.team2composition['point guard'].append('Jose Calderon')
                self.team2composition['shooting guard'].append('J.R Smith')
                self.team2composition['small forward'].append('LeBron James')
                self.team2composition['power forward'].append('Jae Crowder')
                self.team2composition['centre'].append('Kevin Love')
                if userChoice2 == self.teamname:
                    validTeamChoice2 = True
            else:
                validTeamChoice2 = False

        self.team1players = []
        for position , name in self.team1composition.items():
            print (position, name)
            self.team1players.append(Player(name, 15, random.randint(0,470),random.randint(0,500), Team1Colour, 0, Team1Name, 0.01, 30))
        self.team2players = []#
        for position, name in self.team2composition.items():
            print(position , name)
            self.team2players.append(Player(name, 15, random.randint(470,940),random.randint(0,500)
</code>```

When the code is now ran here is the result (not the Pygame window)...

```<code>Please select a team // GSW or CAVS: gsw
Please select an opposing team // GSW or CAVS: cavs
point guard []
shooting guard []
small forward []
power forward []
centre []
point guard ['Jose Calderon']
shooting guard ['J.R Smith']
small forward ['LeBron James']
power forward ['Jae Crowder']
centre ['Kevin Love']
</code>```

答:
Instead of

```<code>for i in range(numPlayers):
    self.team2players.append(Player(self.composition['point guard'], ...))
</code>```

you can use for with dictionary

```<code>self.team2players = []#

for position, name in self.composition.items():
    #print(position, name)
    self.team2players.append(Player(name, ...))
</code>```

BTW:

Because you have only one player in self.composition

so it will create only one player in self.team2players.

Dictionary doesn't keep order so when you will have more players in self.composition

then for ... in self.composition may create players in different order.

EDIT:

When I look at Player(self.composition['point guard'], then it seems you have only one string assigned to self.composition['point guard'] and previous code should works,

but when I look on your dictionary it seems you have list with many names assigned to self.composition['point guard']:

```<code>    self.composition = {
        'point guard' : [],
        'shooting guard': [],
        'small forward': [],
        'power forward': [],
        'centre': []
    }
</code>```

and it means you need two for loops

```<code>self.team2players = []#

for position, names_list in self.composition.items():
    #print(position, names_list)
    for name in names_list:
        #print(name)
        self.team2players.append(Player(name, ...))
</code>```

EDIT:

If you will keep only one name for every position then you don't need list   but you can use string with name or empty string (or None) if there is no name.

```<code>self.composition = {
    'point guard' : None,
    'shooting guard': None,
    'small forward': None,
    'power forward': None,
    'centre': None
}
</code>```

and you assign name without append()

```<code>self.composition['point guard'] = 'Jose Calderon'
</code>```

and to create player you need use if to check None

```<code>self.team2players = []

for position, name in self.composition.items():
    if name: # the same as `if (name is not None) and (name != "") and (name != 0) and (name != False) ...:
        self.team2players.append(Player(name, ...))
    #else:
    #   print("you don't have player on position", position)
</code>```

Body:
I am creating a NBA simulator similar to Haxball, in which each circle should have a user name and be its own thing so that during the running of the program an indiviual circle could have its own attributes changed e.g a player gets slower but not everyone does.

I have used a few lines in the teams class to create the Player and put them in a team1players list. This does work in creating 5 circles all in different co-ords. However I need the playername attribute (from the Player class) to change for each circle as only certain players play certain positions. I have tried to use self.composition in the for loop but it wont allow me to use a dictionary as an int. I need each player created to be a different playername - with the playername deriving from the composition dictionary containing all positions. So far I have added 1 name (Jose Calderon) to the point guard slot in the composition and I have tried to use the point guard list in the creation of the circle however this results in all players being named Jose Calderon as opposed to just team1players[0] (being the point guard) called Jose.

Below is the section of code I need help with - there is plenty of other flaws but this is a basic prototype:

self.team1players = []
for i in range(numPlayers):
    self.team1players.append(Player('Ruari', 15, random.randint(0,470),random.randint(0,500), Team1Colour, 0, Team1Name, 0.01, 30))
self.team2players = []#
for i in range(numPlayers):
    self.team2players.append(Player(self.composition['point guard'], 15, random.randint(470,940),random.randint(0,500), Team2Colour, 0, Team2Name, 0.01, 30))

Below is the full code as it will probably be needed for anyone to understand what is happening. Its a bit messy at the minute, sorry. :'(

import pygame
import random
import math
pygame.init()#initialising python

(width, height) = (940,500)#variables for screen
screen = pygame.display.set_mode((width, height)) #sets the screen size as "screen"
pygame.display.set_caption('Basketball Simulator') #sets the title of the window
background_image = pygame.image.load("bballcourt.jpg") #setting the background image as a variable to be used to display on the screen
icon_image = pygame.image.load("basketball-tiny.png") #setting the icon image

numPlayers = 5

class teams():

    def __init__(self, teamname = "unknown", wins = "0", losses = "0", team1player = "unknown", team2player ="unknown", colour = "255,255,255"):
        #above I have created all the attributes of teams
        self.teamname = teamname #sets teamname
        self.composition = {
            'point guard' : [],
            'shooting guard': [],
            'small forward': [],
            'power forward': [],
            'centre': []
        }
        self.wins = wins #number of wins
        self.losses = losses #number of losses
        self.team1player = team1player #holds a player and can be used to create players I have made this here so that the players are a part of the team
        self.team2player = team2player

        self.colour = colour #holds the rgb colour specific to the team

    def startTeam(self):
        validTeamChoice1 = False #creating a while loop to only allow valid inputs for the first team choice
        validTeamChoice2 = False #loop for second team choice
        userChoice1 = " "
        Team1Colour = userChoice1
        Team1Name = " "
        userChoice2 = " "
        Team2Colour = userChoice2
        Team2Name = " "
        while validTeamChoice1 == False:
            userChoice1 = self.teamname = input("Please select a team // GSW or CAVS: ") #allowing user input
            if userChoice1.upper() == "GSW":
                userChoice1 = self.teamname = ("Golden State Warriors")
                Team1Colour = self.colour = (0,107,182) #rgb colour for GSW yellow
                Team1Name = self.teamname
                if userChoice1 == self.teamname:
                    validTeamChoice1 = True
            else:
                validTeamChoice1 = False #continues loop
        while validTeamChoice2 == False:
            userChoice2 = self.teamname = input("Please select an opposing team // GSW or CAVS: ")
            if userChoice2.upper() == "CAVS":
                userChoice2 = self.teamname = ("Cleveland Cavaliers")
                Team2Colour = self.colour = (134,0,56) #rgb colour for CAVS red
                Team2Name = self.teamname
                self.composition['point guard'].append('Jose Calderon')
                if userChoice2 == self.teamname:
                    validTeamChoice2 = True
            else:
                validTeamChoice2 = False

        self.team1players = []
        for i in range(numPlayers):
            self.team1players.append(Player('Ruari', 15, random.randint(0,470),random.randint(0,500), Team1Colour, 0, Team1Name, 0.01, 30))
        self.team2players = []#
        for i in range(numPlayers):
            self.team2players.append(Player(self.composition['point guard'], 15, random.randint(470,940),random.randint(0,500), Team2Colour, 0, Team2Name, 0.01, 30))
    def displayPlayers(self): #displays the player using the player attributes and the display method from the Player class
        for n in range(numPlayers):
            self.team1players[n].displayCircle()
            self.team2players[n].displayCircle()
    def printPlayers(self):
        print(self.team2players[1].playername)

class Player(): #the player class holds information on the player symbol
    def __init__(self, playername, size, x, y, colour, thickness,teamname,speed, angle): #teamname is predetermined
        self.playername = playername
        self.size = size #size is a unit for the radius
        self.x = x #x, y are position on the court
        self.y = y
        self.speed = speed
        self.angle = angle
        self.colour = colour
        self.thickness = 0 #thickness is set to 0

    def displayCircle(self): #drawing the circle onto the screen using colour, co-ordinates and radii
            pygame.draw.circle(screen, self.colour, (self.x, self.y), self.size, self.thickness)

pygame.display.set_icon(icon_image)
screen.blit(background_image, [0,0]) #this sets the background court image (note: its outside all the classes)
myTeam1 = teams() #creates a myTeam1 object from the teams class
myTeam1.startTeam() #runs the startTeam method from the teams class
myTeam1.displayPlayers() #runs the displayPlayers method from the teams
pygame.display.flip() #updates the screen based on current events ("flip" is the same as "update()")
myTeam1.printPlayers()
#the below code monitors current on screen events should they be needed for movement etc. it also allows the window to be closed.
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
            pygame.quit()
            quit

Any help is appreciated!

EDIT Below I have made it so that the relevant players are appended to their positions after the user has selected a team (each team has diff. players) and I have also created a new composition attribute in the teams class - now there's team1composition and team2composition so that both teams have a different point guard, shooting guard etc.   Is there a more efficient way? At first I planned to have both teams players in lists in the dictionary and I would use the array to select which player is for which team however I believe this is better?

class teams():

    def __init__(self, teamname = "unknown", wins = "0", losses = "0", team1player = "unknown", team2player ="unknown", colour = "255,255,255"):
        #above I have created all the attributes of teams
        self.teamname = teamname #sets teamname
        self.team1composition = {
            'point guard' : [],
            'shooting guard': [],
            'small forward': [],
            'power forward': [],
            'centre': []
        }
        self.team2composition = {
            'point guard' : [],
            'shooting guard': [],
            'small forward': [],
            'power forward': [],
            'centre': []
        }
        self.wins = wins #number of wins
        self.losses = losses #number of losses
        self.team1player = team1player #holds a player and can be used to create players I have made this here so that the players are a part of the team
        self.team2player = team2player

        self.colour = colour #holds the rgb colour specific to the team

    def startTeam(self):
        validTeamChoice1 = False #creating a while loop to only allow valid inputs for the first team choice
        validTeamChoice2 = False #loop for second team choice
        userChoice1 = " "
        Team1Colour = userChoice1
        Team1Name = " "
        userChoice2 = " "
        Team2Colour = userChoice2
        Team2Name = " "
        while validTeamChoice1 == False:
            userChoice1 = self.teamname = input("Please select a team // GSW or CAVS: ") #allowing user input
            if userChoice1.upper() == "GSW":
                userChoice1 = self.teamname = ("Golden State Warriors")
                Team1Colour = self.colour = (0,107,182) #rgb colour for GSW yellow
                Team1Name = self.teamname
                if userChoice1 == self.teamname:
                    validTeamChoice1 = True
            else:
                validTeamChoice1 = False #continues loop
        while validTeamChoice2 == False:
            userChoice2 = self.teamname = input("Please select an opposing team // GSW or CAVS: ")
            if userChoice2.upper() == "CAVS":
                userChoice2 = self.teamname = ("Cleveland Cavaliers")
                Team2Colour = self.colour = (134,0,56) #rgb colour for CAVS red
                Team2Name = self.teamname
                self.team2composition['point guard'].append('Jose Calderon')
                self.team2composition['shooting guard'].append('J.R Smith')
                self.team2composition['small forward'].append('LeBron James')
                self.team2composition['power forward'].append('Jae Crowder')
                self.team2composition['centre'].append('Kevin Love')
                if userChoice2 == self.teamname:
                    validTeamChoice2 = True
            else:
                validTeamChoice2 = False

        self.team1players = []
        for position , name in self.team1composition.items():
            print (position, name)
            self.team1players.append(Player(name, 15, random.randint(0,470),random.randint(0,500), Team1Colour, 0, Team1Name, 0.01, 30))
        self.team2players = []#
        for position, name in self.team2composition.items():
            print(position , name)
            self.team2players.append(Player(name, 15, random.randint(470,940),random.randint(0,500)

When the code is now ran here is the result (not the Pygame window)...

Please select a team // GSW or CAVS: gsw
Please select an opposing team // GSW or CAVS: cavs
point guard []
shooting guard []
small forward []
power forward []
centre []
point guard ['Jose Calderon']
shooting guard ['J.R Smith']
small forward ['LeBron James']
power forward ['Jae Crowder']
centre ['Kevin Love']

Body:
Instead of

for i in range(numPlayers):
    self.team2players.append(Player(self.composition['point guard'], ...))

you can use for with dictionary

self.team2players = []#

for position, name in self.composition.items():
    #print(position, name)
    self.team2players.append(Player(name, ...))

BTW:

Because you have only one player in self.composition

so it will create only one player in self.team2players.

Dictionary doesn't keep order so when you will have more players in self.composition

then for ... in self.composition may create players in different order.

EDIT:

When I look at Player(self.composition['point guard'], then it seems you have only one string assigned to self.composition['point guard'] and previous code should works,

but when I look on your dictionary it seems you have list with many names assigned to self.composition['point guard']:

    self.composition = {
        'point guard' : [],
        'shooting guard': [],
        'small forward': [],
        'power forward': [],
        'centre': []
    }

and it means you need two for loops

self.team2players = []#

for position, names_list in self.composition.items():
    #print(position, names_list)
    for name in names_list:
        #print(name)
        self.team2players.append(Player(name, ...))

EDIT:

If you will keep only one name for every position then you don't need list   but you can use string with name or empty string (or None) if there is no name.

self.composition = {
    'point guard' : None,
    'shooting guard': None,
    'small forward': None,
    'power forward': None,
    'centre': None
}

and you assign name without append()

self.composition['point guard'] = 'Jose Calderon'

and to create player you need use if to check None

self.team2players = []

for position, name in self.composition.items():
    if name: # the same as `if (name is not None) and (name != "") and (name != 0) and (name != False) ...:
        self.team2players.append(Player(name, ...))
    #else:
    #   print("you don't have player on position", position)


问:
how to add mp3 player to facebook members from my facebook application
I am making an application that reads an mp3 file , and I want the user to be able to share the mp3 player on his profile and be shown like the image below:

and not like the normal share button.

答:
```<code><embed id="mpl" height="16" name="mpl"
       type="application/x-shockwave-flash" width="176"
       src="http://hexol.org/partners/player/player.swf"
       flashvars="author=Bindas Radio&description=Bindas Radio&captions=Bindas&duration=9999999999&file=http://74.63.104.27:8234/;stream.mp3&link=http://www.fnradio.net/sms.php&backcolor=000000&frontcolor=FFFFFF&lightcolor=CCCCCC&screencolor=000000&volume=40&autostart=true&repeat=always"
       wmode="opaque" allowscriptaccess="always"
       allowfullscreen="true" quality="high"></embed>
</code>```

OwnerDisplayName: webtuto

Body:
<embed id="mpl" height="16" name="mpl"
       type="application/x-shockwave-flash" width="176"
       src="http://hexol.org/partners/player/player.swf"
       flashvars="author=Bindas Radio&amp;description=Bindas Radio&amp;captions=Bindas&amp;duration=9999999999&amp;file=http://74.63.104.27:8234/;stream.mp3&amp;link=http://www.fnradio.net/sms.php&amp;backcolor=000000&amp;frontcolor=FFFFFF&amp;lightcolor=CCCCCC&amp;screencolor=000000&amp;volume=40&amp;autostart=true&amp;repeat=always"
       wmode="opaque" allowscriptaccess="always"
       allowfullscreen="true" quality="high"></embed>