问:
String is nil when converting back from NSData
I'm attempting to encrypt a hexadecimal string with a C library, a heroic feat that bridges Swift, Objective-C and C.

However the end result when I convert my NSData to a String is nil.

I start with this:

```<code>let fakeHex = "9F1D53E732E48F25F94711D5B22086778278624F715D9B2BEC8FB81134E7C904".toData()
let data = Data(repeating: 1, count: 32)
</code>```

data is a set of 32 true values

fakeHex is a hard-coded hexadecimal that I run through the following extension to UTF8 encode it:

```<code>extension String {

    func toData() -> Data {
        let data = NSMutableData()
        let terminator = [0]
        for char in self {
            let encodedString = String(char).data(using: .utf8)!
            data.append(encodedString)
            data.append(terminator, length: 1)
        }

        return Data(referencing: data)
    }

}
</code>```

Next, I have an Objective-C class called Blakey that takes the hex NSData and the trues NSData and hashes them via the Blake2 hashing algorithm:

```<code>let x = Blakey().createKeyPair(withHexData: fakeHex, andIndexData: data)
</code>```

^ this returns some NSData as well

```<code>- (NSData *)createKeyPairWithHexData:(NSData *)data andIndexData:(NSData *)indexData;
{
    struct blake2b_state__ state;
    blake2b_init(&state, 32);

    blake2b_update(&state, data.bytes, data.length); // data.length is 128
    blake2b_update(&state, indexData.bytes, indexData.length); // indexData.length is 32

    void *foo = malloc(32);
    blake2b_final(&state, foo, 32);

    NSData *accountKey = [NSData dataWithBytes:foo length:32];

    free(foo);

    return accountKey;
}
</code>```

This code is modeled off of what's going on in a companion implementation in Python:

```<code>def seed_account(seed, index):
    # (seed here is our hex string, index is 1)
    # Given an account seed and index #, provide the account private and public keys
    h = blake2b(digest_size=32)

    seed_data = BitArray(hex=seed)
    seed_index = BitArray(int=index,length=32)

    h.update(seed_data.bytes)
    h.update(seed_index.bytes)

    return account_key = BitArray(h.digest())
</code>```

Finally, I take the NSData from the Blakey function and try to turn it into a string:

```<code>NSString(data: x!, encoding: String.Encoding.utf8.rawValue)
String(data: x!, encoding: .utf8)
</code>```

Both print nil.

I'm doing something wrong in the process, not sure what. Would love some help if anything stands out.

Thanks!

答: You append terminator after each character, but you probably want to append it in the end of the string (this one data.append(terminator, length: 1))

Body:
I'm attempting to encrypt a hexadecimal string with a C library, a heroic feat that bridges Swift, Objective-C and C.

However the end result when I convert my NSData to a String is nil.

I start with this:

let fakeHex = "9F1D53E732E48F25F94711D5B22086778278624F715D9B2BEC8FB81134E7C904".toData()
let data = Data(repeating: 1, count: 32)

data is a set of 32 true values

fakeHex is a hard-coded hexadecimal that I run through the following extension to UTF8 encode it:

extension String {

    func toData() -> Data {
        let data = NSMutableData()
        let terminator = [0]
        for char in self {
            let encodedString = String(char).data(using: .utf8)!
            data.append(encodedString)
            data.append(terminator, length: 1)
        }

        return Data(referencing: data)
    }

}

Next, I have an Objective-C class called Blakey that takes the hex NSData and the trues NSData and hashes them via the Blake2 hashing algorithm:

let x = Blakey().createKeyPair(withHexData: fakeHex, andIndexData: data)

^ this returns some NSData as well

- (NSData *)createKeyPairWithHexData:(NSData *)data andIndexData:(NSData *)indexData;
{
    struct blake2b_state__ state;
    blake2b_init(&state, 32);

    blake2b_update(&state, data.bytes, data.length); // data.length is 128
    blake2b_update(&state, indexData.bytes, indexData.length); // indexData.length is 32

    void *foo = malloc(32);
    blake2b_final(&state, foo, 32);

    NSData *accountKey = [NSData dataWithBytes:foo length:32];

    free(foo);

    return accountKey;
}

This code is modeled off of what's going on in a companion implementation in Python:

def seed_account(seed, index):
    # (seed here is our hex string, index is 1)
    # Given an account seed and index #, provide the account private and public keys
    h = blake2b(digest_size=32)

    seed_data = BitArray(hex=seed)
    seed_index = BitArray(int=index,length=32)

    h.update(seed_data.bytes)
    h.update(seed_index.bytes)

    return account_key = BitArray(h.digest())

Finally, I take the NSData from the Blakey function and try to turn it into a string:

NSString(data: x!, encoding: String.Encoding.utf8.rawValue)
String(data: x!, encoding: .utf8)

Both print nil.

I'm doing something wrong in the process, not sure what. Would love some help if anything stands out.

Thanks!


来源: stackexchange

问:
How to make inline plots in Jupyter Notebook larger?
I have made my plots inline on my Ipython Notebook with "%matplotlib inline."

Now, the plot appears.  However, it is very small.  Is there a way to make it appear larger using either notebook settings or plot settings?

答:
The question is about matplotlib, but for the sake of any R users that end up here given the language-agnostic title:

If you're using an R kernel, just use:

```<code>options(repr.plot.width=4, repr.plot.height=3)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The question is about matplotlib, but for the sake of any R users that end up here given the language-agnostic title:

If you're using an R kernel, just use:

options(repr.plot.width=4, repr.plot.height=3)


问:
C++ inserting into an unordered_set breaks my program
I created a custom class and custom hash functions for an unordered_set. Each time I try to insert into that unordered_set, I get a memory error:

```<code>malloc: *** error for object 0x9000000000000000: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
Abort trap: 6
</code>```

It is imperative that I use an unordered_set.

This is my custom class:

```<code>template <class T>
class Seed {

  private:
    Point start;
    int seed_size;
    T** data;
    Seed* seed_match;
    T _value;

  public:
    Seed(int x, int y, int s): seed_size(s), data( new T*[s] ), _value( T() ) {
      start = Point(x, y);
      for ( int i = 0; i < seed_size; i++ )
          data[i] = new T[seed_size];

      for ( int i = 0; i < seed_size; i++ ) {
        for ( int j = 0; j < seed_size; j++ ) data[i][j] = NULL;
      }

      seed_match = NULL;
    }

    ~Seed() {
        for ( int x = 0; x < seed_size; x++ ) {
            delete [] data[x];
        }
      delete [] data;
    }

    void add(int x, int y, T color_val) {
      assert( data[x][y] == NULL );
      data[x][y] = color_val;
      _value += color_val;
    }

    bool match ( const Seed &_match ) {
      if ( seed_match == NULL ) {
        seed_match = &_match;
        return true;
      }
      else return false;
    }

    T get_color(int x, int y) const {
      assert( x >= 0 );
      assert( y >= 0 );
      assert( x < seed_size );
      assert( y < seed_size );

      return data[x][y];
    }

    bool operator==( const Seed<T> &b ) {

      for ( int x = 0; x < seed_size; x++ ) {
        for ( int y = 0; y < seed_size; y++ ) {
          if ( get_color(x, y) != b.get_color(x, y) ) return false;
        }
      }

      return true;

    }

    int seed_value() const { return _value; }

};
</code>```

These are my custom hash functions:

```<code>template <class T>
struct SeedEqualByValue {
public:
    bool operator()(const Seed<T> & seed1, const Seed<T> & seed2) const {

        if (seed1.seed_value() == seed2.seed_value())
            return true;
        else
            return false;
    }
};

template <class T>
struct SeedHashByValue {
public:
    size_t operator()(const Seed<T> & s1) const {
        return std::hash<int>()( s1.seed_value() );
    }
};
</code>```

In my main, I instantiate 3 instances of the Seed class into 3 variables and also instantiate an unordered_set that takes in Seed, with the hash function as my SeedHashByValue struct and my compare function as SeedEqualByValue struct.
After creating the unordered_map, anytime I insert a Seed object into the unordered_map, I get an malloc error and I am not sure how to fix this.

These are the contents of my main function:

```<code>Seed<int> b(0, 0, 5);
Seed<int> a(0, 0, 5);
Seed<int> c(0, 0, 5);
c.add(4, 4, 100);
a.add(1, 2, 4);
a.add(1, 1, 3);
b.add(1, 1, 3);
unordered_set<Seed<int>, SeedHashByValue<int>, SeedEqualByValue<int> > seeds;
seeds.insert(c);
</code>```

Also, Point is just a class that holds x and y values with public member variables int x and int y, in case anyone needed clarification.

答:
To follow-up on what @Algirdas said, I believe what's happening is that the Seed is shallow-copied into the set, so you end up with a double delete on the same parent pointer, once when the set goes out of scope, and once when the variable goes out of scope.

You'll need to modify how you are handling the data by either transferring it in the assignment operator or by using something like a std::unique_ptr and making sure that it is assigned (which by default transfers ownership).

Body:
I created a custom class and custom hash functions for an unordered_set. Each time I try to insert into that unordered_set, I get a memory error:

malloc: *** error for object 0x9000000000000000: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
Abort trap: 6

It is imperative that I use an unordered_set.

This is my custom class:

template <class T>
class Seed {

  private:
    Point start;
    int seed_size;
    T** data;
    Seed* seed_match;
    T _value;

  public:
    Seed(int x, int y, int s): seed_size(s), data( new T*[s] ), _value( T() ) {
      start = Point(x, y);
      for ( int i = 0; i < seed_size; i++ )
          data[i] = new T[seed_size];

      for ( int i = 0; i < seed_size; i++ ) {
        for ( int j = 0; j < seed_size; j++ ) data[i][j] = NULL;
      }

      seed_match = NULL;
    }

    ~Seed() {
        for ( int x = 0; x < seed_size; x++ ) {
            delete [] data[x];
        }
      delete [] data;
    }

    void add(int x, int y, T color_val) {
      assert( data[x][y] == NULL );
      data[x][y] = color_val;
      _value += color_val;
    }

    bool match ( const Seed &_match ) {
      if ( seed_match == NULL ) {
        seed_match = &_match;
        return true;
      }
      else return false;
    }

    T get_color(int x, int y) const {
      assert( x >= 0 );
      assert( y >= 0 );
      assert( x < seed_size );
      assert( y < seed_size );

      return data[x][y];
    }

    bool operator==( const Seed<T> &b ) {

      for ( int x = 0; x < seed_size; x++ ) {
        for ( int y = 0; y < seed_size; y++ ) {
          if ( get_color(x, y) != b.get_color(x, y) ) return false;
        }
      }

      return true;

    }

    int seed_value() const { return _value; }

};

These are my custom hash functions:

template <class T>
struct SeedEqualByValue {
public:
    bool operator()(const Seed<T> & seed1, const Seed<T> & seed2) const {

        if (seed1.seed_value() == seed2.seed_value())
            return true;
        else
            return false;
    }
};

template <class T>
struct SeedHashByValue {
public:
    size_t operator()(const Seed<T> & s1) const {
        return std::hash<int>()( s1.seed_value() );
    }
};

In my main, I instantiate 3 instances of the Seed class into 3 variables and also instantiate an unordered_set that takes in Seed, with the hash function as my SeedHashByValue struct and my compare function as SeedEqualByValue struct.
After creating the unordered_map, anytime I insert a Seed object into the unordered_map, I get an malloc error and I am not sure how to fix this.

These are the contents of my main function:

Seed<int> b(0, 0, 5);
Seed<int> a(0, 0, 5);
Seed<int> c(0, 0, 5);
c.add(4, 4, 100);
a.add(1, 2, 4);
a.add(1, 1, 3);
b.add(1, 1, 3);
unordered_set<Seed<int>, SeedHashByValue<int>, SeedEqualByValue<int> > seeds;
seeds.insert(c);

Also, Point is just a class that holds x and y values with public member variables int x and int y, in case anyone needed clarification.


问:
Fast hill climbing algorithm that can stabilize when near optimal
I have a floating point number x from [1, 500] that generates a binary y of 1 at some probability p. And I'm trying to find the x that can generate the most 1 or has highest p. I'm assuming there's only one maximum.

Is there a algorithm that can converge fast to the x with highest p while making sure it doesn't jump around too much after it's achieved for e.x. within 0.1% of the optimal x? Specifically, it would be great if it stabilizes when near < 0.1% of optimal x.

I know we can do this with simulated annealing but I don't think I should hard code temperature because I need to use the same algorithm when x could be from [1, 3000] or the p distribution is different.

答:
This paper provides an for smart hill-climbing algorithm. The idea is  basically you take n samples as starting points. The algorithm is as follows (it is simplified into one dimensional for your problem):

Take n sample points in the search space. In the paper, he uses Linear Hypercube Sampling since the dimensions of the data in the paper is assumed to be large. In your case, since it is one-dimensional, you can just use random sapling as usual.

For each sample points, gather points from its "local neighborhood" and find a best fit quadratic curve. Find the new maximum candidate from the quadratic curve. If the objective function of the new maximum candidate is actually higher than the previous one, update the sample point to the new maximum candidate. Repeat this step with smaller "local neighborhood" size for each iteration.

Use the best point from the sample points

Restart: repeat step 2 and 3, and then compare the maximums. If there is no improvement, stop. If there is improvement, repeat again.


问:
React-native StackNavigation pass props
I'm building an app in react-native and I'm trying to put navigation into it. I have a button and I want to move to another page by clicking on it.
But I got that error : undefined is not an object (evaluating '_this.props.navigation')

App.js :

```<code>import React, { Component } from 'react';
import { View } from 'react-native';
import YTSearch from 'youtube-api-search';
import AppHeader from './components/AppHeader';
import SearchBar from './components/SearchBar';
import VideoList from './components/VideoList';
import TrackPlayerScreen from './Screens/TrackPlayerScreen';
import VideoListItems from './components/VideoListItems';

