问:
SSL Error while connecting through cellular connection
We have developed app iOS app using Xamarin.

It's working well in my test devices. My client is running into an issue of SSL error when he is using cellular connection.

Same app is running perfectly fine when he is using Wifi connection.

I am using Modern HTTP client to make web connection to use native APIs.

I have also tested app in IPV6 environment and it is also working fine.

Settings of App transport security are okay that I have verified. [If error is here then it should come all time irrespective of connection type.]

Issue is at remote end so, I dont have too much opportunity to experiment with various settings, debug and see what is causing this issue.
Having any clue or direction would be really helpful.

Note: Using third party online tools we have verified that our server is ATS compliant and using TLS 1.2

Stacktrace

```<code>System.Net.WebException: An SSL error has occurred and a secure connection to the server cannot be made. ---> Foundation.NSErrorException: Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made." UserInfo={NSErrorFailingURLStringKey=MYURL, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, _kCFStreamErrorDomainKey=3,

_NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <5C93BDAD-10CE-478B-9D72-5AA02AA84617>.<1>, _NSURLErrorRelatedURLSessionTaskErrorKey=(
    "LocalDataTask <5C93BDAD-10CE-478B-9D72-5AA02AA84617>.<1>"
), NSLocalizedDescription=An SSL error has occurred and a secure connection to the server cannot be made., NSErrorFailingURLKey=MYURL, NSUnderlyingError=0x282ea41e0 {Error Domain=kCFErrorDomainCFNetwork Code=-1200 "(null)"

UserInfo={_kCFStreamPropertySSLClientCertificateState=0, _kCFNetworkCFStreamSSLErrorOriginalValue=-9816, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9816}}, _kCFStreamErrorCodeKey=-9816}
</code>```

Update
We have updated server instance and that has made this issue random instead of all time producing. Removed HTTP client but still issue is there. We are neither getting steps or situation to produce it all time nor fix.

答:
Is the connection failing all the time or sometimes? If the latter, then the bottom could help.

I'm not sure if this is the case, might be worth checking. But, we also had a similar issue on some Cellular Providers. What happened was the SIM had no more data (hit the limit), so the Provider would initially allow connection but cut it in the middle. This would show as an SSL error.

In our case, we could not do anything about it since it was the Cellular Provider's specific implementation.

Body:
We have developed app iOS app using Xamarin.

It's working well in my test devices. My client is running into an issue of SSL error when he is using cellular connection.

Same app is running perfectly fine when he is using Wifi connection.

I am using Modern HTTP client to make web connection to use native APIs.

I have also tested app in IPV6 environment and it is also working fine.

Settings of App transport security are okay that I have verified. [If error is here then it should come all time irrespective of connection type.]

Issue is at remote end so, I dont have too much opportunity to experiment with various settings, debug and see what is causing this issue.
Having any clue or direction would be really helpful.

Note: Using third party online tools we have verified that our server is ATS compliant and using TLS 1.2

Stacktrace

System.Net.WebException: An SSL error has occurred and a secure connection to the server cannot be made. ---> Foundation.NSErrorException: Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made." UserInfo={NSErrorFailingURLStringKey=MYURL, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, _kCFStreamErrorDomainKey=3,

_NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <5C93BDAD-10CE-478B-9D72-5AA02AA84617>.<1>, _NSURLErrorRelatedURLSessionTaskErrorKey=(
    "LocalDataTask <5C93BDAD-10CE-478B-9D72-5AA02AA84617>.<1>"
), NSLocalizedDescription=An SSL error has occurred and a secure connection to the server cannot be made., NSErrorFailingURLKey=MYURL, NSUnderlyingError=0x282ea41e0 {Error Domain=kCFErrorDomainCFNetwork Code=-1200 "(null)"

UserInfo={_kCFStreamPropertySSLClientCertificateState=0, _kCFNetworkCFStreamSSLErrorOriginalValue=-9816, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9816}}, _kCFStreamErrorCodeKey=-9816}

Update
We have updated server instance and that has made this issue random instead of all time producing. Removed HTTP client but still issue is there. We are neither getting steps or situation to produce it all time nor fix.


来源: stackexchange

问:
Is it possible to make an iframe truly responsive using HTML & CSS
I have some simple code for an iframe. I want to display a webpage within a webpage seamlessly i.e no scroll bar

I have tried hidden overflow but I just cant seem to get it right

HTML

```<code> <iframe name="Framename"     src="https://website"
 width="100%" height="100%" frameborder="0" scrolling="auto"
 class="frame-
 area">
 </iframe>
</code>```

CSS

```<code>.frame-area {
  display: block;
  width: 100%;  /* RESPONSIVE WIDTH */
  max-width: 100%;
  height: 100%;
  overflow: hidden;  /* EDIT TO hidden FOR NO SCROLLBAR */
  border: #999999 1px solid;
  margin: 0px;
  padding: 0px;
  }
</code>```

The results I have is a full width page with only a small amount of height

I wish it to display full width and height and be fully responsive

答:
To make your iframe full height and width of your page use this css and iframe tag.

[EDIT] Due to your comment that there is a footer I have edited so it will work with a footer.  The footer disappeared because the iframe was 100% height and pushed it off at the bottom, which caused a scroll bar to appear. See below for the fix.

In the example code below, notice the CSS for the footer shows 30px height. So the iframe should be 30px less than the screen height to allow for the footer space. This is possible to do using height:calc(100% - 30px); of course substitute the actual height of your footer for 30px.

```<code>body {
    margin:0;
    padding:0;
}

.frame-area {
    position:absolute;
    height:calc(100% - 30px); /* example below if your footer is 30px in height */
    width:100%;
    border:none;
}

footer {
    position:absolute;
    bottom:0;
    height:30px; /* match this height in your iframe width calc value */
}
</code>```

And with the CSS above, you can simplify the iframe tag's formatting:

```<code><iframe name="Framename" src="https://website" class="frame-area"</iframe>
<footer>This is the footer</footer>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have some simple code for an iframe. I want to display a webpage within a webpage seamlessly i.e no scroll bar

I have tried hidden overflow but I just cant seem to get it right

HTML

CSS

.frame-area {
  display: block;
  width: 100%;  /* RESPONSIVE WIDTH */
  max-width: 100%;
  height: 100%;
  overflow: hidden;  /* EDIT TO hidden FOR NO SCROLLBAR */
  border: #999999 1px solid;
  margin: 0px;
  padding: 0px;
  }

The results I have is a full width page with only a small amount of height

I wish it to display full width and height and be fully responsive

Body:
To make your iframe full height and width of your page use this css and iframe tag.

[EDIT] Due to your comment that there is a footer I have edited so it will work with a footer.  The footer disappeared because the iframe was 100% height and pushed it off at the bottom, which caused a scroll bar to appear. See below for the fix.

In the example code below, notice the CSS for the footer shows 30px height. So the iframe should be 30px less than the screen height to allow for the footer space. This is possible to do using height:calc(100% - 30px); of course substitute the actual height of your footer for 30px.

body {
    margin:0;
    padding:0;
}

.frame-area {
    position:absolute;
    height:calc(100% - 30px); /* example below if your footer is 30px in height */
    width:100%;
    border:none;
}

footer {
    position:absolute;
    bottom:0;
    height:30px; /* match this height in your iframe width calc value */
}

And with the CSS above, you can simplify the iframe tag's formatting:

<iframe name="Framename" src="https://website" class="frame-area"</iframe>
<footer>This is the footer</footer>


问:
Remove / Override default styles from materialui components
I'm trying to change the background color of the menuitem popover. But I am unable to remove paddingtop and paddingBottom from menuitem. It's kind of annoying because some materialui components inherit styles from paper, list, menu and etc. Is there a clean and efficient way to work around this? For eg, using overrides in theme and etc.

I have experiment and I know it can be done using inline styles/classes but i do not wish to use that method. I've tried using ListProps={{disablePadding: true}}, MenuProps={{{disablePadding: true}}. But it Doesn't work.

```<code>       <FormControl className={classes.formControl}>
            <Select
            value={value.groupId}
            onChange={handleChange}
            MenuProps={{
                getContentAnchorEl: null,
                anchorOrigin: {
                  vertical: "bottom",
                  horizontal: "left",
                },
              }}
            classes={{
                icon:  isDarkMode ?  classes.iconLight :classes.icon,

            }}
            ListProps={{disablePadding: true}}
            inputProps={{
                name: 'groupId',
                id: 'group-machines',
              }}
            >

        {
            equipmentgroups.map(equipmentgroup =>
            <MenuItem
            style={isDarkMode ? {backgroundColor: theme.palette.primary.dark} :
            {backgroundColor: theme.palette.secondary.main}}
            className={classes.menuItemDisplay}
            value={equipmentgroup.groupId}
            key={equipmentgroup.groupId}
            >{equipmentgroup.groupName}</MenuItem>
            )

        }

            </Select>
        </FormControl>
</code>```

I'm still GETTING this when I'm inspecting the element.

```<code>        .MuiList-padding-370 {
             padding-top: 8px;
             padding-bottom: 8px;
         }
</code>```

答:
You need MenuProps={{ MenuListProps: { disablePadding: true } }}.

Here's a working example:

```<code>import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import InputLabel from "@material-ui/core/InputLabel";
import MenuItem from "@material-ui/core/MenuItem";
import FormControl from "@material-ui/core/FormControl";
import Select from "@material-ui/core/Select";

const useStyles = makeStyles(theme => ({
  root: {
    display: "flex",
    flexWrap: "wrap"
  },
  formControl: {
    margin: theme.spacing(1),
    minWidth: 120
  },
  selectEmpty: {
    marginTop: theme.spacing(2)
  }
}));

