问:
Error in constexpr using clang to compile TensorFlow
I am trying to compile tensorflow using clang ,
And getting following error regarding constexpr

```<code>In file included from /tensorflow/tensorflow/lite/tools/make/downloads/absl/absl/time/clock.h:26:
/tensorflow/tensorflow/lite/tools/make/downloads/absl/absl/time/time.h:1404:55: error: constexpr function's 2nd parameter type 'std::ratio<60>' is not a literal type
constexpr Duration FromInt64(int64_t v, std::ratio<60>) {
                                        ~~~~~~~~~~~~~~^
/toolkit/include/usr/h/public/ratio:100:9: note: 'ratio<60, 1>' is not literal because it is not an aggregate and has no constexpr constructors other than copy or move constructors
        struct ratio
               ^
</code>```

This is the relevant piece of code:

template <std::intmax_t N>
constexpr Duration FromInt64(int64_t v, std::ratio<1, N>) {
  static_assert(0 < N && N <= 1000 * 1000 * 1000, "Unsupported ratio");
  // Subsecond ratios cannot overflow.
  return MakeNormalizedDuration(
      v / N, v % N * kTicksPerNanosecond * 1000 * 1000 * 1000 / N);
}

constexpr Duration FromInt64(int64_t v, std::ratio<60>) {
  return (v <= (std::numeric_limits<int64_t>::max)() / 60 &&
          v >= (std::numeric_limits<int64_t>::min)() / 60)
             ? MakeDuration(v * 60)
             : v > 0 ? InfiniteDuration() : -InfiniteDuration();
}
```

Thanks if someone can point me to the right direction

答:
It seems to work in a playground for me</p>

```<code>#include <ratio>
#include <iostream>

template <std::intmax_t N>
constexpr std::intmax_t FromInt64(int64_t v, std::ratio<1, N>) {
  static_assert(0 < N && N <= 1000 * 1000 * 1000, "Unsupported ratio");
  return N;
}

constexpr std::intmax_t FromInt64(int64_t v, std::ratio<60>) {
  return -100;
}

int main() {
    auto a = FromInt64(5, std::ratio<1, 5>{});
    std::cout << a << " "; // 5
    auto b = FromInt64(5, std::ratio<60>{});
    std::cout << b; // -100
}
</code>```

Body:
I am trying to compile tensorflow using clang ,
And getting following error regarding constexpr

In file included from /tensorflow/tensorflow/lite/tools/make/downloads/absl/absl/time/clock.h:26:
/tensorflow/tensorflow/lite/tools/make/downloads/absl/absl/time/time.h:1404:55: error: constexpr function's 2nd parameter type 'std::ratio<60>' is not a literal type
constexpr Duration FromInt64(int64_t v, std::ratio<60>) {
                                        ~~~~~~~~~~~~~~^
/toolkit/include/usr/h/public/ratio:100:9: note: 'ratio<60, 1>' is not literal because it is not an aggregate and has no constexpr constructors other than copy or move constructors
        struct ratio
               ^

This is the relevant piece of code:

template <std::intmax_t N>
constexpr Duration FromInt64(int64_t v, std::ratio<1, N>) {
  static_assert(0 < N && N <= 1000 * 1000 * 1000, "Unsupported ratio");
  // Subsecond ratios cannot overflow.
  return MakeNormalizedDuration(
      v / N, v % N * kTicksPerNanosecond * 1000 * 1000 * 1000 / N);
}

constexpr Duration FromInt64(int64_t v, std::ratio<60>) {
  return (v <= (std::numeric_limits<int64_t>::max)() / 60 &&
          v >= (std::numeric_limits<int64_t>::min)() / 60)
             ? MakeDuration(v * 60)
             : v > 0 ? InfiniteDuration() : -InfiniteDuration();
}

Thanks if someone can point me to the right direction

Body:
It seems to work in a playground for me

#include <ratio>
#include <iostream>

template <std::intmax_t N>
constexpr std::intmax_t FromInt64(int64_t v, std::ratio<1, N>) {
  static_assert(0 < N && N <= 1000 * 1000 * 1000, "Unsupported ratio");
  return N;
}

constexpr std::intmax_t FromInt64(int64_t v, std::ratio<60>) {
  return -100;
}

int main() {
    auto a = FromInt64(5, std::ratio<1, 5>{});
    std::cout << a << " "; // 5
    auto b = FromInt64(5, std::ratio<60>{});
    std::cout << b; // -100
}


来源: stackexchange

问:
How to store and retrieve a dictionary with redis
```<code># I have the dictionary my_dict
my_dict = {
    'var1' : 5
    'var2' : 9
}
r = redis.StrictRedis()
</code>```

How would I store my_dict and retrieve it with redis.  For example, the following code does not work.

```<code>#Code that doesn't work
r.set('this_dict', my_dict)  # to store my_dict in this_dict
r.get('this_dict')  # to retrieve my_dict
</code>```

答:
HMSET is deprecated per the Redis docs. You can now use HSET with a dictionary as follows:

import redis

r = redis.Redis('localhost')

key = "hashexample"
entry = {
    "version":"1.2.3",
    "tag":"main",
    "status":"CREATED",
    "timeout":"30"
}
r.hset(key, mapping=entry)
```
<hr />
<p>Caution: very unintuitively, <code>hset</code> won't accept a dictionary (raising an error suggesting it does not accept dictionaries, see [1]) if it is simply passed to the 2nd positional (unnamed) argument. You need to pass the dictionary to a <strong>named</strong> argument <code>mapping=</code>.</p>
```[1] *** redis.exceptions.DataError: Invalid input of type: 'dict'. Convert to a bytes, string, int or float first.
```

ContentLicense: CC BY-SA 3.0

Body:
# I have the dictionary my_dict
my_dict = {
    'var1' : 5
    'var2' : 9
}
r = redis.StrictRedis()

How would I store my_dict and retrieve it with redis.  For example, the following code does not work.

#Code that doesn't work
r.set('this_dict', my_dict)  # to store my_dict in this_dict
r.get('this_dict')  # to retrieve my_dict

Body:
HMSET is deprecated per the Redis docs. You can now use HSET with a dictionary as follows:

import redis

r = redis.Redis('localhost')

key = "hashexample"
entry = {
    "version":"1.2.3",
    "tag":"main",
    "status":"CREATED",
    "timeout":"30"
}
r.hset(key, mapping=entry)

Caution: very unintuitively, hset won't accept a dictionary (raising an error suggesting it does not accept dictionaries, see [1]) if it is simply passed to the 2nd positional (unnamed) argument. You need to pass the dictionary to a named argument mapping=.

[1] *** redis.exceptions.DataError: Invalid input of type: 'dict'. Convert to a bytes, string, int or float first.

ContentLicense: CC BY-SA 4.0


问:
How to save the state of a button in AndroidStudio?
I am new at programing in Java and I am taking a course of Android application. I am building a button inside an activity. But when I exit the activity, the button changes to it's original state. I know I am not doing anything to save its state, but how do I do it?

Here is the xml file (only the button part):

```<code><Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/Catch"
    android:id="@+id/button"
    android:onClick="toggleCatch" />
</code>```

And here is toggleCatch:

```<code>private boolean isCaught = false;
@SuppressLint("SetTextI18n")
    public void toggleCatch(View view) {
        Button button = findViewById(R.id.button);

        if (isCaught) {
            button.setText("Catch");
            isCaught = false;
        } else {
            button.setText("Release");
            isCaught = true;
        }
    }
</code>```

What could I do to make it work?

答:
you should store the data that indicate on it state in some place:
1. SQLlite
2. Server
3. SharedPreference

and then when you create the activity you set the state of the btn based on the data you loaded.

if you do it just for practice, I believe that the sharepreference will be just fine.

https://developer.android.com/training/data-storage/shared-preferences

to store any data locally in the sharedPreference:

```<code>SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("SOME_NAME_FOR_YOUR_VARIABLE_EX_BTN_STATE", trueOrFalse);
editor.commit();
</code>```

to get the saved data:

```<code>SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
boolean stateBtn = sharedPref.getBoolean("SOME_NAME_FOR_YOUR_VARIABLE_EX_BTN_STATE", defaultValueForExTrue);
</code>```

sharedPref.getBoolean can be used also for sharedPref.getString, sharedPref.getInt Etc..

hope that helped..
My recommendation for you is to read about the subjects above.(SQLlite, SharedPreference)

Body:
I am new at programing in Java and I am taking a course of Android application. I am building a button inside an activity. But when I exit the activity, the button changes to it's original state. I know I am not doing anything to save its state, but how do I do it?

Here is the xml file (only the button part):

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/Catch"
    android:id="@+id/button"
    android:onClick="toggleCatch" />

And here is toggleCatch:

private boolean isCaught = false;
@SuppressLint("SetTextI18n")
    public void toggleCatch(View view) {
        Button button = findViewById(R.id.button);

        if (isCaught) {
            button.setText("Catch");
            isCaught = false;
        } else {
            button.setText("Release");
            isCaught = true;
        }
    }

What could I do to make it work?

Body:
you should store the data that indicate on it state in some place:
1. SQLlite
2. Server
3. SharedPreference

and then when you create the activity you set the state of the btn based on the data you loaded.

if you do it just for practice, I believe that the sharepreference will be just fine.

https://developer.android.com/training/data-storage/shared-preferences

to store any data locally in the sharedPreference:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("SOME_NAME_FOR_YOUR_VARIABLE_EX_BTN_STATE", trueOrFalse);
editor.commit();

to get the saved data:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
boolean stateBtn = sharedPref.getBoolean("SOME_NAME_FOR_YOUR_VARIABLE_EX_BTN_STATE", defaultValueForExTrue);

sharedPref.getBoolean can be used also for sharedPref.getString, sharedPref.getInt Etc..

hope that helped..
My recommendation for you is to read about the subjects above.(SQLlite, SharedPreference)


问:
Add specific artifact to a Gradle project (Androind)
I need to use, in an Android project using Gradle, a specific artifact of a repositorty.
The artifact is  kotlinx-serialization-cbor version 0.20.0 (available in the readme) from the kotlinx serialization GitHub project.
I don't know where and how to add this specific dependencies. (Probably I should add something in "gradle.build" file, the one marked as Project:YourProjectName or the one Module:app
Any help?

答: You should probably look here https://mvnrepository.com/artifact/org.jetbrains.kotlinx/kotlinx-serialization-cbor/0.20.0 and copy-paste from Gradle/Maven etc (build system of your choice).</p>


问:
Is there a way to solve "DataError: No numeric types to aggregate" because of having "nan" values in the column?
I have a Dataframe like this

```<code>import pandas as pd
import numpy as np
df = pd.DataFrame({
    "name": ["john","peter","john","peter","peter"],
    "height": ["6","5","4","nan","8"],
})
df
</code>```

I want to do GROUPBY name and AGG the height for mean

```<code>df2=df.groupby('name')
df3=df2.agg({'height':'mean'})
</code>```

