问:
How to convert this string "Mon Jan 01 00:00:00 AEDT 1990" into "1990101"?
I have a string "Mon Jan 01 00:00:00 AEDT 1990" and I need to convert it into the format "yyyyMMdd" so in this case it would be "19900101".

I think it's possible to do this with Regular Expressions so that I could pull out the year, month(but would need to convert Jan to 01 and etc) and day from the string but I am not well versed in Regular Expressions. Anyone have any ideas?

答:
Now assuming that each month and day names inside each passed string is matching one of enum name values (i.e "Mar" matches the value of field name in Month.MARCH, while "Marc" or "March" do not) and the format of the sample string you gave us is truly consistent, as in it is no subject to change during runtime and will always remain <day-name> <month> <day> <time> <zone> <year> where year is always a 4 digit number, the following code should answer give you exactly what you want:

Main Class

```<code>public static void main(String[] args) {

    String time = "Mon Jul 05 00:00:00 AEDT 1990";
    int result = CustomDateFormat.parseToInt(time);
    System.out.println("Parsed in format [yyyyMMdd]: " + result);
}
</code>```

CustomDateFormat Class

```<code>import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CustomDateFormat {

    private static final Pattern STANDARD_PATTERN =
    Pattern.compile("^(?:[a-zA-Z]{3})\\s([a-zA-Z]{3})\\s([0-9]{2}).*([0-9]{4})");

    /*
     * This is just in case you want
     * the name of the day as well
     */
    public enum Day {

        MONDAY("Mon", "Monday"),
        TUESDAY("Tue", "Tuesday"),
        WEDNESDAY("Wed", "Wednesday"),
        THURSDAY("Thu", "Thursday"),
        FRIDAY("Fri", "Friday"),
        SATURDAY("Sat", "Saturday"),
        SUNDAY("Sun", "Sunday");

        final String shortName;
        final String fullName;

        Day(String name1, String name2) {
            this.shortName = name1;
            this.fullName = name2;
        }

        public static String getFullName(String alias) {
            for (Day d : Day.values()) {
                if (d.shortName.equals(alias))
                    return d.fullName;
            }
            return "";
        }
    }

    public enum Month {

        JANUARY("Jan", 1), FEBRUARY("Feb", 2),
        MARCH("Mar", 3), APRIL("Apr", 4),
        MAY("May", 5), JUNE("Jun", 6),
        JULY("Jul", 7), AUGUST("Aug", 8),
        SEPTEMBER("Sep", 9), OCTOBER("Oct", 10),
        NOVEMBER("Nov", 11), DECEMBER("Dec", 12);

        final String name;
        final int value;

        Month(String name, int value) {
            this.name = name;
            this.value = value;
        }

        public static int getMonth(String month) {
            for (Month m : Month.values()) {
                if (m.name.equals(month))
                    return m.value;
            }
            return 0;
        }
    }

    public static int parseToInt(String date) {

        System.out.println("Parsing date: " + date);
        Matcher matcher = STANDARD_PATTERN.matcher(date);

        if (matcher.find() && matcher.groupCount() == 3)
        {
            int month = Month.getMonth(matcher.group(1));
            int day = Integer.valueOf(matcher.group(2));
            int year = Integer.valueOf(matcher.group(3));

            if (day == 0 || month == 0) {
                throw new IllegalStateException("Unable to parse day or month from date " + date);
            }
            else return Integer.valueOf(year + "0" + month + "0" + day);
        }
        else throw new IllegalStateException("Unable to parse date " + date);
    }
}
</code>```

Output

```<code>Parsing date: Mon Jul 05 00:00:00 AEDT 1990
Parsed in format [yyyyMMdd]: 19900705
</code>```

Let me know if this meets your requirements and if any other conditions need to be met or special case scenarios considered. It's a fairly simple implementation so it should take no time to adjust it to more specific needs.

EDIT: Fix some implementation mistakes, change sample string to a custom one and remove redundant output line.

Body:
Now assuming that each month and day names inside each passed string is matching one of enum name values (i.e "Mar" matches the value of field name in Month.MARCH, while "Marc" or "March" do not) and the format of the sample string you gave us is truly consistent, as in it is no subject to change during runtime and will always remain <day-name> <month> <day> <time> <zone> <year> where year is always a 4 digit number, the following code should answer give you exactly what you want:

Main Class

public static void main(String[] args) {

    String time = "Mon Jul 05 00:00:00 AEDT 1990";
    int result = CustomDateFormat.parseToInt(time);
    System.out.println("Parsed in format [yyyyMMdd]: " + result);
}

CustomDateFormat Class

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CustomDateFormat {

    private static final Pattern STANDARD_PATTERN =
    Pattern.compile("^(?:[a-zA-Z]{3})\\s([a-zA-Z]{3})\\s([0-9]{2}).*([0-9]{4})");

    /*
     * This is just in case you want
     * the name of the day as well
     */
    public enum Day {

        MONDAY("Mon", "Monday"),
        TUESDAY("Tue", "Tuesday"),
        WEDNESDAY("Wed", "Wednesday"),
        THURSDAY("Thu", "Thursday"),
        FRIDAY("Fri", "Friday"),
        SATURDAY("Sat", "Saturday"),
        SUNDAY("Sun", "Sunday");

        final String shortName;
        final String fullName;

        Day(String name1, String name2) {
            this.shortName = name1;
            this.fullName = name2;
        }

        public static String getFullName(String alias) {
            for (Day d : Day.values()) {
                if (d.shortName.equals(alias))
                    return d.fullName;
            }
            return "";
        }
    }

    public enum Month {

        JANUARY("Jan", 1), FEBRUARY("Feb", 2),
        MARCH("Mar", 3), APRIL("Apr", 4),
        MAY("May", 5), JUNE("Jun", 6),
        JULY("Jul", 7), AUGUST("Aug", 8),
        SEPTEMBER("Sep", 9), OCTOBER("Oct", 10),
        NOVEMBER("Nov", 11), DECEMBER("Dec", 12);

        final String name;
        final int value;

        Month(String name, int value) {
            this.name = name;
            this.value = value;
        }

        public static int getMonth(String month) {
            for (Month m : Month.values()) {
                if (m.name.equals(month))
                    return m.value;
            }
            return 0;
        }
    }

    public static int parseToInt(String date) {

        System.out.println("Parsing date: " + date);
        Matcher matcher = STANDARD_PATTERN.matcher(date);

        if (matcher.find() && matcher.groupCount() == 3)
        {
            int month = Month.getMonth(matcher.group(1));
            int day = Integer.valueOf(matcher.group(2));
            int year = Integer.valueOf(matcher.group(3));

            if (day == 0 || month == 0) {
                throw new IllegalStateException("Unable to parse day or month from date " + date);
            }
            else return Integer.valueOf(year + "0" + month + "0" + day);
        }
        else throw new IllegalStateException("Unable to parse date " + date);
    }
}

Output

Parsing date: Mon Jul 05 00:00:00 AEDT 1990
Parsed in format [yyyyMMdd]: 19900705

Let me know if this meets your requirements and if any other conditions need to be met or special case scenarios considered. It's a fairly simple implementation so it should take no time to adjust it to more specific needs.

EDIT: Fix some implementation mistakes, change sample string to a custom one and remove redundant output line.


来源: stackexchange

问:
How to choose right threshold value for DCU percentage metric alert?
I have created a single instance of azure sql database with DTU-based purchase model. I am trying to setup some metric alerts for this database so once I use this Db for some application I can have better picture of how DTU's are actually being used, how many / much DTU's I will need etc. This information will help me to Configure right Pricing tier for this database.

Pricing tier info

答:
Before you set the alerts, you should first use the Metric to monitor databases using the Azure portal.
In the Azure portal, you can monitor an individual databases utilization by selecting your database and clicking the Monitoring chart. This brings up a Metric window that you can change by clicking the Edit chart button. Add the following metrics:

CPU percentage

DTU percentage

Data IO percentage

Database size percentage

You can also configure alerts on the performance metrics. Click the Add alert button in the Metric window. Follow the wizard to configure your alert. You have the option to alert if the metrics exceed a certain threshold or if the metric falls below a certain threshold.

For example, if you expect the workload on your database to grow, you can choose to configure an email alert whenever your database reaches 80% on any of the performance metrics. You can use this as an early warning to figure out when you might have to switch to the next highest compute size.

The performance metrics can also help you determine if you are able to downgrade to a lower compute size. Assume you are using a Standard S2 database and all performance metrics show that the database on average does not use more than 10% at any given time. It is likely that the database will work well in Standard S1. However, be aware of workloads that spike or fluctuate before making the decision to move to a lower compute size.

Azure gives you the examples are setting the threshold value of the DTU/CPU metric 80%. You also can get this in this document: Create an alert rule on a metric with the Azure portal.

So you can reference this value on threshold. If your database CPU or DTU percentage is over 80%  or with slow performance for a long time, you should consider to scale up the DTU-based price tier.

Hope this helps.

ContentLicense: CC BY-SA 4.0


问:
Can't center div inside slick-slider item with flex
I made a slick slider component in vue, I'm trying to center a circular div inside each one of the slider items but I can't get tit to work, it centers horizontally after I added margin:auto but it doesn't center vertically despite using align and justify center, any idea how I can get this to work? I think it has something to do with how slick slider changes the width of the slick items via javascript...</p>

```<code><template>
<slick class="SLIDERcontainer6_maincontainer" ref="slick" :options="slickOptions">
    <div class="SLIDERcontainer6_item_container" v-for="slider in globals.producsSlider" :key="slider.title">
        <div class="SLIDERcontainer6_item_image" :style="'background-image:url('+slider.image+');'"></div>
    </div>
</slick>
</template>
<!--SCRIPTS-->
<script>
import { mapState } from 'vuex';
import Slick from 'vue-slick';
export default {
name: 'SLIDERcontainer10',

components: { Slick },

computed:
{
    ...mapState('Globals',['globals'])
},

data()
{
    return {
        slickOptions: {
        infinite: true,
        slidesToShow: 4,
        slidesToScroll: 1,
        prevArrow: '<i class="fa fa-chevron-left fs_bigger c_light" style="position:absolute; left:10px; top:50%; transform:translateY(-50%); z-index:99999;"></i>',
        nextArrow: '<i class="fa fa-chevron-right fs_bigger c_light" style="position:absolute; right:10px; top:50%; transform:translateY(-50%); z-index:99999;"></i>',
        arrows: true,
        autoplay: true,
        speed: 2000,
        autoplaySpeed: 4000,
        responsive:
        [
        {
        breakpoint: 1120,
            settings:
            {
            slidesToShow: 3,
            slidesToScroll: 1,
            }
        },
        {
            breakpoint: 800,
            settings:
            {
            slidesToShow: 2,
            slidesToScroll: 2
            }
        },
        {
            breakpoint: 600,
            settings:
            {
            slidesToShow: 1,
            slidesToScroll: 1
            }
        }]
        },

    };
},

beforeUpdate()
{
    if (this.$refs.slick) {
        this.$refs.slick.destroy();
    }
},

updated()
{
    this.$nextTick(function () {
        if (this.$refs.slick) {
            this.$refs.slick.create(this.slickOptions);
        }
    });
},

mounted()
{
    console.log(this.$options.name+' component successfully mounted');

},

};
</script>
<!--STYLES-->
<style scoped>
.SLIDERcontainer6_maincontainer{width:100%; height:auto; position:relative;}
.SLIDERcontainer6_item_container{width:33.33%; height:350px; display:flex; flex-direction:column; align-items:center; justify-content:center; background-color:var(--web_primary_color); position:relative;}
.SLIDERcontainer6_item_image{width:275px; height:275px; border-radius:50%; background-size:cover; background-position:center; margin:auto; align-self:center;}
@media only screen and (max-width: 736px)
{
}
</style>

</code>```