function SimpleSelect() {
  const classes = useStyles();
  const [values, setValues] = React.useState({
    age: "",
    name: "hai"
  });

  const inputLabel = React.useRef(null);

  function handleChange(event) {
    setValues(oldValues => ({
      ...oldValues,
      [event.target.name]: event.target.value
    }));
  }

  return (
    <form className={classes.root} autoComplete="off">
      <FormControl className={classes.formControl}>
        <InputLabel htmlFor="age-simple">Age</InputLabel>
        <Select
          value={values.age}
          onChange={handleChange}
          MenuProps={{ MenuListProps: { disablePadding: true } }}
          inputProps={{
            name: "age",
            id: "age-simple"
          }}
        >
          <MenuItem value="">
            <em>None</em>
          </MenuItem>
          <MenuItem value={10}>Ten</MenuItem>
          <MenuItem value={20}>Twenty</MenuItem>
          <MenuItem value={30}>Thirty</MenuItem>
        </Select>
      </FormControl>
    </form>
  );
}

export default SimpleSelect;
</code>```

Body:
I'm trying to change the background color of the menuitem popover. But I am unable to remove paddingtop and paddingBottom from menuitem. It's kind of annoying because some materialui components inherit styles from paper, list, menu and etc. Is there a clean and efficient way to work around this? For eg, using overrides in theme and etc.

I have experiment and I know it can be done using inline styles/classes but i do not wish to use that method. I've tried using ListProps={{disablePadding: true}}, MenuProps={{{disablePadding: true}}. But it Doesn't work.

       <FormControl className={classes.formControl}>
            <Select
            value={value.groupId}
            onChange={handleChange}
            MenuProps={{
                getContentAnchorEl: null,
                anchorOrigin: {
                  vertical: "bottom",
                  horizontal: "left",
                },
              }}
            classes={{
                icon:  isDarkMode ?  classes.iconLight :classes.icon,

            }}
            ListProps={{disablePadding: true}}
            inputProps={{
                name: 'groupId',
                id: 'group-machines',
              }}
            >

        {
            equipmentgroups.map(equipmentgroup =>
            <MenuItem
            style={isDarkMode ? {backgroundColor: theme.palette.primary.dark} :
            {backgroundColor: theme.palette.secondary.main}}
            className={classes.menuItemDisplay}
            value={equipmentgroup.groupId}
            key={equipmentgroup.groupId}
            >{equipmentgroup.groupName}</MenuItem>
            )

        }

            </Select>
        </FormControl>

I'm still GETTING this when I'm inspecting the element.

        .MuiList-padding-370 {
             padding-top: 8px;
             padding-bottom: 8px;
         }

Body:
You need MenuProps={{ MenuListProps: { disablePadding: true } }}.

Here's a working example:

import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import InputLabel from "@material-ui/core/InputLabel";
import MenuItem from "@material-ui/core/MenuItem";
import FormControl from "@material-ui/core/FormControl";
import Select from "@material-ui/core/Select";

const useStyles = makeStyles(theme => ({
  root: {
    display: "flex",
    flexWrap: "wrap"
  },
  formControl: {
    margin: theme.spacing(1),
    minWidth: 120
  },
  selectEmpty: {
    marginTop: theme.spacing(2)
  }
}));

function SimpleSelect() {
  const classes = useStyles();
  const [values, setValues] = React.useState({
    age: "",
    name: "hai"
  });

  const inputLabel = React.useRef(null);

  function handleChange(event) {
    setValues(oldValues => ({
      ...oldValues,
      [event.target.name]: event.target.value
    }));
  }

  return (
    <form className={classes.root} autoComplete="off">
      <FormControl className={classes.formControl}>
        <InputLabel htmlFor="age-simple">Age</InputLabel>
        <Select
          value={values.age}
          onChange={handleChange}
          MenuProps={{ MenuListProps: { disablePadding: true } }}
          inputProps={{
            name: "age",
            id: "age-simple"
          }}
        >
          <MenuItem value="">
            <em>None</em>
          </MenuItem>
          <MenuItem value={10}>Ten</MenuItem>
          <MenuItem value={20}>Twenty</MenuItem>
          <MenuItem value={30}>Thirty</MenuItem>
        </Select>
      </FormControl>
    </form>
  );
}

export default SimpleSelect;


问:
Mongoose expand default validation
I want to build "minLength" and "maxLength" in the mongoose schema validation rules, the current solution is:

```<code>var blogSchema = new Schema({
  title: { required: true, type: String }
});

blogSchema.path('title').validate(function(value) {
  if (value.length < 8 || value.length > 32) return next(new Error('length'));
});
</code>```

However I think this should be simplified by just adding custom schema rules like so:

```<code>var blogSchema = new Schema({
    title: {
        type: String,
        required: true,
        minLength: 8,
        maxLength: 32
    }
});
</code>```

How can I do this, is this even possible?

答:
Min and max have changed

```<code>var breakfastSchema = new Schema({
  eggs: {
    type: Number,
    min: [6, 'Too few eggs'],
    max: 12
  },
  bacon: {
    type: Number,
    required: [true, 'Why no bacon?']
  },
  drink: {
    type: String,
    enum: ['Coffee', 'Tea'],
    required: function() {
      return this.bacon > 3;
    }
  }
});
</code>```

https://mongoosejs.com/docs/validation.html

ContentLicense: CC BY-SA 3.0

Title: Mongoose expand default validation

Body:
I want to build "minLength" and "maxLength" in the mongoose schema validation rules, the current solution is:

var blogSchema = new Schema({
  title: { required: true, type: String }
});

blogSchema.path('title').validate(function(value) {
  if (value.length < 8 || value.length > 32) return next(new Error('length'));
});

However I think this should be simplified by just adding custom schema rules like so:

var blogSchema = new Schema({
    title: {
        type: String,
        required: true,
        minLength: 8,
        maxLength: 32
    }
});

How can I do this, is this even possible?

Body:
Min and max have changed

var breakfastSchema = new Schema({
  eggs: {
    type: Number,
    min: [6, 'Too few eggs'],
    max: 12
  },
  bacon: {
    type: Number,
    required: [true, 'Why no bacon?']
  },
  drink: {
    type: String,
    enum: ['Coffee', 'Tea'],
    required: function() {
      return this.bacon > 3;
    }
  }
});

https://mongoosejs.com/docs/validation.html


问:
Is it possible to include a Vue.js component from a URL?
We are designing a plugin architecture and are curious if there is a way to allow including 3rd party plug-ins as Vue components through a URL.

How can I import a vue file from a remote url? For example, I am attempting to follow Alex Jover Morales's approach to importing an async componentAsync vue.js components. In this approach, when a user clicks an "import plugin" button, a vue component should appear that is imported from a url. I published the vue component that I'd like to import on a github page.

The app cannot resolve the url. Why not? What must I do to fix this?
Import error

This is the code for my vue component that is doing the importing...

```<code>  <div v-if="showPlugin">
    <MassEmailerPlugin>
    </MassEmailerPlugin>
    <button @click.prevent="addPlugin">Add Plugin</button>
  </div>
</template>

<style>
</style>

<script>
export default {
  name: "Plugins",
  components: {
    MassEmailerPlugin: () => import('https://github.com/gideongrossmanHome/test-vuejs-plugin/blob/master/index.html')
  },

  data() {
    return {
      showPlugin: false
    }

  },

  methods: {
    addPlugin() {
      this.showPlugin = true;
      console.log("showing plugin");
    }
  }
};
</script>

</code>```

Here is the component that I am trying to import...

```<code><template>
    <div>
        Plugin from url
    </div>
</template>

<script>
export default {
    name: "MassEmailerPlugin"
}
</script>
</code>```

答:
There are a few issues with your current implementation:

The dynamic import statement that you have is to the GitHub.com web page, not the the code of the component itself. If you just want the code, you should click on the "Raw" button on the top right of the page that will give you an URL like this: https://raw.githubusercontent.com/gideongrossmanHome/test-vuejs-plugin/master/index.html.

Your Vue component should be declared as .vue and not .html.

Even then, you need to somehow compile the Vue component from the .vue file and register it inside the Vue instance for it to work.

What you can do if you REALLY want to use components from remote URLs is compile them to JS code using webpack and import that dynamically like in your code. However, allowing external JS to run on your own site is extremely dangerous and might open you up to XSS attacks.

Instead, if you are working on something that will be used internally, I suggest you have a look at being able to export your plugin as an npm package. That way, you can just import it if needed (still works with dynamic imports) and is packaged nicely as a working and reusable package. Here is the basic guide on how to do that but you might need more research: https://v2.vuejs.org/v2/cookbook/packaging-sfc-for-npm.html.

Body:
We are designing a plugin architecture and are curious if there is a way to allow including 3rd party plug-ins as Vue components through a URL.

How can I import a vue file from a remote url? For example, I am attempting to follow Alex Jover Morales's approach to importing an async componentAsync vue.js components. In this approach, when a user clicks an "import plugin" button, a vue component should appear that is imported from a url. I published the vue component that I'd like to import on a github page.

The app cannot resolve the url. Why not? What must I do to fix this?
Import error

This is the code for my vue component that is doing the importing...

    <MassEmailerPlugin>
    </MassEmailerPlugin>
    <button @click.prevent="addPlugin">Add Plugin</button>

</template>

Here is the component that I am trying to import...

<template>

        Plugin from url

</template>


问:
Embedding JAR Game into Wordpress website
Hello I am a designer not a programmer. My brother programmed a game for me a while ago with eclipse. It has the extension JAR. I want to embed this game into my wordpress website but I dont know how. I only have the .exe and the .jar file of the game but not the code.

How this can be possible without going into deep programming?

答:
"The best way to deploy a Java desktop application is using Java Web Start. A JWS app. can be launched from a link on a web site" [1]

[1] Andrew Thompson,  Publishing a .jar game online
Wiki: https://www.java.com/es/download/faq/java_webstart.xml


问:
how to capture returned values from php function parameter?
I am working with a wordpress plugin Gravity Forms.

The parameter $value var_dump result using gform_field_validation filter returns is  this...

```<code>string(4) "2434"
string(8) "Fantasma"
string(8) "fantasma"
string(13) "buzzlightyear"
array(1) {
  ["11.1"]=>
  string(0) ""
}
array(1) {
  ["15.1"]=>
  string(1) "1"
}
string(2) "10"
</code>```

I'm trying to capture the first string(4) "2434" but I have no idea how to target this.

Is there some php magic that can allow me to target this first string?

I know it's utter filth but Gravity Forms has left me choice to get this integer using their gform_field_validation filter.

Any ideas or thoughts would be much appreciated.

答:
I think you will find that your output is the gform_field_validation being looped over all of the inputs.

If you are wanting to get the $value for a given field you will need to check the $field object to match what you are after such as this:

```<code>add_filter('gform_field_validation', function($result, $value, $form, $field) {
    if ($field->name == 'postcode') {
        return $value;
    }
});
</code>```

This will then return the $value for the input named 'postcode' for example

Body:
I am working with a wordpress plugin Gravity Forms.

The parameter $value var_dump result using gform_field_validation filter returns is  this...

string(4) "2434"
string(8) "Fantasma"
string(8) "fantasma"
string(13) "buzzlightyear"
array(1) {
  ["11.1"]=>
  string(0) ""
}
array(1) {
  ["15.1"]=>
  string(1) "1"
}
string(2) "10"

I'm trying to capture the first string(4) "2434" but I have no idea how to target this.

Is there some php magic that can allow me to target this first string?

I know it's utter filth but Gravity Forms has left me choice to get this integer using their gform_field_validation filter.

Any ideas or thoughts would be much appreciated.

Body:
I think you will find that your output is the gform_field_validation being looped over all of the inputs.

If you are wanting to get the $value for a given field you will need to check the $field object to match what you are after such as this:

add_filter('gform_field_validation', function($result, $value, $form, $field) {
    if ($field->name == 'postcode') {
        return $value;
    }
});

This will then return the $value for the input named 'postcode' for example


问:
PlatformException (PlatformException(sign_in_failed, com.google.android.gms.common.api.ApiException: 12500: , null))
The line where is going to crash:

```<code>GoogleSignInAccount googleUser = await _googleSignIn.signIn();
</code>```

What have I tried:

I've generated my SH1 key with this command keytool -list -v \
-alias androiddebugkey -keystore ~/.android/debug.keystore

Adding SH1 encryption into console.firebase.google.com

Re-downloading the google-service.json

Copying the debug.keystore from .android to MyProject/android

Run in debug and release

Adding into android/build.gradle those lines:

classpath 'com.android.tools.build:gradle:3.2.1'

classpath 'com.google.gms:google-services:4.2.0'

Adding into android/app/build.gradle this lines:

implementation 'com.google.firebase:firebase-core:16.0.9' under dependencies

apply plugin: 'com.google.gms.google-services' on the end of the file.

Creating a file named release-signing.properties under my project folder with those lines in it.

storeFile=debug.keystore

keyAlias=androiddebugkey

storePassword=android

keyPassword=android

Also, I've searched in ALL StackOverflow question that I could found for this question, and none of them was useful for me.

My pubspec.yaml:

```<code>firebase_core: ^0.4.0+1
firebase_analytics: ^3.0.1