But I get this ERROR
DataError: No numeric types to aggregate
I did some search and I applied this one

```<code>df.height = pd.to_numeric(df.height,errors='ignore')
</code>```

But still the code does not work and I get the same error!

"nan" values were created as a result of some joins that I did on previous dataframes.
Thank you for your time and help.
I will upvote your answers.

答:
You need to use sum() function

```<code>df2=df.groupby('name').height.sum()
</code>```

I hope you find it helpful

Body:
I have a Dataframe like this

import pandas as pd
import numpy as np
df = pd.DataFrame({
    "name": ["john","peter","john","peter","peter"],
    "height": ["6","5","4","nan","8"],
})
df

I want to do GROUPBY name and AGG the height for mean

df2=df.groupby('name')
df3=df2.agg({'height':'mean'})

But I get this ERROR
DataError: No numeric types to aggregate
I did some search and I applied this one

df.height = pd.to_numeric(df.height,errors='ignore')

But still the code does not work and I get the same error!

"nan" values were created as a result of some joins that I did on previous dataframes.
Thank you for your time and help.
I will upvote your answers.

Body:
You need to use sum() function

df2=df.groupby('name').height.sum()

I hope you find it helpful


问:
Will dockerizing the application increase the startup time of application?
We have a java application which was running without docker before. Recently we dockerized the application, startup time is more than before. So I just want to ask will dockerizing the application increase the startup time of application?</p>

答: There shouldn't be a significant difference, but you do have the docker layer to deal with and the docker engine itself might have fewer resources such as CPU and memory and filesystem drivers which could have some effect.</p>


问:
Moving messages from BackOut queue to main queue
We have defined BackOut queue for each main queue. The poison messages are added into BackOut queue automatically as we are using JMS.
But few valid messages are also considered as poison messages due to temporary infrastructure/DB issues and added into BackOut queue.

Now I want to move those poison messages from BackOut queue to the main queue. Does anyone have any utility or any JMS/IBM MQ classes which can do it in less code?

I want it do it through java code.

答:
I'm not sure why you would want to write Java code to move messages when there are already existing tools to do it for you:

(1) If the poison messages have the Dead Letter Header prefixed to the message then use the IBM MQ Dead Letter Queue Handler (runmqdlq).

(2) If the poison messages do NOT have the Dead Letter Header prefixed to the message then use dmpmqmsg utility as JoshMc pointed out.  Note: You need to be at IBM MQ v8.0 or higher.  If you are using an older release of IBM MQ then you can use a commercial program like MQ Batch Toolkit or QLoad.


问:
Remove unwanted space inside a column while placing image at end in flutter?
am new for flutter development i have got struck in placing the image in corner of the column which i have shown in the image

Need to remove the spacing  which i have marked with arrow how to do this? now let me post what i tried so far:

```<code>Card(
                  margin: EdgeInsets.all(10),
                  clipBehavior: Clip.antiAlias,
                  shape: RoundedRectangleBorder(
                    side: BorderSide(color: Colors.white, width: 1),
                    borderRadius: BorderRadius.circular(20),
                  ),
                  color: Colors.white,
                  child: Container(
                    width: MediaQuery.of(context).size.width / 2.3,
                    height: 200,
                    // color: Colors.pink,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.end,
                      mainAxisSize: MainAxisSize.min,
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: <Widget>[
                        Container(
                          color: Colors.red,
                          child: Image.asset('assets/intersection_png.png',
                          fit: BoxFit.cover,),
                        )
                      ],
                    ),
                  ),
                )
</code>```

Thanks in advance!!

答:
you should set the BorderSide color as transparent

and set the width equal to 0

```<code>side: BorderSide(color: Colors.transparent, width: 0),
</code>```

Body:
am new for flutter development i have got struck in placing the image in corner of the column which i have shown in the image

Need to remove the spacing  which i have marked with arrow how to do this? now let me post what i tried so far:

Card(
                  margin: EdgeInsets.all(10),
                  clipBehavior: Clip.antiAlias,
                  shape: RoundedRectangleBorder(
                    side: BorderSide(color: Colors.white, width: 1),
                    borderRadius: BorderRadius.circular(20),
                  ),
                  color: Colors.white,
                  child: Container(
                    width: MediaQuery.of(context).size.width / 2.3,
                    height: 200,
                    // color: Colors.pink,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.end,
                      mainAxisSize: MainAxisSize.min,
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: <Widget>[
                        Container(
                          color: Colors.red,
                          child: Image.asset('assets/intersection_png.png',
                          fit: BoxFit.cover,),
                        )
                      ],
                    ),
                  ),
                )

Thanks in advance!!

Body:
you should set the BorderSide color as transparent

and set the width equal to 0

side: BorderSide(color: Colors.transparent, width: 0),


问:
Unable to resolve module `./Linking/Linking` from `node_modules/expo/build/ExpoLazy.js`
Has anyone experience this error with expo, when running react-native run-android?

```<code>error: bundling failed: Error: Unable to resolve module `./Linking/Linking` from `node_modules/expo/build/ExpoLazy.js`:

None of these files exist:
  * node_modules/expo/build/Linking/Linking(.native|.android.js|.native.js|.js|.android.json|.native.json|.json|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx)
  * node_modules/expo/build/Linking/Linking/index(.native|.android.js|.native.js|.js|.android.json|.native.json|.json|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx)
</code>```

"expo": "^37.0.9",

答:
What worked for me:

1) In package.json change to "expo": "37.0.8"
2) Delete your node_modules
3) installl packages npm i
4) clean cache in expo expo r -c

Now it started to work again. Couldn't find the last step in previous comments.

Body:
Has anyone experience this error with expo, when running react-native run-android?

error: bundling failed: Error: Unable to resolve module `./Linking/Linking` from `node_modules/expo/build/ExpoLazy.js`:

None of these files exist:
  * node_modules/expo/build/Linking/Linking(.native|.android.js|.native.js|.js|.android.json|.native.json|.json|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx)
  * node_modules/expo/build/Linking/Linking/index(.native|.android.js|.native.js|.js|.android.json|.native.json|.json|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx)

"expo": "^37.0.9",


问:
Regular expression for all abbreviated keyword variations
I need to search for a keyword, such as "abcdef", which can also be in an abbreviated version with a dot at the end. All valid variants are:

```<code>abcdef
abcde.
abcd.
abc.
ab.
a.
</code>```

I have a regular expression for this, which is clear:

```<code>abcdef|abcde\.|abcd\.|abc\.|ab\.|a\.
</code>```

Another regular expression where the keyword characters are not repeated:

```<code>a(b(c(d(e(f|\.)|\.)|\.)|\.)|\.)
</code>```

I'm looking for a more compact expression where not even a dot will be repeated.
I use .NET syntax.

答:
As a variant:

a(bcdef|(bcde|bcd|bc|b|)\.)

With shorting 2 letters (a bit shorter):

a(bcdef|(b(cde|cd|c|)|)\.)

With shorting 3 letters (the same length):

a(bcdef|(b(c(de|d|)|)|)\.)

With shorting 4 letters the shortest - 25 symbols:

a(bcdef|(b(c(de?|)|)|)\.)

Body:
I need to search for a keyword, such as "abcdef", which can also be in an abbreviated version with a dot at the end. All valid variants are:

abcdef
abcde.
abcd.
abc.
ab.
a.

I have a regular expression for this, which is clear:

abcdef|abcde\.|abcd\.|abc\.|ab\.|a\.

Another regular expression where the keyword characters are not repeated:

a(b(c(d(e(f|\.)|\.)|\.)|\.)|\.)

I'm looking for a more compact expression where not even a dot will be repeated.
I use .NET syntax.


问:
Loop that terminates when condition is met
I was doing some python practice and have been stumped with this question. I have figured out how to do all the operations but do not know how to create the terminating loop, any help would be appreciated.

Question:
Write a program that generates 2 numbers between 1 and 15.  Display them in order from biggest to smallest. Display the sum of the numbers. The program should continue until the random numbers generated are the same.  At the end of the program display, the total sum of all the numbers generated.

from random import randint

numberOne = randint(1, 15)
numberTwo = randint(1, 15)

print("Your two random numbers are: ", numberOne, numberTwo)
print()

if (numberOne > numberTwo):
    biggest_num = numberOne
elif (numberTwo > numberOne):
    biggest_num = numberTwo

if (numberOne < numberTwo):
    smallest_num = numberOne
elif (numberTwo < numberOne):
    smallest_num = numberTwo

print("From biggest to smallest, the two random numbers are: ", biggest_num, smallest_num)
print("The sum of the two numbers is: ", numberOne + numberTwo)
```

答:
This should do the job</p>

```<code>import random
numberOne = 0
numberTwo = 1

while numberOne != numberTwo:
    numberOne = random.randint(1, 15)
    numberTwo = random.randint(1, 15)

    print('\nYour two numbers are:', numberOne, numberTwo)

    if numberOne > numberTwo:
        largest = numberOne
        smallest = numberTwo
    else:
        largest = numberTwo
        smallest = numberOne

    print('From largest to smallest, the two random numbers are:', largest, smallest)
    print('The sum of the two numbers is:', numberOne + numberTwo)
