问:
POST data request on server via react native?
Basically what i'm trying to do is, on click of login button it should take my input data and check whether the data is valid for authentication and send back response to user and display on UI. After authentication it should be redirected to home screen. I tried using fetch but it's not working. Below is the code:</p>

```<code>import React, { Component } from 'react';
import {
  AppRegistry,
  Text,
  Image,
  View,
  StyleSheet,
  TextInput,
  Linking,
  Alert,
  Navigator
} from 'react-native';
import { Button } from 'react-native-elements';
import t from 'tcomb-form-native';

const Form = t.form.Form;

// here we are: define your domain model
const Email = t.subtype(t.Str, (email) => {
  const reg = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  return reg.test(email);
});

const LoginFields = t.struct({
  username: Email,  // a required string
  password: t.String, // a required string
});

const options = {
  fields: {
    password: {
      type: 'password',
      placeholder: 'Password',
      error: 'Password cannot be empty'
    },
    username: {
      placeholder: 'e.g: abc@gmail.com',
      error: 'Insert a valid email'
    }
  }
}; // optional rendering options (see documentation)

export class ChildComponent extends Component {
  render() {
    if(this.props.result) {
      var res = this.props.result.map((item, i) => {
        return(
          <Text key={i}>{item.useremail}</Text>
        )
      })
    }
    return (
      <View>
        {res}
      </View>
    )
  }
}

export default class Login extends Component {
  constructor(props) {
    super(props);
    this.state = {
      buttonState: true,
      value: {}
    }
  }

  _onSubmit() {
    const value = this.refs.form.getValue();
     if (value) { // if validation fails, value will be null
       console.log(value);
        // value here is an instance of LoginFields
     }
     componentDidMount() {
       fetch('http://192.168.100.160:6016/admin/login', {
     method: 'POST',
     headers: {
       'Accept': 'application/x-www-form-urlencoded',
       'Content-Type': 'application/x-www-form-urlencoded',
     },
     body: JSON.stringify({
       useremail: 'kirti@pws.com',
       userpassword: '1234',
     })
   })
   .then((response) => response.json())
   .then((responseJson) => {
     this.setState ({
       data: responseJson.admin/login
     })
   })
     }

     this.props.navigator.push({
       id: 'Home'
     });
  }

  onChange = () => {
    const value = this.refs.form.getValue();
    if(value) {
      this.setState({
        value,
        buttonState: false
      });
    }
  }
  render() {
    return (
      <View style={styles.container}>
        <View style={styles.header}>
        </View>
        <View style={styles.content}>
          <Text style={styles.contentHeader}>
            Pateast Login
          </Text>
          <View style={styles.loginFormContent}>
            <Form
              ref="form"
              type={LoginFields}
              options={options}
              value={this.state.value}
              onChange={this.onChange}
            />
              <Text style={{color: 'blue', marginBottom: 10}}
                onPress={() => Linking.openURL('https://www.google.co.in')}>
                Forgot Password?
              </Text>
              <Button
                  raise
                  icon={{name: 'key', type: 'octicon'}}
                  onPress={this._onSubmit.bind(this)}
                  title="Login"
                  disabled={this.state.buttonState}
                  accessibilityLabel="Ok, Great!"
                />
            </View>
        </View>
        <View style={styles.footer}>
        </View>
        <ChildComponent status={this.state.status} result={this.state.data} />
      </View>
    );
  }
}

const styles = StyleSheet.create(
  {
    container: {
      flex: 1
    },
    contentHeader: {
      // fontFamily: 'sans-serif-condensed',
      fontWeight: 'bold',
      fontSize: 40,
      alignSelf: 'center',
      marginBottom: 30
    },
    header : {
      flex: 0.5,
      backgroundColor: '#008080'
    },
    content: {
      flex: 10,
      backgroundColor: '#f8f8ff',
      justifyContent: 'center'
    },
    loginFormContent: {
      marginHorizontal: 20
    },
    footer: {
      flex: 0.5,
      backgroundColor: '#008080'
    },
    loginText: {
      fontSize: 20,
      marginBottom: 10
    },
    inputFields: {
      fontSize: 20,
      borderStyle: 'solid',
      borderColor: '#000000',
      borderRadius: 30,
      marginBottom: 10
    }
  }
);
</code>```

答:
you were just one step away from your goal. The only thing you have to change is your body object in your post request. This object has to be a FormData https://developer.mozilla.org/de/docs/Web/API/FormData

Try to set the body like this:

```<code>let data = new FormData();
data.append("useremail", 'kirti@pws.com');
data.append("userpassword", '1234');
</code>```

After that your fetch request should look like this:

```<code>fetch('http://192.168.100.160:6016/admin/login', {
     method: 'POST',
     headers: {
       'Accept': 'application/x-www-form-urlencoded',
       'Content-Type': 'application/x-www-form-urlencoded',
     },
    body: data
}
...
</code>```

Body:
Basically what i'm trying to do is, on click of login button it should take my input data and check whether the data is valid for authentication and send back response to user and display on UI. After authentication it should be redirected to home screen. I tried using fetch but it's not working. Below is the code:

import React, { Component } from 'react';
import {
  AppRegistry,
  Text,
  Image,
  View,
  StyleSheet,
  TextInput,
  Linking,
  Alert,
  Navigator
} from 'react-native';
import { Button } from 'react-native-elements';
import t from 'tcomb-form-native';

const Form = t.form.Form;

// here we are: define your domain model
const Email = t.subtype(t.Str, (email) => {
  const reg = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  return reg.test(email);
});

const LoginFields = t.struct({
  username: Email,  // a required string
  password: t.String, // a required string
});

const options = {
  fields: {
    password: {
      type: 'password',
      placeholder: 'Password',
      error: 'Password cannot be empty'
    },
    username: {
      placeholder: 'e.g: abc@gmail.com',
      error: 'Insert a valid email'
    }
  }
}; // optional rendering options (see documentation)

export class ChildComponent extends Component {
  render() {
    if(this.props.result) {
      var res = this.props.result.map((item, i) => {
        return(
          <Text key={i}>{item.useremail}</Text>
        )
      })
    }
    return (
      <View>
        {res}
      </View>
    )
  }
}

export default class Login extends Component {
  constructor(props) {
    super(props);
    this.state = {
      buttonState: true,
      value: {}
    }
  }

  _onSubmit() {
    const value = this.refs.form.getValue();
     if (value) { // if validation fails, value will be null
       console.log(value);
        // value here is an instance of LoginFields
     }
     componentDidMount() {
       fetch('http://192.168.100.160:6016/admin/login', {
     method: 'POST',
     headers: {
       'Accept': 'application/x-www-form-urlencoded',
       'Content-Type': 'application/x-www-form-urlencoded',
     },
     body: JSON.stringify({
       useremail: 'kirti@pws.com',
       userpassword: '1234',
     })
   })
   .then((response) => response.json())
   .then((responseJson) => {
     this.setState ({
       data: responseJson.admin/login
     })
   })
     }

     this.props.navigator.push({
       id: 'Home'
     });
  }

  onChange = () => {
    const value = this.refs.form.getValue();
    if(value) {
      this.setState({
        value,
        buttonState: false
      });
    }
  }
  render() {
    return (
      <View style={styles.container}>
        <View style={styles.header}>
        </View>
        <View style={styles.content}>
          <Text style={styles.contentHeader}>
            Pateast Login
          </Text>
          <View style={styles.loginFormContent}>
            <Form
              ref="form"
              type={LoginFields}
              options={options}
              value={this.state.value}
              onChange={this.onChange}
            />
              <Text style={{color: 'blue', marginBottom: 10}}
                onPress={() => Linking.openURL('https://www.google.co.in')}>
                Forgot Password?
              </Text>
              <Button
                  raise
                  icon={{name: 'key', type: 'octicon'}}
                  onPress={this._onSubmit.bind(this)}
                  title="Login"
                  disabled={this.state.buttonState}
                  accessibilityLabel="Ok, Great!"
                />
            </View>
        </View>
        <View style={styles.footer}>
        </View>
        <ChildComponent status={this.state.status} result={this.state.data} />
      </View>
    );
  }
}

const styles = StyleSheet.create(
  {
    container: {
      flex: 1
    },
    contentHeader: {
      // fontFamily: 'sans-serif-condensed',
      fontWeight: 'bold',
      fontSize: 40,
      alignSelf: 'center',
      marginBottom: 30
    },
    header : {
      flex: 0.5,
      backgroundColor: '#008080'
    },
    content: {
      flex: 10,
      backgroundColor: '#f8f8ff',
      justifyContent: 'center'
    },
    loginFormContent: {
      marginHorizontal: 20
    },
    footer: {
      flex: 0.5,
      backgroundColor: '#008080'
    },
    loginText: {
      fontSize: 20,
      marginBottom: 10
    },
    inputFields: {
      fontSize: 20,
      borderStyle: 'solid',
      borderColor: '#000000',
      borderRadius: 30,
      marginBottom: 10
    }
  }
);

Body:
you were just one step away from your goal. The only thing you have to change is your body object in your post request. This object has to be a FormData https://developer.mozilla.org/de/docs/Web/API/FormData

Try to set the body like this:

let data = new FormData();
data.append("useremail", 'kirti@pws.com');
data.append("userpassword", '1234');

After that your fetch request should look like this:

fetch('http://192.168.100.160:6016/admin/login', {
     method: 'POST',
     headers: {
       'Accept': 'application/x-www-form-urlencoded',
       'Content-Type': 'application/x-www-form-urlencoded',
     },
    body: data
}
...


来源: stackexchange

问:
Using the text replaced in the replace text
I'm using the version 7.3.3 of Notepad++.

I have this list of numbers to 1.000.000.

```<code>1
2
3
4
5
6
7
8
9
10
11
12
13
14
</code>```

I want to add XML tags to these numbers like this:

```<code><SerialNumber>
    <SN>1</SN>
</SerialNumber>
<SerialNumber>
    <SN>2</SN>
</SerialNumber>
<SerialNumber>
    <SN>3</SN>
</SerialNumber>
<SerialNumber>
    <SN>4</SN>
</SerialNumber>
</code>```

So I need a regular expression to find a number ended with a \n\r, and use the number I've found with the regular expression in the text that I'm going to add.

Do you know to do that in Notepad++?

I have tried with \d{*} but it is not a valid regular expression.

答:
Open the "Replace" menu (Search > Replace...).

And set like that :

- Find what: (\d+)[(\r)?\n]

- Replace with : <SerialNumber>\r\n    <SN>$1</SN>\r\n</SerialNumber>

- Check : Search mode -> Regular expression

Then press Replace All. To even match the last number, add an empty line at the end of your file.

I  hope it helps.

ContentLicense: CC BY-SA 3.0

Body:
I'm using the version 7.3.3 of Notepad++.

I have this list of numbers to 1.000.000.

1
2
3
4
5
6
7
8
9
10
11
12
13
14

I want to add XML tags to these numbers like this:

<SerialNumber>
    <SN>1</SN>
</SerialNumber>
<SerialNumber>
    <SN>2</SN>
</SerialNumber>
<SerialNumber>
    <SN>3</SN>
</SerialNumber>
<SerialNumber>
    <SN>4</SN>
</SerialNumber>

So I need a regular expression to find a number ended with a \n\r, and use the number I've found with the regular expression in the text that I'm going to add.

Do you know to do that in Notepad++?

I have tried with \d{*} but it is not a valid regular expression.


问:
UNMET PEER DEPENDENCY react
I have errors when want to install npm install node-saas

├── UNMET PEER DEPENDENCY react@15.4.2

└── UNMET PEER DEPENDENCY react-dom@15.4.2

npm ERR! peer dep missing: react@^0.14.1, required by
  react-select@0.9.1

npm ERR! peer dep missing: react-dom@^0.14.1, required by
  react-select@0.9.1

npm ERR! code 1

Please help, Thank you very much.

答:
I think you forgot to install react and react-dom, first run this command it will install react and react-dom properly with all dependencies, after that run other commands.

```<code>npm install react react-dom --save
</code>```

By using --save it will make a entry in package.json file, after using above command check your package.json file, these entries will be there:

```<code>"react": "^XX.X.X",
"react-dom": "^XX.X.X",
</code>```

Title: UNMET PEER DEPENDENCY react

Body:
I think you forgot to install react and react-dom, first run this command it will install react and react-dom properly with all dependencies, after that run other commands.

npm install react react-dom --save

By using --save it will make a entry in package.json file, after using above command check your package.json file, these entries will be there:

"react": "^XX.X.X",
"react-dom": "^XX.X.X",


问:
Laravel 5.4 Script loading issue
I'm working on my first Laravel project (5.4), actually I don't understand why my js script doesn't work like I expected.
I use Mix and Blade :

```<code>// webpack.mix.js
let { mix } = require('laravel-mix').mix;

    // copy fonts and patterns
mix .copy('resources/assets/vendor/bootstrap/fonts', 'public/fonts')
    .copy('resources/assets/vendor/font-awesome/fonts', 'public/fonts')
    .copy('resources/assets/patterns', 'public/css/patterns')

    // compile scss and concatenate css files
    .sass('resources/assets/sass/app.scss', 'public/css')
    .styles([
        'resources/assets/vendor/bootstrap/css/bootstrap.css',
        'resources/assets/vendor/animate/animate.css'
        // ...
    ], 'public/css/vendor.css')

    // concatenate js files
    .js([
        'resources/assets/vendor/jquery/jquery-3.1.1.min.js',
        'resources/assets/vendor/bootstrap/js/bootstrap.js',
        'resources/assets/js/app.js'
        // ...
    ], 'public/js/app.js')
    .options({ processCssUrls: false }); // fix for path issue : https://github.com/almasaeed2010/AdminLTE/issues/1360
</code>```

After npm run dev compliation looks good :

```<code>DONE  Compiled successfully in 6497ms                                                     4:20:57 PM

                                   Asset      Size  Chunks                    Chunk Names
  fonts/glyphicons-halflings-regular.ttf   45.4 kB          [emitted]
                              /js/app.js    1.2 MB       0  [emitted]  [big]  /js/app
                       mix-manifest.json  66 bytes          [emitted]
  fonts/glyphicons-halflings-regular.eot   20.1 kB          [emitted]
fonts/glyphicons-halflings-regular.woff2     18 kB          [emitted]
  fonts/glyphicons-halflings-regular.svg    109 kB          [emitted]
 fonts/glyphicons-halflings-regular.woff   23.4 kB          [emitted]
                            /css/app.css    178 kB       0  [emitted]         /js/app
           fonts/fontawesome-webfont.ttf    166 kB          [emitted]
           fonts/fontawesome-webfont.svg    444 kB          [emitted]  [big]
           fonts/fontawesome-webfont.eot    166 kB          [emitted]
          fonts/fontawesome-webfont.woff     98 kB          [emitted]
         fonts/fontawesome-webfont.woff2   77.2 kB          [emitted]
                   fonts/FontAwesome.otf    135 kB          [emitted]
         css/patterns/header-profile.png   5.88 kB          [emitted]
</code>```

CSS works fine, bootstrap.js also works and when I check inside /js/app.js it seems like everything is inside.

An here is my tempate :

```<code>{{-- app.blade.php--}}
<!DOCTYPE html>
<html lang="{{ config('app.locale', 'en') }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@yield('title')</title>
    <link rel="stylesheet" href="{!! asset('css/vendor.css') !!}" />
    <link rel="stylesheet" href="{!! asset('css/app.css') !!}" />
</head>
<body>
    <!-- Main view  -->
    @yield('content')

    <script src="{!! asset('js/app.js') !!}" type="text/javascript"></script>

    @section('scripts')
    @show
</body>
</html>
</code>```

My troubles began when I want to add a script inside the script section from a child.

```<code>@extends('layouts.app')

@section('scripts')
    <script type="text/javascript">
        $(document).ready(function () {
            alert('test');
        });
    </script>
@endsection
</code>```

I got Uncaught ReferenceError: $ is not defined like if jquery wasn't loaded.

I have no clue why, any idea ?

[note]

It works if I replace inside app.blade.php :

```<code><script src="{!! asset('js/app.js') !!}" type="text/javascript"></script>
</code>```

with :

```<code><script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</code>```

答:
I had a similar issue, and the problem was that at the moment I was using jQuery for the first time, the app.js file generated by webpack wasn't loaded yet.

You can do a simple test to see if you have the same issue. In your first chunk of code where you use jQuery (the line of code that throws you the $ error), wrap that code in this:

```<code>document.addEventListener("DOMContentLoaded", function(event) {
 // Your jQuery code
});
</code>```

One workaround is to load app.js earlier in your blade main layout file, but I am sure it can be done in a better way. I am fairly new to Laravel, so I am still figuring out these kinds of things...

Edit:

Ok, I think I understood now how to do it properly:

In your main blade layout (in my case app.blade.php), at the bottom right before the  tag, load your webpack script, all other external scripts you might load, and finally add a yield scripts section.

Example:

```<code><script src="/js/app.js"></script>
<script src="other/scripts/that/you/need.js"></script>
@yield('scripts')
</code>```

In the blade template where you need jQuery code, instead of adding it directly in the content section, you create a new section called scripts.

Example:

```<code>@section('content')
//Your view code
@endsection

@section('scripts')
//Your jQuery code
@endsection
</code>```

That way, your jQuery code is loaded after the main layout has already loaded the webpack javascript file (which loads jQuery).

Title: Laravel 5.4 Script loading issue

Body:
I'm working on my first Laravel project (5.4), actually I don't understand why my js script doesn't work like I expected.
I use Mix and Blade :

// webpack.mix.js
let { mix } = require('laravel-mix').mix;

    // copy fonts and patterns
mix .copy('resources/assets/vendor/bootstrap/fonts', 'public/fonts')
    .copy('resources/assets/vendor/font-awesome/fonts', 'public/fonts')
    .copy('resources/assets/patterns', 'public/css/patterns')

    // compile scss and concatenate css files
    .sass('resources/assets/sass/app.scss', 'public/css')
    .styles([
        'resources/assets/vendor/bootstrap/css/bootstrap.css',
        'resources/assets/vendor/animate/animate.css'
        // ...
    ], 'public/css/vendor.css')

    // concatenate js files
    .js([
        'resources/assets/vendor/jquery/jquery-3.1.1.min.js',
        'resources/assets/vendor/bootstrap/js/bootstrap.js',
        'resources/assets/js/app.js'
        // ...
    ], 'public/js/app.js')
    .options({ processCssUrls: false }); // fix for path issue : https://github.com/almasaeed2010/AdminLTE/issues/1360

After npm run dev compliation looks good :

DONE  Compiled successfully in 6497ms                                                     4:20:57 PM

                                   Asset      Size  Chunks                    Chunk Names
  fonts/glyphicons-halflings-regular.ttf   45.4 kB          [emitted]
                              /js/app.js    1.2 MB       0  [emitted]  [big]  /js/app
                       mix-manifest.json  66 bytes          [emitted]
  fonts/glyphicons-halflings-regular.eot   20.1 kB          [emitted]
fonts/glyphicons-halflings-regular.woff2     18 kB          [emitted]
  fonts/glyphicons-halflings-regular.svg    109 kB          [emitted]
 fonts/glyphicons-halflings-regular.woff   23.4 kB          [emitted]
                            /css/app.css    178 kB       0  [emitted]         /js/app
           fonts/fontawesome-webfont.ttf    166 kB          [emitted]
           fonts/fontawesome-webfont.svg    444 kB          [emitted]  [big]
           fonts/fontawesome-webfont.eot    166 kB          [emitted]
          fonts/fontawesome-webfont.woff     98 kB          [emitted]
         fonts/fontawesome-webfont.woff2   77.2 kB          [emitted]
                   fonts/FontAwesome.otf    135 kB          [emitted]
         css/patterns/header-profile.png   5.88 kB          [emitted]

CSS works fine, bootstrap.js also works and when I check inside /js/app.js it seems like everything is inside.

An here is my tempate :

{{-- app.blade.php--}}
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@yield('title')</title>
    <link rel="stylesheet" href="{!! asset('css/vendor.css') !!}" />
    <link rel="stylesheet" href="{!! asset('css/app.css') !!}" />

    @yield('content')

    @section('scripts')
    @show

My troubles began when I want to add a script inside the script section from a child.

@extends('layouts.app')

@section('scripts')

@endsection

I got Uncaught ReferenceError: $ is not defined like if jquery wasn't loaded.

I have no clue why, any idea ?

[note]

It works if I replace inside app.blade.php :

with :

Body:
I had a similar issue, and the problem was that at the moment I was using jQuery for the first time, the app.js file generated by webpack wasn't loaded yet.

You can do a simple test to see if you have the same issue. In your first chunk of code where you use jQuery (the line of code that throws you the $ error), wrap that code in this:

document.addEventListener("DOMContentLoaded", function(event) {
 // Your jQuery code
});

One workaround is to load app.js earlier in your blade main layout file, but I am sure it can be done in a better way. I am fairly new to Laravel, so I am still figuring out these kinds of things...

Edit:

Ok, I think I understood now how to do it properly:

In your main blade layout (in my case app.blade.php), at the bottom right before the </body> tag, load your webpack script, all other external scripts you might load, and finally add a yield scripts section.

Example:

<script src="/js/app.js"></script>
<script src="other/scripts/that/you/need.js"></script>
@yield('scripts')

In the blade template where you need jQuery code, instead of adding it directly in the content section, you create a new section called scripts.

Example:

@section('content')
//Your view code
@endsection

@section('scripts')
//Your jQuery code
@endsection

That way, your jQuery code is loaded after the main layout has already loaded the webpack javascript file (which loads jQuery).


问:
Is there any way to use appium with xcode 8, iOS 10, real device
Is there any way to use appium 1.6 with xcode 8, iOS 10, real device.

Currently I am using appium 1.4 and while running it with xcode 8(swift 3 coding) , iOS 10 real device I am getting some errors and I have searched on some sites where its given that there is not any successful compatibility yet of xcode 8 with appium.

Is that true? If anyone can explain exact remark about this.

Thanks in advance

答:
To execute the appium scripts on ios 10 devices xcode 8 is mandatory.If you have xcode 8 you can run the scripts on ios 10 simulators and also real devices.

For this you need to install appium 1.6 and this is not GUI app like appium 1.5.3. You have to launch appium 1.6.0 from terminal only.


问:
How can I get the jobs count when I started a spark application
I was trying to get the jobs count in the first time,
and I try to get it from JobprogressListener. But only stages and tasks information, not jobs. We know Spark application generate the jobs "as it goes".

But if there is a component or a class recording the job information UP FRONT?

答:
It's possible, but I would recommend Spark RESTful API

Steps:

Get applicationId from SparkContext.applicationId property

Query http://context-url:port/applications/api/v1/[app-id]/jobs Where context-url is address of your Spark Driver and port is port with Web UI, it's 4040 normally. Here is documentation

Count jobs that are returned in response from RESTful API


问:
How to install snappy C libraries on Windows 10 for use with python-snappy in Anaconda?
I want to install parquet for python using pip within an Anaconda 2 installation on Windows 10.

While installing I ran into the error that is described here, the installer can't find snappy-c.h.

There is no mention on how to install this on Windows in the answers.

I downloaded the Snappy library from http://google.github.io/snappy/ and now I'm stuck.

From my error message I would have assumed that the header files need to be in C:\Users\...\AppData\Local\Continuum\Anaconda2\include, but in the downlaoded archive header and library files are just all in the same folder.

How do I install these properly in the Anaconda folder?

Full error message:

```<code>Building wheels for collected packages: python-snappy
  Running setup.py bdist_wheel for python-snappy ... error
  Complete output from command C:\Users\...\AppData\Local\Continuum\Anaconda2\python.exe -u -c "import setup
tools, tokenize;__file__='c:\\users\\...\\appdata\\local\\temp\\pip-build-kl4zef\\python-snappy\\setup.py';f=ge
tattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec
'))" bdist_wheel -d c:\users\...\appdata\local\temp\tmpt8fz9bpip-wheel- --python-tag cp27:
  running bdist_wheel
  running build
  running build_py
  creating build
  creating build\lib.win-amd64-2.7
  copying snappy.py -> build\lib.win-amd64-2.7
  running build_ext
  building '_snappy' extension
  creating build\temp.win-amd64-2.7
  creating build\temp.win-amd64-2.7\Release
  C:\Users\...\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\Bin\amd64\cl.exe /c /nol
ogo /Ox /MD /W3 /GS- /DNDEBUG -IC:\Users\...\AppData\Local\Continuum\Anaconda2\include -IC:\Users\...
\AppData\Local\Continuum\Anaconda2\PC /Tpsnappymodule.cc /Fobuild\temp.win-amd64-2.7\Release\snappymodule.obj
  snappymodule.cc
  snappymodule.cc(31) : fatal error C1083: Cannot open include file: 'snappy-c.h': No such file or directory
  error: command 'C:\\Users\\...\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++ for Python\\9.0\\V
C\\Bin\\amd64\\cl.exe' failed with exit status 2
</code>```

答:
EDIT: Refer to the other answers in this thread, I only keep this up for reference.

Here's the steps it took me to install Snappy and Python-Snappy on Windows 10:

Install cygwin.

Download snappy from http://google.github.io/snappy/ and unpack it somewhere into the cygwin directory.

Write AM_PROG_AR into configure.ac above LT_INIT and run autogen.sh from the cygwin terminal, install missing cygwin packages if needed.

Copy snappy-c.h into the Anaconda2/include folder and libsnappy.a into the Anaconda2/Lib folder (in ~/AppData/Local/Continuum/).

stdint.h was missing for Visual C++ Compiler for Python 2.7., I found it here and put it into ~\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\include.

Installing python-snappy should now work without throwing any errors.

If you get problems and weird imports check if the SnapPy library is also installed and deinstall it because it causes a conflict.

(Everything works fine now.)

EDIT: No it does not. This method is not reliable, once you try to update you run into new problems. And installing on Python 3 is another monster that isn't tackled by this solution.

Body:
I want to install parquet for python using pip within an Anaconda 2 installation on Windows 10.

While installing I ran into the error that is described here, the installer can't find snappy-c.h.

There is no mention on how to install this on Windows in the answers.

I downloaded the Snappy library from http://google.github.io/snappy/ and now I'm stuck.

From my error message I would have assumed that the header files need to be in C:\Users\...\AppData\Local\Continuum\Anaconda2\include, but in the downlaoded archive header and library files are just all in the same folder.

How do I install these properly in the Anaconda folder?

Full error message:

Building wheels for collected packages: python-snappy
  Running setup.py bdist_wheel for python-snappy ... error
  Complete output from command C:\Users\...\AppData\Local\Continuum\Anaconda2\python.exe -u -c "import setup
tools, tokenize;__file__='c:\\users\\...\\appdata\\local\\temp\\pip-build-kl4zef\\python-snappy\\setup.py';f=ge
tattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec
'))" bdist_wheel -d c:\users\...\appdata\local\temp\tmpt8fz9bpip-wheel- --python-tag cp27:
  running bdist_wheel
  running build
  running build_py
  creating build
  creating build\lib.win-amd64-2.7
  copying snappy.py -> build\lib.win-amd64-2.7
  running build_ext
  building '_snappy' extension
  creating build\temp.win-amd64-2.7
  creating build\temp.win-amd64-2.7\Release
  C:\Users\...\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\Bin\amd64\cl.exe /c /nol
ogo /Ox /MD /W3 /GS- /DNDEBUG -IC:\Users\...\AppData\Local\Continuum\Anaconda2\include -IC:\Users\...
\AppData\Local\Continuum\Anaconda2\PC /Tpsnappymodule.cc /Fobuild\temp.win-amd64-2.7\Release\snappymodule.obj
  snappymodule.cc
  snappymodule.cc(31) : fatal error C1083: Cannot open include file: 'snappy-c.h': No such file or directory
  error: command 'C:\\Users\\...\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++ for Python\\9.0\\V
C\\Bin\\amd64\\cl.exe' failed with exit status 2

ContentLicense: CC BY-SA 4.0


问:
Android Flash support
Can Android applications can use flash content in them?</p>

答: Well you can instantiate a web browser object or similar, and have that open a Flash swf file from a website or local storage, so yeah, in theory you could have flash inside your app...</p>

ContentLicense: CC BY-SA 2.5

Title: Android Flash support


问:
How to acess imageview defined in adapter?
I have an imageview defined in Recyclerview's Adapter on View holder in Android.I want to access that imageview to my activity for setting image programatically.How i can do it?</p>

答:
Assuming you have an adapter ImageRecyclerAdapter class:

```<code>public class ImageRecyclerAdapter extends RecyclerView.Adapter<ViewHolder>{

     public interface ImageViewInterface {

           void onImageViewLoaded(ImageView imageView);
         }

final ImageViewInterface imageViewInterface;

public ImageRecyclerAdapter(ImageViewInterface imageViewInterface) {

    this.imageViewInterface = imageViewInterface;

}

//in the onBindViewHolder method

public void onBindViewHolder(final ViewHolder holder, int position) {

   imageViewInterface.onImageViewLoaded(holder.imageView);

  }
}
</code>```

Then in your activity you can instantiate and use it like

```<code>ImageRecyclerAdapter imageRecyclerAdapter = new ImageRecyclerAdapter(new ImageRecyclerAdapter.ImageViewInterface() {

        @Override
        public void onImageViewLoaded(ImageView imageView) {
            //do what ever with your image view
        }
    });
</code>```

Body:
Assuming you have an adapter ImageRecyclerAdapter class:

public class ImageRecyclerAdapter extends RecyclerView.Adapter<ViewHolder>{

     public interface ImageViewInterface {

           void onImageViewLoaded(ImageView imageView);
         }

final ImageViewInterface imageViewInterface;

public ImageRecyclerAdapter(ImageViewInterface imageViewInterface) {

    this.imageViewInterface = imageViewInterface;

}

//in the onBindViewHolder method

public void onBindViewHolder(final ViewHolder holder, int position) {

   imageViewInterface.onImageViewLoaded(holder.imageView);

  }
}

Then in your activity you can instantiate and use it like

ImageRecyclerAdapter imageRecyclerAdapter = new ImageRecyclerAdapter(new ImageRecyclerAdapter.ImageViewInterface() {

        @Override
        public void onImageViewLoaded(ImageView imageView) {
            //do what ever with your image view
        }
    });


问:
Excel remove duplicate and get count
I Have data sheet of 45k data. in below format. What I need to do is get the 1st 3 count from individual number and display.

e.g. if you take 61406142526 you should only count the 1st 3 contents.

```<code>Number          Content

61406142526 DEW 858

61406142526 DEW 858

61406142526 DEW 858

61406142526 DEW 858

61410140808 DEW 10

61410140808 DEW 9

61410545997 DEW 10
</code>```

The End display should be

```<code>**DEV 858  = 3**

**DEV 10   = 2**

**DEV  9   = 1**
</code>```

since I'm new to VBA, appreciate anyone can guide me to do this.

答:
No need to use VBA. You can get a unique list by this way. So when your number is on A2:A8 and content is on B2:B8, first get the unique lists at C2:C8 and D2:D8 respectively.

C2:C8: {=IFERROR(INDEX($A$2:$A$8, MATCH(0, COUNTIF($C$1:C1, $A$2:$A$8), 0)),0)}

D2:D8: {=IFERROR(INDEX($B$2:$B$8, MATCH(0, COUNTIF($D$1:D1, $B$2:$B$8), 0)),0)}

Now you can get the n-th largest number by large() formula. So when F2:F4 is {1; 2; 3}, you can get the 1st largest number by =LARGE($C$2:$C$8,$F2). Say this was G2, then drag down to G3:G4 and you got the 2nd and 3rd largest numbers now.

Now you can search those numbers at C2:C8 and retrieve its corresponding content at D2:D8. Generally one can use index() & match() formula for this. So type =INDEX($D$2:$D$8, MATCH($G2,$C$2:$C$8,0)) at H2 and drag down to H3:H4. Finished. Sample file is here.

Title: Excel remove duplicate and get count

Body:
I Have data sheet of 45k data. in below format. What I need to do is get the 1st 3 count from individual number and display.

e.g. if you take 61406142526 you should only count the 1st 3 contents.

Number          Content

61406142526 DEW 858

61406142526 DEW 858

61406142526 DEW 858

61406142526 DEW 858

61410140808 DEW 10

61410140808 DEW 9

61410545997 DEW 10

The End display should be

**DEV 858  = 3**

**DEV 10   = 2**

**DEV  9   = 1**

since I'm new to VBA, appreciate anyone can guide me to do this.


问:
Bug in my HiveUDF
Im trying to write a Hive UDF which checks a column in a Hive table and concatenates a string with it.
my Hive table- cityTab schema and data:

```<code>Schema:
id         int
name       char(30)
rank       int

Data:
1   NewYork  10
2   Amsterdam  30
</code>```

I wrote the following Hive UDF:

```<code>public class MyHiveUdf extends UDF {
    private Text result = new Text();
    public Text evaluate(Text text) {
        if(text == null) {
            return null;
        } else {
            String str = text.toString();
            if(str.contains("NewYork")) {
                result.set(text.toString().concat(" America"));
            }
            return result;
        }
    }
}
</code>```

I added the jar, created a temporary function and executed it like below:

```<code>ADD jar /home/cloudera/Desktop/HiveStrCon.jar;
create temporary function strcon as 'com.hiveudf.strmnp.MyHiveUdf';
select strcon(name) from cityTab;
</code>```

But I see the output data without any concatenation of the new string:

```<code>OK
NewYork
Amsterdam
Time taken: 0.191 seconds, Fetched: 3 row(s)
</code>```

Can anyone tell me what is the mistake I am making here.

答:
I have tried your example and it is working fine at my end just did one minor change in code</p>

```<code>public class MyHiveUdf extends UDF {
    private Text result = new Text();
    public Text evaluate(Text text) {
        if(text == null) {
            return null;
        } else {
            String str = text.toString();
            if(str.contains("NewYork")) {
                result.set(text.toString().concat(" America"));
                return result;
            }
            return text;
        }
    }

hive> ADD jar /root/HiveStrCon.jar;
Added [/root/HiveStrCon.jar] to class path
Added resources: [/root/HiveStrCon.jar]
hive> create temporary function strcon as 'com.hiveudf.strmnp.MyHiveUdf';
OK
Time taken: 0.005 seconds
hive> select strcon(name) from cityTab;
Query ID = root_20170331132222_690e8d43-381c-4e40-a90b-368397c1df5b
Total jobs = 1
Launching Job 1 out of 1
Number of reduce tasks is set to 0 since there's no reduce operator
Starting Job = job_1490796950103_0007, Tracking URL = http://mac127:8088/proxy/application_1490796950103_0007/
Kill Command = /opt/cloudera/parcels/CDH-5.9.0-1.cdh5.9.0.p0.23/lib/hadoop/bin/hadoop job  -kill job_1490796950103_0007
Hadoop job information for Stage-1: number of mappers: 1; number of reducers: 0
2017-03-31 13:22:42,264 Stage-1 map = 0%,  reduce = 0%
2017-03-31 13:22:50,720 Stage-1 map = 100%,  reduce = 0%, Cumulative CPU 2.14 sec
MapReduce Total cumulative CPU time: 2 seconds 140 msec
Ended Job = job_1490796950103_0007
MapReduce Jobs Launched:
Stage-Stage-1: Map: 1   Cumulative CPU: 2.14 sec   HDFS Read: 3166 HDFS Write: 26 SUCCESS
Total MapReduce CPU Time Spent: 2 seconds 140 msec
OK
NewYork America
Amsterdam
Time taken: 19.788 seconds, Fetched: 2 row(s)
</code>```

Title: Bug in my HiveUDF

Body:
Im trying to write a Hive UDF which checks a column in a Hive table and concatenates a string with it.
my Hive table- cityTab schema and data:

Schema:
id         int
name       char(30)
rank       int

Data:
1   NewYork  10
2   Amsterdam  30

I wrote the following Hive UDF:

public class MyHiveUdf extends UDF {
    private Text result = new Text();
    public Text evaluate(Text text) {
        if(text == null) {
            return null;
        } else {
            String str = text.toString();
            if(str.contains("NewYork")) {
                result.set(text.toString().concat(" America"));
            }
            return result;
        }
    }
}

I added the jar, created a temporary function and executed it like below:

ADD jar /home/cloudera/Desktop/HiveStrCon.jar;
create temporary function strcon as 'com.hiveudf.strmnp.MyHiveUdf';
select strcon(name) from cityTab;

But I see the output data without any concatenation of the new string:

OK
NewYork
Amsterdam
Time taken: 0.191 seconds, Fetched: 3 row(s)

Can anyone tell me what is the mistake I am making here.

Body:
I have tried your example and it is working fine at my end just did one minor change in code

public class MyHiveUdf extends UDF {
    private Text result = new Text();
    public Text evaluate(Text text) {
        if(text == null) {
            return null;
        } else {
            String str = text.toString();
            if(str.contains("NewYork")) {
                result.set(text.toString().concat(" America"));
                return result;
            }
            return text;
        }
    }

hive> ADD jar /root/HiveStrCon.jar;
Added [/root/HiveStrCon.jar] to class path
Added resources: [/root/HiveStrCon.jar]
hive> create temporary function strcon as 'com.hiveudf.strmnp.MyHiveUdf';
OK
Time taken: 0.005 seconds
hive> select strcon(name) from cityTab;
Query ID = root_20170331132222_690e8d43-381c-4e40-a90b-368397c1df5b
Total jobs = 1
Launching Job 1 out of 1
Number of reduce tasks is set to 0 since there's no reduce operator
Starting Job = job_1490796950103_0007, Tracking URL = http://mac127:8088/proxy/application_1490796950103_0007/
Kill Command = /opt/cloudera/parcels/CDH-5.9.0-1.cdh5.9.0.p0.23/lib/hadoop/bin/hadoop job  -kill job_1490796950103_0007
Hadoop job information for Stage-1: number of mappers: 1; number of reducers: 0
2017-03-31 13:22:42,264 Stage-1 map = 0%,  reduce = 0%
2017-03-31 13:22:50,720 Stage-1 map = 100%,  reduce = 0%, Cumulative CPU 2.14 sec
MapReduce Total cumulative CPU time: 2 seconds 140 msec
Ended Job = job_1490796950103_0007
MapReduce Jobs Launched:
Stage-Stage-1: Map: 1   Cumulative CPU: 2.14 sec   HDFS Read: 3166 HDFS Write: 26 SUCCESS
Total MapReduce CPU Time Spent: 2 seconds 140 msec
OK
NewYork America
Amsterdam
Time taken: 19.788 seconds, Fetched: 2 row(s)


问:
How to make boundary of x and y points using turtle in Python
I want to ask about turtle library in Python.

I have a CSV file with more than a thousand x and y coordinates in decimal form.

I have been trying to draw a boundary out of it. It would be better if someone guide me on this.

```<code>x,y

74.741996766068,37.0220565806516

74.7491989145055,37.0214805616257

74.7692108154297,37.0256614702854

74.7718505859375,37.0269050617947

74.7776947040111,37.0296592720303

74.7827606210485,37.0320396441619
</code>```

So for I have written this below code but it didn't get work for me.

```<code>import turtle

import csv

import sys

def main():

    daniel = turtle.Turtle()    #Set up a turtle named "daniel"

    myWin = turtle.Screen()     #The graphics window

    t = open('CSV.csv')

    #Draw a square

    for i in t:
        daniel.forward(t[1])     #Move forward 10 steps

        daniel.right(t[0])        #Turn 90 degrees to the right

    myWin.exitonclick()         #Close the window when clicked

main()
</code>```

答:
You took some turtle code that simply draws a square, imported a csv reader module but didn't use it, randomly modified the code and are now frustrated that it doesn't work.  Let's try to do better:

```<code>import turtle
import csv

daniel = turtle.Turtle()  # Set up a turtle named "daniel"
daniel.penup()

with open('CSV.csv', newline='') as t:
    next(t)  # skip over column descriptions

    reader = csv.reader(t, quoting=csv.QUOTE_NONNUMERIC)  # turn unquoted values into floats

    for x, y in reader:
        daniel.goto(x, y)
        daniel.pendown()  # no-op after 1st iteration

myWin = turtle.Screen()  # The graphics window

myWin.exitonclick()  # Close the window when clicked
</code>```

This assumes your CVS.cvs data is single spaced, not double spaced as you presented it:

```<code>x,y
74.741996766068,37.0220565806516
74.7491989145055,37.0214805616257
74.7692108154297,37.0256614702854
74.7718505859375,37.0269050617947
74.7776947040111,37.0296592720303
74.7827606210485,37.0320396441619
</code>```

This data will not draw anything as your points are effectively all the same since they are so close together -- you may need to scale your data, or use more/different data to see any actual drawing.

Body:
I want to ask about turtle library in Python.

I have a CSV file with more than a thousand x and y coordinates in decimal form.

I have been trying to draw a boundary out of it. It would be better if someone guide me on this.

x,y

74.741996766068,37.0220565806516

74.7491989145055,37.0214805616257

74.7692108154297,37.0256614702854

74.7718505859375,37.0269050617947

74.7776947040111,37.0296592720303

74.7827606210485,37.0320396441619

So for I have written this below code but it didn't get work for me.

import turtle

import csv

import sys

def main():

    daniel = turtle.Turtle()    #Set up a turtle named "daniel"

    myWin = turtle.Screen()     #The graphics window

    t = open('CSV.csv')

    #Draw a square

    for i in t:
        daniel.forward(t[1])     #Move forward 10 steps

        daniel.right(t[0])        #Turn 90 degrees to the right

    myWin.exitonclick()         #Close the window when clicked

main()

Body:
You took some turtle code that simply draws a square, imported a csv reader module but didn't use it, randomly modified the code and are now frustrated that it doesn't work.  Let's try to do better:

import turtle
import csv

daniel = turtle.Turtle()  # Set up a turtle named "daniel"
daniel.penup()

with open('CSV.csv', newline='') as t:
    next(t)  # skip over column descriptions

    reader = csv.reader(t, quoting=csv.QUOTE_NONNUMERIC)  # turn unquoted values into floats

    for x, y in reader:
        daniel.goto(x, y)
        daniel.pendown()  # no-op after 1st iteration

myWin = turtle.Screen()  # The graphics window

myWin.exitonclick()  # Close the window when clicked

This assumes your CVS.cvs data is single spaced, not double spaced as you presented it:

x,y
74.741996766068,37.0220565806516
74.7491989145055,37.0214805616257
74.7692108154297,37.0256614702854
74.7718505859375,37.0269050617947
74.7776947040111,37.0296592720303
74.7827606210485,37.0320396441619

This data will not draw anything as your points are effectively all the same since they are so close together -- you may need to scale your data, or use more/different data to see any actual drawing.


问:
Show title of currently active tab from chrome extension
I'm a complete beginner at javascript.
I don't understand howto use  chrome.windows.get

What I want to do is:

Grab the current tab's title

using chrome.windows.get or anything that will work.

when the button (showbtn) is clicked

store this title to the div : showurl

popup.js followed by popup.html

function output2() {
//internal variable el
el1 = document.getElementById('showurl');
chrome.windows.get(integer windowId, object getInfo, function callback)
}
document.getElementById('showbtn').addEventListener('click', output2);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
  <head>
    <title>Popup</title>
    <link href="popup.css" rel="stylesheet">
    <script src="popup.js"></script>
  </head>
  <body>
    <h1>show url</h1>
    <div role="main">
      <form>
 <div id="showurl"></div>
        <button id="showbtn">Show Url title!</button>
      </form>
    </div>
  </body>
</html></code>```

答:
Solved,
Achieved by using the getSelected method:

chrome.tabs.getSelected(null,function(tab) { // null defaults to current window
  var title = tab.title;

  el1 = document.getElementById('showurl');
  el1.innerHTML = title;
 });```

Body:
I'm a complete beginner at javascript.
I don't understand howto use  chrome.windows.get

What I want to do is:

Grab the current tab's title

using chrome.windows.get or anything that will work.

when the button (showbtn) is clicked

store this title to the div : showurl

popup.js followed by popup.html

function output2() {
//internal variable el
el1 = document.getElementById('showurl');
chrome.windows.get(integer windowId, object getInfo, function callback)
}
document.getElementById('showbtn').addEventListener('click', output2);

<!DOCTYPE html>

    <title>Popup</title>
    <link href="popup.css" rel="stylesheet">

show url

      <form>

        <button id="showbtn">Show Url title!</button>
      </form>


问:
Javascript - Read value of a JSON property, if that key doesn't exist return null, in a single line
Let me give a python analogy of what I am looking for:

```<code>fruits_dict = {"banana": 4, "apple": 3}
num_apples = fruits_dict.get("apple", None)
num_oranges = fruits_dict.get("orange", None)
print(num_apples, num_oranges)
</code>```

prints:
    3 None

Now in Javascript, with a similar JS object, we can use hasOwnProperty(key) in a if block

```<code>var fruits_obj = {"banana": 4, "apple": 3};
var num_apples = null;
if (fruits_obj.hasOwnProperty("apple")) {
    num_apples = fruits_obj["apple"];
}
var num_oranges = null;
if (fruits_obj.hasOwnProperty("orange")) {
    num_oranges = fruits_obj["orange"];
}
console.log(num_apples, num_oranges);
</code>```

gives:
    3 null

Is there a better way? Something on the lines of python's get function?

答:
We can use JavaScript conditional (ternary) operator.

This operator is used as a shortcut for the if statement.

Syntax :

```<code>condition ? expr1 : expr2
</code>```

If condition is true, the operator returns the value of expr1; otherwise, it returns the value of expr2.

```<code>var res = fruits_obj.hasOwnProperty("orange") ? fruits_obj['orange'] : null
</code>```

Body:
Let me give a python analogy of what I am looking for:

fruits_dict = {"banana": 4, "apple": 3}
num_apples = fruits_dict.get("apple", None)
num_oranges = fruits_dict.get("orange", None)
print(num_apples, num_oranges)

prints:
    3 None

Now in Javascript, with a similar JS object, we can use hasOwnProperty(key) in a if block

var fruits_obj = {"banana": 4, "apple": 3};
var num_apples = null;
if (fruits_obj.hasOwnProperty("apple")) {
    num_apples = fruits_obj["apple"];
}
var num_oranges = null;
if (fruits_obj.hasOwnProperty("orange")) {
    num_oranges = fruits_obj["orange"];
}
console.log(num_apples, num_oranges);

gives:
    3 null

Is there a better way? Something on the lines of python's get function?

Body:
We can use JavaScript conditional (ternary) operator.

This operator is used as a shortcut for the if statement.

Syntax :

condition ? expr1 : expr2

If condition is true, the operator returns the value of expr1; otherwise, it returns the value of expr2.

var res = fruits_obj.hasOwnProperty("orange") ? fruits_obj['orange'] : null


问:
Oracle sql issue with returning rows that have null values on table joins
I am working on a view (not originally created by myself) and what I am trying to do is return requests (table alias req) that dont have hours allocated to them (table alias te) and i am kinda struggling to get any kind of outer join to return this on the following sql:

```<code>SELECT
te.tc_date_yyyy_ww,
te.tc_date_yyyy_mm,
te.tc_date_yyyy,
te.dc_date,
te.nc_request_id_fk,
te.nc_subrequest_id_fk,
te.tc_clock,
te.nc_hours,
te.nc_amount,
te.nc_discipline_id_fk,
te.tc_discipline_desc,
req.tc_request_name,
req.mc_project_cost,
req.nt_fetr_project,
req.nc_bus_unit_id_fk,
req.nc_location_id_fk,
req.nc_cemt_status_id_fk,
coord.tc_user_fname || ' ' || coord.tc_user_lname AS projectcoodname,
assoc.tc_fname || ' ' || assoc.tc_lname AS empname,
assoc_disc.tc_long_desc AS user_discipline,
sr.tc_name AS child_project,
sr.tc_cost_center_or_wbs,
sr.tc_cost_center_nbr,
sr.tc_cost_center_desc,
sr.tc_profit_center_desc,
sr.tc_profit_center_nbr,
sr.tc_wbs_nbr,
sr.tc_wbs_desc,
sr.nc_child_type_id_fk,
sre.nc_estimate,
stat_li.tc_med_desc AS req_status,
NVL(PP.NC_PRIORITY,0) AS PRIORITY
 FROM te07fear.tbye10_time_entry te,
      te07fear.tbxg100_requests req,
      (SELECT *
         FROM te07fear.tbye05_form_users
        WHERE tc_role_id_fk = 'project_coordinator') coord,
      te07fear.tbye07_subrequest sr,
      te07fear.tbye08_subrequest_est sre,
      te07fear.tbye02_list_items stat_li,
      te07fear.tbye04_associates assoc,
      te07fear.tbxg95_dropdowns assoc_disc,
      TE07FEAR.TBYF43_PROJECT_PRIORITY PP
WHERE
    te.tc_clock = assoc.tc_clock
  AND
    te.nc_subrequest_id_fk = sr.nc_subrequest_id(+)
  AND
    te.nc_subrequest_id_fk = sre.nc_subrequest_id_fk(+)
  AND
    te.tc_clock = sre.tc_clock(+)
  AND
    te.nc_request_id_fk = req.nc_request_id
  AND
    te.nc_request_id_fk = coord.nc_form_id_fk
  AND
    assoc.nc_discipline_id_fk = assoc_disc.nc_key_id
  AND
    req.nc_cemt_status_id_fk = stat_li.nc_value_id
  AND
    TE.NC_REQUEST_ID_FK = PP.NC_REQUEST_ID_FK
  AND
    TE.NC_SUBREQUEST_ID_FK = PP.NC_SUB_REQUEST_ID_FK
  AND
    TE.TC_DATE_YYYY_WW = PP.TC_DATE_YYYY_WW
  AND
    TE.TC_CLOCK = PP.TC_CLOCK_NUMBER
</code>```

Any help or ideas would be greatly appreciated.I am assuming that a left outer join should enable me to to this.

Thanks
JC

答:
As far as I understand, you actually need NOT EXISTS clause, not outer join.
Here's a simplified snippet, to show you what I mean (skipped most of the query, but you'l get the idea):

```<code>SELECT req.tc_request_name,
       req.mc_project_cost,
       req.nt_fetr_project,
       req.nc_bus_unit_id_fk,
       req.nc_location_id_fk,
       req.nc_cemt_status_id_fk
  FROM te07fear.tbxg100_requests req
 WHERE NOT EXISTS (select 1
                     from te07fear.tbye10_time_entry te
                    where te.nc_request_id_fk = req.nc_request_id)
;
</code>```

Let me know if that's the case and if it serves the purpose.

Cheers

Body:
I am working on a view (not originally created by myself) and what I am trying to do is return requests (table alias req) that dont have hours allocated to them (table alias te) and i am kinda struggling to get any kind of outer join to return this on the following sql:

SELECT
te.tc_date_yyyy_ww,
te.tc_date_yyyy_mm,
te.tc_date_yyyy,
te.dc_date,
te.nc_request_id_fk,
te.nc_subrequest_id_fk,
te.tc_clock,
te.nc_hours,
te.nc_amount,
te.nc_discipline_id_fk,
te.tc_discipline_desc,
req.tc_request_name,
req.mc_project_cost,
req.nt_fetr_project,
req.nc_bus_unit_id_fk,
req.nc_location_id_fk,
req.nc_cemt_status_id_fk,
coord.tc_user_fname || ' ' || coord.tc_user_lname AS projectcoodname,
assoc.tc_fname || ' ' || assoc.tc_lname AS empname,
assoc_disc.tc_long_desc AS user_discipline,
sr.tc_name AS child_project,
sr.tc_cost_center_or_wbs,
sr.tc_cost_center_nbr,
sr.tc_cost_center_desc,
sr.tc_profit_center_desc,
sr.tc_profit_center_nbr,
sr.tc_wbs_nbr,
sr.tc_wbs_desc,
sr.nc_child_type_id_fk,
sre.nc_estimate,
stat_li.tc_med_desc AS req_status,
NVL(PP.NC_PRIORITY,0) AS PRIORITY
 FROM te07fear.tbye10_time_entry te,
      te07fear.tbxg100_requests req,
      (SELECT *
         FROM te07fear.tbye05_form_users
        WHERE tc_role_id_fk = 'project_coordinator') coord,
      te07fear.tbye07_subrequest sr,
      te07fear.tbye08_subrequest_est sre,
      te07fear.tbye02_list_items stat_li,
      te07fear.tbye04_associates assoc,
      te07fear.tbxg95_dropdowns assoc_disc,
      TE07FEAR.TBYF43_PROJECT_PRIORITY PP
WHERE
    te.tc_clock = assoc.tc_clock
  AND
    te.nc_subrequest_id_fk = sr.nc_subrequest_id(+)
  AND
    te.nc_subrequest_id_fk = sre.nc_subrequest_id_fk(+)
  AND
    te.tc_clock = sre.tc_clock(+)
  AND
    te.nc_request_id_fk = req.nc_request_id
  AND
    te.nc_request_id_fk = coord.nc_form_id_fk
  AND
    assoc.nc_discipline_id_fk = assoc_disc.nc_key_id
  AND
    req.nc_cemt_status_id_fk = stat_li.nc_value_id
  AND
    TE.NC_REQUEST_ID_FK = PP.NC_REQUEST_ID_FK
  AND
    TE.NC_SUBREQUEST_ID_FK = PP.NC_SUB_REQUEST_ID_FK
  AND
    TE.TC_DATE_YYYY_WW = PP.TC_DATE_YYYY_WW
  AND
    TE.TC_CLOCK = PP.TC_CLOCK_NUMBER

Any help or ideas would be greatly appreciated.I am assuming that a left outer join should enable me to to this.

Thanks
JC

Body:
As far as I understand, you actually need NOT EXISTS clause, not outer join.
Here's a simplified snippet, to show you what I mean (skipped most of the query, but you'l get the idea):