cloud_firestore: ^0.11.0+2

firebase_auth: ^0.11.1
google_sign_in: ^4.0.1+3

rxdart: ^0.22.0
</code>```

Auth class:

```<code>class AuthService {
  final GoogleSignIn _googleSignIn = GoogleSignIn();
  final FirebaseAuth _auth = FirebaseAuth.instance;
  final Firestore _db = Firestore.instance;

  Observable<FirebaseUser> user;
  Observable<Map<String, dynamic>> profile;
  PublishSubject loading = PublishSubject();

  AuthService() {
    user = Observable(_auth.onAuthStateChanged);
    profile = user.switchMap((FirebaseUser user) {
      if (user != null) {
        return _db
            .collection('user')
            .document(user.uid)
            .snapshots()
            .map((snap) => snap.data);
      } else {
        return Observable.just({});
      }
    });
  }

  Future<FirebaseUser> googleSignIn() async {
    loading.add(true);
    GoogleSignInAccount googleUser = await _googleSignIn.signIn();
    GoogleSignInAuthentication googleAuth = await googleUser.authentication;
    // FirebaseUser user = await _auth.signInWithGoogle(
        // accessToken: googleAuth.accessToken, idToken: googleAuth.idToken);
    final AuthCredential credential = GoogleAuthProvider.getCredential(
      accessToken: googleAuth.accessToken,
      idToken: googleAuth.idToken,
    );
    FirebaseUser user = await _auth.signInWithCredential(credential);
    updateUserData(user);
    print("Sign in" + user.displayName);

    loading.add(false);

    return user;
  }
}
</code>```

Main class:

```<code>void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  AuthService authService = AuthService();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blueGrey,
      ),
      home: Scaffold(
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              MaterialButton(
                child: Text("Log in with Google"),
                color: Colors.blueGrey,
                textColor: Colors.deepOrange,
                onPressed: () => authService.googleSignIn(),
              ),
              MaterialButton(
                child: Text("LogOut"),
                color: Colors.redAccent,
                textColor: Colors.purple,
                onPressed: () => authService.signOut(),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
</code>```

Now if any of you could point me in the right direction I would be very grateful.

Here are some stackoverflow links that I've tried already:

Google sign in doesn't work after release of flutter app

Flutter and google_sign_in plugin: PlatformException(sign_in_failed, com.google.android.gms.common.api.ApiException: 10: , null)

Google Sign In error 12500

I didn't have luck with any of them, please let me know what do you think and how can I fix it.

答:
The OP, @Mircea, specifically mentioned error 12500. This is how I overcame that error:

I have spent the last few days running into the same problem. I refactored my code dozens of times, added break points, reset the SHA-1, SHA-256 and did just about every other 'code' based solution I could find. I was constantly running into the error:

E/flutter (11935): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: PlatformException(sign_in_failed, com.google.android.gms.common.api.ApiException: 12500: , null)

I was losing my mind so I decided to start with fresh eyes and move slowly through solutions one more time. I noticed an obscure post nestled deep in a thread that mentioned something about having a support email. It was not until I added a said support email that things "magically" started working. I've attached a screenshot below of the Firebase settings for my project.

Body:
The line where is going to crash:

GoogleSignInAccount googleUser = await _googleSignIn.signIn();

What have I tried:

I've generated my SH1 key with this command keytool -list -v \
-alias androiddebugkey -keystore ~/.android/debug.keystore

Adding SH1 encryption into console.firebase.google.com

Re-downloading the google-service.json

Copying the debug.keystore from .android to MyProject/android

Run in debug and release

Adding into android/build.gradle those lines:

classpath 'com.android.tools.build:gradle:3.2.1'

classpath 'com.google.gms:google-services:4.2.0'

Adding into android/app/build.gradle this lines:

implementation 'com.google.firebase:firebase-core:16.0.9' under dependencies

apply plugin: 'com.google.gms.google-services' on the end of the file.

Creating a file named release-signing.properties under my project folder with those lines in it.

storeFile=debug.keystore

keyAlias=androiddebugkey

storePassword=android

keyPassword=android

Also, I've searched in ALL StackOverflow question that I could found for this question, and none of them was useful for me.

My pubspec.yaml:

firebase_core: ^0.4.0+1
firebase_analytics: ^3.0.1

cloud_firestore: ^0.11.0+2

firebase_auth: ^0.11.1
google_sign_in: ^4.0.1+3

rxdart: ^0.22.0

Auth class:

class AuthService {
  final GoogleSignIn _googleSignIn = GoogleSignIn();
  final FirebaseAuth _auth = FirebaseAuth.instance;
  final Firestore _db = Firestore.instance;

  Observable<FirebaseUser> user;
  Observable<Map<String, dynamic>> profile;
  PublishSubject loading = PublishSubject();

  AuthService() {
    user = Observable(_auth.onAuthStateChanged);
    profile = user.switchMap((FirebaseUser user) {
      if (user != null) {
        return _db
            .collection('user')
            .document(user.uid)
            .snapshots()
            .map((snap) => snap.data);
      } else {
        return Observable.just({});
      }
    });
  }

  Future<FirebaseUser> googleSignIn() async {
    loading.add(true);
    GoogleSignInAccount googleUser = await _googleSignIn.signIn();
    GoogleSignInAuthentication googleAuth = await googleUser.authentication;
    // FirebaseUser user = await _auth.signInWithGoogle(
        // accessToken: googleAuth.accessToken, idToken: googleAuth.idToken);
    final AuthCredential credential = GoogleAuthProvider.getCredential(
      accessToken: googleAuth.accessToken,
      idToken: googleAuth.idToken,
    );
    FirebaseUser user = await _auth.signInWithCredential(credential);
    updateUserData(user);
    print("Sign in" + user.displayName);

    loading.add(false);

    return user;
  }
}

Main class:

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  AuthService authService = AuthService();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blueGrey,
      ),
      home: Scaffold(
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              MaterialButton(
                child: Text("Log in with Google"),
                color: Colors.blueGrey,
                textColor: Colors.deepOrange,
                onPressed: () => authService.googleSignIn(),
              ),
              MaterialButton(
                child: Text("LogOut"),
                color: Colors.redAccent,
                textColor: Colors.purple,
                onPressed: () => authService.signOut(),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Now if any of you could point me in the right direction I would be very grateful.

Here are some stackoverflow links that I've tried already:

Google sign in doesn't work after release of flutter app

Flutter and google_sign_in plugin: PlatformException(sign_in_failed, com.google.android.gms.common.api.ApiException: 10: , null)

Google Sign In error 12500

I didn't have luck with any of them, please let me know what do you think and how can I fix it.


问:
Is this class Threadsafe?
Hi

Is the class below threadsafe?

```<code>class ImmutablePossiblyThreadsafeClass<K, V> {

    private final Map<K, V> map;

    public ImmutablePossiblyThreadsafeClass(final Map<K, V> map) {
        this.map = new HashMap<K, V>();

        for (Entry<K, V> entry : map.entrySet()) {
            this.map.put(entry.getKey(), entry.getValue());
        }
    }

    public V get(K key) {
        return this.map.get(key);
    }
}
</code>```

答:
Yes and no, for different values of "thread safe" (sorry for the obtuse answer). The construction is not thread safe, but once the constructor completes, and assuming that has happened correctly, it will be immutable and threadsafe.

During construction, the map paramater may be modified by another thread between the call to map.entrySet and the calls to entry.getKey and entry.getValue. From the javadoc of Map.entrySet. This can result in undefined behaviour.

From the java.util.Map javadoc for entrySet:

Returns a set view of the mappings
  contained in this map. Each element in
  the returned set is a Map.Entry. The
  set is backed by the map, so changes
  to the map are reflected in the set,
  and vice-versa. If the map is modified
  while an iteration over the set is in
  progress, the results of the iteration
  are undefined. The set supports
  element removal, which removes the
  corresponding mapping from the map,
  via the Iterator.remove, Set.remove,
  removeAll, retainAll and clear
  operations. It does not support the
  add or addAll operations.

So depending on who has a reference to the map, and how they manipulate it across threads, and how long it takes to copy the elements, you have undefined behaviour, and possibly different behaviour on different executions of the program.

There seems to be little you can do about ensuring it is constructed correctly from within this class (since, for example, ConcurrentHashMap has a similar problem). If the rest of your code can ensure that the constructor is given a thread-safe map, it will also be thread safe, but that's a wider scope than you asked.

Once, however, the constructor completes, and it is safely published[1] it will be immutable and thread safe - though only in a shallow way - if the keys or entries are mutable, this taints your class, making it neither immutable nor thread-safe. So, if your keys are String's and your values are Integer's, it will be immutable and thus thread safe. If however, your keys are a bean-like object with setters, and your values are other mutable collection types, then your class is not immutable. I tend to label this a "turtles all the way down" condition.

Essentially, your class could be immutable and thread safe, under certain, out-of-scope conditions not covered in your question.

[1] Your class will currently be published safely, but if, for instance, it becomes a nested class, or you pass the this reference to another method during the constructor, this can become an unsafe publication.

Title: Is this class Threadsafe?

Body:
Hi

Is the class below threadsafe?

class ImmutablePossiblyThreadsafeClass<K, V> {

    private final Map<K, V> map;

    public ImmutablePossiblyThreadsafeClass(final Map<K, V> map) {
        this.map = new HashMap<K, V>();

        for (Entry<K, V> entry : map.entrySet()) {
            this.map.put(entry.getKey(), entry.getValue());
        }
    }

    public V get(K key) {
        return this.map.get(key);
    }
}


问:
How to fix this error popping up on git while I am trying to push the project to a repo?
I am getting this error whenever I try to push my project to github:

error: failed to push some refs to
  'https://github.com/projectlink.git' hint: Updates were rejected
  because the remote contains work that you do not have locally. This is
  usually caused by another repository pushing to the same ref. You may
  want to first integrate the remote changes (e.g., 'git pull ...')
  before pushing again. See the 'Note about fast-forwards' in 'git push
  --help' for details.

I also tried to pull it and then push the code but I still get the same error. Please help!

答:
This could happen when

Your branch was updated by another dev, so you first have to pull and merge your working copy, then push another commit

You have rebased your branch, in this case all commits are re-written so you have to force-push your branch

You have amended your commit that was pushed before. Also in this case the history has changed and you have to force-push.

Anyway with the info you gave use it is very hard to help you, we need some context.


问:
can I split some text on python?
I want to split text on python and take some part, for example:

let the blue sky meet the blue sea

I want this for the result:

blue sky

this is my code

text = "let the blue sky meet the blue sea"
bluee = text.split("the", 1)[1]
print bluee
```

and the result from the code is
blue sky meet the blue sea

答:
Firstly, I think understanding split syntax will help us.

text.split(sep, max): (both sep and max are optional)

sep: the way you want to separate your text (default is space)

max: the maximum number of group you want to split (default is -1, it means all groups)

Here is in your case:

```<code> text = "let the blue sky meet the blue sea"
## short answer
print(' '.join(text.split()[2:4]))
</code>```

Explanation

We will do 3 steps

```<code># split it by default
list_word = text.split() # return ['let', 'the', 'blue', 'sky', 'meet', 'the', 'blue', 'sea']
# then we choose from 3rd to 4th elements
target_word = list_word[2:4] # return ['blue', 'sky']
# connect all element together with space
result = ' '.join(target_word)
print(result)
</code>```

Title: can I split some text on python?

Body:
I want to split text on python and take some part, for example:

let the blue sky meet the blue sea

I want this for the result:

blue sky

this is my code

text = "let the blue sky meet the blue sea"
bluee = text.split("the", 1)[1]
print bluee

and the result from the code is
blue sky meet the blue sea

Body:
Firstly, I think understanding split syntax will help us.

text.split(sep, max): (both sep and max are optional)

sep: the way you want to separate your text (default is space)

max: the maximum number of group you want to split (default is -1, it means all groups)

Here is in your case:

 text = "let the blue sky meet the blue sea"
## short answer
print(' '.join(text.split()[2:4]))

Explanation

We will do 3 steps

# split it by default
list_word = text.split() # return ['let', 'the', 'blue', 'sky', 'meet', 'the', 'blue', 'sea']
# then we choose from 3rd to 4th elements
target_word = list_word[2:4] # return ['blue', 'sky']
# connect all element together with space
result = ' '.join(target_word)
print(result)


问:
How to trigger an event in VSTS when there is a state change
Am looking to create a trigger (A json payload to a server) when an User Story is changed to closed/resolved state.

I am following this documentation

答:
How to trigger an event in VSTS when there is a state change

First, Azure Devops has capabilities to set up email notifications for the work Item. Check this the document Manage your notifications for some more details.

For you requirement, you could add a new subscription with following settings:

Then, if any User Story is changed to closed/resolved state, you will receive a e-mail about it.

Besides, if the trigger event is more than just a e-mail notification, like build. You could configure a service hook to send request to build related builds:

Check this thread for the details.

Hope this helps.


问:
Sprite Mask option doesn't appear
I want to create a Sprite Mask object. I follow the instructions on the unity docs:

To create a Sprite Mask select from the main menu GameObject > 2D Object > Sprite Mask

But the only option that appears is "Sprite". I am using the latest version of Unity (5.6.3p2)

答:
A Sprite Mask object is nothing but a gameobject with a SpriteMask script attached to it.
So create a empty game object and add a SpriteMask component to it through inspector manually

Title: Sprite Mask option doesn't appear


问:
Custom NavigationHandler cannot be cast to javax.faces.application.ConfigurableNavigationHandler
Following my previous question, i have a question about why is it this exception is being thrown if i use
 from primefaces after registering the RedirectNavigationHandler in the faces-config.xml. :

```<code>SEVERE: Error Rendering View[/TBrowse.xhtml]
java.lang.ClassCastException: my.package.RedirectNavigationHandler cannot be cast to javax.faces.application.ConfigurableNavigationHandler
        at org.primefaces.component.button.ButtonRenderer.findNavigationCase(ButtonRenderer.java:114)
        at org.primefaces.component.button.ButtonRenderer.buildOnclick(ButtonRenderer.java:90)
        at org.primefaces.component.button.ButtonRenderer.encodeMarkup(ButtonRenderer.java:56)
        at org.primefaces.component.button.ButtonRenderer.encodeEnd(ButtonRenderer.java:38)
        at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:883)
        at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1659)
        at javax.faces.render.Renderer.encodeChildren(Renderer.java:168)
        at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:853)
        at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeRecursive(HtmlBasicRenderer.java:304)
        at com.sun.faces.renderkit.html_basic.GridRenderer.renderRow(GridRenderer.java:185)
        at com.sun.faces.renderkit.html_basic.GridRenderer.encodeChildren(GridRenderer.java:129)
        at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:853)
        at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1652)
        at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1655)
        at org.primefaces.component.tabview.TabViewRenderer.encodeContents(TabViewRenderer.java:177)
        at org.primefaces.component.tabview.TabViewRenderer.encodeMarkup(TabViewRenderer.java:120)
        at org.primefaces.component.tabview.TabViewRenderer.encodeEnd(TabViewRenderer.java:61)
        at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:883)
        at org.primefaces.renderkit.CoreRenderer.renderChild(CoreRenderer.java:59)
        at org.primefaces.renderkit.CoreRenderer.renderChildren(CoreRenderer.java:43)
        at org.primefaces.component.panel.PanelRenderer.encodeContent(PanelRenderer.java:229)
        at org.primefaces.component.panel.PanelRenderer.encodeMarkup(PanelRenderer.java:152)
        at org.primefaces.component.panel.PanelRenderer.encodeEnd(PanelRenderer.java:75)
        at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:883)
        at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1659)
        at javax.faces.render.Renderer.encodeChildren(Renderer.java:168)
        at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:853)
        at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1652)
        at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1655)
        at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1655)
        at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:399)
        at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131)
        at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121)
        at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
        at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
        at javax.faces.webapp.FacesServlet.service(FacesServlet.java:313)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:306)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
        at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:541)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:383)
        at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:243)
        at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
        at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:288)
        at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
        at java.lang.Thread.run(Thread.java:662)
unhandled exception : java.lang.ClassCastException: my.package.RedirectNavigationHandler cannot be cast to javax.faces.application.ConfigurableNavigationHandler
cause exception : java.lang.ClassCastException: my.package.RedirectNavigationHandler cannot be cast to javax.faces.application.ConfigurableNavigationHandler, cause exception is BE : false
</code>```

Using
 is fine, but not so with
.

Here's my faces-config.xml excerpt :

```<code><application>
   ...
   <navigation-handler>id.co.sofcograha.RedirectNavigationHandler</navigation-handler>
   ...
</application>
</code>```

And the code :

```<code>import javax.faces.application.NavigationHandler;
import javax.faces.context.FacesContext;

public class RedirectNavigationHandler extends NavigationHandler {
    private NavigationHandler parent;

    public RedirectNavigationHandler(NavigationHandler parent) {
        this.parent = parent;
    }

    @Override
    public void handleNavigation(FacesContext context, String from, String outcome) {
        if (outcome != null && !outcome.trim().equals("") && !outcome.endsWith("?faces-redirect=true")) {
            System.out.println("adding faces redirect for " + outcome);
            outcome += "?faces-redirect=true";
        }

        parent.handleNavigation(context, from, outcome);
    }
}
</code>```

Here's the maven dependencies :

```<code><dependency>
    <groupId>com.sun.faces</groupId>
    <artifactId>jsf-api</artifactId>
    <version>2.0.4-b09</version>
    <scope>compile</scope>
</dependency>
<dependency>
    <groupId>com.sun.faces</groupId>
    <artifactId>jsf-impl</artifactId>
    <version>2.0.4-b09</version>
    <scope>compile</scope>
</dependency>
<dependency>
    <groupId>org.primefaces</groupId>
    <artifactId>primefaces</artifactId>
    <version>2.2.1</version>
</dependency>
</code>```

Any ideas on this matter ?

Thank you !

答:
For JSF 2.0 you're apparently supposed to extend ConfigurableNavigationHandler instead.

ConfigurableNavigationHandler extends the contract of NavigationHandler to allow runtime inspection of the NavigationCases that make up the rule-base for navigation. An implementation compliant with the version of the specification in which this class was introduced (or a later version) must make it so that its NavigationHandler is an extension of this class.

(emphasis mine) This is by the way not mentioned/warned in NavigationHandler javadoc, so I completely overlooked that bit in your previous question.

Here's how you could do it:

```<code>package com.example;

import java.util.Map;
import java.util.Set;

import javax.faces.application.ConfigurableNavigationHandler;
import javax.faces.application.NavigationCase;
import javax.faces.application.NavigationHandler;
import javax.faces.context.FacesContext;

public class RedirectNavigationHandler extends ConfigurableNavigationHandler {

    private NavigationHandler parent;

    public RedirectNavigationHandler(NavigationHandler parent) {
        this.parent = parent;
    }

    @Override
    public void handleNavigation(FacesContext context, String from, String outcome) {
        if (!outcome.endsWith("?faces-redirect=true")) {
            outcome += "?faces-redirect=true";
        }

        parent.handleNavigation(context, from, outcome);
    }

    @Override
    public NavigationCase getNavigationCase(FacesContext context, String fromAction, String outcome) {
        if (parent instanceof ConfigurableNavigationHandler) {
            return ((ConfigurableNavigationHandler) parent).getNavigationCase(context, fromAction, outcome);
        } else {
            return null;
        }
    }

    @Override
    public Map<String, Set<NavigationCase>> getNavigationCases() {
        if (parent instanceof ConfigurableNavigationHandler) {
            return ((ConfigurableNavigationHandler) parent).getNavigationCases();
        } else {
            return null;
        }
    }

}
</code>```

Body:
Following my previous question, i have a question about why is it this exception is being thrown if i use
 from primefaces after registering the RedirectNavigationHandler in the faces-config.xml. :

SEVERE: Error Rendering View[/TBrowse.xhtml]
java.lang.ClassCastException: my.package.RedirectNavigationHandler cannot be cast to javax.faces.application.ConfigurableNavigationHandler
        at org.primefaces.component.button.ButtonRenderer.findNavigationCase(ButtonRenderer.java:114)
        at org.primefaces.component.button.ButtonRenderer.buildOnclick(ButtonRenderer.java:90)
        at org.primefaces.component.button.ButtonRenderer.encodeMarkup(ButtonRenderer.java:56)
        at org.primefaces.component.button.ButtonRenderer.encodeEnd(ButtonRenderer.java:38)
        at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:883)
        at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1659)
        at javax.faces.render.Renderer.encodeChildren(Renderer.java:168)
        at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:853)
        at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeRecursive(HtmlBasicRenderer.java:304)
        at com.sun.faces.renderkit.html_basic.GridRenderer.renderRow(GridRenderer.java:185)
        at com.sun.faces.renderkit.html_basic.GridRenderer.encodeChildren(GridRenderer.java:129)
        at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:853)
        at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1652)
        at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1655)
        at org.primefaces.component.tabview.TabViewRenderer.encodeContents(TabViewRenderer.java:177)
        at org.primefaces.component.tabview.TabViewRenderer.encodeMarkup(TabViewRenderer.java:120)
        at org.primefaces.component.tabview.TabViewRenderer.encodeEnd(TabViewRenderer.java:61)
        at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:883)
        at org.primefaces.renderkit.CoreRenderer.renderChild(CoreRenderer.java:59)
        at org.primefaces.renderkit.CoreRenderer.renderChildren(CoreRenderer.java:43)
        at org.primefaces.component.panel.PanelRenderer.encodeContent(PanelRenderer.java:229)
        at org.primefaces.component.panel.PanelRenderer.encodeMarkup(PanelRenderer.java:152)
        at org.primefaces.component.panel.PanelRenderer.encodeEnd(PanelRenderer.java:75)
        at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:883)
        at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1659)
        at javax.faces.render.Renderer.encodeChildren(Renderer.java:168)
        at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:853)
        at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1652)
        at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1655)
        at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1655)
        at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:399)
        at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131)
        at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121)
        at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
        at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
        at javax.faces.webapp.FacesServlet.service(FacesServlet.java:313)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:306)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
        at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:541)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:383)
        at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:243)
        at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
        at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:288)
        at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
        at java.lang.Thread.run(Thread.java:662)