import {StackNavigator}  from 'react-navigation';

const AppNavigator = StackNavigator({
  VideoListItems: { screen: VideoListItems, navigationOptions: { header: null } },
  TrackPlayerScreen: { screen: TrackPlayerScreen,navigationOptions: { header: null } }
});

const API_KEY = 'APIKEY;

export default class App extends Component {
  state = {
    loading: false,
    videos: []
  }

  componentWillMount(){
    this.searchYT('');
  }

  onPressSearch = term => {
    this.searchYT(term);
  }

  searchYT = term => {
    this.setState({ loading: true });
    YTSearch({key: API_KEY, term }, videos => {
      console.log(videos);
      this.setState({
        loading: false,
        videos
      });
    });
  }

  render() {
    const { loading, videos } = this.state;
    return (
      <View style={{ flex: 1, backgroundColor: '#ddd' }}>

        <AppHeader headerText="Project Master Sound Control" />
        <SearchBar
        loading={loading}
        onPressSearch={this.onPressSearch} />
        <VideoList videos={videos} />
      </View>
    );
  }
}
</code>```

File where button will navigate to another page by clicking on it VideoListItems :

```<code>import React from 'react';
import { View, Text, Image } from 'react-native';
import { Card } from 'react-native-elements';
import TrackPlayerScreen from '../Screens/TrackPlayerScreen';
import { Button } from 'react-native-elements';
import { WebBrowser } from 'expo';
import {StackNavigator}  from 'react-navigation';

const VideoListItems = ({ video }) => {
    const {
        cardStyle,
        imageStyle,
        contentStyle,
        titleStyle,
        channelTitleStyle,
        descriptionStyle
     } = styles;
    const {
        title,
        channelTitle,
        description,
        thumbnails: { medium: { url } }
    } = video.snippet;

    const videoId = video.id.videoId;

    return(
        <View>
             <Card title={null} containerStyle={cardStyle}>
                <Image
                    style={imageStyle}
                    source= {{ uri: url}}
                />
                <View style={contentStyle}>
                    <Text style={titleStyle}>
                        {title}
                    </Text>
                    <Text style={channelTitleStyle}>
                        {channelTitle}
                    </Text>
                    <Text style={descriptionStyle}>
                        {description}
                    </Text>
                    <Button
                      raised
                      title="Save And Play"
                      icon={{ name: 'play-arrow' }}
                      containerViewStyle={{ marginTop: 10 }}
                      backgroundColor="#E62117"
                      onPress={() => {
                        this.props.navigation.navigate('InformationScreen')
                      }}
                    />

                </View>
             </Card>
        </View>
    );
};
export default VideoListItems;
</code>```

I'm having trouble of how to pass the navigation props to my VideoListItems, anyone any ideas ? Or am I missing something somewhere else ?

答:
React functional form won't generate an object with this, you have to make it a class:

class VideoListItems extends Component {
    render() {
        /// this.props.navigation.navigate should works here
    }
};
```

Title: React-native StackNavigation pass props

Body:
I'm building an app in react-native and I'm trying to put navigation into it. I have a button and I want to move to another page by clicking on it.
But I got that error : undefined is not an object (evaluating '_this.props.navigation')

App.js :

import React, { Component } from 'react';
import { View } from 'react-native';
import YTSearch from 'youtube-api-search';
import AppHeader from './components/AppHeader';
import SearchBar from './components/SearchBar';
import VideoList from './components/VideoList';
import TrackPlayerScreen from './Screens/TrackPlayerScreen';
import VideoListItems from './components/VideoListItems';

import {StackNavigator}  from 'react-navigation';

const AppNavigator = StackNavigator({
  VideoListItems: { screen: VideoListItems, navigationOptions: { header: null } },
  TrackPlayerScreen: { screen: TrackPlayerScreen,navigationOptions: { header: null } }
});

const API_KEY = 'APIKEY;

export default class App extends Component {
  state = {
    loading: false,
    videos: []
  }

  componentWillMount(){
    this.searchYT('');
  }

  onPressSearch = term => {
    this.searchYT(term);
  }

  searchYT = term => {
    this.setState({ loading: true });
    YTSearch({key: API_KEY, term }, videos => {
      console.log(videos);
      this.setState({
        loading: false,
        videos
      });
    });
  }

  render() {
    const { loading, videos } = this.state;
    return (
      <View style={{ flex: 1, backgroundColor: '#ddd' }}>

        <AppHeader headerText="Project Master Sound Control" />
        <SearchBar
        loading={loading}
        onPressSearch={this.onPressSearch} />
        <VideoList videos={videos} />
      </View>
    );
  }
}

File where button will navigate to another page by clicking on it VideoListItems :

import React from 'react';
import { View, Text, Image } from 'react-native';
import { Card } from 'react-native-elements';
import TrackPlayerScreen from '../Screens/TrackPlayerScreen';
import { Button } from 'react-native-elements';
import { WebBrowser } from 'expo';
import {StackNavigator}  from 'react-navigation';

const VideoListItems = ({ video }) => {
    const {
        cardStyle,
        imageStyle,
        contentStyle,
        titleStyle,
        channelTitleStyle,
        descriptionStyle
     } = styles;
    const {
        title,
        channelTitle,
        description,
        thumbnails: { medium: { url } }
    } = video.snippet;

    const videoId = video.id.videoId;

    return(
        <View>
             <Card title={null} containerStyle={cardStyle}>
                <Image
                    style={imageStyle}
                    source= {{ uri: url}}
                />
                <View style={contentStyle}>
                    <Text style={titleStyle}>
                        {title}
                    </Text>
                    <Text style={channelTitleStyle}>
                        {channelTitle}
                    </Text>
                    <Text style={descriptionStyle}>
                        {description}
                    </Text>
                    <Button
                      raised
                      title="Save And Play"
                      icon={{ name: 'play-arrow' }}
                      containerViewStyle={{ marginTop: 10 }}
                      backgroundColor="#E62117"
                      onPress={() => {
                        this.props.navigation.navigate('InformationScreen')
                      }}
                    />

                </View>
             </Card>
        </View>
    );
};
export default VideoListItems;

I'm having trouble of how to pass the navigation props to my VideoListItems, anyone any ideas ? Or am I missing something somewhere else ?


问:
post params not being stored in Mongo db
I'm trying to build a simple blog with a MEAN stack and I'm currently setting up the back end. I'm testing my routes with Postman and for some reason, I can't save the title and body of a post in the DB.

My model:
models/posts/db.js

```<code>var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var PostSchema = new Schema ({
  title: { type: String },
  body: { type: String },
  date: { type: Date, default: Date.now }
});

module.exports = mongoose.model('Post', PostSchema);
</code>```

My controller: controllers/posts.index.js

```<code>var base = process.env.PWD;
var Post = require(base + '/models/posts/db.js')

var createPost = function(req, res) {
  var post = new Post(req.body)

  post.save(function(err, post) {
    if(err) { res.sendStatus(500, err); }
    res.json(post);
  })
}

var getPosts = function(req, res) {
  Post.find(function(err, posts) {
    if (err) { res.sendStatus(500, err); }
    res.json(posts);
  })
};

module.exports = {
  createPost,
  getPosts
}
</code>```

And here are my main routes in routes/index.js

```<code>router.get('/posts', posts.getPosts);
router.post('/posts/create', posts.createPost);

module.exports = router;
</code>```

And my main server is using a /api endpoint:

```<code>`app.use('/api', routes);`
</code>```

So in Postman, when I send a POST request to /api/posts/create with a post containing a title and a body, an empty post is stored. I get something like this inserted:

```<code>{
    "__v": 0,
    "_id": "5a29de91521f168eb9e1bcf2",
    "date": "2017-12-08T00:36:33.280Z"
}
</code>```

Any help would be appreciated.

答:
It looks like the Post may not be getting the body of your actual post. You can fill the body property on your request with the body-parser module. Do an npm install body-parser and add this to your code:

```<code>const bodyParser = require('body-parser')
app.use(bodyParser.json())
</code>```