SELECT req.tc_request_name,
       req.mc_project_cost,
       req.nt_fetr_project,
       req.nc_bus_unit_id_fk,
       req.nc_location_id_fk,
       req.nc_cemt_status_id_fk
  FROM te07fear.tbxg100_requests req
 WHERE NOT EXISTS (select 1
                     from te07fear.tbye10_time_entry te
                    where te.nc_request_id_fk = req.nc_request_id)
;

Let me know if that's the case and if it serves the purpose.

Cheers


问:
Remove number from large string in specific position [PHP RegEx]
I have a large string (multiple lines) I need to find numbers in with regex. The position the number I need is always proceeded/follow by an exact order of characters so I can use non-capturing matches to pinpoint the exact number I need. I put together a regex to get this number but it refuses to work and I can't figure it out!

Below is a small bit of php code that I can't get to work showing the basic format of what i need

```<code>$sTestData = 'lak sjdhfklsjaf<?kjnsdfh461uihrfkjsn+%5Bmlknsadlfjncas dlk';

$sNumberStripRE = '/.*?(?:sjdhfklsjaf<\\?kjnsdfh)(\\d+)(?:uihrfkjsn\\+%5Bmlknsadlfjncas).*?/gim';

if (preg_match_all($sNumberStripRE, $sTestData, $aMatches))
{
    var_dump($aMatches);
}
</code>```