unhandled exception : java.lang.ClassCastException: my.package.RedirectNavigationHandler cannot be cast to javax.faces.application.ConfigurableNavigationHandler
cause exception : java.lang.ClassCastException: my.package.RedirectNavigationHandler cannot be cast to javax.faces.application.ConfigurableNavigationHandler, cause exception is BE : false

Using
 is fine, but not so with
.

Here's my faces-config.xml excerpt :

<application>
   ...
   <navigation-handler>id.co.sofcograha.RedirectNavigationHandler</navigation-handler>
   ...
</application>

And the code :

import javax.faces.application.NavigationHandler;
import javax.faces.context.FacesContext;

public class RedirectNavigationHandler extends NavigationHandler {
    private NavigationHandler parent;

    public RedirectNavigationHandler(NavigationHandler parent) {
        this.parent = parent;
    }

    @Override
    public void handleNavigation(FacesContext context, String from, String outcome) {
        if (outcome != null && !outcome.trim().equals("") && !outcome.endsWith("?faces-redirect=true")) {
            System.out.println("adding faces redirect for " + outcome);
            outcome += "?faces-redirect=true";
        }

        parent.handleNavigation(context, from, outcome);
    }
}

Here's the maven dependencies :

<dependency>
    <groupId>com.sun.faces</groupId>
    <artifactId>jsf-api</artifactId>
    <version>2.0.4-b09</version>
    <scope>compile</scope>
