问:
Date as variable name
I'd like to use the date as a variable name. I understand I'll need to append a character to the front and also that it's not a good way to store data (it's purely for report aesthetics). I've tried %eval() but can't solve it.

```<code>%let var_date = '_'||today();
data date;
    %eval(&var_date) = .;
run;
</code>```

I'd like the variable name to be _02JUN2011. Thanks for any help.

答:
I don't think you want to take this approach. You should use labels in PROC REPORT (or any other reporting PROC), or pivot your data dynamically instead. Perhaps if you describe the data you've got and the output you want, people here will be able to help find an appropriate solution.

For your edification though, the following code does what you're trying to do in your post:

```%let var_date=_%sysfunc(today(),date9.);

data test;
  &var_date=.;
run;```

Title: Date as variable name

Body:
I'd like to use the date as a variable name. I understand I'll need to append a character to the front and also that it's not a good way to store data (it's purely for report aesthetics). I've tried %eval() but can't solve it.

%let var_date = '_'||today();
data date;
    %eval(&var_date) = .;
run;

I'd like the variable name to be _02JUN2011. Thanks for any help.

Body:
I don't think you want to take this approach. You should use labels in PROC REPORT (or any other reporting PROC), or pivot your data dynamically instead. Perhaps if you describe the data you've got and the output you want, people here will be able to help find an appropriate solution.

For your edification though, the following code does what you're trying to do in your post:

%let var_date=_%sysfunc(today(),date9.);

data test;
  &var_date=.;
run;


来源: stackexchange

问:
Decrypt Word document knowing part of its content
I have a ciphered .docx document I would like to recover and I don't remember the password. I'm trying brute-forcing it but it's taking way too long, so it's not going to be option. However, I know the exact content of part of it (296 characters). Any help?</p>

答:
Unfortunately, part of the document wouldn't help.

To get to the cleartext, any cracker would still need to go through trying to crack the password hash that is exported from the document, and with your logic try to decrypt the file and interpret it's content, compare it to the known cleartext. There is no such funcitonality, especially for specialized document formats.

Here is an example how to approach it:

Document: encrypted_doc.docx

Password: 123horse123
You will have to use office2john to export the hash to be cracked from the document.

```<code>wget https://raw.githubusercontent.com/magnumripper/JohnTheRipper/bleeding-jumbo/run/office2john.py

python office2john.py encrypted_doc.docx > doc_pass_hash.txt
cat doc_pass_hash.txt
encrypted_doc.docx:$**office$*2013***100000*256*16*e77e386a8e68462d2a0a703718febbc9*08ee275ccf4946ae0e5922e9ff3114b7*0ab5fc00964f7ed4be9e45c77a33b441b2c4874d28e4bc30f38e99bfb169fcf4
</code>```

Remembering some information about the password(complexity, some chosen words if any, character set etc.) mask attack could help you run a more effective way to uncover the document.

Run hashcat --help to see which document file are you dealing with:

```<code>   9700 | MS Office <= 2003 $0/$1, MD5 + RC4               | Documents
   9710 | MS Office <= 2003 $0/$1, MD5 + RC4, collider #1  | Documents
   9720 | MS Office <= 2003 $0/$1, MD5 + RC4, collider #2  | Documents
   9800 | MS Office <= 2003 $3/$4, SHA1 + RC4              | Documents
   9810 | MS Office <= 2003 $3, SHA1 + RC4, collider #1    | Documents
   9820 | MS Office <= 2003 $3, SHA1 + RC4, collider #2    | Documents
   9400 | MS Office 2007                                   | Documents
   9500 | MS Office 2010                                   | Documents
   9600 | MS Office 2013                                   | Documents
</code>```

Based on what you can recall from the password, you can choose from the following:

```<code>  - [ Attack Modes ] -

      # | Mode
     ===+======
      0 | Straight
      1 | Combination
      3 | Brute-force
      6 | Hybrid Wordlist + Mask
      7 | Hybrid Mask + Wordlist
</code>```

Here are the options for hashcat to specify the password:

```<code>?l = abcdefghijklmnopqrstuvwxyz
?u = ABCDEFGHIJKLMNOPQRSTUVWXYZ
?d = 0123456789
?h = 0123456789abcdef
?H = 0123456789ABCDEF
?s = «space»!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
?a = ?l?u?d?s
?b = 0x00 - 0xff
</code>```

You can also create your own dictionary, which then will be used when generating the passwords, if you remember at least part of the password. This can be the most efficient help.

So in my example, let's run a brute force attack with mask(3 digits, 5 alphabetical characters, and another 3 digits):

```<code>hashcat -m 9600 -a 3 doc_pass_hash.txt --username -o cracked_pass.txt ?d?d?d?l?l?l?l?l?d?d?d --force
</code>```

You can hit [s] for status:

```<code>[s]tatus [p]ause [b]ypass [c]heckpoint [q]uit => s

Session..........: hashcat
Status...........: Running
Hash.Type........: MS Office 2013
Hash.Target......: $office$*2013*100000*256*16*e77e386a8e68462d2a0a703...69fcf4
Time.Started.....: Sat May 30 16:59:30 2020 (3 mins, 41 secs)
Time.Estimated...: Next Big Bang (17614 years, 157 days)
Guess.Mask.......: ?d?d?d?l?l?l?l?l?d?d?d [11]
Guess.Queue......: 1/1 (100.00%)
Speed.#1.........:       21 H/s (7.50ms) @ Accel:128 Loops:32 Thr:1 Vec:8
Recovered........: 0/1 (0.00%) Digests, 0/1 (0.00%) Salts
Progress.........: 4608/11881376000000 (0.00%)
Rejected.........: 0/4608 (0.00%)
Restore.Point....: 0/1188137600000 (0.00%)
Restore.Sub.#1...: Salt:0 Amplifier:9-10 Iteration:24672-24704
Candidates.#1....: 623anane123 -> 612kerin123
</code>```

As you see, this one doesn't seem to be very effective (Time.Estimated...: Next Big Bang (17614 years, 157 days)), however, adding a wordlist is a good idea:

```<code>cat wordlist.txt
dog
horse
cat

hashcat -m 9600 -a 6 doc_pass_hash.txt wordlist.dict ?d?d?d?l?l?l?l?l?d?d?d --username -o cracked_pass.txt --forces

Session..........: hashcat
Status...........: Running
Hash.Type........: MS Office 2013
Hash.Target......: $office$*2013*100000*256*16*e77e386a8e68462d2a0a703...69fcf4
Time.Started.....: Sat May 30 17:15:34 2020 (1 min, 25 secs)
Time.Estimated...: Next Big Bang (734631 years, 226 days)
Guess.Base.......: File (wordlist.dict), Left Side
Guess.Mod........: Mask (?d?d?d?l?l?l?l?l?d?d?d) [11], Right Side
Guess.Queue.Base.: 1/1 (100.00%)
Guess.Queue.Mod..: 1/1 (100.00%)
Speed.#1.........:        2 H/s (0.47ms) @ Accel:128 Loops:32 Thr:1 Vec:8
Recovered........: 0/1 (0.00%) Digests, 0/1 (0.00%) Salts
Progress.........: 129/35644128000000 (0.00%)
Rejected.........: 0/129 (0.00%)
Restore.Point....: 0/3 (0.00%)
Restore.Sub.#1...: Salt:0 Amplifier:43-44 Iteration:32000-32032
Candidates.#1....: dog360verin123 -> cat360verin123
</code>```

As we see this is not yet correct, as the candidates generate prior the mask. So this needs some more tweaking.
Masks you can define specific characters as well, for instance:

```<code>hashcat -m 9600 -a 3 doc_pass_hash.txt ?d?d?dhorse?d?d?d --username -o cracked_pass.txt --force

Session..........: hashcat
Status...........: Cracked
Hash.Type........: MS Office 2013
Hash.Target......: $office$*2013*100000*256*16*e77e386a8e68462d2a0a703...69fcf4
Time.Started.....: Sat May 30 17:24:32 2020 (28 secs)
Time.Estimated...: Sat May 30 17:25:00 2020 (0 secs)
Guess.Mask.......: ?d?d?dhorse?d?d?d [11]
Guess.Queue......: 1/1 (100.00%)
Speed.#1.........:       18 H/s (8.21ms) @ Accel:128 Loops:32 Thr:1 Vec:8
Recovered........: 1/1 (100.00%) Digests, 1/1 (100.00%) Salts
Progress.........: 512/1000000 (0.05%)
Rejected.........: 0/512 (0.00%)
Restore.Point....: 0/100000 (0.00%)
Restore.Sub.#1...: Salt:0 Amplifier:0-1 Iteration:99968-100000
Candidates.#1....: 123horse123 -> 112horse778

cat cracked_pass.txt
$office$*2013*100000*256*16*e77e386a8e68462d2a0a703718febbc9*08ee275ccf4946ae0e5922e9ff3114b7*0ab5fc00964f7ed4be9e45c77a33b441b2c4874d28e4bc30f38e99bfb169fcf4:123horse123
</code>```

Cracked password in the end of the file: 123horse123

There is more to be read about rules and cracking with increased password lenght (--incremental) and combined attacks, but you get the idea.

Here are the official basic examples to get you started:

```<code>- [ Basic Examples ] -

  Attack-          | Hash- |
  Mode             | Type  | Example command
 ==================+=======+==================================================================
  Wordlist         | $P$   | hashcat -a 0 -m 400 example400.hash example.dict
  Wordlist + Rules | MD5   | hashcat -a 0 -m 0 example0.hash example.dict -r rules/best64.rule
  Brute-Force      | MD5   | hashcat -a 3 -m 0 example0.hash ?a?a?a?a?a?a
  Combinator

 | MD5   | hashcat -a 1 -m 0 example0.hash example.dict example.dict
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Unfortunately, part of the document wouldn't help.

To get to the cleartext, any cracker would still need to go through trying to crack the password hash that is exported from the document, and with your logic try to decrypt the file and interpret it's content, compare it to the known cleartext. There is no such funcitonality, especially for specialized document formats.

Here is an example how to approach it:

Document: encrypted_doc.docx

Password: 123horse123
You will have to use office2john to export the hash to be cracked from the document.

wget https://raw.githubusercontent.com/magnumripper/JohnTheRipper/bleeding-jumbo/run/office2john.py

python office2john.py encrypted_doc.docx > doc_pass_hash.txt
cat doc_pass_hash.txt
encrypted_doc.docx:$**office$*2013***100000*256*16*e77e386a8e68462d2a0a703718febbc9*08ee275ccf4946ae0e5922e9ff3114b7*0ab5fc00964f7ed4be9e45c77a33b441b2c4874d28e4bc30f38e99bfb169fcf4

Remembering some information about the password(complexity, some chosen words if any, character set etc.) mask attack could help you run a more effective way to uncover the document.

Run hashcat --help to see which document file are you dealing with:

   9700 | MS Office <= 2003 $0/$1, MD5 + RC4               | Documents
   9710 | MS Office <= 2003 $0/$1, MD5 + RC4, collider #1  | Documents
   9720 | MS Office <= 2003 $0/$1, MD5 + RC4, collider #2  | Documents
   9800 | MS Office <= 2003 $3/$4, SHA1 + RC4              | Documents
   9810 | MS Office <= 2003 $3, SHA1 + RC4, collider #1    | Documents
   9820 | MS Office <= 2003 $3, SHA1 + RC4, collider #2    | Documents
   9400 | MS Office 2007                                   | Documents
   9500 | MS Office 2010                                   | Documents
   9600 | MS Office 2013                                   | Documents

Based on what you can recall from the password, you can choose from the following:

  - [ Attack Modes ] -

      # | Mode
     ===+======
      0 | Straight
      1 | Combination
      3 | Brute-force
      6 | Hybrid Wordlist + Mask
      7 | Hybrid Mask + Wordlist

Here are the options for hashcat to specify the password:

?l = abcdefghijklmnopqrstuvwxyz
?u = ABCDEFGHIJKLMNOPQRSTUVWXYZ
?d = 0123456789
?h = 0123456789abcdef
?H = 0123456789ABCDEF
?s = «space»!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
?a = ?l?u?d?s
?b = 0x00 - 0xff

You can also create your own dictionary, which then will be used when generating the passwords, if you remember at least part of the password. This can be the most efficient help.

So in my example, let's run a brute force attack with mask(3 digits, 5 alphabetical characters, and another 3 digits):

hashcat -m 9600 -a 3 doc_pass_hash.txt --username -o cracked_pass.txt ?d?d?d?l?l?l?l?l?d?d?d --force

You can hit [s] for status:

[s]tatus [p]ause [b]ypass [c]heckpoint [q]uit => s

Session..........: hashcat
Status...........: Running
Hash.Type........: MS Office 2013
Hash.Target......: $office$*2013*100000*256*16*e77e386a8e68462d2a0a703...69fcf4
Time.Started.....: Sat May 30 16:59:30 2020 (3 mins, 41 secs)
Time.Estimated...: Next Big Bang (17614 years, 157 days)
Guess.Mask.......: ?d?d?d?l?l?l?l?l?d?d?d [11]
Guess.Queue......: 1/1 (100.00%)
Speed.#1.........:       21 H/s (7.50ms) @ Accel:128 Loops:32 Thr:1 Vec:8
Recovered........: 0/1 (0.00%) Digests, 0/1 (0.00%) Salts
Progress.........: 4608/11881376000000 (0.00%)
Rejected.........: 0/4608 (0.00%)
Restore.Point....: 0/1188137600000 (0.00%)
Restore.Sub.#1...: Salt:0 Amplifier:9-10 Iteration:24672-24704
Candidates.#1....: 623anane123 -> 612kerin123

As you see, this one doesn't seem to be very effective (Time.Estimated...: Next Big Bang (17614 years, 157 days)), however, adding a wordlist is a good idea:

cat wordlist.txt
dog
horse
cat

hashcat -m 9600 -a 6 doc_pass_hash.txt wordlist.dict ?d?d?d?l?l?l?l?l?d?d?d --username -o cracked_pass.txt --forces

Session..........: hashcat
Status...........: Running
Hash.Type........: MS Office 2013
Hash.Target......: $office$*2013*100000*256*16*e77e386a8e68462d2a0a703...69fcf4
Time.Started.....: Sat May 30 17:15:34 2020 (1 min, 25 secs)
Time.Estimated...: Next Big Bang (734631 years, 226 days)
Guess.Base.......: File (wordlist.dict), Left Side
Guess.Mod........: Mask (?d?d?d?l?l?l?l?l?d?d?d) [11], Right Side
Guess.Queue.Base.: 1/1 (100.00%)
Guess.Queue.Mod..: 1/1 (100.00%)
Speed.#1.........:        2 H/s (0.47ms) @ Accel:128 Loops:32 Thr:1 Vec:8
Recovered........: 0/1 (0.00%) Digests, 0/1 (0.00%) Salts
Progress.........: 129/35644128000000 (0.00%)
Rejected.........: 0/129 (0.00%)
Restore.Point....: 0/3 (0.00%)
Restore.Sub.#1...: Salt:0 Amplifier:43-44 Iteration:32000-32032
Candidates.#1....: dog360verin123 -> cat360verin123

As we see this is not yet correct, as the candidates generate prior the mask. So this needs some more tweaking.
Masks you can define specific characters as well, for instance:

hashcat -m 9600 -a 3 doc_pass_hash.txt ?d?d?dhorse?d?d?d --username -o cracked_pass.txt --force

Session..........: hashcat
Status...........: Cracked
Hash.Type........: MS Office 2013
Hash.Target......: $office$*2013*100000*256*16*e77e386a8e68462d2a0a703...69fcf4
Time.Started.....: Sat May 30 17:24:32 2020 (28 secs)
Time.Estimated...: Sat May 30 17:25:00 2020 (0 secs)
Guess.Mask.......: ?d?d?dhorse?d?d?d [11]
Guess.Queue......: 1/1 (100.00%)
Speed.#1.........:       18 H/s (8.21ms) @ Accel:128 Loops:32 Thr:1 Vec:8
Recovered........: 1/1 (100.00%) Digests, 1/1 (100.00%) Salts
Progress.........: 512/1000000 (0.05%)
Rejected.........: 0/512 (0.00%)
Restore.Point....: 0/100000 (0.00%)
Restore.Sub.#1...: Salt:0 Amplifier:0-1 Iteration:99968-100000
Candidates.#1....: 123horse123 -> 112horse778

cat cracked_pass.txt
$office$*2013*100000*256*16*e77e386a8e68462d2a0a703718febbc9*08ee275ccf4946ae0e5922e9ff3114b7*0ab5fc00964f7ed4be9e45c77a33b441b2c4874d28e4bc30f38e99bfb169fcf4:123horse123

Cracked password in the end of the file: 123horse123

There is more to be read about rules and cracking with increased password lenght (--incremental) and combined attacks, but you get the idea.

Here are the official basic examples to get you started:

- [ Basic Examples ] -

  Attack-          | Hash- |
  Mode             | Type  | Example command
 ==================+=======+==================================================================
  Wordlist         | $P$   | hashcat -a 0 -m 400 example400.hash example.dict
  Wordlist + Rules | MD5   | hashcat -a 0 -m 0 example0.hash example.dict -r rules/best64.rule
  Brute-Force      | MD5   | hashcat -a 3 -m 0 example0.hash ?a?a?a?a?a?a
  Combinator

 | MD5   | hashcat -a 1 -m 0 example0.hash example.dict example.dict


问:
Using let instead of var breaks User:*/vector.js in MediaWiki
I try to understand what's going on with my adaption of the basic example of a MediaWiki user script.

It works in the original form, but when I replace var by let in the format_words function, it stops working. I'm quite new to JavaScript and jQuery. Here is the working version:

function format_words(title, numWords){
  var text = title+" ("+numWords+" words)";
  return text;
}

$(document).ready(function(){
  var numWords = $("#mw-content-text > div").text().split(" ").length;
  var header = $("#firstHeading").text();
  $("#firstHeading").text(format_words(header, numWords));
});
```

<p>And here the version that doesn't work</p>

<pre class="lang-js prettyprint-override"><code>function format_words(title, numWords){
  let text = title+" ("+numWords+" words)";
  return text;
}

$(document).ready(function(){
  var numWords = $("#mw-content-text > div").text().split(" ").length;
  var header = $("#firstHeading").text();
  $("#firstHeading").text(format_words(header, numWords));
});
</code>```

The first gives leads to this h1 heading:

User:Wolf/vector.js (74 words)

the second gives

User:Wolf/vector.js

I tested this in MediaWiki 1.31.6 and in MediaWiki 1.35.0-wmf.34 (6ff15fd), same effect.

After slowly getting familiar with jQuery, I expect a lot of asynchrony, but at this point I cannot figure out its influence.

Counter example

When I tested similar code in local HTML+JavaScript (with hot jQuery), switching from var to let doesn't break the code.

Console log

Thanks to charlietfl I changed my script to

function format_words(title, numWords){
  console.log("format_words [enter]");
  let text = title+" ("+numWords+" words)";
  console.log("format_words: text:"+text);
  return text;
}

$(document).ready(function(){
  console.log("on ready [enter]");
  var numWords = $("#mw-content-text > div").text().split(" ").length;
  var header = $("#firstHeading").text();
  $("#firstHeading").text(format_words(header, numWords));
  console.log("on ready [leave]");
});
```

<p>... and opened the console. For the <code>let</code> version it shows the following error:</p>

<pre class="lang-none prettyprint-override"><code>JavaScript parse error: Parse error: Missing ; before statement in file↵
 'User:Wolf/vector.js' on line 3 vector.js line 1 > scriptElement:1:8
    <anonym> https://some.wiki/w/User:Wolf/vector.js line 1 > scriptElement:1
    jQuery 9
        DOMEval
        globalEval
        runScript
        fire
        add
        always
        checkCssHandles
        execute
        implement
    <anonym> https://some.wiki/load.php?debug=false&lang=en&modules=user&↵
skin=vector&user=Wolf&version=0hjxbj8:1
</code>```

I read this as let not being supported by JavaScript. Very strange: I was sure that JavaScript comes from the browser? And it worked with my Counter example.

What is going on here?

答:
While Tgr may have (somehow) answered my original phrasing of the question

How can using let instead of var break my MediaWiki userScript?

... I must somehow cope with this surprising limitation.1 And luckily I found a quite satisfying workaround: const is supported by the JS minifier despite being an ES6 feature!

1 that I'm still failing to google, but there is hope: tomorrow I'll find this answer to my own question

Body:
I try to understand what's going on with my adaption of the basic example of a MediaWiki user script.

It works in the original form, but when I replace var by let in the format_words function, it stops working. I'm quite new to JavaScript and jQuery. Here is the working version:

function format_words(title, numWords){
  var text = title+" ("+numWords+" words)";
  return text;
}

$(document).ready(function(){
  var numWords = $("#mw-content-text > div").text().split(" ").length;
  var header = $("#firstHeading").text();
  $("#firstHeading").text(format_words(header, numWords));
});

And here the version that doesn't work

function format_words(title, numWords){
  let text = title+" ("+numWords+" words)";
  return text;
}

$(document).ready(function(){
  var numWords = $("#mw-content-text > div").text().split(" ").length;
  var header = $("#firstHeading").text();
  $("#firstHeading").text(format_words(header, numWords));
});

The first gives leads to this h1 heading:

User:Wolf/vector.js (74 words)

the second gives

User:Wolf/vector.js

I tested this in MediaWiki 1.31.6 and in MediaWiki 1.35.0-wmf.34 (6ff15fd), same effect.

After slowly getting familiar with jQuery, I expect a lot of asynchrony, but at this point I cannot figure out its influence.

Counter example

When I tested similar code in local HTML+JavaScript (with hot jQuery), switching from var to let doesn't break the code.

Console log

Thanks to charlietfl I changed my script to

function format_words(title, numWords){
  console.log("format_words [enter]");
  let text = title+" ("+numWords+" words)";
  console.log("format_words: text:"+text);
  return text;
}

$(document).ready(function(){
  console.log("on ready [enter]");
  var numWords = $("#mw-content-text > div").text().split(" ").length;
  var header = $("#firstHeading").text();
  $("#firstHeading").text(format_words(header, numWords));
  console.log("on ready [leave]");
});

... and opened the console. For the let version it shows the following error:

JavaScript parse error: Parse error: Missing ; before statement in file↵
 'User:Wolf/vector.js' on line 3 vector.js line 1 > scriptElement:1:8
    <anonym> https://some.wiki/w/User:Wolf/vector.js line 1 > scriptElement:1
    jQuery 9
        DOMEval
        globalEval
        runScript
        fire
        add
        always
        checkCssHandles
        execute
        implement
    <anonym> https://some.wiki/load.php?debug=false&lang=en&modules=user&↵
skin=vector&user=Wolf&version=0hjxbj8:1

I read this as let not being supported by JavaScript. Very strange: I was sure that JavaScript comes from the browser? And it worked with my Counter example.

What is going on here?


问:
Update SWIFTUI text font size with slider?
I am trying to update font size but using user interaction with slider object.
But using below code is not updating font as texts are not updating on changed value.

@State var fontSize: CGFloat = 14.0

```<code> HStack(alignment: .firstTextBaseline, spacing: 20) {
                            Spacer()
                            Text(viewModel.isSelectionStarted ? viewModel.verseModels[viewModel.selectedFrameworkIndex1 ].English: "")
                                .font(.subheadline)
                                .font(.system(size: CGFloat(fontSize)))
                                .foregroundColor(Color.white)

                            Text(viewModel.isSelectionStarted ? viewModel.verseModels[viewModel.selectedFrameworkIndex1 ].Spanish: "")
                                .font(.subheadline)
                                .font(.system(size: CGFloat(fontSize)))
                                .foregroundColor(Color.white)
                        }