</code>```

Body:
This should do the job

import random
numberOne = 0
numberTwo = 1

while numberOne != numberTwo:
    numberOne = random.randint(1, 15)
    numberTwo = random.randint(1, 15)

    print('\nYour two numbers are:', numberOne, numberTwo)

    if numberOne > numberTwo:
        largest = numberOne
        smallest = numberTwo
    else:
        largest = numberTwo
        smallest = numberOne

    print('From largest to smallest, the two random numbers are:', largest, smallest)
    print('The sum of the two numbers is:', numberOne + numberTwo)


问:
Selenium with Angular - XPath how to get to elements when $index present?
Using Python 3.7 with Selenium on pages that include Angular, please advise how to best locate an element such as this:

```<code><input type="radio" ng-model="section3.data.generalSection3.container[$index].lseCatTy" value="FEDERAL" ng-disabled="!section3.data.generalSection3.container[$index].editable" ng-class="classes('lseCatTy')" ng-change="section3.updateLseCatTy($index, section3.data.generalSection3.container[$index].lseCatTy)" class="ng-valid ng-not-empty ng-dirty ng-touched ng-valid-parse" name="759" style="">
</code>```

or this

```<code><button type="button" uib-tooltip="Edit" tooltip-placement="right" class="btn btn-primary" ng-click="section3.data.editContainer($index);" ng-disabled="editingDrilling1 || submissionTypeSR">
</code>```

when it exists in blocks such as the following. What's tripping me up is the $index... The page has multiple fieldset tags and that number is DYNAMIC... For example, a user can add more of one type of the fieldset while editing the page- but only this one type.

```<code><div ng-if="section3.data.generalSection3.srvyTyId != null && section3.data.generalSection3.srvyTyId != ''" class="ng-scope" style="">
    <!-- ngRepeat: wellFeature in section3.data.generalSection3.container track by $index -->
    <div ng-repeat="wellFeature in section3.data.generalSection3.container track by $index" class="ng-scope">
        <!-- ngIf: section3.data.generalSection3.container[$index].deleteSegmentLocation == null -->
        <fieldset class="legend-border ng-scope" ng-if="section3.data.generalSection3.container[$index].deleteSegmentLocation == null">
            <legend/>
            <div class="col-lg-12 panel panel-default">
                <div class="row panel-heading ng-binding">
                            SHL <br>
                        <!-- ngIf: section3.data.generalSection3.container[$index].legBHLAttr == 'PPP' -->
                        <!-- ngIf: section3.data.generalSection3.container[$index].legBHLAttr != 'PPP' && section3.data.generalSection3.container[$index].legBHLAttr != 'SHL' -->
                        <!-- ngIf: section3.data.generalSection3.container[$index].legBHLAttr == 'SHL' -->
                        <div ng-if="section3.data.generalSection3.container[$index].legBHLAttr == 'SHL'" class="ng-scope"/>
                        <!-- end ngIf: section3.data.generalSection3.container[$index].legBHLAttr == 'SHL' -->
                    </div>
                </div>
                <div class="row">
                    <div class="col-lg-11">
                        <!-- ngIf: section3.data.generalSection3.srvyTyId=='1'|| section3.data.generalSection3.srvyTyId=='3' || section3.data.generalSection3.srvyTyId=='2' || section3.data.generalSection3.srvyTyId=='4' -->
                        <div ng-if="section3.data.generalSection3.srvyTyId=='1'|| section3.data.generalSection3.srvyTyId=='3' || section3.data.generalSection3.srvyTyId=='2' || section3.data.generalSection3.srvyTyId=='4'" style="padding-left: 15px; padding-right: 15px;" class="ng-scope">
                            <div class="row">
                                <div class="col-lg-6">
                                    <div class="form-group">
                                        <label class="required-field">Lease Type</label>
                                        <br>
                                            <div ng-class="classes('lseCatTy'+','+$index.toString(), [])">
                                                <label class="radio-inline">
                                                    <input type="radio" ng-model="section3.data.generalSection3.container[$index].lseCatTy" value="FEDERAL" ng-disabled="!section3.data.generalSection3.container[$index].editable" ng-class="classes('lseCatTy')" ng-change="section3.updateLseCatTy($index, section3.data.generalSection3.container[$index].lseCatTy)" class="ng-valid ng-not-empty ng-dirty ng-touched ng-valid-parse" name="759" style=""> Federal
                                                    </label>
                                                    <label class="radio-inline">

</code>```

What I have working is:

```<code>self.wait.until(EC.presence_of_element_located((By.XPATH, "//button[@ng-click='section3.data.editContainer($index);']"))).click()
</code>```

And this gets the first instance of that button (in the top fieldset), but I don't know how to get an arbitrary instance of it.

答:
I learned to navigate the DOM using parent elements and finding elements within parent elements --

This became a matter of finding a unique parent (lines 1 and 2), then finding the edit button for that section (line 3), and finding the desired element (line 4).

```<code>shl_div = self.wait.until(EC.presence_of_element_located((By.XPATH, "//div[@class='row panel-heading ng-binding' and contains(text(),'SHL')]")))
shl_par = shl_div.find_element_by_xpath("..")
shl_par.find_element_by_xpath(".//button[@ng-click='section3.data.editContainer($index);']").click()
shl_par.find_element_by_xpath(".//input[@value='FEDERAL']").click()
</code>```

Body:
Using Python 3.7 with Selenium on pages that include Angular, please advise how to best locate an element such as this:

<input type="radio" ng-model="section3.data.generalSection3.container[$index].lseCatTy" value="FEDERAL" ng-disabled="!section3.data.generalSection3.container[$index].editable" ng-class="classes('lseCatTy')" ng-change="section3.updateLseCatTy($index, section3.data.generalSection3.container[$index].lseCatTy)" class="ng-valid ng-not-empty ng-dirty ng-touched ng-valid-parse" name="759" style="">

or this

<button type="button" uib-tooltip="Edit" tooltip-placement="right" class="btn btn-primary" ng-click="section3.data.editContainer($index);" ng-disabled="editingDrilling1 || submissionTypeSR">

when it exists in blocks such as the following. What's tripping me up is the $index... The page has multiple fieldset tags and that number is DYNAMIC... For example, a user can add more of one type of the fieldset while editing the page- but only this one type.

        <fieldset class="legend-border ng-scope" ng-if="section3.data.generalSection3.container[$index].deleteSegmentLocation == null">
            <legend/>

                            SHL

                                        Lease Type

                                                    <input type="radio" ng-model="section3.data.generalSection3.container[$index].lseCatTy" value="FEDERAL" ng-disabled="!section3.data.generalSection3.container[$index].editable" ng-class="classes('lseCatTy')" ng-change="section3.updateLseCatTy($index, section3.data.generalSection3.container[$index].lseCatTy)" class="ng-valid ng-not-empty ng-dirty ng-touched ng-valid-parse" name="759" style=""> Federal

What I have working is:

self.wait.until(EC.presence_of_element_located((By.XPATH, "//button[@ng-click='section3.data.editContainer($index);']"))).click()

And this gets the first instance of that button (in the top fieldset), but I don't know how to get an arbitrary instance of it.

Body:
I learned to navigate the DOM using parent elements and finding elements within parent elements --

This became a matter of finding a unique parent (lines 1 and 2), then finding the edit button for that section (line 3), and finding the desired element (line 4).

shl_div = self.wait.until(EC.presence_of_element_located((By.XPATH, "//div[@class='row panel-heading ng-binding' and contains(text(),'SHL')]")))
shl_par = shl_div.find_element_by_xpath("..")
shl_par.find_element_by_xpath(".//button[@ng-click='section3.data.editContainer($index);']").click()
shl_par.find_element_by_xpath(".//input[@value='FEDERAL']").click()


问:
Google Drive raw data?
Is there any URL google has that contains the raw data for the file? using https://drive.google.com/file/d/FILE_ID just takes you to a 'share' section of the file... say I have a .js file on GDrive. If you go to their share link, they have a share page. Is there any link to get the raw javascript from the file, as to use in a

答:
First, go to the sharing settings for your document and choose "Anyone with a link." It will generate a link in the format https://drive.google.com/file/d/XXX/view?usp=sharing.

Now you can use the following URL format: https://drive.google.com/uc?id=XXX

Note that I'm seeing an HTTP redirect when I do this, so use curl -L on the command line or otherwise make sure that your HTTP client follows redirect.

Title: Google Drive raw data?


答:
Easiest approach here is an infinite loop with a break

from random import randint

total_sum = 0

while True:
    numberOne = randint(1, 15)
    numberTwo = randint(1, 15)

    print("Your two random numbers are: ", numberOne, numberTwo)
    print()

    if numberOne == numberTwo:
        break

    if numberOne > numberTwo:
        biggest_num = numberOne
    elif numberTwo > numberOne:
        biggest_num = numberTwo

    if numberOne < numberTwo:
        smallest_num = numberOne
    elif numberTwo < numberOne:
        smallest_num = numberTwo

    print("From biggest to smallest, the two random numbers are: ", biggest_num, smallest_num)
    print("The sum of the two numbers is: ", numberOne + numberTwo)
    total_sum += numberOne + numberTwo

print('Total sum:', total_sum)
```

Title: Loop that terminates when condition is met

Body:
I was doing some python practice and have been stumped with this question. I have figured out how to do all the operations but do not know how to create the terminating loop, any help would be appreciated.

Question:
Write a program that generates 2 numbers between 1 and 15.  Display them in order from biggest to smallest. Display the sum of the numbers. The program should continue until the random numbers generated are the same.  At the end of the program display, the total sum of all the numbers generated.

from random import randint

numberOne = randint(1, 15)
numberTwo = randint(1, 15)

print("Your two random numbers are: ", numberOne, numberTwo)
print()

if (numberOne > numberTwo):
    biggest_num = numberOne
elif (numberTwo > numberOne):
    biggest_num = numberTwo

if (numberOne < numberTwo):
    smallest_num = numberOne
elif (numberTwo < numberOne):
    smallest_num = numberTwo

print("From biggest to smallest, the two random numbers are: ", biggest_num, smallest_num)
print("The sum of the two numbers is: ", numberOne + numberTwo)


答:
Normally not really as a container is just a toolset that use many kernel and linux tools to works.

But if you use Docker for Mac or Docker for Windows, you may see a performance hit as theses 2 solutions use a small VM to run and, by default, do not use all your CPU core and RAM available.

And, if you are on Windows or Mac and you use bind mount volume, the performance could decrease even more as the IO are not as fast as without docker.

Title: Will dockerizing the application increase the startup time of application?

Body: We have a java application which was running without docker before. Recently we dockerized the application, startup time is more than before. So I just want to ask will dockerizing the application increase the startup time of application?


问:
Java public interface and public class in same file
In a single .Java file, is it possible to have a public interface and a public class (which implements the interface)

I'm new to Java coding and it is written on most places on the net that a .java file cannot contain more than 2 public class. I want to know if it is true for the interface and a class also.

答:
Yes we can write both Interface as well as public class in a same java file

```<code>interface Interfable {
public void interfMethod();
</code>```

}

public class TestLam {

```<code>int x = 5;

public void testLamMethod() {
    int y = 10;
    Interfable i = () -> {
        System.out.println(x);
        System.out.println(y);
    };
    i.interfMethod();
}

public static void main(String[] args) {

    TestLam t = new TestLam();
    t.testLamMethod();
}
</code>```

}

output:
5

10

// NOTE .java file name should be same as class name

Body:
Yes we can write both Interface as well as public class in a same java file

interface Interfable {
public void interfMethod();

}

public class TestLam {

int x = 5;

public void testLamMethod() {
    int y = 10;
    Interfable i = () -> {
        System.out.println(x);
        System.out.println(y);
    };
    i.interfMethod();
}

public static void main(String[] args) {

    TestLam t = new TestLam();
    t.testLamMethod();
}

}

output:
5

10

// NOTE .java file name should be same as class name


问:
Google App engine - submitting form field "field[key]"
So my question is, how I can get form values as list when submitting this particular form:

```<code><form action="/foobar" method="post">

<input type="text" value="text 1" name="text[key_1]" />
<input type="text" value="text 2" name="text[key_2]" />
<input type="text" value="text 3" name="text[key_3]" />
<input type="text" value="text 4" name="text[key_4]" />

</form>
</code>```

Currently, you cannot get all this values as dict / touple / list using self.request.get('text') or self.request.get_all('text'), cause this only works if you exactly specify self.request.get('text[key_1]').

You can do this type of form:

```<code><form action="/foobar" method="post">

<input type="text" value="text 1" name="text" />
<input type="text" value="text 2" name="text" />
<input type="text" value="text 3" name="text" />
<input type="text" value="text 4" name="text" />

</form>
</code>```

texts = self.request.get_all('text') // you would get texts = ['text 1', 'text 2', 'text 3', 'text 4']