</dependency>
<dependency>
    <groupId>com.sun.faces</groupId>
    <artifactId>jsf-impl</artifactId>
    <version>2.0.4-b09</version>
    <scope>compile</scope>
</dependency>
<dependency>
    <groupId>org.primefaces</groupId>
    <artifactId>primefaces</artifactId>
    <version>2.2.1</version>
</dependency>

Any ideas on this matter ?

Thank you !

Body:
For JSF 2.0 you're apparently supposed to extend ConfigurableNavigationHandler instead.

ConfigurableNavigationHandler extends the contract of NavigationHandler to allow runtime inspection of the NavigationCases that make up the rule-base for navigation. An implementation compliant with the version of the specification in which this class was introduced (or a later version) must make it so that its NavigationHandler is an extension of this class.

(emphasis mine) This is by the way not mentioned/warned in NavigationHandler javadoc, so I completely overlooked that bit in your previous question.

Here's how you could do it:

package com.example;

import java.util.Map;
import java.util.Set;

import javax.faces.application.ConfigurableNavigationHandler;
import javax.faces.application.NavigationCase;
import javax.faces.application.NavigationHandler;
import javax.faces.context.FacesContext;

public class RedirectNavigationHandler extends ConfigurableNavigationHandler {

    private NavigationHandler parent;

    public RedirectNavigationHandler(NavigationHandler parent) {
        this.parent = parent;
    }

    @Override
    public void handleNavigation(FacesContext context, String from, String outcome) {
        if (!outcome.endsWith("?faces-redirect=true")) {
            outcome += "?faces-redirect=true";
        }

        parent.handleNavigation(context, from, outcome);
    }

    @Override
    public NavigationCase getNavigationCase(FacesContext context, String fromAction, String outcome) {
        if (parent instanceof ConfigurableNavigationHandler) {
            return ((ConfigurableNavigationHandler) parent).getNavigationCase(context, fromAction, outcome);
        } else {
            return null;
        }
    }

    @Override
    public Map<String, Set<NavigationCase>> getNavigationCases() {
        if (parent instanceof ConfigurableNavigationHandler) {
            return ((ConfigurableNavigationHandler) parent).getNavigationCases();
        } else {
            return null;
        }
    }

}


问:
Get memory usage per domain in Varnish
I have a Varnish cache on my server and have 5 different domains on it. I can get the total memory usage of Varnish with varnishstat and top. But I want to know how much memory is occupied for each domain in Varnish? </p>

答:
This won't give you the exact memory, rather the cache usage per domain.

Run varnishd, specifying multiple storages:

```<code>varnishd -s domain1=malloc,1G -s domain2=malloc,2G ...
</code>```

In your VCL, set the storage based on the domain:

```<code>sub vcl_backend_response {
    if (bereq.http.host == "domain1.example.com") {
        set beresp.storage = domain1;
    } else if {
        set beresp.storage = domain2;
    }
}
</code>```

then you can then use:

```<code>varnishstat  -1 -f SMA.domain1.g_bytes -f SMA.domain1.g_space
varnishstat  -1 -f SMA.domain2.g_bytes -f SMA.domain2.g_space
</code>```

to see how much space is used (g_bytes) and available (g_space) for each store.

Title: Get memory usage per domain in Varnish

Body:
This won't give you the exact memory, rather the cache usage per domain.

Run varnishd, specifying multiple storages:

varnishd -s domain1=malloc,1G -s domain2=malloc,2G ...

In your VCL, set the storage based on the domain:

sub vcl_backend_response {
    if (bereq.http.host == "domain1.example.com") {
        set beresp.storage = domain1;
    } else if {
        set beresp.storage = domain2;
    }
}

