问:
Why does postgres say operator does not exist: json ? unknown
I have the following query which I'm trying to run against my postgres database:

```<code>select distinct offer_id from offers
    where listing_id = 2299392
    group by offer_id
    having not bool_or(status in ('Rejected', 'Draft') or (status = 'Pending' and expiry_date < now())
        or (seller_t_and_c_accepted = true and buyer_t_and_c_accepted = true and
            (   (seller_conditions = null and buyer_conditions = null) -- neither buyer nor seller have any conditions
                -- seller has conditions and they are all done
                or (buyer_conditions = null and not exists (select * from json_each(offers.seller_conditions::json) as sc(key,val) where (sc.val -> 'done')::text = 'false' or sc.val ? 'done'))
                -- buyer has conditions and they are all done
                or (seller_conditions = null and not exists (select * from json_each(offers.buyer_conditions::json) as bc(key,val) where (bc.val -> 'done')::text = 'false' or bc.val ? 'done'))
                -- both buyer and seller have conditions and they are all done
                or (not exists (select * from json_each(offers.buyer_conditions::json) as bc(key,val) where (bc.val -> 'done')::text = 'false' or sc.val ? 'done') and not exists (select * from json_each(offers.seller_conditions::json) as sc(key,val) where (sc.val -> 'done')::text = 'false' or sc.val ? 'done'))
            )
        )
    )
</code>```

I'm getting the error:

```<code>operator does not exist: json ? unknown
</code>```

This happens when I add the following pieces to the above query:

```<code>sc.val ? 'done'

...

bc.val ? 'done'
</code>```

I'm no sql or postgres expert, but I think json_object ? 'field' is supposed to returns true if 'field' is the name of a field that exists in the json object, and false otherwise (i.e. if it doesn't exist in the json object).

I don't think you need to know what I'm trying to accomplish in the query above but it might help, so I'll break it down for you.

I'm trying to get all active offers for a given real estate listing (in this case, listing with id 2299392). An active offer on a listing is an offer that is not rejected, not in draft, not expired, and not complete. A 'complete' offer is an offer in which both the buyer and the seller have accepted the terms and conditions and all the buyer's conditions (if any) are met and all the seller's conditions (if any) are met.

It's the conditions for a 'complete' offer in the query above that are most convoluted, so I'll break that down further. It starts with this:

```<code>...or (seller_t_and_c_accepted = true and buyer_t_and_c_accepted = true and
</code>```

Buyer and seller have both accepted the terms and conditions...

```<code>(   (seller_conditions = null and buyer_conditions = null) or ...
</code>```

covers the case where neither the buyer nor the seller have any conditions.

```<code>(buyer_conditions = null and not exists (select * from json_each(offers.seller_conditions::json) as sc(key,val) where (sc.val -> 'done')::text = 'false' or sc.val ? 'done')) or...
</code>```

covers the case where the buyer has no conditions but the seller does. The conditions are stored as a json object:

```<code>{
  "Subject to financing": {"date": "2020-03-19", "time": "2100", "done": false},
  "Subject to inspection": {"date": "2020-03-19", "time": "2100", "done": true}
}
</code>```

It's essentially a series of conditions, each of which is itself a json object consisting of a deadline (date and time) and whether or not it has been met (done).

In order to parse through this to see if all conditions are met, I have a nested select:

```<code>select * from json_each(offers.seller_conditions::json) as sc(key,val) where (sc.val -> 'done')::text = 'false' or sc.val ? 'done'
</code>```

I am looping through all conditions with json_each and getting key/value pairs (so the key might be "subject to financing" and the value is {"date": "2020-03-19", "time": "2100", "done": false}). Then I'm checking the value to see if the 'done' field is false (meaning this condition is not satisfied and therefore belongs in my results). I also check that the value HAS a field called 'done' (because sometimes it won't, as in: {"date": "2020-03-19", "time": "2100"}). <-- It's this part which is throwing the error: operator does not exist: json ? unknown.

Anyway, the rest is more of the same:

```<code>(seller_conditions = null and not exists (select * from json_each(offers.buyer_conditions::json) as bc(key,val) where (bc.val -> 'done')::text = 'false' or bc.val ? 'done')) or ...
</code>```

covers the case where the seller has no conditions but the buyer does, and:

```<code>(not exists (select * from json_each(offers.buyer_conditions::json) as bc(key,val) where (bc.val -> 'done')::text = 'false' or sc.val ? 'done') and not exists (select * from json_each(offers.seller_conditions::json) as sc(key,val) where (sc.val -> 'done')::text = 'false' or sc.val ? 'done'))
</code>```

covers the case where both the buyer and the seller have conditions.

Anyway, does anyone see why it would tell me that the ? operator does not exist? Am I writing it wrong? Is there another way of accomplishing what I want? Thanks.

答:
The ? operator is only defined for jsonb, not for json.  Notice the docs have two tables, one for dual typed operators and one for jsonb only.

You will need to cast the value to jsonb.  Ideally you would change the column type to jsonb, then use jsonb operators/functions all the way down.

Body:
I have the following query which I'm trying to run against my postgres database:

select distinct offer_id from offers
    where listing_id = 2299392
    group by offer_id
    having not bool_or(status in ('Rejected', 'Draft') or (status = 'Pending' and expiry_date < now())
        or (seller_t_and_c_accepted = true and buyer_t_and_c_accepted = true and
            (   (seller_conditions = null and buyer_conditions = null) -- neither buyer nor seller have any conditions
                -- seller has conditions and they are all done
                or (buyer_conditions = null and not exists (select * from json_each(offers.seller_conditions::json) as sc(key,val) where (sc.val -> 'done')::text = 'false' or sc.val ? 'done'))
                -- buyer has conditions and they are all done
                or (seller_conditions = null and not exists (select * from json_each(offers.buyer_conditions::json) as bc(key,val) where (bc.val -> 'done')::text = 'false' or bc.val ? 'done'))
                -- both buyer and seller have conditions and they are all done
                or (not exists (select * from json_each(offers.buyer_conditions::json) as bc(key,val) where (bc.val -> 'done')::text = 'false' or sc.val ? 'done') and not exists (select * from json_each(offers.seller_conditions::json) as sc(key,val) where (sc.val -> 'done')::text = 'false' or sc.val ? 'done'))
            )
        )
    )

I'm getting the error:

operator does not exist: json ? unknown

This happens when I add the following pieces to the above query:

sc.val ? 'done'

...

bc.val ? 'done'

I'm no sql or postgres expert, but I think json_object ? 'field' is supposed to returns true if 'field' is the name of a field that exists in the json object, and false otherwise (i.e. if it doesn't exist in the json object).

I don't think you need to know what I'm trying to accomplish in the query above but it might help, so I'll break it down for you.

I'm trying to get all active offers for a given real estate listing (in this case, listing with id 2299392). An active offer on a listing is an offer that is not rejected, not in draft, not expired, and not complete. A 'complete' offer is an offer in which both the buyer and the seller have accepted the terms and conditions and all the buyer's conditions (if any) are met and all the seller's conditions (if any) are met.

It's the conditions for a 'complete' offer in the query above that are most convoluted, so I'll break that down further. It starts with this:

...or (seller_t_and_c_accepted = true and buyer_t_and_c_accepted = true and

Buyer and seller have both accepted the terms and conditions...

(   (seller_conditions = null and buyer_conditions = null) or ...

covers the case where neither the buyer nor the seller have any conditions.

(buyer_conditions = null and not exists (select * from json_each(offers.seller_conditions::json) as sc(key,val) where (sc.val -> 'done')::text = 'false' or sc.val ? 'done')) or...

covers the case where the buyer has no conditions but the seller does. The conditions are stored as a json object:

{
  "Subject to financing": {"date": "2020-03-19", "time": "2100", "done": false},
  "Subject to inspection": {"date": "2020-03-19", "time": "2100", "done": true}
}

It's essentially a series of conditions, each of which is itself a json object consisting of a deadline (date and time) and whether or not it has been met (done).

In order to parse through this to see if all conditions are met, I have a nested select:

select * from json_each(offers.seller_conditions::json) as sc(key,val) where (sc.val -> 'done')::text = 'false' or sc.val ? 'done'

I am looping through all conditions with json_each and getting key/value pairs (so the key might be "subject to financing" and the value is {"date": "2020-03-19", "time": "2100", "done": false}). Then I'm checking the value to see if the 'done' field is false (meaning this condition is not satisfied and therefore belongs in my results). I also check that the value HAS a field called 'done' (because sometimes it won't, as in: {"date": "2020-03-19", "time": "2100"}). <-- It's this part which is throwing the error: operator does not exist: json ? unknown.

Anyway, the rest is more of the same:

(seller_conditions = null and not exists (select * from json_each(offers.buyer_conditions::json) as bc(key,val) where (bc.val -> 'done')::text = 'false' or bc.val ? 'done')) or ...

covers the case where the seller has no conditions but the buyer does, and:

(not exists (select * from json_each(offers.buyer_conditions::json) as bc(key,val) where (bc.val -> 'done')::text = 'false' or sc.val ? 'done') and not exists (select * from json_each(offers.seller_conditions::json) as sc(key,val) where (sc.val -> 'done')::text = 'false' or sc.val ? 'done'))

covers the case where both the buyer and the seller have conditions.

Anyway, does anyone see why it would tell me that the ? operator does not exist? Am I writing it wrong? Is there another way of accomplishing what I want? Thanks.


来源: stackexchange

问:
Asp Sql Data Uniq Id String + Integer +1
I want to make an incremental value in my sql table automatically, but I want it to read the previous data and str + int every time.
For example ;
ABC0001
ABC0002
ABC0003
.
.
.
to be continued .

Can you help with this

答:
Check whether the Sequence can be made use of
(With your limited data, I assume that you have SQL Server as your DBMS)

```<code>Create Table T (ColABCIncremtnt varchar(20), Col2 int, Col3 datetime)

CREATE SEQUENCE dbo.Id AS INT
    START WITH 1 INCREMENT BY 1 MINVALUE 0 NO MAXVALUE

Insert Into T (ColABCIncremtnt,Col2,Col3)
Select 'ABC000' + Convert(varchar(10), next value for dbo.Id), 43,getdate()

Insert Into T (ColABCIncremtnt,Col2,Col3)
Select 'ABC000' + Convert(varchar(10), next value for dbo.Id), 72,getdate()

Insert Into T (ColABCIncremtnt,Col2,Col3)
Select 'ABC000' + Convert(varchar(10), next value for dbo.Id), 36,getdate()

Select * from T
</code>```

if you want to embed the sequence to the table

```<code>ALTER TABLE dbo.T
ADD CONSTRAINT Cnstrnt_Seq
DEFAULT FORMAT((NEXT VALUE FOR dbo.ID),'ABC000#') FOR ColABCIncremtnt;

Insert Into T (Col2,Col3) values
(1,getdate()),
(2,getdate()),
(3,getdate())

Select * from T
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Check whether the Sequence can be made use of
(With your limited data, I assume that you have SQL Server as your DBMS)

Create Table T (ColABCIncremtnt varchar(20), Col2 int, Col3 datetime)

CREATE SEQUENCE dbo.Id AS INT
    START WITH 1 INCREMENT BY 1 MINVALUE 0 NO MAXVALUE

Insert Into T (ColABCIncremtnt,Col2,Col3)
Select 'ABC000' + Convert(varchar(10), next value for dbo.Id), 43,getdate()

Insert Into T (ColABCIncremtnt,Col2,Col3)
Select 'ABC000' + Convert(varchar(10), next value for dbo.Id), 72,getdate()

Insert Into T (ColABCIncremtnt,Col2,Col3)
Select 'ABC000' + Convert(varchar(10), next value for dbo.Id), 36,getdate()

Select * from T

if you want to embed the sequence to the table

ALTER TABLE dbo.T
ADD CONSTRAINT Cnstrnt_Seq
DEFAULT FORMAT((NEXT VALUE FOR dbo.ID),'ABC000#') FOR ColABCIncremtnt;

Insert Into T (Col2,Col3) values
(1,getdate()),
(2,getdate()),
(3,getdate())

Select * from T


问:
How can i extract month and year from a string in python?
Input text:

```<code>text = "Wipro Limited | Hyderabad, IN                Dec 2017 – Present
Project Analyst

Infosys | Delhi, IN                Apr 2017 – Nov 2017
Software Developer

HCL Technologies | Hyderabad, IN                Jun 2016 – Mar 2017
Software Engineer
"
</code>```

I have written a code for this but it displays in list for each extracted word and unable to do anything of it.

```<code>regex = re.compile('(?P<month>[a-zA-Z]+)\s+(?P<year>\d{4})\s+\–\s+(?P<month1>[a-zA-Z]+)\s+(?P<year1>\d{4})')
mat = re.findall(regex, text)
mat
</code>```

Check out the code : https://regex101.com/r/mMlgYp/1.
I want the output like below to preview the dates and make difference of it then calculate total experience:
Here Present or Till date should consider current month and year.

```<code>import time
Present = time.strftime("%m-%Y")
Present
# output: '05-2020'
</code>```

```<code>#Desired output
Extracted dates:
[('Dec 2017 - Present'),
 ('Apr 2017 - Nov 2017'),
 ('Jun 2016 - Mar 2017')]# and so on ...should display all the search results

First experience: 1.9 years
second experience: 8 months
third experience: 7 months
# and so on ...should display all the search results
Total experience: 3.4 years
</code>```

Please help me with this I'm new to programming lang and NLP, regex stuff.

答:
You probably ultimately want this in a dataframe since you tagged it pandas (see Andrej's answer), but either way, you can parse dates from the string with the interpolated:

```<code>fr"(?i)((?:{months}) *\d{{4}}) *(?:-|–) *(present|(?:{months}) *\d{{4}})"
</code>```

Where {months} is an alternating group of all possible month names and abbreviations.

```<code>import calendar
import re
from datetime import datetime
from dateutil.relativedelta import relativedelta

text = """Wipro Limited | Hyderabad, IN                Dec 2017 – Present
Project Analyst

Infosys | Delhi, IN                Apr 2017 – Nov 2017
Software Developer

HCL Technologies | Hyderabad, IN                Jun 2016 – Mar 2017
Software Engineer
"""

def parse_date(x, fmts=("%b %Y", "%B %Y")):
    for fmt in fmts:
        try:
            return datetime.strptime(x, fmt)
        except ValueError:
            pass

months = "|".join(calendar.month_abbr[1:] + calendar.month_name[1:])
pattern = fr"(?i)((?:{months}) *\d{{4}}) *(?:-|–) *(present|(?:{months}) *\d{{4}})"
total_experience = None

for start, end in re.findall(pattern, text):
    if end.lower() == "present":
        today = datetime.today()
        end = f"{calendar.month_abbr[today.month]} {today.year}"

    duration = relativedelta(parse_date(end), parse_date(start))

    if total_experience:
        total_experience += duration
    else:
        total_experience = duration

    print(f"{start}-{end} ({duration.years} years, {duration.months} months)")

if total_experience:
    print(f"total experience:  {total_experience.years} years, {total_experience.months} months")
else:
    print("couldn't parse text")
</code>```

Output:

Dec 2017-May 2020 (2 years, 5 months)
Apr 2017-Nov 2017 (0 years, 7 months)
Jun 2016-Mar 2017 (0 years, 9 months)
total experience:  3 years, 9 months
```

Body:
Input text:

text = "Wipro Limited | Hyderabad, IN                Dec 2017 – Present
Project Analyst

Infosys | Delhi, IN                Apr 2017 – Nov 2017
Software Developer

HCL Technologies | Hyderabad, IN                Jun 2016 – Mar 2017
Software Engineer
"

I have written a code for this but it displays in list for each extracted word and unable to do anything of it.

regex = re.compile('(?P<month>[a-zA-Z]+)\s+(?P<year>\d{4})\s+\–\s+(?P<month1>[a-zA-Z]+)\s+(?P<year1>\d{4})')
mat = re.findall(regex, text)
mat

Check out the code : https://regex101.com/r/mMlgYp/1.
I want the output like below to preview the dates and make difference of it then calculate total experience:
Here Present or Till date should consider current month and year.

import time
Present = time.strftime("%m-%Y")
Present
# output: '05-2020'

#Desired output
Extracted dates:
[('Dec 2017 - Present'),
 ('Apr 2017 - Nov 2017'),
 ('Jun 2016 - Mar 2017')]# and so on ...should display all the search results

First experience: 1.9 years
second experience: 8 months
third experience: 7 months
# and so on ...should display all the search results
Total experience: 3.4 years

Please help me with this I'm new to programming lang and NLP, regex stuff.

Body:
You probably ultimately want this in a dataframe since you tagged it pandas (see Andrej's answer), but either way, you can parse dates from the string with the interpolated:

fr"(?i)((?:{months}) *\d{{4}}) *(?:-|–) *(present|(?:{months}) *\d{{4}})"

Where {months} is an alternating group of all possible month names and abbreviations.

import calendar
import re
from datetime import datetime
from dateutil.relativedelta import relativedelta

text = """Wipro Limited | Hyderabad, IN                Dec 2017 – Present
Project Analyst

Infosys | Delhi, IN                Apr 2017 – Nov 2017
Software Developer

HCL Technologies | Hyderabad, IN                Jun 2016 – Mar 2017
Software Engineer
"""

def parse_date(x, fmts=("%b %Y", "%B %Y")):
    for fmt in fmts:
        try:
            return datetime.strptime(x, fmt)
        except ValueError:
            pass

months = "|".join(calendar.month_abbr[1:] + calendar.month_name[1:])
pattern = fr"(?i)((?:{months}) *\d{{4}}) *(?:-|–) *(present|(?:{months}) *\d{{4}})"
total_experience = None

for start, end in re.findall(pattern, text):
    if end.lower() == "present":
        today = datetime.today()
        end = f"{calendar.month_abbr[today.month]} {today.year}"

    duration = relativedelta(parse_date(end), parse_date(start))

    if total_experience:
        total_experience += duration
    else:
        total_experience = duration

    print(f"{start}-{end} ({duration.years} years, {duration.months} months)")

if total_experience:
    print(f"total experience:  {total_experience.years} years, {total_experience.months} months")
else:
    print("couldn't parse text")

Output:

Dec 2017-May 2020 (2 years, 5 months)
Apr 2017-Nov 2017 (0 years, 7 months)
Jun 2016-Mar 2017 (0 years, 9 months)
total experience:  3 years, 9 months


问:
Azure Servicebus Competing consumers with round robin
Are competing consumers of an Azure ServiceBus Queue / Subscription meant to round-robin?

I'm looping back to a question I asked a while back, and doing a little more testing.

There, I understood that a positive PrefetchCount was causing one client to have an affinity to all messages (unless load increases sufficiently for that client to be too busy to handle everything).

It actually looks like setting the SubscriptionClient's
MaxConcurrentCalls to anything other than 1 results in only one client receiving all messages under low load.

Setting the MaxConcurrentCalls = 1 suddenly causes alternative messages to be sent to competing consumers.
(Note that I'm not setting a PrefetchCount at all here)

Is this expected? We're scaling out, and I need a client to handle multiple messages concurrently, but 90% of the time, only one instance of a service is handling everything....the others are idle.

FWIW, Here's a sample project on Github based off the stock-standard MS documentation

答:
When setting MaxConcurrentCalls to a single message without a prefetch (PrefetchCount) you're asking a broker to provide just a single message to the requesting consumer. Assuming there are multiple messages on the broker, each consumer will get one message to process and receive another message once the previous message is completed, and so on. Depending on the latency and processing speed, messages will be distributed among the consumers as those request them. There will be no affinity or round-robin assignment. First come first served is what's happening.

Is this expected?

Yes.

We're scaling out, and I need a client to handle multiple messages concurrently, but 90% of the time, only one instance of a service is handling everything....the others are idle.

Setting up PrefetchCount and MaxConcurrentCalls that are not too greedy will give you some distribution, but if you're looking for an even distribution among instances of your consumer, that won't happen. That was already answered in the post you're referred to.


问:
html css tabs handle clips and sizes of tabs
I want to use tabs that I made with HTML and CSS only I don't use javascript at all, but I have some issues that I can not fix .. so I need your help.
so I got two questions I hope that I will be clear and you understand my problems :

how can I fix the problem of tabs clip when I resize the screen(or use phone)

can I sperate the tabs on the ALL contact block without care of tabs numbers?

here the code
    http://jsfiddle.net/waL0d6gu/

.tabss {
  position: relative;
  min-height: 200px;
  clear: both;
  margin: 25px 0;

}
.tabb {
  float: left;
  margin-right:3px;

}
.tabb label {
  background: #eee;
  padding: 7px;
  border: 1px solid #ccc;
  margin-left: -1px;
  position: relative;
  left: 1px;
  border-radius: 15px 15px 0px 0px;
  padding-left: 50px;
  padding-right: 50px;
  cursor: pointer;

}
.tabb [type=radio] {
  display: none;

}
.contentt {

  position: absolute;
  top: 28px;
  left: 0;
  background: #11426f;
  padding: 20px;
  border: 1px solid #ccc;
  display:none;
  min-width:700px;
  color:white;
}
[type=radio]:checked ~ label {
  background: #11426f;
  border-bottom: 1px solid #11426f;
  color:white;
  z-index: 2;
  padding-left: 75px;
  padding-right: 75px;

}
[type=radio]:checked ~ label ~ .contentt {
  display:block;
  border-radius: 0px 15px 15px 15px;
  width:95%

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="tabss">
<div class="tabb"><input type="radio" id="tab-1" name="tab-group-1" checked="checked" /> <label for="tab-1"><i class="fas fa-dollar-sign"></i><span> </span>aaaaa</label>
<div class="clear"></div>
<div class="contentt">[[aaaaa]]</div>
</div>
<div class="tabb"><input type="radio" id="tab-2" name="tab-group-1" /> <label for="tab-2"><i class="fa fa-truck"></i> bbbbb</label>
<div class="contentt">[[bbbb]]</div>
</div>
<div class="tabb"><input type="radio" id="tab-3" name="tab-group-1" /> <label for="tab-3"><i class="fa fa-info-circle"></i><span> </span>dddddd</label>
<div class="contentt">[[dddddd]]</div>
<div class="tabb"><input type="radio" id="tab-4" name="tab-group-1" /> <label for="tab-4"><i class="fas fa-undo"></i> cccccc</label>
<div class="contentt">[[cccccc]]</div>
</div></code>```

答:
instead of using float left - right, I used display flex and added media query for responsive. I just added it for mobile view. You can add whatever you want to the other views yourself. I wrote down my additions and changes in the comment lines. Good Luck!

* {
  box-sizing: border-box;
  /* added */
}

.tabss {
  width: 100%;
  /* added */
  position: relative;
  min-height: 200px;
  margin: 25px auto;
  display: flex;
  /* added */
  justify-content: space-around;
  /* added */
}

.tabb label {
  display: flex;
  /* added */
  justify-content: space-between;
  /* added */
  align-items: center;
  /* added */
  background: #eee;
  padding: 7px;
  border: 1px solid #ccc;
  margin-left: -1px;
  position: relative;
  left: 1px;
  border-radius: 15px 15px 0px 0px;
  padding-left: 40px;
  /* changed */
  padding-right: 40px;
  /* changed */
  cursor: pointer;
}

.tabb [type="radio"] {
  display: none;
}

.contentt {
  position: absolute;
  top: 25px;
  left: 0;
  background: #11426f;
  padding: 20px;
  border: 1px solid #ccc;
  display: none;
  width: 100%;
  color: white;
}

[type="radio"]:checked~label {
  background: #11426f;
  border-bottom: 1px solid #11426f;
  color: white;
  z-index: 2;
  padding-left: 75px;
  padding-right: 75px;
}

[type="radio"]:checked~label~.contentt {
  display: block;
  border-radius: 0px 15px 15px 15px;
  width: 100%;
}

/* added all , you can configure what you want*/

@media (max-width: 575.98px) {
  .tabb label {
    padding-left: 20px;
    padding-right: 20px;
  }
  [type="radio"]:checked~label {
    padding-left: 30px;
    padding-right: 30px;
  }
}

@media (max-width: 767.98px) {}

@media (max-width: 991.98px) {}

@media (max-width: 1199.98px) {}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <script src="https://kit.fontawesome.com/dc0c634418.js" crossorigin="anonymous"></script>
  <link rel="stylesheet" href="style2.css">
  <title>Document</title>

</head>

<body>

  <div class="tabss">
    <div class="tabb">
      <input type="radio" id="tab-1" name="tab-group-1" checked="checked" />
      <label for="tab-1">
        <i class="fas fa-dollar-sign"></i class> </i>
        <span> </span>aaaaa
      </label>
      <div class="clear"></div>
      <div class="contentt">[[aaaaa]]</div>
    </div>
    <div class="tabb"><input type="radio" id="tab-2" name="tab-group-1" /> <label for="tab-2"><i
          class="fa fa-truck"></i> bbbbb</label>
      <div class="contentt">[[bbbb]]</div>
    </div>
    <div class="tabb"><input type="radio" id="tab-3" name="tab-group-1" /> <label for="tab-3"><i
          class="fa fa-info-circle"></i><span> </span>dddddd</label>
      <div class="contentt">[[dddddd]]</div>
    </div>
    <div class="tabb"><input type="radio" id="tab-4" name="tab-group-1" /> <label for="tab-4"><i
          class="fas fa-undo"></i> cccccc</label>
      <div class="contentt">[[cccccc]]</div>
    </div>

</body>

</html></code>```

Body:
I want to use tabs that I made with HTML and CSS only I don't use javascript at all, but I have some issues that I can not fix .. so I need your help.
so I got two questions I hope that I will be clear and you understand my problems :

how can I fix the problem of tabs clip when I resize the screen(or use phone)

can I sperate the tabs on the ALL contact block without care of tabs numbers?

here the code
    http://jsfiddle.net/waL0d6gu/

.tabss {
  position: relative;
  min-height: 200px;
  clear: both;
  margin: 25px 0;

}
.tabb {
  float: left;
  margin-right:3px;

}
.tabb label {
  background: #eee;
  padding: 7px;
  border: 1px solid #ccc;
  margin-left: -1px;
  position: relative;
  left: 1px;
  border-radius: 15px 15px 0px 0px;
  padding-left: 50px;
  padding-right: 50px;
  cursor: pointer;

}
.tabb [type=radio] {
  display: none;

}
.contentt {

  position: absolute;
  top: 28px;
  left: 0;
  background: #11426f;
  padding: 20px;
  border: 1px solid #ccc;
  display:none;
  min-width:700px;
  color:white;
}
[type=radio]:checked ~ label {
  background: #11426f;
  border-bottom: 1px solid #11426f;
  color:white;
  z-index: 2;
  padding-left: 75px;
  padding-right: 75px;

}
[type=radio]:checked ~ label ~ .contentt {
  display:block;
  border-radius: 0px 15px 15px 15px;
  width:95%

}

<input type="radio" id="tab-1" name="tab-group-1" checked="checked" />  aaaaa

[[aaaaa]]

<input type="radio" id="tab-2" name="tab-group-1" />  bbbbb

[[bbbb]]

<input type="radio" id="tab-3" name="tab-group-1" />  dddddd

[[dddddd]]

<input type="radio" id="tab-4" name="tab-group-1" />  cccccc

[[cccccc]]

Body:
instead of using float left - right, I used display flex and added media query for responsive. I just added it for mobile view. You can add whatever you want to the other views yourself. I wrote down my additions and changes in the comment lines. Good Luck!

* {
  box-sizing: border-box;
  /* added */
}

.tabss {
  width: 100%;
  /* added */
  position: relative;
  min-height: 200px;
  margin: 25px auto;
  display: flex;
  /* added */
  justify-content: space-around;
  /* added */
}

.tabb label {
  display: flex;
  /* added */
  justify-content: space-between;
  /* added */
  align-items: center;
  /* added */
  background: #eee;
  padding: 7px;
  border: 1px solid #ccc;
  margin-left: -1px;
  position: relative;
  left: 1px;
  border-radius: 15px 15px 0px 0px;
  padding-left: 40px;
  /* changed */
  padding-right: 40px;
  /* changed */
  cursor: pointer;
}

.tabb [type="radio"] {
  display: none;
}

.contentt {
  position: absolute;
  top: 25px;
  left: 0;
  background: #11426f;
  padding: 20px;
  border: 1px solid #ccc;
  display: none;
  width: 100%;
  color: white;
}

[type="radio"]:checked~label {
  background: #11426f;
  border-bottom: 1px solid #11426f;
  color: white;
  z-index: 2;
  padding-left: 75px;
  padding-right: 75px;
}

[type="radio"]:checked~label~.contentt {
  display: block;
  border-radius: 0px 15px 15px 15px;
  width: 100%;
}

/* added all , you can configure what you want*/

@media (max-width: 575.98px) {
  .tabb label {
    padding-left: 20px;
    padding-right: 20px;
  }
  [type="radio"]:checked~label {
    padding-left: 30px;
    padding-right: 30px;
  }
}

@media (max-width: 767.98px) {}

@media (max-width: 991.98px) {}

@media (max-width: 1199.98px) {}

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <script src="https://kit.fontawesome.com/dc0c634418.js" crossorigin="anonymous"></script>
  <link rel="stylesheet" href="style2.css">
  <title>Document</title>

</head>

<body>

  <div class="tabss">
    <div class="tabb">
      <input type="radio" id="tab-1" name="tab-group-1" checked="checked" />
      <label for="tab-1">
        <i class="fas fa-dollar-sign"></i class> </i>
        <span>&nbsp;</span>aaaaa
      </label>
      <div class="clear"></div>
      <div class="contentt">[[aaaaa]]</div>
    </div>
    <div class="tabb"><input type="radio" id="tab-2" name="tab-group-1" /> <label for="tab-2"><i
          class="fa fa-truck"></i> bbbbb</label>
      <div class="contentt">[[bbbb]]</div>
    </div>
    <div class="tabb"><input type="radio" id="tab-3" name="tab-group-1" /> <label for="tab-3"><i
          class="fa fa-info-circle"></i><span>&nbsp;</span>dddddd</label>
      <div class="contentt">[[dddddd]]</div>
    </div>
    <div class="tabb"><input type="radio" id="tab-4" name="tab-group-1" /> <label for="tab-4"><i
          class="fas fa-undo"></i> cccccc</label>
      <div class="contentt">[[cccccc]]</div>
    </div>

</body>

</html>


问:
AWS CloudFormation Outputs: Exporting AZ's
Creating a layered stack set in cloudformation. Network Stack and App Stack

Just need the syntax to Output and Export two Availability Zones that are captured when a cfn user chooses them in the network template parameters dialogue.

eg, a user chooses two AZ's in a region via the usual mechanism.

```<code>AZoneNames:
    Type: 'List<AWS::EC2::AvailabilityZone::Name>'
    Description: Availability Zones (choose two zones)
</code>```

That captures the az's, and i assume, cfn indexes them [0,1] to an array in the background. That part works.

So I need to output the two az's and export them for the app stack but not sure how. I've attempted with the below snippet but it doesnt work

```<code>StackAvailabilityZone1:
    Description: The first az that was chosen at network stack creation
    Value: !Ref AvailabilityZone 0
    Export:
      Name: !Sub 'AZ1'
</code>```

I'm sure its probably staring me in the face. Thanks so much for any ideas.

答:
You can try the following, using Select:</p>

```<code>StackAvailabilityZone1:
    Description: The first az that was chosen at network stack creation
    Value: !Select [0, !Ref AZoneNames]
    Export:
      Name: AZ1
</code>```

Body:
Creating a layered stack set in cloudformation. Network Stack and App Stack

Just need the syntax to Output and Export two Availability Zones that are captured when a cfn user chooses them in the network template parameters dialogue.

eg, a user chooses two AZ's in a region via the usual mechanism.

AZoneNames:
    Type: 'List<AWS::EC2::AvailabilityZone::Name>'
    Description: Availability Zones (choose two zones)

That captures the az's, and i assume, cfn indexes them [0,1] to an array in the background. That part works.

So I need to output the two az's and export them for the app stack but not sure how. I've attempted with the below snippet but it doesnt work

StackAvailabilityZone1:
    Description: The first az that was chosen at network stack creation
    Value: !Ref AvailabilityZone 0
    Export:
      Name: !Sub 'AZ1'

I'm sure its probably staring me in the face. Thanks so much for any ideas.

Body:
You can try the following, using Select:

StackAvailabilityZone1:
    Description: The first az that was chosen at network stack creation
    Value: !Select [0, !Ref AZoneNames]
    Export:
      Name: AZ1


问:
Is it possible to store an unique_ptr both in class and vector in C++?
I am trying to hold a unique pointer to both a vector (from a Base class) and a Derivated class object, so later I am able to call a method for all. However I want to call aswell methods from Derivated classes so I need to store the reference for them aswell.

```<code>class Foo
{
     vector<unique_ptr<Base>> bar;
     unique_ptr<Derivated1> bar2;
     unique_ptr<Derivated2> bar3;
}

Foo::Foo(){
     this->bar2 = make_unique<Derivated1>();
     this->bar2->doSomethingDerivated1();
     this->bar3 = make_unique<Derivated2>();
     this->bar->push_back(move(bar2));
     this->bar->push_back(move(bar3));
}

Foo::callForAll() {
     for (const auto& foo: this->bar) foo->doSomethingBase();
}

Foo::callForDerivated1() {
     this->bar2->doSomethingDerivated1();
}
</code>```

Is something like this possible? For my understanding this code will most likely fail. Will move place bar2 and bar3 to nullptr? Creating a unique_ptr, store a raw pointer with bar2->get() and then push_back to vector works?

Note: These objects only belong to this class, so unique would make sense.

答:
No. The whole point of unique_ptr is to be unique. This means you cannot copy it.

However, you CAN make copies of the underlying pointer that unique_ptr manages. E.g.

```<code>unique_ptr<Foo> foo(new Foo);
Foo* foo_copy = foo.get();
</code>```

There are a couple things that you need to be careful of when doing this:

Do not delete foo_copy. That is the job of unique_ptr. If you delete foo_copy, then you will have committed the sin of double delete, which has undefined behavior (i.e. the compiler is allowed to generate code that launches a nuclear missile).

Do not use foo_copy after foo has been destroyed because when foo is destroyed, the underlying pointer is deleted (unless foo has relinquished ownership of the underlying pointer, and the underlying pointer hasn't been deleted by some other means yet). This is the sin of use after free, and it also has UB.

Moving is one way for unique_ptr to relinquish ownership. Once you move out of a unique_ptr, it no longer points to anything (that is the whole point of moving; when you walk from A to B, you are no longer at A, because there is only one of you, and you have decided to instead be located at B). I believe that trying to call a method using the -> operator on an empty unique_ptr is also UB.

It seems like what you should do is

vector<unique_ptr<Base>> v;

Derived* ob = v[i].get();

Let me reiterate that this is slightly dangerous and unusual.

Tangent: I find it highly suspicious that you are not using virtual methods; virtual really should be the default (kind of like how double is the default, not float, even though float looks like it is and should be the default). Actually, I find it suspicious that you are using inheritance. Inheritance is one of the most over-rated features of all time. I suspect that this is where your troubles may be originating. For example, the Go language doesn't even have inheritance, yet it does have polymorphism (i.e. different implementations of the same interface).

PS: Please, do not accidentally extinguish the human race by invoking UB.

Body:
I am trying to hold a unique pointer to both a vector (from a Base class) and a Derivated class object, so later I am able to call a method for all. However I want to call aswell methods from Derivated classes so I need to store the reference for them aswell.

class Foo
{
     vector<unique_ptr<Base>> bar;
     unique_ptr<Derivated1> bar2;
     unique_ptr<Derivated2> bar3;
}

Foo::Foo(){
     this->bar2 = make_unique<Derivated1>();
     this->bar2->doSomethingDerivated1();
     this->bar3 = make_unique<Derivated2>();
     this->bar->push_back(move(bar2));
     this->bar->push_back(move(bar3));
}

Foo::callForAll() {
     for (const auto& foo: this->bar) foo->doSomethingBase();
}

Foo::callForDerivated1() {
     this->bar2->doSomethingDerivated1();
}

Is something like this possible? For my understanding this code will most likely fail. Will move place bar2 and bar3 to nullptr? Creating a unique_ptr, store a raw pointer with bar2->get() and then push_back to vector works?

Note: These objects only belong to this class, so unique would make sense.

Body:
No. The whole point of unique_ptr is to be unique. This means you cannot copy it.

However, you CAN make copies of the underlying pointer that unique_ptr manages. E.g.

unique_ptr<Foo> foo(new Foo);
Foo* foo_copy = foo.get();

There are a couple things that you need to be careful of when doing this:

Do not delete foo_copy. That is the job of unique_ptr. If you delete foo_copy, then you will have committed the sin of double delete, which has undefined behavior (i.e. the compiler is allowed to generate code that launches a nuclear missile).

Do not use foo_copy after foo has been destroyed because when foo is destroyed, the underlying pointer is deleted (unless foo has relinquished ownership of the underlying pointer, and the underlying pointer hasn't been deleted by some other means yet). This is the sin of use after free, and it also has UB.

Moving is one way for unique_ptr to relinquish ownership. Once you move out of a unique_ptr, it no longer points to anything (that is the whole point of moving; when you walk from A to B, you are no longer at A, because there is only one of you, and you have decided to instead be located at B). I believe that trying to call a method using the -> operator on an empty unique_ptr is also UB.

It seems like what you should do is

vector<unique_ptr<Base>> v;

Derived* ob = v[i].get();

Let me reiterate that this is slightly dangerous and unusual.

Tangent: I find it highly suspicious that you are not using virtual methods; virtual really should be the default (kind of like how double is the default, not float, even though float looks like it is and should be the default). Actually, I find it suspicious that you are using inheritance. Inheritance is one of the most over-rated features of all time. I suspect that this is where your troubles may be originating. For example, the Go language doesn't even have inheritance, yet it does have polymorphism (i.e. different implementations of the same interface).

PS: Please, do not accidentally extinguish the human race by invoking UB.


问:
I'm trying to pull a aproject from my pc via git (command line) to github. but I can't get the link from github
On my PC, I have already made these steps:

```<code>git init
git add "the directory name"
git commit -m "****"
</code>```

答:
What you see is a pull request page, not the project page itself.

Consider instead, for instance, clayakers/Dasmoto-Project: (replace clayakers with your GitHub username): this is where you find the URL (HTTPS or SSH) to use:

You would need, assuming the GitHub repo is still empty, to do:

```<code>cd /path/to/local/repo
git remote add origin https://github.com/clayakers/Dasmoto-Project
git push -u origin/master
</code>```

Body:
On my PC, I have already made these steps:

git init
git add "the directory name"
git commit -m "****"

Body:
What you see is a pull request page, not the project page itself.

Consider instead, for instance, clayakers/Dasmoto-Project: (replace clayakers with your GitHub username): this is where you find the URL (HTTPS or SSH) to use:

You would need, assuming the GitHub repo is still empty, to do:

cd /path/to/local/repo
git remote add origin https://github.com/clayakers/Dasmoto-Project
git push -u origin/master


问:
Accessing Guardian info in Google Classroom via Apps Script
I'm trying to access Google Classroom Guardian info in a Google Apps Script using the Classroom service. I've added the service and enabled the API in the API console. I can access some data (for example courses) but when I try to get guardian info via Classroom.UserProfiles.Guardians.list(student_id ) if fails with a permission error. However, if I add a (dummy) call to Classroom.UserProfiles.GuardianInvitations.create() then the auth screen with the required scopes pops up and the script works thereafter. Is there something I'm missing, or is this a bug in Apps Scripts?

答:
You should be a superadminstrator (domain administrator) to be able to work with Guardians through the Google Classroom API

Reference

Manage guardians in your domain


问:
How I can copy google document and share access to email?
There is a template on google doc.
We want to copy it and provide access by mail.
Maybe there are those who know how to implement this?</p>

答:
How about this answer?

Unfortunately, the copy of file and the modification of permissions of the file cannot be done with Google Docs API. In this case, it is required to use Drive API. The flow for achieving your goal is as follows.

1. Copy of Google Document file.

In this case, the method of "Files: copy" of Drive API v3 is used. The endpoint and sample request body is as follows. The file ID is the file ID of the template Google Document file.

Endpoint:

```<code>POST https://www.googleapis.com/drive/v3/files/fileId/copy
</code>```

Sample request body:

```<code>{"name": "sample name"}
</code>```

Sample curl command:

```<code>curl --request POST \
  'https://www.googleapis.com/drive/v3/files/fileId/copy'
  --header 'Authorization: Bearer [YOUR_ACCESS_TOKEN]' \
  --header 'Accept: application/json' \
  --header 'Content-Type: application/json' \
  --data '{"name":"sample name"}' \
  --compressed
</code>```

When the file is copied, the file ID of the copied file is returned.

2. Create permissions.

In this case, the method of "Permissions: create" of Drive API v3 is used. The endpoint and sample request body is as follows. The file ID is the file ID of copied file.

Endpoint:

```<code>POST https://www.googleapis.com/drive/v3/files/fileId/permissions
</code>```

Sample request body:

```<code>{
  "role": "writer",
  "type": "user",
  "emailAddress": "###"
}
</code>```

Sample curl command:

```<code>curl --request POST \
  'https://www.googleapis.com/drive/v3/files/fileId/permissions' \
  --header 'Authorization: Bearer [YOUR_ACCESS_TOKEN]' \
  --header 'Accept: application/json' \
  --header 'Content-Type: application/json' \
  --data '{"role":"writer","type":"user","emailAddress":"###"}' \
  --compressed
</code>```

In this case, the user of email address ### has the permission of the writer for the file.

Note:

In above flow, the access token is required. Unfortunately, the API key cannot be used for this situation. Please be careful this.

If you want to modify the copied Google Document using API, please use Google Docs API.

References:

Files: copy

Permissions: create

Body:
How about this answer?

Unfortunately, the copy of file and the modification of permissions of the file cannot be done with Google Docs API. In this case, it is required to use Drive API. The flow for achieving your goal is as follows.

1. Copy of Google Document file.

In this case, the method of "Files: copy" of Drive API v3 is used. The endpoint and sample request body is as follows. The file ID is the file ID of the template Google Document file.

Endpoint:

POST https://www.googleapis.com/drive/v3/files/fileId/copy

Sample request body:

{"name": "sample name"}

Sample curl command:

curl --request POST \
  'https://www.googleapis.com/drive/v3/files/fileId/copy'
  --header 'Authorization: Bearer [YOUR_ACCESS_TOKEN]' \
  --header 'Accept: application/json' \
  --header 'Content-Type: application/json' \
  --data '{"name":"sample name"}' \
  --compressed

When the file is copied, the file ID of the copied file is returned.

2. Create permissions.

In this case, the method of "Permissions: create" of Drive API v3 is used. The endpoint and sample request body is as follows. The file ID is the file ID of copied file.

Endpoint:

POST https://www.googleapis.com/drive/v3/files/fileId/permissions

Sample request body:

{
  "role": "writer",
  "type": "user",
  "emailAddress": "###"
}

Sample curl command:

curl --request POST \
  'https://www.googleapis.com/drive/v3/files/fileId/permissions' \
  --header 'Authorization: Bearer [YOUR_ACCESS_TOKEN]' \
  --header 'Accept: application/json' \
  --header 'Content-Type: application/json' \
  --data '{"role":"writer","type":"user","emailAddress":"###"}' \
  --compressed

In this case, the user of email address ### has the permission of the writer for the file.

Note:

In above flow, the access token is required. Unfortunately, the API key cannot be used for this situation. Please be careful this.

If you want to modify the copied Google Document using API, please use Google Docs API.

References:

Files: copy

Permissions: create


问:
How can I make turret rotate facing target if the target is close enough and make the target rotate around turret with random height and speed?
The target is a simple 3d cube.

This screenshot showing the turret in the hierarchy and the script attached to it and the target.

The script is attached to the Turret child :

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RotateTurret : MonoBehaviour
{
    [SerializeField]
    private float turnRateRadians = 2 * Mathf.PI;

    [SerializeField]
    private Transform turretTop; // the gun part that rotates

    [SerializeField]
    private Transform bulletSpawnPoint;

    //private Enemy target;
    public GameObject target;

    void Update()
    {
        TargetEnemy();
    }

    void TargetEnemy()
    {
        if (target != null)
        {
            Vector3 targetDir = target.transform.position - transform.position;
            // Rotating in 2D Plane...
            targetDir.y = 0.0f;
            targetDir = targetDir.normalized;

            Vector3 currentDir = turretTop.forward;

            currentDir = Vector3.RotateTowards(currentDir, targetDir, turnRateRadians * Time.deltaTime, 1.0f);

            Quaternion qDir = new Quaternion();
            qDir.SetLookRotation(currentDir, Vector3.up);
            turretTop.rotation = qDir;
        }
    }
}
</code>```

When running the game the cube is not moving the turret is not moving. Only if I'm moving the target cube in the scene view window drag it then the turret rotate but also the turret is a bit behind never facing the target cube.

What I need it to do is when running the game the cube will start make circles nonstop around the turret with random speed and the target cube also should move up down with random height between min/max height.

And the turret should rotate facing the target according to the target height and speed.

答:
Make an empty gameobject same position with turret, then make target child of that empty object and place it to where you want to rotate it, then rotate empty parent object with that sciprt</p>

```<code>private int _minY, _maxY;
private int _targetHeight;
private const float Tolerance = 0.1f;

private void Start()
{
    _minY = -10;
    _maxY = 10;
    _targetHeight = Random.Range(_minY, _maxY);
}

private void FixedUpdate()
{
    var randomSpeed = Random.Range(2, 4);
    transform.Rotate(0,randomSpeed,0);
    if(Math.Abs(transform.position.y - _targetHeight) < Tolerance)
         _targetHeight = Random.Range(_minY, _maxY);
    transform.position = Vector3.MoveTowards(transform.position, new Vector3(transform.position.x, _targetHeight, transform.position.z), randomSpeed/10f);
}
</code>```

Body:
The target is a simple 3d cube.

This screenshot showing the turret in the hierarchy and the script attached to it and the target.

The script is attached to the Turret child :

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RotateTurret : MonoBehaviour
{
    [SerializeField]
    private float turnRateRadians = 2 * Mathf.PI;

    [SerializeField]
    private Transform turretTop; // the gun part that rotates

    [SerializeField]
    private Transform bulletSpawnPoint;

    //private Enemy target;
    public GameObject target;

    void Update()
    {
        TargetEnemy();
    }

    void TargetEnemy()
    {
        if (target != null)
        {
            Vector3 targetDir = target.transform.position - transform.position;
            // Rotating in 2D Plane...
            targetDir.y = 0.0f;
            targetDir = targetDir.normalized;

            Vector3 currentDir = turretTop.forward;

            currentDir = Vector3.RotateTowards(currentDir, targetDir, turnRateRadians * Time.deltaTime, 1.0f);

            Quaternion qDir = new Quaternion();
            qDir.SetLookRotation(currentDir, Vector3.up);
            turretTop.rotation = qDir;
        }
    }
}

When running the game the cube is not moving the turret is not moving. Only if I'm moving the target cube in the scene view window drag it then the turret rotate but also the turret is a bit behind never facing the target cube.

What I need it to do is when running the game the cube will start make circles nonstop around the turret with random speed and the target cube also should move up down with random height between min/max height.

And the turret should rotate facing the target according to the target height and speed.

Body:
Make an empty gameobject same position with turret, then make target child of that empty object and place it to where you want to rotate it, then rotate empty parent object with that sciprt

private int _minY, _maxY;
private int _targetHeight;
private const float Tolerance = 0.1f;

private void Start()
{
    _minY = -10;
    _maxY = 10;
    _targetHeight = Random.Range(_minY, _maxY);
}

private void FixedUpdate()
{
    var randomSpeed = Random.Range(2, 4);
    transform.Rotate(0,randomSpeed,0);
    if(Math.Abs(transform.position.y - _targetHeight) < Tolerance)
         _targetHeight = Random.Range(_minY, _maxY);
    transform.position = Vector3.MoveTowards(transform.position, new Vector3(transform.position.x, _targetHeight, transform.position.z), randomSpeed/10f);
}


问:
React-router urls not working when manually typing in browser
When I navigate between pages using the navbar and the buttons, the URL on the browser changes normally. But once I try to modify the URL manually, it does not work !

Example 1

Step 1 : I open localhost:3000

Step 2 : I click on Athletes to go to localhost:3000/Athletes

Step 3 : I choose an athlete to go to localhost:3000/Athletes/2/AthleteSessions/

Step 4 : I change the URL manually to localhost:3000/Athletes then I choose an athlete, I'm redirected to localhost:3000/Athletes/2/AthleteSessions/ fine until now, but when I modify the URL to put localhost:3000/Athletes/ with a slash then I choose an athlete it does not work and I'm redirected to localhost:3000/Athletes/Athletes/2/AthleteSessions/

Example 2

Step 1, 2 and 3 are the same as the first example.

Step 4 : I choose an AthleteSession to go to localhost:3000/Athletes/2/AthleteSessions/1/TrainingSession/ it works fine, but when I try to go back to previous page by modifying manually the URL localhost:3000/Athletes/2/AthleteSessions then I choose an AthleteSession again, it does not work and I'm redirected to localhost:3000/Athletes/2/1/TrainingSession/

App.js

```<code>import { Route, Switch, Redirect } from "react-router-dom";

<Route path="/Athletes" exact component={Athletes} />
<Route path="/Athletes/:id/AthleteSessions" exact component={AthleteSessions} />
<Route path="/Athletes/:athleteId/AthleteSessions/:athleteSessionId/TrainingSession"
       exact component={AthleteTrainingSession} />
</code>```

Index.js

```<code>import { BrowserRouter as Router } from "react-router-dom";

render( <Router> <App /> </Router>, document.getElementById("root") );
</code>```

Athletes.js

```<code>onClick={() => {
  this.props.history.push({
    pathname:
      "Athletes/" + ath.AthleteId + "/AthleteSessions/",
  });
}}
</code>```

AthleteSessions.js

```<code>passedAthleteId = this.props.match.params.id;

onClick={() => {
  this.props.history.push({
    pathname:
      athSess.AthleteSessionId + "/TrainingSession/",
  });
}}
</code>```

答:
Your current route definition is fine:

```<code><Switch>
    <Route exact path="/" component={Home} />
    <Route exact path="/Athletes" component={Athletes} />
    <Route
        exact
        path="/Athletes/:id/AthleteSessions"
        component={AthleteSessions}
    />
    <Route
        exact
        path="/Athletes/:athleteId/AthleteSessions/:athleteSessionId/TrainingSession"
        component={AthleteTrainingSession}
    />
</Switch>
</code>```

But to go to any route you are currently doing history.push without leading /, and with a trailing / which causes the problem:

```<code>// FIRST (lets refer it first)
onClick={() => {
    this.props.history.push({
    pathname:
        "Athletes/" + ath.AthleteId + "/AthleteSessions/",
    });
}}

// SECOND (lets refer it second)
onClick={() => {
    this.props.history.push({
    pathname:
        athSess.AthleteSessionId + "/TrainingSession/",
    });
}}
</code>```

history.push('/hello') takes from localhost:3000/some/url to localhost:3000/hello --> Easy to understand

history.push('hello') takes from localhost:3000/some/url to localhost:3000/some/hello --> Not so easy, so avoid

So, everything is working fine as long as you are going to FIRST and SECOND using above history.push methods.

But problems start when you start manually typing a URL in the browser, sometimes with an ending / and sometimes without one.

Solution 1:

Change your FIRST and SECOND to use fully qualified urls with leading / and no trailing /, trailing / isn't important anymore as we using full qualified urls. Also, see Strict-Bool:

```<code>// FIRST
onClick={() => {
    this.props.history.push({
    pathname:
        "/Athletes/" + ath.AthleteId + "/AthleteSessions",
    });
}}

// SECOND
onClick={() => {
  this.props.history.push({
    pathname: `/Athletes/${this.props.match.params?.id}/AthleteSessions/${athSess.AthleteSessionId}/TrainingSession`,
  });
}}
</code>```

As we are now using full qualified URLs, it will work perfectly but the code seems hard to manage as you will be forming the full urls at each history push.

Solution 2:

SAME as Solution 1 but better code:

Define your routes using paths and makePaths:

```<code>export const paths = {
  Athletes: "/Athletes",
  AthleteSessions: "/Athletes/:id/AthleteSessions",
  AthleteTrainingSession:
    "/Athletes/:athleteId/AthleteSessions/:athleteSessionId/TrainingSession",
};

export const makePaths = {
  AthleteSessions: (id) => {
    return `/Athletes/${id}/AthleteSessions`;
  },
  AthleteTrainingSession: (athleteId, athleteSessionId) => {
    return `/Athletes/${athleteId}/AthleteSessions/${athleteSessionId}/TrainingSession`;
  },
};

// in JSX
<Switch>
  <Route exact path="/" component={Home} />
  <Route exact path={paths.Athletes} component={Athletes} />
  <Route exact path={paths.AthleteSessions} component={AthleteSessions} />
  <Route
    exact
    path={paths.AthleteTrainingSession}
    component={AthleteTrainingSession}
  />
</Switch>
</code>```

And history.push:

```<code>// FIRST
onClick={() => {
  this.props.history.push({
    pathname: makePaths.AthleteSessions(ath.AthleteId),
  });
}}

// SECOND
onClick={() => {
  this.props.history.push({
    pathname: makePaths.AthleteTrainingSession(
      this.props.match.params?.id,
      athSess.AthleteSessionId
    ),
  });
}}
</code>```

Solution 3:

Do nested routing. See nesting example in docs, how to do nesting? and how to access URL Params i.e. :id in path.

I would recommend going with Solution 2 but do read Solution 3 (nesting) and if / when possible go with that.

Body:
When I navigate between pages using the navbar and the buttons, the URL on the browser changes normally. But once I try to modify the URL manually, it does not work !

Example 1

Step 1 : I open localhost:3000

Step 2 : I click on Athletes to go to localhost:3000/Athletes

Step 3 : I choose an athlete to go to localhost:3000/Athletes/2/AthleteSessions/

Step 4 : I change the URL manually to localhost:3000/Athletes then I choose an athlete, I'm redirected to localhost:3000/Athletes/2/AthleteSessions/ fine until now, but when I modify the URL to put localhost:3000/Athletes/ with a slash then I choose an athlete it does not work and I'm redirected to localhost:3000/Athletes/Athletes/2/AthleteSessions/

Example 2

Step 1, 2 and 3 are the same as the first example.

Step 4 : I choose an AthleteSession to go to localhost:3000/Athletes/2/AthleteSessions/1/TrainingSession/ it works fine, but when I try to go back to previous page by modifying manually the URL localhost:3000/Athletes/2/AthleteSessions then I choose an AthleteSession again, it does not work and I'm redirected to localhost:3000/Athletes/2/1/TrainingSession/

App.js

import { Route, Switch, Redirect } from "react-router-dom";

<Route path="/Athletes" exact component={Athletes} />
<Route path="/Athletes/:id/AthleteSessions" exact component={AthleteSessions} />
<Route path="/Athletes/:athleteId/AthleteSessions/:athleteSessionId/TrainingSession"
       exact component={AthleteTrainingSession} />

Index.js

import { BrowserRouter as Router } from "react-router-dom";

render( <Router> <App /> </Router>, document.getElementById("root") );

Athletes.js

onClick={() => {
  this.props.history.push({
    pathname:
      "Athletes/" + ath.AthleteId + "/AthleteSessions/",
  });
}}

AthleteSessions.js

passedAthleteId = this.props.match.params.id;

onClick={() => {
  this.props.history.push({
    pathname:
      athSess.AthleteSessionId + "/TrainingSession/",
  });
}}

Body:
Your current route definition is fine:

<Switch>
    <Route exact path="/" component={Home} />
    <Route exact path="/Athletes" component={Athletes} />
    <Route
        exact
        path="/Athletes/:id/AthleteSessions"
        component={AthleteSessions}
    />
    <Route
        exact
        path="/Athletes/:athleteId/AthleteSessions/:athleteSessionId/TrainingSession"
        component={AthleteTrainingSession}
    />
</Switch>

But to go to any route you are currently doing history.push without leading /, and with a trailing / which causes the problem:

// FIRST (lets refer it first)
onClick={() => {
    this.props.history.push({
    pathname:
        "Athletes/" + ath.AthleteId + "/AthleteSessions/",
    });
}}

// SECOND (lets refer it second)
onClick={() => {
    this.props.history.push({
    pathname:
        athSess.AthleteSessionId + "/TrainingSession/",
    });
}}

history.push('/hello') takes from localhost:3000/some/url to localhost:3000/hello --> Easy to understand

history.push('hello') takes from localhost:3000/some/url to localhost:3000/some/hello --> Not so easy, so avoid

So, everything is working fine as long as you are going to FIRST and SECOND using above history.push methods.

But problems start when you start manually typing a URL in the browser, sometimes with an ending / and sometimes without one.

Solution 1:

Change your FIRST and SECOND to use fully qualified urls with leading / and no trailing /, trailing / isn't important anymore as we using full qualified urls. Also, see Strict-Bool:

// FIRST
onClick={() => {
    this.props.history.push({
    pathname:
        "/Athletes/" + ath.AthleteId + "/AthleteSessions",
    });
}}

// SECOND
onClick={() => {
  this.props.history.push({
    pathname: `/Athletes/${this.props.match.params?.id}/AthleteSessions/${athSess.AthleteSessionId}/TrainingSession`,
  });
}}

As we are now using full qualified URLs, it will work perfectly but the code seems hard to manage as you will be forming the full urls at each history push.

Solution 2:

SAME as Solution 1 but better code:

Define your routes using paths and makePaths:

export const paths = {
  Athletes: "/Athletes",
  AthleteSessions: "/Athletes/:id/AthleteSessions",
  AthleteTrainingSession:
    "/Athletes/:athleteId/AthleteSessions/:athleteSessionId/TrainingSession",
};

export const makePaths = {
  AthleteSessions: (id) => {
    return `/Athletes/${id}/AthleteSessions`;
  },
  AthleteTrainingSession: (athleteId, athleteSessionId) => {
    return `/Athletes/${athleteId}/AthleteSessions/${athleteSessionId}/TrainingSession`;
  },
};

// in JSX
<Switch>
  <Route exact path="/" component={Home} />
  <Route exact path={paths.Athletes} component={Athletes} />
  <Route exact path={paths.AthleteSessions} component={AthleteSessions} />
  <Route
    exact
    path={paths.AthleteTrainingSession}
    component={AthleteTrainingSession}
  />
</Switch>

And history.push:

// FIRST
onClick={() => {
  this.props.history.push({
    pathname: makePaths.AthleteSessions(ath.AthleteId),
  });
}}

// SECOND
onClick={() => {
  this.props.history.push({
    pathname: makePaths.AthleteTrainingSession(
      this.props.match.params?.id,
      athSess.AthleteSessionId
    ),
  });
}}

Solution 3:

Do nested routing. See nesting example in docs, how to do nesting? and how to access URL Params i.e. :id in path.

I would recommend going with Solution 2 but do read Solution 3 (nesting) and if / when possible go with that.


问:
How to determine number Saturdays and Sundays comes between two dates in java script
I have requirement as follows
I have two dates i need to find how may saturdays and sundays will come in between

Date1: 02/06/2011

Date2: 02/07/2011

10 days are weekends

Thanks
Srini

答:
According to your dates, they are not in US format (at least not if there are 10 weekend days between them). You can get them in US format with something such as...

```<code>var chunks = str.split('/');
str = [chunks[1], chunks[0], chunks[2]].join('/');
</code>```

This code loops through each day between the dates and increments a counter if the day is a Saturday or Sunday.

```<code>var start = new Date('06/02/2011'),
    finish = new Date('07/02/2011'),
    dayMilliseconds = 1000 * 60 * 60 * 24;

var weekendDays = 0;

while (start <= finish) {
    var day = start.getDay()
    if (day == 0 || day == 6) {
        weekendDays++;
    }
    start = new Date(+start + dayMilliseconds);
}
</code>```

jsFiddle.

ContentLicense: CC BY-SA 3.0

Body:
According to your dates, they are not in US format (at least not if there are 10 weekend days between them). You can get them in US format with something such as...

var chunks = str.split('/');
str = [chunks[1], chunks[0], chunks[2]].join('/');

This code loops through each day between the dates and increments a counter if the day is a Saturday or Sunday.

var start = new Date('06/02/2011'),
    finish = new Date('07/02/2011'),
    dayMilliseconds = 1000 * 60 * 60 * 24;

var weekendDays = 0;

while (start <= finish) {
    var day = start.getDay()
    if (day == 0 || day == 6) {
        weekendDays++;
    }
    start = new Date(+start + dayMilliseconds);
}

jsFiddle.


问:
How do I read a list surrounded in double quotes from a csv file?
I am creating a ticket tracking project where I have a pandas dataframe holding the ticket information. I am then storing this dataframe into a csv file. The dataframe will initialize at the start of the program.

One of the column values is a list. When you store the pandas dataframe in a csv file with this line of code: self.ticketDF.to_csv(self.ticketCSVFilePath), it surrounds the list in double quotes. When you then read it back in, it now is interpreted as a string, not a list. In my example, you can see the list with double quotes under the comments column.

Here is my file - tickets.csv:

```<code>Ticket ID,Subject,Project,Description,Priority,Comments
PROT-18,testSubject,testProject,testDescription,testPriority,"['comment1', 'comment2', 'comment3']"
PROT-19,testSubject,testProject,testDescription,testPriority,"['comment4', 'comment5', 'comment6']"
</code>```

I am initializing the pandas dataframe, using these two functions:

```<code>def initializeTicketDF(self):
   if path.exists(self.ticketCSVFilePath) and path.getsize(self.ticketCSVFilePath) > 0:
       self.ticketDF = pd.read_csv(self.ticketCSVFilePath)  #reading the csv file into the dataframe
       self.ticketDF.set_index('Ticket ID', inplace=True)   #I am setting the index to the Ticket ID
       self.columnToList("Comments")                        #Calling my function that currently does the
                                                            #workaround

def columnToList(self, columnName):
   count = 0                                #this represents the current row in the dataframe
   for x in self.ticketDF['Comments']:      #x holds the "Comments" value for every row
       x = x.replace('[', '')               #replace left and right brackets
       x = x.replace(']', '')
       x = re.findall('\'([^\']*)\'', x)    #get a list of all values between single quotes
       self.ticketDF[columnName][count] = x #store the list back into the dataframe
       count += 1
</code>```

To work around this issue as shown above, I am replacing each bracket separately and then getting a list of all values between single quotations with this line: x = re.findall('\'([^\']*)\'', x) I am then storing the list back into the dataframe row by row.

I have also tried using csv.DictReader/Writer and it does the same thing.

Is there a way to read the list in the csv without having to do any string modifications? Is there a regular expression I could use to clean up the list's string?

Any thoughts would be greatly appreciated. Thanks!

答:
You can pass a converted for a column to pd.read_csv():

```<code>import pandas as pd
from ast import literal_eval

p = pd.read_csv(path, converters={'Comments':literal_eval})

p['Comments']
# 0    [comment1, comment2, comment3]
# 1    [comment4, comment5, comment6]

p['Comments'][0][1]
# 'comment2'
</code>```

literal_eval will safely evaluate simple expressions like your list.

Body:
I am creating a ticket tracking project where I have a pandas dataframe holding the ticket information. I am then storing this dataframe into a csv file. The dataframe will initialize at the start of the program.

One of the column values is a list. When you store the pandas dataframe in a csv file with this line of code: self.ticketDF.to_csv(self.ticketCSVFilePath), it surrounds the list in double quotes. When you then read it back in, it now is interpreted as a string, not a list. In my example, you can see the list with double quotes under the comments column.

Here is my file - tickets.csv:

Ticket ID,Subject,Project,Description,Priority,Comments
PROT-18,testSubject,testProject,testDescription,testPriority,"['comment1', 'comment2', 'comment3']"
PROT-19,testSubject,testProject,testDescription,testPriority,"['comment4', 'comment5', 'comment6']"

I am initializing the pandas dataframe, using these two functions:

def initializeTicketDF(self):
   if path.exists(self.ticketCSVFilePath) and path.getsize(self.ticketCSVFilePath) > 0:
       self.ticketDF = pd.read_csv(self.ticketCSVFilePath)  #reading the csv file into the dataframe
       self.ticketDF.set_index('Ticket ID', inplace=True)   #I am setting the index to the Ticket ID
       self.columnToList("Comments")                        #Calling my function that currently does the
                                                            #workaround

def columnToList(self, columnName):
   count = 0                                #this represents the current row in the dataframe
   for x in self.ticketDF['Comments']:      #x holds the "Comments" value for every row
       x = x.replace('[', '')               #replace left and right brackets
       x = x.replace(']', '')
       x = re.findall('\'([^\']*)\'', x)    #get a list of all values between single quotes
       self.ticketDF[columnName][count] = x #store the list back into the dataframe
       count += 1

To work around this issue as shown above, I am replacing each bracket separately and then getting a list of all values between single quotations with this line: x = re.findall('\'([^\']*)\'', x) I am then storing the list back into the dataframe row by row.

I have also tried using csv.DictReader/Writer and it does the same thing.

Is there a way to read the list in the csv without having to do any string modifications? Is there a regular expression I could use to clean up the list's string?

Any thoughts would be greatly appreciated. Thanks!

Body:
You can pass a converted for a column to pd.read_csv():

import pandas as pd
from ast import literal_eval

p = pd.read_csv(path, converters={'Comments':literal_eval})

p['Comments']
# 0    [comment1, comment2, comment3]
# 1    [comment4, comment5, comment6]

p['Comments'][0][1]
# 'comment2'

literal_eval will safely evaluate simple expressions like your list.


问:
Understanding list `pop index out of range`
I'm trying to arrange a list generated in ascending order.

Using remove in my while loop works. But if I use pop I keep getting an IndexError: Pop index out of range.

I also tried increasing the length of values list when the last iteration will be carried out; to while len(values) > 1 and I'm still getting the same error.

Can anyone please explain why I keep getting this error when using pop but not when using remove?

```<code>
#import randrange
from random import randrange

#generate a list of values
values = []
for i in range(1, 10):
   values.append(randrange(1, 10))
print(values)

#initiate list for keeping minimum values
new_values = []

#define how least value would be determined
while len(values) > 0 :
   new_values.append(min(values))
   values.pop(min(values))

print(new_values)

</code>```

答: You are providing direct values to pop while writing values.pop(min(values)), instead you have to provide the index position.

Body:
I'm trying to arrange a list generated in ascending order.

Using remove in my while loop works. But if I use pop I keep getting an IndexError: Pop index out of range.

I also tried increasing the length of values list when the last iteration will be carried out; to while len(values) > 1 and I'm still getting the same error.

Can anyone please explain why I keep getting this error when using pop but not when using remove?

#import randrange
from random import randrange

#generate a list of values
values = []
for i in range(1, 10):
   values.append(randrange(1, 10))
print(values)

#initiate list for keeping minimum values
new_values = []

#define how least value would be determined
while len(values) > 0 :
   new_values.append(min(values))
   values.pop(min(values))

print(new_values)


问:
problem with clearInterval() in javascript
I made a simple little timer with a start, reset, plus a nonfunctional stop button. All the documentation that I have read on it makes it seem very simple so I have no idea what's going wrong.

the stop.onclick function is getting read, but it only works for a second before it gets overwritten by the setInterval function

ps- I intend to improve the accuracy so please no hints on how best to do that

```<code>const start = document.getElementById("button1")
const stop = document.getElementById("stop")
const reset = document.getElementById("reset")

var clock = start.onclick = function(){
    let seconds = 1
    let minutes = 0
    setInterval(function() {

        if (minutes == 0){
            if (seconds < 10)
                timer.innerHTML = '0:0' + seconds++;
            else
                timer.innerHTML = '0:' + seconds++;
            if (seconds == 60){
                minutes++
                seconds = 0
            }
        }

        else {
            if (seconds < 10)
                timer.innerHTML = minutes + ':0' + seconds++;
            else
                timer.innerHTML = minutes + ':' + seconds++;
            if (seconds == 60){
                minutes++
                seconds = 0
            }
        }

    }, 1000);
    reset.onclick = function(){
        seconds = 0
    }
    stop.onclick = function(){
        let display = seconds
        timer.innerHTML = display
        clearInterval(clock)
        // alert("You stopped the clock!")
    }
}

```

```

答:
The problem is that that is not how setInterval and clearInterval work.  Specifically, you don't pass clearInterval the function that you have running at some interval to clear the interval.  Instead, setInterval returns a reference to the process; you can then pass that reference to clearInterval to clear it.  For instance:

const myIntervalProcess = setInterval(() => console.log('hi'), 1000);

setTimeout(() => clearInterval(myIntervalProcess), 5000);```
</div>
</div>
</p>

<p>What we see above is that we set a function that logs "hi" to the console every second.  We save the reference returned from <code>setInterval</code> to a variable called <code>myIntervalProcess</code>.  Then we set a timeout to pass <code>myIntervalProcess</code> to <code>clearInterval</code> after five seconds.  If you run this you can see that "hi" will be logged to console exactly five times, after which point it will cease.</p>

<p>If we apply this fix to your code we get:</p>

<pre class="lang-js prettyprint-override"><code>const start = document.getElementById("button1")
const stop = document.getElementById("stop")
const reset = document.getElementById("reset")

var clock = start.onclick = function(){
    let seconds = 1
    let minutes = 0
    const clockProcess = setInterval(function() {

        if (minutes == 0){
            if (seconds < 10)
                timer.innerHTML = '0:0' + seconds++;
            else
                timer.innerHTML = '0:' + seconds++;
            if (seconds == 60){
                minutes++
                seconds = 0
            }
        }

        else {
            if (seconds < 10)
                timer.innerHTML = minutes + ':0' + seconds++;
            else
                timer.innerHTML = minutes + ':' + seconds++;
            if (seconds == 60){
                minutes++
                seconds = 0
            }
        }

    }, 1000);
    reset.onclick = function(){
        seconds = 0
    }
    stop.onclick = function(){
        let display = seconds
        timer.innerHTML = display
        clearInterval(clockProcess)
        // alert("You stopped the clock!")
    }
}
</code>```

Also, for what it's worth, you may wish to use a linter on your code-- I see some missing semicolons and other errors/inconsistencies it would help you catch and resolve.  Good luck!

Body:
I made a simple little timer with a start, reset, plus a nonfunctional stop button. All the documentation that I have read on it makes it seem very simple so I have no idea what's going wrong.

the stop.onclick function is getting read, but it only works for a second before it gets overwritten by the setInterval function

ps- I intend to improve the accuracy so please no hints on how best to do that

const start = document.getElementById("button1")
const stop = document.getElementById("stop")
const reset = document.getElementById("reset")

var clock = start.onclick = function(){
    let seconds = 1
    let minutes = 0
    setInterval(function() {

        if (minutes == 0){
            if (seconds < 10)
                timer.innerHTML = '0:0' + seconds++;
            else
                timer.innerHTML = '0:' + seconds++;
            if (seconds == 60){
                minutes++
                seconds = 0
            }
        }

        else {
            if (seconds < 10)
                timer.innerHTML = minutes + ':0' + seconds++;
            else
                timer.innerHTML = minutes + ':' + seconds++;
            if (seconds == 60){
                minutes++
                seconds = 0
            }
        }

    }, 1000);
    reset.onclick = function(){
        seconds = 0
    }
    stop.onclick = function(){
        let display = seconds
        timer.innerHTML = display
        clearInterval(clock)
        // alert("You stopped the clock!")
    }
}

```

Body:
The problem is that that is not how setInterval and clearInterval work.  Specifically, you don't pass clearInterval the function that you have running at some interval to clear the interval.  Instead, setInterval returns a reference to the process; you can then pass that reference to clearInterval to clear it.  For instance:

const myIntervalProcess = setInterval(() => console.log('hi'), 1000);

setTimeout(() => clearInterval(myIntervalProcess), 5000);

What we see above is that we set a function that logs "hi" to the console every second.  We save the reference returned from setInterval to a variable called myIntervalProcess.  Then we set a timeout to pass myIntervalProcess to clearInterval after five seconds.  If you run this you can see that "hi" will be logged to console exactly five times, after which point it will cease.

If we apply this fix to your code we get:

const start = document.getElementById("button1")
const stop = document.getElementById("stop")
const reset = document.getElementById("reset")

var clock = start.onclick = function(){
    let seconds = 1
    let minutes = 0
    const clockProcess = setInterval(function() {

        if (minutes == 0){
            if (seconds < 10)
                timer.innerHTML = '0:0' + seconds++;
            else
                timer.innerHTML = '0:' + seconds++;
            if (seconds == 60){
                minutes++
                seconds = 0
            }
        }

        else {
            if (seconds < 10)
                timer.innerHTML = minutes + ':0' + seconds++;
            else
                timer.innerHTML = minutes + ':' + seconds++;
            if (seconds == 60){
                minutes++
                seconds = 0
            }
        }

    }, 1000);
    reset.onclick = function(){
        seconds = 0
    }
    stop.onclick = function(){
        let display = seconds
        timer.innerHTML = display
        clearInterval(clockProcess)
        // alert("You stopped the clock!")
    }
}

Also, for what it's worth, you may wish to use a linter on your code-- I see some missing semicolons and other errors/inconsistencies it would help you catch and resolve.  Good luck!


问:
How to validate GUID is a GUID
How to determine if a string contains a GUID vs just a string of numbers.

will a GUID always contain at least 1 alpha character?

答:
See if these helps :-

Guid.Parse - Docs

Guid guidResult = Guid.Parse(inputString)
```
<ol start="2">
<li><code>Guid.TryParse</code> - Docs</li>
</ol>
<pre class="lang-cs prettyprint-override"><code>bool isValid = Guid.TryParse(inputString, out guidOutput)
</code>```

Title: How to validate GUID is a GUID

Body:
See if these helps :-

Guid.Parse - Docs

Guid guidResult = Guid.Parse(inputString)

Guid.TryParse - Docs

bool isValid = Guid.TryParse(inputString, out guidOutput)


问:
Comparison of byte literals in Python
The following question arose because I was trying to use bytes strings as dictionary keys and bytes values that I understood to be equal weren't being treated as equal.

Why doesn't the following Python code compare equal - aren't these two equivalent representations of the same binary data (the example is knowingly chosen to avoid endianness)?

```<code>b'0b11111111' == b'0xff'
</code>```

I know the following evaluates true, demonstrating the equivalence:

```<code>int(b'0b11111111', 2) == int(b'0xff', 16)
</code>```

But why does Python force me to know the representation? Is it related to endianness? Is there some easy way to force these to compare equivalent other than converting them all to, e.g., hexadecimal literals? Is there a transparent and clear method to move between all representations in a (somewhat) platform independent way (or am I asking too much)?

Say I want to actually index a dictionary using 8 bits in the form b'0b11111111', then why does Python expand it to ten bytes and how do I prevent that?

This is a smaller piece of a large tree data structure and expanding my indexing by a factor of 80 seems like a huge waste of memory.

答:
It seems that what you were trying to do is get a byte string representing the value 0b11111111 (or 255). This is not what b'0b11111111' does – that actually stands for a byte string representing the character (Unicode) string '0b11111111'.

What you want would be written as b'\xff'. You can check that it is actually one byte: len(b'\xff') == 1.

To convert a Python int to a binary representation, you can use the ctypes library. You need to choose one of the C integer types, e.g.:

>>> bytes(ctypes.c_ubyte(255))
b'\xff'

>>> bytes(ctypes.c_ubyte(0xff))
b'\xff'

>>> bytes(ctypes.c_long(255))
b'\xff\x00\x00\x00\x00\x00\x00\x00'
```

<p>Note: Instead of <code>c_ubyte</code> and <code>c_long</code>, you can use the aliases <code>c_uint8</code> (i.e. 8-bit unsigned C integer) and <code>c_int64</code> (64-bit signed C integer), respectively.</p>

<p>To convert back:</p>

<pre class="lang-python prettyprint-override"><code>>>> ctypes.c_ubyte.from_buffer_copy(b'\xff').value
255
</code>```

Be careful about overflow:

>>> ctypes.c_ubyte(256)
c_ubyte(0)
```

Title: Comparison of byte literals in Python

Body:
The following question arose because I was trying to use bytes strings as dictionary keys and bytes values that I understood to be equal weren't being treated as equal.

Why doesn't the following Python code compare equal - aren't these two equivalent representations of the same binary data (the example is knowingly chosen to avoid endianness)?

b'0b11111111' == b'0xff'

I know the following evaluates true, demonstrating the equivalence:

int(b'0b11111111', 2) == int(b'0xff', 16)

But why does Python force me to know the representation? Is it related to endianness? Is there some easy way to force these to compare equivalent other than converting them all to, e.g., hexadecimal literals? Is there a transparent and clear method to move between all representations in a (somewhat) platform independent way (or am I asking too much)?

Say I want to actually index a dictionary using 8 bits in the form b'0b11111111', then why does Python expand it to ten bytes and how do I prevent that?

This is a smaller piece of a large tree data structure and expanding my indexing by a factor of 80 seems like a huge waste of memory.

Body:
It seems that what you were trying to do is get a byte string representing the value 0b11111111 (or 255). This is not what b'0b11111111' does – that actually stands for a byte string representing the character (Unicode) string '0b11111111'.

What you want would be written as b'\xff'. You can check that it is actually one byte: len(b'\xff') == 1.

To convert a Python int to a binary representation, you can use the ctypes library. You need to choose one of the C integer types, e.g.:

>>> bytes(ctypes.c_ubyte(255))
b'\xff'

>>> bytes(ctypes.c_ubyte(0xff))
b'\xff'

>>> bytes(ctypes.c_long(255))
b'\xff\x00\x00\x00\x00\x00\x00\x00'

Note: Instead of c_ubyte and c_long, you can use the aliases c_uint8 (i.e. 8-bit unsigned C integer) and c_int64 (64-bit signed C integer), respectively.

To convert back:

>>> ctypes.c_ubyte.from_buffer_copy(b'\xff').value
255

Be careful about overflow:

>>> ctypes.c_ubyte(256)
c_ubyte(0)