</code>```

Slider code:

```<code>Slider(value: $fontSize, in: 6...32, step: 1)
                        .padding()
                        .accentColor(Color.green)
                        .border(Color(hex: "#066892"), width: 2)
</code>```

答:
Just change the order of the Text functions:

```<code>.font(.subheadline)
.font(.system(size: CGFloat(fontSize)))
.foregroundColor(Color.white)
</code>```

To:

```<code>.font(.system(size: CGFloat(fontSize)))
.font(.subheadline)
.foregroundColor(Color.white)
</code>```

Should work.

Body:
I am trying to update font size but using user interaction with slider object.
But using below code is not updating font as texts are not updating on changed value.

@State var fontSize: CGFloat = 14.0

 HStack(alignment: .firstTextBaseline, spacing: 20) {
                            Spacer()
                            Text(viewModel.isSelectionStarted ? viewModel.verseModels[viewModel.selectedFrameworkIndex1 ].English: "")
                                .font(.subheadline)
                                .font(.system(size: CGFloat(fontSize)))
                                .foregroundColor(Color.white)

                            Text(viewModel.isSelectionStarted ? viewModel.verseModels[viewModel.selectedFrameworkIndex1 ].Spanish: "")
                                .font(.subheadline)
                                .font(.system(size: CGFloat(fontSize)))
                                .foregroundColor(Color.white)
                        }

Slider code:

Slider(value: $fontSize, in: 6...32, step: 1)
                        .padding()
                        .accentColor(Color.green)
                        .border(Color(hex: "#066892"), width: 2)

Body:
Just change the order of the Text functions:

.font(.subheadline)
.font(.system(size: CGFloat(fontSize)))
.foregroundColor(Color.white)

To:

.font(.system(size: CGFloat(fontSize)))
.font(.subheadline)
.foregroundColor(Color.white)

Should work.


问:
Comparing string data received from a socket in C
I have a question on sockets.  I have this code:

```<code>while(bytes = recv(sClient, cClientMessage, 599, 0)){
</code>```

This puts the message it recives into cClientMessage and the message is always "Message".  How I made an if statement like if(cClientMessage == "Message"){//do func}.  Now this code will not do the function I want.  I think this is because it's not receiving the message right.  Can someone help me?

答:
First there is a bug in the code you wrote:

```<code>while(bytes = recv(sClient, cClientMessage, 599, 0)){
</code>```

This is wrong because recv will return non zero if there is a socket error and your code will lead to an infinite loop.  In particular you want to check for > 0

```<code>char cClientMessage[599];
while((bytes = recv(sClient, cClientMessage, sizeof(cClientMessage), 0)) > 0)
{
  if(strlen("Message") == bytes && !strncmp("Message", cClientMessage, bytes))
  {
    //cClientMesssage contains "Message"
  }
}

if(bytes == 0)
{
  //socket was gracefully closed
}
else if(bytes < 0)
{
  //socket error occurred
}
</code>```

The problem with what you did: cClientMessage == "Message"  is that if you compare a char* to a string literal, or a char[] to a string literal, then you will be comparing the pointer addresses and not the actual content.

ContentLicense: CC BY-SA 2.5

Body:
I have a question on sockets.  I have this code:

while(bytes = recv(sClient, cClientMessage, 599, 0)){

This puts the message it recives into cClientMessage and the message is always "Message".  How I made an if statement like if(cClientMessage == "Message"){//do func}.  Now this code will not do the function I want.  I think this is because it's not receiving the message right.  Can someone help me?

LastEditorDisplayName: Brian R. Bondy

Body:
First there is a bug in the code you wrote:

while(bytes = recv(sClient, cClientMessage, 599, 0)){

This is wrong because recv will return non zero if there is a socket error and your code will lead to an infinite loop.  In particular you want to check for > 0

char cClientMessage[599];
while((bytes = recv(sClient, cClientMessage, sizeof(cClientMessage), 0)) > 0)
{
  if(strlen("Message") == bytes && !strncmp("Message", cClientMessage, bytes))
  {
    //cClientMesssage contains "Message"
  }
}

if(bytes == 0)
{
  //socket was gracefully closed
}
else if(bytes < 0)
{
  //socket error occurred
}

The problem with what you did: cClientMessage == "Message"  is that if you compare a char* to a string literal, or a char[] to a string literal, then you will be comparing the pointer addresses and not the actual content.

OwnerDisplayName: Brian R. Bondy


问:
Difference between x + x and 2*x in Java
I was reading the answers to a Leetcode problem: https://leetcode.com/problems/divide-two-integers/. This problem requires not using multiplication. After reading a few answers, I somehow had a misconception that x+x is better than 2*x in terms of memory and avoiding type overflow. After post the question, I cannot find any evidence to support this statement. Please ignore this question.

I saw a common practice in Java is using x + x instead of 2*x especially for int. For example

```<code>int x = 1;
x += x;
</code>```

Instead of

```<code>int x = 1;
x = 2*x;
</code>```

Using

```<code>if (a < b + b) {
  ...
}
</code>```

Instead of

```<code>if (a < 2*b) {
  ...
}
</code>```

Does x + x save slightly more memory than 2*x?

答: It seems more like a habit than has any reason to use this convention, unless JVM is more efficient in carrying our + operation than *, which probably is something we can totally ignore  </p>

Body:
I was reading the answers to a Leetcode problem: https://leetcode.com/problems/divide-two-integers/. This problem requires not using multiplication. After reading a few answers, I somehow had a misconception that x+x is better than 2*x in terms of memory and avoiding type overflow. After post the question, I cannot find any evidence to support this statement. Please ignore this question.

I saw a common practice in Java is using x + x instead of 2*x especially for int. For example

int x = 1;
x += x;

Instead of

int x = 1;
x = 2*x;

Using

if (a < b + b) {
  ...
}

Instead of

if (a < 2*b) {
  ...
}

Does x + x save slightly more memory than 2*x?


问:
Saving output after choosing option menu (python - Tkinter)
I'm attempting to save the choice of the user [Red, Green-red, Green-blue, blue] after the user hits the okay button and the window closes in Tkinter... I've put this together so far using things I've found online but I can't deduce a "simple" way of doing this?

```<code>def select_channel():
     OPTIONS = [
       "Red",
       "Green-red",
       "Green-blue",
       "Blue"
    ]

    master = tk.Tk()

    var = tk.StringVar(master)
    var.set(OPTIONS)  # initial value

    option = tk.OptionMenu(master, var, *OPTIONS)
    option.pack()

    def ok():
       print("value is", var.get())
       channel = var.get()
       master.destroy()

    button = tk.Button(master, text="OK", command=ok)
    button.pack()
    tk.mainloop()
</code>```

Any thoughts? I save it under channel but its not available outside of that function. hmm

答:
Use global to assign value to global variable

```<code>def ok():
    global channel

    print("value is", var.get())
    channel = var.get()
    master.destroy()
</code>```

BTW: There is no sense to use return channel because function is executed by button and it can't returned value and assign to other value.

BTW: If you want save only channel then maybe do it inside function ok()

BTW: You should use [0] in var.set(OPTIONS[0]) to set only first element as default/initial value.

```<code>import tkinter as tk

# --- functions ---

def select_channel():

     def ok():
         global channel

         #print("value is", var.get())
         channel = var.get()
         master.destroy()

     OPTIONS = [
       "Red",
       "Green-red",
       "Green-blue",
       "Blue"
     ]

     master = tk.Tk()

     var = tk.StringVar(master)
     var.set(OPTIONS[0])  # initial value

     option = tk.OptionMenu(master, var, *OPTIONS)
     option.pack()

     button = tk.Button(master, text="OK", command=ok)
     button.pack()

     tk.mainloop()

# --- main ---

select_channel()
print('after closing window:', channel)
</code>```

Body:
I'm attempting to save the choice of the user [Red, Green-red, Green-blue, blue] after the user hits the okay button and the window closes in Tkinter... I've put this together so far using things I've found online but I can't deduce a "simple" way of doing this?

def select_channel():
     OPTIONS = [
       "Red",
       "Green-red",
       "Green-blue",
       "Blue"
    ]

    master = tk.Tk()

    var = tk.StringVar(master)
    var.set(OPTIONS)  # initial value

    option = tk.OptionMenu(master, var, *OPTIONS)
    option.pack()

    def ok():
       print("value is", var.get())
       channel = var.get()
       master.destroy()

    button = tk.Button(master, text="OK", command=ok)
    button.pack()
    tk.mainloop()

Any thoughts? I save it under channel but its not available outside of that function. hmm

Body:
Use global to assign value to global variable

def ok():
    global channel

    print("value is", var.get())
    channel = var.get()
    master.destroy()

BTW: There is no sense to use return channel because function is executed by button and it can't returned value and assign to other value.

BTW: If you want save only channel then maybe do it inside function ok()

BTW: You should use [0] in var.set(OPTIONS[0]) to set only first element as default/initial value.

import tkinter as tk

# --- functions ---

def select_channel():

     def ok():
         global channel

         #print("value is", var.get())
         channel = var.get()
         master.destroy()

     OPTIONS = [
       "Red",
       "Green-red",
       "Green-blue",
       "Blue"
     ]

     master = tk.Tk()

     var = tk.StringVar(master)
     var.set(OPTIONS[0])  # initial value

     option = tk.OptionMenu(master, var, *OPTIONS)
     option.pack()

     button = tk.Button(master, text="OK", command=ok)
     button.pack()

     tk.mainloop()

# --- main ---

select_channel()
print('after closing window:', channel)


问:
Loop through list operating on result and next value
I have a sorted list of objects

```<code>l = sorted(['/path/to/1.obj', '/path/to/2.obj', '/path/to/3.obj', '/path/to/4.obj'])
</code>```

I want to loop through the object performing an operation on them and using the result to preform the next operation.

For example

```<code>result1 = my_operation(l[0], l[1])
result2 = my_operation(result1, l[2])
resultFinal = my_operation(result2, l[3])
</code>```

How can I do this in a list of an arbitrary length?

答:
That is exactly what reduce does:

from functools import reduce

def my_operation(total, value):
    return total + value

print(reduce(my_operation, [1,2,3,4]))
```

Body:
I have a sorted list of objects

l = sorted(['/path/to/1.obj', '/path/to/2.obj', '/path/to/3.obj', '/path/to/4.obj'])

I want to loop through the object performing an operation on them and using the result to preform the next operation.

For example

result1 = my_operation(l[0], l[1])
result2 = my_operation(result1, l[2])
resultFinal = my_operation(result2, l[3])

How can I do this in a list of an arbitrary length?


问:
Determine if a base64 string or a buffer contains JPEG or PNG without metadata? Possible?
Is there any way to do this using node, whether natively or with a plugin?

What I'm trying to accomplish is to choose loseless or lossy image compression depending on the input type. Loseless on a large JPEG is a storage catastrophe.

答:
@MarkSetchell's answer above is correct in theory.
However, in practice, it doesn't work for JPGs!

It is true that head -c2 test.jpg | base64 produces /9g

However

```<code>head -c3 test.jpg | base64`
/9j/
</code>```

So, if you want to "Determine if a base64 string or a buffer contains JPEG" you need to test that it starts with /9j not /9g!

Body:
@MarkSetchell's answer above is correct in theory.
However, in practice, it doesn't work for JPGs!

It is true that head -c2 test.jpg | base64 produces /9g

However

head -c3 test.jpg | base64`
/9j/

So, if you want to "Determine if a base64 string or a buffer contains JPEG" you need to test that it starts with /9j not /9g!


问:
How to display a image in any format from a SQL LONGBLOB in HTML with PHP
I want to read a image from a field LONGBLOB in a SQL table, and then display it in a HTML document. The query is made with php.
The code example:

```<code><?php
    foreach(.....):
?>

<?php header("Content-type: image/jpg"); // For jpg
echo "<td>" .$p['imagen'] . "</td>"; // The image must be in a SQL BLOB or LONGBLOB
?>

<?php
    endforeach;
?>
</code>```

But this just works for jpg images, and my database also contains png images. Can anybody tell me how to read images in a SQL LONGBLOB in any format?

And another question, this may cause slowness troubles in a free server? I've heard that using base64 may cause performance problems specifically if the LONGBLOB contains ñ or accents.

It could be read the format of the image in the LONGBLOB and using it to change the line 5?

答:
```<code>$conn = mysqli_connect('localhost', 'root', '', '*your_database_name*');

$imgQuery = ("SELECT FROM *your_table_name* WHERE *imageName* = 'theImageYouWant'");
$imgResult = mysqli_query($conn, $imgQuery);
$imgRow = mysqli_fetch_assoc($imgResult);
echo"<img src='".$imgRow['profileImage']."'>";
</code>```

This is from an assignment im currently working on as of right now. However i'm using XAMPP and phpMyAdmin as a mysqli database. Thus the $conn variable is using my localhost, root folder etc. You should not have to change the localhost and root unless you're not using XAMPP, else I'm not sure. I've been doing php for about 5-6 months only. So I hope this can be of help to you in some way. :)

Body:
I want to read a image from a field LONGBLOB in a SQL table, and then display it in a HTML document. The query is made with php.
The code example:

<?php
    foreach(.....):
?>

<?php header("Content-type: image/jpg"); // For jpg
echo "" .$p['imagen'] . "	"; // The image must be in a SQL BLOB or LONGBLOB
?>

<?php
    endforeach;
?>

But this just works for jpg images, and my database also contains png images. Can anybody tell me how to read images in a SQL LONGBLOB in any format?

And another question, this may cause slowness troubles in a free server? I've heard that using base64 may cause performance problems specifically if the LONGBLOB contains ñ or accents.

It could be read the format of the image in the LONGBLOB and using it to change the line 5?

Body:
$conn = mysqli_connect('localhost', 'root', '', '*your_database_name*');

$imgQuery = ("SELECT FROM *your_table_name* WHERE *imageName* = 'theImageYouWant'");
$imgResult = mysqli_query($conn, $imgQuery);
$imgRow = mysqli_fetch_assoc($imgResult);
echo"<img src='".$imgRow['profileImage']."'>";

This is from an assignment im currently working on as of right now. However i'm using XAMPP and phpMyAdmin as a mysqli database. Thus the $conn variable is using my localhost, root folder etc. You should not have to change the localhost and root unless you're not using XAMPP, else I'm not sure. I've been doing php for about 5-6 months only. So I hope this can be of help to you in some way. :)