But like I said, I need key/pair form values

答:
I guess you are using webapp framework. To get key/value pairs. you can do something like this

if your method is GET,

```<code>self.request.str_GET.items()
</code>```

else

```<code>self.request.str_POST.items()
</code>```

More reference here

Body:
So my question is, how I can get form values as list when submitting this particular form:

<form action="/foobar" method="post">

<input type="text" value="text 1" name="text[key_1]" />
<input type="text" value="text 2" name="text[key_2]" />
<input type="text" value="text 3" name="text[key_3]" />
<input type="text" value="text 4" name="text[key_4]" />

</form>

Currently, you cannot get all this values as dict / touple / list using self.request.get('text') or self.request.get_all('text'), cause this only works if you exactly specify self.request.get('text[key_1]').

You can do this type of form:

<form action="/foobar" method="post">

<input type="text" value="text 1" name="text" />
<input type="text" value="text 2" name="text" />
<input type="text" value="text 3" name="text" />
<input type="text" value="text 4" name="text" />

</form>

texts = self.request.get_all('text') // you would get texts = ['text 1', 'text 2', 'text 3', 'text 4']

But like I said, I need key/pair form values

Body:
I guess you are using webapp framework. To get key/value pairs. you can do something like this

if your method is GET,

self.request.str_GET.items()

else

self.request.str_POST.items()

More reference here


问:
malloc or _Znwm, which should we use in LLVM IR System
While applying for memory in heap in LLVM, we can use malloc, but the IR clang++ compiled c++ code, using _Znwm (_ZdlPv instead of free).

Why?  And which one should we choose?

Source Code:

class A {
  public:
  A();
  int a;
};

int main() {
  A *a = new A();
  // delete a;
  return 0;
}
```

<p>IR Code;</p>

<pre class="lang-cpp prettyprint-override"><code>define i32 @main() ... {
  %1 = alloca i32, align 4
  %2 = alloca %class.A*, align 8
  ...
  %5 = call i8* @_Znwm(i64 4) #4
  %6 = bitcast i8* %5 to %class.A*
  invoke void @_ZN1AC1Ev(%class.A* %6)
          to label %7 unwind label %8
  ...
</code>```

答:
_Znwm stands for operator new (and _ZdlPv for operator delete):

```<code>$ echo _Znwm | c++filt
operator new(unsigned long)
</code>```

Body:
While applying for memory in heap in LLVM, we can use malloc, but the IR clang++ compiled c++ code, using _Znwm (_ZdlPv instead of free).

Why?  And which one should we choose?

Source Code:

class A {
  public:
  A();
  int a;
};

int main() {
  A *a = new A();
  // delete a;
  return 0;
}

IR Code;

define i32 @main() ... {
  %1 = alloca i32, align 4
  %2 = alloca %class.A*, align 8
  ...
  %5 = call i8* @_Znwm(i64 4) #4
  %6 = bitcast i8* %5 to %class.A*
  invoke void @_ZN1AC1Ev(%class.A* %6)
          to label %7 unwind label %8
  ...

Body:
_Znwm stands for operator new (and _ZdlPv for operator delete):

$ echo _Znwm | c++filt
operator new(unsigned long)


答:
The README in the root of the github project explains how to add the plugins to your project. So long as your gradle install is up to date you just need to add a section at the top of your app level build.gradle like this:

```<code>plugins {
    id 'org.jetbrains.kotlin.multiplatform' version '1.3.70' // or any other kotlin plugin
    id 'org.jetbrains.kotlin.plugin.serialization' version '1.3.70'
}
</code>```

In the same file make sure jcenter is included in your repositories:

```<code>repositories {
    jcenter()
}
</code>```

Then again in the same file add the basic library, as well as the cbor library to the dependencies:

```<code>dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" // or "kotlin-stdlib-jdk8"
    implementation "org.jetbrains.kotlinx:kotlinx-serialization-runtime:0.20.0" // JVM dependency
    implementation "org.jetbrains.kotlinx:kotlinx-serialization-cbor:0.20.0"
}
</code>```

Title: Add specific artifact to a Gradle project (Androind)

Body:
I need to use, in an Android project using Gradle, a specific artifact of a repositorty.
The artifact is  kotlinx-serialization-cbor version 0.20.0 (available in the readme) from the kotlinx serialization GitHub project.
I don't know where and how to add this specific dependencies. (Probably I should add something in "gradle.build" file, the one marked as Project:YourProjectName or the one Module:app
Any help?

Body:
The README in the root of the github project explains how to add the plugins to your project. So long as your gradle install is up to date you just need to add a section at the top of your app level build.gradle like this:

plugins {
    id 'org.jetbrains.kotlin.multiplatform' version '1.3.70' // or any other kotlin plugin
    id 'org.jetbrains.kotlin.plugin.serialization' version '1.3.70'
}

In the same file make sure jcenter is included in your repositories:

repositories {
    jcenter()
}

Then again in the same file add the basic library, as well as the cbor library to the dependencies:

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" // or "kotlin-stdlib-jdk8"
    implementation "org.jetbrains.kotlinx:kotlinx-serialization-runtime:0.20.0" // JVM dependency
    implementation "org.jetbrains.kotlinx:kotlinx-serialization-cbor:0.20.0"
}


问:
Creating my own filter function in python
I need to create my own filter function in python, i.e., it should return the value from an iterable only if running any given function on it returns True or, if the function is None, if the iterable itself returns True. My problem is that I cannot get to work with a function that returns only even numbers.

This is my code:

```<code>def my_own_filter(func, *iterable):
    l = []
    if func is None:
        for i in iterable:
            if i:
                l.append(i)
    else:
        for i in iterable:
            if func(i):
                l.append(i)
    return(l)

print(my_own_filter(None, 1, 0, -1, (), "hello", 1, 2, 3, 4))
print(my_own_filter(sum, (1, 2, 3), [], [3, 4, 5]))
</code>```

Any help will be highly appreciated!

答: it would  be better if you provide your code of function that return even</p>

Body:
I need to create my own filter function in python, i.e., it should return the value from an iterable only if running any given function on it returns True or, if the function is None, if the iterable itself returns True. My problem is that I cannot get to work with a function that returns only even numbers.

This is my code:

def my_own_filter(func, *iterable):
    l = []
    if func is None:
        for i in iterable:
            if i:
                l.append(i)
    else:
        for i in iterable:
            if func(i):
                l.append(i)
    return(l)

print(my_own_filter(None, 1, 0, -1, (), "hello", 1, 2, 3, 4))
print(my_own_filter(sum, (1, 2, 3), [], [3, 4, 5]))

Any help will be highly appreciated!


问:
How can i send a automatic message to the bot at the beginning (Webchat V4 + Javascript)
im trying to set up a bot with the Microsoft Bot Framework.
For the communication interface im using the Webchat V4 (https://github.com/microsoft/BotFramework-WebChat). I want a message to be sent to the bot once the webchat is loaded on the website. The message can be hidden or seen in the chat window (hidden would be better tho). Can i implement this and if so how?

Im using the javascript version of the Webchat by the way.

答:
The BotFramework-WebChat repo has a sample, 04.api/a.welcome-event, that demonstrates how to set this up.

In short, when Web Chat connects, an event is emitted from Web Chat to the bot. When the bot receives this particular event, the "Welcome Message" from the bot is sent back to the client and is displayed to the user.

As for hiding a message, there is no way to do this. If you don't want the message to display immediately, then don't use the above and, instead, explore some of the other Web Chat store actions and determine a client/bot setup that works for you.

For instance, you could

Put a timer on the welcome message so it sends n seconds after connecting (or sends n seconds after connecting if no message is first sent from the user)

Sends a welcome message only after a message is received by the bot (primarily a bot implementation but you could utilize Web Chat to further customize)

(If there is some page interaction) you could dispatch a window event that sends an event to the bot which then displays the message.

Hope of help!


问:
How to set font size of chart,axis values and axis titles in python-pptx for xyscatter chart
I have very simple xy chart that I made with python-pptx (thanks all from stack overflows who helped me with this). I am struggling with setting font size of XTitle, YTitle, ChartTitle, Series Name and also values on x any axis like (0 20 40 60). The pptx documentation is not very clear to me

```<code>from pptx import Presentation
from pptx.util import Inches,Pt

from pptx.enum.chart import XL_CHART_TYPE
from pptx.chart.data import XySeriesData,XyChartData

prs = Presentation()
title_slide_layout = prs.slide_layouts[0]
blank_slide_layout = prs.slide_layouts[6]

slide = prs.slides.add_slide(title_slide_layout)
slide2 = prs.slides.add_slide(blank_slide_layout)

title = slide.shapes.title
subtitle = slide.placeholders[1]

title.text = "Hello, World!"
subtitle.text = "python-pptx was here!"
chart_data = XyChartData()
cd = chart_data.add_series('Series Name',number_format=None)
cxvalues=[0,1,2,3,4,5]
cyvalues=[10,22,33,38,40,43]

for x, y in list(zip(cxvalues, cyvalues)):
    cd.add_data_point(x, y, number_format=None)

x, y, cx, cy = Inches(1), Inches(2), Inches(8), Inches(3)
chart = slide2.shapes.add_chart(XL_CHART_TYPE.XY_SCATTER_LINES_NO_MARKERS, x, y, cx, cy, chart_data).chart
chart.category_axis.axis_title.text_frame.text= "XTitle"
chart.value_axis.axis_title.text_frame.text= "YTitle"

chart.chart_title.text_frame.text='ChartTitle'

prs.save('test_template.pptx')
</code>```

答:
Try using the Font object on the first paragraph of the axis and chart title:

```<code>from pptx.util import Pt

chart.chart_title.text_frame.paragraphs[0].font.size = Pt(36)
chart.category_axis.axis_title.text_frame.paragraphs[0].font.size = Pt(24)
chart.value_axis.axis_title.text_frame.paragraphs[0].font.size = Pt(24)
</code>```

This is pretty much how you would format text in any other text-frame, although I believe in the case of these title objects there is exactly one paragraph.

Body:
I have very simple xy chart that I made with python-pptx (thanks all from stack overflows who helped me with this). I am struggling with setting font size of XTitle, YTitle, ChartTitle, Series Name and also values on x any axis like (0 20 40 60). The pptx documentation is not very clear to me

from pptx import Presentation
from pptx.util import Inches,Pt

from pptx.enum.chart import XL_CHART_TYPE
from pptx.chart.data import XySeriesData,XyChartData

prs = Presentation()
title_slide_layout = prs.slide_layouts[0]
blank_slide_layout = prs.slide_layouts[6]

slide = prs.slides.add_slide(title_slide_layout)
slide2 = prs.slides.add_slide(blank_slide_layout)

title = slide.shapes.title
subtitle = slide.placeholders[1]

title.text = "Hello, World!"
subtitle.text = "python-pptx was here!"
chart_data = XyChartData()
cd = chart_data.add_series('Series Name',number_format=None)
cxvalues=[0,1,2,3,4,5]
cyvalues=[10,22,33,38,40,43]

for x, y in list(zip(cxvalues, cyvalues)):
    cd.add_data_point(x, y, number_format=None)

x, y, cx, cy = Inches(1), Inches(2), Inches(8), Inches(3)
chart = slide2.shapes.add_chart(XL_CHART_TYPE.XY_SCATTER_LINES_NO_MARKERS, x, y, cx, cy, chart_data).chart
chart.category_axis.axis_title.text_frame.text= "XTitle"
chart.value_axis.axis_title.text_frame.text= "YTitle"

chart.chart_title.text_frame.text='ChartTitle'

prs.save('test_template.pptx')

Body:
Try using the Font object on the first paragraph of the axis and chart title:

from pptx.util import Pt

chart.chart_title.text_frame.paragraphs[0].font.size = Pt(36)
chart.category_axis.axis_title.text_frame.paragraphs[0].font.size = Pt(24)
chart.value_axis.axis_title.text_frame.paragraphs[0].font.size = Pt(24)

This is pretty much how you would format text in any other text-frame, although I believe in the case of these title objects there is exactly one paragraph.


问:
Unpacking a zip object causing ValueError
I created a zip object using the following line of code:

```<code>k=zip([1,2,3],['a','b','c'])
</code>```

Converting this into a list gives the output:

```<code>[(1,'a'),(2,'b'),(3,'c')]
</code>```

However, when I use this line of code

```<code>x,y=zip(*k)
</code>```

it gives me this ValueError:

```<code>"ValueError: not enough values to unpack (expected 2, got 0)"
</code>```

I've been trying to find out what the problem is but couldn't figure anything out.

答:
Method zip returns a iterator, so when you print it, you consume it so after that k is empty

apply the second zip directly

```<code>k = zip([1,2,3],['a','b','c'])
x,y = zip(*k)
print(x, "/", y) # (1, 2, 3) / ('a', 'b', 'c')
</code>```

wrap it in a list to use it multiple times

```<code>k = list(zip([1,2,3],['a','b','c']))
print(k)         # [(1, 'a'), (2, 'b'), (3, 'c')]
x,y = zip(*k)
print(x, "/", y) # (1, 2, 3) / ('a', 'b', 'c')
</code>```

Body:
I created a zip object using the following line of code:

k=zip([1,2,3],['a','b','c'])

Converting this into a list gives the output:

[(1,'a'),(2,'b'),(3,'c')]

However, when I use this line of code

x,y=zip(*k)

it gives me this ValueError:

"ValueError: not enough values to unpack (expected 2, got 0)"

I've been trying to find out what the problem is but couldn't figure anything out.

Body:
Method zip returns a iterator, so when you print it, you consume it so after that k is empty

apply the second zip directly

k = zip([1,2,3],['a','b','c'])
x,y = zip(*k)
print(x, "/", y) # (1, 2, 3) / ('a', 'b', 'c')

wrap it in a list to use it multiple times

k = list(zip([1,2,3],['a','b','c']))
print(k)         # [(1, 'a'), (2, 'b'), (3, 'c')]
x,y = zip(*k)
print(x, "/", y) # (1, 2, 3) / ('a', 'b', 'c')


问:
how to specify dynamically last row number in row_spec kable()?
I am generating different tables of different row length, so I want to have all the text of certain color,  but I have a question about the last row of my code in row_spec

```<code> library(kable)
 library(kableExtra)

mtcars  %>% filter(cyl=4) %>%
kable(align=c("l", rep("c", ncol(.)-1)),bootstrap_options = c("striped", "hover", "condensed", "responsive")) %>%
  kable_styling(c("striped", "hover", "condensed", "responsive"), full_width = TRUE) %>%
  row_spec(0: nrow(.),  color = "black")
</code>```

0: nrow(.) is not valid and I am not sure why, while rep("c", ncol(.)-1)) works.