答:
Try adding !important on display: flex for SLIDERcontainer6_item_container.

```<code>.SLIDERcontainer6_item_container {
    display: flex !important;
}
</code>```

It seems that slider library overrides display property.

Body:
I made a slick slider component in vue, I'm trying to center a circular div inside each one of the slider items but I can't get tit to work, it centers horizontally after I added margin:auto but it doesn't center vertically despite using align and justify center, any idea how I can get this to work? I think it has something to do with how slick slider changes the width of the slick items via javascript...

<template>
<slick class="SLIDERcontainer6_maincontainer" ref="slick" :options="slickOptions">

</slick>
</template>

Body:
Try adding !important on display: flex for SLIDERcontainer6_item_container.

.SLIDERcontainer6_item_container {
    display: flex !important;
}

It seems that slider library overrides display property.


问:
MapNetworkDrive will accept any password
I am writing a script for adding a network share to windows laptops provided for students at the school i work at.

The script is written in VBS, and uses the MapNetworkDrive function, so it is very simple, just two dialogs asking for username and password. But when I test it with my own username it seams to completely ignore the password I enter and, presumably, use a password stored somewhere, as it allways maps the drive. Does anyone know where these credentials are stored in windows 7? (It is not stored in credential storage, i checked)

答:
The credentials aren't stored anywhere at all. Rather, Windows is using the credentials of the currently logged-in user to authenticate the connection to the shared resource. That is to say, if the user name and password of the user currently logged in to the local machine matches a user with the appropriate credentials on the remote machine, access will be granted.

Let me see if I can explain that more clearly with an example. Say I'm logged in to my laptop with the user name "Cody Gray" and the password "1234". Then, I try to initiate a connection to a shared resource on my desktop computer. Since I have the same user name and password on my desktop computer, and that user account has sufficient privileges to connect to shared resources remotely, I'll be automatically authenticated and access will be automatically granted. However, if I try to connect to one of my coworkers' machines, on which I do not have an account, I'll be required to provide a user name and password with valid access credentials.

The user name and password you supply to the WSH MapNetworkDrive method are used only if the credentials of the currently logged-in user failed to authenticate successfully. The documentation says:

strUser

Optional. String value indicating the user name. You must supply this argument if you are mapping a network drive using the credentials of someone other than the current user.

strPassword

Optional. String value indicating the user password. You must supply this argument if you are mapping a network drive using the credentials of someone other than the current user.

In short, for testing purposes, you might create a new account on your computer that doesn't correspond directly to an account on the server. And if the students already have accounts on the server, there's no reason to require them to enter their user name and password again; Windows already knows what it is, and it will be used for authentication automatically.

ContentLicense: CC BY-SA 3.0


问:
python pandas replacing strings in dataframe with numbers
Is there any way to use the mapping function or something better to replace values in an entire dataframe?

I only know how to perform the mapping on series.

I would like to replace the strings in the 'tesst' and 'set' column with a number
for example set = 1, test =2

Here is a example of my dataset: (Original dataset is very large)

```<code>ds_r
  respondent  brand engine  country  aware  aware_2  aware_3  age tesst   set
0          a  volvo      p      swe      1        0        1   23   set   set
1          b  volvo   None      swe      0        0        1   45   set   set
2          c    bmw      p       us      0        0        1   56  test  test
3          d    bmw      p       us      0        1        1   43  test  test
4          e    bmw      d  germany      1        0        1   34   set   set
5          f   audi      d  germany      1        0        1   59   set   set
6          g  volvo      d      swe      1        0        0   65  test   set
7          h   audi      d      swe      1        0        0   78  test   set
8          i  volvo      d       us      1        1        1   32   set   set
</code>```

Final result should be

```<code> ds_r
  respondent  brand engine  country  aware  aware_2  aware_3  age  tesst  set
0          a  volvo      p      swe      1        0        1   23      1    1
1          b  volvo   None      swe      0        0        1   45      1    1
2          c    bmw      p       us      0        0        1   56      2    2
3          d    bmw      p       us      0        1        1   43      2    2
4          e    bmw      d  germany      1        0        1   34      1    1
5          f   audi      d  germany      1        0        1   59      1    1
6          g  volvo      d      swe      1        0        0   65      2    1
7          h   audi      d      swe      1        0        0   78      2    1
8          i  volvo      d       us      1        1        1   32      1    1
</code>```

答: df.replace(to_replace=['set', 'test'], value=[1, 2]) from @Ishnark comment on accepted answer.

Body:
Is there any way to use the mapping function or something better to replace values in an entire dataframe?

I only know how to perform the mapping on series.

I would like to replace the strings in the 'tesst' and 'set' column with a number
for example set = 1, test =2

Here is a example of my dataset: (Original dataset is very large)

ds_r
  respondent  brand engine  country  aware  aware_2  aware_3  age tesst   set
0          a  volvo      p      swe      1        0        1   23   set   set
1          b  volvo   None      swe      0        0        1   45   set   set
2          c    bmw      p       us      0        0        1   56  test  test
3          d    bmw      p       us      0        1        1   43  test  test
4          e    bmw      d  germany      1        0        1   34   set   set
5          f   audi      d  germany      1        0        1   59   set   set
6          g  volvo      d      swe      1        0        0   65  test   set
7          h   audi      d      swe      1        0        0   78  test   set
8          i  volvo      d       us      1        1        1   32   set   set

Final result should be

 ds_r
  respondent  brand engine  country  aware  aware_2  aware_3  age  tesst  set
0          a  volvo      p      swe      1        0        1   23      1    1
1          b  volvo   None      swe      0        0        1   45      1    1
2          c    bmw      p       us      0        0        1   56      2    2
3          d    bmw      p       us      0        1        1   43      2    2
4          e    bmw      d  germany      1        0        1   34      1    1
5          f   audi      d  germany      1        0        1   59      1    1
6          g  volvo      d      swe      1        0        0   65      2    1
7          h   audi      d      swe      1        0        0   78      2    1
8          i  volvo      d       us      1        1        1   32      1    1


问:
Using Flexbox to Display Content Not Working HTML CSS
I have a flexbox with an image and text. Currently, I'm using margins and padding, but would it be better with justify content and align content?

Currently, what I'm doing isn't working correctly, I can't seem to get the images to line up with their text. Is there a way for me to put the text and image inline with each other.

Website:

/*flexbox*/
section {
    display: flex;
    flex-flow: wrap;
    width: 80%;

    margin: 1em auto;
    padding: 1em;

    border: solid .125em #00aaff;
    background-color: white;
    opacity:0.9;
}

section > * {
    flex: 1 1 40%;
    padding: 1em;
}

/*Images*/
figure img {
    width:50%;
    margin-left:5em;
}