the number I need is 461 and the characters before/after the spaces on either side of this number are always the same

any help getting the above regex working would be great!

This link RegExr: My Reg Ex (to an online regex genereator and my regex) shows that it should work!

答:
With regard to that link, which regular expression engine is it working from?  Built in Flex, so probably the ActionScript RegExp engine.  They are not all the same, each one varies.

You have a number of double-backslashes, they should probably be single in those strings.

Body:
I have a large string (multiple lines) I need to find numbers in with regex. The position the number I need is always proceeded/follow by an exact order of characters so I can use non-capturing matches to pinpoint the exact number I need. I put together a regex to get this number but it refuses to work and I can't figure it out!

Below is a small bit of php code that I can't get to work showing the basic format of what i need

$sTestData = 'lak sjdhfklsjaf<?kjnsdfh461uihrfkjsn+%5Bmlknsadlfjncas dlk';

$sNumberStripRE = '/.*?(?:sjdhfklsjaf<\\?kjnsdfh)(\\d+)(?:uihrfkjsn\\+%5Bmlknsadlfjncas).*?/gim';

if (preg_match_all($sNumberStripRE, $sTestData, $aMatches))
{
    var_dump($aMatches);
}

the number I need is 461 and the characters before/after the spaces on either side of this number are always the same

any help getting the above regex working would be great!