Body:
I'm trying to build a simple blog with a MEAN stack and I'm currently setting up the back end. I'm testing my routes with Postman and for some reason, I can't save the title and body of a post in the DB.

My model:
models/posts/db.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var PostSchema = new Schema ({
  title: { type: String },
  body: { type: String },
  date: { type: Date, default: Date.now }
});

module.exports = mongoose.model('Post', PostSchema);

My controller: controllers/posts.index.js

var base = process.env.PWD;
var Post = require(base + '/models/posts/db.js')

var createPost = function(req, res) {
  var post = new Post(req.body)

  post.save(function(err, post) {
    if(err) { res.sendStatus(500, err); }
    res.json(post);
  })
}

var getPosts = function(req, res) {
  Post.find(function(err, posts) {
    if (err) { res.sendStatus(500, err); }
    res.json(posts);
  })
};

module.exports = {
  createPost,
  getPosts
}

And here are my main routes in routes/index.js

router.get('/posts', posts.getPosts);
router.post('/posts/create', posts.createPost);

module.exports = router;

And my main server is using a /api endpoint:

`app.use('/api', routes);`

So in Postman, when I send a POST request to /api/posts/create with a post containing a title and a body, an empty post is stored. I get something like this inserted:

{
    "__v": 0,
    "_id": "5a29de91521f168eb9e1bcf2",
    "date": "2017-12-08T00:36:33.280Z"
}

Any help would be appreciated.

Body:
It looks like the Post may not be getting the body of your actual post. You can fill the body property on your request with the body-parser module. Do an npm install body-parser and add this to your code:

const bodyParser = require('body-parser')
app.use(bodyParser.json())


问:
Drupal 6: in hook_cron, how do I specify the path to a module file?
In my .module file, I have an basic implementation of hook_cron:

```<code>function foobar_cron()
{
    $file = fopen('my_file', 'a');
    // stuff
    fclose($file);
}
</code>```

The problem is that this method is called by (http://www.example.com/)cron.php, so the path my_file is incorrect. How do I specify the correct path for my_file which is located in the foobar module directory?

答:
I found out that you can use following code to access files in your module's directory when implementing hook_cron():

```<code>function foobar_cron()
{
        $file = fopen(realpath(".") . PATH_SEPARATOR . drupal_get_path('module', 'foobar') . PATH_SEPARATOR . 'myfile.txt', 'a');
}
</code>```

PATH_SEPARATOR makes sure the path also works on Windows.

ContentLicense: CC BY-SA 2.5

Body:
In my .module file, I have an basic implementation of hook_cron:

function foobar_cron()
{
    $file = fopen('my_file', 'a');
    // stuff
    fclose($file);
}

The problem is that this method is called by (http://www.example.com/)cron.php, so the path my_file is incorrect. How do I specify the correct path for my_file which is located in the foobar module directory?

Body:
I found out that you can use following code to access files in your module's directory when implementing hook_cron():

function foobar_cron()
{
        $file = fopen(realpath(".") . PATH_SEPARATOR . drupal_get_path('module', 'foobar') . PATH_SEPARATOR . 'myfile.txt', 'a');
}

PATH_SEPARATOR makes sure the path also works on Windows.


问:
How to change provisioning profile for existing app?
I have never developed apps for iPhone, but our client has an app, which was developed by his previous vendor, now that vendor has wrapped up his operation from our country, So now we have that source code for that app for further development. The immediate action we need to take is that the app is not running on iOS 11.0 and we need to provide build for 11.0.

So I opened the app in Xcode and set deployment target to iOS 11, the app build was successful and it is running on the simulator, So I thought lets check it on real device, but when I connected a device and asked Xcode to build and deploy on my device I received the error.

No profile for team '***********' matching 'PROTEST' found:  Xcode couldn't find any provisioning profiles matching '***********/PROTEST'. Install the profile (by dragging and dropping it onto Xcode's dock item) or select a different one in the General tab of the target editor.

Code signing is required for product type 'Application' in SDK 'iOS 11.1'

So as I have understood I need to create provisioning profile for app development for iOS.

Can someone please guide me, I need to know, how to create a provisioning profile and how should I use for existing project which was developed by someone else before.

NOTE: the *********** represent the key or provisioning profile ID, I am not really sure but I thought I should censor it.

答:
Follow these steps :

Login to the developer.apple.com/membercenter and generate the Certificate, APP ID, Provisioning profile (Developer, Distribution) as your needs. Refer Apple development doc for details: https://developer.apple.com/library/content/documentation/IDEs/Conceptual/AppDistributionGuide/MaintainingProfiles/MaintainingProfiles.html

In that dev-account register your device UUID and add that when you are creating a developer profile, distribution may not require though(if its enterprise account and you creating Universal distribution profile).

Do this in your project now

Go to your App --> Click project on left project navigator window

Check on the right side you will see project settings

Click general tab and enter the bundle identifier as the APP ID you
just created in step 1 above from dev account.

Now select the checkbox "Automatic provisioning" this is an easy way to automatically pick the profile from the developer account that you have used for appID creation. (note go to your Xcode preference and Accounts tab to enter the same dev-account credentials so XCode can automatically download and create profiles for you)

Now connect your device and you should see the device reflected to the top left corner.

Run the project and you will see the app is getting installed on the device.

Code signing is required for product type 'Application' in SDK 'iOS 11.1' -- For this you just make sure all the Pods and libraries are having to Do not Code sign set to the build settings area and only the App and extensions if any are signed with the right certificate you created from apple.

Also, note on this: If the previous vendor has released the binary from his apple account, you cannot create the same bundle ID with your apple account. Hence you end up having this as a new app on AppStore unless the vendor revokes/delete the bundle Id from this account.

Hope this helps.


问:
Can methods be added to an object?
So we have a class, Customer. I don't have any choice but to use Customer to represent any Customer I have, including in the signature of any methods, etc I write. But my data is slightly different; I still want much of the functionality inside Customer, but some fields I need to sorta bastardize for my special case. Example:

```<code>class Customer
{
public:
  string GetName();
  void SetName(string _name);

  string GetAge();
  void SetAge(string _age);

protected:
  string name;
  string age;
};

class SpecialCustomer : public Customer
{
public:
  string GetAddress();
  void SetAddress(string _address);
}
</code>```

So this all seems rather simple, but the problem I have is I am forced to pass around Customers. But as luck would  have it, in my special case, I don't need age at all! So what I need to do is re-use the age data member to hold my address. Yes, I know it's bad. No, I can't change the requirements - my special data has to fit into a Customer object.

So to do this, I could of course just construct a SpecialCustomer from a Customer, but I'd like to avoid the copy. (edit: Also, many data members are exposed directly publicly, so I can't use composition and support their use) Instead, I considered making SpecialCustomer a wrapper, exposing the pieces of functionality I want. The problem is the real implementation of Customer is not trivial - it's be a bit of work to re-implement the whole interface, minus the fields I don't want.

The only way that jumps to mind to achieve this is with something like this:

```<code>void foo (Customer & _c)
{
  SpecialCustomer & sc = reinterpret_cast<SpecialCustomer &>(_c);
}
</code>```

Obviously if SpecialCustomer has any virtual methods or data members, this won't work. But what if it is just a set of methods I want available on the object? Is there a better alternative to achieve this functionality?

答:
This ought to do it, using composition instead of inheritance.

```<code>class SpecialCustomer {
public:
    SpecialCustomer(Customer&) : _customer(customer) {}

    string getAge() { return customer.GetAge(); }

private:
    Customer& _customer;

}
</code>```

No casting is needed at this point. Rather instantiating the wrapper class will be adequate.

Usage:

```<code>void foo (Customer & _c)
{
    SpecialCustomer sc(_c);
}
</code>```

Title: Can methods be added to an object?

Body:
So we have a class, Customer. I don't have any choice but to use Customer to represent any Customer I have, including in the signature of any methods, etc I write. But my data is slightly different; I still want much of the functionality inside Customer, but some fields I need to sorta bastardize for my special case. Example:

class Customer
{
public:
  string GetName();
  void SetName(string _name);

  string GetAge();
  void SetAge(string _age);

protected:
  string name;
  string age;
};

class SpecialCustomer : public Customer
{
public:
  string GetAddress();
  void SetAddress(string _address);
}

So this all seems rather simple, but the problem I have is I am forced to pass around Customers. But as luck would  have it, in my special case, I don't need age at all! So what I need to do is re-use the age data member to hold my address. Yes, I know it's bad. No, I can't change the requirements - my special data has to fit into a Customer object.

So to do this, I could of course just construct a SpecialCustomer from a Customer, but I'd like to avoid the copy. (edit: Also, many data members are exposed directly publicly, so I can't use composition and support their use) Instead, I considered making SpecialCustomer a wrapper, exposing the pieces of functionality I want. The problem is the real implementation of Customer is not trivial - it's be a bit of work to re-implement the whole interface, minus the fields I don't want.

The only way that jumps to mind to achieve this is with something like this:

void foo (Customer & _c)
{
  SpecialCustomer & sc = reinterpret_cast<SpecialCustomer &>(_c);
}

Obviously if SpecialCustomer has any virtual methods or data members, this won't work. But what if it is just a set of methods I want available on the object? Is there a better alternative to achieve this functionality?

Body:
This ought to do it, using composition instead of inheritance.

class SpecialCustomer {
public:
    SpecialCustomer(Customer&) : _customer(customer) {}

    string getAge() { return customer.GetAge(); }

private:
    Customer& _customer;

}

No casting is needed at this point. Rather instantiating the wrapper class will be adequate.

Usage:

void foo (Customer & _c)
{
    SpecialCustomer sc(_c);
}


问:
Login My User name share point its showing System Login Name
enter image description hereI am working with Sharepoint 2013, when logging in My Username (Username) and password (Password) its login successfully, after Login the screen right hand side its shows e system login Name like "System/Account" and Permission level also taken System Login only, not for my Login ID

Important Note : I don't have Admin access to check for share point server.

答: Your account may be a farm admin account or an app pool account.  </p>


问:
Logging into a VM to run GUI tests at test startup
We are setting up our automation to run remotely so we can start incorporating them into the builds (you know, the whole CI/CD thing). These are a handful of important automated GUI tests that for obvious reasons, need an active VM to run. These are not browser tests, they are actually automated tests for a windows application so any support that Selenium brings to the table is off for us.

So now on to the challenge - how can I keep the VMs up and running without having to log into them using the Remote Desktop Connection to allow them to run the tests properly. Currently, I have to connect to them from my local machine and then minimize it and then I can kick off the builds. As soon as I exit however, the virtual machine is locked again.

I want the VMs to work completely independently from my machine, so I was skeptical about this approach because it seemed like it would still be tied to my machine only. Pretty much anyone in the company can log into the VMs from their machine using their credentials. What I would like to do is to programatically connect to the VM during my global TestStartup and then disconnect at TearDown. Is this possible to do? Has anyone had success or ran into similar situations with their automation integration process? We use a tool called LeanFT and NUnit as our test runner. .