/*Text*/
p{
    padding: 1em;
    margin-left:-3em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section id="display">
        <figure id="image1">
            <img src="images/512x512.png" alt="Dynamo">
        </figure>

        <article>
                <p><span id="name">Houston Dynamo</span></p>
                <p>Sport Science/Sport Performance Intern</p>
                <p><time datetime="2018-01-01"></time>January 2019 - Present</p>
        </article>

        <figure>
            <img src="images/UW-Logo.png" alt="UIC">
        </figure>

         <article>
                <p><span id="name">University of Madison Wisconsin-Madison</span></p>
                <p>Strength and Conditioning Coach, Graduate Assistant</p>
                <p><time datetime="2011-08-01"></time>August 2018 - <time datetime="2014-12-31">December 2018</time></p>
        </article></code>```

答:
Really helps to avoid flex wrap for a layout like this. I have wrapped each "row" of you layout in a div with class flex-wrapper-thingy to which I have applied display: flex so the flexbox layout is happening in each row.

Now the flexbox config is just in relation to each pair of figure and article elements. align-items: center is the perfect way to get these items to line up nicely despite their different heights. Now check out how few rules are needed to adjust the spacing and relative sizing.

/*flexbox*/
section {
  width: 80%;
  margin: 1em auto;
  padding: 1em;
  border: solid .125em #00aaff;
  background-color: white;
}

.flex-wrapper-thingy {
  display: flex;
  align-items: center;
  justify-content: space-between; // maybe you want to try "center" too
}

section > * {
  padding: 1em;
}

/*Images*/
figure {
  width: 50%;
}

/*Text*/
article {
  margin-left: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section id="display">
  <div class="flex-wrapper-thingy">
    <figure id="image1">
      <img src="https://picsum.photos/200" alt="Dynamo">
    </figure>
    <article>
      <p><span id="name">Houston Dynamo</span></p>
      <p>Sport Science/Sport Performance Intern</p>
      <p><time datetime="2018-01-01"></time>January 2019 - Present</p>
    </article>
  </div>

  <div class="flex-wrapper-thingy">
    <figure>
      <img src="https://picsum.photos/201" alt="UIC">
    </figure>
    <article>
      <p><span id="name">University of Madison Wisconsin-Madison</span></p>
      <p>Strength and Conditioning Coach, Graduate Assistant</p>
      <p><time datetime="2011-08-01"></time>August 2018 - <time datetime="2014-12-31">December 2018</time></p>
    </article>
  </div>
</section></code>```

Body:
I have a flexbox with an image and text. Currently, I'm using margins and padding, but would it be better with justify content and align content?

Currently, what I'm doing isn't working correctly, I can't seem to get the images to line up with their text. Is there a way for me to put the text and image inline with each other.

Website:

/*flexbox*/
section {
    display: flex;
    flex-flow: wrap;
    width: 80%;

    margin: 1em auto;
    padding: 1em;

    border: solid .125em #00aaff;
    background-color: white;
    opacity:0.9;
}

section > * {
    flex: 1 1 40%;
    padding: 1em;
}

/*Images*/
figure img {
    width:50%;
    margin-left:5em;
}

/*Text*/
p{
    padding: 1em;
    margin-left:-3em;
}

Houston Dynamo

Sport Science/Sport Performance Intern

<time datetime="2018-01-01"></time>January 2019 - Present

University of Madison Wisconsin-Madison

Strength and Conditioning Coach, Graduate Assistant

<time datetime="2011-08-01"></time>August 2018 - <time datetime="2014-12-31">December 2018</time>

Body:
Really helps to avoid flex wrap for a layout like this. I have wrapped each "row" of you layout in a div with class flex-wrapper-thingy to which I have applied display: flex so the flexbox layout is happening in each row.

Now the flexbox config is just in relation to each pair of figure and article elements. align-items: center is the perfect way to get these items to line up nicely despite their different heights. Now check out how few rules are needed to adjust the spacing and relative sizing.

/*flexbox*/
section {
  width: 80%;
  margin: 1em auto;
  padding: 1em;
  border: solid .125em #00aaff;
  background-color: white;
}

.flex-wrapper-thingy {
  display: flex;
  align-items: center;
  justify-content: space-between; // maybe you want to try "center" too
}

section > * {
  padding: 1em;
}

/*Images*/
figure {
  width: 50%;
}

/*Text*/
article {
  margin-left: 20px;
}

<section id="display">
  <div class="flex-wrapper-thingy">
    <figure id="image1">
      <img src="https://picsum.photos/200" alt="Dynamo">
    </figure>
    <article>
      <p><span id="name">Houston Dynamo</span></p>
      <p>Sport Science/Sport Performance Intern</p>
      <p><time datetime="2018-01-01"></time>January 2019 - Present</p>
    </article>
  </div>

  <div class="flex-wrapper-thingy">
    <figure>
      <img src="https://picsum.photos/201" alt="UIC">
    </figure>
    <article>
      <p><span id="name">University of Madison Wisconsin-Madison</span></p>
      <p>Strength and Conditioning Coach, Graduate Assistant</p>
      <p><time datetime="2011-08-01"></time>August 2018 - <time datetime="2014-12-31">December 2018</time></p>
    </article>
  </div>
</section>


问:
Retrieve an image to ImageView using Firestore and Firebase Storage
I have an Identification app that retrieves user information based on user authentication. I have TextViews for information like email, idnumber, etc. I have those displaying based on the uId on sign in. I am trying to show the a picture for that specific person to an ImageView. Also, if another person logs in, their picture will show as well.

This run in Android Studio. Firebase storage has an image with a url. I created a collection of "images" that will correspond by the iud (So the uid is the same for the user and the image) that has a string of the image url.  Below is an image of how its set up.

Below is the code:

```<code>    private ImageView ProfileImage;
private Button logout;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_profile);
    fireStore = FirebaseFirestore.getInstance();

    mAuth = FirebaseAuth.getInstance();
    FirebaseUser user = mAuth.getCurrentUser();
    userID = user.getUid();

    Name = (TextView) findViewById(R.id.profileName);
    Email = (TextView) findViewById(R.id.profileEmail);
    TwoPNum = (TextView) findViewById(R.id.profileUid);
    Meal = (TextView) findViewById(R.id.mealsNum);
    PantherFunds = (TextView) findViewById(R.id.pFundsNum);
    Expiration = (TextView) findViewById(R.id.expirationDate);
    Campus = (TextView) findViewById(R.id.campusText);
    ProfileImage = (ImageView) findViewById(R.id.profilePhoto);

    mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();
            //new
            if (user != null) {
                // User is signed in
                Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
                toastMessage("Successfully signed in with: " + user.getEmail());
            } else {
                // User is signed out
                Log.d(TAG, "onAuthStateChanged:signed_out");
                toastMessage("Successfully signed out.");
            }
            showData();
        }

    };

}

private void showData() {
    DocumentReference user = fireStore.collection("users").document(userID);
    user.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<DocumentSnapshot> task) {
            if (task.isSuccessful()) {
                DocumentSnapshot doc = task.getResult();

                assert doc != null;
                Name.setText(doc.getString("name"));
                Email.setText(doc.getString("email"));
                TwoPNum.setText(doc.getString("twop_num"));
                Meal.setText(String.valueOf(doc.getLong("meals")));
                PantherFunds.setText(String.valueOf(doc.getDouble("pfunds")));
                Expiration.setText(getDate(Long.parseLong("expiration_date")));
                Campus.setText(doc.getString("campus"));
            }
        }
    });

}
</code>```

**My first thought was to create another method ShowImage and have a document reference to Firestore based on the uId, then pull the url of the picture and attach that picture to the ImageView like I did with all of the other User information. Didnt work. **

答:
You can use the Picasso plugin to accomplish this.
You simply provide it a url and an ImageView and it will automagically download and place your image in the view.

Simply add it to your gradle dependency file with:

```<code>implementation 'com.squareup.picasso:picasso:(insert latest version)'
</code>```

Or maven:

```<code><dependency>
    <groupId>com.squareup.picasso3</groupId>
    <artifactId>picasso</artifactId>
    <version>(insert latest version)</version>
</dependency>
</code>```

Then you can use something like this to load the image:

```<code>Picasso.get().load("http://i.imgur.com/DvpvklR.png").into(imageView);
</code>```

Body:
I have an Identification app that retrieves user information based on user authentication. I have TextViews for information like email, idnumber, etc. I have those displaying based on the uId on sign in. I am trying to show the a picture for that specific person to an ImageView. Also, if another person logs in, their picture will show as well.

This run in Android Studio. Firebase storage has an image with a url. I created a collection of "images" that will correspond by the iud (So the uid is the same for the user and the image) that has a string of the image url.  Below is an image of how its set up.

Below is the code:

    private ImageView ProfileImage;
private Button logout;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_profile);
    fireStore = FirebaseFirestore.getInstance();

    mAuth = FirebaseAuth.getInstance();
    FirebaseUser user = mAuth.getCurrentUser();
    userID = user.getUid();

    Name = (TextView) findViewById(R.id.profileName);
    Email = (TextView) findViewById(R.id.profileEmail);
    TwoPNum = (TextView) findViewById(R.id.profileUid);
    Meal = (TextView) findViewById(R.id.mealsNum);
    PantherFunds = (TextView) findViewById(R.id.pFundsNum);
    Expiration = (TextView) findViewById(R.id.expirationDate);
    Campus = (TextView) findViewById(R.id.campusText);
    ProfileImage = (ImageView) findViewById(R.id.profilePhoto);

    mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();
            //new
            if (user != null) {
                // User is signed in
                Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
                toastMessage("Successfully signed in with: " + user.getEmail());
            } else {
                // User is signed out
                Log.d(TAG, "onAuthStateChanged:signed_out");
                toastMessage("Successfully signed out.");
            }
            showData();
        }

    };

}

private void showData() {
    DocumentReference user = fireStore.collection("users").document(userID);
    user.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<DocumentSnapshot> task) {
            if (task.isSuccessful()) {
                DocumentSnapshot doc = task.getResult();

                assert doc != null;
                Name.setText(doc.getString("name"));
                Email.setText(doc.getString("email"));
                TwoPNum.setText(doc.getString("twop_num"));
                Meal.setText(String.valueOf(doc.getLong("meals")));
                PantherFunds.setText(String.valueOf(doc.getDouble("pfunds")));
                Expiration.setText(getDate(Long.parseLong("expiration_date")));
                Campus.setText(doc.getString("campus"));
            }
        }
    });

}

**My first thought was to create another method ShowImage and have a document reference to Firestore based on the uId, then pull the url of the picture and attach that picture to the ImageView like I did with all of the other User information. Didnt work. **

Body:
You can use the Picasso plugin to accomplish this.
You simply provide it a url and an ImageView and it will automagically download and place your image in the view.

Simply add it to your gradle dependency file with:

implementation 'com.squareup.picasso:picasso:(insert latest version)'

Or maven:

<dependency>
    <groupId>com.squareup.picasso3</groupId>
    <artifactId>picasso</artifactId>
    <version>(insert latest version)</version>
</dependency>

Then you can use something like this to load the image:

Picasso.get().load("http://i.imgur.com/DvpvklR.png").into(imageView);


问:
How to disable wi-fi on Android device in Appium?
In our test case: I need to disable Wi-Fi at some specific point/action.

I have verified:

```<code>driver[deviceIndex].setConnection(Connection.NONE);
assertEquals(Connection.ALL, driver[deviceIndex].getConnection());
</code>```

But it's not doing anything.

My expectation is "turning OFF wi-fi" and keeping Mobile Data ON.

Current code is doing no action.

答:
What is the type of driver you are using? You should use AndroidDriver if you are working on Android. Here are the working code for me.</p>

```<code>// turn on all (data and wi-fi)
public void turnOnAllData() {
    driver.setConnection(Connection.ALL);

}

// turn off all (data and wi-fi)
public void turnOffAllData() {
    driver.setConnection(Connection.NONE);

}

// turn on airplane
public void turnOnAirplaneMode() {
    driver.setConnection(Connection.AIRPLANE);
}

// turn on data
public void turnOnMobileData() {
    driver.setConnection(Connection.DATA);
}

// turn on wi-fi
public void turnOnWiFi() {
    driver.setConnection(Connection.WIFI);

}
</code>```

Body:
In our test case: I need to disable Wi-Fi at some specific point/action.

I have verified:

driver[deviceIndex].setConnection(Connection.NONE);
assertEquals(Connection.ALL, driver[deviceIndex].getConnection());

But it's not doing anything.

My expectation is "turning OFF wi-fi" and keeping Mobile Data ON.

Current code is doing no action.

Body:
What is the type of driver you are using? You should use AndroidDriver if you are working on Android. Here are the working code for me.

// turn on all (data and wi-fi)
public void turnOnAllData() {
    driver.setConnection(Connection.ALL);

}

// turn off all (data and wi-fi)
public void turnOffAllData() {
    driver.setConnection(Connection.NONE);

}

// turn on airplane
public void turnOnAirplaneMode() {
    driver.setConnection(Connection.AIRPLANE);
}

// turn on data
public void turnOnMobileData() {
    driver.setConnection(Connection.DATA);
}

// turn on wi-fi
public void turnOnWiFi() {
    driver.setConnection(Connection.WIFI);

}


问:
replace a string with special " ' "
I want to find and replace string with special symbol " ' " using gsub of awk.

I tried escape the symbol with \ and even \\ but my code returns > .

```<code>awk '{ gsub("%27","'",$1); print $1 }' file.txt
</code>```

file.txt:

```<code>%27SWAY%27
</code>```

I want above to be replaced to 'SWAY'

答:
Could you please try following too.

```<code>awk '{gsub("%27","\047")} 1'  Input_file
</code>```

Ohh, I just now saw @jas already have this, let me add a sed solution now.

```<code>sed 's/%27/'"'"'/g'  Input_file
</code>```

Or as per @ghoti sir's comment could use in sed like:

```<code>sed "s/%27/'/g" input_file
</code>```

Title: replace a string with special " ' "

Body:
I want to find and replace string with special symbol " ' " using gsub of awk.

I tried escape the symbol with \ and even \\ but my code returns > .

awk '{ gsub("%27","'",$1); print $1 }' file.txt

file.txt:

%27SWAY%27

I want above to be replaced to 'SWAY'

Body:
Could you please try following too.

awk '{gsub("%27","\047")} 1'  Input_file

Ohh, I just now saw @jas already have this, let me add a sed solution now.

sed 's/%27/'"'"'/g'  Input_file

Or as per @ghoti sir's comment could use in sed like:

sed "s/%27/'/g" input_file


问:
Setup Cypress.io to access a page through a proxy
Is it possible to setup cypress.io to access pages through a proxy?

I have a proxy that I need to go through, in order to test my application.
Is there anyway to configure cypress.io to honour the standard HTTP_PROXY environment variables.. or is there some other setup that is required?

答: I use  "cypress": "3.3.1", there is a proxy setting


问:
WordPress + jQuery Mobile - Synchronous XMLHttpRequest on the main thread is deprecated?
Why do I get these errors below after adding jquery mobile to my WordPress website?