then you can then use:

varnishstat  -1 -f SMA.domain1.g_bytes -f SMA.domain1.g_space
varnishstat  -1 -f SMA.domain2.g_bytes -f SMA.domain2.g_space

to see how much space is used (g_bytes) and available (g_space) for each store.


问:
How can you make animate faster and faster?
How can you make animate faster and faster?

You can see by looking at the code. I've always had the animation effect at the same speed. But I wanted to have an animation effect that was slow at first, and then fast. How can you do that? I also want to know how to be slow at first, then faster in the middle, and then slower again.

```<code>$('.menu').animate({left : '0px'}, 500);
</code>```

答:
I think those animations effects you mentioned are as follows, you can cross check to see whether these are the intended effects.

ease-in: slow at the beginning, fast/abrupt at the end;

ease-out: fast/abrupt at the beginning, slow at the end;

ease-in-out:  the change happens slowly both at the beginning and end, and speeds up only in the middle somewhere.

More refers to
https://www.w3schools.com/cssref/css3_pr_animation-timing-function.asp or
https://css-tricks.com/ease-out-in-ease-in-out/

However, to use JQuery animate function, you can combine any of the effect above with jquery animate function like below
$('.menu').animate({left : '0px'}, 500,"easein"); , with tweaks of the syntax.

This will only works if you provide a plugin that provides the easing function. More on http://api.jquery.com/animate/ .

Body:
How can you make animate faster and faster?

You can see by looking at the code. I've always had the animation effect at the same speed. But I wanted to have an animation effect that was slow at first, and then fast. How can you do that? I also want to know how to be slow at first, then faster in the middle, and then slower again.

$('.menu').animate({left : '0px'}, 500);


问:
Room entities and domain models, should they be separate?
It seems to me that many guides on Room (and other ORMs for that matter) focus on the creation of Room entities and go on to use these as their domain models from then on. But what if my model needs its actual structure to perform some business logic?

For example, take the following class:

```<code>class Report(var id: Long, var patient: Patient, var surgery: Surgery) {

    var minimumAllowableBloodLoss: Double = 0.0
        get() = ((this.patient.hemoglobin - this.patient.minHemoglobin) / this.patient.hemoglobin) * this.patient.bloodVolume * this.patient.weight
        private set

    var hourlyDiuresis: Double = 0.0
         get() = this.patient.diuresisOutput / this.surgery.duration
         private set

    var urineOutput: Double = 0.0
        get() = this.hourlyDiuresis / this.patient.weight
        private set

    var intakeSupply: Double = 0.0
        get() = this.patient.totalIntake / this.patient.weight
        private set

    var finalFluidBalance: Double = 0.0
        get() = this.patient.totalIntake - this.patient.totalOutput
        private set

}
</code>```

If I made this class into a Room entity, I would've had to change my object references to just foreign keys, essentially making impossible doing the calculations I need from this class.

Naturally, my first instinct was to scrap that idea entirely and create a representation object, I believe it's also called a "persistance model":

```<code>@Entity
data class ReportRow(
    var patientId: Long, var surgeryId: Long) {
    @PrimaryKey(autoGenerate = true)
    var id: Int = 0
}
</code>```

But this also means I would have to create conversion methods from the persistence model to domain and vice versa.

This led me to believe maybe I'm missing something entirely or I'm just not using the tools correctly, is there a better alternative for these cases?

答:
They should be separate.

From the docs:

Entity: Represents a table within the database.

Despite the documention referring often to entities as "data models", many examples simplify the design and assume entities = business models.

However, such design is likely to violate Single Responsibility Principle and quickly falls apart once you wish to keep your data in the cloud, where data may be kept using some no-SQL solution.

Body:
It seems to me that many guides on Room (and other ORMs for that matter) focus on the creation of Room entities and go on to use these as their domain models from then on. But what if my model needs its actual structure to perform some business logic?

For example, take the following class:

class Report(var id: Long, var patient: Patient, var surgery: Surgery) {

    var minimumAllowableBloodLoss: Double = 0.0
        get() = ((this.patient.hemoglobin - this.patient.minHemoglobin) / this.patient.hemoglobin) * this.patient.bloodVolume * this.patient.weight
        private set

    var hourlyDiuresis: Double = 0.0
         get() = this.patient.diuresisOutput / this.surgery.duration
         private set

    var urineOutput: Double = 0.0
        get() = this.hourlyDiuresis / this.patient.weight
        private set

    var intakeSupply: Double = 0.0
        get() = this.patient.totalIntake / this.patient.weight
        private set

    var finalFluidBalance: Double = 0.0
        get() = this.patient.totalIntake - this.patient.totalOutput
        private set

}

If I made this class into a Room entity, I would've had to change my object references to just foreign keys, essentially making impossible doing the calculations I need from this class.

Naturally, my first instinct was to scrap that idea entirely and create a representation object, I believe it's also called a "persistance model":

@Entity
data class ReportRow(
    var patientId: Long, var surgeryId: Long) {
    @PrimaryKey(autoGenerate = true)
    var id: Int = 0
}

But this also means I would have to create conversion methods from the persistence model to domain and vice versa.

This led me to believe maybe I'm missing something entirely or I'm just not using the tools correctly, is there a better alternative for these cases?


问:
Continuous Integration for Flex 4
My team wants to set up a continuous integration server for a flex 4 project that we are developing. I have been evaluating various options and have some questions.

Really torn between Cruise Control and Hudson/Jenkins. Continuous integration servers for Flex shows at least two successful installations of Hudson for Flex.

Which source control should we use? I am personally inclined towards GIT, but looks like SVN has a lot more in-built support in both CC and Hudson.

In the worst case scenario, we might be forced to use VSS. What is the support for VSS like?

Regards,
Ravi.

答:
First, NEVER USE VSS.  Biggest POS out there.  Cruise Control/Hudson/Bamboo/Teamcity/etc are just build servers, but they need something to build with like Ant or Maven.  After the build is done, they normally deploy whatever was created to your place of choosing.  Any one of them will work just fine unless you have some very specific requirements.

As for version control, all of them can be used with the build server so it comes down to preference.  In a team environment, I prefer Git; however, it is a bit more 'complex' to use than subversion, so training might be involved.  But trust me, a lot less headaches merging with Git than subversion.

The most important part of the whole equation is your Ant or Maven build file.  I personally recommend using Maven over Ant since the dependency management is wonderful for larger projects.  You'll also want to take a look at the FlexMojos project to compile/test your Flex application.

Title: Continuous Integration for Flex 4


问:
how to append something to array correctly?
I'm going to make a custom cell, already have some labels on it, then I create a cell object and array, try to append that object to array then show on table, but after append, there's no content in my array's properties

I've tried to find out solutions but likely no one has these problems

//tableview implement

var recordCell : [RecordCell] = []
let note = RecordCell()

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.recordCell.count
    }

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = self.tableView.dequeueReusableCell(withIdentifier: "recordCell",for: indexPath) as! RecordCell
        let indexPath = indexPath.row

        cell.recordFileName?.text = self.recordCell[indexPath].recordFileName?.text
        cell.recordDate?.text = self.recordCell[indexPath].recordDate?.text
        cell.delegate = self
        cell.playBtn.tag = indexPath
        return cell
    }
```

<p>//append to array</p>

<pre class="lang-swift prettyprint-override"><code>let alertController = UIAlertController(title: "請輸入錄音名稱", message: "錄音名稱", preferredStyle: .alert)
        let okAction = UIAlertAction(title: "OK", style: .default) { (_) in
            var name : String = ""
            if(alertController.textFields![0].text == ""){
                name = "record"
            }else{
                name = alertController.textFields![0].text!
            }

            guard self.audioRecorder == nil else{return}
                self.recordNumber += 1
                self.record.isEnabled = false
                self.pause.isEnabled = true
                self.stop.isEnabled = true
                let destinationUrl = self.getFileURL().appendingPathComponent("\(name).m4a")

                let settings = [AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
                                AVSampleRateKey: 44100,
                                AVNumberOfChannelsKey: 2,
                                AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
                ]

                do {
                    self.audioRecorder = try AVAudioRecorder(url: destinationUrl, settings: settings)
                    self.audioRecorder.record()
                    self.note.recordFileName?.text = name
                    self.note.recordDate?.text = self.getDate()
                    self.recordCell.append(self.note)
                } catch {
                    print("Record error:", error.localizedDescription)
                }

        }
        let cancelAction = UIAlertAction(title: "取消", style: .cancel) { (_) in
            self.dismiss(animated: true, completion: {
                self.audioRecorder.stop()
            })
        }
        alertController.addTextField { (textField) in
            textField.placeholder = "輸入名稱"
            textField.keyboardType = .default
        }
        alertController.addAction(okAction)
        alertController.addAction(cancelAction)
        self.present(alertController,animated: true,completion: nil)
    }
</code>```

I expect when I append something, there's something in array

答:
I didnt see anything wrong.

Are you sure your code is called? Try giving a print() right before adding and see if it's called.

Maybe it's not called because of guard self.audioRecorder == nil else{return}

Body:
I'm going to make a custom cell, already have some labels on it, then I create a cell object and array, try to append that object to array then show on table, but after append, there's no content in my array's properties

I've tried to find out solutions but likely no one has these problems

//tableview implement

var recordCell : [RecordCell] = []
let note = RecordCell()

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.recordCell.count
    }

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = self.tableView.dequeueReusableCell(withIdentifier: "recordCell",for: indexPath) as! RecordCell
        let indexPath = indexPath.row

        cell.recordFileName?.text = self.recordCell[indexPath].recordFileName?.text
        cell.recordDate?.text = self.recordCell[indexPath].recordDate?.text
        cell.delegate = self
        cell.playBtn.tag = indexPath
        return cell
    }

//append to array