答:
Your idea to log in as part of the test is a bit fragile and prone to instabilities.

Here is the setup that works for every UI automation tool I've used for Windows

set up your VM to not lock / sleep /hibernate, etc.

Avoid using RDC (turn that feature off, even for admins if you can)

Only use the console viewer for your vm server

Limit access to those systems using the permissions in the VM server so that only you and your team can interact with them.

Here is why this works. You have already discovered that when you disconnect the RDP connection, the session locks and your automation fails. By using the vm console viewer, it's essentially like turning on/off the monitor connected to the system. By keeping them on all the time and not sleeping, they are always available for running tests.

We are using LeanFT and to encourage the stability of our tests, we have setup tasks to check the running processes to kill any stray leanft runtimes that didn't get closed cleanly from a prior run, as well as any stray applications that were not closed properly after a testing run.


问:
Getting incorrect sort order
Failing test case:

Input:
[-2147483648,1,1]

Output:
-2147483648

Expected:
1

Why is the output expected as 1 when -2147483648 is the 2nd max number here?

```<code>public int thirdMax(int[] nums) {

    PriorityQueue<Integer> pq = new PriorityQueue(new Comparator<Integer>(){
        public int compare(Integer a, Integer b){return b-a;}
    });

    int res=0;

    for(int num : nums){
        if(!pq.contains(num)  )
            pq.add(num);

    }

    if(pq.size()<=2){
       for(int i=0; i<pq.size(); i++){
            res=pq.poll();
        }
    }
    else {
        for(int i=0; i<3; i++){
            res=pq.poll();
        }
    }
    return res;
}
</code>```

答:
Your method of comparing isn't correct for int.

Rather than:

```<code>return b - a;
</code>```

you should do:

```<code>return Integer.compare(b, a);
</code>```

An int can only hold values of up to Integer.MAX_VALUE. But if you do 1 - -2147483648, the result is greater than Integer.MAX_VALUE, which makes it negative again - and you get wrong sort orders as a result. Basically, return b - a; is only safe if you know that all numbers are positive (or if the numbers won't be further apart than Integer.MAX_VALUE).

In other cases, you can use the API method Integer.compare.

Note that, since you are comparing by the inverse of the natural order of integers, you can also shorten your code with:

```<code>PriorityQueue<Integer> pq = new PriorityQueue<>(Comparator.reverseOrder());
</code>```

Title: Getting incorrect sort order

Body:
Failing test case:

Input:
[-2147483648,1,1]

Output:
-2147483648

Expected:
1

Why is the output expected as 1 when -2147483648 is the 2nd max number here?

public int thirdMax(int[] nums) {

    PriorityQueue<Integer> pq = new PriorityQueue(new Comparator<Integer>(){
        public int compare(Integer a, Integer b){return b-a;}
    });

    int res=0;

    for(int num : nums){
        if(!pq.contains(num)  )
            pq.add(num);

    }

    if(pq.size()<=2){
       for(int i=0; i<pq.size(); i++){
            res=pq.poll();
        }
    }
    else {
        for(int i=0; i<3; i++){
            res=pq.poll();
        }
    }
    return res;
}

Body:
Your method of comparing isn't correct for int.

Rather than:

return b - a;

you should do:

return Integer.compare(b, a);

An int can only hold values of up to Integer.MAX_VALUE. But if you do 1 - -2147483648, the result is greater than Integer.MAX_VALUE, which makes it negative again - and you get wrong sort orders as a result. Basically, return b - a; is only safe if you know that all numbers are positive (or if the numbers won't be further apart than Integer.MAX_VALUE).

In other cases, you can use the API method Integer.compare.

Note that, since you are comparing by the inverse of the natural order of integers, you can also shorten your code with:

PriorityQueue<Integer> pq = new PriorityQueue<>(Comparator.reverseOrder());


问:
Ways to make one line in console window disappear after a couple seconds?
I need to basically flash a set of numbers for roughly 2 seconds. The user will then have to remember the numbers and type them. How can I do this? I have tried to use a timer or changing the color of the text to the same color of the background, but I can't think of a better way of doing so. Any suggestions?</p>

答:
You have basically three ways of handling this, because typical terminals don't have have the concept of a "screen", just lines.

Use carriage return or backspace characters to overwrite previous characters with blank spaces (but note the user can hit Enter to "preserve" the data in this case).

Print out a bunch of empty lines afterwards, but the user can scroll back.

Use a curses library of some kind (probably ncurses).

You'll need to look at the choices and see which is the best fit for exactly what you are trying to achieve.


问:
AWS Cognito Federated Identity Pool - Role on Authentication
I have 2 identity pools - one for Unauth (with only Unauth role set) and other for Federated Identities (FB and Google - with only Auth role set).

I have an iOS app in with 2 classes implementing AWSIdentityProviderManager protocol - GuestProvider which returns an empty logins and FBProvider which populates the FB token in logins.

When I launch the app and browse as guest, it works, Similarly if I launch the app and directly login to FB, it also works with proper auth role.

The problem comes when I login as Guest and then switch to FB - though I get the Auth token and set it in Provider and update the defaultServiceConfiguration, but Lambda invoke fails with AccessDenied error - logs show it still has the unauth role. This does not happen if I launch the app and login via FB (not going to Guest first).

These are the functions that set the AWS config for resp use case:

```<code>func initializeGuestCredentialsProvider() {
// AWS
credentialsProvider = AWSCognitoCredentialsProvider(
regionType: Constants.AWS_REGION,
identityPoolId: Constants.COGNITO_UNAUTH_IDENTITY_POOL_ID);

let configuration = AWSServiceConfiguration(
region: Constants.AWS_REGION,
credentialsProvider: credentialsProvider
);

AWSServiceManager.default().defaultServiceConfiguration = configuration
}

func initializeFBCredentialsProvider() {
credentialsProvider = AWSCognitoCredentialsProvider(
regionType: Constants.AWS_REGION,
identityPoolId: Constants.COGNITO_IDENTITY_POOL_ID,
identityProviderManager: FacebookProvider());

let configuration = AWSServiceConfiguration(
region: AWSRegionType.USWest2,
credentialsProvider: credentialsProvider
);

AWSServiceManager.default().defaultServiceConfiguration = configuration

}
</code>```

I am not sure what could be the reason for this error. Possibly the first credentials provider that has been set in config, can not be changed ?

答: I would suggest using a single identity pool. When a user switches from Guest to Authenticated, then just pass the identityId and the provider token (in the logins map) to GetCredentialsForIdentity. This would link the same identityId to the provider (Facebook) user.</p>

Body:
I have 2 identity pools - one for Unauth (with only Unauth role set) and other for Federated Identities (FB and Google - with only Auth role set).

I have an iOS app in with 2 classes implementing AWSIdentityProviderManager protocol - GuestProvider which returns an empty logins and FBProvider which populates the FB token in logins.

When I launch the app and browse as guest, it works, Similarly if I launch the app and directly login to FB, it also works with proper auth role.

The problem comes when I login as Guest and then switch to FB - though I get the Auth token and set it in Provider and update the defaultServiceConfiguration, but Lambda invoke fails with AccessDenied error - logs show it still has the unauth role. This does not happen if I launch the app and login via FB (not going to Guest first).

These are the functions that set the AWS config for resp use case:

func initializeGuestCredentialsProvider() {
// AWS
credentialsProvider = AWSCognitoCredentialsProvider(
regionType: Constants.AWS_REGION,
identityPoolId: Constants.COGNITO_UNAUTH_IDENTITY_POOL_ID);

let configuration = AWSServiceConfiguration(
region: Constants.AWS_REGION,
credentialsProvider: credentialsProvider
);

AWSServiceManager.default().defaultServiceConfiguration = configuration
}

func initializeFBCredentialsProvider() {
credentialsProvider = AWSCognitoCredentialsProvider(
regionType: Constants.AWS_REGION,
identityPoolId: Constants.COGNITO_IDENTITY_POOL_ID,
identityProviderManager: FacebookProvider());

let configuration = AWSServiceConfiguration(
region: AWSRegionType.USWest2,
credentialsProvider: credentialsProvider
);

AWSServiceManager.default().defaultServiceConfiguration = configuration

}

I am not sure what could be the reason for this error. Possibly the first credentials provider that has been set in config, can not be changed ?


问:
Endless carousel with Onsen UI
Is it possible to make the carousel in onsen framework endless? So that when I overscroll the last element to the right that the first element will be displayed?
I made it in that way, but it is not seemless:

```<code>ons.ready(function () {
    carousel.on("overscroll", function (event) {
        if (event.direction == "right") {
            carousel.first();
        } else {
            carousel.last();
        }
    });
});
</code>```

Thank you for tips.

答:
Just give function and attribute overscroll to your carousel :

```<code><ons-carousel var="carousel" ons-overscroll="over($event.activeIndex)" swipeable ....
</code>```

and in your controller :

```<code>$scope.over = function(idx) { if(idx==0){carousel.last();}else{carousel.first();} }
</code>```

It also can be implemented to button for example in ons-carousel-cover :

```<code><ons-carousel-cover>
    <div class="cover-label">
        <ons-button modifier="quiet" ng-click="prev(carousel.getActiveIndex());"> prev </ons-button>
        Swipe left or right
        <ons-button modifier="quiet" ng-click="next(carousel.getActiveIndex());;"> next </ons-button>
    </div>
</ons-carousel-cover>
</code>```

and in your controller (for example 4 item of carousel {max_index=3}):

```<code>$scope.prev = function(idx) { if(idx==0){carousel.last();}else{carousel.prev();} }
$scope.next = function(idx) { if(idx==3){carousel.first();}else{carousel.next();} }
</code>```

css for beauty :

```<code>.cover-label {
  text-align: center;
  position: absolute;
  left: 0px;
  width: 100%;
  bottom: 10px;
  color: white;
}
</code>```

Hope it Helps.

Title: Endless carousel with Onsen UI

Body:
Is it possible to make the carousel in onsen framework endless? So that when I overscroll the last element to the right that the first element will be displayed?
I made it in that way, but it is not seemless:

ons.ready(function () {
    carousel.on("overscroll", function (event) {
        if (event.direction == "right") {
            carousel.first();
        } else {
            carousel.last();
        }
    });
});

Thank you for tips.

Body:
Just give function and attribute overscroll to your carousel :

<ons-carousel var="carousel" ons-overscroll="over($event.activeIndex)" swipeable ....

and in your controller :

$scope.over = function(idx) { if(idx==0){carousel.last();}else{carousel.first();} }

It also can be implemented to button for example in ons-carousel-cover :

<ons-carousel-cover>
    <div class="cover-label">
        <ons-button modifier="quiet" ng-click="prev(carousel.getActiveIndex());"> prev </ons-button>
        Swipe left or right
        <ons-button modifier="quiet" ng-click="next(carousel.getActiveIndex());;"> next </ons-button>
    </div>
</ons-carousel-cover>

and in your controller (for example 4 item of carousel {max_index=3}):

$scope.prev = function(idx) { if(idx==0){carousel.last();}else{carousel.prev();} }
$scope.next = function(idx) { if(idx==3){carousel.first();}else{carousel.next();} }

css for beauty :

.cover-label {
  text-align: center;
  position: absolute;
  left: 0px;
  width: 100%;
  bottom: 10px;
  color: white;
}

Hope it Helps.


问:
JQuery Default text on empty text box
I have a email form text box that while it is empty I would like it to have the value "E-Mail" And when you click on it the text goes away. If someone clicks on it and doesn't enter text. on Blur I would like for it to return to having the default text.

I have been trying a few things but nothing is working. Could someone please point me in the right direction?

答:
Call the below function and pass it two args: slightLabel(jQuery('#email_field'), 'email');</p>

```<code>  function slightLabel(input, text) {
        jQuery(input).val(text);
        jQuery(input).data('defaultText', text);
        jQuery(input).focus(function(){
            if(!jQuery(this).data('touched'))
            {
                jQuery(this).data('touched', true);
                jQuery(input).val('');
            }
        });

        // the part to restore the original text in
        jQuery(input).blur(function(){
            if(jQuery(this).val() == '')
            {
                jQuery(this).val(jQuery(this).data('defaultText'));
            }
        });

    }
</code>```

Title: JQuery Default text on empty text box

Body:
Call the below function and pass it two args: slightLabel(jQuery('#email_field'), 'email');

  function slightLabel(input, text) {
        jQuery(input).val(text);
        jQuery(input).data('defaultText', text);
        jQuery(input).focus(function(){
            if(!jQuery(this).data('touched'))
            {
                jQuery(this).data('touched', true);
                jQuery(input).val('');
            }
        });

        // the part to restore the original text in
        jQuery(input).blur(function(){
            if(jQuery(this).val() == '')
            {
                jQuery(this).val(jQuery(this).data('defaultText'));
            }
        });

    }


问:
Crashlytics - I'm getting lots of crash report from ios 9.1-9.2 after releasing new version
I released a new version of my application a couple of hours ago.

I suddenly get a lot of crash (about 50 - until now) reports that I didn't have till now.

The common of all crashes is:

iOS version 9.1-9.2

Crash types are: EXC_BAD_ACCESS KERN_INVALID_ADDRESS, EXC_BAD_ACCESS

What changed from the previous version:

iOS minimum target changed from 7 to 8

xCode changed from 7 to 8

fabric updated to the version 2.6.4 (1271)

I didn't find any explanation for that

I'd appreciate your help

Thanks in Advance

答:
I have crash similar in only iOS 9.2.x - 9.1.x, 9.0.x
No crash in 9.3.x, 10.x.x, 11.x.x
Is it error iOS system?
I use Swift 3.x</p>


问:
Autoplay Javascript carousel until button click
So I have a tidy little carousel that functions by clicking a left or right arrow.

Javascript:

```<code>unitWidth = 760;
unitTotal = 4;
unitCtr = 1;

onLeftArrow = function(e) {
    //alert("Left");
    disableArrows();
    if (unitCtr<=unitTotal) {
        unitCtr++;
        TweenLite.to(productImg, 0.6, {x: "-="+unitWidth, onComplete:enableArrows });
    }
    hideArrows();
}

onRightArrow = function(e) {
    //alert("Right");
    disableArrows();
    if (unitCtr>1) {
        unitCtr--;
        TweenLite.to(productImg, 0.6, {x: "+="+unitWidth, onComplete:enableArrows });
    }
    hideArrows();
}

function hideArrows() {
    //alert(unitCtr)
    if (unitCtr <= 1) {
        arrowRight.style.visibility = "hidden";
        arrowLeft.style.visibility = "visible";
    }
    if (unitCtr >= unitTotal) {
        arrowRight.style.visibility = "visible";
        arrowLeft.style.visibility = "hidden";
    }
    if (unitCtr>1 && unitCtr<unitTotal) {
        arrowRight.style.visibility = "visible";
        arrowLeft.style.visibility = "visible";
    }
}

function disableArrows() { //ADDED NEW FUNCTION TO DISABLE ARROWS
    arrowLeft.removeEventListener('click', onLeftArrow, false);
    arrowRight.removeEventListener('click', onRightArrow, false);
}

function enableArrows() { //ADDED NEW FUNCTION TO RE-ENABLE ARROWS
    arrowLeft.addEventListener('click', onLeftArrow, false);
    arrowRight.addEventListener('click', onRightArrow, false);
}
</code>```

HTML:

```<code><div id="arrowL">
    <img src="arrow_click.png" width="100" height="415" />
</div>

<div id="arrowR">
    <img src="arrow_click.png" width="100" height="415" />
</div>

<div id="product_img">
    <div class="img_container" id="product1">
        <img src="panel1.jpg" class="product" />
    </div>
    <div class="img_container" id="product2">
        <img src="panel2.jpg" class="product" />
    </div>
    <div class="img_container" id="product3">
        <img src="panel3.jpg" class="product" />
    </div>
    <div class="img_container" id="product4">
        <img src="panel4.jpg" class="product" />
    </div>
</div>
</code>```

I'd like for the carousel to autoplay all the way through once, until it reaches the end or someone clicks an arrow. Any suggestions for the best way to do this? (i'm using GSAP to handle the actual motion)

答:
Try to use part of your code that will handle transition as module to make it easier to call/use them.

Please Note: I didn't test it but it will give you idea about how carousel should work as autoplay and how you be able to stop it. (You can add rest of your code too, this is just about parts that are new or updated.)

javascript:

```<code>var unitWidth = 760,
    unitTotal = 4,
    unitCtr = 1,
    interval;

onLeftArrow = function(e) {
    disableArrows();
    transition_forward();
    hideArrows();
}

function transition_forward(){
    if (unitCtr<=unitTotal) {
        unitCtr++;
        TweenLite.to(productImg, 0.6, {x: "-="+unitWidth, onComplete:enableArrows });
    }
}

function auto_play(){
    interval = setInterval(function(){
        transition_forward();
    }, 2500);
}

auto_play();

clearIV = function(){
    clearInterVal(interval );
}

arrowLeft.addEventListener('click', clearIV, false);
arrowRight.addEventListener('click', clearIV, false);
</code>```

Body:
So I have a tidy little carousel that functions by clicking a left or right arrow.

Javascript:

unitWidth = 760;
unitTotal = 4;
unitCtr = 1;

onLeftArrow = function(e) {
    //alert("Left");
    disableArrows();
    if (unitCtr<=unitTotal) {
        unitCtr++;
        TweenLite.to(productImg, 0.6, {x: "-="+unitWidth, onComplete:enableArrows });
    }
    hideArrows();
}

onRightArrow = function(e) {
    //alert("Right");
    disableArrows();
    if (unitCtr>1) {
        unitCtr--;
        TweenLite.to(productImg, 0.6, {x: "+="+unitWidth, onComplete:enableArrows });
    }
    hideArrows();
}

function hideArrows() {
    //alert(unitCtr)
    if (unitCtr <= 1) {
        arrowRight.style.visibility = "hidden";
        arrowLeft.style.visibility = "visible";
    }
    if (unitCtr >= unitTotal) {
        arrowRight.style.visibility = "visible";
        arrowLeft.style.visibility = "hidden";
    }
    if (unitCtr>1 && unitCtr<unitTotal) {
        arrowRight.style.visibility = "visible";
        arrowLeft.style.visibility = "visible";
    }
}

function disableArrows() { //ADDED NEW FUNCTION TO DISABLE ARROWS
    arrowLeft.removeEventListener('click', onLeftArrow, false);
    arrowRight.removeEventListener('click', onRightArrow, false);
}

function enableArrows() { //ADDED NEW FUNCTION TO RE-ENABLE ARROWS
    arrowLeft.addEventListener('click', onLeftArrow, false);
    arrowRight.addEventListener('click', onRightArrow, false);
}

HTML:

I'd like for the carousel to autoplay all the way through once, until it reaches the end or someone clicks an arrow. Any suggestions for the best way to do this? (i'm using GSAP to handle the actual motion)