问:
JPanel graphics flickering when is used the method getGraphics()
I try to create a class that was similar to the famous Processing, but soon I found a problem, since in Processing there are the setup () and draw () functions, in to which it is possible to perform certain functions, such as square (10,10,50), I tried to imitate it by creating a class, in which there is a Graphics object called "gfx" to which the various figures are added. If you read this papyrus ... thank you and I put below the PFrame class (that is the one that imitates Processing) and the BohClass class which will be the test class.

```<code>package PFrame.com;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class PFrame {
    private JFrame frame = new JFrame();
    private DPane pane = new DPane(); //DPane is a class that extends JPanel

    private Graphics2D gfx;
    private Color selColor = new Color(255,255,255); //selected color
    private boolean fill = true; //the shapes are filled?

    public int width = 200, height = 200; //starting frame dimensins

    public PFrame() {
        //SKY
        pane.setPreferredSize(new Dimension(width,height));

        //HEAD
        title(); //this functions give to the frame the name of the class (in this case "BohClass")
        frame.setResizable(false);

        //BODY
        frame.add(pane);
        pane.addComponentListener(new ResizeListener());

        //TAIL
        size(width,height); //function that setting size
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        gfx = (Graphics2D) pane.getGraphics();

        pane.paint(); //DPane function
    }

    //--|METHODS|--//
    //FRAME CONFIG
    public final void size(int x, int y) {
        width = x;
        height = y;
        pane.setPreferredSize(new Dimension(width,height));
        frame.pack();
        frame.setLocationRelativeTo(null);
        gfx = (Graphics2D) pane.getGraphics();
    }
    public final void exit() {
        System.exit(0);
    }
    public final void hide() {
        frame.setVisible(false);
    }
    public final void show() {
        frame.setVisible(true);
    }
    public final void location(int XY) {
        frame.setLocation(XY,XY);
    }
    public final void location(int X, int Y) {
        frame.setLocation(X,Y);
    }
    public final void title() {
        frame.setTitle((getClass() + "").split(" ")[1]);
    }
    public final void title(Object title) {
        frame.setTitle(title.toString());
    }
    public final void resizable() {
        frame.setResizable(!frame.isResizable());
    }
    public final void resizable(boolean resizable) {
        frame.setResizable(resizable);
    }

    //2D CONFIG
    public final void fill(boolean fill) {
        this.fill = fill;
    }
    public final void color(int RGB) {
        selColor = new Color(RGB,RGB,RGB);
    }
    public final void color(int R, int G, int B) {
        selColor = new Color(R,G,B);
    }

    //2D
    public final void square(int X, int Y, int L) {
        rect(X,Y,L,L);
    }
    public final void square(int X, int Y, int L, int A) {
        rect(X,Y,L,L,A);
    }
    public final void square(int X, int Y, int L, int Ax, int Ay) {
        rect(X,Y,L,L,Ax,Ay);
    }
    public final void rect(int X, int Y, int W, int H) {
        gfx.setColor(selColor);
        if(fill) gfx.fillRect(X, Y, W, H);
        else gfx.drawRect(X, Y, W, H);
    }
    public final void rect(int X, int Y, int W, int H,int A) {
        gfx.setColor(selColor);
        if(fill) gfx.fillRoundRect(X, Y, W, H, A, A);
        else gfx.drawRoundRect(X, Y, W, H, A, A);
    }
    public final void rect(int X, int Y, int W, int H,int Ax, int Ay) {
        gfx.setColor(selColor);
        if(fill) gfx.fillRoundRect(X, Y, W, H, Ax, Ay);
        else gfx.drawRoundRect(X, Y, W, H, Ax, Ay);
    }
    public final void circle(int X, int Y, int d) {
        ellipse(X,Y,d,d);
    }
    public final void ellipse(int X, int Y, int W, int H) {
        gfx.setColor(selColor);
        if(fill) gfx.fillOval(X, Y, W, H);
        else gfx.drawOval(X, Y, W, H);
    }
    public final void triangle(int Ax, int Ay, int Bx, int By, int Cx, int Cy) {
        gfx.setColor(selColor);
        if(fill) gfx.fillPolygon(new Polygon(new int[] {Ax,Bx,Cx}, new int[] {Ay,By,Cy}, 3));
        else gfx.drawPolygon(new Polygon(new int[] {Ax,Bx,Cx}, new int[] {Ay,By,Cy}, 3));
    }

    //PANEL CONFIG
    public final void background(int RGB) {
        pane.setBackground(new Color(RGB,RGB,RGB));
    }
    public final void background(int R, int G, int B) {
        pane.setBackground(new Color(R,G,B));
    }
    public final void clear() {
        gfx.clearRect(0, 0, width, height);
    }

    //PUBLIC METHODS
    public void setup() {}
    public void loop() {}

    //PRIVATE CLASS PANEL
    private class DPane extends JPanel {
        private static final long serialVersionUID = 57423L;

        public void paint() {
            setup();

            while(true) {
                loop();
            }
        }
    }

    //LISTENERS
    class ResizeListener implements ComponentListener {
        public void componentResized(ComponentEvent e) {
            width = pane.getWidth();
            height = pane.getHeight();
        }
        public void componentMoved(ComponentEvent e) {}
        public void componentShown(ComponentEvent e) {}
        public void componentHidden(ComponentEvent e) {}
    }
}
</code>```

and...

```<code>import PFrame.com.*;

public class BohClass extends PFrame {
    public void setup() {
        size(800,600);
        background(100);
    }
    public void loop() {
        color(72,28,47);
        triangle(60,10,10,60,110,60);
        color(255);
        square(12,12,123);
    }

    public static void main(String[] args) {
        new BohClass();
    }
}
</code>```

答:
Like others have said, you should not have a while(true) loop inside your painting function.

Shameless self-promotion: here is a tutorial on custom painting in Swing, coming from a Processing background. Basically you need to create a Timer that triggers a repaint.

Body:
I try to create a class that was similar to the famous Processing, but soon I found a problem, since in Processing there are the setup () and draw () functions, in to which it is possible to perform certain functions, such as square (10,10,50), I tried to imitate it by creating a class, in which there is a Graphics object called "gfx" to which the various figures are added. If you read this papyrus ... thank you and I put below the PFrame class (that is the one that imitates Processing) and the BohClass class which will be the test class.