let alertController = UIAlertController(title: "請輸入錄音名稱", message: "錄音名稱", preferredStyle: .alert)
        let okAction = UIAlertAction(title: "OK", style: .default) { (_) in
            var name : String = ""
            if(alertController.textFields![0].text == ""){
                name = "record"
            }else{
                name = alertController.textFields![0].text!
            }

            guard self.audioRecorder == nil else{return}
                self.recordNumber += 1
                self.record.isEnabled = false
                self.pause.isEnabled = true
                self.stop.isEnabled = true
                let destinationUrl = self.getFileURL().appendingPathComponent("\(name).m4a")

                let settings = [AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
                                AVSampleRateKey: 44100,
                                AVNumberOfChannelsKey: 2,
                                AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
                ]

                do {
                    self.audioRecorder = try AVAudioRecorder(url: destinationUrl, settings: settings)
                    self.audioRecorder.record()
                    self.note.recordFileName?.text = name
                    self.note.recordDate?.text = self.getDate()
                    self.recordCell.append(self.note)
                } catch {
                    print("Record error:", error.localizedDescription)
                }

        }
        let cancelAction = UIAlertAction(title: "取消", style: .cancel) { (_) in
            self.dismiss(animated: true, completion: {
                self.audioRecorder.stop()
            })
        }
        alertController.addTextField { (textField) in
            textField.placeholder = "輸入名稱"
            textField.keyboardType = .default
        }
        alertController.addAction(okAction)
        alertController.addAction(cancelAction)
        self.present(alertController,animated: true,completion: nil)
    }

I expect when I append something, there's something in array


问:
Uncaught TypeError: Cannot read property 'teams' of undefined thrown - Karma
I'm running into this issues when I'm running ng test. It compiles fine, and ng build --prod runs fine. I don't even see those variables with that name just the Observables but the have a $ infront of the variables.

QUESTION UPDATED

"@types/jasmine": "2.8.9",
      "@types/jasminewd2": "~2.0.3",
      "@types/node": "~8.9.4",
      "codelyzer": "~4.2.1",
      "jasmine-core": "~2.99.1",
      "jasmine-spec-reporter": "~4.2.1",
      "karma": "~1.7.1",
      "karma-chrome-launcher": "~2.2.0",
      "karma-coverage-istanbul-reporter": "~2.0.0",
      "karma-jasmine": "~1.1.1",
      "karma-jasmine-html-reporter": "^0.2.2",
      "protractor": "^5.4.2",
      "ts-node": "~5.0.1",
      "tslint": "~5.9.1",
      "typescript": "~2.7.2"

Thi is all I see when Karma opens

My command line

PARENT TEST file

```<code>describe('MembersComponent', () => {
  let component: MembersComponent;
  let fixture: ComponentFixture<MembersComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        ReactiveFormsModule,
        HttpClientModule,
        RouterTestingModule,
        StoreModule.forRoot({})
      ],
      declarations: [MembersComponent, ModalComponent],
      providers: [{ provide: Store, useClass: StoreStub }]
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(MembersComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});
</code>```

CHILD TEST FILE

```<code>describe('ModalComponent', () => {
  let component: ModalComponent;
  let fixture: ComponentFixture<ModalComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ModalComponent],
      imports: [FormsModule, ReactiveFormsModule, StoreModule.forRoot({})],
      providers: [Store]
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ModalComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});
</code>```

答:
If you don't even want to test store then try below below:

```<code>import { of } from 'rxjs';

class StoreStub {
    select(val: any) {
        if (val === 'whatever action you have defined for RacingSelectors.selectMembers') {
            return of<Member[]>([
                {}, // create dummy member objects
            ]);
        } else if (val === 'whatever action you have defined for RacingSelectors.selectTeams') {
            return of<Team[]>([
                { firstName: '' },
                { lastName: '' },
                { jobTitle: '' },
                { team: '' },
                { status: '' }, // create dummy member objects
            ]);
        }
    }
    dispatch() {}
}

</code>```

and in spec file:

```<code>    TestBed.configureTestingModule({
      imports: [
        ReactiveFormsModule,
        HttpClientModule,
        RouterTestingModule,
        StoreModule.forRoot({})
      ],
      declarations: [MembersComponent, ModalComponent],
      providers: [{ provide: Store, useClass: StoreStub}]
    }).compileComponents();
  }));

  it('should create', () => {
        component.ngOnInit();
       expect(component).toBeTruthy();
   });

</code>```

Body:
I'm running into this issues when I'm running ng test. It compiles fine, and ng build --prod runs fine. I don't even see those variables with that name just the Observables but the have a $ infront of the variables.

QUESTION UPDATED

"@types/jasmine": "2.8.9",
      "@types/jasminewd2": "~2.0.3",
      "@types/node": "~8.9.4",
      "codelyzer": "~4.2.1",
      "jasmine-core": "~2.99.1",
      "jasmine-spec-reporter": "~4.2.1",
      "karma": "~1.7.1",
      "karma-chrome-launcher": "~2.2.0",
      "karma-coverage-istanbul-reporter": "~2.0.0",
      "karma-jasmine": "~1.1.1",
      "karma-jasmine-html-reporter": "^0.2.2",
      "protractor": "^5.4.2",
      "ts-node": "~5.0.1",
      "tslint": "~5.9.1",
      "typescript": "~2.7.2"

Thi is all I see when Karma opens

My command line

PARENT TEST file

describe('MembersComponent', () => {
  let component: MembersComponent;
  let fixture: ComponentFixture<MembersComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        ReactiveFormsModule,
        HttpClientModule,
        RouterTestingModule,
        StoreModule.forRoot({})
      ],
      declarations: [MembersComponent, ModalComponent],
      providers: [{ provide: Store, useClass: StoreStub }]
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(MembersComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

CHILD TEST FILE

describe('ModalComponent', () => {
  let component: ModalComponent;
  let fixture: ComponentFixture<ModalComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ModalComponent],
      imports: [FormsModule, ReactiveFormsModule, StoreModule.forRoot({})],
      providers: [Store]
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ModalComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

Body:
If you don't even want to test store then try below below:

import { of } from 'rxjs';

class StoreStub {
    select(val: any) {
        if (val === 'whatever action you have defined for RacingSelectors.selectMembers') {
            return of<Member[]>([
                {}, // create dummy member objects
            ]);
        } else if (val === 'whatever action you have defined for RacingSelectors.selectTeams') {
            return of<Team[]>([
                { firstName: '' },
                { lastName: '' },
                { jobTitle: '' },
                { team: '' },
                { status: '' }, // create dummy member objects
            ]);
        }
    }
    dispatch() {}
}

and in spec file:

    TestBed.configureTestingModule({
      imports: [
        ReactiveFormsModule,
        HttpClientModule,
        RouterTestingModule,
        StoreModule.forRoot({})
      ],
      declarations: [MembersComponent, ModalComponent],
      providers: [{ provide: Store, useClass: StoreStub}]
    }).compileComponents();
  }));

  it('should create', () => {
        component.ngOnInit();
       expect(component).toBeTruthy();
   });


问:
Rename a dictionary key
Is there a way to rename a dictionary key, without reassigning its value to a new name and removing the old name key; and without iterating through dict key/value?

In case of OrderedDict do the same, while keeping that key's position.

答:
Suppose you want to rename key k3 to k4:</p>

```<code>temp_dict = {'k1':'v1', 'k2':'v2', 'k3':'v3'}
temp_dict['k4']= temp_dict.pop('k3')
</code>```

Title: Rename a dictionary key

Body:
Suppose you want to rename key k3 to k4:

temp_dict = {'k1':'v1', 'k2':'v2', 'k3':'v3'}
temp_dict['k4']= temp_dict.pop('k3')


问:
IFormFile as a Nested ViewModel Property
I'm trying to use IFormFile as a property in a nested ViewModel. I am running into issues trying to bind the ViewModel to the controller action at runtime. The AJAX request stalls and never reaches the action.

This conceptual question is in reference to my specific issue at IFormFile property in .NET Core ViewModel causing stalled AJAX Request

ViewModel:

```<code>public class ProductViewModel
{
    public ProductDTO Product { get; set; }
    public List<ProductImageViewModel> Images { get; set; }
}
</code>```

Nested ViewModel:

```<code>public class ProductImageViewModel
{
    public ProductImageDTO ProductImage { get; set; }
    public IFormFile ImageFile { get; set; }
}
</code>```

Action:

```<code>[HttpPost]
public IActionResult SaveProduct([FromForm]ProductViewModel model)
{
    //save code
}
</code>```

I am wondering if an IFormFile Property needs to be a direct property of the ViewModel you are binding to a controller action.

The IFormFile Documentation does not seem to answer my question.

答:
The AJAX request stalls and never reaches the action.

This is a known issue that has been fixed in v3.0.0-preview and won't be merged into 2.2.x branch. See see #4802.

When posting a form with IList<Something> Something where Something has a property of IFormFile directly, it will result in an infinite loop. Because the model binding happens before the invocation of action method, you'll find that it never enters the action method. Also, if you inspect the Task Manager, you'll find that a crazy memory usage.

To walk around it, as suggested by @WahidBitar, simply create a wrapper on the IFormFile so that Something doesn't have a IFormFile directly .

As for your question itself, change your code as below:

```
    public class ProductViewModel
    {
        public ProductDTO Product { get; set; }
        public List<ProductImageViewModel> Images { get; set; }
    }

    public class ProductImageViewModel
    {
        public ProductImageDTO ProductImage { get; set; }
        // since this ProductImageViewModel will be <b>embedded as List<ProductImageViewModel></b>
        //     make sure it <b>has no IFormFile property directly</b>
        <strike>public IFormFile ImageFile { get; set; }</strike>
        <b>public IFormFileWrapper Image{ get; set; }</b>

        // a dummy wrapper
        <b>public class IFormFileWrapper</b>
        <b>{</b>
        <b>    public IFormFile File { get; set;}</b>
        <b>}</b>
    }
```

Now your client side should rename the field name as below:

```<code>Images[0].ProductImage.Prop1     # Your DTO prop's
Images[0].Image.File             # instead of Images[0].ImageFile
Images[0].ProductImage.Prop2     # Your DTO prop's
Images[1].Image.File             # instead of Images[1].ImageFile
...                              # other images
Product.Prop1
Product.Prop2
...                              # other props of Product
</code>```