```<code>Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.
send @ jquery.min.js?ver=3.1.1:4
ajax @ jquery.min.js?ver=3.1.1:4
a.ajax @ jquery-migrate.min.js?ver=3.0.0:2
r._evalUrl @ jquery.min.js?ver=3.1.1:4
Ia @ jquery.min.js?ver=3.1.1:3
append @ jquery.min.js?ver=3.1.1:3
r.fn.(anonymous function) @ jquery.min.js?ver=3.1.1:3
_include @ jquery.mobile.js:4790
(anonymous) @ jquery.mobile.js:890
(anonymous) @ jquery.mobile.js:4997
e @ jquery.min.js?ver=3.1.1:2
i @ jquery.min.js?ver=3.1.1:2
fireWith @ jquery.min.js?ver=3.1.1:2
A @ jquery.min.js?ver=3.1.1:4
(anonymous) @ jquery.min.js?ver=3.1.1:4

my-wordpress:1 IntersectionObserver.observe(target): target element is not a descendant of root.
</code>```

The WP just stopped working - when I click to the menu and I can see that URL has changed but the page content stay the same.

Any ideas?

This is how I add the jquery stuff in the function.php:

```<code>    // Load latest compiled and minified jquery.
    wp_enqueue_script( 'jquery-min', get_template_directory_uri() . '/node_modules/jquery/dist/jquery.min.js', array(), '3.1.1' );

    // Load latest compiled and minified jquery migrate.
    wp_enqueue_script( 'jquery-migrate-2', get_template_directory_uri() . '/node_modules/jquery-migrate/dist/jquery-migrate.min.js', array(), '3.0.0' );

    // Load latest compiled and minified jquery mobile.
    wp_enqueue_script( 'jquery-mobile', get_template_directory_uri() . '/node_modules/jquery-mobile/dist/jquery.mobile.min.js', array(), '1.4.1' );
</code>```

Notes: I don't have any AJAX call on my WP site.#

I found something odd at the bottom of my page - Loading:

What's that? Is not from me!

I use jQuery mobile because I need to touch and swipe images on mobile devices:

```<code>// bind scroll to anchor links
// http://stackoverflow.com/questions/11397028/document-click-function-for-touch-device
$(document).on("click touchstart", "a[href^='#']", function (e) {
  var id = $(this).attr("href");
  if ($(id).length > 0) {
    e.preventDefault();

    // trigger scroll
    scrollMagicController.scrollTo(id);

      // if supported by the browser we can even update the URL.
    if (window.history && window.history.pushState) {
      history.pushState("", document.title, id);
    }
  }
});

// Add swipe to carousel.
$("#myCarousel").swiperight(function() {
  $(this).carousel('prev');
});
$("#myCarousel").swipeleft(function() {
  $(this).carousel('next');
});
</code>```

答:
Just to add to Examizer's answer, if you prefer not to amend the jQueryMobile code directly you can run your own custom script to set defaults on jQueryMobile. Just make sure you queue it before jQueryMobile's script is queued.

This worked for me:

```<code>$(document).bind("mobileinit", function () {
    $.mobile.ajaxEnabled = false;
});
</code>```

From this answer: https://stackoverflow.com/a/8684532

Body:
Why do I get these errors below after adding jquery mobile to my WordPress website?

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.
send @ jquery.min.js?ver=3.1.1:4
ajax @ jquery.min.js?ver=3.1.1:4
a.ajax @ jquery-migrate.min.js?ver=3.0.0:2
r._evalUrl @ jquery.min.js?ver=3.1.1:4
Ia @ jquery.min.js?ver=3.1.1:3
append @ jquery.min.js?ver=3.1.1:3
r.fn.(anonymous function) @ jquery.min.js?ver=3.1.1:3
_include @ jquery.mobile.js:4790
(anonymous) @ jquery.mobile.js:890
(anonymous) @ jquery.mobile.js:4997
e @ jquery.min.js?ver=3.1.1:2
i @ jquery.min.js?ver=3.1.1:2
fireWith @ jquery.min.js?ver=3.1.1:2
A @ jquery.min.js?ver=3.1.1:4
(anonymous) @ jquery.min.js?ver=3.1.1:4

my-wordpress:1 IntersectionObserver.observe(target): target element is not a descendant of root.

The WP just stopped working - when I click to the menu and I can see that URL has changed but the page content stay the same.

Any ideas?

This is how I add the jquery stuff in the function.php:

    // Load latest compiled and minified jquery.
    wp_enqueue_script( 'jquery-min', get_template_directory_uri() . '/node_modules/jquery/dist/jquery.min.js', array(), '3.1.1' );

    // Load latest compiled and minified jquery migrate.
    wp_enqueue_script( 'jquery-migrate-2', get_template_directory_uri() . '/node_modules/jquery-migrate/dist/jquery-migrate.min.js', array(), '3.0.0' );

    // Load latest compiled and minified jquery mobile.
    wp_enqueue_script( 'jquery-mobile', get_template_directory_uri() . '/node_modules/jquery-mobile/dist/jquery.mobile.min.js', array(), '1.4.1' );

Notes: I don't have any AJAX call on my WP site.#

I found something odd at the bottom of my page - Loading:

What's that? Is not from me!

I use jQuery mobile because I need to touch and swipe images on mobile devices:

// bind scroll to anchor links
// http://stackoverflow.com/questions/11397028/document-click-function-for-touch-device
$(document).on("click touchstart", "a[href^='#']", function (e) {
  var id = $(this).attr("href");
  if ($(id).length > 0) {
    e.preventDefault();

    // trigger scroll
    scrollMagicController.scrollTo(id);

      // if supported by the browser we can even update the URL.
    if (window.history && window.history.pushState) {
      history.pushState("", document.title, id);
    }
  }
});

// Add swipe to carousel.
$("#myCarousel").swiperight(function() {
  $(this).carousel('prev');
});
$("#myCarousel").swipeleft(function() {
  $(this).carousel('next');
});

Body:
Just to add to Examizer's answer, if you prefer not to amend the jQueryMobile code directly you can run your own custom script to set defaults on jQueryMobile. Just make sure you queue it before jQueryMobile's script is queued.

This worked for me:

$(document).bind("mobileinit", function () {
    $.mobile.ajaxEnabled = false;
});

From this answer: https://stackoverflow.com/a/8684532


问:
Angular 6, Externally update variables from data in form fields filled by javascript
I'm essentially trying to add data to a website from a desktop database/CRM tool, where no API exists to the website.
I've found I can load up the webpage, login and use Javascript to fill the form with data from the CRM.

I can see the form fields are correct with my values. However the Angular 6 variables don't update unless I actually physically type in the form fields. So I get 'required field' warnings.

Is the there a way to force Angular to pick up the values in the form fields?

答:
Figure out which events are causing the Angular model to update

```<code>document.querySelectorAll('input, select, textarea').forEach(obj => { obj.keyup(); });
</code>```

Try blur, keyup, change. Angular will be listening to some DOM event handler. Refine the query in the query selector to be a bit more targeted at your inputs and not the whole page.

How did you fill in the field? If you did something like

```<code>document.getElementById('someId').value = 'New Value';
</code>```

Then try calling the DOM events on the element you set.

Body:
Figure out which events are causing the Angular model to update

document.querySelectorAll('input, select, textarea').forEach(obj => { obj.keyup(); });

Try blur, keyup, change. Angular will be listening to some DOM event handler. Refine the query in the query selector to be a bit more targeted at your inputs and not the whole page.

How did you fill in the field? If you did something like

document.getElementById('someId').value = 'New Value';

Then try calling the DOM events on the element you set.


问:
How to call a function which is not a string?
How do I load a function with some code, inside another function exactly the same way?

or

How do I load global_variables() correctly into my step1(), and step2() function without having to copy/paste it in each function?

    def global_variables():
        global txt
        global option_a
        global option_b
        global option_c
        global next_function_a
        global next_function_b
        global next_function_c

    def step1():
        global_variables()

        txt = step1_text # fill with correct text

        option_a = step1a_text
        option_b = step1b_text
        option_c = step1c_text

        next_function_a = step1_1 # variable = call function
        next_function_b = step2 # variable = call function
        next_function_c = step5 # variable = call function

        start_step() # call step function

    def step2():
        global_variables()

        txt = step2_text # fill with correct text

        option_a = step2a_text
        option_b = step2b_text
        option_c = step2c_text

        next_function_a = game_over(step2c_text) # variable = call function
        next_function_b = step3 # variable = call function
        next_function_c = step2_1 # variable = call function

        start_step() # call step function
```

<p>I expect the:</p>

<pre class="lang-py prettyprint-override"><code>    global txt
    global option_a
    global option_b
    global option_c
    global next_function_a
    global next_function_b
    global next_function_c
</code>```

to be included inside the step1(), or step2() function, just as if I would have copy/pasted it each time manually there.

# function to start at each new step
def start_step():
    print(txt) # print story
    attempt = False

    choice = input('> ') # variable = user input prompt

    if "A" in choice or "B" in choice or "C" in choice: # if-statement is '0' in variable (choice) or 1 then
        step_end(choice)
    else: # if-statement is other than 'A' or 'B' or 'C' then
        game_over("Man, learn to type a letter.") # call dead function and show text message

def step_end(choice):
    if choice =="A":
        print(option_a)
        next_function_a()
    elif choice =="B":
        print(option_b)
        next_function_b()
    elif choice =="C":
        print(option_c)
        next_function_c()

# function to exit program without errors by 'game-over' or 'winning' the game
def game_over(why): # function name (parameter)
    print(why) # show argument ('why')
    exit(0) # good normal exit without errors.
```

答:
as the comments suggest,  you might have to global it manually but there are ways around it

you can do this:

```<code>def step(numb):
    global txt
    global option_a
    global option_b
    global option_c
    global next_function_a
    global next_function_b
    global next_function_c
    if num == 1:
        txt = step1_text # fill with correct text

        option_a = step1a_text
        option_b = step1b_text
        option_c = step1c_text

        next_function_a = step1_1 # variable = call function
        next_function_b = step2 # variable = call function
        next_function_c = step5 # variable = call function

        start_step() # call step function
    elif numb == 2:
        txt = step2_text # fill with correct text

        option_a = step2a_text
        option_b = step2b_text
        option_c = step2c_text

        next_function_a = game_over(step2c_text) # variable = call function
        next_function_b = step3 # variable = call function
        next_function_c = step2_1 # variable = call function