Body:
Try to use part of your code that will handle transition as module to make it easier to call/use them.

Please Note: I didn't test it but it will give you idea about how carousel should work as autoplay and how you be able to stop it. (You can add rest of your code too, this is just about parts that are new or updated.)

javascript:

var unitWidth = 760,
    unitTotal = 4,
    unitCtr = 1,
    interval;

onLeftArrow = function(e) {
    disableArrows();
    transition_forward();
    hideArrows();
}

function transition_forward(){
    if (unitCtr<=unitTotal) {
        unitCtr++;
        TweenLite.to(productImg, 0.6, {x: "-="+unitWidth, onComplete:enableArrows });
    }
}

function auto_play(){
    interval = setInterval(function(){
        transition_forward();
    }, 2500);
}

auto_play();

clearIV = function(){
    clearInterVal(interval );
}

arrowLeft.addEventListener('click', clearIV, false);
arrowRight.addEventListener('click', clearIV, false);


问:
SQL condition: (A=B AND C LIKE %D%) OR (A LIKE %B% AND C=D)
I've got a table of first names and last names.

I'm trying to make a jQuery instant search on an input, in order to find very quickly and precisely a person in a huge list of people.

When the first word is entered in the input, it might be the first name or the last name.

I do this : SELECT * FROM myTable WHERE firstName LIKE %content% OR lastName LIKE %content%

When two words are entered, it might be:
* the full firstname and a bit of the lastname
* the full lastname and a bit of the firstame

So I tried this query : SELECT * FROM myTable WHERE (firstName = content1 AND lastName LIKE %content2%) OR ( lastName = content1 AND firstName LIKE %content2%)

Unfortunately parenthesis seems to do nothing, and the query is not interpreted this way, I've got a lot of results, basically produced by the two LIKE %% condition

Anyone had deal with this before and could give me a hand?

Thanx

答:
It would probably work this way (assuming that the two words are in the content variable):

```<code>SELECT ... WHERE
   CONCAT(firstName, " ", lastName) LIKE content%
   OR CONCAT(lastName, " ", firstName) LIKE content%
</code>```

however this approach would not be very efficient (no index usage). I would split the two words into two variables (word1, word2) and make it something like:

```<code>SELECT ... WHERE
    (firstName = word1 AND lastName LIKE word2%)
    OR (lastName = word1 AND firstName LIKE word2%)
</code>```

Body:
It would probably work this way (assuming that the two words are in the content variable):

SELECT ... WHERE
   CONCAT(firstName, " ", lastName) LIKE content%
   OR CONCAT(lastName, " ", firstName) LIKE content%

however this approach would not be very efficient (no index usage). I would split the two words into two variables (word1, word2) and make it something like:

SELECT ... WHERE
    (firstName = word1 AND lastName LIKE word2%)
    OR (lastName = word1 AND firstName LIKE word2%)


问:
How to configure Travis-CI to build pull requests & merges to master w/o redundancy
To put it in "BDD" terms:

Background:

  Given I'm contributing to a GH repo

When I create a pull request

  Then Travis should build the latest commit

When I push to an existing pull request

  Then Travis should build the latest commit

When I merge a pull request to master

  Then Travis should build master

I was confused by Travis-CI's "build pushes" and "build PRs" settings, as:

Enabling both causes each Pull Request to be build twice by Travis

once for the commit on that branch

and once again for the merge commit of that branch into its destination

Enabling just "build PRs" causes PRs to be built, but doesn't result in post-merge builds (i.e. on master).

Enabling "pushes" brute-force satisfies the above criteria by building all pushes to the repo. You can try to finagle things by white- & black-listing branches, but that will probably bite you unless you're rigorously disciplined with branch names.

This is explained more in Travis-CI docs and GH issue #3241.

Anyone know a configuration that satisfies the above criteria?

答:
Just found in travis docs

Add to .travis.yml

```<code>if: type = push
</code>```

alternatively:

```<code>if: type = pull_request
</code>```

Body:
Just found in travis docs

Add to .travis.yml

if: type = push

alternatively:

if: type = pull_request


问:
How to set a default title in UIButton subclass that works in Interface Builder (Xcode 9)
I have a button that repeats throughout my app, so I created a subclass to avoid having to set all the basic properties every time.

I am able to set the background colour, the text colour, round the corners.

However, things fall apart when I try to set a default title - something other than "Button".
In Interface Builder it ignores the title, but it also then ignores the font colour, which works when I don't set the title.

If I run the app, it all looks fine, but one major point of using Interface Builder is to save the step of constantly running the app to check basic UI layout.

Here is the subclass.
Note that if you comment out the 2 setTitle lines, the button shows the correct text colour (white).

```<code>import UIKit

@IBDesignable class ContinueButton: UIButton {

    @IBInspectable var titleColour: UIColor = .white {
        didSet {
            setTitleColor(titleColour, for: .normal)
        }
    }

    @IBInspectable var bgColour: UIColor = UIColor.gray {
        didSet {
            backgroundColor = bgColour
        }
    }

    @IBInspectable var buttonTitle: String = "Continue" {
        didSet {
            setTitle(buttonTitle, for: .normal)
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setAttributes()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setAttributes()
    }

    public func setAttributes() {
        setTitleColor(titleColour, for: .normal)
        backgroundColor = bgColour
        setTitle(buttonTitle, for: .normal)
    }

    override public func layoutSubviews() {
        super.layoutSubviews()

        setAttributes()

        layer.cornerRadius = 0.5 * bounds.size.height
        clipsToBounds = true
    }
}
</code>```

ps, My main objective is to create a reusable custom button that takes care of setting a bunch of defaults. If there's a better way to achieve that, I'd be very happy to hear that - especially if it could be done visually rather than through code.

Thanks for any advice you can give,

-Nico

答:
Just override prepareForInterfaceBuilder() and add setAttributes().</p>

```<code>override func prepareForInterfaceBuilder() {
    super.prepareForInterfaceBuilder()
    setAttributes()
}
</code>```

Body:
I have a button that repeats throughout my app, so I created a subclass to avoid having to set all the basic properties every time.

I am able to set the background colour, the text colour, round the corners.

However, things fall apart when I try to set a default title - something other than "Button".
In Interface Builder it ignores the title, but it also then ignores the font colour, which works when I don't set the title.

If I run the app, it all looks fine, but one major point of using Interface Builder is to save the step of constantly running the app to check basic UI layout.

Here is the subclass.
Note that if you comment out the 2 setTitle lines, the button shows the correct text colour (white).

import UIKit

@IBDesignable class ContinueButton: UIButton {

    @IBInspectable var titleColour: UIColor = .white {
        didSet {
            setTitleColor(titleColour, for: .normal)
        }
    }

    @IBInspectable var bgColour: UIColor = UIColor.gray {
        didSet {
            backgroundColor = bgColour
        }
    }