A Working Demo :

Body:
I'm trying to use IFormFile as a property in a nested ViewModel. I am running into issues trying to bind the ViewModel to the controller action at runtime. The AJAX request stalls and never reaches the action.

This conceptual question is in reference to my specific issue at IFormFile property in .NET Core ViewModel causing stalled AJAX Request

ViewModel:

public class ProductViewModel
{
    public ProductDTO Product { get; set; }
    public List<ProductImageViewModel> Images { get; set; }
}

Nested ViewModel:

public class ProductImageViewModel
{
    public ProductImageDTO ProductImage { get; set; }
    public IFormFile ImageFile { get; set; }
}

Action:

[HttpPost]
public IActionResult SaveProduct([FromForm]ProductViewModel model)
{
    //save code
}

I am wondering if an IFormFile Property needs to be a direct property of the ViewModel you are binding to a controller action.

The IFormFile Documentation does not seem to answer my question.

Body:
The AJAX request stalls and never reaches the action.

This is a known issue that has been fixed in v3.0.0-preview and won't be merged into 2.2.x branch. See see #4802.

When posting a form with IList<Something> Something where Something has a property of IFormFile directly, it will result in an infinite loop. Because the model binding happens before the invocation of action method, you'll find that it never enters the action method. Also, if you inspect the Task Manager, you'll find that a crazy memory usage.

To walk around it, as suggested by @WahidBitar, simply create a wrapper on the IFormFile so that Something doesn't have a IFormFile directly .

As for your question itself, change your code as below:

    public class ProductViewModel
    {
        public ProductDTO Product { get; set; }
        public List<ProductImageViewModel> Images { get; set; }
    }

    public class ProductImageViewModel
    {
        public ProductImageDTO ProductImage { get; set; }
        // since this ProductImageViewModel will be embedded as List<ProductImageViewModel>
        //     make sure it has no IFormFile property directly
        public IFormFile ImageFile { get; set; }
        public IFormFileWrapper Image{ get; set; }

        // a dummy wrapper
        public class IFormFileWrapper
        {
            public IFormFile File { get; set;}
        }
    }

Now your client side should rename the field name as below:

Images[0].ProductImage.Prop1     # Your DTO prop's
Images[0].Image.File             # instead of Images[0].ImageFile
Images[0].ProductImage.Prop2     # Your DTO prop's
Images[1].Image.File             # instead of Images[1].ImageFile
...                              # other images
Product.Prop1
Product.Prop2
...                              # other props of Product

A Working Demo :


问:
Linux + Wordpress: how to fired a function from a Linux Cron job?
I created a Linux Cron Job like:

```<code>0 0 * * * home/www/wp-content/themes/my_theme/functions.php
</code>```

The file wp-content/themes/my_theme/functions.php has the function I need to call from the cron job: do_something().

As you can see the command is: home/www/wp-content/themes/my_theme/functions.php is wrong, since I need to specify my function: do_something().

My question is: how do chage the job command to execute the function  do_something().

答:
what you're missing is the PHP path, so this should work like this:

Find out your PHP binary by running this command:

whereis php
```
</blockquote>

<ul>
<li>Add your function on an empty .php file e.g. <code>cron-functions.php</code></li>
<li>Edit your cron so it looks like this:</li>
</ul>

<blockquote>
  <pre class="lang-sh prettyprint-override"><code># Replace "/path/to/php" bellow with your PHP binary location
0 0 * * * /path/to/php home/www/wp-content/themes/my_theme/cron-functions.php
</code>```

In case you are wondering you can also pass in arguments or function calls via cron like:

# Pass function name as an argument, in this case our sample do_something() function.
0 0 * * * /path/to/php home/www/wp-content/themes/my_theme/cron-functions.php do_something
```

And that should be pretty much it, some times you may have issues with user permissions to run cron or PHP CLI processes if that is the case and this does not work just let us know so we can help you.

Good luck.

Body:
I created a Linux Cron Job like:

0 0 * * * home/www/wp-content/themes/my_theme/functions.php

The file wp-content/themes/my_theme/functions.php has the function I need to call from the cron job: do_something().

As you can see the command is: home/www/wp-content/themes/my_theme/functions.php is wrong, since I need to specify my function: do_something().

My question is: how do chage the job command to execute the function  do_something().

Body:
what you're missing is the PHP path, so this should work like this:

Find out your PHP binary by running this command:

whereis php

Add your function on an empty .php file e.g. cron-functions.php

Edit your cron so it looks like this:

# Replace "/path/to/php" bellow with your PHP binary location
0 0 * * * /path/to/php home/www/wp-content/themes/my_theme/cron-functions.php

In case you are wondering you can also pass in arguments or function calls via cron like:

# Pass function name as an argument, in this case our sample do_something() function.
0 0 * * * /path/to/php home/www/wp-content/themes/my_theme/cron-functions.php do_something

And that should be pretty much it, some times you may have issues with user permissions to run cron or PHP CLI processes if that is the case and this does not work just let us know so we can help you.

Good luck.


问:
Overload typings with Python *args in super class
I have a simple base class as follows:

class Base:
  def get(self, *names: str) -> Any:
    # implementation not important
```

<p>I'm trying to define a subclass with stricter typing for some use cases:</p>

<pre class="lang-py prettyprint-override"><code>from typing import overload, Any
from typing_extensions import Literal

class Sub(Base):
  # mypy error here: Signature of "get" incompatible with supertype "Base"
  @overload
  def get(self, *names: Literal['Something']) -> Something: ...
  @overload
  def get(self, *names: Literal['Else']) -> Else: ...
  def get(self, *names: str) -> Any:
    return super().get(*names)
</code>```

However, I get the error noted in the code above: Signature of "get" incompatible with supertype "Base". I've tried other forms for the arguments of the overload for the Sub class, but all generate a similar error.

Is there anyway, for a base class method that takes *args, to provide specific overloads in a subclass when literal values are passed in?

答:
The correct typings for Sub should look something like this:

class Sub(Base):
  @overload
  def get(self, __name: Literal['Something']) -> Something: ...
  @overload
  def get(self, __name: Literal['Else']) -> Else: ...
  @overload
  def get(self, *names: str) -> Any: ...
  def get(self, *names: str) -> Any:
    return super().get(*names)
```

<p>There are a few changes here compared to the question.</p>

<p>1) We define an additional overload that has types identical to the implementation. The python docs for <code>@overload</code> explain this: "the [non-@overload-decorated definition] is used at runtime but should be ignored by a type checker."</p>

<p>2) Nobody would pass the same literal more than once, so we might as well change <code>*names</code> to <code>__name</code>. The leading underscores indicate that <code>name</code> is 'positional-only', as described in the mypy docs:</p>

<pre class="lang-py prettyprint-override"><code># An argument can be declared positional-only by giving it a name
# starting with two underscores:
def quux(__x: int) -> None:
    pass

quux(3)  # Fine
quux(__x=3)  # Error
</code>```

With the above changes, out Sub class typechecks as desired.

Body:
I have a simple base class as follows:

class Base:
  def get(self, *names: str) -> Any:
    # implementation not important

I'm trying to define a subclass with stricter typing for some use cases:

from typing import overload, Any
from typing_extensions import Literal

class Sub(Base):
  # mypy error here: Signature of "get" incompatible with supertype "Base"
  @overload
  def get(self, *names: Literal['Something']) -> Something: ...
  @overload
  def get(self, *names: Literal['Else']) -> Else: ...
  def get(self, *names: str) -> Any:
    return super().get(*names)

However, I get the error noted in the code above: Signature of "get" incompatible with supertype "Base". I've tried other forms for the arguments of the overload for the Sub class, but all generate a similar error.

Is there anyway, for a base class method that takes *args, to provide specific overloads in a subclass when literal values are passed in?

Body:
The correct typings for Sub should look something like this:

class Sub(Base):
  @overload
  def get(self, __name: Literal['Something']) -> Something: ...
  @overload
  def get(self, __name: Literal['Else']) -> Else: ...
  @overload
  def get(self, *names: str) -> Any: ...
  def get(self, *names: str) -> Any:
    return super().get(*names)

There are a few changes here compared to the question.

1) We define an additional overload that has types identical to the implementation. The python docs for @overload explain this: "the [non-@overload-decorated definition] is used at runtime but should be ignored by a type checker."

2) Nobody would pass the same literal more than once, so we might as well change *names to __name. The leading underscores indicate that name is 'positional-only', as described in the mypy docs:

# An argument can be declared positional-only by giving it a name
# starting with two underscores:
def quux(__x: int) -> None:
    pass

quux(3)  # Fine
quux(__x=3)  # Error

With the above changes, out Sub class typechecks as desired.


问:
AWS - Send Message to an SQS from a Lambda function inside a VPC
I have hosted a Lambda function using AWS Chalice inside a VPC since I want it to access a Serverless Aurora DB Instance. Now I also want this function to send_message() to an SQS.

I followed Tutorial: Sending a Message to an Amazon SQS Queue from Amazon Virtual Private Cloud and was able to call the SQS from inside my EC2. But even then I could not use my Lambda function to call the SQS.

It would be very helpful if someone could actually tell me how to do the whole thing manually rather than using the CloudFormation stack, or at least tell me how to get the SQS Endpoint working.

答:
It appears that your situation is:

An Amazon VPC with an Amazon Aurora database

An AWS Lambda function that wants to communicate with the Aurora database AND an Amazon SQS queue

An AWS Lambda function can be configured as:

Connected to a subnet in a VPC, or

Not connected to a VPC, which means it is connected to the Internet

If you wish to have an AWS Lambda function communicate with resources inside a VPC AND the Internet, then you will need:

The Lambda function connected to a private subnet

A NAT Gateway in a public subnet

An Internet Gateway connected to the public subnet (it is most probably already in your VPC)

Alternatively, you can use a VPC Endpoint for SQS, which allows the Lambda function to access SQS without going to the Internet. If you are wanting to connect to multiple service (eg S3, SNS, SQS), it is probably easier just to use a NAT Gateway rather than creating VPC Endpoints for each service.