</code>```

this way you can write even more steps

hope it helps :)

Body:
How do I load a function with some code, inside another function exactly the same way?

or

How do I load global_variables() correctly into my step1(), and step2() function without having to copy/paste it in each function?

    def global_variables():
        global txt
        global option_a
        global option_b
        global option_c
        global next_function_a
        global next_function_b
        global next_function_c

    def step1():
        global_variables()

        txt = step1_text # fill with correct text

        option_a = step1a_text
        option_b = step1b_text
        option_c = step1c_text

        next_function_a = step1_1 # variable = call function
        next_function_b = step2 # variable = call function
        next_function_c = step5 # variable = call function

        start_step() # call step function

    def step2():
        global_variables()

        txt = step2_text # fill with correct text

        option_a = step2a_text
        option_b = step2b_text
        option_c = step2c_text

        next_function_a = game_over(step2c_text) # variable = call function
        next_function_b = step3 # variable = call function
        next_function_c = step2_1 # variable = call function

        start_step() # call step function

I expect the:

    global txt
    global option_a
    global option_b
    global option_c
    global next_function_a
    global next_function_b
    global next_function_c

to be included inside the step1(), or step2() function, just as if I would have copy/pasted it each time manually there.

# function to start at each new step
def start_step():
    print(txt) # print story
    attempt = False

    choice = input('> ') # variable = user input prompt

    if "A" in choice or "B" in choice or "C" in choice: # if-statement is '0' in variable (choice) or 1 then
        step_end(choice)
    else: # if-statement is other than 'A' or 'B' or 'C' then
        game_over("Man, learn to type a letter.") # call dead function and show text message

def step_end(choice):
    if choice =="A":
        print(option_a)
        next_function_a()
    elif choice =="B":
        print(option_b)
        next_function_b()
    elif choice =="C":
        print(option_c)
        next_function_c()

# function to exit program without errors by 'game-over' or 'winning' the game
def game_over(why): # function name (parameter)
    print(why) # show argument ('why')
    exit(0) # good normal exit without errors.

Body:
as the comments suggest,  you might have to global it manually but there are ways around it

you can do this:

def step(numb):
    global txt
    global option_a
    global option_b
    global option_c
    global next_function_a
    global next_function_b
    global next_function_c
    if num == 1:
        txt = step1_text # fill with correct text

        option_a = step1a_text
        option_b = step1b_text
        option_c = step1c_text

        next_function_a = step1_1 # variable = call function
        next_function_b = step2 # variable = call function
        next_function_c = step5 # variable = call function

        start_step() # call step function
    elif numb == 2:
        txt = step2_text # fill with correct text

        option_a = step2a_text
        option_b = step2b_text
        option_c = step2c_text

        next_function_a = game_over(step2c_text) # variable = call function
        next_function_b = step3 # variable = call function
        next_function_c = step2_1 # variable = call function

this way you can write even more steps

hope it helps :)


答:
If those variable names exist in the scope of the module where the functions are defined then you will need to make the global declarations in step1() and step2() for your code to work.

Instead you could create a dictionary in the module's scope then modify that dictionary in step1() and step2()

```<code>gv_s = {'txt':None,
        'option_a':None,
        'option_b':None,
        'option_c':None,
        'next_function_a':None,
        'next_function_b':None,
        'next_function_c':None}

def step1():

    gv_s['txt'] = step1_text # fill with correct text

    gv_s['option_a'] = step1a_text
    gv_s['option_b'] = step1b_text
    gv_s['option_c'] = step1c_text

    gv_s['next_function_a'] = step1_1 # variable = call function
    gv_s['next_function_b'] = step2 # variable = call function
    gv_s['next_function_c'] = step5 # variable = call function

    start_step() # call step function

def step2():

    gv_s['txt'] = step2_text # fill with correct text

    gv_s['option_a'] = step2a_text
    gv_s['option_b'] = step2b_text
    gv_s['option_c'] = step2c_text

    gv_s['next_function_a'] = game_over(step2c_text) # variable = call function
    gv_s['next_function_b'] = step3 # variable = call function
    gv_s['next_function_c'] = step2_1 # variable = call function

    start_step() # call step function
</code>```

step_end refactored to:

```<code>def step_end(choice):
    if choice =="A":
        print(gv_s['option_a'])
        gv_s['next_function_a']()
    elif choice =="B":
        print(gv_s['option_b'])
        gv_s['next_function_b']()
    elif choice =="C":
        print(gv_s['option_c'])
        gv_s['next_function_c']()
</code>```

That will get it to work but still probably isn't the best way to organize your process.

Another option might be for step1 and step2 to just return a dictionary of options and assign the return value to a name in the module's namespace.

```<code>def step1():
    return {'txt':step1_text,
            'option_a':step1a_text,
            'option_b':step1b_text,
            'option_c':step1c_text,
            'next_function_a':step1_1,
            'next_function_b':step2,
            'next_function_c':step5}

def step2():
    return {'txt':step2_text,
            'option_a':step2a_text,
            'option_b':step2b_text,
            'option_c':step2c_text,
            'next_function_a':game_over(step2c_text),
            'next_function_b':step3,
            'next_function_c':step2_1}

gv_s = step1()
# or
#gv_s = step2()
start_step()
</code>```

With step_end accessing the module level dictionary

```<code>def step_end(choice):
    if choice =="A":
        print(gv_s['option_a'])
        gv_s['next_function_a']()
    elif choice =="B":
        print(gv_s['option_b'])
        gv_s['next_function_b']()
    elif choice =="C":
        print(gv_s['option_c'])
        gv_s['next_function_c']()
</code>```

Instead of a dictionary you could use a class.

Title: How to call a function which is not a string?

Body:
If those variable names exist in the scope of the module where the functions are defined then you will need to make the global declarations in step1() and step2() for your code to work.

Instead you could create a dictionary in the module's scope then modify that dictionary in step1() and step2()

gv_s = {'txt':None,
        'option_a':None,
        'option_b':None,
        'option_c':None,
        'next_function_a':None,
        'next_function_b':None,
        'next_function_c':None}

def step1():

    gv_s['txt'] = step1_text # fill with correct text

    gv_s['option_a'] = step1a_text
    gv_s['option_b'] = step1b_text
    gv_s['option_c'] = step1c_text

    gv_s['next_function_a'] = step1_1 # variable = call function
    gv_s['next_function_b'] = step2 # variable = call function
    gv_s['next_function_c'] = step5 # variable = call function

    start_step() # call step function

def step2():

    gv_s['txt'] = step2_text # fill with correct text

    gv_s['option_a'] = step2a_text
    gv_s['option_b'] = step2b_text
    gv_s['option_c'] = step2c_text

    gv_s['next_function_a'] = game_over(step2c_text) # variable = call function
    gv_s['next_function_b'] = step3 # variable = call function
    gv_s['next_function_c'] = step2_1 # variable = call function

    start_step() # call step function

step_end refactored to:

def step_end(choice):
    if choice =="A":
        print(gv_s['option_a'])
        gv_s['next_function_a']()
    elif choice =="B":
        print(gv_s['option_b'])
        gv_s['next_function_b']()
    elif choice =="C":
        print(gv_s['option_c'])
        gv_s['next_function_c']()

That will get it to work but still probably isn't the best way to organize your process.

Another option might be for step1 and step2 to just return a dictionary of options and assign the return value to a name in the module's namespace.

def step1():
    return {'txt':step1_text,
            'option_a':step1a_text,
            'option_b':step1b_text,
            'option_c':step1c_text,
            'next_function_a':step1_1,
            'next_function_b':step2,
            'next_function_c':step5}

def step2():
    return {'txt':step2_text,
            'option_a':step2a_text,
            'option_b':step2b_text,
            'option_c':step2c_text,
            'next_function_a':game_over(step2c_text),
            'next_function_b':step3,
            'next_function_c':step2_1}

gv_s = step1()
# or
#gv_s = step2()
start_step()

With step_end accessing the module level dictionary

def step_end(choice):
    if choice =="A":
        print(gv_s['option_a'])
        gv_s['next_function_a']()
    elif choice =="B":
        print(gv_s['option_b'])
        gv_s['next_function_b']()
    elif choice =="C":
        print(gv_s['option_c'])
        gv_s['next_function_c']()

Instead of a dictionary you could use a class.


问:
Converting a Date to Datetime gives error in sql
I am storing a date in a varchar(50) column with values like thie:

```<code>1/01/2018
</code>```

I want to convert these to a Datetime value eg: 2018-01-22 00:00:00.0000000

My SQL is like;

```<code>select
  [Site],
  CONVERT(VARCHAR(50), CAST([InvDay] AS DATETIME), 101) as Date,
from tableA;
</code>```

But I am getting;

The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

I tried like this also but same error;

```<code>CONVERT(datetime, [InvDay]) as  Date,
</code>```

How can I make this work?

答:
Look at the values that cannot be converted:

```<code>select invday
from tableA
where try_cast(invday as date) is null and invday is not null;
</code>```

It is also unclear if your format is mm/dd/yyyy or dd/mm/yyyy.  You can specify a format using convert():

```<code>-- mm/dd/yyyy
select invday
from tableA
where try_convert(date, invday, 101) is null and
      invday is not null;

-- dd/mm/yyyy
select invday
from tableA
where try_convert(date, invday, 103) is null and
      invday is not null;
</code>```

Body:
I am storing a date in a varchar(50) column with values like thie:

1/01/2018

I want to convert these to a Datetime value eg: 2018-01-22 00:00:00.0000000

My SQL is like;

select
  [Site],
  CONVERT(VARCHAR(50), CAST([InvDay] AS DATETIME), 101) as Date,
from tableA;

But I am getting;

The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

I tried like this also but same error;

CONVERT(datetime, [InvDay]) as  Date,

How can I make this work?

Body:
Look at the values that cannot be converted:

select invday
from tableA
where try_cast(invday as date) is null and invday is not null;

It is also unclear if your format is mm/dd/yyyy or dd/mm/yyyy.  You can specify a format using convert():

-- mm/dd/yyyy
select invday
from tableA
where try_convert(date, invday, 101) is null and
      invday is not null;

-- dd/mm/yyyy
select invday
from tableA
where try_convert(date, invday, 103) is null and
      invday is not null;


问:
Adding advice around final methods in AspectJ
Is it possible to add advice around a final method using AspectJ? I am totally aware that it is impossible using Spring AOP. But I couldn't find anything related to AspectJ.</p>

答:
Sorry for the introductory personal opinion, but I want to say this: You want to use AspectJ. Why don't you just try? You get a result much faster than by writing a question here and waiting for someone to answer it. Your question format is also unsuited for SO because you don't post any code you have trouble with, you just ask a general question.

Yes, instrumenting final classes and/or methods is possible with AspectJ:

Driver application with final method:

package de.scrum_master.app;

public class Application {
  public final void doSomething() {}

  public static void main(String[] args) {
    new Application().doSomething();
  }
}
```

<p><strong>Aspect in native AspectJ syntax:</strong></p>

<pre class="lang-java prettyprint-override"><code>package de.scrum_master.aspect;

public aspect MyAspect {
  Object around() : execution(* doSomething()) {
    System.out.println(thisJoinPoint);
    return proceed();
  }
}
</code>```

Aspect in @AspectJ syntax:

I really prefer the native syntax, but anyway, for some unknown reason some people seem to prefer this ugly and wordy version with imports, throws, explicitly declared joinpoint instances and more complicated way to proceed:

package de.scrum_master.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

@Aspect
public class MyAspect {
  @Around("execution(* doSomething())")
  public Object aroundAdvice(ProceedingJoinPoint thisJoinPoint) throws Throwable {
    System.out.println(thisJoinPoint);
    return thisJoinPoint.proceed();
  }
}
```

<p><strong>Console log:</strong></p>

<p>The effect is the same for both aspect variants:</p>