    @IBInspectable var buttonTitle: String = "Continue" {
        didSet {
            setTitle(buttonTitle, for: .normal)
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setAttributes()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setAttributes()
    }

    public func setAttributes() {
        setTitleColor(titleColour, for: .normal)
        backgroundColor = bgColour
        setTitle(buttonTitle, for: .normal)
    }

    override public func layoutSubviews() {
        super.layoutSubviews()

        setAttributes()

        layer.cornerRadius = 0.5 * bounds.size.height
        clipsToBounds = true
    }
}

ps, My main objective is to create a reusable custom button that takes care of setting a bunch of defaults. If there's a better way to achieve that, I'd be very happy to hear that - especially if it could be done visually rather than through code.

Thanks for any advice you can give,

-Nico

Body:
Just override prepareForInterfaceBuilder() and add setAttributes().

override func prepareForInterfaceBuilder() {
    super.prepareForInterfaceBuilder()
    setAttributes()
}


问:
sh: react-scripts: command not found after running npm start
I cloned a react application onto my system and ran following commands

```<code>npm install -g create-react-app
npm install --save react react-dom
</code>```

After that i ran

```<code>npm start
</code>```

But it threw the above mentioned error, It is working fine on my other system from which i pushed it on github. But it is not working on any other system after cloning whether windows or mac.

答: Deleting package-lock.json and node_modules then npm install worked for me. </p>

Body:
I cloned a react application onto my system and ran following commands

npm install -g create-react-app
npm install --save react react-dom

After that i ran

npm start

But it threw the above mentioned error, It is working fine on my other system from which i pushed it on github. But it is not working on any other system after cloning whether windows or mac.


问:
Create an array of hashes describing files obtained from a given directory
I need to

Read a list of the files from in a specified directory

Create an array of hashes describing those files

My program fetches the path to a directory from the command line, opens it and reads its contents. Directories and "dot" files are skipped, and the absolute path to every other entry is printed.

```<code>use strict;
use warnings;

use Data::Dumper qw(Dumper);
use File::Spec;
use Digest::SHA qw(sha256_hex);

my $dir = $ARGV[0];

opendir DIR, $dir or die "cannot open dir $dir: $!";

while ( my $file = readdir DIR ) {
    next unless ( -f "${ \File::Spec->catfile($dir, $file) }" );
    next if ( "$file" =~ m/^\./) ;
    print "${ \File::Spec->rel2abs($file) }\n";
}

closedir DIR;
</code>```

Here I take a single file and create a hash with the path, size, and sha256sum.

```<code>my $file = "file1.txt";

my @fileref = (
    {
        path    =>  "Full path: " . File::Spec->rel2abs($file),
        size    =>  "Size (bytes): " . -s $file,
        id      =>  "SHA256SUM: " . sha256_hex($file),
    },
);

print "\n";
print "$fileref[0]{path}\n";
print "$fileref[0]{size}\n";
print "$fileref[0]{id}\n";
</code>```

All of this works, but I cannot figure out how to iterate over each file and add it to the array.

This is what I planned

```<code>for each file
    push file into array
    add the path, size, and id key:value pairs to file
repeat
</code>```

How can I generate the necessary array?

答:
Thanks to Wumpus Q. Wumbley's push suggestion, I have solved my problem:

```<code>my @array;
opendir DIR, $dir or die "cannot open dir $dir: $!";
while(my $file = readdir DIR) {
    next unless(-f "${\File::Spec->catfile($dir, $file)}");
    next if("$file" =~ m/^\./);
    #print "${\File::Spec->rel2abs($file)}\n";

    my  %hash = (
        path    =>  File::Spec->rel2abs($file),
        size    =>  -s $file,
        id      =>  sha256_hex($file),
    );

    push(@array, \%hash);

    #print Dumper sort \@array;
}
closedir DIR;

print Dumper \@array;
</code>```

I create the "frame" for the hash, and then pass it to the array via reference and the push function.

Body:
I need to

Read a list of the files from in a specified directory

Create an array of hashes describing those files

My program fetches the path to a directory from the command line, opens it and reads its contents. Directories and "dot" files are skipped, and the absolute path to every other entry is printed.

use strict;
use warnings;

use Data::Dumper qw(Dumper);
use File::Spec;
use Digest::SHA qw(sha256_hex);

my $dir = $ARGV[0];

opendir DIR, $dir or die "cannot open dir $dir: $!";

while ( my $file = readdir DIR ) {
    next unless ( -f "${ \File::Spec->catfile($dir, $file) }" );
    next if ( "$file" =~ m/^\./) ;
    print "${ \File::Spec->rel2abs($file) }\n";
}

closedir DIR;

Here I take a single file and create a hash with the path, size, and sha256sum.

my $file = "file1.txt";

my @fileref = (
    {
        path    =>  "Full path: " . File::Spec->rel2abs($file),
        size    =>  "Size (bytes): " . -s $file,
        id      =>  "SHA256SUM: " . sha256_hex($file),
    },
);

print "\n";
print "$fileref[0]{path}\n";
print "$fileref[0]{size}\n";
print "$fileref[0]{id}\n";

All of this works, but I cannot figure out how to iterate over each file and add it to the array.

This is what I planned

for each file
    push file into array
    add the path, size, and id key:value pairs to file
repeat

How can I generate the necessary array?

Body:
Thanks to Wumpus Q. Wumbley's push suggestion, I have solved my problem:

my @array;
opendir DIR, $dir or die "cannot open dir $dir: $!";
while(my $file = readdir DIR) {
    next unless(-f "${\File::Spec->catfile($dir, $file)}");
    next if("$file" =~ m/^\./);
    #print "${\File::Spec->rel2abs($file)}\n";

    my  %hash = (
        path    =>  File::Spec->rel2abs($file),
        size    =>  -s $file,
        id      =>  sha256_hex($file),
    );

    push(@array, \%hash);

    #print Dumper sort \@array;
}
closedir DIR;

print Dumper \@array;

I create the "frame" for the hash, and then pass it to the array via reference and the push function.


问:
It's better to hardcore constant values than make query to DB?
I have quite complicated form which contains a lot of values and I wonder, which option is better from performance perspective:

Load the data () from the database

Hardcode these data () right in the form

Basically these constant options (values will never change) are in the Database and have their own tables to avoid data duplication and they also have ManyToMany relationships with posts.

But wouldn't be better to hardcode these options in the selectable fields rather than making bunch of queries to the database to get these options?

Thanks in advance.

答:
Create a single configuration table in database. Then you can emit a single query to read all values you require.

Read once from DB on start up and then cache/save in your application.


问:
Using existing JMS libraries with a AMQP broker (RabbitMQ)
We use RabbitMQ and Spring-AMQP for our messaging system.

However there are many Java libraries that use JMS that I would rather not rewrite to AMQP.

I failed to Google a JMS client that will use AMQP.

Should I just rewrite the library to use AMQP directly?

答:
qpid , which also speaks amqp , has a JMS client library. Perhaps that also works with rabbitmq.

There's some (old) indications the OpenAMQ library works works with rabbitmq


问:
Cannot connect to GMail SMTP (PHPMailer) - Certificate Verify Failed
Very recently encountered this error when trying to send mail via SMTP and GMail.

```<code>Warning: stream_socket_enable_crypto(): SSL operation failed with code 1.
OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in C:\xampp\htdocs\portal\libraries\php_mailer\class.smtp.php on line 343
2017-12-05 09:48:03 SMTP Error: Could not connect to SMTP host.
2017-12-05 09:48:03 CLIENT -> SERVER: QUIT
2017-12-05 09:48:03 SMTP ERROR: QUIT command failed:
</code>```

Server address is https://gg-portal.com, and SSL configuration seems correct (verified through online checkers).

PHPMailer code is...

```<code>$mail = new PHPMailer();
$mail->isSMTP();
$mail->Host = "smtp.gmail.com";
$mail->SMTPAuth = true;
$mail->Username = $this->_config["EmailUser"];
$mail->Password = $this->_config["EmailPass"];
$mail->SMTPSecure = "tls";
$mail->SMTPDebug = 1;
$mail->Port = 587;
$mail->FromName = $this->_config["Brand"];
$mail->From     = $this->_config["EmailFrom"];
$mail->AddCC("...emailAddress...");
$mail->Subject  = "...subject...";
$mail->Body     = "...content...";
$mail->IsHTML(true);
$mail->WordWrap = 50;
if(!$mail->Send()) {
    echo ' Message was not sent.';
    echo 'Mailer error: ' . $mail->ErrorInfo;
}
</code>```

Have looked at the documentation which suggests certificate issues, though as stated SSL setup seems fine. Have looked into the issue elsewhere and most popular suggestions is to bypass the SSL (which works) however I'd prefer not to do this.

```<code>'context' => [
    'ssl' => [
        'verify_peer' => false,
        'verify_peer_name' => false,
        'allow_self_signed' => true
    ]
]
</code>```

答:
FIXED ISSUE FOR ME
I fixed this issue in my windows php environment by downloading an updated root certificates file and pointing my php.ini file to it.
It seems the problem was not with gmail's cert but rather with an outdated root certificate file due to windows server 2012 no longer updating this file automatically. Download cacert.pem from here: https://curl.haxx.se/docs/caextract.html.  Then in php.ini use following line to point to it (assuming you have openssl.dll installed).

openssl.cafile={Path to the file on your server}\cacert.pem.

That fixed it and I no longer needed to bypass SSL/TLS verification like suggested.  Ultimately I need to get windows to update root certs automatically using GPO or WSUS.  see https://serverfault.com/questions/541922/where-to-get-root-ca-certificates-for-windows-server-now-that-microsoft-no-longe

Body:
Very recently encountered this error when trying to send mail via SMTP and GMail.

Warning: stream_socket_enable_crypto(): SSL operation failed with code 1.
OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in C:\xampp\htdocs\portal\libraries\php_mailer\class.smtp.php on line 343
2017-12-05 09:48:03 SMTP Error: Could not connect to SMTP host.
2017-12-05 09:48:03 CLIENT -> SERVER: QUIT
2017-12-05 09:48:03 SMTP ERROR: QUIT command failed:

Server address is https://gg-portal.com, and SSL configuration seems correct (verified through online checkers).

PHPMailer code is...

$mail = new PHPMailer();
$mail->isSMTP();
$mail->Host = "smtp.gmail.com";
$mail->SMTPAuth = true;
$mail->Username = $this->_config["EmailUser"];
$mail->Password = $this->_config["EmailPass"];
$mail->SMTPSecure = "tls";
$mail->SMTPDebug = 1;
$mail->Port = 587;
$mail->FromName = $this->_config["Brand"];
$mail->From     = $this->_config["EmailFrom"];
$mail->AddCC("...emailAddress...");
$mail->Subject  = "...subject...";
$mail->Body     = "...content...";
$mail->IsHTML(true);
$mail->WordWrap = 50;
if(!$mail->Send()) {
    echo ' Message was not sent.';
    echo 'Mailer error: ' . $mail->ErrorInfo;
}

Have looked at the documentation which suggests certificate issues, though as stated SSL setup seems fine. Have looked into the issue elsewhere and most popular suggestions is to bypass the SSL (which works) however I'd prefer not to do this.

'context' => [
    'ssl' => [
        'verify_peer' => false,
        'verify_peer_name' => false,
        'allow_self_signed' => true
    ]
]


问:
Using rscript for expression with dash
I am using rscript to run some expressions but I'm having an issue with some cases with dashes. A simple example would be:

```<code>$ rscript -e '-1'
ERROR: option '-e' requires a non-empty argument
</code>```

Adding parenthesis works out (rscript -e (-1)) but I'm not always sure that they will be properly parenthesized.

In the documentation it says

When using -e options be aware of the quoting rules in the shell used

So I tried using different quoting rules for bash, escaping the dashes or using single quotes but it still doesn't work.

```<code>$ rscript -e "\-1"
Error: unexpected input in "\"
Execution halted
</code>```

Is there something I'm missing?

答:
You misunderstand one part here. "Expression" is something R can parse, ie:

```<code>$ R --slave -e '1+1'
[1] 2
$
</code>```

What you hit with -1 is a corner case. You can do

```<code>$ R --slave -e 'a <- -1; a'
[1] -1
$
</code>```

or

```<code>$ R --slave -e 'print(-1)'
[1] -1
$
</code>```

For actual argument parsing do you want an package like docopt (which I like and use a lot), or getopt (which I used before) or optparse.  All are on CRAN.

Title: Using rscript for expression with dash

Body:
I am using rscript to run some expressions but I'm having an issue with some cases with dashes. A simple example would be:

$ rscript -e '-1'
ERROR: option '-e' requires a non-empty argument

Adding parenthesis works out (rscript -e (-1)) but I'm not always sure that they will be properly parenthesized.

In the documentation it says

When using -e options be aware of the quoting rules in the shell used

So I tried using different quoting rules for bash, escaping the dashes or using single quotes but it still doesn't work.

$ rscript -e "\-1"
Error: unexpected input in "\"
Execution halted

Is there something I'm missing?

Body:
You misunderstand one part here. "Expression" is something R can parse, ie:

$ R --slave -e '1+1'
[1] 2
$

What you hit with -1 is a corner case. You can do

$ R --slave -e 'a <- -1; a'
[1] -1
$

or

$ R --slave -e 'print(-1)'
[1] -1
$

For actual argument parsing do you want an package like docopt (which I like and use a lot), or getopt (which I used before) or optparse.  All are on CRAN.


问:
PHP - How do I read all attributes of XML items using simpleXML?
I'm making a script, that reads through the passed XML file and displays the source code. I've got it almost done, but the item attributes .. I can't find a way to catch them. Here's the code:

```<code>$xml = simplexml_load_file("path/to/file.xml");

    showTree($xml->children(), 0);

    function showTree($value, $i) {

        if($value == '') {

            foreach($value as $name2 => $value2) {

                echo str_repeat('--', $i)." <$name2> \n";
                    showTree($value2, ($i+1));
                echo str_repeat('--', $i)." </$name2> \n";
            }

        } else { echo str_repeat('--', $i)." ".trim($value)."\n"; }

    } // end: function
</code>```

As I said, it works fine, but doesn't display the attributes, for example:

```<code><item id=2>Item</item>
</code>```

returns only the:

```<code><item>Item</item>
</code>```

Thanks for any responses, Mike.

答: Have a look at http://php.net/manual/en/simplexmlelement.attributes.php</p>

Body:
I'm making a script, that reads through the passed XML file and displays the source code. I've got it almost done, but the item attributes .. I can't find a way to catch them. Here's the code:

$xml = simplexml_load_file("path/to/file.xml");

    showTree($xml->children(), 0);

    function showTree($value, $i) {

        if($value == '') {

            foreach($value as $name2 => $value2) {

                echo str_repeat('--', $i)." <$name2> \n";
                    showTree($value2, ($i+1));
                echo str_repeat('--', $i)." </$name2> \n";
            }

        } else { echo str_repeat('--', $i)." ".trim($value)."\n"; }

    } // end: function

As I said, it works fine, but doesn't display the attributes, for example:

<item id=2>Item</item>

returns only the:

<item>Item</item>

Thanks for any responses, Mike.


问:
JavaFX slows down backend
This is a school project. We built a JavaFX GUI to take inputs for an algorithm. The algorithm runs only 45 minutes in stand-alone mode. However, when calling from JavaFX GUI, the running time is doubled. Any idea what might cause this? Also, the JavaFX GUI consumes about 400 Mb memory, is this normal?

Any help is appreciated.

Yulian

答:
There are very minute things that one needs to keep in mind while developing if they need to optimize their JavaFX Applications (performance wise):

1. Many people think that they should write the entire application using pure JavaFX coding. This may be fine for small test applications. But when we write real-world applications, we need to divide the I/O portion, Business logic and all Non-UI related code to different layers.

2.
 Use JavaFx Api Async + Callback methods so as to execute these code outside Event-Dispatch-Thread.

Title: JavaFX slows down backend


问:
Django arranging model foreign key attributes after delete()
I have a model like so:

```<code>class RepairOrder(models.Model):
user = models.ForeignKey(User)
ro_number = models.IntegerField(validators=[MaxValueValidator(999999999999)])
service_writer = models.ForeignKey(ServiceWriter, null=True, blank=True)
RO_STATUS_CHOICES = (
    ('P', 'Pending'),
    ('O', 'Open'),
    ('C', 'Closed')
)
ro_status = models.CharField(max_length=10, blank=False, choices=RO_STATUS_CHOICES)
open_date = models.DateTimeField()
closed_date = models.DateTimeField(null=True, blank=True)
mileage = models.IntegerField(blank=False, validators=[MaxValueValidator(999999999999)])
line_number_1 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL,
                                  related_name='line_number_1')
line_number_2 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL,
                                  related_name='line_number_2')
line_number_3 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL,
                                  related_name='line_number_3')
line_number_4 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL
                                  , related_name='line_number_4')
line_number_5 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL,
                                  related_name='line_number_5')
line_number_6 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL,
                                  related_name='line_number_6')
line_number_7 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL,
                                  related_name='line_number_7')
line_number_8 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL,
                                  related_name='line_number_8')
line_number_9 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL,
                                  related_name='line_number_9')
line_number_10 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL,
                                   related_name='line_number_10')
vehicle = models.ForeignKey(Vehicle, blank=False, related_name='vehicle')

def __str__(self):
    return str(self.ro_number)
</code>```

Some of these objects might have

```<code>line_number_(1 through 5)
</code>```

assigned to a JobLine object and the remaining set as Null.
Other RepairOrder objects may only have

```<code>line_number_(1 through 3)
</code>```

assigned to a JobLine object while the remaining are set as Null. But during the creation of a RepairOrder object the

```<code>line_number_(x)
</code>```

attributes are always assigned in ascending order starting from 1.

Here is what I am trying to accomplish:
Lets assume I have a RepairOrder that has

```<code>line_number_(1 through 5)
</code>```

assigned to JobLine objects and the rest are assigned as a Null value. I want to be able to delete the JobLine object assigned to the

```<code>line_number_3
</code>```

attribute of a RepairOrder object and have the remaining filled attributes re arranged to fill the

```<code>line_number_(1-4)
</code>```

attributes of that RepairOrder object.

Here is what I have tried so far:

```<code>views.py
def advanced_delete_line(request, pk, jl):
user = request.user

if request.method == "POST":
    raise PermissionDenied
else:
    # Get RepairOrder object with pk passed in from url
    ro_obj = RepairOrder.objects.get(pk=pk, user=user)
    # Get attribute object of 'line_number_(jl passed in from url)
    ro_line = getattr(ro_obj, "line_number_" + str(jl))
    # Delete this object
    ro_line.delete()
    # Get the object assigned to the next numerically higher attribute or RepairOrder object
    x = int(jl) + 1
    for i in range(10-int(jl)):  # Only loop as many times is needed
        # Get the object assigned to the next numerically higher attribute or RepairOrder object
        line = getattr(ro_obj, "line_number_" + str(x))
        y = x - 1
        # Assign the previously retrieved object to the next lower job_line_attribute
        line_2 = setattr(ro_obj, "line_number_" + str(y), line)
        if line is None:
            pass
        else:
            line_2.save()
        # Do it all over again but starting at the next numerically higher attribute
        x += 1

    return HttpResponseRedirect('/advanced/repair-order/' + str(pk) + "/")
</code>```

I am having little to no luck with this method. Can anyone provide me with a better way to do this?

答:
I was able to figure out some issues with my logic. I was assigning the setattr() function to a variable when it doesn't work like that. You need to use the settattr() function like so:</p>

```<code>replacement_value = "value"
setattr(object, "attribute_name", replacement_value)
object.save()
</code>```

Body:
I have a model like so:

class RepairOrder(models.Model):
user = models.ForeignKey(User)
ro_number = models.IntegerField(validators=[MaxValueValidator(999999999999)])
service_writer = models.ForeignKey(ServiceWriter, null=True, blank=True)
RO_STATUS_CHOICES = (
    ('P', 'Pending'),
    ('O', 'Open'),
    ('C', 'Closed')
)
ro_status = models.CharField(max_length=10, blank=False, choices=RO_STATUS_CHOICES)
open_date = models.DateTimeField()
closed_date = models.DateTimeField(null=True, blank=True)
mileage = models.IntegerField(blank=False, validators=[MaxValueValidator(999999999999)])
line_number_1 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL,
                                  related_name='line_number_1')