答:
I think it doesn't work because nrow(.) returns NULL:

```<code>library(kable)
library(kableExtra)
mtcars  %>%
  kable(align=c("l", rep("c", ncol(.)-1)),bootstrap_options = c("striped", "hover", "condensed", "responsive")) %>%
  kable_styling(c("striped", "hover", "condensed", "responsive"), full_width = TRUE) %>% nrow(.)
#NULL
</code>```

You could do this to color all rows:

```<code>  mtcars  %>%
    kable(align=c("l", rep("c", ncol(.)-1)),bootstrap_options = c("striped", "hover", "condensed", "responsive")) %>%
    kable_styling(c("striped", "hover", "condensed", "responsive"), full_width = TRUE) %>%
  row_spec(1:nrow(mtcars),color = "black")
</code>```

Body:
I am generating different tables of different row length, so I want to have all the text of certain color,  but I have a question about the last row of my code in row_spec

 library(kable)
 library(kableExtra)

mtcars  %>% filter(cyl=4) %>%
kable(align=c("l", rep("c", ncol(.)-1)),bootstrap_options = c("striped", "hover", "condensed", "responsive")) %>%
  kable_styling(c("striped", "hover", "condensed", "responsive"), full_width = TRUE) %>%
  row_spec(0: nrow(.),  color = "black")

0: nrow(.) is not valid and I am not sure why, while rep("c", ncol(.)-1)) works.

Body:
I think it doesn't work because nrow(.) returns NULL:

library(kable)
library(kableExtra)
mtcars  %>%
  kable(align=c("l", rep("c", ncol(.)-1)),bootstrap_options = c("striped", "hover", "condensed", "responsive")) %>%
  kable_styling(c("striped", "hover", "condensed", "responsive"), full_width = TRUE) %>% nrow(.)
#NULL

You could do this to color all rows:

  mtcars  %>%
    kable(align=c("l", rep("c", ncol(.)-1)),bootstrap_options = c("striped", "hover", "condensed", "responsive")) %>%
    kable_styling(c("striped", "hover", "condensed", "responsive"), full_width = TRUE) %>%
  row_spec(1:nrow(mtcars),color = "black")


问:
How can I get a particular part of a String enclosed between 2 characters using Excel VBA?
I need to write a macro in excel which can help me get a particular part of a string. My string is as follows :

PAYPAL *VINAYAKAGGRAWAL 4029357733

I need to extract VINAYAKAGGRAWAL from the above string. Any help with vba macro or any excel formula to do this would help.

Thanks in advance.

答:
```<code>strClean = Split(Replace("PAYPAL *VINAYAKAGGRAWAL 4029357733", "*", ""))(1)
</code>```

How it works:

First, we get rid of the * character with Replace function - change it to empty string.

Then we split the string by the space with Split function. We don't mention the space delimiter explicitly, because it's a default delimiter for Split.

Finally, we get the second item from the string with (1). Split returns zero-based array, so that first item is (0), second is (1) etc. Since we need second item, we use (1).

Body:
strClean = Split(Replace("PAYPAL *VINAYAKAGGRAWAL 4029357733", "*", ""))(1)

How it works:

First, we get rid of the * character with Replace function - change it to empty string.

Then we split the string by the space with Split function. We don't mention the space delimiter explicitly, because it's a default delimiter for Split.

Finally, we get the second item from the string with (1). Split returns zero-based array, so that first item is (0), second is (1) etc. Since we need second item, we use (1).


答:
```<code>import random

numbers = set()
while(True):
    numberOne = random.randint(1, 15)
    numberTwo = random.randint(1, 15)
    numbers.update([numberOne,numberTwo])
    if (numberOne==numberTwo):
        break
    print("From biggest to smallest, the two random numbers are: ",sorted([numberOne,numberTwo],reverse=True))
    print("The sum of the two numbers is: ",sum([numberOne,numberTwo]))
print('--------------------------------------------------------------')
print("From biggest to smallest, all random numbers are: ",sorted(list(numbers),reverse=True))
print("The sum of all numbers is: ",sum(numbers))
</code>```

Body:
I was doing some python practice and have been stumped with this question. I have figured out how to do all the operations but do not know how to create the terminating loop, any help would be appreciated.

Question:
Write a program that generates 2 numbers between 1 and 15.  Display them in order from biggest to smallest. Display the sum of the numbers. The program should continue until the random numbers generated are the same.  At the end of the program display, the total sum of all the numbers generated.

from random import randint

numberOne = randint(1, 15)
numberTwo = randint(1, 15)

print("Your two random numbers are: ", numberOne, numberTwo)
print()

if (numberOne > numberTwo):
    biggest_num = numberOne
elif (numberTwo > numberOne):
    biggest_num = numberTwo

if (numberOne < numberTwo):
    smallest_num = numberOne
elif (numberTwo < numberOne):
    smallest_num = numberTwo

print("From biggest to smallest, the two random numbers are: ", biggest_num, smallest_num)
print("The sum of the two numbers is: ", numberOne + numberTwo)


问:
Can git branches be listed with numbers?
I was wondering if anyone had built a script or had a way to list git branches with numbers so that instead of this (preferably in bash)

```<code>feature/myusername/ID-1111-my-branch-name
feature/myusername/ID-2222-my-branch-name
feature/myusername/ID-3333-my-branch-name
feature/myusername/ID-4444-my-branch-name
</code>```

I could get a list like this (or similar)

```<code>#1 feature/myusername/ID-1111-my-branch-name
#2 feature/myusername/ID-2222-my-branch-name
#3 feature/myusername/ID-3333-my-branch-name
#4 feature/myusername/ID-4444-my-branch-name
</code>```

Then checking out a branch would be as easy as

```<code>git checkout #4
</code>```

答:
For Git Bash on Windows, I edited the .gitconfig file in my user directory to have the following section:

```<code>[alias]
    lbn = !git branch | cat -n
    cobn = "!f() { branch_name=$(git branch --format='%(refname:short)' | head -n $1 | tail -n 1); git checkout $branch_name; }; f"
</code>```

This may not be the most sophisticated approach, but it worked for me:

```<code>$ git lbn
     1    bugfix/1234_CrashInAboutScreen
     2    feature/feature1
     3    feature/feature2
     4  * master

$ git cobn 2
Switched to branch 'feature/feature1'

</code>```

Like Alderath's answer, mine is also a simple implementation without input validation or error handling.

Body:
I was wondering if anyone had built a script or had a way to list git branches with numbers so that instead of this (preferably in bash)

feature/myusername/ID-1111-my-branch-name
feature/myusername/ID-2222-my-branch-name
feature/myusername/ID-3333-my-branch-name
feature/myusername/ID-4444-my-branch-name

I could get a list like this (or similar)

#1 feature/myusername/ID-1111-my-branch-name
#2 feature/myusername/ID-2222-my-branch-name
#3 feature/myusername/ID-3333-my-branch-name
#4 feature/myusername/ID-4444-my-branch-name

Then checking out a branch would be as easy as

git checkout #4

Body:
For Git Bash on Windows, I edited the .gitconfig file in my user directory to have the following section:

[alias]
    lbn = !git branch | cat -n
    cobn = "!f() { branch_name=$(git branch --format='%(refname:short)' | head -n $1 | tail -n 1); git checkout $branch_name; }; f"