This link RegExr: My Reg Ex (to an online regex genereator and my regex) shows that it should work!


问:
How can you return status code 404 from angular PageNotFoundComponent?
My understanding is that you can customize the not found page by setting { path: '**', component: PageNotFoundComponent } to RouterMoudle.forRoot(routes).

However it returns http status code 200.
How can you return status code 404?

答:
I guess you are mixing two concepts here:

With { path: '**', component: PageNotFoundComponent } you define what component should be shown, if your router can not resolve the given url. The request is handled clientside and angular provides a defined component/page and therefore the request http status code is 200, because there was never a resource which could not be found.

Usually  there are only http requests if the 404 page is loaded asynchronously or does contain any extra resources like for example images.

An HTTP 404 on the other side will occur when a webserver can not find a requested resource. So in this case a server handles the response and will provide the correct http status code.

So all in all your use case does not make much sense, because if you want to provide a custom 404 error page with angular, the http response code must be 200.


问:
How To Create And Start Docker Container with specific port, detached mode using docker-java
I want to create and run docker using docker java client. I want running something like this :

```<code>docker run -d -p 4444:4444 --name selenium-hub selenium/hub:2.53.0
</code>```

How to implement this command on docker-java client? Here is my code so far :

```<code>CreateContainerResponse response = dockerClient.createContainerCmd("selenium/hub")
               .withName(name)
               .exec();
</code>```