package PFrame.com;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class PFrame {
    private JFrame frame = new JFrame();
    private DPane pane = new DPane(); //DPane is a class that extends JPanel

    private Graphics2D gfx;
    private Color selColor = new Color(255,255,255); //selected color
    private boolean fill = true; //the shapes are filled?

    public int width = 200, height = 200; //starting frame dimensins

    public PFrame() {
        //SKY
        pane.setPreferredSize(new Dimension(width,height));

        //HEAD
        title(); //this functions give to the frame the name of the class (in this case "BohClass")
        frame.setResizable(false);

        //BODY
        frame.add(pane);
        pane.addComponentListener(new ResizeListener());

        //TAIL
        size(width,height); //function that setting size
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        gfx = (Graphics2D) pane.getGraphics();

        pane.paint(); //DPane function
    }

    //--|METHODS|--//
    //FRAME CONFIG
    public final void size(int x, int y) {
        width = x;
        height = y;
        pane.setPreferredSize(new Dimension(width,height));
        frame.pack();
        frame.setLocationRelativeTo(null);
        gfx = (Graphics2D) pane.getGraphics();
    }
    public final void exit() {
        System.exit(0);
    }
    public final void hide() {
        frame.setVisible(false);
    }
    public final void show() {
        frame.setVisible(true);
    }
    public final void location(int XY) {
        frame.setLocation(XY,XY);
    }
    public final void location(int X, int Y) {
        frame.setLocation(X,Y);
    }
    public final void title() {
        frame.setTitle((getClass() + "").split(" ")[1]);
    }
    public final void title(Object title) {
        frame.setTitle(title.toString());
    }
    public final void resizable() {
        frame.setResizable(!frame.isResizable());
    }
    public final void resizable(boolean resizable) {
        frame.setResizable(resizable);
    }

    //2D CONFIG
    public final void fill(boolean fill) {
        this.fill = fill;
    }
    public final void color(int RGB) {
        selColor = new Color(RGB,RGB,RGB);
    }
    public final void color(int R, int G, int B) {
        selColor = new Color(R,G,B);
    }

    //2D
    public final void square(int X, int Y, int L) {
        rect(X,Y,L,L);
    }
    public final void square(int X, int Y, int L, int A) {
        rect(X,Y,L,L,A);
    }
    public final void square(int X, int Y, int L, int Ax, int Ay) {
        rect(X,Y,L,L,Ax,Ay);
    }
    public final void rect(int X, int Y, int W, int H) {
        gfx.setColor(selColor);
        if(fill) gfx.fillRect(X, Y, W, H);
        else gfx.drawRect(X, Y, W, H);
    }
    public final void rect(int X, int Y, int W, int H,int A) {
        gfx.setColor(selColor);
        if(fill) gfx.fillRoundRect(X, Y, W, H, A, A);
        else gfx.drawRoundRect(X, Y, W, H, A, A);
    }
    public final void rect(int X, int Y, int W, int H,int Ax, int Ay) {
        gfx.setColor(selColor);
        if(fill) gfx.fillRoundRect(X, Y, W, H, Ax, Ay);
        else gfx.drawRoundRect(X, Y, W, H, Ax, Ay);
    }
    public final void circle(int X, int Y, int d) {
        ellipse(X,Y,d,d);
    }
    public final void ellipse(int X, int Y, int W, int H) {
        gfx.setColor(selColor);
        if(fill) gfx.fillOval(X, Y, W, H);
        else gfx.drawOval(X, Y, W, H);
    }
    public final void triangle(int Ax, int Ay, int Bx, int By, int Cx, int Cy) {
        gfx.setColor(selColor);
        if(fill) gfx.fillPolygon(new Polygon(new int[] {Ax,Bx,Cx}, new int[] {Ay,By,Cy}, 3));
        else gfx.drawPolygon(new Polygon(new int[] {Ax,Bx,Cx}, new int[] {Ay,By,Cy}, 3));
    }

    //PANEL CONFIG
    public final void background(int RGB) {
        pane.setBackground(new Color(RGB,RGB,RGB));
    }
    public final void background(int R, int G, int B) {
        pane.setBackground(new Color(R,G,B));
    }
    public final void clear() {
        gfx.clearRect(0, 0, width, height);
    }

    //PUBLIC METHODS
    public void setup() {}
    public void loop() {}

    //PRIVATE CLASS PANEL
    private class DPane extends JPanel {
        private static final long serialVersionUID = 57423L;

        public void paint() {
            setup();

            while(true) {
                loop();
            }
        }
    }

    //LISTENERS
    class ResizeListener implements ComponentListener {
        public void componentResized(ComponentEvent e) {
            width = pane.getWidth();
            height = pane.getHeight();
        }
        public void componentMoved(ComponentEvent e) {}
        public void componentShown(ComponentEvent e) {}
        public void componentHidden(ComponentEvent e) {}
    }
}

and...

import PFrame.com.*;

public class BohClass extends PFrame {
    public void setup() {
        size(800,600);
        background(100);
    }
    public void loop() {
        color(72,28,47);
        triangle(60,10,10,60,110,60);
        color(255);
        square(12,12,123);
    }

    public static void main(String[] args) {
        new BohClass();
    }
}


问:
How can I create a dictionary from 2 lists, one representing keys and the other values?
As the question says, I have two lists that look like this:

```<code>list1 = ["key1", "key2"]
list2 = ["value1", "value2"]
</code>```

I would like to create a dictionary like this:

```<code>dict1 = {"key1": "value1" , "key2" : "value2"}
</code>```

Is there are an easy way to do so?

答:
my_dict = dict(zip(list1, list2))
```

Body:
As the question says, I have two lists that look like this:

list1 = ["key1", "key2"]
list2 = ["value1", "value2"]

I would like to create a dictionary like this:

dict1 = {"key1": "value1" , "key2" : "value2"}

Is there are an easy way to do so?

Body: my_dict = dict(zip(list1, list2))


问:
Styling part of label in legend in matplotlib
Is it possible to have part of the text of a legend in a particular style, let's say, bold or italic?

答:
Adding more options to the above answer by fixing the issues with that answer, with OO interface not just the state-based pyplot interface, possibility to have spaces as part of the text, boldface option in addition to italics:

```<code>ax.legend(handles=legend_handles,
          labels=legend_labels,
          loc='upper right',
          shadow=True,
          fancybox=True,
          facecolor='#C19A6B',
          title="$\\bf{BOLDFACED\ TITLE}$",     # to boldface title with space in between
          prop={'size': 12, 'style': 'italic'}  # properties for legend text
         )
</code>```

For italicized title with space in between replace the above title with,

```<code> title="$\\it{ITALICIZED\ TITLE}$",
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Adding more options to the above answer by fixing the issues with that answer, with OO interface not just the state-based pyplot interface, possibility to have spaces as part of the text, boldface option in addition to italics:

ax.legend(handles=legend_handles,
          labels=legend_labels,
          loc='upper right',
          shadow=True,
          fancybox=True,
          facecolor='#C19A6B',
          title="$\\bf{BOLDFACED\ TITLE}$",     # to boldface title with space in between
          prop={'size': 12, 'style': 'italic'}  # properties for legend text
         )

For italicized title with space in between replace the above title with,

 title="$\\it{ITALICIZED\ TITLE}$",


问:
getting some values in the table view rows in an iphone app
hii every one

i am new to iphone, i have done a sample data entry project in that i am saving data into the sqlite then displaying the saved data in the table view , & then on click of each row of the table it will go to other page (grouped table view where i am displying detailed data) now i have the table view like this

on click of each row it will go to detailed view like this

then on click of back button it ill come back to data list  screen but it ill add some other data into the screen like this

i am using reload data in view will apear ,, is that causing this problem?it works fine  if i comment that n try,,

can any one help me

thanx in advance

答:
When you add new row in the table upon back button press, you can either add a new row in the table using

```<code>insertRowsAtIndexPaths:withRowAnimation:
</code>```

or update your array (adding this extra row) with the help of which you show the rows and then reload the table view. Because when you reload your table view, its datasource methods will be called again and then you need to return updated number of sections, rows and cell's

Body:
When you add new row in the table upon back button press, you can either add a new row in the table using

insertRowsAtIndexPaths:withRowAnimation:

or update your array (adding this extra row) with the help of which you show the rows and then reload the table view. Because when you reload your table view, its datasource methods will be called again and then you need to return updated number of sections, rows and cell's


问:
How to add a separator to a WPF combobox that is databound?
Is there any way I can add a seprator into a WPF combobox that is databound?  ie in my xaml, the combobox's ItemsSource="{Binding TheList}".  The list is an observable collection of objects, one of i want separated from the rest.  This list is also generated from sql, so its not hard-coded or anything.  I wouldn't want the seaprator to be selectable, either.  Thanks!</p>

答:
If you want to do the same in C# code:</p>

```<code>Cbx.Items.Add("ABC");
Cbx.Items.Add("DEF");
ComboBoxItem item = new ComboBoxItem();
item.Content = "GHI";
item.BorderBrush = Brushes.Black;
item.BorderThickness = new Thickness(0, 0, 0, 2);
Cbx.Items.Add(item);
Cbx.Items.Add("KLM");
Cbx.Items.Add("NOP");
</code>```

Body:
If you want to do the same in C# code:

Cbx.Items.Add("ABC");
Cbx.Items.Add("DEF");
ComboBoxItem item = new ComboBoxItem();
item.Content = "GHI";
item.BorderBrush = Brushes.Black;
item.BorderThickness = new Thickness(0, 0, 0, 2);
Cbx.Items.Add(item);
Cbx.Items.Add("KLM");
Cbx.Items.Add("NOP");


问:
How to SUM with missing numbers substituted with most recent records
Suppose the game has 5 levels, and for each level players can gain a score of 1, 2 and 3. Player X has the following data:

```<code>Level | Attempt | Score
1     | 1       | 2
1     | 2       | 3
2     | 1       | 3
3     | 1       | 3
4     | 1       | 1
4     | 2       | 3
5     | 1       | 2
5     | 2       | 2
5     | 3       | 3
</code>```

Now that I want to SUM the scores GROUP BY attempt, but in a special way:

Attempt 1: Simply 2 + 3 + 3 + 1 + 3 = 12

Attempt 2: Now that Level 2 and 3 do not have Attempt 2, but I still want to use their most recent score to add up: 3 + 3 + 3 + 3 + 2 = 14

Attempt 3: Again I want to add up all levels with their most recent score (if there is no attempt 3), so I get 3 + 3 + 3 + 3 + 3 = 15

How can I do it with SQL? Please note that there is no limitation on the number of attempts, so a player may actually attempt a level 100 times and I have to provide 100 sums.

答:
Then, it could be something like this:</p>

```<code>WITH
-- your input ...
input(level,attempt,score) AS (
          SELECT 1,1,2
UNION ALL SELECT 1,2,3
UNION ALL SELECT 2,1,3
UNION ALL SELECT 3,1,3
UNION ALL SELECT 4,1,1
UNION ALL SELECT 4,2,3
UNION ALL SELECT 5,1,2
UNION ALL SELECT 5,2,2
UNION ALL SELECT 5,3,3
)
-- your input ends here
, -- replace comma with WITH in real query ..
-- creating a table with 5 rows per each of the 3 attempts
frame (level,attempt) AS (
  SELECT
     i.level
   , a.attempt
   FROM input i
   CROSS JOIN (
     SELECT DISTINCT
       attempt
     FROM input
    ) a
   WHERE i.attempt=1
)
-- SELECT * FROM frame; -- un-comment this line to test the frame table
,
gapfilled AS (
-- Query before GROUPing: left join the frame table with the input table
-- and fill the resulting NULLs using the LAST_VALUE ( ... IGNORE NULLS)
-- OLAP function. If you can take a previous one, pick it, if not , pick
-- a following one.
-- Vertica has named OLAP windows, which we use here - one forward, one backward
  SELECT
    frame.level
  , NVL(
      LAST_VALUE(input.attempt IGNORE NULLS) OVER(fwd)
    , LAST_VALUE(input.attempt IGNORE NULLS) OVER(bwd)
    )  AS attempt
  , NVL(
      LAST_VALUE(input.score   IGNORE NULLS) OVER(fwd)
    , LAST_VALUE(input.score   IGNORE NULLS) OVER(bwd)
    )  AS score
  FROM frame LEFT JOIN input USING(level,attempt)
  WINDOW fwd AS (PARTITION BY frame.attempt ORDER BY frame.level)
  ,      bwd AS (PARTITION BY frame.attempt ORDER BY frame.level DESC)
)
-- SELECT * FROM gapfilled ORDER BY 2,1; -- UN-comment to test gapfilled table
SELECT
  attempt
, SUM(score) AS score_sum
FROM gapfilled
GROUP BY
  attempt;
-- out  attempt | score_sum
-- out ---------+-----------
-- out        1 |        11
-- out        2 |        14
-- out        3 |        15

</code>```

Body:
Suppose the game has 5 levels, and for each level players can gain a score of 1, 2 and 3. Player X has the following data:

Level | Attempt | Score
1     | 1       | 2
1     | 2       | 3
2     | 1       | 3
3     | 1       | 3
4     | 1       | 1
4     | 2       | 3
5     | 1       | 2
5     | 2       | 2
5     | 3       | 3

Now that I want to SUM the scores GROUP BY attempt, but in a special way:

Attempt 1: Simply 2 + 3 + 3 + 1 + 3 = 12

Attempt 2: Now that Level 2 and 3 do not have Attempt 2, but I still want to use their most recent score to add up: 3 + 3 + 3 + 3 + 2 = 14

Attempt 3: Again I want to add up all levels with their most recent score (if there is no attempt 3), so I get 3 + 3 + 3 + 3 + 3 = 15

