问:
Making a div inside a div responsive
I am beginner in web development, and i am trying to develop a responsive website. While developing i made one div element that has an image, then inside that i have one box with content "BUILD THAT MATTERS", which is inside a div with a class "firstBlock", the div "firstBlock" moves down when i click the hover button of navigation bar, but the box inside "BUILD THAT MATTERS", doesn't move.

I tried to make the image as a background image of the the div firstBlock, but that made the fitting of image in such a way that it got cropped, so is there any way so that the box inside the div moves with the navigation bar drop down menu, as of now only the firstBlock, that is the image moves, but inner box "BUILD THAT MATTERS" remains fixed in its position.

```<code><-- html-->
<div id="firstBlock">
    <img id="img1" src="image1.jpg">
    <div class="box1">
       <h1 class="text1">BUILD THAT MATTERS</h1>
    </div>
</div>

/*CSS*/
#firstBlock {
    display: flex;
    height: 90%;
    width: 100%;
}
#img1 {
    width: 100%;
    height: 100%;
    object-fit: cover;
}
.box1 {
    display: flex;
    border: 5px solid black;
    position: absolute;
    top: 70%;
    left: 50%;
    transform: translateX(-50%) translateY(-50%);
}
</code>```

So, the box with content "BUILD THAT MATTERS" should move down with the first block when navigation drop down scrolls down.

fiddle link: https://jsfiddle.net/gj7v8huc/

git link: https://ayush-flash.github.io/StartupLandingPage/StartUpLandingPage/

答:
Very simple rule:
make the parent of the absolute element relative

Your class:

```<code>.box1 {
   display: flex;
    border: 5px solid black;
    position: absolute;       # parent of this should be relative
    top: 40%;                 # I set this to 40%
    left: 50%;
    transform: translateX(-50%) translateY(-50%);
}
</code>```

the parent:

```<code>#firstBlock {
    display: flex;
    height: 90%;
    width: 100%;
    position: relative;        # take care of child with absolute position
}
</code>```

What is this rule for?

When we have an element that has position: absolute it is removed from current flow of document. For bringing it back to the document's flow but meanwhile keeping it according to the need of absolute position, we can make the parent's position relative

Title: Making a div inside a div responsive

Body:
I am beginner in web development, and i am trying to develop a responsive website. While developing i made one div element that has an image, then inside that i have one box with content "BUILD THAT MATTERS", which is inside a div with a class "firstBlock", the div "firstBlock" moves down when i click the hover button of navigation bar, but the box inside "BUILD THAT MATTERS", doesn't move.

I tried to make the image as a background image of the the div firstBlock, but that made the fitting of image in such a way that it got cropped, so is there any way so that the box inside the div moves with the navigation bar drop down menu, as of now only the firstBlock, that is the image moves, but inner box "BUILD THAT MATTERS" remains fixed in its position.

<-- html-->

BUILD THAT MATTERS

/*CSS*/
#firstBlock {
    display: flex;
    height: 90%;
    width: 100%;
}
#img1 {
    width: 100%;
    height: 100%;
    object-fit: cover;
}
.box1 {
    display: flex;
    border: 5px solid black;
    position: absolute;
    top: 70%;
    left: 50%;
    transform: translateX(-50%) translateY(-50%);
}

So, the box with content "BUILD THAT MATTERS" should move down with the first block when navigation drop down scrolls down.

fiddle link: https://jsfiddle.net/gj7v8huc/

git link: https://ayush-flash.github.io/StartupLandingPage/StartUpLandingPage/

Body:
Very simple rule:
make the parent of the absolute element relative

Your class:

.box1 {
   display: flex;
    border: 5px solid black;
    position: absolute;       # parent of this should be relative
    top: 40%;                 # I set this to 40%
    left: 50%;
    transform: translateX(-50%) translateY(-50%);
}

the parent:

#firstBlock {
    display: flex;
    height: 90%;
    width: 100%;
    position: relative;        # take care of child with absolute position
}

What is this rule for?

When we have an element that has position: absolute it is removed from current flow of document. For bringing it back to the document's flow but meanwhile keeping it according to the need of absolute position, we can make the parent's position relative


来源: stackexchange

问:
Image Recognition - Tensorflow
I am using a Convolutional Neural Network (CNN) for image detection of 30 different kinds of fruits.
The dataset I have currently consists of "train" and "test" folders, each of them having 30 sub directories for the 30 different classes.

"train" folder has in total 671 jpg files while "test" folder has in total 300 jpg files.

The Python code that I have written to achieve image detection is as follows-

```<code>from keras.preprocessing.image import ImageDataGenerator
import numpy as np
import matplotlib.pyplot as plt
from keras.utils import to_categorical
from keras.models import Sequential
from keras.layers import Dense, Conv2D, Flatten, Dropout
from keras.layers.convolutional import MaxPooling2D
from keras import backend as K
from sklearn.metrics import accuracy_score, precision_score, recall_score

# Read in images from 'train' folder-
train_datagen = ImageDataGenerator(
    rescale=1./255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True
)

train_generator = train_datagen.flow_from_directory(
    directory=r"./train/", target_size=(420, 420), color_mode="rgb",
    batch_size=30, class_mode="categorical", shuffle=True
    )
# O/P-
# Found 671 images belonging to 30 classes.

# Read in images from 'test' folder-
test_datagen = ImageDataGenerator(
    rescale=1./255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True
)

valid_generator = test_datagen.flow_from_directory(
    directory=r"./test/", target_size=(420, 420), color_mode="rgb", batch_size=30,
    class_mode="categorical", shuffle=True
    )
# O/P-
# Found 300 images belonging to 30 classes.

# Dimensions of our image(s)-
img_width, img_height = 420, 420

if K.image_data_format() == 'channels_first':
    input_shape = (3, img_width, img_height)
else:
    input_shape = (img_width, img_height, 3)

print("\ninput_shape = {0}\n\n".format(input_shape))
# input_shape = (420, 420, 3)

# Build the CNN-

model = Sequential()

# model.add(Conv2D(32, (5, 5), input_shape = (32, 32, 3), activation = 'relu'))
model.add(Conv2D(32, (3, 3), input_shape = input_shape, activation = 'relu'))
# model.add(Conv2D(32, (3, 3), activation = 'relu'))
# model.add(Dense(40, activation = 'relu'))
model.add(MaxPooling2D(pool_size = (2, 2)))
model.add(Dropout(0.2))
# model.add(Conv2D(64, (3, 3), activation = 'relu'))
model.add(Conv2D(64, (3, 3), activation = 'relu'))
model.add(MaxPooling2D(pool_size = (2, 2)))
model.add(Dropout(0.2))
model.add(Flatten())
# model.add(Dense(512, activation = 'relu'))
model.add(Dense(128, activation = 'relu'))
model.add(Dense(30, activation = 'softmax'))

# Compiling the model-
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics = ['accuracy'])

STEP_SIZE_TRAIN=train_generator.n//train_generator.batch_size
STEP_SIZE_VALID=valid_generator.n//valid_generator.batch_size

model.fit_generator(generator=train_generator, steps_per_epoch=STEP_SIZE_TRAIN, epochs=5)
</code>```

When I attempt to execute this code, I get the following message-

Using TensorFlow backend.
Found 671 images belonging to 30 classes.
Found 300 images belonging to 30 classes.

input_shape = (420, 420, 3)

Epoch 1/5 2019-02-12 14:48:18.088495: I
  tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports
  instructions that this TensorFlow binary was not compiled to use: AVX2
  FMA 2019-02-12 14:48:23.270184: W
  tensorflow/core/framework/allocator.cc:122] Allocation of 670940160
  exceeds 10% of system memory. 2019-02-12 14:48:31.747262: W
  tensorflow/core/framework/allocator.cc:122] Allocation of 670940160
  exceeds 10% of system memory.

After this, my system hangs and I have to restart the system. This has happened already 4 times. My system has Intel Core i5 @ 2.2 GHz with 8 GB RAM.

What's going wrong?

答:
Try reducing batch_size attribute to a small number like 1 or 2 and execute

```<code>train_generator = data_generator.flow_from_directory(
    'path_to_the_training_set',
    target_size = (IMG_SIZE,IMG_SIZE),
    batch_size = 2,
    class_mode = 'categorical'
    )
</code>```

Refer the below link
https://github.com/tensorflow/tensorflow/issues/18736

Hope this helps .

ContentLicense: CC BY-SA 4.0

Title: Image Recognition - Tensorflow

Body:
I am using a Convolutional Neural Network (CNN) for image detection of 30 different kinds of fruits.
The dataset I have currently consists of "train" and "test" folders, each of them having 30 sub directories for the 30 different classes.

"train" folder has in total 671 jpg files while "test" folder has in total 300 jpg files.

The Python code that I have written to achieve image detection is as follows-

from keras.preprocessing.image import ImageDataGenerator
import numpy as np
import matplotlib.pyplot as plt
from keras.utils import to_categorical
from keras.models import Sequential
from keras.layers import Dense, Conv2D, Flatten, Dropout
from keras.layers.convolutional import MaxPooling2D
from keras import backend as K
from sklearn.metrics import accuracy_score, precision_score, recall_score

# Read in images from 'train' folder-
train_datagen = ImageDataGenerator(
    rescale=1./255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True
)

train_generator = train_datagen.flow_from_directory(
    directory=r"./train/", target_size=(420, 420), color_mode="rgb",
    batch_size=30, class_mode="categorical", shuffle=True
    )
# O/P-
# Found 671 images belonging to 30 classes.

# Read in images from 'test' folder-
test_datagen = ImageDataGenerator(
    rescale=1./255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True
)

valid_generator = test_datagen.flow_from_directory(
    directory=r"./test/", target_size=(420, 420), color_mode="rgb", batch_size=30,
    class_mode="categorical", shuffle=True
    )
# O/P-
# Found 300 images belonging to 30 classes.

# Dimensions of our image(s)-
img_width, img_height = 420, 420

if K.image_data_format() == 'channels_first':
    input_shape = (3, img_width, img_height)
else:
    input_shape = (img_width, img_height, 3)

print("\ninput_shape = {0}\n\n".format(input_shape))
# input_shape = (420, 420, 3)

# Build the CNN-

model = Sequential()

# model.add(Conv2D(32, (5, 5), input_shape = (32, 32, 3), activation = 'relu'))
model.add(Conv2D(32, (3, 3), input_shape = input_shape, activation = 'relu'))
# model.add(Conv2D(32, (3, 3), activation = 'relu'))
# model.add(Dense(40, activation = 'relu'))
model.add(MaxPooling2D(pool_size = (2, 2)))
model.add(Dropout(0.2))
# model.add(Conv2D(64, (3, 3), activation = 'relu'))
model.add(Conv2D(64, (3, 3), activation = 'relu'))
model.add(MaxPooling2D(pool_size = (2, 2)))
model.add(Dropout(0.2))
model.add(Flatten())
# model.add(Dense(512, activation = 'relu'))
model.add(Dense(128, activation = 'relu'))
model.add(Dense(30, activation = 'softmax'))

# Compiling the model-
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics = ['accuracy'])

STEP_SIZE_TRAIN=train_generator.n//train_generator.batch_size
STEP_SIZE_VALID=valid_generator.n//valid_generator.batch_size

model.fit_generator(generator=train_generator, steps_per_epoch=STEP_SIZE_TRAIN, epochs=5)