Actually IDK how to specify -d (for running in background). and -p.
please help me. sorry I am new in Docker.

答:
docker-java has a nice wiki on https://github.com/docker-java/docker-java/wiki. Searching for "port" got me this:

Create new Docker container and start it with exposed ports

```<code>ExposedPort tcp22 = ExposedPort.tcp(22);
ExposedPort tcp23 = ExposedPort.tcp(23);

Ports portBindings = new Ports();
portBindings.bind(tcp22, Ports.Binding(11022));
portBindings.bind(tcp23, Ports.Binding(11023));

CreateContainerResponse container = dockerClient.createContainerCmd("busybox")
   .withCmd("true")
   .withExposedPorts(tcp22, tcp23)
   .withPortBindings(portBindings)
   .exec();
</code>```

I looked at some tests in docker-java, and it looks like you only did half the work for running a container, because you only created the container and didn't start it. Based on what I see in this test (https://github.com/docker-java/docker-java/blob/069987852c842e3bba85ed3325a8877c36f9e87f/src/test/java/com/github/dockerjava/core/command/ExecStartCmdImplTest.java#L69), your code should look something like this:

```<code>ExposedPort tcp4444 = ExposedPort.tcp(4444);

Ports portBindings = new Ports();
portBindings.bind(tcp4444, Ports.Binding(4444));

// Create the container (it will not be running)
CreateContainerResponse container = dockerClient.createContainerCmd("selenium/hub")
    .withName(name)
    .withExposedPorts(tcp4444)
    .withPortBindings(portBindings)
    .exec();

// Actually run the container
dockerClient.startContainerCmd(container).exec();
</code>```

As far as I can tell, there's no reason to explicitly run it in detached mode because it will be started asynchronously by default.

Body:
I want to create and run docker using docker java client. I want running something like this :

docker run -d -p 4444:4444 --name selenium-hub selenium/hub:2.53.0

How to implement this command on docker-java client? Here is my code so far :

CreateContainerResponse response = dockerClient.createContainerCmd("selenium/hub")
               .withName(name)
               .exec();

Actually IDK how to specify -d (for running in background). and -p.
please help me. sorry I am new in Docker.

Body:
docker-java has a nice wiki on https://github.com/docker-java/docker-java/wiki. Searching for "port" got me this:

Create new Docker container and start it with exposed ports

ExposedPort tcp22 = ExposedPort.tcp(22);
ExposedPort tcp23 = ExposedPort.tcp(23);

Ports portBindings = new Ports();
portBindings.bind(tcp22, Ports.Binding(11022));
portBindings.bind(tcp23, Ports.Binding(11023));

CreateContainerResponse container = dockerClient.createContainerCmd("busybox")
   .withCmd("true")
   .withExposedPorts(tcp22, tcp23)
   .withPortBindings(portBindings)
   .exec();

I looked at some tests in docker-java, and it looks like you only did half the work for running a container, because you only created the container and didn't start it. Based on what I see in this test (https://github.com/docker-java/docker-java/blob/069987852c842e3bba85ed3325a8877c36f9e87f/src/test/java/com/github/dockerjava/core/command/ExecStartCmdImplTest.java#L69), your code should look something like this:

ExposedPort tcp4444 = ExposedPort.tcp(4444);

Ports portBindings = new Ports();
portBindings.bind(tcp4444, Ports.Binding(4444));

// Create the container (it will not be running)
CreateContainerResponse container = dockerClient.createContainerCmd("selenium/hub")
    .withName(name)
    .withExposedPorts(tcp4444)
    .withPortBindings(portBindings)
    .exec();

// Actually run the container
dockerClient.startContainerCmd(container).exec();

As far as I can tell, there's no reason to explicitly run it in detached mode because it will be started asynchronously by default.


问:
Why does this sort in Java not work?
I'm trying to implement a short sorting algorithm, but it simply doesn't work. Anyone with more experience in programming got any tips? The array is not sorted, several values are coming up multiple times in the end print. Why?</p>

```<code>public static void main(String[] args) {
    // Sort the data
    int[] array = {1,5,2,3,6,2,29,-2,23,3};

    for (int i = 0; i<array.length-1; i++) {

        if (array[i] > array[i+1]) {
            array[i+1] = array[i];
            array[i] = array[i+1];
        }
    }

    // Print the data.
    for (int i = 0; i<array.length; i++) {
        System.out.print(i+ ", ");
    }
}
</code>```

答:
Your swap is broken. After you call array[i+1] = array[i];, array[i] = array[i+1]; does nothing because array[i+1] is overwritten. You need to store the value in a temporary variable:

```<code>int temp = array[i+1];
array[i+1] = array[i];
array[i] = temp;
</code>```

Title: Why does this sort in Java not work?

Body:
I'm trying to implement a short sorting algorithm, but it simply doesn't work. Anyone with more experience in programming got any tips? The array is not sorted, several values are coming up multiple times in the end print. Why?

public static void main(String[] args) {
    // Sort the data
    int[] array = {1,5,2,3,6,2,29,-2,23,3};

    for (int i = 0; i<array.length-1; i++) {

        if (array[i] > array[i+1]) {
            array[i+1] = array[i];
            array[i] = array[i+1];
        }
    }

    // Print the data.
    for (int i = 0; i<array.length; i++) {
        System.out.print(i+ ", ");
    }
}

Body:
Your swap is broken. After you call array[i+1] = array[i];, array[i] = array[i+1]; does nothing because array[i+1] is overwritten. You need to store the value in a temporary variable:

int temp = array[i+1];
array[i+1] = array[i];
array[i] = temp;


问:
Boolean != false
In Java, you would usually say that

if(someBool != false)

is the same as

if(someBool)

But what if someBool is not of type boolean but  Boolean, and its value is null?

答:
It will throw a NullPointerException (autounboxing of null throws NPE).

But that only means that you must not allow a null value. Either use a default, or don't use autounboxing and make a non-null check. Because using a null value of a boolean means you have 3, not 2 values. (Better ways of handling it were proposed by Michael and Tobiask)

Title: Boolean != false


答:
While on the surface it seems like a good idea to restrict the search space by setting the cost function to a high value, this approach has a few drawbacks.

You need to be sure that this value dominates the cost function.

The optimizer does not know that the range is forbidden. It just sees a high cost but that does not prevent it to go there.

You are creating a plateau in the cost function. When the optimizer runs into the forbidden area it may not know how to get out because the function looks the same in every direction.

In general, it is better to use a bounded or constrained optimizer. That way the algorithm knows where it may not go. Usually I use scipy.optimize.minimize and let it choose automatically which optimization algorithm to use, based on the information (cost function, derivatives, bounds, constraints) it gets.

However, if you really need to use a specific optimization algorithm that does not take bounds or constraints you can help it get back into the feasible region by making the cost function slope towards positive values. For example:

```<code>if (coeff[0] or coeff[1] or coeff[2] or coeff[3]) < 0:
    return (np.minimum(coef, 0)**2 + 1) * 100000000.0
</code>```

Title: optimalizacja using fmin_powell, only positive parameters

Body:
I've been trying optimize coefficients using the fmin_powell method.
I want an optimizer to check only positive values. Therefore I added the condition whether any of parameters is negative - return 100000000.0

coeff = np.array([1.,1.,1.,1.])

def run(coeff, *func):
     if (coeff[0] or coeff[1] or coeff[2] or coeff[3]) < 0: return 100000000.0
     else:
          [some math operations]
          return Energy

def optimize(f):
   return opt.fmin_powell(run, coeff, args=(f,f), disp=0)

f = ['1a','2b','3c', '4d', '5e', '6e', '7f', '8g']

p = Pool(processes=8)
async_ret = p.map(optimize,f,chunksize=1)
result = async_ret.get()
p.terminate()

Anyways that I wrote down a condition, I am getting negative values:

    [ 1.  1.  1.  1.]10.1985596621
    [ 1.  1.  1.  1.]10.1985596621
    [ 2.  1.  1.  1.]10.2100842541
    [ 1.  1.  1.  1.]10.1985596621
    [ 0.38196603  1.          1.          1.        ]10.1822540716
    [ 0.14589804  1.          1.          1.        ]10.1678012695
    [ 0.0557281  1.         1.         1.       ]10.1563797355
    [ 0.02128625  1.          1.          1.        ]10.1480644959
    [ 0.01000002  1.          1.          1.        ]10.1433906566
    [  1.55472633e-08  -6.18034000e-01   1.00000000e+00   1.00000000e+00]10.1319877158
    [  1.55472633e-08  -3.23606803e+00   1.00000000e+00   1.00000000e+00]10.1319475286

What am I doing wrong?

Body:
While on the surface it seems like a good idea to restrict the search space by setting the cost function to a high value, this approach has a few drawbacks.

You need to be sure that this value dominates the cost function.

The optimizer does not know that the range is forbidden. It just sees a high cost but that does not prevent it to go there.

You are creating a plateau in the cost function. When the optimizer runs into the forbidden area it may not know how to get out because the function looks the same in every direction.

In general, it is better to use a bounded or constrained optimizer. That way the algorithm knows where it may not go. Usually I use scipy.optimize.minimize and let it choose automatically which optimization algorithm to use, based on the information (cost function, derivatives, bounds, constraints) it gets.

However, if you really need to use a specific optimization algorithm that does not take bounds or constraints you can help it get back into the feasible region by making the cost function slope towards positive values. For example:

if (coeff[0] or coeff[1] or coeff[2] or coeff[3]) < 0:
    return (np.minimum(coef, 0)**2 + 1) * 100000000.0


问:
For Loop to Count Letters in a Word
I'm just learning python and I came to a problem that required me to put a string as an input in my "count letters function."

The function is supposed to count how many "a"s are in a word given (specifically, a fruit inputed by the user).

The final value is correct, but in my function, it lists me the programs "procedure" if you will by listing how many "a"s are at each index and adding everything that was before.

I just want one final value, not a list.

If I'm not too clear, here is my program and test it out for yourself to see what I mean, and maybe help me come to a solution?

```<code>def count_letters(a):
    count=0
    for char in a:
        if char == 'a':
            count+=1
        print count

a=raw_input("Name a fruit and I will tell you how many letters are in it." + '\n')
print count_letters(a)
</code>```

答:
If you want to keep a similar structure and calculate the count yourself, you can use :

```<code>def count_a(fruit_name):
    return sum(1 for char in fruit_name if char == 'a')
</code>```

It's shorter, it's more pythonic, it's not a standard method call, it returns an integer instead of just printing it and the variable names might be a bit clearer.

If you don't mind using an existing python method, you can use :

```<code>return fruit_name.count('a')
</code>```

Title: For Loop to Count Letters in a Word

Body:
I'm just learning python and I came to a problem that required me to put a string as an input in my "count letters function."

The function is supposed to count how many "a"s are in a word given (specifically, a fruit inputed by the user).

The final value is correct, but in my function, it lists me the programs "procedure" if you will by listing how many "a"s are at each index and adding everything that was before.

I just want one final value, not a list.

If I'm not too clear, here is my program and test it out for yourself to see what I mean, and maybe help me come to a solution?

def count_letters(a):
    count=0
    for char in a:
        if char == 'a':
            count+=1
        print count

a=raw_input("Name a fruit and I will tell you how many letters are in it." + '\n')
print count_letters(a)

Body:
If you want to keep a similar structure and calculate the count yourself, you can use :

def count_a(fruit_name):
    return sum(1 for char in fruit_name if char == 'a')

It's shorter, it's more pythonic, it's not a standard method call, it returns an integer instead of just printing it and the variable names might be a bit clearer.

If you don't mind using an existing python method, you can use :

return fruit_name.count('a')


问:
How do specify an environment name for elastic bean stalk?
I am trying to deploy to elastic beanstalk using the cli.

The command I run is

```<code> eb create --modules ebtargets/goapi -v
</code>```

I get the following error

```<code>WARNING: You have uncommitted changes.
INFO: Getting version label from git with git-describe
INFO: Uploading archive to s3 location: goapi/app-d4ec2-160630_135740.json
Uploading goapi/app-d4ec2-160630_135740.json to S3. This may take a while.
Upload Complete.
INFO: Creating AppVersion app-d4ec2-160630_135740
--- Waiting for application versions to be pre-processed ---
Finished processing application version app-d4ec2-160630_135740
--- Creating modules ---
ERROR: ServiceError - ApplicationVersion app-d4ec2-160630_135740 must specify an environment name in env.yaml
</code>```

I have the key EnvironmentName in my env.yaml file. Any help on this?

答:
I had a similar problem and I noticed you have to check your env.yaml into version control otherwise it won't be used:</p>

```<code>git add env.yaml
git commit -m "add elastic beanstalk environment config"
</code>```

Body:
I am trying to deploy to elastic beanstalk using the cli.

The command I run is

 eb create --modules ebtargets/goapi -v

I get the following error

WARNING: You have uncommitted changes.
INFO: Getting version label from git with git-describe
INFO: Uploading archive to s3 location: goapi/app-d4ec2-160630_135740.json
Uploading goapi/app-d4ec2-160630_135740.json to S3. This may take a while.
Upload Complete.
INFO: Creating AppVersion app-d4ec2-160630_135740
--- Waiting for application versions to be pre-processed ---
Finished processing application version app-d4ec2-160630_135740
--- Creating modules ---
ERROR: ServiceError - ApplicationVersion app-d4ec2-160630_135740 must specify an environment name in env.yaml

I have the key EnvironmentName in my env.yaml file. Any help on this?

Body:
I had a similar problem and I noticed you have to check your env.yaml into version control otherwise it won't be used:

git add env.yaml
git commit -m "add elastic beanstalk environment config"


问:
Android slide animation
Why I am not able to slide text view in android from right to left continuously?

I am using below xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<set
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/linear_interpolator"
    android:fillAfter="true">

    <translate
        android:fromXDelta="-3%p"
        android:toXDelta="3%p"
        android:duration="1200" />
</set>
</code>```

答:
If you want your animation to play continuously, you need to add the following two attributes to "translate" tag.

```<code><set
xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/linear_interpolator"
android:fillAfter="true">

    <translate
        android:fromXDelta="-3%p"
        android:toXDelta="3%p"
        android:duration="1200"
        android:repeatCount="infinite"
        android:repeatMode="reverse"/>
</set>
</code>```

Note that if “repeatCount" and "repeatMode" are added to "set" tag, things will not work as expected.

Title: Android slide animation

Body:
Why I am not able to slide text view in android from right to left continuously?

I am using below xml:

<?xml version="1.0" encoding="utf-8"?>
<set
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/linear_interpolator"
    android:fillAfter="true">

    <translate
        android:fromXDelta="-3%p"
        android:toXDelta="3%p"
        android:duration="1200" />
</set>

Body:
If you want your animation to play continuously, you need to add the following two attributes to "translate" tag.

<set
xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/linear_interpolator"
android:fillAfter="true">

    <translate
        android:fromXDelta="-3%p"
        android:toXDelta="3%p"
        android:duration="1200"
        android:repeatCount="infinite"
        android:repeatMode="reverse"/>
</set>

Note that if “repeatCount" and "repeatMode" are added to "set" tag, things will not work as expected.


问:
Send email report sonar scanner in jenkins
Please help Me getting result of sonar scanner in jenkins to send email report.

I can get sonar scanner's id:

${it.getAction('hudson.plugins.sonar.action.SonarAnalysisAction').getCeTaskId()}

But I dont get any status process .

(I am using ext-email report)

答:
I assume you want to get quality gate status. You know that an important part of the analysis (like measure aggregation and quality gate check) is made on SonarQube server asynchronously.
We have implemented a Jenkins Pipeline step named waitForQualityGate() that will pause your pipeline until processing is done on SonarQube side, and return the quality gate status.

If you want to do something similar for an old style Jenkins job, you'll have to implement something similar on your own. For now we don't plan to backport this feature. The main reason is that doing this "wait" in a normal Job will occupy a slave for nothing.


问:
Add data from DropdownList to table(ASP.NET MVC)
I have Companies table and Vacancies.

Company have some number of Vacancies

I have View like this

So I select company  and second dropdown list is updated depending on company.

Here is View code (DropdownList section )

```<code> <div class="right-grid-in-grid" style="width:100%;">
                <div style="margin-left:20px;width:50%; ">
                    @Html.DropDownList("Company", ViewBag.Companies as SelectList, new { @class = "greeting" })
                    @Html.ValidationMessageFor(model => model.VacancyId, "", new { @class = "text-danger" })
                </div>
                <div style="margin-left:20px;width:100%">
                    <select name="id" id="vacancy" style="width:55%" class="greeting" data-url="@Url.Action("Vacancies","Questions")" />
                </div>
</code>```

Here is code for AJAX request

```<code> $(function () {
        $("#Company").change(function (e) {
            var $vacancy = $("#vacancy");
            var url = $vacancy.data("url") + '?companyId=' + $(this).val();
            $.getJSON(url, function (items) {
                $.each(items, function (a, b) {
                    $vacancy.append('<option value="' + b.Value + '">' + b.Text + '</option>');
                });
            });
        });
    });
</code>```

And here is controller code

```<code> public ActionResult WelcomeScreen()
    {
        // Формируем список команд для передачи в представление
        //SelectList teams = new SelectList(db.Vacancy, "VacancyId", "VacancyName");
        //ViewBag.Teams = teams;

        ViewBag.Companies = new SelectList(db.Companies, "CompanyID", "CompanyName");
        return View();
    }

    //Заносим инфу о вакансии в таблицу
    [HttpPost]
    public ActionResult WelcomeScreen(Interview interview)
    {
        db.Interview.Add(interview);
        db.SaveChanges();

        return RedirectToAction("Index", "Questions", new { id = interview.Interview_Id });
    }