<pre class="lang-none prettyprint-override"><code>execution(void de.scrum_master.app.Application.doSomething())
</code>```

Body:
Sorry for the introductory personal opinion, but I want to say this: You want to use AspectJ. Why don't you just try? You get a result much faster than by writing a question here and waiting for someone to answer it. Your question format is also unsuited for SO because you don't post any code you have trouble with, you just ask a general question.

Yes, instrumenting final classes and/or methods is possible with AspectJ:

Driver application with final method:

package de.scrum_master.app;

public class Application {
  public final void doSomething() {}

  public static void main(String[] args) {
    new Application().doSomething();
  }
}

Aspect in native AspectJ syntax:

package de.scrum_master.aspect;

public aspect MyAspect {
  Object around() : execution(* doSomething()) {
    System.out.println(thisJoinPoint);
    return proceed();
  }
}

Aspect in @AspectJ syntax:

I really prefer the native syntax, but anyway, for some unknown reason some people seem to prefer this ugly and wordy version with imports, throws, explicitly declared joinpoint instances and more complicated way to proceed:

package de.scrum_master.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

@Aspect
public class MyAspect {
  @Around("execution(* doSomething())")
  public Object aroundAdvice(ProceedingJoinPoint thisJoinPoint) throws Throwable {
    System.out.println(thisJoinPoint);
    return thisJoinPoint.proceed();
  }
}

Console log:

The effect is the same for both aspect variants:

execution(void de.scrum_master.app.Application.doSomething())


问:
doesn't add img from array to div background
I want to add a background image to a div from an array. It works when I just set the background like this:

```<code>div.style.background = "url(path/to/img.jpg) no-repeat"
</code>```

But if I take it from an array such as this:

```<code>const array=[
    '"url(path/to/img.jpg) no repeat"',
    '"url(path/to/img2.jpg) no repeat"',
    '"url(path/to/img3.jpg) no repeat"'
];
div.style.background = array[1];
</code>```

it does not work.

```<code>const grid = document.getElementById("grid");
const photos = ['"url(img/DSC_0387.JPG) no-repeat"', '"url(img/DSC_0389.JPG) no-repeat"', '"url(img/DSC_0392.JPG) no-repeat"', '"url(img/DSC_0393.JPG) no-repeat"', '"url(img/DSC_0399.JPG) no-repeat"'];

function add() {
  let div = document.createElement('div');
  div.style.background = photos[2];
  div.style.borderRadius = "10px";
  div.style.height = "350px";
  div.style.backgroundSize = "contain";
  grid.appendChild(div);
};
add();
</code>```

答:
In photos Array change the values of the array as below. Remove the single quotes for the values of the array.

```<code>const photos = [
  "url(img/DSC_0387.JPG) no-repeat",
  "url(img/DSC_0389.JPG) no-repeat",
  "url(img/DSC_0392.JPG) no-repeat",
  "url(img/DSC_0393.JPG) no-repeat",
  "url(img/DSC_0399.JPG) no-repeat"
];
</code>```

Body:
I want to add a background image to a div from an array. It works when I just set the background like this:

div.style.background = "url(path/to/img.jpg) no-repeat"

But if I take it from an array such as this:

const array=[
    '"url(path/to/img.jpg) no repeat"',
    '"url(path/to/img2.jpg) no repeat"',
    '"url(path/to/img3.jpg) no repeat"'
];
div.style.background = array[1];

it does not work.

const grid = document.getElementById("grid");
const photos = ['"url(img/DSC_0387.JPG) no-repeat"', '"url(img/DSC_0389.JPG) no-repeat"', '"url(img/DSC_0392.JPG) no-repeat"', '"url(img/DSC_0393.JPG) no-repeat"', '"url(img/DSC_0399.JPG) no-repeat"'];

function add() {
  let div = document.createElement('div');
  div.style.background = photos[2];
  div.style.borderRadius = "10px";
  div.style.height = "350px";
  div.style.backgroundSize = "contain";
  grid.appendChild(div);
};
add();

Body:
In photos Array change the values of the array as below. Remove the single quotes for the values of the array.

const photos = [
  "url(img/DSC_0387.JPG) no-repeat",
  "url(img/DSC_0389.JPG) no-repeat",
  "url(img/DSC_0392.JPG) no-repeat",
  "url(img/DSC_0393.JPG) no-repeat",
  "url(img/DSC_0399.JPG) no-repeat"
];


答:
```<code>import requests

r = requests.get(url)
for i in r.json()['coordinates']['coordinate']:
    print(i['latitude'], i['longitude'])
</code>```

Title: How do I loop through the values in a JSON list

Body:
I have the following JSON and I need to split the longitude and latitude as this seems to just be 1 value.

flowSegmentData
{'frc': 'FRC4', 'currentSpeed': 5, 'freeFlowSpeed': 19,
'currentTravelTime': 455, 'freeFlowTravelTime': 119, 'confidence': 0.97,
'coordinates': {'coordinate': [{'latitude': 40.76318662561519,
'longitude': -73.97803225828615}, {'latitude': 40.76307819934861,
'longitude': -73.97777255819328}, {'latitude': 40.76243445763016,
'longitude': -73.97623298971268}, {'latitude': 40.76217211653262,
'longitude': -73.97560468273522}, {'latitude': 40.76186028731343,
'longitude': -73.97485418331016}, {'latitude': 40.76183730132585,
'longitude': -73.97479828391468}, {'latitude': 40.761791637117156,
'longitude': -73.974692572878}, {'latitude': 40.761147670996316,
'longitude': -73.97318635609318}, {'latitude': 40.760523501913,
'longitude': -73.97171011866205}, {'latitude': 40.76047481980789,
'longitude': -73.97159916585734}, {'latitude': 40.76042245345445,
'longitude': -73.9714749278917}]}, '@version': 'traffic-service 2.0.011'}

getData = urllib.request.urlopen(myURL).read()
mystring = json.loads(getData)

for (value) in mystring.items():
        print(value)


问:
ORA-06550 with alter statement
I'm trying this code for some test and i got this error ORA-06550

I tried to modify column with set and many things still the same result

CODE :

```<code>declare

cursor cur is select  comm from emp where comm is not null ;

enreg emp.comm%type;

moyene number;

somme number;

begin

open cur;
loop

fetch cur into enreg;

if emp.comm=enreg.com then

ALTER TABLE emp

set columun

emp.comm := enreg.com*100/emp.comm ;

end if ;

exit when cur%notfound;

end loop;