When I attempt to execute this code, I get the following message-

Using TensorFlow backend.
Found 671 images belonging to 30 classes.
Found 300 images belonging to 30 classes.

input_shape = (420, 420, 3)

Epoch 1/5 2019-02-12 14:48:18.088495: I
  tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports
  instructions that this TensorFlow binary was not compiled to use: AVX2
  FMA 2019-02-12 14:48:23.270184: W
  tensorflow/core/framework/allocator.cc:122] Allocation of 670940160
  exceeds 10% of system memory. 2019-02-12 14:48:31.747262: W
  tensorflow/core/framework/allocator.cc:122] Allocation of 670940160
  exceeds 10% of system memory.

After this, my system hangs and I have to restart the system. This has happened already 4 times. My system has Intel Core i5 @ 2.2 GHz with 8 GB RAM.

What's going wrong?

Body:
Try reducing batch_size attribute to a small number like 1 or 2 and execute

train_generator = data_generator.flow_from_directory(
    'path_to_the_training_set',
    target_size = (IMG_SIZE,IMG_SIZE),
    batch_size = 2,
    class_mode = 'categorical'
    )

Refer the below link
https://github.com/tensorflow/tensorflow/issues/18736

Hope this helps .


问:
How to set manual key value in array instead of index in multi-dimensional array in PHP?
I am using PHP 7.0 for my development. I got

```<code>Array
(
    [0] => Array
        (
            [lngCngSecUserId] => 0
            [sdtHolidayDate] => 1
        )

)
</code>```

as output by following code:

```<code><?php
    $tblActualHoliday = array();
    $arrColFields= array();
    $arrColFields["lngCngSecUserId"] = 0;
    $arrColFields["sdtHolidayDate"] = 1;
    array_push($tblActualHoliday,$arrColFields);
    print_r($tblActualHoliday);
?>
</code>```

but I want output as

```<code>Array
(
    [ColHeader] => Array
        (
            [lngCngSecUserId] => 0
            [sdtHolidayDate] => 1
        )

)
</code>```

How can I get it? I want ColHeader instead of 0 as index key.

答:
You can set "ColHeader" as a key for entry in $tblActualHoliday the same way as "lngCngSecUserId" for $arrColFields.

```<code>    $arrColFields= array();
    $arrColFields["lngCngSecUserId"] = 0;
    $arrColFields["sdtHolidayDate"] = 1;

    $tblActualHoliday["ColHeader"] = $arrColFields;

?>
</code>```

Body:
I am using PHP 7.0 for my development. I got

Array
(
    [0] => Array
        (
            [lngCngSecUserId] => 0
            [sdtHolidayDate] => 1
        )

)

as output by following code:

<?php
    $tblActualHoliday = array();
    $arrColFields= array();
    $arrColFields["lngCngSecUserId"] = 0;
    $arrColFields["sdtHolidayDate"] = 1;
    array_push($tblActualHoliday,$arrColFields);
    print_r($tblActualHoliday);
?>

but I want output as

Array
(
    [ColHeader] => Array
        (
            [lngCngSecUserId] => 0
            [sdtHolidayDate] => 1
        )

)

How can I get it? I want ColHeader instead of 0 as index key.

Body:
You can set "ColHeader" as a key for entry in $tblActualHoliday the same way as "lngCngSecUserId" for $arrColFields.

    $arrColFields= array();
    $arrColFields["lngCngSecUserId"] = 0;
    $arrColFields["sdtHolidayDate"] = 1;

    $tblActualHoliday["ColHeader"] = $arrColFields;

?>


问:
Google IntensityMap Visualization US States
I am attempting to use the google visualization library - intensity map.  I have a list of states and the number of users in each state.  I can only get the world map to show, I want to highlight the us states and only show us map.

http://code.google.com/apis/visualization/documentation/gallery/geomap.html

Does anyone have a good example, tutorial or instructions on how to do this?

答: It looks like Google isn't sharing that capability right now. It's a few months old, but this reply on the Google Chart API group seems to kill the idea. I'm looking for the same functionality, but the closest I've found is Maps Alive (no affiliation). However, their API seems more limited and the pricing adds up quickly. Best of luck!</p>

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
org.koin.android.error.MissingAndroidContextException: when try to test app with context
I want to write test for koin. I use RoomDatabase, which receives context in constructor. App works well but test fails

Can't resolve Application instance. Please use androidContext()
  function in your KoinApplication configuration.

答:
Make sure to set your context when you start koin. Then you should be able to access it via androidContext() in your modules.</p>

```<code>startKoin {
    androidContext(this@App)
    modules(...)
    ...
}
</code>```

Body:
Make sure to set your context when you start koin. Then you should be able to access it via androidContext() in your modules.

startKoin {
    androidContext(this@App)
    modules(...)
    ...
}


问:
How should be the regex for alphanumeric where alphabet only with combinations of"w" or "d" or "h"
I need the regex to validate the user entered string, the string may be of following formats.

ex: 1w 2d 1h or 2w 1h or 1w 2d. Likewise combinations of numbers and w,d and h.

I am looking for the regex to allow the combinations number and w or d or h.

Is it possible to have a regex like that way?

答:
Try ^(?:\d+w ?)?(?:\d+d ?)?(?:\d+h)?$

Explaantion:

^ - match beginning of a string

(?:...) - non-capturing group

\d+ - match one or more digits

w, d, h - match literally w, d, h respectively

? - match preceeding pattern zero or one time

Demo


问:
How to change apk name by using gradle like this format?
I'd like to change "app-release.apk" file name to like following when I build an app by using gradle.

```
[format]
(appname of package name)_V(version code)_(yyMMdd)_(R|T)

[explain]
(appname of package name) : example) com.example.myApp -> myApp
(version code) : build version code 2.2.3 -> 223
(yyMMdd) : build date 2015.11.18 -> 151118
(R|T) : if app is release, "R" but debug is "T".
```

If I generate an apk file in release, result is : myApp_V223_151118_R.apk.

How to make a file name like this in gradle?

答:
2019 / 2020 - How to change APK name For Gradle 3.3, 3.4, 3.5, 4.0 and above

```<code>android {
   ......
   applicationVariants.all { variant ->
       variant.outputs.all {
           def flavor = variant.name
           def versionName = variant.versionName
           outputFileName = "prefix_${flavor}_${versionName}.apk"
       }
   }
}
</code>```

The result would be like this,

prefix_release_1.0.1.apk

Body:
I'd like to change "app-release.apk" file name to like following when I build an app by using gradle.

[format]
(appname of package name)_V(version code)_(yyMMdd)_(R|T)

[explain]
(appname of package name) : example) com.example.myApp -> myApp
(version code) : build version code 2.2.3 -> 223
(yyMMdd) : build date 2015.11.18 -> 151118
(R|T) : if app is release, "R" but debug is "T".

If I generate an apk file in release, result is : myApp_V223_151118_R.apk.

How to make a file name like this in gradle?

Body:
2019 / 2020 - How to change APK name For Gradle 3.3, 3.4, 3.5, 4.0 and above

android {
   ......
   applicationVariants.all { variant ->
       variant.outputs.all {
           def flavor = variant.name
           def versionName = variant.versionName
           outputFileName = "prefix_${flavor}_${versionName}.apk"
       }
   }
}

The result would be like this,

prefix_release_1.0.1.apk


问:
Create one variable within another in SASS
I have a problem converting the obtained values into variables so that I can control the arrival data.

HTML:

```<code>$itemicon-ca: "\a100";
$itemicon-star: "\a101";
$itemicon-pin: "\a102";

$itemicon-collection: ('ca', 'star', 'pin');

@for $i from 0 to length($itemicon-collection) {

  $name: nth($itemicon-collection, $i+1);
  $value: itemicon-#{$name};

    .itemicon-#{$name} {
      &:before {
        content: #{$value};
      }
    }
}
</code>```

Currently print this:

```<code>.itemicon-ca:before {
  content: itemicon-ca;
}

.itemicon-star:before {
  content: itemicon-star;
}

.itemicon-pin:before {
  content: itemicon-pin;
}
</code>```

The idea is to convert the generated value into a variable, so you can print the data

I should print this:

```<code>.itemicon-ca {
  &:before {
    content: $itemicon-ca;
  }
}

.itemicon-star {
  &:before {
    content: $itemicon-star;
  }
}

.itemicon-pin {
  &:before {
    content: $itemicon-pin;
  }
}
</code>```

Any ideas or suggestions to find a possible solution?

答:
You can't call a variable dynamically in SASS. However, you can achieve what you want with a map and a @each loop:

```<code>$itemicon-collection: (
  'ca' : "\a100",
  'star' : "\a101",
  'pin' : "\a102"
);

@each $name, $value in $itemicon-collection {
  .itemicon-#{$name} {
    &:before {
      content: #{$value};
    }
  }
}
</code>```

You can check this for more info about @each loops.

Body:
I have a problem converting the obtained values into variables so that I can control the arrival data.

HTML:

$itemicon-ca: "\a100";
$itemicon-star: "\a101";
$itemicon-pin: "\a102";

$itemicon-collection: ('ca', 'star', 'pin');

@for $i from 0 to length($itemicon-collection) {

  $name: nth($itemicon-collection, $i+1);
  $value: itemicon-#{$name};

    .itemicon-#{$name} {
      &:before {
        content: #{$value};
      }
    }
}

Currently print this:

.itemicon-ca:before {
  content: itemicon-ca;
}

.itemicon-star:before {
  content: itemicon-star;
}

.itemicon-pin:before {
  content: itemicon-pin;
}

The idea is to convert the generated value into a variable, so you can print the data

I should print this:

.itemicon-ca {
  &:before {
    content: $itemicon-ca;
  }
}

.itemicon-star {
  &:before {
    content: $itemicon-star;
  }
}

.itemicon-pin {
  &:before {
    content: $itemicon-pin;
  }
}

Any ideas or suggestions to find a possible solution?

Body:
You can't call a variable dynamically in SASS. However, you can achieve what you want with a map and a @each loop:

$itemicon-collection: (
  'ca' : "\a100",
  'star' : "\a101",
  'pin' : "\a102"
);

@each $name, $value in $itemicon-collection {
  .itemicon-#{$name} {
    &:before {
      content: #{$value};
    }
  }
}

You can check this for more info about @each loops.


问:
Vuejs load component via v-if and use v-show afterwards
I want to load a component for the first time via v-if condition but once its rendered I want to toggle its visiblity via v-show, is there any preferred way of achieving it?</p>

答:
How about emitting an event from the component when it's first created / mounted and listening for that to toggle the v-show.

For example

<my-component v-if="componentLoad" v-show="componentLoaded && componentToggle"
              @load="componentLoaded = true" />
```

<pre class="lang-js prettyprint-override"><code>data: {
  componentLoad: false,
  componentLoaded: false,
  componentToggle: true,
}
</code>```

and in the component