How can I do it with SQL? Please note that there is no limitation on the number of attempts, so a player may actually attempt a level 100 times and I have to provide 100 sums.

Body:
Then, it could be something like this:

WITH
-- your input ...
input(level,attempt,score) AS (
          SELECT 1,1,2
UNION ALL SELECT 1,2,3
UNION ALL SELECT 2,1,3
UNION ALL SELECT 3,1,3
UNION ALL SELECT 4,1,1
UNION ALL SELECT 4,2,3
UNION ALL SELECT 5,1,2
UNION ALL SELECT 5,2,2
UNION ALL SELECT 5,3,3
)
-- your input ends here
, -- replace comma with WITH in real query ..
-- creating a table with 5 rows per each of the 3 attempts
frame (level,attempt) AS (
  SELECT
     i.level
   , a.attempt
   FROM input i
   CROSS JOIN (
     SELECT DISTINCT
       attempt
     FROM input
    ) a
   WHERE i.attempt=1
)
-- SELECT * FROM frame; -- un-comment this line to test the frame table
,
gapfilled AS (
-- Query before GROUPing: left join the frame table with the input table
-- and fill the resulting NULLs using the LAST_VALUE ( ... IGNORE NULLS)
-- OLAP function. If you can take a previous one, pick it, if not , pick
-- a following one.
-- Vertica has named OLAP windows, which we use here - one forward, one backward
  SELECT
    frame.level
  , NVL(
      LAST_VALUE(input.attempt IGNORE NULLS) OVER(fwd)
    , LAST_VALUE(input.attempt IGNORE NULLS) OVER(bwd)
    )  AS attempt
  , NVL(
      LAST_VALUE(input.score   IGNORE NULLS) OVER(fwd)
    , LAST_VALUE(input.score   IGNORE NULLS) OVER(bwd)
    )  AS score
  FROM frame LEFT JOIN input USING(level,attempt)
  WINDOW fwd AS (PARTITION BY frame.attempt ORDER BY frame.level)
  ,      bwd AS (PARTITION BY frame.attempt ORDER BY frame.level DESC)
)
-- SELECT * FROM gapfilled ORDER BY 2,1; -- UN-comment to test gapfilled table
SELECT
  attempt
, SUM(score) AS score_sum
FROM gapfilled
GROUP BY
  attempt;
-- out  attempt | score_sum
-- out ---------+-----------
-- out        1 |        11
-- out        2 |        14
-- out        3 |        15


答:
A dictionary comprehension is perfect for this:

```<code>
dict1 = {k: v for k, v in zip(list1, list2)}

</code>```

Edit: it seems there is an even shorter solution, as per Sazzy's answer :)

Title: How can I create a dictionary from 2 lists, one representing keys and the other values?

Body:
A dictionary comprehension is perfect for this:

dict1 = {k: v for k, v in zip(list1, list2)}

Edit: it seems there is an even shorter solution, as per Sazzy's answer :)


问:
Flutter - CircularProgressIndicator always running
I do a search in database (firebase firestore) and I would like the screen to behave as follows: While the search is running, show a CircularProgressIndicator. When the search is finished, if data has been found, show the data. Otherwise, show the "records not found" message. My problem is that the CircularProgressIndicator display is in an eternal loop. What do I do?

```<code>  Stream<QuerySnapshot> getStreamOfBooks() {
    return bookCollection.snapshots();
  }
</code>```

j

```<code> body: StreamBuilder<QuerySnapshot>(
          stream: repository.getStreamOfBooks(),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.done) {
              if (snapshot.hasData) {
                return _buildList(context, snapshot.data.documents);
              } else {
                return Text("Records not found");
              }
            }
            else {
              return Dialog(
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.all(Radius.circular(10.0))),
                  child: new Row(
                      mainAxisSize: MainAxisSize.max,
                      children: <Widget>[
                        new CircularProgressIndicator(),
                        new Text("Loading")
                      ]));
            }
          })
</code>```

Edit 1 - Trying Future Builder

```<code>  Future<QuerySnapshot> getStreamOfBooks() async {
    bookCollection.snapshots();
  }

 body: FutureBuilder<QuerySnapshot>(
            future: repository.getStreamOfBooks(),
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.done) {
                return _buildList(context, snapshot.data.documents);
              }
              else if (snapshot.connectionState == ConnectionState.none) {
                return Text("No data");
              }
              return Dialog(
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.all(Radius.circular(10.0))),
                  child: new Row(
                      mainAxisSize: MainAxisSize.max,
                      children: <Widget>[
                        new CircularProgressIndicator(),
                        new Text("Loading")
                      ]));
            }),
</code>```

Error message: The following NoSuchMethodError was thrown building FutureBuilder(dirty, state: _FutureBuilderState#41a05):
The getter 'documents' was called on null.
Receiver: null
Tried calling: documents

答:
Change it to the following:

```<code>  Future<QuerySnapshot> getBooks() async {
    bookCollection.getDocuments();
  }

 body: FutureBuilder<QuerySnapshot>(
          future: repository.getBooks(),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.done) {
                return _buildList(context, snapshot.data.documents);
              }
              else if (snapshot.connectionState == ConnectionState.none) {
                return Text("No data");
              }
               return Dialog(
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.all(Radius.circular(10.0))),
                  child: new Row(
                      mainAxisSize: MainAxisSize.max,
                      children: <Widget>[
                        new CircularProgressIndicator(),
                        new Text("Loading")
                      ]));
          })
</code>```

ConnectionState.done means it returned data, ConnectionState.waiting means its still waiting for the asynchronous operation to finish, and ConnectionState.none means it returned no data.

Body:
I do a search in database (firebase firestore) and I would like the screen to behave as follows: While the search is running, show a CircularProgressIndicator. When the search is finished, if data has been found, show the data. Otherwise, show the "records not found" message. My problem is that the CircularProgressIndicator display is in an eternal loop. What do I do?

  Stream<QuerySnapshot> getStreamOfBooks() {
    return bookCollection.snapshots();
  }

j

 body: StreamBuilder<QuerySnapshot>(
          stream: repository.getStreamOfBooks(),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.done) {
              if (snapshot.hasData) {
                return _buildList(context, snapshot.data.documents);
              } else {
                return Text("Records not found");
              }
            }
            else {
              return Dialog(
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.all(Radius.circular(10.0))),
                  child: new Row(
                      mainAxisSize: MainAxisSize.max,
                      children: <Widget>[
                        new CircularProgressIndicator(),
                        new Text("Loading")
                      ]));
            }
          })

Edit 1 - Trying Future Builder

  Future<QuerySnapshot> getStreamOfBooks() async {
    bookCollection.snapshots();
  }

 body: FutureBuilder<QuerySnapshot>(
            future: repository.getStreamOfBooks(),
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.done) {
                return _buildList(context, snapshot.data.documents);
              }
              else if (snapshot.connectionState == ConnectionState.none) {
                return Text("No data");
              }
              return Dialog(
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.all(Radius.circular(10.0))),
                  child: new Row(
                      mainAxisSize: MainAxisSize.max,
                      children: <Widget>[
                        new CircularProgressIndicator(),
                        new Text("Loading")
                      ]));
            }),

Error message: The following NoSuchMethodError was thrown building FutureBuilder(dirty, state: _FutureBuilderState#41a05):
The getter 'documents' was called on null.
Receiver: null
Tried calling: documents

Body:
Change it to the following:

  Future<QuerySnapshot> getBooks() async {
    bookCollection.getDocuments();
  }

 body: FutureBuilder<QuerySnapshot>(
          future: repository.getBooks(),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.done) {
                return _buildList(context, snapshot.data.documents);
              }
              else if (snapshot.connectionState == ConnectionState.none) {
                return Text("No data");
              }
               return Dialog(
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.all(Radius.circular(10.0))),
                  child: new Row(
                      mainAxisSize: MainAxisSize.max,
                      children: <Widget>[
                        new CircularProgressIndicator(),
                        new Text("Loading")
                      ]));
          })

ConnectionState.done means it returned data, ConnectionState.waiting means its still waiting for the asynchronous operation to finish, and ConnectionState.none means it returned no data.


问:
pyomo mindtpy example program when run becomes unfeasible for binary variable
So I installed pyomo, glpk, and ipopt with anaconda,

When I run the example code here: https://pyomo.readthedocs.io/en/stable/contributed_packages/mindtpy.html

```<code>from pyomo.environ import *

model = ConcreteModel()

model.x = Var(bounds=(1.0,10.0),initialize=5.0)
model.y = Var(within=Binary)

model.c1 = Constraint(expr=(model.x-3.0)**2 <= 50.0*(1-model.y))
model.c2 = Constraint(expr=model.x*log(model.x)+5.0 <= 50.0*(model.y))

model.objective = Objective(expr=model.x, sense=minimize)
SolverFactory('mindtpy').solve(model, mip_solver='glpk', nlp_solver='ipopt',tee=True)

model.objective.display()
model.display()
model.pprint()
</code>```

I get the output that the binary variable has apparently become infeasible:

```<code>python minlpex.py
INFO: ---Starting MindtPy---
INFO: Original model has 2 constraints (2 nonlinear) and 0 disjunctions, with
    2 variables, of which 1 are binary, 0 are integer, and 1 are continuous.
INFO: NLP 1: Solve relaxed integrality
INFO: NLP 1: OBJ: 1.0  LB: 1.0  UB: inf
INFO: ---MindtPy Master Iteration 0---
INFO: MIP 1: Solve master problem.
WARNING: Empty constraint block written in LP format - solver may error
Traceback (most recent call last):
  File "minlpex.py", line 13, in <module>
    op.SolverFactory('mindtpy').solve(model, mip_solver='glpk', nlp_solver='ipopt',tee=True)
  File "/anaconda3/envs/py36/lib/python3.6/site-packages/pyomo/contrib/mindtpy/MindtPy.py", line 370, in solve
    MindtPy_iteration_loop(solve_data, config)
  File "/anaconda3/envs/py36/lib/python3.6/site-packages/pyomo/contrib/mindtpy/iterate.py", line 30, in MindtPy_iteration_loop
    handle_master_mip_optimal(master_mip, solve_data, config)
  File "/anaconda3/envs/py36/lib/python3.6/site-packages/pyomo/contrib/mindtpy/mip_solve.py", line 62, in handle_master_mip_optimal
    config)
  File "/anaconda3/envs/py36/lib/python3.6/site-packages/pyomo/contrib/gdpopt/util.py", line 199, in copy_var_list_values
    v_to.set_value(value(v_from, exception=False))
  File "/anaconda3/envs/py36/lib/python3.6/site-packages/pyomo/core/base/var.py", line 173, in set_value
    if valid or self._valid_value(val):
  File "/anaconda3/envs/py36/lib/python3.6/site-packages/pyomo/core/base/var.py", line 185, in _valid_value
    "domain %s" % (val, type(val), self.domain))
ValueError: Numeric value `0.22709088987977885` (<class 'float'>) is not in domain Binary
</code>```

So I was a little confused, since this was a code provided, I would not expect it to error like this. So I feel like I'm messing something up or I am missing some required library?

Thanks a lot.

答:
Looks like something must be wrong with the conda pyomo install or ipopt install.

When I reinstalled using pip for ipopt and compiling pyomo from github source everything works fine.

Body:
So I installed pyomo, glpk, and ipopt with anaconda,

When I run the example code here: https://pyomo.readthedocs.io/en/stable/contributed_packages/mindtpy.html

from pyomo.environ import *

model = ConcreteModel()

model.x = Var(bounds=(1.0,10.0),initialize=5.0)
model.y = Var(within=Binary)