</code>```

My problem in this -  I need to get VacancyId from second dropdownlist and write it to table.

All other data is writing well.

Not writing only VacancyId

Here is code of table

```<code>CREATE TABLE [dbo].[Interviews] (
[Interview_Id] INT            IDENTITY (1, 1) NOT NULL,
[Greeting]     NVARCHAR (MAX) NULL,
[Detail]       NVARCHAR (MAX) NULL,
[VacancyId]    INT            NULL,
PRIMARY KEY CLUSTERED ([Interview_Id] ASC),
CONSTRAINT [FK_Interviews_ToTable] FOREIGN KEY ([VacancyId]) REFERENCES [dbo].[Vacancies] ([VacancyId]) ON DELETE CASCADE);
</code>```

答:
Thank's for all. I solve my problem yesterday

Here is code how to implement this using AJAX, in this AJAX call we get values from fields and pass them to backend.

Here is AJAX code:

```<code> <script>
    $(document).ready(function () {
    $('#save').click(function () {
        save();
    });
});
    function save() {
        $.ajax({
            type: 'Post',
            dataType: 'Json',
            data: {
                Detail: $('#Detail').val(),
                Greeting: $('#Greeting').val(),
                id: $('#vacancy').val(),

            },
            url: '@Url.Action("WelcomeScreenPost", "Questions")',
            success: function (da) {
                if (da.Result === "Success") {

                    window.location.href = da.RedirectUrl;

                } else {

                    alert('Error' + da.Message);
                }
            },
            error: function (da) {
                alert('Error');
            }
        });
    }
</script>
</code>```

On backend we will write this in Controller action method.

```<code> [HttpPost]
   public ActionResult WelcomeScreenPost(string Detail, string Greeting, int id)
    {
        Interview inter = new Interview
        {

            Greeting = Greeting,
            Detail = Detail,
            VacancyId = id,
        };
        db.Interview.Add(inter);
        db.SaveChanges();
        var urlBuilder = new UrlHelper(Request.RequestContext);
        var url = urlBuilder.Action("Index", "Questions", new { id = inter.Interview_Id });
        return Json(new { Result = "Success", Message = "Saved Successfully", RedirectUrl = url });
    }
</code>```

And all will  works well.

Body:
I have Companies table and Vacancies.

Company have some number of Vacancies

I have View like this

So I select company  and second dropdown list is updated depending on company.

Here is View code (DropdownList section )

                    @Html.DropDownList("Company", ViewBag.Companies as SelectList, new { @class = "greeting" })
                    @Html.ValidationMessageFor(model => model.VacancyId, "", new { @class = "text-danger" })

                    <select name="id" id="vacancy" style="width:55%" class="greeting" data-url="@Url.Action("Vacancies","Questions")" />

Here is code for AJAX request

 $(function () {
        $("#Company").change(function (e) {
            var $vacancy = $("#vacancy");
            var url = $vacancy.data("url") + '?companyId=' + $(this).val();
            $.getJSON(url, function (items) {
                $.each(items, function (a, b) {
                    $vacancy.append('<option value="' + b.Value + '">' + b.Text + '</option>');
                });
            });
        });
    });

And here is controller code

 public ActionResult WelcomeScreen()
    {
        // Формируем список команд для передачи в представление
        //SelectList teams = new SelectList(db.Vacancy, "VacancyId", "VacancyName");
        //ViewBag.Teams = teams;

        ViewBag.Companies = new SelectList(db.Companies, "CompanyID", "CompanyName");
        return View();
    }

    //Заносим инфу о вакансии в таблицу
    [HttpPost]
    public ActionResult WelcomeScreen(Interview interview)
    {
        db.Interview.Add(interview);
        db.SaveChanges();

        return RedirectToAction("Index", "Questions", new { id = interview.Interview_Id });
    }

My problem in this -  I need to get VacancyId from second dropdownlist and write it to table.

All other data is writing well.

Not writing only VacancyId

Here is code of table

CREATE TABLE [dbo].[Interviews] (
[Interview_Id] INT            IDENTITY (1, 1) NOT NULL,
[Greeting]     NVARCHAR (MAX) NULL,
[Detail]       NVARCHAR (MAX) NULL,
[VacancyId]    INT            NULL,
PRIMARY KEY CLUSTERED ([Interview_Id] ASC),
CONSTRAINT [FK_Interviews_ToTable] FOREIGN KEY ([VacancyId]) REFERENCES [dbo].[Vacancies] ([VacancyId]) ON DELETE CASCADE);

Body:
Thank's for all. I solve my problem yesterday

Here is code how to implement this using AJAX, in this AJAX call we get values from fields and pass them to backend.

Here is AJAX code:

 <script>
    $(document).ready(function () {
    $('#save').click(function () {
        save();
    });
});
    function save() {
        $.ajax({
            type: 'Post',
            dataType: 'Json',
            data: {
                Detail: $('#Detail').val(),
                Greeting: $('#Greeting').val(),
                id: $('#vacancy').val(),

            },
            url: '@Url.Action("WelcomeScreenPost", "Questions")',
            success: function (da) {
                if (da.Result === "Success") {

                    window.location.href = da.RedirectUrl;

                } else {

                    alert('Error' + da.Message);
                }
            },
            error: function (da) {
                alert('Error');
            }
        });
    }
</script>

On backend we will write this in Controller action method.

 [HttpPost]
   public ActionResult WelcomeScreenPost(string Detail, string Greeting, int id)
    {
        Interview inter = new Interview
        {

            Greeting = Greeting,
            Detail = Detail,
            VacancyId = id,
        };
        db.Interview.Add(inter);
        db.SaveChanges();
        var urlBuilder = new UrlHelper(Request.RequestContext);
        var url = urlBuilder.Action("Index", "Questions", new { id = inter.Interview_Id });
        return Json(new { Result = "Success", Message = "Saved Successfully", RedirectUrl = url });
    }

And all will  works well.


问:
Jquery ajax request not working in IE?
I'm experiencing a strange problem in IE with an ajax request. It works fine in FF and Chrome, but for some reason no data is added to the resultsPage, slideInResults is called, and the empty page appears. Inspecting it I can see there is nothing there. What can I do to fix this?</p>

```<code>$.ajax({
        type: "GET",
        url: "library/ajax/search.php",
        data: dataString,
        cache: false,
        dataType: "html",
        success: function(html){
            $('#resultsPage').html(html);
            slideInResults();
            }
        });
</code>```

答: Report the response of the PHP page by using an Alert. This will assist with you identifying the source of the issue.</p>

Title: Jquery ajax request not working in IE?

Body:
I'm experiencing a strange problem in IE with an ajax request. It works fine in FF and Chrome, but for some reason no data is added to the resultsPage, slideInResults is called, and the empty page appears. Inspecting it I can see there is nothing there. What can I do to fix this?

$.ajax({
        type: "GET",
        url: "library/ajax/search.php",
        data: dataString,
        cache: false,
        dataType: "html",
        success: function(html){
            $('#resultsPage').html(html);
            slideInResults();
            }
        });


问:
RXJS: Single Observable from dynamically created Observables
I am trying to create an observable (fixedObservable here) which will be fed by multiple dynamically created observable over time. Whenever a subscription is made than the subscriber should get the most recent value from the fixedObservable. Although I have achieved it but I wanted to know if there is any simple solution to it. You can find the code here https://jsfiddle.net/dzm2t3pa/8/ .

Thanks

var resultdiv = document.getElementById('result');

function print(message) {
  var paraEl = document.createElement('p');
  paraEl.innerHTML = message;
  resultdiv.appendChild(paraEl);
}
var startTime = new Date();

var fixedObservable = new Rx.Subject();
var subscription;

function subscribe() {
  subscription = fixedObservable.subscribe(function(value) {
    print('subscriber 1:' + value + ' :after ' + (new Date() - startTime) / 1000 + ' secs');
  });
}

function unsubscribe() {
  subscription.unsubscribe();
}
// Subscribe to the fixedObservable(i.e Subject) initiallly
subscribe()

//Unsubscribe and resubscribe after 11 sec here to see what
// happens in that period.
//Observation: The values generated in that period are not received as needed.
setTimeout(unsubscribe, 11000);
setTimeout(subscribe, 22000);

//just a simple check with multiple subscribers later.All the
//subscribers get the latest value.
/*setTimeout(function(){
  fixedObservable.subscribe(function(value){
    print('subscriber 2:'+value+' :after '+(new Date()-startTime)/1000+' secs');
   });
},30000);*/
//setTimeout(function(){},)

//Initial Observables which feed the data to fixedObservable
var dynamicObservable1 = Rx.Observable.interval(4000);
var dynamicObservable2 = Rx.Observable.interval(5000);
var counter1 = 0;
//subscribe to dynamic observable and pass the data to fixedObservable
dynamicObservable1.subscribe(function(value) {
  counter1 += 1;
  fixedObservable.next(counter1 + 'th value from 1');
});
var counter2 = 0;
dynamicObservable2.subscribe(function(value) {
  counter2 += 1;
  fixedObservable.next(counter2 + 'th value from 2');
});

//create a dynamicObservable after 5secs to feed the data and
// then destroy it after 2.5 sec i.e at 7.5 sec from start.
//Observation: 2 value from this stream is received and then stops
setTimeout(function() {
  var counter3 = 0;
  var dynamicObservable3 = Rx.Observable.interval(1000);
  var subs = dynamicObservable3.subscribe(function(value) {
    counter3 += 1;
    fixedObservable.next(counter3 + 'th value from 3');
  });
  setTimeout(function() {
    subs.unsubscribe()
  }, 2500)
}, 5000);

setTimeout(function() {
  unsubscribe();
}, 50000)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.0.1/Rx.min.js"></script>
<div id="result">

</div></code>```

答:
using merge, and no need for a subject i guess.
Is something like that ok for you?</p>

```<code>const dyn1 = Rx.Observable.interval(300)
                      .timeInterval()
                      .map(interval => {return {value:interval.value, origin:'dyn1'}});
const dyn2 = Rx.Observable.interval(601)
                          .timeInterval()
                          .map(interval => {return {value:interval.value, origin:'dyn2'}});

const m = Rx.Observable.merge(dyn1, dyn2);
m.subscribe(v => console.log(v.value + " from " + v.origin));
</code>```

Body:
using merge, and no need for a subject i guess.
Is something like that ok for you?

const dyn1 = Rx.Observable.interval(300)
                      .timeInterval()
                      .map(interval => {return {value:interval.value, origin:'dyn1'}});
const dyn2 = Rx.Observable.interval(601)
                          .timeInterval()
                          .map(interval => {return {value:interval.value, origin:'dyn2'}});

const m = Rx.Observable.merge(dyn1, dyn2);
m.subscribe(v => console.log(v.value + " from " + v.origin));