mounted () {
  this.$emit('load')
}
```

Then you just need to flip componentLoad to initially create and mount the component and then alter componentToggle to show / hide it.

Body:
How about emitting an event from the component when it's first created / mounted and listening for that to toggle the v-show.

For example

<my-component v-if="componentLoad" v-show="componentLoaded && componentToggle"
              @load="componentLoaded = true" />

data: {
  componentLoad: false,
  componentLoaded: false,
  componentToggle: true,
}

and in the component

mounted () {
  this.$emit('load')
}

Then you just need to flip componentLoad to initially create and mount the component and then alter componentToggle to show / hide it.


问:
Remove backslashes from response entity Json in Java
I am testing my Rest controller and when i print the results in java they seem to be okay but on swagger or postman it return slashes. How do i remove these.

In Java i print the object with a log and the result is as below:

ReturnObject

```<code>    {
      create=Create{
        create={
          "Apartment": "Flat",
          "Drink": {
            "Alchol": {
              "Beer": {
                "Dutch": "Groeshe",
                "Zimbo": "Zambezi"
              },
              "Wine": "pocupine"
            },
            "NonAlcoholic": {
              "fizzy": "Coke",
              "juice": "liquifruit"
            }
          },
          "fruit": "Apple",
          "size": "Large",
          "color": "Red",
          "Proffesion": [
            "Java",
            "Lawyer"
          ],
          "cars": {
            "type": "BMW",
            "Color": "Brown"
          }
        }
      },
      update=null,
      delete=null
    }
</code>```

I googled and nothing in java seems to solve this problem. Please assist

```<code>    @RestController
    public class ProcessController<T extends Serializable> {

    @Autowired
    private EngineImpl engine;

    @RequestMapping(value = "/api/processEngine", method = RequestMethod.POST, produces = "application/json")
    public ResponseEntity<ReturnObject<T>> processEngine(@RequestBody final Request request) throws Exception {

        ReturnObject<T> response = engine.calculate((T) request.getA(), (T) request.getB());

        LOG.info("ReturnObject engine response parameters: " + response);
        //Prints: ReturnObject{create=Create{create={"Apartment":"Flat","Drink":{"Alchol":{"Beer":{"Dutch":"Groeshe","Zimbo":"Zambezi"},"Wine":"pocupine"},"NonAlcoholic":{"fizzy":"Coke","juice":"liquifruit"}},"fruit":"Apple","size":"Large","color":"Red","Proffesion":["Java","Lawyer"],"cars":{"type":"BMW","Color":"Brown"}}}, update=null, delete=null}
        return new ResponseEntity<>(response, HttpStatus.OK);
    }
}
</code>```

Expected:

```<code>    {
      "create": {
        "create": {
            "Apartment": "Flat",
            "Drink": {
                "Alchol": {
                    "Beer": {
                        "Dutch": "Groeshe",
                        "Zimbo": "Zambezi"

                    },
                    "Wine": "pocupine"

                },
                "NonAlcoholic": {
                    "fizzy": "Coke",
                    "juice": "liquifruit"
                }
            },
            "fruit": "Apple",
            "size": "Large",
            "color": "Red",
            "Proffesion": ["Java", "Lawyer"],
            "cars": {
                "type": "BMW",
                "Color": "Brown"
            }
        },
        "update": null,
        "delete": null
    }
}
</code>```

Actual:

```<code>    {
      "create": {
        "create": "{\"Apartment\":\"Flat\",\"Drink\":{\"Alchol\":{\"Beer\":{\"Dutch\":\"Groeshe\",\"Zimbo\":\"Zambezi\"},\"Wine\":\"pocupine\"},\"NonAlcoholic\":{\"fizzy\":\"Coke\",\"juice\":\"liquifruit\"}},\"fruit\":\"Apple\",\"size\":\"Large\",\"color\":\"Red\",\"Proffesion\":[\"Java\",\"Lawyer\"],\"cars\":{\"type\":\"BMW\",\"Color\":\"Brown\"}}"
      },
      "update": null,
      "delete": null
    }
</code>```

答:
You need to use the parser, to get pretty JSON string, guess you're using Jackson,  so you can do it in this way:</p>

```<code>ObjectMapper objectMapper = new ObjectMapper();
objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(yourObject);
</code>```

Body:
I am testing my Rest controller and when i print the results in java they seem to be okay but on swagger or postman it return slashes. How do i remove these.

In Java i print the object with a log and the result is as below:

ReturnObject

    {
      create=Create{
        create={
          "Apartment": "Flat",
          "Drink": {
            "Alchol": {
              "Beer": {
                "Dutch": "Groeshe",
                "Zimbo": "Zambezi"
              },
              "Wine": "pocupine"
            },
            "NonAlcoholic": {
              "fizzy": "Coke",
              "juice": "liquifruit"
            }
          },
          "fruit": "Apple",
          "size": "Large",
          "color": "Red",
          "Proffesion": [
            "Java",
            "Lawyer"
          ],
          "cars": {
            "type": "BMW",
            "Color": "Brown"
          }
        }
      },
      update=null,
      delete=null
    }

I googled and nothing in java seems to solve this problem. Please assist

    @RestController
    public class ProcessController<T extends Serializable> {

    @Autowired
    private EngineImpl engine;

    @RequestMapping(value = "/api/processEngine", method = RequestMethod.POST, produces = "application/json")
    public ResponseEntity<ReturnObject<T>> processEngine(@RequestBody final Request request) throws Exception {

        ReturnObject<T> response = engine.calculate((T) request.getA(), (T) request.getB());

        LOG.info("ReturnObject engine response parameters: " + response);
        //Prints: ReturnObject{create=Create{create={"Apartment":"Flat","Drink":{"Alchol":{"Beer":{"Dutch":"Groeshe","Zimbo":"Zambezi"},"Wine":"pocupine"},"NonAlcoholic":{"fizzy":"Coke","juice":"liquifruit"}},"fruit":"Apple","size":"Large","color":"Red","Proffesion":["Java","Lawyer"],"cars":{"type":"BMW","Color":"Brown"}}}, update=null, delete=null}
        return new ResponseEntity<>(response, HttpStatus.OK);
    }
}

Expected:

    {
      "create": {
        "create": {
            "Apartment": "Flat",
            "Drink": {
                "Alchol": {
                    "Beer": {
                        "Dutch": "Groeshe",
                        "Zimbo": "Zambezi"

                    },
                    "Wine": "pocupine"

                },
                "NonAlcoholic": {
                    "fizzy": "Coke",
                    "juice": "liquifruit"
                }
            },
            "fruit": "Apple",
            "size": "Large",
            "color": "Red",
            "Proffesion": ["Java", "Lawyer"],
            "cars": {
                "type": "BMW",
                "Color": "Brown"
            }
        },
        "update": null,
        "delete": null
    }
}

Actual:

    {
      "create": {
        "create": "{\"Apartment\":\"Flat\",\"Drink\":{\"Alchol\":{\"Beer\":{\"Dutch\":\"Groeshe\",\"Zimbo\":\"Zambezi\"},\"Wine\":\"pocupine\"},\"NonAlcoholic\":{\"fizzy\":\"Coke\",\"juice\":\"liquifruit\"}},\"fruit\":\"Apple\",\"size\":\"Large\",\"color\":\"Red\",\"Proffesion\":[\"Java\",\"Lawyer\"],\"cars\":{\"type\":\"BMW\",\"Color\":\"Brown\"}}"
      },
      "update": null,
      "delete": null
    }

Body:
You need to use the parser, to get pretty JSON string, guess you're using Jackson,  so you can do it in this way:

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(yourObject);


问:
How to add image/icon for right side of a button?
These days I am developing flutter mobile application for the Android platform. I want to add a button with text an icon/image. That image must be the right side of the button text.

I have already attached the image here.

This is my code.

```<code>child: FlatButton.icon(
     icon: Image.asset("images/notesicon.png", width: 20.0,height: 20.0,),
     label: Text("Add Note",
        style: TextStyle(
           fontSize: 11.0,
           fontFamily: "Raleway"
        ),
     ),
     textColor: Colors.white,
     color: Color(0xFF226597),
     shape: OutlineInputBorder(borderSide: BorderSide(
               style: BorderStyle.solid,
               width: 1.0,
               color: Colors.black),
            borderRadius: new BorderRadius.circular(20.0)
      ),
    ),
</code>```

答:
Here you have your code fixed , don't use FlatButton.icon just use the FlatButton constructor and add a custom child , Row in this case.

```<code>    SizedBox(
            width: 150,
            child: FlatButton(
              child: Row(
                children: [
                  Text(
                    "Add Note",
                    style: TextStyle(fontSize: 11.0, fontFamily: "Raleway"),
                  ),
                  Image.asset(
                    "images/notesicon.png",
                    width: 20.0,
                    height: 20.0,
                  )
                ],
              ),
              onPressed: () {},
              textColor: Colors.white,
              color: Color(0xFF226597),
              shape: OutlineInputBorder(
                  borderSide: BorderSide(
                      style: BorderStyle.solid, width: 1.0, color: Colors.black),
                  borderRadius: new BorderRadius.circular(20.0)),
            ),
          ),