end;
</code>```

the expected result is to change every emp.comm with the 10% of it but i got this error

Error :

```<code>ORA-06550: line 12, column 1:
PLS-00103: Encountered the symbol "ALTER" when expecting one of the following:

   ( begin case declare exit for goto if loop mod null pragma
   raise return select update while with
     <<
   continue close current delete fetch lock insert open rollback
   savepoint set sql execute commit forall merge pipe purge

1. declare
2. cursor cur is select  comm from emp where comm is not null ;
3. enreg emp.comm%type;
</code>```

答:
In SQL, you use an UPDATE statement to change values in a table. ALTER TABLE is used to change the structure of a table, such as by adding columns, etc. You could rewrite your code as follows:

```<code>declare
  cursor cur is select  comm from emp where comm is not null;
  enreg   emp.comm%type;
  moyene  number;
  somme   number;
begin
  open cur;

  loop
    fetch cur into enreg;
    exit when cur%notfound;

    if emp.comm = enreg then
      update emp
         set emp.comm = enreg * 100 / emp.comm;
    end if ;
  end loop;

  commit;
end;
</code>```

Best of luck.

Title: ORA-06550 with alter statement

Body:
I'm trying this code for some test and i got this error ORA-06550

I tried to modify column with set and many things still the same result

CODE :

declare

cursor cur is select  comm from emp where comm is not null ;

enreg emp.comm%type;

moyene number;

somme number;

begin

open cur;
loop

fetch cur into enreg;

if emp.comm=enreg.com then

ALTER TABLE emp

set columun

emp.comm := enreg.com*100/emp.comm ;

end if ;

exit when cur%notfound;

end loop;

end;

the expected result is to change every emp.comm with the 10% of it but i got this error

Error :

ORA-06550: line 12, column 1:
PLS-00103: Encountered the symbol "ALTER" when expecting one of the following:

   ( begin case declare exit for goto if loop mod null pragma
   raise return select update while with
     <<
   continue close current delete fetch lock insert open rollback
   savepoint set sql execute commit forall merge pipe purge

1. declare
2. cursor cur is select  comm from emp where comm is not null ;
3. enreg emp.comm%type;

Body:
In SQL, you use an UPDATE statement to change values in a table. ALTER TABLE is used to change the structure of a table, such as by adding columns, etc. You could rewrite your code as follows:

declare
  cursor cur is select  comm from emp where comm is not null;
  enreg   emp.comm%type;
  moyene  number;
  somme   number;
begin
  open cur;

  loop
    fetch cur into enreg;
    exit when cur%notfound;

    if emp.comm = enreg then
      update emp
         set emp.comm = enreg * 100 / emp.comm;
    end if ;
  end loop;

  commit;
end;

Best of luck.


问:
Adding two big numbers in javascript
I've been trying to add the following numbers using javascript;
76561197960265728 + 912447736

Sadly, because of rounding in javascript it will not get the correct number, I need the number as a string.

I've tried removing the last few digits using substr and then adding the two numbers together and then putting the two strings together, sadly this doesn't work if the first of the number is a 1.

```<code>function steamid(tradelink){
    var numbers = parseInt(tradelink.split('?partner=')[1].split('&')[0]),
            base = '76561197960265728';

    var number = parseInt(base.substr(-(numbers.toString().length + 1))) + numbers;
            steamid = //put back together
}

steamid('https://steamcommunity.com/tradeoffer/new/?partner=912447736&token=qJD0Oui2');
</code>```

Expected:
76561198872713464

答:
For doing operations with such big integers, you should use BigInt, it will correctly operate on integers bigger than 2ˆ53 (which is the largest size that normal Number can support on JS

const sum = BigInt(76561197960265728) + BigInt(912447736);

console.log(sum.toString());```

Edit 2020: This API still not widely supported by some browsers, so you may need to have a polyfill, please check this library

Title: Adding two big numbers in javascript

Body:
I've been trying to add the following numbers using javascript;
76561197960265728 + 912447736

Sadly, because of rounding in javascript it will not get the correct number, I need the number as a string.

I've tried removing the last few digits using substr and then adding the two numbers together and then putting the two strings together, sadly this doesn't work if the first of the number is a 1.

function steamid(tradelink){
    var numbers = parseInt(tradelink.split('?partner=')[1].split('&')[0]),
            base = '76561197960265728';

    var number = parseInt(base.substr(-(numbers.toString().length + 1))) + numbers;
            steamid = //put back together
}

steamid('https://steamcommunity.com/tradeoffer/new/?partner=912447736&token=qJD0Oui2');

Expected:
76561198872713464

Body:
For doing operations with such big integers, you should use BigInt, it will correctly operate on integers bigger than 2ˆ53 (which is the largest size that normal Number can support on JS

const sum = BigInt(76561197960265728) + BigInt(912447736);

console.log(sum.toString());

Edit 2020: This API still not widely supported by some browsers, so you may need to have a polyfill, please check this library


问:
How to convert hex to float using C#
I'm get data from ST MCU via UART and display value to PC screen but its result is different with what I expected in float type.

I'm using TrueStudio for ST MCU and C# to display values in screen.
I'm using float value at MCU and send data to PC
When I get in PC, if I display float value to textBox, its result is too different with I expected.
In TrueStudio memory view and watch view, I can see below

In TrueStudio MCU, I can see

in watch window : acc.x = 5.12400007

in memory view : 5.124000E0 in floating point format
                CFF7A340 in hex format

I could get this data in PC via visual studio in C#

I can see byte[] array data via watch window and I can see I got

```<code>msg[4] = 0xCF, msg[5] = 0xF7, msg[6] = 0xA3, msg[7] = 0x40
</code>```

so in dec, 3489112896

I converted this value with these but I couldn't get what I wanted, 5.124

```<code>str = "3489112896"
Convert.ToDouble(str) = 2246812992
</code>```

Converted dec to UInt32 so

```<code>u32 = Convert.ToDouble(str)
u32 = 0xcff7a340
(double)u32 = 3489112896
(float)u32 = 3.48911283E+09
BitConverter.ToSingle(BitConverter.GetBytes((int)u32), 0) = -2.21599971E-35
</code>```

In TrueStudio, copied like below (in C)

```<code>memcpy(&ethBuf[len], &g_Bsp.acc, sizeof(ACC_ST));
len += sizeof(ACC_ST);
</code>```

In visual studio, C#

```<code>UInt32 u32 = (UInt32)( msg[4] | (msg[5] << 8) | (msg[6] << 16) | (msg[7]<<24));
LOG("u32 : " + u32 + "\n");
</code>```

I have tried with MSB/LSB first and couldn't get what I wanted.
How can I get 5.123 floating value in C#?

答:
You can convert to hex using BitConverter.GetBytes and BitConverter.ToString:

```<code>public static string FloatToHex(float val)
{
    var bytes = BitConverter.GetBytes(val);
    return BitConverter.ToString(bytes).Replace("-", string.Empty);
}
</code>```

And you can convert back from hex by converting the data back into a byte array, and then using BitConverter.ToSingle:

```<code>public static float HexToFloat(string hexVal)
{
    byte[] data = new byte[hexVal.Length / 2];
    for (int i = 0; i < data.Length; ++i)
    {
        data[i] = Convert.ToByte(hexVal.Substring(i * 2, 2), 16);
    }
    return BitConverter.ToSingle(data, 0);
}
</code>```

Try it online

Depending on the system you want to exchange data with, you might have to account for endianness and reverse the order of the bytes accordingly. You can check for endianness using BitConverter.IsLittleEndian.

Title: How to convert hex to float using C#

Body:
I'm get data from ST MCU via UART and display value to PC screen but its result is different with what I expected in float type.

I'm using TrueStudio for ST MCU and C# to display values in screen.
I'm using float value at MCU and send data to PC
When I get in PC, if I display float value to textBox, its result is too different with I expected.
In TrueStudio memory view and watch view, I can see below

In TrueStudio MCU, I can see

in watch window : acc.x = 5.12400007

in memory view : 5.124000E0 in floating point format
                CFF7A340 in hex format

I could get this data in PC via visual studio in C#

I can see byte[] array data via watch window and I can see I got

msg[4] = 0xCF, msg[5] = 0xF7, msg[6] = 0xA3, msg[7] = 0x40

so in dec, 3489112896

I converted this value with these but I couldn't get what I wanted, 5.124

str = "3489112896"
Convert.ToDouble(str) = 2246812992

Converted dec to UInt32 so

u32 = Convert.ToDouble(str)
u32 = 0xcff7a340
(double)u32 = 3489112896
(float)u32 = 3.48911283E+09
BitConverter.ToSingle(BitConverter.GetBytes((int)u32), 0) = -2.21599971E-35

In TrueStudio, copied like below (in C)

memcpy(&ethBuf[len], &g_Bsp.acc, sizeof(ACC_ST));
len += sizeof(ACC_ST);

In visual studio, C#

UInt32 u32 = (UInt32)( msg[4] | (msg[5] << 8) | (msg[6] << 16) | (msg[7]<<24));
LOG("u32 : " + u32 + "\n");

I have tried with MSB/LSB first and couldn't get what I wanted.
How can I get 5.123 floating value in C#?

Body:
You can convert to hex using BitConverter.GetBytes and BitConverter.ToString:

public static string FloatToHex(float val)
{
    var bytes = BitConverter.GetBytes(val);
    return BitConverter.ToString(bytes).Replace("-", string.Empty);
}

And you can convert back from hex by converting the data back into a byte array, and then using BitConverter.ToSingle:

public static float HexToFloat(string hexVal)
{
    byte[] data = new byte[hexVal.Length / 2];
    for (int i = 0; i < data.Length; ++i)
    {
        data[i] = Convert.ToByte(hexVal.Substring(i * 2, 2), 16);
    }
    return BitConverter.ToSingle(data, 0);
}

Try it online

Depending on the system you want to exchange data with, you might have to account for endianness and reverse the order of the bytes accordingly. You can check for endianness using BitConverter.IsLittleEndian.


问:
How does the boolean keyword argument get evaluated in a method?
Hopefully this isn't too dumb/basic, but I think I am missing an essential building block.

I am writing a Python loop to rename files based on OCR results, but want to have the option to keep the original filename. I am new to Python and programming, and have a question to how boolean logic is computed. As background, I understand that True is True, False is False, not True is False, and not False is True.

As for the method/function, it checks to see if the keyword argument for rename = True or False. To do this, I have an if loop that just says "if rename:". By default rename is False. I am unsure why saying "if rename: then dont rename files" does not work, but  writing"if not rename: dont rename files" does work.

I figured out that if I type "if not rename: don't rename files", I get the expected result, but I am not sure why that works.

```<code>def pnid_rename(file_name, new_name, rename = False):
    if not rename:
        print('Not renaming')
        return
    else:
        print('Renaming ' + file_name)
        os.rename(file_name, str(new_name) + '.png')
        return
</code>```

To me, "if rename" is the same as "if False", as rename = False, so the files should not rename because it is True that False == False. Instead, this triggers the rename loop.

So why do I need 'not'?

答:
Is similar to ask if the variable rename is empty or has any value. So if you write:

```<code>if rename:
        print('Not renaming')
</code>```

Is like if you're asking, if the rename variable has any content , so is that true? No, because the value is False, for that reason in that case the function returns Renaming...

And if you write:

```<code>if not rename:
        print('Not renaming')
</code>```

Is like if you're asking, if the value doesn't have any value, and that is true, because False is similar to say empty. This is a way to understand your logic, but in fact it's not an issue.

Body:
Hopefully this isn't too dumb/basic, but I think I am missing an essential building block.

I am writing a Python loop to rename files based on OCR results, but want to have the option to keep the original filename. I am new to Python and programming, and have a question to how boolean logic is computed. As background, I understand that True is True, False is False, not True is False, and not False is True.

As for the method/function, it checks to see if the keyword argument for rename = True or False. To do this, I have an if loop that just says "if rename:". By default rename is False. I am unsure why saying "if rename: then dont rename files" does not work, but  writing"if not rename: dont rename files" does work.

I figured out that if I type "if not rename: don't rename files", I get the expected result, but I am not sure why that works.

def pnid_rename(file_name, new_name, rename = False):
    if not rename:
        print('Not renaming')
        return
    else:
        print('Renaming ' + file_name)
        os.rename(file_name, str(new_name) + '.png')
        return

To me, "if rename" is the same as "if False", as rename = False, so the files should not rename because it is True that False == False. Instead, this triggers the rename loop.

So why do I need 'not'?

Body:
Is similar to ask if the variable rename is empty or has any value. So if you write:

if rename:
        print('Not renaming')

Is like if you're asking, if the rename variable has any content , so is that true? No, because the value is False, for that reason in that case the function returns Renaming...

And if you write:

if not rename:
        print('Not renaming')

Is like if you're asking, if the value doesn't have any value, and that is true, because False is similar to say empty. This is a way to understand your logic, but in fact it's not an issue.


问:
Can I send auto generated email via Cloud Function and GSuite GMail API?
I have GSuite organisation and Google Cloud Project. I need to send auto-generated email from f.e auto@myorg.com on google cloud invocation. Is it possible?

There are lots of examples how to send email via gmail from cloud function. But how can I use my organisation email as a sender source.

答:
You can try using a service account.

You'll need to delegate domain-wide authority to a service account that's bound to your GCP project and enable the appropriate scopes to send email via the gmail api.

Once you have your service account properly configured you can then leverage the google api node.js client library with your service account credentials in your cloud function to send emails on behalf of any user within your organization.


问:
Could not find a setter for property in class
I'm trying to create Criteria as follow:

```<code>var criteria - session.CreateSQLQuery("select * from myTable where ID in (select id from tableB) AND ANOTHERID IN(select id from tableC)");

criteria.SetResultTransformer(Transformers.AliasToBean(typeof(myClass))).List<MyClass>().ToList()
</code>```

And got the following exception:

Could not find a setter for property 'NAME' in class 'MYCLASS'

hbm property:

```<code><property name="Name" type="string" column="NAME" not-null="true" update="true" insert="true"/>
</code>```

.cs:

```<code>private string name;
public virtual string Name
{
   get {return this.name;}
   set { this.name=value;}
}
</code>```

What I'm missing here?

答:
Versions of NHibernate prior 5.0 had a bug where properties were matched case sensitively. In the 5.0+ this query would work.

AliasToBeanResultTransformer (Transformer.AliasToBean(...)) is intended to be used with "projections" and therefore does not use mappings to do the binding from columns to the class.

If you want to return an entity and want to leverage the mapping, you'll need to call AddEntity(...) on your query, like this:

```<code>var query = session.CreateSQLQuery("select * from myTable where ID in (select id from tableB) AND ANOTHERID IN(select id from tableC)");

query.AddEntity(typeof(myClass)).List<MyClass>();
</code>```

Body:
I'm trying to create Criteria as follow:

var criteria - session.CreateSQLQuery("select * from myTable where ID in (select id from tableB) AND ANOTHERID IN(select id from tableC)");

criteria.SetResultTransformer(Transformers.AliasToBean(typeof(myClass))).List<MyClass>().ToList()

And got the following exception:

Could not find a setter for property 'NAME' in class 'MYCLASS'

hbm property:

<property name="Name" type="string" column="NAME" not-null="true" update="true" insert="true"/>

.cs:

private string name;
public virtual string Name
{
   get {return this.name;}
   set { this.name=value;}
}

What I'm missing here?

Body:
Versions of NHibernate prior 5.0 had a bug where properties were matched case sensitively. In the 5.0+ this query would work.

AliasToBeanResultTransformer (Transformer.AliasToBean(...)) is intended to be used with "projections" and therefore does not use mappings to do the binding from columns to the class.

If you want to return an entity and want to leverage the mapping, you'll need to call AddEntity(...) on your query, like this:

var query = session.CreateSQLQuery("select * from myTable where ID in (select id from tableB) AND ANOTHERID IN(select id from tableC)");

query.AddEntity(typeof(myClass)).List<MyClass>();


问:
Inside of classes .grid_rowconfigure() not working
I am creating a GUI based Python game. I have a class for every frame that I am using, but when I set the rows and columns so that they scale with the window, nothing happens. The code executes, but it doesn't do what it should do. I am very new to the coding scene, and after researching for a few hours, I could not find a solution.

I have looked around this site and other places on Google for an answer. I have tested what I coded outside of classes and frames and it all worked. Adding that stuff back in again made it not work.

```<code>from tkinter import *
import sys
class Application(Tk):
    def __init__(self):
        Tk.__init__(self)
        self._frame = None
        self.switch_frame(StartPage)
    def switch_frame(self, frame_class):
        """Destroys current frame and replaces it with a new one."""
        new_frame = frame_class(self)
        if self._frame is not None:
            self._frame.destroy()
        self._frame = new_frame
        self._frame.pack()
#This is the starting page
class StartPage(Frame):
    def __init__(self, root):
        Frame.__init__(self, root)
        label_1 = Label(self,text="I exist", font=('Courier', 30))
        label_1.grid(row=0, column=1)
        label_2 = Label(self, text="Pick a way to play", font=('Courier', 15))
        label_2.grid(row=1, column=1)
        button_1 = Button(self, text="New Game", fg='black', bg='green', width=25, command=lambda: root.switch_frame(PlayerInfo))
        button_1.grid(row=1, column=0)
        button_2 = Button(self, text="Load Game", fg='black', bg='yellow', width=25, command=lambda: root.switch_frame(LoadGame))
        button_2.grid(row=1, column=2)
        button_3 = Button(self, text='Exit Game', fg='black', bg='red', width=25, command=lambda: sys.exit())
        button_3.grid(row=2, column=1)
        label_3 = Label(self, text='')
        label_3.grid(row=1, column=1)
        label_4 = Label(self, text='')
        label_4.grid(row=2, column=0)
        label_5 = Label(self, text='')
        label_5.grid(row=2, column=2)
#Here is the configuring problem
        self.grid_columnconfigure(0,weight=1)
        self.grid_columnconfigure(1,weight=1)
        self.grid_columnconfigure(2,weight=1)
        self.grid_columnconfigure(3,weight=1)
        self.grid_rowconfigure(3, weight=1)
        self.grid_rowconfigure(0,weight=1)
        self.grid_rowconfigure(1,weight=1)
        self.grid_rowconfigure(2,weight=1)
class PlayerInfo(Frame):
    def __init__(self, root):
        Frame.__init__(self, root)
        Label(self, text='Game will start').pack()
class LoadGame(Frame):
    def __init__(self, root):
        Frame.__init__(self, root)
        Label(self, text='Load old game').pack()
#Run it
if __name__ == "__main__":
    app = Application()
    app.mainloop()
</code>```

I understand how to use .grid_rowconfigure(), however when using it inside of a class it just hasn't been doing anything at all. Any help or advice is greatly appreciated! :)

答:
The problem is not with grid_rowconfigure(), but rather how you pack your frame. Your frame occupies only the space it needs to, and so even your window expands it stays the same.

To have the frame also expands, pass two more parameters to your pack method:

```<code>self._frame.pack(expand=True,fill="both")
</code>```

Body:
I am creating a GUI based Python game. I have a class for every frame that I am using, but when I set the rows and columns so that they scale with the window, nothing happens. The code executes, but it doesn't do what it should do. I am very new to the coding scene, and after researching for a few hours, I could not find a solution.

I have looked around this site and other places on Google for an answer. I have tested what I coded outside of classes and frames and it all worked. Adding that stuff back in again made it not work.

from tkinter import *
import sys
class Application(Tk):
    def __init__(self):
        Tk.__init__(self)
        self._frame = None
        self.switch_frame(StartPage)
    def switch_frame(self, frame_class):
        """Destroys current frame and replaces it with a new one."""
        new_frame = frame_class(self)
        if self._frame is not None:
            self._frame.destroy()
        self._frame = new_frame
        self._frame.pack()
#This is the starting page
class StartPage(Frame):
    def __init__(self, root):
        Frame.__init__(self, root)
        label_1 = Label(self,text="I exist", font=('Courier', 30))
        label_1.grid(row=0, column=1)
        label_2 = Label(self, text="Pick a way to play", font=('Courier', 15))
        label_2.grid(row=1, column=1)
        button_1 = Button(self, text="New Game", fg='black', bg='green', width=25, command=lambda: root.switch_frame(PlayerInfo))
        button_1.grid(row=1, column=0)
        button_2 = Button(self, text="Load Game", fg='black', bg='yellow', width=25, command=lambda: root.switch_frame(LoadGame))
        button_2.grid(row=1, column=2)
        button_3 = Button(self, text='Exit Game', fg='black', bg='red', width=25, command=lambda: sys.exit())
        button_3.grid(row=2, column=1)
        label_3 = Label(self, text='')
        label_3.grid(row=1, column=1)
        label_4 = Label(self, text='')
        label_4.grid(row=2, column=0)
        label_5 = Label(self, text='')
        label_5.grid(row=2, column=2)
#Here is the configuring problem
        self.grid_columnconfigure(0,weight=1)
        self.grid_columnconfigure(1,weight=1)
        self.grid_columnconfigure(2,weight=1)
        self.grid_columnconfigure(3,weight=1)
        self.grid_rowconfigure(3, weight=1)
        self.grid_rowconfigure(0,weight=1)
        self.grid_rowconfigure(1,weight=1)
        self.grid_rowconfigure(2,weight=1)
class PlayerInfo(Frame):
    def __init__(self, root):
        Frame.__init__(self, root)
        Label(self, text='Game will start').pack()
class LoadGame(Frame):
    def __init__(self, root):
        Frame.__init__(self, root)
        Label(self, text='Load old game').pack()
#Run it
if __name__ == "__main__":
    app = Application()
    app.mainloop()

I understand how to use .grid_rowconfigure(), however when using it inside of a class it just hasn't been doing anything at all. Any help or advice is greatly appreciated! :)

Body:
The problem is not with grid_rowconfigure(), but rather how you pack your frame. Your frame occupies only the space it needs to, and so even your window expands it stays the same.

To have the frame also expands, pass two more parameters to your pack method:

self._frame.pack(expand=True,fill="both")


问:
Cassandra db PHP driver, cannot page queries with both ORDER BY and a IN restriction on the partition key
I cant get results for the following query using datastax PHP driver,

```<code>select * from track where id='35209' and day in (20180314,20180315,20180316) and datetime < '2018-03-15 11:00:00' order by datetime desc limit 1;
</code>```

error message : "Cannot page queries with both ORDER BY and a IN restriction on the partition key; you must either remove the ORDER BY or the IN and sort client side, or disable paging for this query"

So how can I disable paging when "executeAsync" ?

答: CREATE TABLE music (artist text, album text, tr_num int, song text, PRIMARY KEY((artist), album , tr_num)) with clustering order by (album DESC ,tr_num DESC);</p>

Body:
I cant get results for the following query using datastax PHP driver,

select * from track where id='35209' and day in (20180314,20180315,20180316) and datetime < '2018-03-15 11:00:00' order by datetime desc limit 1;

error message : "Cannot page queries with both ORDER BY and a IN restriction on the partition key; you must either remove the ORDER BY or the IN and sort client side, or disable paging for this query"

So how can I disable paging when "executeAsync" ?


问:
My table header resizes when setting table body to block to only make that part scrollable, how do I prevent that?
So, I tried creating a table in which only the body is scrollable, but can't seem to fix this issue. The table header should be as wide as the table body of course.. What am I doing wrong?

The visual result

This is my HTML and CSS for the table:

(NOTE: I insert the table rows via JS)

```<code><table class="metadata_table">
<thead class="thead">
    <tr class="tr">
        <th class="th" scope="col">Tag</th>
        <th class="th" scope="col">Creator</th>
        <th class="th" scope="col">Source</th>
        <th class="th" scope="col">Date of creation</th>
    </tr>
</thead>
<tbody class="table-body">
</tbody>
</code>```

```<code>.metadata_table {
    position: absolute;
    bottom: 120px;
    max-height: 105px;
    text-align: left;
    line-height: 35px;
    border-collapse: separate;
    border-spacing: 0;
    display: none;
    float: top;
    width: fit-content;
}

thead tr:first-child {
    background: #39ae3f;
    color: #fff;
    border: none;
}

.th, .td {
    padding: 0 15px 0 20px;
}

.th {
    font-weight: 500;
}

thead .tr:last-child .th {
    border-bottom: 3px solid #ddd;
}

tbody .tr:hover {
    background-color: #f2f2f2;
    cursor: default;
}

tbody .td {
    border-bottom: 1px solid #ddd;
}

.table-body {
    display: block;
    overflow-y: scroll;
    height: 105px;
    overflow-x: hidden;
}

.td:last-child {
    text-align: right;
    padding-right: 10px;
}
</code>```

答:
You'll need to set static widths, perhaps in EMs, or use JavaScript to set the widths:</p>

```<code>function setHeaderCellWidths() {
    var aSlice=Array.prototype.slice;
    aSlice.call(document.querySelectorAll('.metadata_table')).forEach(function(table){
        var tds=table.querySelectorAll('tbody:first-of-type tr:first-child>*');
        aSlice.call(table.querySelectorAll('thead th')).forEach(function(cell,idx){
            cell.style.width=window.getComputedStyle(tds[idx],null).width;
        });
    });
}
window.addEventListener('load',setHeaderCellWidths,null);
window.addEventListener('resize',function(){
    clearTimeout(setHeaderCellWidths.timer);
    setHeaderCellWidths.timer=setTimeout(setHeaderCellWidths,250);
},null);
</code>```

Body:
So, I tried creating a table in which only the body is scrollable, but can't seem to fix this issue. The table header should be as wide as the table body of course.. What am I doing wrong?

The visual result

This is my HTML and CSS for the table:

(NOTE: I insert the table rows via JS)

        Tag
        Creator
        Source
        Date of creation

.metadata_table {
    position: absolute;
    bottom: 120px;
    max-height: 105px;
    text-align: left;
    line-height: 35px;
    border-collapse: separate;
    border-spacing: 0;
    display: none;
    float: top;
    width: fit-content;
}

thead tr:first-child {
    background: #39ae3f;
    color: #fff;
    border: none;
}

.th, .td {
    padding: 0 15px 0 20px;
}

.th {
    font-weight: 500;
}

thead .tr:last-child .th {
    border-bottom: 3px solid #ddd;
}

tbody .tr:hover {
    background-color: #f2f2f2;
    cursor: default;
}

tbody .td {
    border-bottom: 1px solid #ddd;
}

.table-body {
    display: block;
    overflow-y: scroll;
    height: 105px;
    overflow-x: hidden;
}

.td:last-child {
    text-align: right;
    padding-right: 10px;
}

Body:
You'll need to set static widths, perhaps in EMs, or use JavaScript to set the widths:

function setHeaderCellWidths() {
    var aSlice=Array.prototype.slice;
    aSlice.call(document.querySelectorAll('.metadata_table')).forEach(function(table){
        var tds=table.querySelectorAll('tbody:first-of-type tr:first-child>*');
        aSlice.call(table.querySelectorAll('thead th')).forEach(function(cell,idx){
            cell.style.width=window.getComputedStyle(tds[idx],null).width;
        });
    });
}
window.addEventListener('load',setHeaderCellWidths,null);
window.addEventListener('resize',function(){
    clearTimeout(setHeaderCellWidths.timer);
    setHeaderCellWidths.timer=setTimeout(setHeaderCellWidths,250);
},null);