This may not be the most sophisticated approach, but it worked for me:

$ git lbn
     1    bugfix/1234_CrashInAboutScreen
     2    feature/feature1
     3    feature/feature2
     4  * master

$ git cobn 2
Switched to branch 'feature/feature1'

Like Alderath's answer, mine is also a simple implementation without input validation or error handling.


问:
How to install aws-cli on alpine?
I'm installing aws-cli on a docker swarm manager node running alpine (Linux 0317632a4ad9 4.9.59-moby #1 SMP Thu Mar 1 20:54:00 UTC 2018 x86_64 Linux).  The aws-cli package for Alpine is currently listed in the community repo on the edge branch (1.18.55.r0).  I modified /etc/apk/repositories to target this repo.

The install blew up looking for py3-urllib3, but I got around that and finally got a clean install with no errors, as below:

```<code>  ~ $ sudo apk add aws-cli@edge-comm
    fetch http://dl-cdn.alpinelinux.org/alpine/edge/community/x86_64/APKINDEX.tar.gz
    ERROR: unsatisfiable constraints:
      py3-urllib3-1.25.9-r0:
        masked in: @edge
        satisfies: py3-botocore-1.16.12-r0[py3-urllib3<1.26]

    ~ $ sudo apk add py3-urllib3@edge aws-cli@edge-comm
    (1/23) Installing groff (1.22.3-r1)
    (2/23) Installing py3-six (1.10.0-r6)
    (3/23) Installing py3-dateutil (2.6.0-r1)
    (4/23) Installing libpng (1.6.37-r0)
    (5/23) Installing freetype (2.7.1-r2)
    (6/23) Installing libjpeg-turbo (1.5.3-r2)
    (7/23) Installing lcms2 (2.8-r1)
    (8/23) Installing openjpeg (2.3.0-r2)
    (9/23) Installing tiff (4.0.10-r0)
    (10/23) Installing libwebp (0.6.0-r0)
    (11/23) Installing py3-pillow (4.1.0-r0)
    (12/23) Installing py3-roman (2.0.0-r2)
    (13/23) Installing py3-docutils (0.13.1-r0)
    (14/23) Installing py3-jmespath@edge-comm (0.9.5-r0)
    (15/23) Installing py3-urllib3@edge (1.25.9-r0)
    (16/23) Installing py3-botocore@edge-comm (1.16.12-r0)
    (17/23) Installing py3-s3transfer@edge-comm (0.3.3-r0)
    (18/23) Installing py3-colorama@edge-comm (0.4.3-r0)
    (19/23) Installing yaml (0.1.7-r0)
    (20/23) Installing py3-yaml (3.12-r1)
    (21/23) Installing py3-asn1 (0.2.3-r0)
    (22/23) Installing py3-rsa (3.4.2-r1)
    (23/23) Installing aws-cli@edge-comm (1.18.55-r0)
    Executing busybox-1.26.2-r11.trigger
    OK: 576 MiB in 81 packages
</code>```

The binary is created at /usr/bin/aws, but crashes looking for an awscli module:

```<code>~ $ aws
Traceback (most recent call last):
  File "/usr/bin/aws", line 19, in <module>
    import awscli.clidriver
ModuleNotFoundError: No module named 'awscli'
</code>```

Thanks!

答:
For anybody who googles this,
I've been using the image node:12.16.1-alpine.