</code>```

Body:
These days I am developing flutter mobile application for the Android platform. I want to add a button with text an icon/image. That image must be the right side of the button text.

I have already attached the image here.

This is my code.

child: FlatButton.icon(
     icon: Image.asset("images/notesicon.png", width: 20.0,height: 20.0,),
     label: Text("Add Note",
        style: TextStyle(
           fontSize: 11.0,
           fontFamily: "Raleway"
        ),
     ),
     textColor: Colors.white,
     color: Color(0xFF226597),
     shape: OutlineInputBorder(borderSide: BorderSide(
               style: BorderStyle.solid,
               width: 1.0,
               color: Colors.black),
            borderRadius: new BorderRadius.circular(20.0)
      ),
    ),

Body:
Here you have your code fixed , don't use FlatButton.icon just use the FlatButton constructor and add a custom child , Row in this case.

    SizedBox(
            width: 150,
            child: FlatButton(
              child: Row(
                children: [
                  Text(
                    "Add Note",
                    style: TextStyle(fontSize: 11.0, fontFamily: "Raleway"),
                  ),
                  Image.asset(
                    "images/notesicon.png",
                    width: 20.0,
                    height: 20.0,
                  )
                ],
              ),
              onPressed: () {},
              textColor: Colors.white,
              color: Color(0xFF226597),
              shape: OutlineInputBorder(
                  borderSide: BorderSide(
                      style: BorderStyle.solid, width: 1.0, color: Colors.black),
                  borderRadius: new BorderRadius.circular(20.0)),
            ),
          ),


问:
argument of type 'elementfinder' is not assignable to parameter of type 'boolean'
I am trying to make function if check box is not checked then click on it when I call this function I am getting error message
"argument of type 'elementfinder' is not assignable to parameter of type 'boolean'"

//variable

```<code>md5hash_checkbox = element(by.id('md5hash'));
 //To check check box if not selected
  selectCheckBox(checkValue: boolean){
        this.checkValue.isSelected().then(selected => {
            if (selected) {
                console.log(checkValue+': Is Already selected');
            } else {
                this.checkValue.click();
            }
        });
</code>```

on calling function like this.selectCheckBox(this.sha1hash_checkbox);
Getting error message "argument of type 'elementfinder' is not assignable to parameter of type 'boolean'"

答:
isSelected() is applicable to ElementFinder not boolean.
You should do this:

```<code>selectCheckbox(): void {
  el:ElementFinder =  element(by.id('md5hash'));
  el.isSelected().then(selected => {
    if (selected) {
        console.log(el + ': Is Already selected');
    } else {
        el.click();
    }
  });
}
</code>```

Body:
I am trying to make function if check box is not checked then click on it when I call this function I am getting error message
"argument of type 'elementfinder' is not assignable to parameter of type 'boolean'"

//variable

md5hash_checkbox = element(by.id('md5hash'));
 //To check check box if not selected
  selectCheckBox(checkValue: boolean){
        this.checkValue.isSelected().then(selected => {
            if (selected) {
                console.log(checkValue+': Is Already selected');
            } else {
                this.checkValue.click();
            }
        });

on calling function like this.selectCheckBox(this.sha1hash_checkbox);
Getting error message "argument of type 'elementfinder' is not assignable to parameter of type 'boolean'"

Body:
isSelected() is applicable to ElementFinder not boolean.
You should do this:

selectCheckbox(): void {
  el:ElementFinder =  element(by.id('md5hash'));
  el.isSelected().then(selected => {
    if (selected) {
        console.log(el + ': Is Already selected');
    } else {
        el.click();
    }
  });
}


问:
Confirmation popup Box according to a condition on submit button
I am using Drupal 7. In my list I have 2000 subscribers. Now I want a confirmation box before executing the form. The only issue is If I have more than 20 users I want the confirmation form to ask the question" Do you want to continue with 20 users' If the answer is yes, then perform some php operation on it else go to the main page.

```<code>function player_operation_display_form_submit($form, &$form_state)

 {
     if($total_players > 20){

    echo '<script type="text/JavaScript">
    var a = confirm("Do you want to continue with more than 20 users");

    if(a){ //performing some operation
       $operation[] = array('Assign_goals', array($records_value,
                           $records_key, $assign_username));

      }
       else{
           drupal_goto('exit_operation');
             die();
        }
      </script>';
         }
</code>```

Now I understand that $operation[] and exit_operation are my php functions and wont execute in my js file. I just want to know how to execute these functions.

答:
You can do this on js file just before submit the form. </p>

```<code><script>
   $(function() {

        var total_players  = <?php echo $total_players;?>;

        $('#form').submit(function() {
          if(total_players > 20){
             if (confirm("Do you want to continue with more than 20 users?")){
                 $('form').submit();
             }else{
                 return false;
             }
          }
       });
   });
</script>
</code>```

<p>For more appropriate solution please share your html form code and java script code.  </p>

Body:
I am using Drupal 7. In my list I have 2000 subscribers. Now I want a confirmation box before executing the form. The only issue is If I have more than 20 users I want the confirmation form to ask the question" Do you want to continue with 20 users' If the answer is yes, then perform some php operation on it else go to the main page.

function player_operation_display_form_submit($form, &$form_state)

 {
     if($total_players > 20){

    echo '';
         }

Now I understand that $operation[] and exit_operation are my php functions and wont execute in my js file. I just want to know how to execute these functions.

Body:
You can do this on js file just before submit the form.

<script>
   $(function() {

        var total_players  = <?php echo $total_players;?>;

        $('#form').submit(function() {
          if(total_players > 20){
             if (confirm("Do you want to continue with more than 20 users?")){
                 $('form').submit();
             }else{
                 return false;
             }
          }
       });
   });
</script>

For more appropriate solution please share your html form code and java script code.


问:
Problems installing Haskell library regex-pcre on Mac OS X
I'm trying to install the Haskell regex-pcre library using:

```<code>cabal install --extra-include-dirs=/usr/local/include \
              --extra-include-dirs=/usr/include regex-pcre
</code>```

However I get this weird error:

```<code>Resolving dependencies...
Configuring regex-pcre-0.94.2...
Preprocessing library regex-pcre-0.94.2...
In file included from /Library/Frameworks/GHC.framework/Versions/7.0.2-i386/usr/lib/ghc-7.0.2/include/HsFFI.h:68,
                 from /Library/Frameworks/GHC.framework/Versions/7.0.2-i386/usr/lib/ghc-7.0.2/template-hsc.h:4,
                 from dist/build/Text/Regex/PCRE/Wrap_hsc_make.c:1:
/usr/include/float.h:8:24: error: float.h: No such file or directory
In file included from /Library/Frameworks/GHC.framework/Versions/7.0.2-i386/usr/lib/ghc-7.0.2/template-hsc.h:9,
                 from dist/build/Text/Regex/PCRE/Wrap_hsc_make.c:1:
/usr/include/stdarg.h:4:25: error: stdarg.h: No such file or directory
compiling dist/build/Text/Regex/PCRE/Wrap_hsc_make.c failed (exit code 1)
command was: /usr/bin/gcc -c dist/build/Text/Regex/PCRE/Wrap_hsc_make.c -o dist/build/Text/Regex/PCRE/Wrap_hsc_make.o -march=i686 -m32 -isysroot /Developer/SDKs/MacOSX10.5.sdk -mmacosx-version-min=10.5 -fno-stack-protector -march=i686 -m32 -isysroot /Developer/SDKs/MacOSX10.5.sdk -mmacosx-version-min=10.5 -fno-stack-protector -march=i686 -m32 -isysroot /Developer/SDKs/MacOSX10.5.sdk -mmacosx-version-min=10.5 -D__GLASGOW_HASKELL__=700 -Ddarwin_BUILD_OS -Ddarwin_HOST_OS -Di386_BUILD_ARCH -Di386_HOST_ARCH -I/usr/include -I/usr/local/include -DHAVE_PCRE_H -DSPLIT_BASE=1 -I/Library/Frameworks/GHC.framework/Versions/7.0.2-i386/usr/lib/ghc-7.0.2/bytestring-0.9.1.10/include -I/Library/Frameworks/GHC.framework/Versions/7.0.2-i386/usr/lib/ghc-7.0.2/base-4.3.1.0/include -I/Library/Frameworks/GHC.framework/Versions/7.0.2-i386/usr/lib/ghc-7.0.2/include -I/Library/Frameworks/GHC.framework/Versions/7.0.2-i386/usr/lib/ghc-7.0.2/include -I/Library/Frameworks/GHC.framework/Versions/7.0.2-i386/usr/lib/ghc-7.0.2/include/
cabal: Error: some packages failed to install:
regex-pcre-0.94.2 failed during the building phase. The exception was:
ExitFailure 1
</code>```

The gist of it, seems to be that it can't find a second float.h file:

```<code>/usr/include/float.h:8:24: error: float.h: No such file or directory
</code>```

I've opened /usr/include/float.h and line 8 reads:

```<code>#include_next <float.h>
</code>```

I've done my searching on Google, and although I don't know that much C I think I understand what that line is supposed to say, but... I don't know how to really solve this problem. I don't know where else I have a float.h file on my system.

The GHC and GCC versions I'm using. GCC comes from XCode 4. GHC is 32bit, but I've tried the 64bit version too, with the same results.

```<code>$ gcc --version
i686-apple-darwin10-gcc-4.2.1 (GCC) 4.2.1 (Apple Inc. build 5666) (dot 3)

$ ghc --version
The Glorious Glasgow Haskell Compilation System, version 7.0.2
</code>```

OS X version is 10.6.7.

Any help greatly appreciated.

答:
Looks to me like ticket #5011 - XCode 4 on Mac + GHC 7.0.2 fails to link.

This is fixed in GHC 7.0.3 which will be part of the mid-April release of the Haskell Platform.

And alternative fix is to downgrade to the 2010.2 Haskell Platform.

See this question yesterday: Can't install OpenGLRaw-1.1.0.1 on OS X

Body:
I'm trying to install the Haskell regex-pcre library using:

cabal install --extra-include-dirs=/usr/local/include \
              --extra-include-dirs=/usr/include regex-pcre

However I get this weird error:

Resolving dependencies...
Configuring regex-pcre-0.94.2...
Preprocessing library regex-pcre-0.94.2...
In file included from /Library/Frameworks/GHC.framework/Versions/7.0.2-i386/usr/lib/ghc-7.0.2/include/HsFFI.h:68,
                 from /Library/Frameworks/GHC.framework/Versions/7.0.2-i386/usr/lib/ghc-7.0.2/template-hsc.h:4,
                 from dist/build/Text/Regex/PCRE/Wrap_hsc_make.c:1:
/usr/include/float.h:8:24: error: float.h: No such file or directory
In file included from /Library/Frameworks/GHC.framework/Versions/7.0.2-i386/usr/lib/ghc-7.0.2/template-hsc.h:9,
                 from dist/build/Text/Regex/PCRE/Wrap_hsc_make.c:1:
/usr/include/stdarg.h:4:25: error: stdarg.h: No such file or directory
compiling dist/build/Text/Regex/PCRE/Wrap_hsc_make.c failed (exit code 1)
command was: /usr/bin/gcc -c dist/build/Text/Regex/PCRE/Wrap_hsc_make.c -o dist/build/Text/Regex/PCRE/Wrap_hsc_make.o -march=i686 -m32 -isysroot /Developer/SDKs/MacOSX10.5.sdk -mmacosx-version-min=10.5 -fno-stack-protector -march=i686 -m32 -isysroot /Developer/SDKs/MacOSX10.5.sdk -mmacosx-version-min=10.5 -fno-stack-protector -march=i686 -m32 -isysroot /Developer/SDKs/MacOSX10.5.sdk -mmacosx-version-min=10.5 -D__GLASGOW_HASKELL__=700 -Ddarwin_BUILD_OS -Ddarwin_HOST_OS -Di386_BUILD_ARCH -Di386_HOST_ARCH -I/usr/include -I/usr/local/include -DHAVE_PCRE_H -DSPLIT_BASE=1 -I/Library/Frameworks/GHC.framework/Versions/7.0.2-i386/usr/lib/ghc-7.0.2/bytestring-0.9.1.10/include -I/Library/Frameworks/GHC.framework/Versions/7.0.2-i386/usr/lib/ghc-7.0.2/base-4.3.1.0/include -I/Library/Frameworks/GHC.framework/Versions/7.0.2-i386/usr/lib/ghc-7.0.2/include -I/Library/Frameworks/GHC.framework/Versions/7.0.2-i386/usr/lib/ghc-7.0.2/include -I/Library/Frameworks/GHC.framework/Versions/7.0.2-i386/usr/lib/ghc-7.0.2/include/
cabal: Error: some packages failed to install:
regex-pcre-0.94.2 failed during the building phase. The exception was:
ExitFailure 1

The gist of it, seems to be that it can't find a second float.h file:

/usr/include/float.h:8:24: error: float.h: No such file or directory

I've opened /usr/include/float.h and line 8 reads:

#include_next <float.h>

I've done my searching on Google, and although I don't know that much C I think I understand what that line is supposed to say, but... I don't know how to really solve this problem. I don't know where else I have a float.h file on my system.

The GHC and GCC versions I'm using. GCC comes from XCode 4. GHC is 32bit, but I've tried the 64bit version too, with the same results.

$ gcc --version
i686-apple-darwin10-gcc-4.2.1 (GCC) 4.2.1 (Apple Inc. build 5666) (dot 3)

$ ghc --version
The Glorious Glasgow Haskell Compilation System, version 7.0.2

OS X version is 10.6.7.

Any help greatly appreciated.


问:
jodit editor not displayed correctly
I have a problem with the jodit wysiwyg editor (or possibly any other type of plugin editor) working within a Bootstrap tab. If I add an editor to the tab content then when the user selects that tab the content is not displayed correctly (it is only a fraction of the height and is missing a lot of it's toolbar).

I suspect it is being rendered within the hidden tab div which possibly affects the redraw process?

Here is a working fiddle Click on the Editor tab to see the reduced size editor. To see the proper working version, grab the small resizer in the bottom right and drag the area, it should auto resize to the correct display.

To render the editor the only code I've used is

```<code>var editor = new Jodit('#editor', {
  autofocus: true,
  height: "600"
});
</code>```

I've also tried running the editor.resize() function after it's been created which doesn't work.

The tabs and the content are generated dynamically.
Is there some other editor function that I can call after the content has been applied that will fix the redraw?

答:
It turns out that there is an option called toolbarAdaptive that turns off adaptive mode. This allows the tool to be drawn as expected. Not sure if that is a bug in the Jodit editor itself or desired functionality.</p>

```<code>var editor = new Jodit('#editor', {
  autofocus: true,
  height: "600",
  toolbarAdaptive: false
});
</code>```

Title: jodit editor not displayed correctly

Body:
I have a problem with the jodit wysiwyg editor (or possibly any other type of plugin editor) working within a Bootstrap tab. If I add an editor to the tab content then when the user selects that tab the content is not displayed correctly (it is only a fraction of the height and is missing a lot of it's toolbar).

I suspect it is being rendered within the hidden tab div which possibly affects the redraw process?

Here is a working fiddle Click on the Editor tab to see the reduced size editor. To see the proper working version, grab the small resizer in the bottom right and drag the area, it should auto resize to the correct display.

To render the editor the only code I've used is

var editor = new Jodit('#editor', {
  autofocus: true,
  height: "600"
});

I've also tried running the editor.resize() function after it's been created which doesn't work.

The tabs and the content are generated dynamically.
Is there some other editor function that I can call after the content has been applied that will fix the redraw?

Body:
It turns out that there is an option called toolbarAdaptive that turns off adaptive mode. This allows the tool to be drawn as expected. Not sure if that is a bug in the Jodit editor itself or desired functionality.

var editor = new Jodit('#editor', {
  autofocus: true,
  height: "600",
  toolbarAdaptive: false
});


答:
Finally, the following string seems to be working fine for me...

```<code>^(?:\d+w)?((?:\d+d)|(?: \d+d))?((?:\d+h)|(?: \d+h))?$
</code>```

Thanks, everyone for helping.

Title: How should be the regex for alphanumeric where alphabet only with combinations of"w" or "d" or "h"

Body:
I need the regex to validate the user entered string, the string may be of following formats.

ex: 1w 2d 1h or 2w 1h or 1w 2d. Likewise combinations of numbers and w,d and h.

I am looking for the regex to allow the combinations number and w or d or h.

Is it possible to have a regex like that way?

Body:
Finally, the following string seems to be working fine for me...

^(?:\d+w)?((?:\d+d)|(?: \d+d))?((?:\d+h)|(?: \d+h))?$

Thanks, everyone for helping.


问:
How to retrieve large amounts of data (5000+ videos) from YouTube Data API v3?
My goal is to extract all videos from a playlist which can have many videos, ~3000 and can  have more than 5000 videos. With maxResults=50 and after implementing pagination with nextPageToken, I'm only able to call the API 20 times, after which nextPageToken isn't sent with the response

I'm calling the API from a python application. I have a while loop running till nextPageToken isn't sent, ideally this should happen AFTER all the videos are extracted, but it prematurely exits after calling the API 19-20 times

def main():
    youtube = get_authorised_youtube()  # returns YouTube resource authorized with OAuth.

    first_response = make_single_request(youtube, None)  # make_single_request() takes in the youtube resource and nextPageToken, if any.
    nextPageToken = first_response["nextPageToken"]

    try:
        count = 0
        while True:
            response = make_single_request(youtube, nextPageToken)
            nextPageToken = response["nextPageToken"]

            count += 1
            print(count, end=" ")
            print(nextPageToken)
    except KeyError as e:  # KeyError to catch if nextPageToken wasn't present
        response.pop("items")
        print(response)  # prints the last response for analysis

if __name__ == '__main__':
    main()
```

<p>snippet of <code>make_single_request()</code>:</p>

<pre class="lang-py prettyprint-override"><code>def make_single_request(youtube, nextPageToken):
    if nextPageToken is None:
        request = youtube.videos().list(
            part="id",
            myRating="like",
            maxResults=50
        )
    else:
        request = youtube.videos().list(
            part="id",
            myRating="like",
            pageToken=nextPageToken,
            maxResults=50
        )
    response = request.execute()

    return response
</code>```

Expected the code to make upwards of 50 API calls but is observed to only make around 20 calls, consistently.

Note: The following code was executed with an unpaid GCP account. The calls made has part="id" which has a quota cost of 0. The calls limit according to GCP is: 10,000. According to the quota on the console, I make only 20.

Output:

```<code>1 CGQQAA
2 CJYBEAA
3 CMgBEAA
4 CPoBEAA
5 CKwCEAA
6 CN4CEAA
7 CJADEAA
8 CMIDEAA
9 CPQDEAA
10 CKYEEAA
11 CNgEEAA
12 CIoFEAA
13 CLwFEAA
14 CO4FEAA
15 CKAGEAA
16 CNIGEAA
17 CIQHEAA
18 CLYHEAA
19 {'kind': 'youtube#videoListResponse', 'etag': '"ETAG"', 'prevPageToken': 'CLYHEAE', 'pageInfo': {'totalResults': TOTAL_RESULTS(>4000), 'resultsPerPage': 50}}
</code>```

EDIT: After changing maxResults=20, It is observed that the code makes around 50 API calls, therefore the total number of videos that can be extracted is a constant at 1000.

答:
Try to wait some time in a such way:</p>

```<code>import time
time.sleep(1) # time here in seconds
</code>```

Body:
My goal is to extract all videos from a playlist which can have many videos, ~3000 and can  have more than 5000 videos. With maxResults=50 and after implementing pagination with nextPageToken, I'm only able to call the API 20 times, after which nextPageToken isn't sent with the response

I'm calling the API from a python application. I have a while loop running till nextPageToken isn't sent, ideally this should happen AFTER all the videos are extracted, but it prematurely exits after calling the API 19-20 times

def main():
    youtube = get_authorised_youtube()  # returns YouTube resource authorized with OAuth.

    first_response = make_single_request(youtube, None)  # make_single_request() takes in the youtube resource and nextPageToken, if any.
    nextPageToken = first_response["nextPageToken"]

    try:
        count = 0
        while True:
            response = make_single_request(youtube, nextPageToken)
            nextPageToken = response["nextPageToken"]

            count += 1
            print(count, end=" ")
            print(nextPageToken)
    except KeyError as e:  # KeyError to catch if nextPageToken wasn't present
        response.pop("items")
        print(response)  # prints the last response for analysis

if __name__ == '__main__':
    main()

snippet of make_single_request():

def make_single_request(youtube, nextPageToken):
    if nextPageToken is None:
        request = youtube.videos().list(
            part="id",
            myRating="like",
            maxResults=50
        )
    else:
        request = youtube.videos().list(
            part="id",
            myRating="like",
            pageToken=nextPageToken,
            maxResults=50
        )
    response = request.execute()

    return response

Expected the code to make upwards of 50 API calls but is observed to only make around 20 calls, consistently.

Note: The following code was executed with an unpaid GCP account. The calls made has part="id" which has a quota cost of 0. The calls limit according to GCP is: 10,000. According to the quota on the console, I make only 20.

Output:

1 CGQQAA
2 CJYBEAA
3 CMgBEAA
4 CPoBEAA
5 CKwCEAA
6 CN4CEAA
7 CJADEAA
8 CMIDEAA
9 CPQDEAA
10 CKYEEAA
11 CNgEEAA
12 CIoFEAA
13 CLwFEAA
14 CO4FEAA
15 CKAGEAA
16 CNIGEAA
17 CIQHEAA
18 CLYHEAA
19 {'kind': 'youtube#videoListResponse', 'etag': '"ETAG"', 'prevPageToken': 'CLYHEAE', 'pageInfo': {'totalResults': TOTAL_RESULTS(>4000), 'resultsPerPage': 50}}

EDIT: After changing maxResults=20, It is observed that the code makes around 50 API calls, therefore the total number of videos that can be extracted is a constant at 1000.

Body:
Try to wait some time in a such way:

import time
time.sleep(1) # time here in seconds


问:
How to use a C++ member function as an interrupt handler in Arduino?
Arduino's attachInterrupt requires a callback function of type void(*)(), but I'd like to pass it a member function instead.  I can't use a C++ member function here because of its implicit this argument.

Background

I know it's possible to use C++ member functions as callbacks.  For example, FreeRTOS' xTaskCreate(...) takes a callback function of type void(*)(*).

isocpp.org has a nice FAQ on the use of member functions as callbacks.

In this related question user thiton writes:

Most sane callback libraries allow you to pass this void* argument to the functions as a way to have user-defined data in it

Perhaps the Arduino library is not "sane?" or perhaps this is design decision made to simplify the Arduino API?

it's there... inside attachInterrupt

I'm programming for an ESP32.  In the arduino-esp32 implementation of attachInterrupt, there's a function called __attachInterruptFunctionalArg(...) that seems to do exactly what I want, but since it's not part of the Arduino API, I'm hesitant to include it in a project that's for public consumption because it may break.

Example program

// An attempt to summarize https://github.com/pierremolinaro/acan2517/issues/4

#include <stdio.h>
#include <stdint.h>
#include <functional>

#define IRAM_ATTR __attribute__((section(".iram1")))

// from `esp32-hal-gpio.c`
typedef void (*voidFuncPtrArg)(void*);
extern void __attachInterruptFunctionalArg(uint8_t pin, voidFuncPtrArg userFunc, void * arg, int intr_type, bool functional);

// from Arduino `FunctionalInterrupt.cpp`
void attachInterrupt(uint8_t pin, std::function<void(void)> intRoutine, int mode);

void IRAM_ATTR interruptFunctional(void* arg);

// from Arduino `FunctionalInterrupt.h`
struct InterruptArgStructure {
    std::function<void(void)> interruptFunction;
};

// from ACAN2517
class ACAN2517
{
    public: ACAN2517 (const int interrupt_pin);
    public: void begin (void (* inInterruptServiceRoutine) (void));
    public: void begin_functional (void (* inInterruptServiceRoutine) (void *), void *);
    public: void isr(void);
    private: const int interrupt_pin;
};

ACAN2517::ACAN2517 (const int interrupt_pin):
    interrupt_pin(interrupt_pin)
{};

#define FALLING 0

// This won't work with a member function
void ACAN2517::begin (void (* inInterruptServiceRoutine) (void)) {
    attachInterrupt(interrupt_pin, inInterruptServiceRoutine, FALLING);
}

// This will, but is prone to breakage when the Arduino internals change
void ACAN2517::begin_functional (void (* inInterruptServiceRoutine) (void *), void *arg)
{
    __attachInterruptFunctionalArg(interrupt_pin, inInterruptServiceRoutine, arg, FALLING, true);
}

void ACAN2517::isr(void)
{
    printf("fhtagn");
}

//===
// User code begin
//===

#define N_DRIVERS 3

ACAN2517 g_driver(23);  // Initializing a driver instance statically
ACAN2517 *drivers[N_DRIVERS];

void call_ACAN_isr(void *arg)
{
    ACAN2517 *driver = (ACAN2517 *)arg;
    driver->isr();
}

int main()
{
    g_driver.begin( []{g_driver.isr();} ); // No problem

    for (int i = 0; i < N_DRIVERS; i++)
    {
        drivers[i] = &ACAN2517(i);
        drivers[i]->begin( []{drivers[i]->isr();} );
        // ERROR
        // static void lambda []void ()->void::_FUN()
        // an enclosing-function local variable cannot be referenced in a lambda body unless it is in the capture list
    }

    for (int i = 0; i < N_DRIVERS; i++)
    {
        drivers[i] = &ACAN2517(i);
        drivers[i]->begin( [i]{drivers[i]->isr();} );
        // ERROR
        // no suitable conversion function from "lambda []void ()->void" to "void (*)()" exists
    }

    for (int i = 0; i < N_DRIVERS; i++)
    {
        drivers[i] = &ACAN2517(i);
        ACAN2517 *driver = drivers[i];
        drivers[i]->begin_functional( [driver]{driver->isr();}, driver);
        // Not sure how to get this to work in a lambda...
    }

    for (int i = 0; i < N_DRIVERS; i++)
    {
        drivers[i] = &ACAN2517(i);
        ACAN2517 *driver = drivers[i];
        drivers[i]->begin_functional( call_ACAN_isr, driver);
        // OK
    }
}

//===
// User code end
//===

// from esp32-hal-gpio.c
extern void __attachInterruptFunctionalArg(uint8_t pin, voidFuncPtrArg userFunc, void * arg, int intr_type, bool functional)
{
    // ...
}

// from Arduino `FunctionalInterrupt.cpp`
void attachInterrupt(uint8_t pin, std::function<void(void)> intRoutine, int mode)
{
    // use the local interrupt routine which takes the ArgStructure as argument
    __attachInterruptFunctionalArg (pin, (voidFuncPtrArg)interruptFunctional, new InterruptArgStructure{intRoutine}, mode, true);
}

void IRAM_ATTR interruptFunctional(void* arg)
{
    InterruptArgStructure* localArg = (InterruptArgStructure*)arg;
    if (localArg->interruptFunction)
    {
      localArg->interruptFunction();
    }
}
```

答:
I can't use a C++ member function here because of its implicit this argument.

Yes, that is exactly the problem and this can't be solved without extra code, if your API did not provide something what lets you store some additional data like the this pointer.

What you simply can do is:
Write your own wrapper and register the callback to the original handler. But that creates another indirection which increases the latency.

The other way is not as simple, but a bit less slow:
Write your own interrupt handler and callback registration. As you have the original sources of the arduino libs, you simply can replace the stuff around the attachInterrupt function.

Sorry, but there is no magic way to generate a data store for this without any additional software.


问:
Is there a way to simulate a click on an alert in JavaScript?
I have a page with an iframe whose source page is in a separate domain. From time to time, the source page generates an alert. When it does so, it stops what it is doing until the user clicks OK to the alert.

What I would like to do is programmatically click OK on this alert so the source page can get back to being useful. Is this possible?

答: I'm pretty sure it's not possible.</p>

OwnerDisplayName: moffdub

Body: I'm pretty sure it's not possible.


问:
django admin crashes when trying to update record but not when inserting a new one
I'm having a weird problem:

technical info for developemnt (production will be on linux/apache/Mysql)
macosx 2.6.6
python 2.6.1
django 1.3
mysql 5.1
and MySQLdb to connect the python to the MySQL...

I'm new at django as every one can see from past questions...but need to get really strong at it, really fast...the problem is that it is really not that smooth for me...

OK, for the question. I'm doing the django tutorial (not for fun, i need to learn it really fast because i need to develop a huge system with it).

I did all the the tutorial untill now and at the stage where i added the admin.

When i try to edit the poll record (if any one know the django 1.3 tutrial) the site crashes with the following exception:

Warning at /admin/polls/poll/2/
  Incorrect string value: '\xD7\xA9\xD7\x95\xD7\xA0...' for column 'change_message' at row 1

there is not problem with adding a new record to the same table, just to edit one....

if any one know's any thing about it....

```<code># Create your models here.
</code>```

class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

```<code>def __unicode__(self):
    return self.question

def was_published_today(self):
    return self.pub_date.date() == datetime.date.today()
</code>```

This is the model, and another this i saw, my MySQL DB is latin1 and not UTF-8...python is unicode....maybe that is the problem....

But still, i can't figure out why i can add records but can't edit them....isn't that the weird part?

答:
Open your mysql shell and run the following:

```<code>mysql> show variables like  'character\_set\_%';
</code>```

Are there any utf8 values from above?

Assuming it's a mysql issue, swap out your db settings to sqlite3:

```<code>DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'database.sqlite3',
        'USER': '',
        'PASSWORD': '',
        'HOST': '',
        'PORT': '',
    }
}
</code>```

Sync and try to input some data again.

Body:
I'm having a weird problem:

technical info for developemnt (production will be on linux/apache/Mysql)
macosx 2.6.6
python 2.6.1
django 1.3
mysql 5.1
and MySQLdb to connect the python to the MySQL...

I'm new at django as every one can see from past questions...but need to get really strong at it, really fast...the problem is that it is really not that smooth for me...

OK, for the question. I'm doing the django tutorial (not for fun, i need to learn it really fast because i need to develop a huge system with it).

I did all the the tutorial untill now and at the stage where i added the admin.

When i try to edit the poll record (if any one know the django 1.3 tutrial) the site crashes with the following exception:

Warning at /admin/polls/poll/2/
  Incorrect string value: '\xD7\xA9\xD7\x95\xD7\xA0...' for column 'change_message' at row 1

there is not problem with adding a new record to the same table, just to edit one....

if any one know's any thing about it....

# Create your models here.

class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

def __unicode__(self):
    return self.question

def was_published_today(self):
    return self.pub_date.date() == datetime.date.today()

This is the model, and another this i saw, my MySQL DB is latin1 and not UTF-8...python is unicode....maybe that is the problem....

But still, i can't figure out why i can add records but can't edit them....isn't that the weird part?

Body:
Open your mysql shell and run the following:

mysql> show variables like  'character\_set\_%';

Are there any utf8 values from above?

Assuming it's a mysql issue, swap out your db settings to sqlite3:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'database.sqlite3',
        'USER': '',
        'PASSWORD': '',
        'HOST': '',
        'PORT': '',
    }
}