line_number_2 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL,
                                  related_name='line_number_2')
line_number_3 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL,
                                  related_name='line_number_3')
line_number_4 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL
                                  , related_name='line_number_4')
line_number_5 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL,
                                  related_name='line_number_5')
line_number_6 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL,
                                  related_name='line_number_6')
line_number_7 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL,
                                  related_name='line_number_7')
line_number_8 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL,
                                  related_name='line_number_8')
line_number_9 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL,
                                  related_name='line_number_9')
line_number_10 = models.ForeignKey(JobLine, null=True, blank=True, on_delete=models.SET_NULL,
                                   related_name='line_number_10')
vehicle = models.ForeignKey(Vehicle, blank=False, related_name='vehicle')

def __str__(self):
    return str(self.ro_number)

Some of these objects might have

line_number_(1 through 5)

assigned to a JobLine object and the remaining set as Null.
Other RepairOrder objects may only have

line_number_(1 through 3)

assigned to a JobLine object while the remaining are set as Null. But during the creation of a RepairOrder object the

line_number_(x)

attributes are always assigned in ascending order starting from 1.

Here is what I am trying to accomplish:
Lets assume I have a RepairOrder that has

line_number_(1 through 5)

assigned to JobLine objects and the rest are assigned as a Null value. I want to be able to delete the JobLine object assigned to the

line_number_3

attribute of a RepairOrder object and have the remaining filled attributes re arranged to fill the

line_number_(1-4)

attributes of that RepairOrder object.

Here is what I have tried so far:

views.py
def advanced_delete_line(request, pk, jl):
user = request.user

if request.method == "POST":
    raise PermissionDenied
else:
    # Get RepairOrder object with pk passed in from url
    ro_obj = RepairOrder.objects.get(pk=pk, user=user)
    # Get attribute object of 'line_number_(jl passed in from url)
    ro_line = getattr(ro_obj, "line_number_" + str(jl))
    # Delete this object
    ro_line.delete()
    # Get the object assigned to the next numerically higher attribute or RepairOrder object
    x = int(jl) + 1
    for i in range(10-int(jl)):  # Only loop as many times is needed
        # Get the object assigned to the next numerically higher attribute or RepairOrder object
        line = getattr(ro_obj, "line_number_" + str(x))
        y = x - 1
        # Assign the previously retrieved object to the next lower job_line_attribute
        line_2 = setattr(ro_obj, "line_number_" + str(y), line)
        if line is None:
            pass
        else:
            line_2.save()
        # Do it all over again but starting at the next numerically higher attribute
        x += 1

    return HttpResponseRedirect('/advanced/repair-order/' + str(pk) + "/")

I am having little to no luck with this method. Can anyone provide me with a better way to do this?

Body:
I was able to figure out some issues with my logic. I was assigning the setattr() function to a variable when it doesn't work like that. You need to use the settattr() function like so:

replacement_value = "value"
setattr(object, "attribute_name", replacement_value)
object.save()


问:
Is there a way to actually delete devices from Apple Developer Portal?
Our company has 11 different apps on AppStore, with different teams developing each app, we have a lot of test devices, and our "Device list" in developer.apple.com/account is completely full. We received a bunch of iPhone 8 and 8 Plus on their release, and a couple of iPhone X on its release, but none of them can be added to our provisioning profiles because our device list is full.

We know that the device list gets updated every year, at the start of our "developer year" when paying the fee. Sadly, in previous years, we have not been deleting unused devices, so we have a lot of devices registered from people who no longer work there, devices we no longer support, and employees' older phones. We can mark them as "inactive", which I guess will mean they get automatically removed when the new year starts..

The next time our membership is renewed is too far into the future. We can't release apps without testing them on these new devices.

I understand the reasoning behind allowing only 100 devices a year, disabling the opportunity to release apps to anyone anytime, but it doesn't really work for us.
There should be a way to apply for an extended list of devices.. Like, 150 would do..

Is there anything I've misunderstood, or is this actually the case? It is impossible for us to add our new devices until the next renewal, even if that's in next August?

答:
Please contact Apple tech support as a technical incident filed from your apple account by Agent. The situation to be explained to apple may allow them to clear all the devices for you and re-register them in middle of the year.  If they agree shouldn't be a problem to do in mid year time.

Note there are 2 free tech-incidents given for your account per year so use it wisely.

https://developer.apple.com/support/technical/


问:
Prolog - How can I save results from recursive calls?
I am still trying to understand the Prolog logic and have stumbled upon a problem.
I am trying to save values found within recursive calls, to pass on or gather.

As such:

```<code>main([]) :- !.
main([H|Tail]) :- findall(X,something(_,_,X),R),
                  getValueReturn(R,H,Lin, Lout),
                  main(Tail).

% X is the Head from main
getValueReturn([H|Tail],X,Lin, Lout) :- subset(X, H) ->
                                findall(A,something(A,_,H),L1),
                                append(Lin,L1,Lout),
                                getValueReturn(Tail,X,Lout,L)
                                ;
                                getValueReturn(Tail,X,Lin,Lout).
</code>```

I would like to gather the results from findall in getValueReturn, combine them, and send them back to main, which can then use them.
How do I create and add to a list within getValueReturn?
Similarly, how can I save the list in my main for all recursive calls?

EDIT:

I edited the code above as per a comment reply, however when I run this through trace, the list deletes all elements when the empty list is found.

What am I doing wrong? This is the first time I try to use the concept of building a list through recursion.

答:
You should post complete code that can be run, with example data. I have not tested this.

You need to pass L around on the top-level also. Using the same variable names for different parameters in adjacent procedures does not improve readability.

```<code>main([E|Es],L0,L) :-
  findall(X,something(_,_,X),Rs),
  getValueReturn(Rs,E,L0,L1),
  main(Es,L1,L).
main([],L,L).

getValueReturn([R|Rs],E,L0,L) :-
  ( subset(E,R) ->
    findall(A,something(A,_,R),New),
    append(L0,New,L1),
    getValueReturn(Rs,E,L1,L)
  ; getValueReturn(Rs,E,L0,L) ).
getValueReturn([],_,L,L).
</code>```

A variable can only have one value in Prolog. In your code, for example, Lout is the output from append/3, an input to a recursive call of getValueReturn/4, and then also the output on the top-level. This is probably not going to do what you want.

Body:
I am still trying to understand the Prolog logic and have stumbled upon a problem.
I am trying to save values found within recursive calls, to pass on or gather.

As such:

main([]) :- !.
main([H|Tail]) :- findall(X,something(_,_,X),R),
                  getValueReturn(R,H,Lin, Lout),
                  main(Tail).

% X is the Head from main
getValueReturn([H|Tail],X,Lin, Lout) :- subset(X, H) ->
                                findall(A,something(A,_,H),L1),
                                append(Lin,L1,Lout),
                                getValueReturn(Tail,X,Lout,L)
                                ;
                                getValueReturn(Tail,X,Lin,Lout).

I would like to gather the results from findall in getValueReturn, combine them, and send them back to main, which can then use them.
How do I create and add to a list within getValueReturn?
Similarly, how can I save the list in my main for all recursive calls?

EDIT:

I edited the code above as per a comment reply, however when I run this through trace, the list deletes all elements when the empty list is found.

What am I doing wrong? This is the first time I try to use the concept of building a list through recursion.

Body:
You should post complete code that can be run, with example data. I have not tested this.

You need to pass L around on the top-level also. Using the same variable names for different parameters in adjacent procedures does not improve readability.

main([E|Es],L0,L) :-
  findall(X,something(_,_,X),Rs),
  getValueReturn(Rs,E,L0,L1),
  main(Es,L1,L).
main([],L,L).

getValueReturn([R|Rs],E,L0,L) :-
  ( subset(E,R) ->
    findall(A,something(A,_,R),New),
    append(L0,New,L1),
    getValueReturn(Rs,E,L1,L)
  ; getValueReturn(Rs,E,L0,L) ).
getValueReturn([],_,L,L).

A variable can only have one value in Prolog. In your code, for example, Lout is the output from append/3, an input to a recursive call of getValueReturn/4, and then also the output on the top-level. This is probably not going to do what you want.


问:
What does this symbol mean in C++? "~"
If we use ~ before a function like this: ~func();, what does this mean?

Thanks.

答: Assuming you're referring to a function declaration, that indicates a destructor -- a function that is run automatically when an object is destroyed. Destructors are normally used to release any resources used by the object (free memory, close files, etc.)

Title: What does this symbol mean in C++? "~"