model.c1 = Constraint(expr=(model.x-3.0)**2 <= 50.0*(1-model.y))
model.c2 = Constraint(expr=model.x*log(model.x)+5.0 <= 50.0*(model.y))

model.objective = Objective(expr=model.x, sense=minimize)
SolverFactory('mindtpy').solve(model, mip_solver='glpk', nlp_solver='ipopt',tee=True)

model.objective.display()
model.display()
model.pprint()

I get the output that the binary variable has apparently become infeasible:

python minlpex.py
INFO: ---Starting MindtPy---
INFO: Original model has 2 constraints (2 nonlinear) and 0 disjunctions, with
    2 variables, of which 1 are binary, 0 are integer, and 1 are continuous.
INFO: NLP 1: Solve relaxed integrality
INFO: NLP 1: OBJ: 1.0  LB: 1.0  UB: inf
INFO: ---MindtPy Master Iteration 0---
INFO: MIP 1: Solve master problem.
WARNING: Empty constraint block written in LP format - solver may error
Traceback (most recent call last):
  File "minlpex.py", line 13, in <module>
    op.SolverFactory('mindtpy').solve(model, mip_solver='glpk', nlp_solver='ipopt',tee=True)
  File "/anaconda3/envs/py36/lib/python3.6/site-packages/pyomo/contrib/mindtpy/MindtPy.py", line 370, in solve
    MindtPy_iteration_loop(solve_data, config)
  File "/anaconda3/envs/py36/lib/python3.6/site-packages/pyomo/contrib/mindtpy/iterate.py", line 30, in MindtPy_iteration_loop
    handle_master_mip_optimal(master_mip, solve_data, config)
  File "/anaconda3/envs/py36/lib/python3.6/site-packages/pyomo/contrib/mindtpy/mip_solve.py", line 62, in handle_master_mip_optimal
    config)
  File "/anaconda3/envs/py36/lib/python3.6/site-packages/pyomo/contrib/gdpopt/util.py", line 199, in copy_var_list_values
    v_to.set_value(value(v_from, exception=False))
  File "/anaconda3/envs/py36/lib/python3.6/site-packages/pyomo/core/base/var.py", line 173, in set_value
    if valid or self._valid_value(val):
  File "/anaconda3/envs/py36/lib/python3.6/site-packages/pyomo/core/base/var.py", line 185, in _valid_value
    "domain %s" % (val, type(val), self.domain))
ValueError: Numeric value `0.22709088987977885` (<class 'float'>) is not in domain Binary

So I was a little confused, since this was a code provided, I would not expect it to error like this. So I feel like I'm messing something up or I am missing some required library?

Thanks a lot.


问:
NoReverseMatch at /basketball/ Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) tried:
I have a Django app where a user can create a Basketball object using the Basketball model and post it to a feed that is a ListView subclass. I then want other users to be able to access the details of that post by clicking the hyperlink for the object.

The problem is, when I set the url for the details page to contain the variable "slug" as the object slug, it overwrites my list page with the url route "" as seen in basketball/urls.py, instead of routing to the list page it says it can't find a page with an empty slug. This does not allow me to get to the url "http://127.0.0.1:8000/basketball/"

I'm working under the impression Django searched for url routes in order, so since the blank path is the first route it should be seen before the route containing the slug.

Note the piece of code that is directly causing the issue is in basketball_list.html:

```<code><a href= "{% url 'basketball:detail' basketball.slug %}">
</code>```

when this code is removed I am able to access "http://127.0.0.1:8000/basketball/" but the hyperlinks aren't there so it defeats the purpose.

Note that I am using:
Python == 3.8.3
Django == 3.0.6

models.py:

```<code>from django.db import models

from django.db import models
from django.urls import reverse
from django.conf import settings
from django.utils.text import slugify

from autoslug import AutoSlugField
from model_utils.models import TimeStampedModel

from nba_api.stats.static import players

PLAYER_CHOICES = [(i['full_name'], i['full_name']) for i in players.get_active_players()]

class Basketball(TimeStampedModel):
    player = models.CharField(max_length = 50, choices = PLAYER_CHOICES, default = None)
    slug = AutoSlugField("Basketball Player", unique = True, populate_from ="player")
    creator = models.ForeignKey(settings.AUTH_USER_MODEL,
    null = True,
    on_delete = models.SET_NULL
    )

    def get_absolute_url(self):
        return reverse(
        'basketball:detail', kwargs={'slug': self.slug}
        )

    def __str__(self):
        return f"{self.creator} posted about: {self.player}"

</code>```

views.py:

```<code>from django.shortcuts import render
from django.views.generic import ListView, CreateView, DetailView
from django.contrib.auth.mixins import LoginRequiredMixin

from .models import Basketball

class BasketballListView(LoginRequiredMixin, ListView):
    model = Basketball

class BasketballDetailView(DetailView):
    model = Basketball

class BasketballCreateView(LoginRequiredMixin, CreateView):
    model = Basketball
    fields = [
    'player',
    ]

    def form_valid(self, form):
        form.instance.creator =self.request.user
        return super().form_valid(form)
</code>```

urls.py:

```<code># wtg/basketball/urls.py
from django.urls import path
from . import views

app_name = "basketball"
urlpatterns = [
    path(
    route='',
    view=views.BasketballListView.as_view(),
    name='list',
    ),
    path(
    route='add/',
    view=views.BasketballCreateView.as_view(),
    name='add',
    ),
    path(
    route='<slug:slug>/',
    view=views.BasketballDetailView.as_view(),
    name='detail'
    ),
]
</code>```

basketball_list.html:

```<code>{% extends 'base.html' %}

{% block title %}Basketball List{% endblock title %}

{% block content %}
  <h2>Basketball List</h2>

<ul>
  {% for x in basketball_list %}
    <li><a href= "{% url 'basketball:detail' basketball.slug %}">{{ x }}</a></li>

  {% endfor %}
</ul>

<hr/>
<p>Post Own Info?</p>
  <p>
    <a class="btn btn-primary"
      href="{% url 'basketball:add' %}" role="button">
      Add Post
    </a>
</p>
{% endblock content %}
</code>```

base urls.py:

```<code>urlpatterns = [
    path(
        "",
        TemplateView.as_view(template_name="pages/home.html"),
        name="home",
    ),
    path(
        "about/",
        TemplateView.as_view(template_name="pages/about.html"),
        name="about",
    ),
    # Django Admin, use {% url 'admin:index' %}
    path(settings.ADMIN_URL, admin.site.urls),
    # User management
    path(
        "users/",
        include("wtg.users.urls", namespace="users"),
    ),
    path("accounts/", include("allauth.urls")),
    # Your stuff: custom urls includes go here
    path(
    'basketball/',
    include('wtg.basketball.urls', namespace='basketball')
    ),
    path(
    "^activity/",
    include("actstream.urls")
    ),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code>```

答:
Your url doesn't match basketball_list loop variable (x). This

```<code>{% for x in basketball_list %}
  <li><a href= "{% url 'basketball:detail' basketball.slug %}">{{ x }}</a></li>
{% endfor %}
</code>```

should be

```<code>{% for x in basketball_list %}
  <li><a href= "{% url 'basketball:detail' x.slug %}">{{ x }}</a></li>
{% endfor %}
</code>```

Body:
I have a Django app where a user can create a Basketball object using the Basketball model and post it to a feed that is a ListView subclass. I then want other users to be able to access the details of that post by clicking the hyperlink for the object.

The problem is, when I set the url for the details page to contain the variable "slug" as the object slug, it overwrites my list page with the url route "" as seen in basketball/urls.py, instead of routing to the list page it says it can't find a page with an empty slug. This does not allow me to get to the url "http://127.0.0.1:8000/basketball/"

I'm working under the impression Django searched for url routes in order, so since the blank path is the first route it should be seen before the route containing the slug.

Note the piece of code that is directly causing the issue is in basketball_list.html:

when this code is removed I am able to access "http://127.0.0.1:8000/basketball/" but the hyperlinks aren't there so it defeats the purpose.

Note that I am using:
Python == 3.8.3
Django == 3.0.6

models.py:

from django.db import models

from django.db import models
from django.urls import reverse
from django.conf import settings
from django.utils.text import slugify

from autoslug import AutoSlugField
from model_utils.models import TimeStampedModel

from nba_api.stats.static import players

PLAYER_CHOICES = [(i['full_name'], i['full_name']) for i in players.get_active_players()]

class Basketball(TimeStampedModel):
    player = models.CharField(max_length = 50, choices = PLAYER_CHOICES, default = None)
    slug = AutoSlugField("Basketball Player", unique = True, populate_from ="player")
    creator = models.ForeignKey(settings.AUTH_USER_MODEL,
    null = True,
    on_delete = models.SET_NULL
    )

    def get_absolute_url(self):
        return reverse(
        'basketball:detail', kwargs={'slug': self.slug}
        )

    def __str__(self):
        return f"{self.creator} posted about: {self.player}"

views.py:

from django.shortcuts import render
from django.views.generic import ListView, CreateView, DetailView
from django.contrib.auth.mixins import LoginRequiredMixin

from .models import Basketball

class BasketballListView(LoginRequiredMixin, ListView):
    model = Basketball

class BasketballDetailView(DetailView):
    model = Basketball

class BasketballCreateView(LoginRequiredMixin, CreateView):
    model = Basketball
    fields = [
    'player',
    ]

    def form_valid(self, form):
        form.instance.creator =self.request.user
        return super().form_valid(form)

urls.py:

# wtg/basketball/urls.py
from django.urls import path
from . import views

app_name = "basketball"
urlpatterns = [
    path(
    route='',
    view=views.BasketballListView.as_view(),
    name='list',
    ),
    path(
    route='add/',
    view=views.BasketballCreateView.as_view(),
    name='add',
    ),
    path(
    route='<slug:slug>/',
    view=views.BasketballDetailView.as_view(),
    name='detail'
    ),
]

basketball_list.html:

{% extends 'base.html' %}

{% block title %}Basketball List{% endblock title %}

{% block content %}

Basketball List

  {% for x in basketball_list %}

{{ x }}

  {% endfor %}

Post Own Info?

      Add Post

{% endblock content %}

base urls.py:

urlpatterns = [
    path(
        "",
        TemplateView.as_view(template_name="pages/home.html"),
        name="home",
    ),
    path(
        "about/",
        TemplateView.as_view(template_name="pages/about.html"),
        name="about",
    ),
    # Django Admin, use {% url 'admin:index' %}
    path(settings.ADMIN_URL, admin.site.urls),
    # User management
    path(
        "users/",
        include("wtg.users.urls", namespace="users"),
    ),
    path("accounts/", include("allauth.urls")),
    # Your stuff: custom urls includes go here
    path(
    'basketball/',
    include('wtg.basketball.urls', namespace='basketball')
    ),
    path(
    "^activity/",
    include("actstream.urls")
    ),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Body:
Your url doesn't match basketball_list loop variable (x). This

{% for x in basketball_list %}
  <li><a href= "{% url 'basketball:detail' basketball.slug %}">{{ x }}</a></li>
{% endfor %}

should be

{% for x in basketball_list %}
  <li><a href= "{% url 'basketball:detail' x.slug %}">{{ x }}</a></li>
{% endfor %}


问:
Jenkins pipeline: execute steps in parallel dynamically
In our Jenkins pipeline we use the following function to execute a set of deployment tasks in parallelized chunks:

```<code>def runParallel(tasks, count) {
    while (tasks.size() > 0) {
        parallel tasks.take(count)
        tasks = tasks.drop(count)
    }
}
</code>```

With the count parameter we control how many of the tasks are executed in parallel, so the network isn't overwhelmed with too many parallel deployments.

This works nicely, but has the downside that if one task in a chunk takes a very long time, the next chunk has to wait until the previous chunk is completely finished. Even though just one task is currently being executed and there are enough resources available to start count - 1 new tasks.

So what we actually need is not splitting the tasks into fixed-size chunks with count tasks, but rather a sliding window approach that iterates over tasks with a window size of count and moves to the next task as soon as the first task inside the window is finished. This way we wouldn't have the wait times our chunk-based approach has.

AFAIK it's not possible to add more tasks to a parallel step after it has been started. But maybe there is a work-around?

Ideally parallel would take a parameter that controls the degree of parallelization. Then we could just do:

```<code>parallel tasks, count
</code>```

答:
It seems you’re very lucky, since there was a plugin released some some weeks ago, with which you can archive this: Jenkins Concurrent Step Plugin.

The original issue for this problem

Example pipeline with a semaphore:

```<code>pipeline {
  agent any

  stages {
    stage('test') {
      steps {
        script {
          def semaphore = createSemaphore permit: 1
          boolean out = false
          parallel(
            semaphore1: {
              acquireSemaphore (semaphore) {
                echo "out=${out}"
              }
            },
            semaphore2: {
              acquireSemaphore (semaphore) {
                sleep 30
                echo "out=${out}"
              }
            },
            semaphore3: {
              acquireSemaphore (semaphore) {
                sleep 10
                echo "out=${out}"
              }
            },
            semaphore4: {
              acquireSemaphore (semaphore) {
                sleep 10
                echo "out=${out}"
              }
            }
          )
        }
      }
    }
  }
}
</code>```

Body:
In our Jenkins pipeline we use the following function to execute a set of deployment tasks in parallelized chunks:

def runParallel(tasks, count) {
    while (tasks.size() > 0) {
        parallel tasks.take(count)
        tasks = tasks.drop(count)
    }
}

With the count parameter we control how many of the tasks are executed in parallel, so the network isn't overwhelmed with too many parallel deployments.

This works nicely, but has the downside that if one task in a chunk takes a very long time, the next chunk has to wait until the previous chunk is completely finished. Even though just one task is currently being executed and there are enough resources available to start count - 1 new tasks.

So what we actually need is not splitting the tasks into fixed-size chunks with count tasks, but rather a sliding window approach that iterates over tasks with a window size of count and moves to the next task as soon as the first task inside the window is finished. This way we wouldn't have the wait times our chunk-based approach has.

AFAIK it's not possible to add more tasks to a parallel step after it has been started. But maybe there is a work-around?

Ideally parallel would take a parameter that controls the degree of parallelization. Then we could just do:

parallel tasks, count

Body:
It seems you’re very lucky, since there was a plugin released some some weeks ago, with which you can archive this: Jenkins Concurrent Step Plugin.

The original issue for this problem

Example pipeline with a semaphore:

pipeline {
  agent any

  stages {
    stage('test') {
      steps {
        script {
          def semaphore = createSemaphore permit: 1
          boolean out = false
          parallel(
            semaphore1: {
              acquireSemaphore (semaphore) {
                echo "out=${out}"
              }
            },
            semaphore2: {
              acquireSemaphore (semaphore) {
                sleep 30
                echo "out=${out}"
              }
            },
            semaphore3: {
              acquireSemaphore (semaphore) {
                sleep 10
                echo "out=${out}"
              }
            },
            semaphore4: {
              acquireSemaphore (semaphore) {
                sleep 10
                echo "out=${out}"
              }
            }
          )
        }
      }
    }
  }
}


问:
select Value in one listbox should affect all other list boxes
i have three list boxes name as state,District, and college. All list boxes contains a value as "All". if i select all in state list box the other list boxes district and college should change as "All". How to make it? i have done changes for two list boxes. i couldn't make for the third one.

```<code>ex :   1. State -
                a) xxxxxxx
                b) yyyyyyy
                c) zzzzzzz
                d) All

          2. District -
               a) aaaaaaa
               b) bbbbbbb
               c) All

          3. College -
               a) aaaaaaa
               b) All
</code>```

see there, if i click "All" in a state list box the District and College Should come as all.
before that i have done if i click "All" in district list box the college sholud change as "All" . How to write code in onChange??

Thanks in advance.

答:
In jQuery you could do something like this:

```<code><select id="state" size="3">
    <option value="0">state1</option>
    <option value="1">state2</option>
    <option value="all">All</option>
</select>

<select id="district" size="3">
    <option value="0">district1</option>
    <option value="1">district9</option>
    <option value="all">All</option>
</select>

<select id="collage" size="3">
    <option value="0">collage1</option>
    <option value="1">collage2</option>
    <option value="all">All</option>
</select>

<script type="text/javascript">
    $('#state').click(function() {
        if ($(this).val() == 'all') {
            $('#district').val('all');
            $('#collage').val('all');
        }
    });
    $('#district').click(function() {
        if ($(this).val() == 'all') $('#collage').val('all');
    });
</script>
</code>```

See http://jsfiddle.net/CDMWK/3/

Body:
i have three list boxes name as state,District, and college. All list boxes contains a value as "All". if i select all in state list box the other list boxes district and college should change as "All". How to make it? i have done changes for two list boxes. i couldn't make for the third one.

ex :   1. State -
                a) xxxxxxx
                b) yyyyyyy
                c) zzzzzzz
                d) All

          2. District -
               a) aaaaaaa
               b) bbbbbbb
               c) All

          3. College -
               a) aaaaaaa
               b) All

see there, if i click "All" in a state list box the District and College Should come as all.
before that i have done if i click "All" in district list box the college sholud change as "All" . How to write code in onChange??

Thanks in advance.

Body:
In jQuery you could do something like this:

<select id="state" size="3">
    <option value="0">state1</option>
    <option value="1">state2</option>
    <option value="all">All</option>
</select>

<select id="district" size="3">
    <option value="0">district1</option>
    <option value="1">district9</option>
    <option value="all">All</option>
</select>

<select id="collage" size="3">
    <option value="0">collage1</option>
    <option value="1">collage2</option>
    <option value="all">All</option>
</select>

<script type="text/javascript">
    $('#state').click(function() {
        if ($(this).val() == 'all') {
            $('#district').val('all');
            $('#collage').val('all');
        }
    });
    $('#district').click(function() {
        if ($(this).val() == 'all') $('#collage').val('all');
    });
</script>

See http://jsfiddle.net/CDMWK/3/


问:
Conversion from int to char failed and console prints weird symbol
I am having a weird issue and I don't know how to explain it. When I run this code it prints this symbol -> .
This is my code:

```<code>#include <iostream>

int main() {
     int num = 1;
     char number = num;

     std::cout<<number<<std::endl;

     system("PAUSE");
     return 0;
}
</code>```

I don't understand why. Normally it should convert the integer to char. I am using Dev C++ and my language standard is ISO C++11. I am programming for 4 years now and this is the first time I get something like this. I hope I explained my issue and if someone can help me I will be grateful.

答:
Conversion from int to char failed

Actually, int was successfully converted to char.

Normally it should convert the integer to char.

That's what it did. The result of the conversion is char with the value 1.

Computers use a "character encoding". Each symbol that you see on the screen is encoded as a number. For example (assuming ASCII or compatible encoding) the value of 'a' character is 97.

A char with value of 1 is not the same as char with the value that encodes the character '1'. As such, when you print a character with value 1, you don't see the number 1, but the character that the value 1 encodes. In the ASCII and compatible encodings, 1 encodes a non-visible symbol "start of heading".

I wanted to print 1 as a char.

You can do it like this:

```<code>std::cout << '1' << '\n';
</code>```

Body:
I am having a weird issue and I don't know how to explain it. When I run this code it prints this symbol -> .
This is my code:

#include <iostream>

int main() {
     int num = 1;
     char number = num;

     std::cout<<number<<std::endl;

     system("PAUSE");
     return 0;
}

I don't understand why. Normally it should convert the integer to char. I am using Dev C++ and my language standard is ISO C++11. I am programming for 4 years now and this is the first time I get something like this. I hope I explained my issue and if someone can help me I will be grateful.

Body:
Conversion from int to char failed

Actually, int was successfully converted to char.

Normally it should convert the integer to char.

That's what it did. The result of the conversion is char with the value 1.

Computers use a "character encoding". Each symbol that you see on the screen is encoded as a number. For example (assuming ASCII or compatible encoding) the value of 'a' character is 97.

A char with value of 1 is not the same as char with the value that encodes the character '1'. As such, when you print a character with value 1, you don't see the number 1, but the character that the value 1 encodes. In the ASCII and compatible encodings, 1 encodes a non-visible symbol "start of heading".

I wanted to print 1 as a char.

You can do it like this:

std::cout << '1' << '\n';


问:
Read the DOM of an html page with an http call or the like
I have an HTML page at the following address:

https://www2.casailaria.it/news/

I wish I could read some elements of the DOM with an http call via javascript.
I'm trying them all, but I still have that damned console error: CORS header "Access-Control-Allow-Origin" missing.

I tried the following ajax call without success, studding it with alleged parameters:

```<code><!DOCTYPE html>
<html lang="it">

<head>
    <meta charset="utf-8" />
    <title>MAURIZIO</title>
    <link rel="stylesheet" type="text/css" href="background.css">
</head>

<body>
    <script src="https://code.jquery.com/jquery-3.5.1.js"
        integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
    <script>
        $.ajax("https://www2.casailaria.it/news/", {
            dataType: "jsonp",
            cors: true,
            secure: true,
            headers: {
                'Access-Control-Allow-Origin': '*', // or 'Access-Control-Allow-Headers: x-requested-with'
            },
            success: function (response) {
                console.log(response);
            }
        });
    </script>
</body>

</html>
</code>```

I hope I'm not too far from the solution, and I think I'm going around it. Once obtained I would simply like to do operations like: response.getElementsByClassName('myClassOfOtherPage')

What do I have to add/remove to make it work well?

Other javascript solutions are welcome as well as ajax calls, as long as they are part of the CDN.

Thanks in advance!

答:
CORS is meant to protect the user from stealing sessions and data on other websites where the user is logged in.

The page that you are trying to load through AJaX is hosted on a different domain.

If you are developing locally, and just want to test, you can start Chrome with a flag to ignore CORS. Here is how to do that

If you want to host your page on a different domain, you need to add the CORS header to https://www2.casailaria.it/news/. If that page is created using PHP, you can add this to that page:

header("Access-Control-Allow-Origin: *");
```

Note that * is not safe. It should be the domain of the page from which the AJaX call is originating.

Body:
I have an HTML page at the following address:

https://www2.casailaria.it/news/

I wish I could read some elements of the DOM with an http call via javascript.
I'm trying them all, but I still have that damned console error: CORS header "Access-Control-Allow-Origin" missing.

I tried the following ajax call without success, studding it with alleged parameters:

<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>MAURIZIO</title>
    <link rel="stylesheet" type="text/css" href="background.css">

I hope I'm not too far from the solution, and I think I'm going around it. Once obtained I would simply like to do operations like: response.getElementsByClassName('myClassOfOtherPage')

What do I have to add/remove to make it work well?

Other javascript solutions are welcome as well as ajax calls, as long as they are part of the CDN.

Thanks in advance!

Body:
CORS is meant to protect the user from stealing sessions and data on other websites where the user is logged in.

The page that you are trying to load through AJaX is hosted on a different domain.

If you are developing locally, and just want to test, you can start Chrome with a flag to ignore CORS. Here is how to do that

If you want to host your page on a different domain, you need to add the CORS header to https://www2.casailaria.it/news/. If that page is created using PHP, you can add this to that page:

header("Access-Control-Allow-Origin: *");

Note that * is not safe. It should be the domain of the page from which the AJaX call is originating.