RUN apk add --no-cache \
        python3 \
        py3-pip \
    && pip3 install --upgrade pip \
    && pip3 install --no-cache-dir \
        awscli \
    && rm -rf /var/cache/apk/*

RUN aws --version   # Just to make sure its installed alright

# Should output aws-cli/1.18.69 etc.
```

Worked fine for me.

NOTE: apk --no-cache and pip3 --no-cache-dir are used to keep the Docker image lean by not retaining package cache.

Title: How to install aws-cli on alpine?

Body:
I'm installing aws-cli on a docker swarm manager node running alpine (Linux 0317632a4ad9 4.9.59-moby #1 SMP Thu Mar 1 20:54:00 UTC 2018 x86_64 Linux).  The aws-cli package for Alpine is currently listed in the community repo on the edge branch (1.18.55.r0).  I modified /etc/apk/repositories to target this repo.

The install blew up looking for py3-urllib3, but I got around that and finally got a clean install with no errors, as below:

  ~ $ sudo apk add aws-cli@edge-comm
    fetch http://dl-cdn.alpinelinux.org/alpine/edge/community/x86_64/APKINDEX.tar.gz
    ERROR: unsatisfiable constraints:
      py3-urllib3-1.25.9-r0:
        masked in: @edge
        satisfies: py3-botocore-1.16.12-r0[py3-urllib3<1.26]

    ~ $ sudo apk add py3-urllib3@edge aws-cli@edge-comm
    (1/23) Installing groff (1.22.3-r1)
    (2/23) Installing py3-six (1.10.0-r6)
    (3/23) Installing py3-dateutil (2.6.0-r1)
    (4/23) Installing libpng (1.6.37-r0)
    (5/23) Installing freetype (2.7.1-r2)
    (6/23) Installing libjpeg-turbo (1.5.3-r2)
    (7/23) Installing lcms2 (2.8-r1)
    (8/23) Installing openjpeg (2.3.0-r2)
    (9/23) Installing tiff (4.0.10-r0)
    (10/23) Installing libwebp (0.6.0-r0)
    (11/23) Installing py3-pillow (4.1.0-r0)
    (12/23) Installing py3-roman (2.0.0-r2)
    (13/23) Installing py3-docutils (0.13.1-r0)
    (14/23) Installing py3-jmespath@edge-comm (0.9.5-r0)
    (15/23) Installing py3-urllib3@edge (1.25.9-r0)
    (16/23) Installing py3-botocore@edge-comm (1.16.12-r0)
    (17/23) Installing py3-s3transfer@edge-comm (0.3.3-r0)
    (18/23) Installing py3-colorama@edge-comm (0.4.3-r0)
    (19/23) Installing yaml (0.1.7-r0)
    (20/23) Installing py3-yaml (3.12-r1)
    (21/23) Installing py3-asn1 (0.2.3-r0)
    (22/23) Installing py3-rsa (3.4.2-r1)
    (23/23) Installing aws-cli@edge-comm (1.18.55-r0)
    Executing busybox-1.26.2-r11.trigger
    OK: 576 MiB in 81 packages

The binary is created at /usr/bin/aws, but crashes looking for an awscli module:

~ $ aws
Traceback (most recent call last):
  File "/usr/bin/aws", line 19, in <module>
    import awscli.clidriver
ModuleNotFoundError: No module named 'awscli'

Thanks!

Body:
For anybody who googles this,
I've been using the image node:12.16.1-alpine.

RUN apk add --no-cache \
        python3 \
        py3-pip \
    && pip3 install --upgrade pip \
    && pip3 install --no-cache-dir \
        awscli \
    && rm -rf /var/cache/apk/*

RUN aws --version   # Just to make sure its installed alright

# Should output aws-cli/1.18.69 etc.

Worked fine for me.

NOTE: apk --no-cache and pip3 --no-cache-dir are used to keep the Docker image lean by not retaining package cache.


问:
Return highest number and associated name from object in Javascript
This is my react app - https://imgur.com/a/QSuK8rY

I'm trying to return the highest and lowest latitude and the name of the city. I have it working to return the latitude but the name is coming up undefined... It is weird because in my jest testing, my function is working fine. I'm using React, Javascript and my API to load and store data... What I'm doing in this function is putting all the latitudes into an array then doing Math.max then looping through this.cities to see which latitude in the object matches the highest latitude that we put into mostNorthLat, then getting the name of the city that matches the lat.

This is my javascript file with my pure functions:

```<code>//Loads cities in API and injects it into this.cities

    async loadCities() {
            const data = await postData(url + "all");
            //Create a dictionary of cities and keep track of the last key
            const cities = {};
            data.forEach(x => {
                cities[x.key] = x;
                this.lastKey = (x.key > this.lastKey) ? x.key : this.lastKey;
            });

            this.cities = cities;
        }

//This is my add function I use for adding new cities to my API, which then React uses to create my cards for each object in my cities object in the API

    async addOrUpdate(city) {
            let theUrl;

            if (city.key) {
                theUrl = url + 'update'
            } else {
                theUrl = url + 'add'
                this.lastKey++;
                city.key = this.lastKey;
                city.population = Number(city.population)
            }
            await postData(theUrl, city);
            this.cities[city.key] = city;
    }

//My functions that are running the most North and most South

    getMostNorthern() {
            let latitudeArray = []
            let theName;
            for (let key in this.cities) {
                latitudeArray.push(this.cities[key].latitude)
            }
            let mostNorthLat = Math.max.apply(null, latitudeArray);
            for (let key in this.cities) {
                if (mostNorthLat === this.cities[key].latitude) {
                    theName = this.cities[key].name
                }
            }
            if (this.length() > 0) {
                return `${theName} at ${mostNorthLat}°`
            }
        }

    getMostSouthern() {
            let latitudeArray = []
            let theName;
            for (let key in this.cities) {
                latitudeArray.push(this.cities[key].latitude)
            }
            let mostSouthLat = Math.min.apply(null, latitudeArray);
            for (let key in this.cities) {
                if (mostSouthLat === this.cities[key].latitude) {
                    theName = this.cities[key].name
                }
            }
            if (this.length() > 0) {
                return `${theName} at ${mostSouthLat}°`
            }
        }
</code>```

Here is what a city object looks like:

```<code>    {
        "key": 1,
        "latitude": "1",
        "longitude": "1",
        "name": "City",
        "population": 49500
    },
</code>```

Each city object is held in a main object called 'cities'

```<code>    constructor() {
            this.cities = {};
            this.lastKey = 0;
        }
</code>```

So this is an what 3 cities inside the object looks like:

```<code>    {
            '1': City {
              name: "Gangster's Paradise",
              latitude: -15,
              longitude: 5,
              population: 10,
              key: 1
            },
            '2': City {
              name: 'Pho City',
              latitude: 5,
              longitude: 52,
              population: 1050,
              key: 2
            },
            '3': City {
              name: 'Frisbee Land',
              latitude: 0,
              longitude: 12,
              population: 1000000,
              key: 3
            }
    }
</code>```

My React portion:

```<code>    function CitiesApp() {
       const classes = useStyles();
       const [message, setMessage] = useState('')

       const [count, setCount] = useState(0)

       const [total, setTotal] = useState()
       const [northest, setNorthest] = useState()
       const [southest, setSouthest] = useState()

       useEffect(() => {
          //Load cities from the API - re-render when count is updated
          async function fetchData() {
             try {
                await cityCtrl.loadCities()
                updateSummary()
             } catch (e) {
                userMsg('Turn on the server')
             }
          }
          fetchData();
       }, [count]);

       async function onSave(city) {
          await cityCtrl.addOrUpdate(city)
          setCount(count + 1)
          updateSummary()
       }

       async function deleteCard(thekey) {
          await cityCtrl.deleteCard(thekey)
          setCount(count + 1)
          updateSummary()
       }

       async function moveIn(thekey, num) {
          await cityCtrl.movedIn(thekey, num)
          setCount(count + 1)
          updateSummary()
       }

       async function moveOut(thekey, num) {
          await cityCtrl.movedOut(thekey, num)
          setCount(count + 1)
          updateSummary()
       }

       function updateSummary() {
          setTotal(cityCtrl.getTotalPopulation())
          setNorthest(cityCtrl.getMostNorthern())
          setSouthest(cityCtrl.getMostSouthern())
       }
    }
</code>```

答:
I have found the issue! The way I had this set up was using defaultValue in react and initially, any new city has default ' ' blank value. Then changes once I submit the form... however if I put in a number it would just be in the string so I had to convert the longitude and lat to a Number just as I did with population and then my functions worked.</p>

```<code>    async addOrUpdate(city) {
        let theUrl;

        if (city.key) {
            theUrl = url + 'update'
        } else {
            theUrl = url + 'add'
            this.lastKey++;
            city.key = this.lastKey;
            city.population = Number(city.population)
            city.latitude = Number(city.latitude)
            city.longitude = Number(city.longitude)
        }
        await postData(theUrl, city);
        this.cities[city.key] = city;
    }
</code>```

Body:
This is my react app - https://imgur.com/a/QSuK8rY

I'm trying to return the highest and lowest latitude and the name of the city. I have it working to return the latitude but the name is coming up undefined... It is weird because in my jest testing, my function is working fine. I'm using React, Javascript and my API to load and store data... What I'm doing in this function is putting all the latitudes into an array then doing Math.max then looping through this.cities to see which latitude in the object matches the highest latitude that we put into mostNorthLat, then getting the name of the city that matches the lat.

This is my javascript file with my pure functions:

//Loads cities in API and injects it into this.cities

    async loadCities() {
            const data = await postData(url + "all");
            //Create a dictionary of cities and keep track of the last key
            const cities = {};
            data.forEach(x => {
                cities[x.key] = x;
                this.lastKey = (x.key > this.lastKey) ? x.key : this.lastKey;
            });

            this.cities = cities;
        }

//This is my add function I use for adding new cities to my API, which then React uses to create my cards for each object in my cities object in the API

    async addOrUpdate(city) {
            let theUrl;

            if (city.key) {
                theUrl = url + 'update'
            } else {
                theUrl = url + 'add'
                this.lastKey++;
                city.key = this.lastKey;
                city.population = Number(city.population)
            }
            await postData(theUrl, city);
            this.cities[city.key] = city;
    }

//My functions that are running the most North and most South

    getMostNorthern() {
            let latitudeArray = []
            let theName;
            for (let key in this.cities) {
                latitudeArray.push(this.cities[key].latitude)
            }
            let mostNorthLat = Math.max.apply(null, latitudeArray);
            for (let key in this.cities) {
                if (mostNorthLat === this.cities[key].latitude) {
                    theName = this.cities[key].name
                }
            }
            if (this.length() > 0) {
                return `${theName} at ${mostNorthLat}°`
            }
        }

    getMostSouthern() {
            let latitudeArray = []
            let theName;
            for (let key in this.cities) {
                latitudeArray.push(this.cities[key].latitude)
            }
            let mostSouthLat = Math.min.apply(null, latitudeArray);
            for (let key in this.cities) {
                if (mostSouthLat === this.cities[key].latitude) {
                    theName = this.cities[key].name
                }
            }
            if (this.length() > 0) {
                return `${theName} at ${mostSouthLat}°`
            }
        }

Here is what a city object looks like:

    {
        "key": 1,
        "latitude": "1",
        "longitude": "1",
        "name": "City",
        "population": 49500
    },

Each city object is held in a main object called 'cities'

    constructor() {
            this.cities = {};
            this.lastKey = 0;
        }

So this is an what 3 cities inside the object looks like:

    {
            '1': City {
              name: "Gangster's Paradise",
              latitude: -15,
              longitude: 5,
              population: 10,
              key: 1
            },
            '2': City {
              name: 'Pho City',
              latitude: 5,
              longitude: 52,
              population: 1050,
              key: 2
            },
            '3': City {
              name: 'Frisbee Land',
              latitude: 0,
              longitude: 12,
              population: 1000000,
              key: 3
            }
    }

My React portion:

    function CitiesApp() {
       const classes = useStyles();
       const [message, setMessage] = useState('')

       const [count, setCount] = useState(0)

       const [total, setTotal] = useState()
       const [northest, setNorthest] = useState()
       const [southest, setSouthest] = useState()

       useEffect(() => {
          //Load cities from the API - re-render when count is updated
          async function fetchData() {
             try {
                await cityCtrl.loadCities()
                updateSummary()
             } catch (e) {
                userMsg('Turn on the server')
             }
          }
          fetchData();
       }, [count]);

       async function onSave(city) {
          await cityCtrl.addOrUpdate(city)
          setCount(count + 1)
          updateSummary()
       }

       async function deleteCard(thekey) {
          await cityCtrl.deleteCard(thekey)
          setCount(count + 1)
          updateSummary()
       }

       async function moveIn(thekey, num) {
          await cityCtrl.movedIn(thekey, num)
          setCount(count + 1)
          updateSummary()
       }

       async function moveOut(thekey, num) {
          await cityCtrl.movedOut(thekey, num)
          setCount(count + 1)
          updateSummary()
       }

       function updateSummary() {
          setTotal(cityCtrl.getTotalPopulation())
          setNorthest(cityCtrl.getMostNorthern())
          setSouthest(cityCtrl.getMostSouthern())
       }
    }

Body:
I have found the issue! The way I had this set up was using defaultValue in react and initially, any new city has default ' ' blank value. Then changes once I submit the form... however if I put in a number it would just be in the string so I had to convert the longitude and lat to a Number just as I did with population and then my functions worked.

    async addOrUpdate(city) {
        let theUrl;

        if (city.key) {
            theUrl = url + 'update'
        } else {
            theUrl = url + 'add'
            this.lastKey++;
            city.key = this.lastKey;
            city.population = Number(city.population)
            city.latitude = Number(city.latitude)
            city.longitude = Number(city.longitude)
        }
        await postData(theUrl, city);
        this.cities[city.key] = city;
    }


问:
JS why FOR LOOP not iterating when condition is A&&B but works when B&&A (A==B==true)
This is my first question so hello everyone!

I wanted to write condition in way to terminate loop ASAP.

Loop which doesn`t work but should terminate loop faster:

```<code>for (
      let i = 0;
      transactionsSortedByTime[i].unixTime <= unixEndTime && i < listLength;
      i++
    ) {}
</code>```

Loop which works:

```<code>for (
      let i = 0;
       i < listLength && transactionsSortedByTime[i].unixTime <= unixEndTime;
      i++
    ) {}
</code>```

Till now I was certain that results of A&&B and B&&A are the same but terminates with false result in different time (when one of them {A or B} is false).

My question is why second one loop iterates properly while first one doesn`t.

答:
Just add (), the loop structure apparently takes the bool value of the first expression, to solve this you must add parentheses, so that your expression takes the value of your && operator:</p>

```<code>for (
  let i = 0;
  (transactionsSortedByTime[i].unixTime <= unixEndTime && i < listLength);
  i++
) {}
</code>```

Body:
This is my first question so hello everyone!

I wanted to write condition in way to terminate loop ASAP.

Loop which doesn`t work but should terminate loop faster:

for (
      let i = 0;
      transactionsSortedByTime[i].unixTime <= unixEndTime && i < listLength;
      i++
    ) {}

Loop which works:

for (
      let i = 0;
       i < listLength && transactionsSortedByTime[i].unixTime <= unixEndTime;
      i++
    ) {}

Till now I was certain that results of A&&B and B&&A are the same but terminates with false result in different time (when one of them {A or B} is false).

My question is why second one loop iterates properly while first one doesn`t.

Body:
Just add (), the loop structure apparently takes the bool value of the first expression, to solve this you must add parentheses, so that your expression takes the value of your && operator:

for (
  let i = 0;
  (transactionsSortedByTime[i].unixTime <= unixEndTime && i < listLength);
  i++
) {}


问:
Publish report using multiple html file- Jenkins
I have two questions here in 'Publish Html report'

1) I am trying to publish html Report from multiple html folders where the name of the html file is same in all the folders.
Please suggest on how to declare multiple html files which has the same name through 'Publish HTML Report' .

2)Is there a way to ignore error ,if some times there is no html file in any of the folder path , on publishing the HTML report.

Thanks in Advance

答:
What you can do is, "Add" multiple reports under "Publish HTML Reports".

The reports folder path is relative to workspace. You have to mention report path folder, file name(s) and report title.

No, since you have identical filenames, I assume, file path is surely different and report title will vary too. So, adding multiple "Publish HTML Report" should work.

Regarding your question about ignoring the report, there is option under "Publishing options" as "Allow missing report".

Allow missing report - if false, build will be marked as failed if the
  report directory does not exist.

Reference : https://plugins.jenkins.io/htmlpublisher/


问:
ERROR: unsatisfiable constraints: flow (missing) in Alpine Linux
I'm trying to install the "flow" package in my Docker image:

```<code>RUN apk add --no-cache --repository https://nl.alpinelinux.org/alpine/edge/testing flow
</code>```

It was working fine until yesterday (it seems they have updated the edge repository yesterday) and removed the Flow package (Don't know the reason):

```<code>Step 5/16 : RUN apk add --no-cache --repository https://nl.alpinelinux.org/alpine/edge/testing flow
 ---> Running in 0b4a87861307
fetch https://nl.alpinelinux.org/alpine/edge/testing/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.8/main/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.8/community/x86_64/APKINDEX.tar.gz
ERROR: unsatisfiable constraints:
  flow (missing):
    required by: world[flow]
</code>```

Is there any solution for this ? Couldn't find it in community either.

答:
Unfortunately, it seems the flow Alpine package was unmaintained, and was indeed removed yesterday:
https://git.alpinelinux.org/aports/commit/?id=81a4c6c5967b97fbaacac401077888c05c4924eb

The package was introduced to Alpine edge/testing on July 2018, resolving the following Github issue:  https://github.com/facebook/flow/issues/1605

It seems it hasn't qualified to a community/main since.

Sadly, when a package is removed from Alpine repositories, the change quickly propagates to all mirrors, so it probably doesn't live in any Alpine repository at the moment. If it is critical to your workflow, you could try recovering an old package version from some Alpine image that has it, if you can find such an image by scanning through DockerHub or Github, but this is very far from ideal. Alternatively, you could try building Flow yourself from source.

I would suggest filing an issue at the Flow Github repository: either revive the existing linked issue, or add a new one of your own. Good luck!

Body:
I'm trying to install the "flow" package in my Docker image:

RUN apk add --no-cache --repository https://nl.alpinelinux.org/alpine/edge/testing flow

It was working fine until yesterday (it seems they have updated the edge repository yesterday) and removed the Flow package (Don't know the reason):

Step 5/16 : RUN apk add --no-cache --repository https://nl.alpinelinux.org/alpine/edge/testing flow
 ---> Running in 0b4a87861307
fetch https://nl.alpinelinux.org/alpine/edge/testing/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.8/main/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.8/community/x86_64/APKINDEX.tar.gz
ERROR: unsatisfiable constraints:
  flow (missing):
    required by: world[flow]

Is there any solution for this ? Couldn't find it in community either.


问:
No EJB found with interface when built as jar
I have the following error when deploying and starting the application with Wildfly.

No EJB found with interface of type "de.dev.java.project.api.ProjectApi" for binding de.dev.java.project.restservice.ProjectRestService/projectApi.

```<code>Project module structure:
- project-api   -> built as jar
   - ProjectApi.java
- project-impl  -> built as jar
   - ProjectRestService.java
     {
         @EJB ProjectApi projectApi
      }
- application -> built as ear, which includes modules above
</code>```

I only have a problem when i build "project-impl" module as jar. When i built as war i do not have a problem. What does war include which jar does not?

答: You must build as a proper ejb jar, not just regular jar. It also needs to be referenced properly in the ear. Use you IDE to setup suitable maven project with the right archetype</p>

Body:
I have the following error when deploying and starting the application with Wildfly.

No EJB found with interface of type "de.dev.java.project.api.ProjectApi" for binding de.dev.java.project.restservice.ProjectRestService/projectApi.

Project module structure:
- project-api   -> built as jar
   - ProjectApi.java
- project-impl  -> built as jar
   - ProjectRestService.java
     {
         @EJB ProjectApi projectApi
      }
- application -> built as ear, which includes modules above

I only have a problem when i build "project-impl" module as jar. When i built as war i do not have a problem. What does war include which jar does not?


问:
How to get the value of a first key-value pair in Python
I'm trying to sole exercise where I have dictionary like this:

```<code>[{"state" : 'Maine', 'capital': 'Augusta'}, {'country': 'Spain', "capital" : "Madrid"}]
</code>```

Output is supposed to be:

```<code>["The capital of Maine is Augusta", "The capital of Spain is Madrid"]
</code>```

My problem stems from the fact that the first key can be either state or country so I cannot just use that key name to access value, so how can I print the first key value if the name can be different across inputs?

答:
```<code>In [3]: out = []

In [4]: for i in d:
   ...:     if 'state' in i:
   ...:         out.append('The capital of {} of is {}'.format(i['state'], i['capital']))
   ...:     else:
   ...:         out.append('The capital of {} of is {}'.format(i['country'], i['capital']))
   ...:

In [5]: out
Out[5]: ['The capital of Maine of is Augusta', 'The capital of Spain of is Madrid']
</code>```

Body:
I'm trying to sole exercise where I have dictionary like this:

[{"state" : 'Maine', 'capital': 'Augusta'}, {'country': 'Spain', "capital" : "Madrid"}]

Output is supposed to be:

["The capital of Maine is Augusta", "The capital of Spain is Madrid"]

My problem stems from the fact that the first key can be either state or country so I cannot just use that key name to access value, so how can I print the first key value if the name can be different across inputs?


答:
```<code>l = [{"state" : 'Maine', 'capital': 'Augusta'}, {'country': 'Spain', "capital" : "Madrid"}]
result = [ "The capital of {} is {}".format( d['state'] if 'state' in d else d['country'], d['capital']) for d in l ]
</code>```

Title: How to get the value of a first key-value pair in Python


问:
Google Cloud Run service url (discovery)
I am running several gcloud services which have assigned urls automatically in following format:

https://SERVICE_NAME-XXXXXXX-ew.a.run.app/

This is not particularly easy to work with and to pass these URLs to clients. Alternative is to use the custom domain, but this needs hardcoding subdomains within DNS records (as far as I understand) and I would like to avoid that and use the default URLs.

What is the best practice to work with these URLs? I can imagine keeping some mapping of service->URL and passing it to clients, but I would like to avoid reinventing the wheels.

答:
Edit: I've released an external tool called runsd that lets you do this. Check it out: https://github.com/ahmetb/runsd

Thanks for this question! The "Service discovery by name" for Cloud Run is very much an active area of work. Though, there are no active timelines we can share yet.

You can see a prototype of me running this on Cloud Run here: https://twitter.com/ahmetb/status/1233147619834118144

APIs like Google Cloud Service Directory linked are geared more towards custom/DIY service discovery you might want to build to your RPC stack such as gRPC. It's more of a managed domain name directory, that you can integrate with your RPC.

If you are interested in participating an alpha for this feature in the future, drop me an email at ahmetb at google.


问:
Split the date into 1st, 2nd, 3rd, 4th week of the month
I have a data frame of dates:

```<code>  id|date
  13|2017-01-31
  12|2016-12-07
  11|2013-03-19
</code>```

I want to classify the dates into weather it is the 1st, 2nd, 3rd or 4th week of the month.

I am using this function:

```<code>
calendar.setfirstweekday(calendar.SUNDAY)

def get_week_of_month(dt):
    year  = dt.year
    month = dt.month
    day   = dt.day
    x = np.array(calendar.monthcalendar(year, month))
    week_of_month = np.where(x==day)[0][0] + 1
    return(week_of_month)

df['week_month'] = df['date'].apply(get_week_of_month)

</code>```

However I am getting 6 possible weeks instead of 4. Please help

Body:
I have a data frame of dates:

  id|date
  13|2017-01-31
  12|2016-12-07
  11|2013-03-19

I want to classify the dates into weather it is the 1st, 2nd, 3rd or 4th week of the month.

I am using this function:

calendar.setfirstweekday(calendar.SUNDAY)

def get_week_of_month(dt):
    year  = dt.year
    month = dt.month
    day   = dt.day
    x = np.array(calendar.monthcalendar(year, month))
    week_of_month = np.where(x==day)[0][0] + 1
    return(week_of_month)

df['week_month'] = df['date'].apply(get_week_of_month)

However I am getting 6 possible weeks instead of 4. Please help

Body:
Like this:

In [1036]: df['date']= pd.to_datetime(df['date'])

In [1044]: df['week_of_month'] = ((df['date'].dt.day-1)//7)+1

In [1045]: df
Out[1045]:
   id       date  week_of_month
0  13 2017-01-31              5
1  12 2016-12-07              1
2  11 2013-03-19              3


问:
how to connect via REST at IBM DB2?
i create a DB2 service in IBM cloud and i read that i can access at my db via REST.

so, i try to connect using this:

```<code>curl -k -X POST 'https://MY_DB_URL/dbapi/v4/auth/tokens'
   -d '{"userid":"MY_SERVICE_USER", "password":"MY_SERVICE_PASSWORD"}'
</code>```

and the response is always:

```<code>{"trace":"TRACE_CODE","errors":
   [{
     "code":"invalid_parameters",
     "message":"HWCSEC0012E: The credential is invalid! For regular credentials, both the user name and password are required. For IAM API key or token credentials, they mustn't be empty.",
     "target":{"type":"","name":""},
     "more_info":""
   }]
}
</code>```

i really don't know how to solve that.

docs:

https://cloud.ibm.com/apidocs/db2-on-cloud#request-a-new-access-token

https://developer.ibm.com/static/site-id/85/api/db2whc/

答:
i solve. they want in header
    {Content-Type: text/plain}
it's not make sense, the body is a json...</p>

Title: how to connect via REST at IBM DB2?

Body:
i create a DB2 service in IBM cloud and i read that i can access at my db via REST.

so, i try to connect using this:

curl -k -X POST 'https://MY_DB_URL/dbapi/v4/auth/tokens'
   -d '{"userid":"MY_SERVICE_USER", "password":"MY_SERVICE_PASSWORD"}'

and the response is always:

{"trace":"TRACE_CODE","errors":
   [{
     "code":"invalid_parameters",
     "message":"HWCSEC0012E: The credential is invalid! For regular credentials, both the user name and password are required. For IAM API key or token credentials, they mustn't be empty.",
     "target":{"type":"","name":""},
     "more_info":""
   }]
}

i really don't know how to solve that.

docs:

https://cloud.ibm.com/apidocs/db2-on-cloud#request-a-new-access-token

https://developer.ibm.com/static/site-id/85/api/db2whc/


问:
How to handle environment-specific settings in your rails?
Currently, the rails environment for my local machine development, i am getting reset password url like this 'localhost:3001/reset_password/aBRINDss'.
i am getting localhost:3001 because i am using development env.

currently in mailer i am using the environment like this

```<code>@reset_password_email = Settings.DEVELOPMENT_HOST_URL + '/users/reset_password/' + user.reset_password_token
</code>```

is there any way in which i don't have to mention different HOST_URL in application.yml for each env and it takes automatically host url according to it's current environment. and i can use it here direct in @reset_password_email = Settings.DEVELOPMENT_HOST_URL + '/users/reset_password/' + user.reset_password_token
in place of Settings.DEVELOPMENT_HOST_URL

答:
You can specify blocks for specific environments like this

production:
  aws:
    access_key_id: 123
    secret_access_key: 345
```

Take a look here for more info: https://blog.engineyard.com/rails-encrypted-credentials-on-rails-5.2

Body:
Currently, the rails environment for my local machine development, i am getting reset password url like this 'localhost:3001/reset_password/aBRINDss'.
i am getting localhost:3001 because i am using development env.

currently in mailer i am using the environment like this

@reset_password_email = Settings.DEVELOPMENT_HOST_URL + '/users/reset_password/' + user.reset_password_token

is there any way in which i don't have to mention different HOST_URL in application.yml for each env and it takes automatically host url according to it's current environment. and i can use it here direct in @reset_password_email = Settings.DEVELOPMENT_HOST_URL + '/users/reset_password/' + user.reset_password_token
in place of Settings.DEVELOPMENT_HOST_URL

Body:
You can specify blocks for specific environments like this

production:
  aws:
    access_key_id: 123
    secret_access_key: 345

Take a look here for more info: https://blog.engineyard.com/rails-encrypted-credentials-on-rails-5.2


问:
How to export Flutter project for web hosting
I have developed a web app using Flutter in Android Studio IDE, and have enabled Flutter Web from the Flutter console. In Android Studio, I am able to run the app and use Chrome(web) as my target device; and the app runs well.

Can anyone advice what is the next step to export this to a web hosting service? Like PorkBun. Any help is appreciated, thanks!

答:
Run this command in the terminal:

```<code>flutter build web
</code>```

It will compile your project for the web, then you should see a generated files under [your_project]/build/web

Upload the contents of the web folder to the root folder of your hosting service. The main page index.html should run your app.

Body:
Run this command in the terminal:

flutter build web

It will compile your project for the web, then you should see a generated files under [your_project]/build/web

Upload the contents of the web folder to the root folder of your hosting service. The main page index.html should run your app.