Sync and try to input some data again.


问:
Update cell values where data is missing using function row-by-row
Suppose I have a DataFrame that looks something like this:

```<code>In [1]: df = pd.DataFrame([['name1', 2, 3, 'red'], ['name2', 4, 5, 'orange'], ['name3', 6, 7, '-'], ['name4', 8, 9, '-']], \
              columns=('names', 'data1', 'data2', 'category'))
        df

Out[1]:
     name   data1   data2   category
0   name1       2       3        red
1   name2       4       5     orange
2   name3       6       7          -
3   name4       8       9          -
</code>```

For some rows, data is missing in certain columns, denoted with '-':

What I want to do is fill in the missing data row-by-row.  There is a function that can identify the correct category for each row if it has the name passed into it.  I've used arbitrary terms to keep the question general and broad since the actual function pulls data from a database.  For example:

```<code>In [2]: import library as lib
        lib.get_category('name1')

Out[2]: ['red']
</code>```

How would I go about updating all missing values using the function row-by-row?  I've tried using df.loc to get all rows with missing data and passing in a series of the corresponding names into the function, but it only updates any missing values with the last value in the series.  I believe the core issue here is with iterating correctly.

The final expected output should look something like this (assuming that lib.get_category('name3') returns ['yellow'] and lib.get_category('name4') returns ['green']:

```<code>Out[1]:
     name   data1   data2   category
0   name1       2       3        red
1   name2       4       5      orange
2   name3       6       7      yellow
3   name4       8       9       green
</code>```

答:
Use can use Series.apply for that:

```<code>import library as lib
def func(name):
    return lib.get_category('name1')

df['category'] = df['name'].apply(func)
</code>```

The apply function func will take values from name column and return a value for the corresponding row. So edit your function accordingly.

Also note that the above code will replace the existing category value of the column. But as you mentioned that the category can be derived from the name, then it shouldn't be a problem.

Body:
Suppose I have a DataFrame that looks something like this:

In [1]: df = pd.DataFrame([['name1', 2, 3, 'red'], ['name2', 4, 5, 'orange'], ['name3', 6, 7, '-'], ['name4', 8, 9, '-']], \
              columns=('names', 'data1', 'data2', 'category'))
        df

Out[1]:
     name   data1   data2   category
0   name1       2       3        red
1   name2       4       5     orange
2   name3       6       7          -
3   name4       8       9          -

For some rows, data is missing in certain columns, denoted with '-':

What I want to do is fill in the missing data row-by-row.  There is a function that can identify the correct category for each row if it has the name passed into it.  I've used arbitrary terms to keep the question general and broad since the actual function pulls data from a database.  For example:

In [2]: import library as lib
        lib.get_category('name1')

Out[2]: ['red']

How would I go about updating all missing values using the function row-by-row?  I've tried using df.loc to get all rows with missing data and passing in a series of the corresponding names into the function, but it only updates any missing values with the last value in the series.  I believe the core issue here is with iterating correctly.

The final expected output should look something like this (assuming that lib.get_category('name3') returns ['yellow'] and lib.get_category('name4') returns ['green']:

Out[1]:
     name   data1   data2   category
0   name1       2       3        red
1   name2       4       5      orange
2   name3       6       7      yellow
3   name4       8       9       green

Body:
Use can use Series.apply for that:

import library as lib
def func(name):
    return lib.get_category('name1')

df['category'] = df['name'].apply(func)

The apply function func will take values from name column and return a value for the corresponding row. So edit your function accordingly.

Also note that the above code will replace the existing category value of the column. But as you mentioned that the category can be derived from the name, then it shouldn't be a problem.


问:
Popup resizing based on orientation
I have assignment to make a resizable popup based on the device orientation. I am instantiating it over the window like this.

```<code>let window = UIApplication.shared.keyWindow
let popOver = DeletePopUpViewController(nibName: "DeletePopUpViewController", bundle: nil)
popOver?.loadViewIfNeeded()
popOver?.view.frame = window!.frame
window?.addSubview(popOver!.view)
</code>```

I have added constraints in the IB, since my task for now wasn't to be resizable. Now I need to transfer my constraints to the code, and this is what bothers me. I was able to detect orientation change with observer like -

```<code>NotificationCenter.default.addObserver(self, selector: #selector(rotated), name: UIDevice.orientationDidChangeNotification, object: nil)

@objc private func rotated() {
    if UIDevice.current.orientation == UIDeviceOrientation.landscapeLeft || UIDevice.current.orientation == UIDeviceOrientation.landscapeRight {
         //code to implement constraints and size in landscape.
    }
    if UIDevice.current.orientation == UIDeviceOrientation.portrait || UIDevice.current.orientation == UIDeviceOrientation.portraitUpsideDown {
        //code to implement constraints and size in portrait.
    }
}
</code>```

Could you please give me some guidelines where to start from since I am fairly new to Swift and haven't done a lot of constraints in code. Also article would be helpful as well. Basically every help is welcome.

Thanks in advance.

答:
You would need this to your popview, that will automatically resize </p>

```<code>let popOver = DeletePopUpViewController(nibName:   "DeletePopUpViewController", bundle: nil)
        popOver?.loadViewIfNeeded()
popOver?.autoresizingMask = [.flexibleHeight, .flexibleWidth, .flexibleTopMargin, .flexibleRightMargin, .flexibleLeftMargin, .flexibleBottomMargin]
        popOver?.view.frame = window!.frame
        window?.addSubview(popOver!.view)
</code>```

Title: Popup resizing based on orientation

Body:
I have assignment to make a resizable popup based on the device orientation. I am instantiating it over the window like this.

let window = UIApplication.shared.keyWindow
let popOver = DeletePopUpViewController(nibName: "DeletePopUpViewController", bundle: nil)
popOver?.loadViewIfNeeded()
popOver?.view.frame = window!.frame
window?.addSubview(popOver!.view)

I have added constraints in the IB, since my task for now wasn't to be resizable. Now I need to transfer my constraints to the code, and this is what bothers me. I was able to detect orientation change with observer like -

NotificationCenter.default.addObserver(self, selector: #selector(rotated), name: UIDevice.orientationDidChangeNotification, object: nil)

@objc private func rotated() {
    if UIDevice.current.orientation == UIDeviceOrientation.landscapeLeft || UIDevice.current.orientation == UIDeviceOrientation.landscapeRight {
         //code to implement constraints and size in landscape.
    }
    if UIDevice.current.orientation == UIDeviceOrientation.portrait || UIDevice.current.orientation == UIDeviceOrientation.portraitUpsideDown {
        //code to implement constraints and size in portrait.
    }
}

Could you please give me some guidelines where to start from since I am fairly new to Swift and haven't done a lot of constraints in code. Also article would be helpful as well. Basically every help is welcome.

Thanks in advance.

Body:
You would need this to your popview, that will automatically resize

let popOver = DeletePopUpViewController(nibName:   "DeletePopUpViewController", bundle: nil)
        popOver?.loadViewIfNeeded()
popOver?.autoresizingMask = [.flexibleHeight, .flexibleWidth, .flexibleTopMargin, .flexibleRightMargin, .flexibleLeftMargin, .flexibleBottomMargin]
        popOver?.view.frame = window!.frame
        window?.addSubview(popOver!.view)


问:
How to set manual key value in array instead of index in multi-dimensional array in PHP?
I am using PHP 7.0 for my development. I got

```<code>Array
(
    [0] => Array
        (
            [lngCngSecUserId] => 0
            [sdtHolidayDate] => 1
        )

)
</code>```

as output by following code:

```<code><?php
    $tblActualHoliday = array();
    $arrColFields= array();
    $arrColFields["lngCngSecUserId"] = 0;
    $arrColFields["sdtHolidayDate"] = 1;
    array_push($tblActualHoliday,$arrColFields);
    print_r($tblActualHoliday);
?>
</code>```

but I want output as

```<code>Array
(
    [ColHeader] => Array
        (
            [lngCngSecUserId] => 0
            [sdtHolidayDate] => 1
        )

)
</code>```

How can I get it? I want ColHeader instead of 0 as index key.

答:
try using </p>

```<code>$tblActualHoliday['ColHeader'] = $arrColFields;
</code>```

Body:
I am using PHP 7.0 for my development. I got

Array
(
    [0] => Array
        (
            [lngCngSecUserId] => 0
            [sdtHolidayDate] => 1
        )

)

as output by following code:

<?php
    $tblActualHoliday = array();
    $arrColFields= array();
    $arrColFields["lngCngSecUserId"] = 0;
    $arrColFields["sdtHolidayDate"] = 1;
    array_push($tblActualHoliday,$arrColFields);
    print_r($tblActualHoliday);
?>

but I want output as

Array
(
    [ColHeader] => Array
        (
            [lngCngSecUserId] => 0
            [sdtHolidayDate] => 1
        )

)

How can I get it? I want ColHeader instead of 0 as index key.

Body:
try using

$tblActualHoliday['ColHeader'] = $arrColFields;


问:
Not able to import Python module
I am having a server and a testing module in falcon but I am not able to import the server module into the testing module when running the test cases.

This is my hierarchy:

```<code>project
   |
    --__init__.py
    --server.py
   |
     /tests
        |
          --__init__.py
          -- apitest.py
</code>```

This is my testing code

```<code>"""
Unit test for Ping api resource
"""

from falcon import testing
import pytest
import server

@pytest.fixture(scope='module')
def client():
    return testing.TestClient(server.api)

def test_get_message(client):
    result = client.simulate_get('/api/ping')
    assert result.status_code == 200
</code>```

But when i run it it shows:

```<code>Traceback:
apiTest.py:7: in <module>
    import server
E   ImportError: No module named 'server'
</code>```

What am I doing wrong here.

答:
Python checks for the module only in the current path of the script, which in your case is /tests. You would need to add /project to your path as well. The following code snippet should work:

```<code>import sys
sys.path.append("../")

import server
</code>```

Title: Not able to import Python module

Body:
I am having a server and a testing module in falcon but I am not able to import the server module into the testing module when running the test cases.

This is my hierarchy:

project
   |
    --__init__.py
    --server.py
   |
     /tests
        |
          --__init__.py
          -- apitest.py

This is my testing code

"""
Unit test for Ping api resource
"""

from falcon import testing
import pytest
import server

@pytest.fixture(scope='module')
def client():
    return testing.TestClient(server.api)

def test_get_message(client):
    result = client.simulate_get('/api/ping')
    assert result.status_code == 200

But when i run it it shows:

Traceback:
apiTest.py:7: in <module>
    import server
E   ImportError: No module named 'server'

What am I doing wrong here.

Body:
Python checks for the module only in the current path of the script, which in your case is /tests. You would need to add /project to your path as well. The following code snippet should work:

import sys
sys.path.append("../")

import server


问:
Passing data between Widgets without using Navigator?
I've some struggling with flutter.
I've two widget Details screen so in the first Details, I have a list and I want to send it to the second Screen without using navigator.

So if there is anyone who can help me I will be very thankful.

Details :

```<code> List<String> _instructions = [];

class Details extends StatefulWidget {
  @override
  _DetailsState createState() => new _DetailsState();
}

class _DetailsState extends State<Details> {
              Expanded(
                child: Container(
                  margin: EdgeInsets.all(3),
                  child: OutlineButton(
                    highlightElevation: 21,
                    color: Colors.white,
                    shape: StadiumBorder(),
                    textColor: Colors.lightBlue,
                    child: Text(
                      'ENVOYER',
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                        fontStyle: FontStyle.normal,
                        color: Colors.lightBlue,
                      ),
                    ),
                    borderSide: BorderSide(
                        color: Colors.lightBlue,
                        style: BorderStyle.solid,
                        width: 1),
                    onPressed: () {

                    },
                  ),
                ),
              ),
}}
</code>```

so what I want is that,when I press the button I will send my list to the next widget without using navigator.

答:
you can use the sharedpreferance which is the simple xml that belongs to the application. And this is how you can set it

```<code>Future<bool> setStringList(String key, List<String> value) =>
_setValue('StringList', key, value);

Future<bool> setStringList (
 String key,
 List<String> value
)
</code>```

For more info here is a link
And you can get your List by

```<code>List<String> getStringList(String key) {
  List<Object> list = _preferenceCache[key];
    if (list != null && list is! List<String>) {
      list = list.cast<String>().toList();
      _preferenceCache[key] = list;
    }
    return list;
}
</code>```

Also you can use sqflite

Body:
I've some struggling with flutter.
I've two widget Details screen so in the first Details, I have a list and I want to send it to the second Screen without using navigator.

So if there is anyone who can help me I will be very thankful.

Details :

 List<String> _instructions = [];

class Details extends StatefulWidget {
  @override
  _DetailsState createState() => new _DetailsState();
}

class _DetailsState extends State {
              Expanded(
                child: Container(
                  margin: EdgeInsets.all(3),
                  child: OutlineButton(
                    highlightElevation: 21,
                    color: Colors.white,
                    shape: StadiumBorder(),
                    textColor: Colors.lightBlue,
                    child: Text(
                      'ENVOYER',
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                        fontStyle: FontStyle.normal,
                        color: Colors.lightBlue,
                      ),
                    ),
                    borderSide: BorderSide(
                        color: Colors.lightBlue,
                        style: BorderStyle.solid,
                        width: 1),
                    onPressed: () {

                    },
                  ),
                ),
              ),
}}

so what I want is that,when I press the button I will send my list to the next widget without using navigator.

Body:
you can use the sharedpreferance which is the simple xml that belongs to the application. And this is how you can set it

Future<bool> setStringList(String key, List<String> value) =>
_setValue('StringList', key, value);

Future<bool> setStringList (
 String key,
 List<String> value
)

For more info here is a link
And you can get your List by

List<String> getStringList(String key) {
  List<Object> list = _preferenceCache[key];
    if (list != null && list is! List<String>) {
      list = list.cast<String>().toList();
      _preferenceCache[key] = list;
    }
    return list;
}

Also you can use sqflite


问:
How to route ASP.Net Core api return value to appropriate observable based on data type returned
I have created an ASP.NET Core Web Api backend with an Angular 7 frontend. One of the methods in the Api can return either an object or an array to an Angular service. How do I route to specific observable, based on the data type returned? I am a noob to Angular, so any kind assistance would be appreciated.</p>

```<code>Angular service call to Api:

getLinksFromSitus(situs: any) {
    this.http.post(this.baseUrl + 'getLinksFromSitus', situs).subscribe(data =>
    this.apiData.next(data)
    );
  }

Portion of Web Api that returns array if more than one APN present:

// if more than one item in list, get status information for each and return list to user to select appropriate apn
            if (propApn.Count > 1)
            {
                return Ok(propApn);
            }

Portion of same method to return object if only one value for APN:

var resultsModel = new Results
            {
                ArcGisLink = arcGisLink,
                HistInfoLink = histInfoLink,
                PropInfoLink = propInfoLink
            };

            return Ok(resultsModel);
</code>```

答:
You can't do this. Typescript can only type things based on static analysis at build time, what your describing would require Typescript to know the result of your API call at build time, which it doesn't do.

The best you can do is indicating that your API call can return both of your them:

```<code>public myApiFunc(req: MyRequestModel): Observable<any>
</code>```

But that will still require you to figure out which type returned at runtime.

Body:
I have created an ASP.NET Core Web Api backend with an Angular 7 frontend. One of the methods in the Api can return either an object or an array to an Angular service. How do I route to specific observable, based on the data type returned? I am a noob to Angular, so any kind assistance would be appreciated.

Angular service call to Api:

getLinksFromSitus(situs: any) {
    this.http.post(this.baseUrl + 'getLinksFromSitus', situs).subscribe(data =>
    this.apiData.next(data)
    );
  }

Portion of Web Api that returns array if more than one APN present:

// if more than one item in list, get status information for each and return list to user to select appropriate apn
            if (propApn.Count > 1)
            {
                return Ok(propApn);
            }

Portion of same method to return object if only one value for APN:

var resultsModel = new Results
            {
                ArcGisLink = arcGisLink,
                HistInfoLink = histInfoLink,
                PropInfoLink = propInfoLink
            };

            return Ok(resultsModel);

Body:
You can't do this. Typescript can only type things based on static analysis at build time, what your describing would require Typescript to know the result of your API call at build time, which it doesn't do.

The best you can do is indicating that your API call can return both of your them:

public myApiFunc(req: MyRequestModel): Observable<any>

But that will still require you to figure out which type returned at runtime.


问:
How to extract column name and column type from SQL in pyspark
The Spark SQL for Create query is like this -

```<code>CREATE [TEMPORARY] TABLE [IF NOT EXISTS] [db_name.]table_name
  [(col_name1 col_type1 [COMMENT col_comment1], ...)]
  USING datasource
  [OPTIONS (key1=val1, key2=val2, ...)]
  [PARTITIONED BY (col_name1, col_name2, ...)]
  [CLUSTERED BY (col_name3, col_name4, ...) INTO num_buckets BUCKETS]
  [LOCATION path]
  [COMMENT table_comment]
  [TBLPROPERTIES (key1=val1, key2=val2, ...)]
  [AS select_statement]
</code>```

where [x] means x is optional. I want the output as a tuple of following order if a CREATE sql query is passed -

```<code>(db_name, table_name, [(col1 name, col1 type), (col2 name, col2 type), ...])
</code>```

So is there any way to do that with pyspark sql functions or need help from regex?

If regex could anyone please help with the regular expression?

答:
It can be done by accessing the unofficial API through java_gateway:

```<code>plan = spark_session._jsparkSession.sessionState().sqlParser().parsePlan("CREATE TABLE foobar.test (foo INT, bar STRING) USING json")
print(f"database: {plan.tableDesc().identifier().database().get()}")
print(f"table: {plan.tableDesc().identifier().table()}")
# perhaps there is a better way to convert the schemas, using JSON string hack here
print(f"schema: {StructType.fromJson(json.loads(plan.tableDesc().schema().json()))}")
</code>```

Output:

```<code>database: foobar
table: test
schema: StructType(List(StructField(foo,IntegerType,true),StructField(bar,StringType,true)))
</code>```

Note that database().get() would fail if the database is not defined and the Scala option should be handled properly. Also, if you use CREATE TEMPORARY VIEW the accessors are named differently. The commands can be found here
https://github.com/apache/spark/blob/master/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/ddl.scala#L38
https://github.com/apache/spark/blob/master/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/ddl.scala#L58

Body:
The Spark SQL for Create query is like this -

CREATE [TEMPORARY] TABLE [IF NOT EXISTS] [db_name.]table_name
  [(col_name1 col_type1 [COMMENT col_comment1], ...)]
  USING datasource
  [OPTIONS (key1=val1, key2=val2, ...)]
  [PARTITIONED BY (col_name1, col_name2, ...)]
  [CLUSTERED BY (col_name3, col_name4, ...) INTO num_buckets BUCKETS]
  [LOCATION path]
  [COMMENT table_comment]
  [TBLPROPERTIES (key1=val1, key2=val2, ...)]
  [AS select_statement]

where [x] means x is optional. I want the output as a tuple of following order if a CREATE sql query is passed -

(db_name, table_name, [(col1 name, col1 type), (col2 name, col2 type), ...])

So is there any way to do that with pyspark sql functions or need help from regex?

If regex could anyone please help with the regular expression?

Body:
It can be done by accessing the unofficial API through java_gateway:

plan = spark_session._jsparkSession.sessionState().sqlParser().parsePlan("CREATE TABLE foobar.test (foo INT, bar STRING) USING json")
print(f"database: {plan.tableDesc().identifier().database().get()}")
print(f"table: {plan.tableDesc().identifier().table()}")
# perhaps there is a better way to convert the schemas, using JSON string hack here
print(f"schema: {StructType.fromJson(json.loads(plan.tableDesc().schema().json()))}")

Output:

database: foobar
table: test
schema: StructType(List(StructField(foo,IntegerType,true),StructField(bar,StringType,true)))

Note that database().get() would fail if the database is not defined and the Scala option should be handled properly. Also, if you use CREATE TEMPORARY VIEW the accessors are named differently. The commands can be found here
https://github.com/apache/spark/blob/master/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/ddl.scala#L38
https://github.com/apache/spark/blob/master/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/ddl.scala#L58


问:
Execution failed for task ':app:compileDebugJavaWithJavac'. > Could not find tools.jar
I get this error while executing

```<code>react-native run-android
</code>```

I have tried copying tools.jar file to JRE installation location, reinstalled JDK and JRE, checked environment variables for path. Nothing worked.

It returned with the below exception

```<code>info Starting JS server...
info Building and installing the app on the device (cd android && gradlew.bat app:installDebug)...
Starting a Gradle Daemon, 1 stopped Daemon could not be reused, use --status for details
> Task :app:compileDebugJavaWithJavac FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileDebugJavaWithJavac'.
> Could not find tools.jar. Please check that C:\Program Files (x86)\Java\jre1.8.0_211 contains a valid JDK installation

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
</code>```

答:
Add this to gradle.properties:

```<code>org.gradle.java.home=C:\\Program Files\\Java\\jdk1.8.0_91
</code>```

Don’t forget to use double back slashes. For example:

```<code>org.gradle.java.home=C:\\Program Files\\Java\\jdk1.8.0_144\
</code>```

Body:
I get this error while executing

react-native run-android

I have tried copying tools.jar file to JRE installation location, reinstalled JDK and JRE, checked environment variables for path. Nothing worked.

It returned with the below exception

info Starting JS server...
info Building and installing the app on the device (cd android && gradlew.bat app:installDebug)...
Starting a Gradle Daemon, 1 stopped Daemon could not be reused, use --status for details
> Task :app:compileDebugJavaWithJavac FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileDebugJavaWithJavac'.
> Could not find tools.jar. Please check that C:\Program Files (x86)\Java\jre1.8.0_211 contains a valid JDK installation

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Body:
Add this to gradle.properties:

org.gradle.java.home=C:\\Program Files\\Java\\jdk1.8.0_91

Don’t forget to use double back slashes. For example:

org.gradle.java.home=C:\\Program Files\\Java\\jdk1.8.0_144\


问:
How to get the class name with parent function in jquery
How can I get  'field_wrapper_1' class name while clicking the function addIncludeTextBox?

```<code><div class="field_wrapper_1">
        <span class="error php-error" id="php-error_includes" style="display: none"></span>
    <div class="row">
        <div class="col-md-11">
            <div class="form_group">
                <label class="form_label">Includes <span>*</span></label>
                <input class="form_input" name="includes[][]" id="includes" placeholder="Enter the details of fees includes" type="text">

            </div>
        </div>
        <div style="padding-top: 3.6%;" class="col-md-1">
            <a href="javascript:void(0);" class="add_button" onclick="addIncludeTextBox(this)" title="Add field"><i class="fa fa-plus" aria-hidden="true"></i></a>
        </div>
    </div>
</div>
</code>```

答:
You can do it like this:

```<code>$(obj).closest('[class^=field_wrapper]').attr("class")
</code>```

Combine .closest and .attr to get the class.

Optional you can also just use .closest('.field_wrapper_1')

Working demo

function addIncludeTextBox(obj){
  console.log($(obj).closest('[class^=field_wrapper]').attr("class"))
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="field_wrapper_1">
        <span class="error php-error" id="php-error_includes" style="display: none"></span>
    <div class="row">
        <div class="col-md-11">
            <div class="form_group">
                <label class="form_label">Includes <span>*</span></label>
                <input class="form_input" name="includes[][]" id="includes" placeholder="Enter the details of fees includes" type="text">

            </div>
        </div>
        <div style="padding-top: 3.6%;" class="col-md-1">
            <i class="fa fa-plus" aria-hidden="true">+</i>
        </div>
    </div>
</div></code>```

Body:
How can I get  'field_wrapper_1' class name while clicking the function addIncludeTextBox?

                Includes *
                <input class="form_input" name="includes[][]" id="includes" placeholder="Enter the details of fees includes" type="text">

Body:
You can do it like this:

$(obj).closest('[class^=field_wrapper]').attr("class")

Combine .closest and .attr to get the class.

Optional you can also just use .closest('.field_wrapper_1')

Working demo

function addIncludeTextBox(obj){
  console.log($(obj).closest('[class^=field_wrapper]').attr("class"))
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="field_wrapper_1">
        <span class="error php-error" id="php-error_includes" style="display: none"></span>
    <div class="row">
        <div class="col-md-11">
            <div class="form_group">
                <label class="form_label">Includes <span>*</span></label>
                <input class="form_input" name="includes[][]" id="includes" placeholder="Enter the details of fees includes" type="text">

            </div>
        </div>
        <div style="padding-top: 3.6%;" class="col-md-1">
            <a href="javascript:void(0);" class="add_button" onclick="addIncludeTextBox(this)" title="Add field"><i class="fa fa-plus" aria-hidden="true">+</i></a>
        </div>
    </div>
</div>


问:
Find first occurrence of a string after the first occurrence of another string with bash
I have an input file that looks like this and i want the first occurrence of words but only after the first occurrence of special

The numbers are only there so i know i got the right string

EDIT: I realized that it matters the strings have /'s

```<code>words/and/stuff #1
words/more #2
some/other/words #3
special/this #1
words/i/need/you/i.really.need.you #4
special/cool #2
words/random #5
</code>```

Im trying to find the first occurrence of "word" after i find the first occurrence of "special"

The output should be

```<code>words/i/need/you/i.really.need.you #4
</code>```

Ive tried the following

```<code>grep -m1 special file | grep -m1 words file

awk 'NR==1,/special/ && NR==1,/words/ {print $0}' file
</code>```

答:
Try:

```<code>$ awk '/special/{f=1} f && /words/ {print; exit}' file
words/i/need/you/i.really.need.you #4
</code>```

How it works:

/special/{f=1}

If the current line matches special then set variable f to 1

f && /words/ {print; exit}

If f is non-zero and the current line matches words, then print the current line and exit.

Words with slashes

If the word you want to match is not merely surrounded by slashes but includes them, the same code works.  It is just necessary to escape the slashes.  For example, if we are looking for the word words/i/need  after special:

```<code>$ awk '/special/{f=1} f && /words\/i\/need/ {print; exit}' file
words/i/need/you/i.really.need.you #4
</code>```

Body:
I have an input file that looks like this and i want the first occurrence of words but only after the first occurrence of special

The numbers are only there so i know i got the right string

EDIT: I realized that it matters the strings have /'s

words/and/stuff #1
words/more #2
some/other/words #3
special/this #1
words/i/need/you/i.really.need.you #4
special/cool #2
words/random #5

Im trying to find the first occurrence of "word" after i find the first occurrence of "special"

The output should be

words/i/need/you/i.really.need.you #4

Ive tried the following

grep -m1 special file | grep -m1 words file

awk 'NR==1,/special/ && NR==1,/words/ {print $0}' file

Body:
Try:

$ awk '/special/{f=1} f && /words/ {print; exit}' file
words/i/need/you/i.really.need.you #4

How it works:

/special/{f=1}

If the current line matches special then set variable f to 1

f && /words/ {print; exit}

If f is non-zero and the current line matches words, then print the current line and exit.

Words with slashes

If the word you want to match is not merely surrounded by slashes but includes them, the same code works.  It is just necessary to escape the slashes.  For example, if we are looking for the word words/i/need  after special:

$ awk '/special/{f=1} f && /words\/i\/need/ {print; exit}' file
words/i/need/you/i.really.need.you #4