问:
How to use Tensorflow dataset API with training and validation sets

Simple task at hand: run training for N epochs performing calculating exact validation accuracy after each epoch. Epoch size can be either equal to full training set or some predefined number of iterations. During validation every validation set input has to be evaluated exactly once.

What would be the best way to mix together one_shot_iterators, initializable iterator and/or handle for that task?

Here is scaffolding of how i see it should work:

def build_training_dataset():
    pass

def build_validation_dataset():
    pass

def construct_train_op(dataset):
    pass

def magic(iterator):
    pass

USE_CUSTOM_EPOCH_SIZE = True
CUSTOM_EPOCH_SIZE = 60
MAX_EPOCHS = 100

training_dataset = build_training_dataset()
validation_dataset = build_validation_dataset()

# Magic goes here to build a nice one-instance dataset
dataset = magic(training_dataset, validation_dataset)

train_op = construct_train_op(dataset)

# Run N epochs in which the training dataset is traversed, followed by the
# validation dataset.
with tf.Session() as sess:
    for epoch in MAX_EPOCHS:

        # train
        if USE_CUSTOM_EPOCH_SIZE:
            for _ in range(CUSTOM_EPOCH_SIZE):
                sess.run(train_op)
        else:
            while True:
                # I guess smth like this:
                try:
                    sess.run(train_op)
                except tf.errors.OutOfRangeError:
                    break # we are done with the epoch

        # validation
        validation_predictions = []
        while True:
            try:
                np.append(validation_predictions, sess.run(train_op)) # but for validation this time
            except tf.errors.OutOfRangeError:
                print('epoch %d finished with accuracy: %f' % (epoch validation_predictions.mean()))
                break
```

答:
Since the solution is a lot messier than I expected it comes in 2 peaces:

0) Auxiliary code shared by both examples:

USE_CUSTOM_EPOCH_SIZE = True
CUSTOM_EPOCH_SIZE = 60
MAX_EPOCHS = 100

TRAIN_SIZE = 500
VALIDATION_SIZE = 145
BATCH_SIZE = 64

def construct_train_op(batch):
    return batch

def build_train_dataset():
    return tf.data.Dataset.range(TRAIN_SIZE) \
        .map(lambda x: x + tf.random_uniform([], -10, 10, tf.int64)) \
        .batch(BATCH_SIZE)

def build_test_dataset():
    return tf.data.Dataset.range(VALIDATION_SIZE) \
        .batch(BATCH_SIZE)
```

<p>1) For epoch equal to the train dataset size:</p>

<pre class="lang-py prettyprint-override"><code># datasets construction
training_dataset = build_train_dataset()
validation_dataset = build_test_dataset()

# handle constructions. Handle allows us to feed data from different dataset by providing a parameter in feed_dict
handle = tf.placeholder(tf.string, shape=[])
iterator = tf.data.Iterator.from_string_handle(handle, training_dataset.output_types, training_dataset.output_shapes)
next_element = iterator.get_next()

train_op = construct_train_op(next_element)

training_iterator = training_dataset.make_initializable_iterator()
validation_iterator = validation_dataset.make_initializable_iterator()

with tf.Session() as sess:
    training_handle = sess.run(training_iterator.string_handle())
    validation_handle = sess.run(validation_iterator.string_handle())

    for epoch in range(MAX_EPOCHS):
        #train
        sess.run(training_iterator.initializer)
        total_in_train = 0
        while True:
            try:
                train_output = sess.run(train_op, feed_dict={handle: training_handle})
                total_in_train += len(train_output)
            except tf.errors.OutOfRangeError:
                assert total_in_train == TRAIN_SIZE
                break # we are done with the epoch

        # validation
        validation_predictions = []
        sess.run(validation_iterator.initializer)
        while True:
            try:
                pred = sess.run(train_op, feed_dict={handle: validation_handle})
                validation_predictions = np.append(validation_predictions, pred)
            except tf.errors.OutOfRangeError:
                assert len(validation_predictions) == VALIDATION_SIZE
                print('Epoch %d finished with accuracy: %f' % (epoch, np.mean(validation_predictions)))
                break
</code>```

2) For custom epoch size:

# datasets construction
training_dataset = build_train_dataset().repeat() # CHANGE 1
validation_dataset = build_test_dataset()

# handle constructions. Handle allows us to feed data from different dataset by providing a parameter in feed_dict
handle = tf.placeholder(tf.string, shape=[])
iterator = tf.data.Iterator.from_string_handle(handle, training_dataset.output_types, training_dataset.output_shapes)
next_element = iterator.get_next()

train_op = construct_train_op(next_element)

training_iterator = training_dataset.make_one_shot_iterator() # CHANGE 2
validation_iterator = validation_dataset.make_initializable_iterator()

with tf.Session() as sess:
    training_handle = sess.run(training_iterator.string_handle())
    validation_handle = sess.run(validation_iterator.string_handle())

    for epoch in range(MAX_EPOCHS):
        #train
        # CHANGE 3: no initiazation, not try/catch
        for _ in range(CUSTOM_EPOCH_SIZE):
            train_output = sess.run(train_op, feed_dict={handle: training_handle})

        # validation
        validation_predictions = []
        sess.run(validation_iterator.initializer)
        while True:
            try:
                pred = sess.run(train_op, feed_dict={handle: validation_handle})
                validation_predictions = np.append(validation_predictions, pred)
            except tf.errors.OutOfRangeError:
                assert len(validation_predictions) == VALIDATION_SIZE
                print('Epoch %d finished with accuracy: %f' % (epoch, np.mean(validation_predictions)))
                break
```

Body:
Since the solution is a lot messier than I expected it comes in 2 peaces:

0) Auxiliary code shared by both examples:

USE_CUSTOM_EPOCH_SIZE = True
CUSTOM_EPOCH_SIZE = 60
MAX_EPOCHS = 100

TRAIN_SIZE = 500
VALIDATION_SIZE = 145
BATCH_SIZE = 64

def construct_train_op(batch):
    return batch

def build_train_dataset():
    return tf.data.Dataset.range(TRAIN_SIZE) \
        .map(lambda x: x + tf.random_uniform([], -10, 10, tf.int64)) \
        .batch(BATCH_SIZE)

def build_test_dataset():
    return tf.data.Dataset.range(VALIDATION_SIZE) \
        .batch(BATCH_SIZE)

1) For epoch equal to the train dataset size:

# datasets construction
training_dataset = build_train_dataset()
validation_dataset = build_test_dataset()

# handle constructions. Handle allows us to feed data from different dataset by providing a parameter in feed_dict
handle = tf.placeholder(tf.string, shape=[])
iterator = tf.data.Iterator.from_string_handle(handle, training_dataset.output_types, training_dataset.output_shapes)
next_element = iterator.get_next()

train_op = construct_train_op(next_element)

training_iterator = training_dataset.make_initializable_iterator()
validation_iterator = validation_dataset.make_initializable_iterator()

with tf.Session() as sess:
    training_handle = sess.run(training_iterator.string_handle())
    validation_handle = sess.run(validation_iterator.string_handle())

    for epoch in range(MAX_EPOCHS):
        #train
        sess.run(training_iterator.initializer)
        total_in_train = 0
        while True:
            try:
                train_output = sess.run(train_op, feed_dict={handle: training_handle})
                total_in_train += len(train_output)
            except tf.errors.OutOfRangeError:
                assert total_in_train == TRAIN_SIZE
                break # we are done with the epoch

        # validation
        validation_predictions = []
        sess.run(validation_iterator.initializer)
        while True:
            try:
                pred = sess.run(train_op, feed_dict={handle: validation_handle})
                validation_predictions = np.append(validation_predictions, pred)
            except tf.errors.OutOfRangeError:
                assert len(validation_predictions) == VALIDATION_SIZE
                print('Epoch %d finished with accuracy: %f' % (epoch, np.mean(validation_predictions)))
                break

2) For custom epoch size:

# datasets construction
training_dataset = build_train_dataset().repeat() # CHANGE 1
validation_dataset = build_test_dataset()

# handle constructions. Handle allows us to feed data from different dataset by providing a parameter in feed_dict
handle = tf.placeholder(tf.string, shape=[])
iterator = tf.data.Iterator.from_string_handle(handle, training_dataset.output_types, training_dataset.output_shapes)
next_element = iterator.get_next()

train_op = construct_train_op(next_element)

training_iterator = training_dataset.make_one_shot_iterator() # CHANGE 2
validation_iterator = validation_dataset.make_initializable_iterator()

with tf.Session() as sess:
    training_handle = sess.run(training_iterator.string_handle())
    validation_handle = sess.run(validation_iterator.string_handle())

    for epoch in range(MAX_EPOCHS):
        #train
        # CHANGE 3: no initiazation, not try/catch
        for _ in range(CUSTOM_EPOCH_SIZE):
            train_output = sess.run(train_op, feed_dict={handle: training_handle})

        # validation
        validation_predictions = []
        sess.run(validation_iterator.initializer)
        while True:
            try:
                pred = sess.run(train_op, feed_dict={handle: validation_handle})
                validation_predictions = np.append(validation_predictions, pred)
            except tf.errors.OutOfRangeError:
                assert len(validation_predictions) == VALIDATION_SIZE
                print('Epoch %d finished with accuracy: %f' % (epoch, np.mean(validation_predictions)))
                break


来源: stackexchange

问:
Issue in installation of mxnet package in R
mxnet package is not installing in r (on windows 10) when I follow the steps given in its documentation.

```<code>install.packages("drat", repos="https://cran.rstudio.com")
drat:::addRepo("dmlc")
install.packages("mxnet")
</code>```

It gives the following result

Installing package into ‘C:/Users/Ashish/Documents/R/win-library/3.3’
  (as ‘lib’ is unspecified) Warning in install.packages :   cannot open
  URL 'http://dmlc.github.io/drat/bin/windows/contrib/3.3/PACKAGES.gz':
  HTTP status was '404 Not Found' Warning in install.packages :   cannot
  open URL
  'http://dmlc.github.io/drat/bin/windows/contrib/3.3/PACKAGES': HTTP
  status was '404 Not Found' Warning in install.packages :   unable to
  access index for repository
  http://dmlc.github.io/drat/bin/windows/contrib/3.3:   cannot open URL
  'http://dmlc.github.io/drat/bin/windows/contrib/3.3/PACKAGES' Package
  which is only available in source form, and may need   compilation of
  C/C++/Fortran: ‘mxnet’ Do you want to attempt to install these from
  sources? y/n: y installing the source package ‘mxnet’

trying URL 'http://dmlc.github.io/drat/src/contrib/mxnet_0.5.tar.gz'
  Warning in install.packages :   cannot open URL
  'http://dmlc.github.io/drat/src/contrib/mxnet_0.5.tar.gz': HTTP status
  was '404 Not Found' Error in download.file(url, destfile, method, mode
  = "wb", ...) :    cannot open URL 'http://dmlc.github.io/drat/src/contrib/mxnet_0.5.tar.gz' Warning in
  install.packages :   download of package ‘mxnet’ failed

Kindly help me resolve this issue. I'm using R version 3.3.0. Is there any other way of installing it in R?

答:
try these commands to install mxnet package:--</p>

```<code>cran <- getOption("repos")
cran["dmlc"] <- "https://s3-us-west-2.amazonaws.com/apache-mxnet/R/CRAN/"
options(repos = cran)
install.packages("mxnet")
</code>```

ContentLicense: CC BY-SA 3.0

Body:
mxnet package is not installing in r (on windows 10) when I follow the steps given in its documentation.

install.packages("drat", repos="https://cran.rstudio.com")
drat:::addRepo("dmlc")
install.packages("mxnet")

It gives the following result

Installing package into ‘C:/Users/Ashish/Documents/R/win-library/3.3’
  (as ‘lib’ is unspecified) Warning in install.packages :   cannot open
  URL 'http://dmlc.github.io/drat/bin/windows/contrib/3.3/PACKAGES.gz':
  HTTP status was '404 Not Found' Warning in install.packages :   cannot
  open URL
  'http://dmlc.github.io/drat/bin/windows/contrib/3.3/PACKAGES': HTTP
  status was '404 Not Found' Warning in install.packages :   unable to
  access index for repository
  http://dmlc.github.io/drat/bin/windows/contrib/3.3:   cannot open URL
  'http://dmlc.github.io/drat/bin/windows/contrib/3.3/PACKAGES' Package
  which is only available in source form, and may need   compilation of
  C/C++/Fortran: ‘mxnet’ Do you want to attempt to install these from
  sources? y/n: y installing the source package ‘mxnet’

trying URL 'http://dmlc.github.io/drat/src/contrib/mxnet_0.5.tar.gz'
  Warning in install.packages :   cannot open URL
  'http://dmlc.github.io/drat/src/contrib/mxnet_0.5.tar.gz': HTTP status
  was '404 Not Found' Error in download.file(url, destfile, method, mode
  = "wb", ...) :    cannot open URL 'http://dmlc.github.io/drat/src/contrib/mxnet_0.5.tar.gz' Warning in
  install.packages :   download of package ‘mxnet’ failed

Kindly help me resolve this issue. I'm using R version 3.3.0. Is there any other way of installing it in R?

Body:
try these commands to install mxnet package:--

cran <- getOption("repos")
cran["dmlc"] <- "https://s3-us-west-2.amazonaws.com/apache-mxnet/R/CRAN/"
options(repos = cran)
install.packages("mxnet")


问:
HttpContext in .net standard library
I am working on couple of projects one of which is an ASP.NET 4.5 application and other one is .Net Core API 1.1 project. The asp.net application is using HttpContext classes to read cookies and page headers. Now, I need to move this to a .net standard library which can be used by both the project. I don't find HttpContext in .net standard SDK. Any suggestions?

答:
There's a problem to your approach: .NET Standard is the most bare-bones implementation of .NET available, meaning that only basic features which are platform- and scenario-agnostic are implemented.

HttpContext exists on both the .NET Framework and .NET Core (both of which implement .NET Standard, by the way),  but being specific to the Web, it does not exist on .NET Standard.

So, you have three options:

Target the .NET Framework and use System.Web.HttpContext

Target .NET Core and use Microsoft.AspNetCore.Http.HttpContext

Move the logic that uses HttpContext away from the .NET Standard project

Do notice, though, that those classes vary greatly. The .NET Core version was created for ASP.NET Core which is vastly different to ASP.NET 4.5 and olders.

Title: HttpContext in .net standard library


问:
Create a new column in python dataframe based on the presence of NaN in a specific column
I have a dataframe with NaNs

```<code>df = pd.DataFrame({"A": [10,20,30, np.nan], "B": [20, np.nan, 10,np.nan]})

     A     B
0  10.0  20.0
1  20.0   NaN
2  30.0  10.0
3   NaN   NaN
</code>```

I would like to create a new column 'C'.
In  any row if either column 'A' or 'B' has a NaN, column 'C' will be set to 0 else 1.

I would like to get as below:

```<code>      A     B  C
0  10.0  20.0  1
1  20.0   NaN  0
2  30.0  10.0  1
3   NaN   NaN  0
</code>```

I tried the below code:

```<code>df['C'] = df.apply(lambda row:0 if (row['A']=='NaN' or row['B']=='NaN')  else 1, axis=1)
</code>```

I get the below df. Column C is always set to 1.

```<code>      A     B  C
0  10.0  20.0  1
1  20.0   NaN  1
2  30.0  10.0  1
3   NaN   NaN  1
</code>```

Tried the below code as well:

```<code>df['C'] = df.apply(lambda row:0 if (row['A'].isnull() or row['B'].isnull())  else 1, axis=1)
</code>```

getting the below error.

```<code>AttributeError: ("'float' object has no attribute 'isnull'", 'occurred at index 0')
</code>```

答:
Use notnull + all:

```<code>df['C'] = df.notnull().all(1).astype(int)
df

      A     B  C
0  10.0  20.0  1
1  20.0   NaN  0
2  30.0  10.0  1
3   NaN   NaN  0
</code>```

Body:
I have a dataframe with NaNs

df = pd.DataFrame({"A": [10,20,30, np.nan], "B": [20, np.nan, 10,np.nan]})

     A     B
0  10.0  20.0
1  20.0   NaN
2  30.0  10.0
3   NaN   NaN

I would like to create a new column 'C'.
In  any row if either column 'A' or 'B' has a NaN, column 'C' will be set to 0 else 1.

I would like to get as below:

      A     B  C
0  10.0  20.0  1
1  20.0   NaN  0
2  30.0  10.0  1
3   NaN   NaN  0

I tried the below code:

df['C'] = df.apply(lambda row:0 if (row['A']=='NaN' or row['B']=='NaN')  else 1, axis=1)

I get the below df. Column C is always set to 1.

      A     B  C
0  10.0  20.0  1
1  20.0   NaN  1
2  30.0  10.0  1
3   NaN   NaN  1

Tried the below code as well:

df['C'] = df.apply(lambda row:0 if (row['A'].isnull() or row['B'].isnull())  else 1, axis=1)

getting the below error.

AttributeError: ("'float' object has no attribute 'isnull'", 'occurred at index 0')

Body:
Use notnull + all:

df['C'] = df.notnull().all(1).astype(int)
df

      A     B  C
0  10.0  20.0  1
1  20.0   NaN  0
2  30.0  10.0  1
3   NaN   NaN  0


问:
Validation loss in keras while training LSTM and stability of LSTM
I am using Keras now to train my LSTM model for a time series problem. My activation function is linear and the optimizer is Rmsprop.
However, i observe the tendency that while the training loss is decreasing slowly overtime, and fluctuate around a small value, the validation loss jumps up and down with a large variance.

Therefore, I come up with two questions:
1. Does the validation loss affect the training process? Will the algorithm look at the validation loss and slow down the learning rate in case it fluctuates alot?
2. How can i make the model more stable so that it will return a more stable values of validation loss?

Thanks

答:
Possible reasons:

Your validation set is very small compare to your trainning set which usually happens. A little change of weights makes validation loss fluctuate much more than trainning loss. This may not neccessary mean that your model is overfiting. As long as the overall trendency of validation loss keeps decreasing.

May be your train and validation data are from different sources, they may have different distributions. This may happen when your data is time series, and you split your train/validation data by a specific timestamp.

Does the validation loss affect the training process?

No, validation(forward-pass-once) and training(forward-and-backward) are different processes. Hence a single forword pass does not change how would you train next.

Will the algorithm look at the validation loss and slow down the learning rate in case it fluctuates alot?

No, But I guess you can implement your own method to do so. However, one thing should be noted, the model is trying to learn the best solution to your cost function which are fed by trainning data only, so changing this learning rate by observing validation loss doesnt make too much sense.

How can i make the model more stable so that it will return a more stable values of validation loss?

The reasons are expained above. If it is the first case, enlarge validation set will make your loss looks more stable but it does NOT mean it fits better. My suggestion is as long as your are sure your model does not overfit (gap between train loss and validation loss are not too large ), you can just save the model which gives the lowest validation loss.

If its the second case, it can be complecated depend on your case. You could try to exclude samples in trainning set which are not "similar" with your validation set, or enlarge your model's capacity if you have enough data. Or perhapes add more metrics to monitor how well the training.


问:
Entity Framework - passing null value as parameter
I am using contrast security (third party tool that indicates SQL Injection, Vulnerabilities) and entity framework, my code is like this:

```<code>public int Insert(UserAddress userAddress)
{
    _context.Entry(userAddress).State = EntityState.Added;
    _context.SaveChanges();
    return userAddress.Id;
}
</code>```

When SaveChanges() gets executed, an insert query is generated like this:

```<code>INSERT [dbo].[Address] ([UserId], [Name], [Address1], [Address2],
                        [City], [State], [PostalCode],
                        [Location], [LocationTypeId],
                        [BusinessName], [DeliveryInstructions],
                        [IsDefault], [SortOrder])
VALUES ('111111a1-22z2-33x3-44y4-fbad42c09c3a', @2, 'address1', null,
        'Alpharetta', 'GA', 30005,
        'POINT (-80.2427068 30.0925161)', 0,
        '', '',
        1, 0)
</code>```

Now, according to contrast security, passing "null" in query is not ethical, it's bad practice - but I want to allow null values!

Can I pass null values using SQL parameters to the SaveChanges() method?

Is there any way to handle this? Does anyone have any idea?

答:
I'm one of the developers for Contrast Security .NET agent.  It does sound like a false positive with our product.  There should not be any problems with using nulls in insert statements.

Could you please submit a support request and include your finding trace xml?  We'll be happy to take a look and fix this issue on our end.

Body:
I am using contrast security (third party tool that indicates SQL Injection, Vulnerabilities) and entity framework, my code is like this:

public int Insert(UserAddress userAddress)
{
    _context.Entry(userAddress).State = EntityState.Added;
    _context.SaveChanges();
    return userAddress.Id;
}

When SaveChanges() gets executed, an insert query is generated like this:

INSERT [dbo].[Address] ([UserId], [Name], [Address1], [Address2],
                        [City], [State], [PostalCode],
                        [Location], [LocationTypeId],
                        [BusinessName], [DeliveryInstructions],
                        [IsDefault], [SortOrder])
VALUES ('111111a1-22z2-33x3-44y4-fbad42c09c3a', @2, 'address1', null,
        'Alpharetta', 'GA', 30005,
        'POINT (-80.2427068 30.0925161)', 0,
        '', '',
        1, 0)

Now, according to contrast security, passing "null" in query is not ethical, it's bad practice - but I want to allow null values!

Can I pass null values using SQL parameters to the SaveChanges() method?

Is there any way to handle this? Does anyone have any idea?


问:
SQL: Add only a year value in a date column
I want a table with the name of an employee and the year of his birth. ONLY THE YEAR IN DATE FORMAT:

```<code>CREATE TABLE EMPLOYEE(
  Name VARCHAR2(50) NOT NULL,
  Year_Birth DATE NOT NULL,
  PRIMARY KEY (Name)
);
</code>```

I want to do this:

```<code>INSERT INTO EMPLOYEE(Name, Year_Birth)
VALUES ('John Smith', 1985);
</code>```

But it doesn't work (cause i'm passing a number value to a date column). I also tried this:

```<code>INSERT INTO EMPLOYEE(Name, Year_Birth)
VALUES ('John Smith', to_date('1972','YYYY') )
</code>```

If i try this one i will get this:
ORA-02290: check constraint (PROJECTNAME.SYS_C0066777818) violated

Year_Birth must be a date column. Is there any way to achieve this?

答:
I think birth year should be an INT, like this:

```<code>CREATE TABLE EMPLOYEE(
  Name VARCHAR(50) NOT NULL,
  Year_Birth INT NOT NULL,
  PRIMARY KEY (Name)
);
</code>```

Then this should work:

```<code>INSERT INTO EMPLOYEE(Name, Year_Birth)
VALUES ('John Smith', 1985);
</code>```

Body:
I want a table with the name of an employee and the year of his birth. ONLY THE YEAR IN DATE FORMAT:

CREATE TABLE EMPLOYEE(
  Name VARCHAR2(50) NOT NULL,
  Year_Birth DATE NOT NULL,
  PRIMARY KEY (Name)
);

I want to do this:

INSERT INTO EMPLOYEE(Name, Year_Birth)
VALUES ('John Smith', 1985);

But it doesn't work (cause i'm passing a number value to a date column). I also tried this:

INSERT INTO EMPLOYEE(Name, Year_Birth)
VALUES ('John Smith', to_date('1972','YYYY') )

If i try this one i will get this:
ORA-02290: check constraint (PROJECTNAME.SYS_C0066777818) violated

Year_Birth must be a date column. Is there any way to achieve this?

Body:
I think birth year should be an INT, like this:

CREATE TABLE EMPLOYEE(
  Name VARCHAR(50) NOT NULL,
  Year_Birth INT NOT NULL,
  PRIMARY KEY (Name)
);

Then this should work:

INSERT INTO EMPLOYEE(Name, Year_Birth)
VALUES ('John Smith', 1985);

ContentLicense: CC BY-SA 4.0


问:
Spring JPARepository querying many to many intersection table
I have 3 entity classes as follows (Example taken from https://hellokoding.com/jpa-many-to-many-extra-columns-relationship-mapping-example-with-spring-boot-maven-and-mysql/)

Book class

```<code>@Entity
public class Book{
    private int id;
    private String name;
    private Set<BookPublisher> bookPublishers;

    public Book() {
    }

    public Book(String name) {
        this.name = name;
        bookPublishers = new HashSet<>();
    }

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @OneToMany(mappedBy = "book", cascade = CascadeType.ALL, orphanRemoval = true)
    public Set<BookPublisher>   getBookPublishers() {
        return bookPublishers;
    }

    public void setBookPublishers(Set<BookPublisher> bookPublishers) {
        this.bookPublishers = bookPublishers;
    }
}
</code>```

Publisher class

```<code>@Entity
public class Publisher {
    private int id;
    private String name;
    private Set<BookPublisher> bookPublishers;

    public Publisher(){

    }

    public Publisher(String name){
        this.name = name;
    }

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @OneToMany(mappedBy = "publisher")
    public Set<BookPublisher> getBookPublishers() {
        return bookPublishers;
    }

    public void setBookPublishers(Set<BookPublisher> bookPublishers) {
        this.bookPublishers = bookPublishers;
    }
}
</code>```

Intersection Table

```<code>@Entity
@Table(name = "book_publisher")
public class BookPublisher implements Serializable{
    private Book book;
    private Publisher publisher;
    private Date publishedDate;

    @Id
    @ManyToOne
    @JoinColumn(name = "book_id")
    public Book getBook() {
        return book;
    }

    public void setBook(Book book) {
        this.book = book;
    }

    @Id
    @ManyToOne
    @JoinColumn(name = "publisher_id")
    public Publisher getPublisher() {
        return publisher;
    }

    public void setPublisher(Publisher publisher) {
        this.publisher = publisher;
    }

    @Column(name = "published_date")
    public Date getPublishedDate() {
        return publishedDate;
    }

    public void setPublishedDate(Date publishedDate) {
        this.publishedDate = publishedDate;
    }
}
</code>```

I want to query 2 things,

Get list of books belonging to a particular publisher e.g. get all books associated with publisher 100

Get list of books not associated with a particular publisher e.g. get all books not associated with publisher 100

I want to achieve this using a simple JPARepository query if possible like findByXYZIn(...) etc.

Please let me know if querying a many to many relation is possible using JPA repository queries and if yes, whether I can do it directly or would it require any changes in the entity classes

答:
Well you can use named Queries to fulfill your requirements:

```<code>@Query("select b from Book b where b.publisher.idd = ?1")
Book findByPublisherId(int id);

@Query("select b from Book b where b.publisher.idd <> ?1")
Book findByDifferentPublisherId(int id);
</code>```

Take a look at Using @Query Spring docs for further details.

Body:
I have 3 entity classes as follows (Example taken from https://hellokoding.com/jpa-many-to-many-extra-columns-relationship-mapping-example-with-spring-boot-maven-and-mysql/)

Book class

@Entity
public class Book{
    private int id;
    private String name;
    private Set<BookPublisher> bookPublishers;

    public Book() {
    }

    public Book(String name) {
        this.name = name;
        bookPublishers = new HashSet<>();
    }

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @OneToMany(mappedBy = "book", cascade = CascadeType.ALL, orphanRemoval = true)
    public Set<BookPublisher>   getBookPublishers() {
        return bookPublishers;
    }

    public void setBookPublishers(Set<BookPublisher> bookPublishers) {
        this.bookPublishers = bookPublishers;
    }
}

Publisher class

@Entity
public class Publisher {
    private int id;
    private String name;
    private Set<BookPublisher> bookPublishers;

    public Publisher(){

    }

    public Publisher(String name){
        this.name = name;
    }

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @OneToMany(mappedBy = "publisher")
    public Set<BookPublisher> getBookPublishers() {
        return bookPublishers;
    }

    public void setBookPublishers(Set<BookPublisher> bookPublishers) {
        this.bookPublishers = bookPublishers;
    }
}

Intersection Table

@Entity
@Table(name = "book_publisher")
public class BookPublisher implements Serializable{
    private Book book;
    private Publisher publisher;
    private Date publishedDate;

    @Id
    @ManyToOne
    @JoinColumn(name = "book_id")
    public Book getBook() {
        return book;
    }

    public void setBook(Book book) {
        this.book = book;
    }

    @Id
    @ManyToOne
    @JoinColumn(name = "publisher_id")
    public Publisher getPublisher() {
        return publisher;
    }

    public void setPublisher(Publisher publisher) {
        this.publisher = publisher;
    }

    @Column(name = "published_date")
    public Date getPublishedDate() {
        return publishedDate;
    }

    public void setPublishedDate(Date publishedDate) {
        this.publishedDate = publishedDate;
    }
}

I want to query 2 things,

Get list of books belonging to a particular publisher e.g. get all books associated with publisher 100

Get list of books not associated with a particular publisher e.g. get all books not associated with publisher 100

I want to achieve this using a simple JPARepository query if possible like findByXYZIn(...) etc.

Please let me know if querying a many to many relation is possible using JPA repository queries and if yes, whether I can do it directly or would it require any changes in the entity classes

Body:
Well you can use named Queries to fulfill your requirements:

@Query("select b from Book b where b.publisher.idd = ?1")
Book findByPublisherId(int id);

@Query("select b from Book b where b.publisher.idd <> ?1")
Book findByDifferentPublisherId(int id);

Take a look at Using @Query Spring docs for further details.


问:
Algorithm to generate random points inside a circle which has a square inscribed in it not working as it should
I try to determine the probabilty of point being inside a square that is inscribed into a circle of radius 1. Firstly I generate my N random points inside my circle and then I check for each one if both the Ox and Oy coordinates are smaller than half of the width respectively the height.I know that the answer gets closer to 2/Pi but I get a number closer to 0,78.. which is not good.

```<code>`close all;clear all;clc;
%length of width and height
a=sqrt(2);
%radius of circle (it is 1)
raza=a*sqrt(2)/2;
%total number of points
N=1000;

%Here I generate my N random numbers inside the circle
theta = 2*pi*rand(1,N);
r = rand(1,N);
x = r.*cos(theta);
y = r.*sin(theta);

%here I count how many point are inside the square that is inscribed in the
%circle
cont = 0;
for i=1:N
    if x(i) >= -a/2 && x(i) <= a/2 && y(i) >= -a/2 && y(i) <= a/2
        cont = cont + 1;
    end
end
%Here i get sth closer to 0,78...not 2/Pi(0,63..)
cont/N
</code>```

Do I generate the points in a wrong way or do I count the points inside the square improperly?

`

答:
I see there is a simple mistake, please see following formula

```<code>square_area/circle_area = number_of_total/number_of_inside_circle
</code>```

so

```<code>(2*R)^2/(pi*R^2) = n_total/n_Indide  --> 4*R^2/pi*R^2=n/cont --> 4/pi = n/con
</code>```

so if you calculate the cont/N so you try to calculate pi/4 base on above formula and 'pi/4is equal to0.7854` so your close

NOTE: if you want to calculate pi then you can write 4*cont/N

But if you want to summarize your program you can write it like below

```<code>n=2000;
x=2*rand(1,n)-1;
y=2*rand(1,n)-1;
inside_index = find(sqrt(x.^2+y.^2)<1); % find index of those point that are inside the circle
PI = 4*numel(inside_index)/n
</code>```

which gave you

```<code>PI =

  3.1540
</code>```

Body:
I try to determine the probabilty of point being inside a square that is inscribed into a circle of radius 1. Firstly I generate my N random points inside my circle and then I check for each one if both the Ox and Oy coordinates are smaller than half of the width respectively the height.I know that the answer gets closer to 2/Pi but I get a number closer to 0,78.. which is not good.

`close all;clear all;clc;
%length of width and height
a=sqrt(2);
%radius of circle (it is 1)
raza=a*sqrt(2)/2;
%total number of points
N=1000;

%Here I generate my N random numbers inside the circle
theta = 2*pi*rand(1,N);
r = rand(1,N);
x = r.*cos(theta);
y = r.*sin(theta);

%here I count how many point are inside the square that is inscribed in the
%circle
cont = 0;
for i=1:N
    if x(i) >= -a/2 && x(i) <= a/2 && y(i) >= -a/2 && y(i) <= a/2
        cont = cont + 1;
    end
end
%Here i get sth closer to 0,78...not 2/Pi(0,63..)
cont/N

Do I generate the points in a wrong way or do I count the points inside the square improperly?

`

Body:
I see there is a simple mistake, please see following formula

square_area/circle_area = number_of_total/number_of_inside_circle

so

(2*R)^2/(pi*R^2) = n_total/n_Indide  --> 4*R^2/pi*R^2=n/cont --> 4/pi = n/con

so if you calculate the cont/N so you try to calculate pi/4 base on above formula and 'pi/4is equal to0.7854` so your close

NOTE: if you want to calculate pi then you can write 4*cont/N

But if you want to summarize your program you can write it like below

n=2000;
x=2*rand(1,n)-1;
y=2*rand(1,n)-1;
inside_index = find(sqrt(x.^2+y.^2)<1); % find index of those point that are inside the circle
PI = 4*numel(inside_index)/n

which gave you

PI =

  3.1540


答:
You can create a column which is of data type int. This will then let you save the year of birth.

If the column must be of data type date then you could just save the date as the first of Jan with the relevant year (eg. for the year 2017 enter '20170101'). This will still allow you then perform date calculations on the data.

Title: SQL: Add only a year value in a date column


问:
If I have an array in excel like (1,1,0,0,0,1,0,0) a
If I have an array in excel like

```<code>A   B   C   D   E   F   G   H

1   1   0   0   0   1   0   0
</code>```

and I want to check the condition that IF even one 1 exists I want to get output as BUY, and if all are 0, then not buy. Can you please tell  me how to get this? Thanks in advance.

答:
```<code>= IF(SUMPRODUCT(<array>)>0,"buy","don't buy")
</code>```

where <array> is a cell range, e.g. A1:H1.

Body:
If I have an array in excel like

A   B   C   D   E   F   G   H

1   1   0   0   0   1   0   0

and I want to check the condition that IF even one 1 exists I want to get output as BUY, and if all are 0, then not buy. Can you please tell  me how to get this? Thanks in advance.

Body:
= IF(SUMPRODUCT(<array>)>0,"buy","don't buy")

where <array> is a cell range, e.g. A1:H1.


问:
Setting maxJsonLength property for USQL Newtonsoft JSON extractor
I'm using USQL for Azure data lake project and my input is in JSON format and I'm extracting each line and converting it back to JSON tuple. But the issue is some string lengths are bigger 102400 and Newtonsoft JSON extractor defaults to 102400 maximum length and this is causing failure on these records. Is it possible to change maxJsonLength property to bigger value to handle these large inputs? I found a property MaximumLength in Newtonsoft.Json.XML file inside assemblies, but it is also not working.
 Any suggestion is highly appreciated. </p>

答: Please note that U-SQL currently has a string data type size limit of 128kB (in UTF-8 encoded data). So even if you increase your Newtonsoft properties, you may run into that limit. Can you provide more information on what you are exactly doing and what the exact error message is to provide you more concrete answers?</p>


问:
React-Native Button style not work

Import_this

import {AppRegistry, Text, View, Button, StyleSheet} from 'react-native';
```

<p>This my React Button code But style not working Hare ...</p>

<pre class="lang-jsx prettyprint-override"><code><Button
  onPress={this.onPress.bind(this)}
  title={"Go Back"}
  style={{color: 'red', marginTop: 10, padding: 10}}
/>
</code>```

Also I was try by this code

<Button
       containerStyle={{padding:10, height:45, overflow:'hidden',
       borderRadius:4, backgroundColor: 'white'}}
       style={{fontSize: 20, color: 'green'}}
       onPress={this.onPress.bind(this)} title={"Go Back"}
      > Press me!
</Button>
```

<h1>Update Question:</h1>

<p>Also I was try by This way..</p>

<pre class="lang-jsx prettyprint-override"><code><Button
    onPress={this.onPress.bind(this)}
    title={"Go Back"}
    style={styles.buttonStyle}
>ku ka</Button>
</code>```

Style

const styles = StyleSheet.create({
    buttonStyle: {
        color: 'red',
        marginTop: 20,
        padding: 20,
        backgroundColor: 'green'
    }
});
```

But No out put:
Screenshot  of my phone:-

答:
Only learning myself, but wrapping in a View may allow you to add styles around the button.

const Stack = StackNavigator({
  Home: {
    screen: HomeView,
    navigationOptions: {
      title: 'Home View'
    }
  },
  CoolView: {
    screen: CoolView,
    navigationOptions: ({navigation}) => ({
      title: 'Cool View',
      headerRight: (<View style={{marginRight: 16}}><Button
        title="Cool"
        onPress={() => alert('cool')}
      /></View>
    )
    })
  }
})
```

Title: React-Native Button style not work

Body:
Import_this

import {AppRegistry, Text, View, Button, StyleSheet} from 'react-native';

This my React Button code But style not working Hare ...

<Button
  onPress={this.onPress.bind(this)}
  title={"Go Back"}
  style={{color: 'red', marginTop: 10, padding: 10}}
/>

Also I was try by this code

<Button
       containerStyle={{padding:10, height:45, overflow:'hidden',
       borderRadius:4, backgroundColor: 'white'}}
       style={{fontSize: 20, color: 'green'}}
       onPress={this.onPress.bind(this)} title={"Go Back"}
      > Press me!
</Button>

Update Question:

Also I was try by This way..

<Button
    onPress={this.onPress.bind(this)}
    title={"Go Back"}
    style={styles.buttonStyle}
>ku ka</Button>

Style

const styles = StyleSheet.create({
    buttonStyle: {
        color: 'red',
        marginTop: 20,
        padding: 20,
        backgroundColor: 'green'
    }
});

But No out put:
Screenshot  of my phone:-


问:
Collatz sequence using linq c#
Good afternoon guys, I have a following problem of the school to solve, being it in relation to Collatz Problem, where I need to develop an application that will find out the starting number between 1 and 1 million that produces the largest sequence.

I made the following code without applying LINQ, and would like to know how to use linq in this situation.

```<code>var sequence_size = 0;
        var best_number = 0;
        var sequence = 0;

        for (var i = 0; i <= 1000000; i ++)
        {
            var size_ = 1;
            sequence = i;

            while (sequence! = 1)
            {

                sequence = sequence% 2 == 0? sequence / 2: sequence * 3 + 1;
                size ++;
            }

            if (size> size)
            {
                size_sequence = size;
                best_number = i;
            }
        }
</code>```

答:
This is what I'd recommend:

```<code>public class MaxSequenceFinder
{
    public int FindBestCollatzSequence(int start, int count)
    {
        return Enumerable.Range(start, count)
            .Select(n => new { Number = n, SequenceLength = CalcCollatzSequence((long)n) })
            .Aggregate((i, j) => i.SequenceLength > j.SequenceLength ? i : j)
            .Number;
    }

    private int CalcCollatzSequence(long n)
    {
        int sequenceLength = 0;

        do
        {
            n = CalcNextTerm(n);
            sequenceLength++;
        }
        while (n != 1);

        return sequenceLength;
    }

    private long CalcNextTerm(long previousTerm)
    {
        return previousTerm % 2 == 0 ? previousTerm / 2 : previousTerm * 3 + 1;
    }
}
</code>```

Which can be used like this:

```<code>var finder = new MaxSequenceFinder();
int result = finder.FindBestCollatzSequence(1, 100);
Console.WriteLine(result);
</code>```

Running it for a count of 1 000 000 will take some time. But in this case (< 100) the longest sequence is:

```<code>97
</code>```

Title: Collatz sequence using linq c#

Body:
Good afternoon guys, I have a following problem of the school to solve, being it in relation to Collatz Problem, where I need to develop an application that will find out the starting number between 1 and 1 million that produces the largest sequence.

I made the following code without applying LINQ, and would like to know how to use linq in this situation.

var sequence_size = 0;
        var best_number = 0;
        var sequence = 0;

        for (var i = 0; i <= 1000000; i ++)
        {
            var size_ = 1;
            sequence = i;

            while (sequence! = 1)
            {

                sequence = sequence% 2 == 0? sequence / 2: sequence * 3 + 1;
                size ++;
            }

            if (size> size)
            {
                size_sequence = size;
                best_number = i;
            }
        }

Body:
This is what I'd recommend:

public class MaxSequenceFinder
{
    public int FindBestCollatzSequence(int start, int count)
    {
        return Enumerable.Range(start, count)
            .Select(n => new { Number = n, SequenceLength = CalcCollatzSequence((long)n) })
            .Aggregate((i, j) => i.SequenceLength > j.SequenceLength ? i : j)
            .Number;
    }

    private int CalcCollatzSequence(long n)
    {
        int sequenceLength = 0;

        do
        {
            n = CalcNextTerm(n);
            sequenceLength++;
        }
        while (n != 1);

        return sequenceLength;
    }

    private long CalcNextTerm(long previousTerm)
    {
        return previousTerm % 2 == 0 ? previousTerm / 2 : previousTerm * 3 + 1;
    }
}

Which can be used like this:

var finder = new MaxSequenceFinder();
int result = finder.FindBestCollatzSequence(1, 100);
Console.WriteLine(result);

Running it for a count of 1 000 000 will take some time. But in this case (< 100) the longest sequence is:

97


问:
PHP - Round more than 14 decimal places
Is it possible to round more than 14 decimal places?

If I do:

```<code>echo round(1/3, 4); // equals .3333
echo round(1/3, 14); // equals .33333333333333
echo round(1/3, 20); // equals .33333333333333
</code>```

Is it possible to get 20 decimal places in PHP for absolute precision?

答:
For lots of decimal places, you'd better use BC Math rather than trying to force PHP to do it.

```<code>$result = bcdiv(1, 3, 20);
</code>```

You can change the precision ini setting, but you won't get the results you're expecting.

Title: PHP - Round more than 14 decimal places

Body:
Is it possible to round more than 14 decimal places?

If I do:

echo round(1/3, 4); // equals .3333
echo round(1/3, 14); // equals .33333333333333
echo round(1/3, 20); // equals .33333333333333

Is it possible to get 20 decimal places in PHP for absolute precision?

Body:
For lots of decimal places, you'd better use BC Math rather than trying to force PHP to do it.

$result = bcdiv(1, 3, 20);

You can change the precision ini setting, but you won't get the results you're expecting.


问:
Adding unrelated step to Robot Data Driven test case
Consider the following data driven test case:

```<code>TC001_Sign_in_test
    [Documentation]     testing sign in with various credentials.
    [Teardown]          ${None}
    [Template]          attempt sign in and check status
    ${corr_usrnm}       ${corr_pswd}        ${welcome_screeen}
    ${corr_usrnm}       ${mispld_pswd}      ${sign_in_error_label}
    ${corr_usrnm}       ${EMPTY}            ${sign_in_error_label}
    ${EMPTY}            ${corr_pswd}        ${sign_in_error_label}
    ${mispld_usrnm}     ${corr_pswd}        ${sign_in_error_label}
</code>```

After my first step in the test where we login with correct username and correct password, my app is already signed in and I would like to sign out so I can work on the next incorrect password step.

I was wondering if it was possible to insert a sign out step between the correct password and incorrect password steps. I dont have to do it this way, I could put the successful step in the end and solve the problem easily or just create another separate test for successful login, but I would like to know if it was somehow possible to insert an action in between the two rows of the data table.

答:
Simply add the logout step(s) to your template keyword, attempt sign in and check status. If this is a keyword imported from a library you cannot modify for some reason, you can always create a wrapper user keyword that calls this keyword and then calls the keyword(s) required to logout

Of course since not all of your tests actually make a successful login, you may have to setup a condition based on the expected status passed to your template keyword.

Body:
Consider the following data driven test case:

TC001_Sign_in_test
    [Documentation]     testing sign in with various credentials.
    [Teardown]          ${None}
    [Template]          attempt sign in and check status
    ${corr_usrnm}       ${corr_pswd}        ${welcome_screeen}
    ${corr_usrnm}       ${mispld_pswd}      ${sign_in_error_label}
    ${corr_usrnm}       ${EMPTY}            ${sign_in_error_label}
    ${EMPTY}            ${corr_pswd}        ${sign_in_error_label}
    ${mispld_usrnm}     ${corr_pswd}        ${sign_in_error_label}

After my first step in the test where we login with correct username and correct password, my app is already signed in and I would like to sign out so I can work on the next incorrect password step.

I was wondering if it was possible to insert a sign out step between the correct password and incorrect password steps. I dont have to do it this way, I could put the successful step in the end and solve the problem easily or just create another separate test for successful login, but I would like to know if it was somehow possible to insert an action in between the two rows of the data table.


问:
dynamically allocated matrix gives seg fault when printed
this code allocates a matrix by means of a series of function calls, but when i print it, it return a segmentation fault error.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void mat_init(int** matx);
void pp_init(int** matx);
void p_init(int** matx);
void mat_fill(int** matx);
void mat_print(int** matx);

int main(void)
{
    srand((unsigned)time(NULL));
    int** matrix;
    mat_init(matrix);
    mat_print(matrix);
    return 0;
}

void mat_init(int** matx)
{
    pp_init(matx);
}

void pp_init(int** matx)
{

    matx=malloc(4*sizeof(int*));
    p_init(matx);
}

void p_init(int** matx)
{
    for(int i=0;i<4;i++)
    {
        *(matx+i)=malloc(4*sizeof(int));
    }
    mat_fill(matx);
}

void mat_fill(int** matx)
{
    for(int i=0;i<4;i++)
    {
        for(int j=0;j<4;j++)
        {
            *(*(matx+i)+j)=rand()%5;
        }
    }
    //mat_print(matx);
}

void mat_print(int** matx)
{
    printf("The matrix is:\n");
    for(int i=0;i<4;i++)
    {
        for(int j=0;j<4;j++)
        {
            printf("%1i|",*(*(matx+i)+j));
        }
        puts("");
    }
    puts("");
}
</code>```

note that this happens only if i print the matrix using mat_print() int the main, if i use it in the function mat_fill() it works correctly, showing that it's been properly initialized.
What's the problem?

答:
You need to do this:

```<code>int** mat_init(int** matx);
int** pp_init(int** matx);

int main(void)
{
    matrix=mat_init(matrix);
}

int** mat_init(int** matx)
{
    return pp_init(matx);
}

int** pp_init(int** matx)
{
    matx=malloc(4*sizeof(int*));
    p_init(matx);
    return matx;
}
</code>```

I omitted some lines that I didn't change. Another option is this:

```<code>void mat_init(int*** matx);
void pp_init(int*** matx);

int main(void)
{
    mat_init(&matrix);
}

void mat_init(int*** matx)
{
    pp_init(matx);
}

void pp_init(int*** matx)
{
    *matx=malloc(4*sizeof(int*));
    p_init(*matx);
}
</code>```

Another thing: You're using the value 4 on a lot of places. That's dangerous. use a constant instead.

```<code>#define MAT_SIZE 4

void mat_fill(int** matx) {
    for(int i=0;i<MAT_SIZE;i++) {
        for(int j=0;j<MAT_SIZE;j++)
</code>```

Body:
this code allocates a matrix by means of a series of function calls, but when i print it, it return a segmentation fault error.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void mat_init(int** matx);
void pp_init(int** matx);
void p_init(int** matx);
void mat_fill(int** matx);
void mat_print(int** matx);

int main(void)
{
    srand((unsigned)time(NULL));
    int** matrix;
    mat_init(matrix);
    mat_print(matrix);
    return 0;
}

void mat_init(int** matx)
{
    pp_init(matx);
}

void pp_init(int** matx)
{

    matx=malloc(4*sizeof(int*));
    p_init(matx);
}

void p_init(int** matx)
{
    for(int i=0;i<4;i++)
    {
        *(matx+i)=malloc(4*sizeof(int));
    }
    mat_fill(matx);
}

void mat_fill(int** matx)
{
    for(int i=0;i<4;i++)
    {
        for(int j=0;j<4;j++)
        {
            *(*(matx+i)+j)=rand()%5;
        }
    }
    //mat_print(matx);
}

void mat_print(int** matx)
{
    printf("The matrix is:\n");
    for(int i=0;i<4;i++)
    {
        for(int j=0;j<4;j++)
        {
            printf("%1i|",*(*(matx+i)+j));
        }
        puts("");
    }
    puts("");
}

note that this happens only if i print the matrix using mat_print() int the main, if i use it in the function mat_fill() it works correctly, showing that it's been properly initialized.
What's the problem?

Body:
You need to do this:

int** mat_init(int** matx);
int** pp_init(int** matx);

int main(void)
{
    matrix=mat_init(matrix);
}

int** mat_init(int** matx)
{
    return pp_init(matx);
}

int** pp_init(int** matx)
{
    matx=malloc(4*sizeof(int*));
    p_init(matx);
    return matx;
}

I omitted some lines that I didn't change. Another option is this:

void mat_init(int*** matx);
void pp_init(int*** matx);

int main(void)
{
    mat_init(&matrix);
}

void mat_init(int*** matx)
{
    pp_init(matx);
}

void pp_init(int*** matx)
{
    *matx=malloc(4*sizeof(int*));
    p_init(*matx);
}

Another thing: You're using the value 4 on a lot of places. That's dangerous. use a constant instead.

#define MAT_SIZE 4

void mat_fill(int** matx) {
    for(int i=0;i<MAT_SIZE;i++) {
        for(int j=0;j<MAT_SIZE;j++)


问:
Maximum memory which malloc can allocate
I was trying to figure out how much memory I can malloc to maximum extent on my machine
(1 Gb RAM 160 Gb HD Windows platform).

I read that the maximum memory malloc can allocate is limited to physical memory (on heap).

Also when a program exceeds consumption of memory to a certain level, the computer stops working because other applications do not get enough memory that they require.

So to confirm, I wrote a small program in C:

```<code>int main(){
    int *p;
    while(1){
        p=(int *)malloc(4);
        if(!p)break;
    }
}
</code>```

I was hoping that there would be a time when memory allocation would fail and the loop would break, but my computer hung as it was an infinite loop.

I waited for about an hour and finally I had to force shut down my computer.

Some questions:

Does malloc allocate memory from HD also?

What was the reason for above behaviour?

Why didn't loop break at any point of time?

Why wasn't there any allocation failure?

答:
I know this thread is old, but for anyone willing to give it a try oneself, use this code snipped

```<code>#include <stdlib.h>

int main() {
int *p;
while(1) {
    int inc=1024*1024*sizeof(char);
    p=(int*) calloc(1,inc);
    if(!p) break;
    }
}
</code>```

run

```<code>$ gcc memtest.c
$ ./a.out
</code>```

upon running, this code fills up ones RAM until killed by the kernel. Using calloc instead of malloc to prevent "lazy evaluation". Ideas taken from this thread:
Malloc Memory Questions

This code quickly filled my RAM (4Gb) and then in about 2 minutes my 20Gb swap partition before it died. 64bit Linux of course.

Body:
I was trying to figure out how much memory I can malloc to maximum extent on my machine
(1 Gb RAM 160 Gb HD Windows platform).

I read that the maximum memory malloc can allocate is limited to physical memory (on heap).

Also when a program exceeds consumption of memory to a certain level, the computer stops working because other applications do not get enough memory that they require.

So to confirm, I wrote a small program in C:

int main(){
    int *p;
    while(1){
        p=(int *)malloc(4);
        if(!p)break;
    }
}

I was hoping that there would be a time when memory allocation would fail and the loop would break, but my computer hung as it was an infinite loop.

I waited for about an hour and finally I had to force shut down my computer.

Some questions:

Does malloc allocate memory from HD also?

What was the reason for above behaviour?

Why didn't loop break at any point of time?

Why wasn't there any allocation failure?

Body:
I know this thread is old, but for anyone willing to give it a try oneself, use this code snipped

#include <stdlib.h>

int main() {
int *p;
while(1) {
    int inc=1024*1024*sizeof(char);
    p=(int*) calloc(1,inc);
    if(!p) break;
    }
}

run

$ gcc memtest.c
$ ./a.out

upon running, this code fills up ones RAM until killed by the kernel. Using calloc instead of malloc to prevent "lazy evaluation". Ideas taken from this thread:
Malloc Memory Questions

This code quickly filled my RAM (4Gb) and then in about 2 minutes my 20Gb swap partition before it died. 64bit Linux of course.


问:
Can i use a partial view inside a partial view?
Im using a partial view, and i have some Razor code that will be used a lot of times in the partial view... Can i use partial views inside this partial view?

Or have a better way to do this?

When i try to do this:

this is the principal page:

```<code>@model List<GolTripulacao.WebApi.Areas.LOG.Controllers.HomeController.Campo>

@{
    ViewBag.Title = "Relatorio";
}

<div>
    <div class="container">
        <div class="row">
            <div class="col-lg-8">
                <input type="text" id="" name="" />
            </div>
            <div class="col-lg-4">
                <div>
                    @Html.Partial("~/Areas/LOG/Views/Home/PhonePreview.cshtml", Model)
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

who uses a partial view:

```<code>@{
    Layout = null;
}

<div>
    <div style="border:1px solid black;font-size:20px;overflow:auto;">

        @if (Model != null)
        {
            <div class="container" style="background-color:orangered;padding-top:5px;padding-bottom:5px;">
                <div class="row">
                    <div class="col-sm-12">
                        @ViewBag.Relatorio
                    </div>
                </div>
            </div>

            foreach (var campo in Model)
            {
                if (campo.Tipo == "Text")
                {
                    @Html.Partial("~/Areas/LOG/Views/Home/text.cshtml", campo)
                }

            }
        }

    </div>

</div>

<style>

    input[type=date]::-webkit-inner-spin-button {
        -webkit-appearance: none;
        display: none;
    }

</style>
</code>```

and this partial calls this another partial

```<code><div class="container" style="padding-top:5px;padding-bottom:5px;">
    <div class="row">
        <div class="col-sm-4">
            @model.Name:
        </div>
        <div class="col-sm-8" style="text-align:right;">
            <input type="text" style="width:100%;" />
        </div>
    </div>
</div>
</code>```

gives me an error:

```<code>'HtmlHelper<dynamic>' has no applicable method named 'RenderPartial' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax
</code>```

regards!!

Rafael

答:
You are getting that error because your partial views are not strongly typed.

You need to make them strongly typed to the data you are passing in.

You are passing the Model of your principal page to the first partial view. Your Model is a list of Campo. So your first partial view should also be strongly typed to that type (List<Campo>).

Add this line as the first line in your first partial view (PhonePreview.cshtml)

```<code>@model List<GolTripulacao.WebApi.Areas.LOG.Controllers.HomeController.Campo>
</code>```

Inside your PhonePreview.cshtml partial view, you are looping through the items passed to it and calling the text.cshtml partial view when your if condition returns true. Here you are passing a simple Campo object to the text partial view. So it should be strongly typed to Campo type.

Add this line as the first line in your first partial view (text.cshtml)

```<code>@model GolTripulacao.WebApi.Areas.LOG.Controllers.HomeController.Campo
</code>```

. Also you should be accessing the Name property like Model.Name , not model.Name

```<code>@model GolTripulacao.WebApi.Areas.LOG.Controllers.HomeController.Campo
    <div class="col-sm-4">
        @Model.Name
    </div>
</code>```

Body:
Im using a partial view, and i have some Razor code that will be used a lot of times in the partial view... Can i use partial views inside this partial view?

Or have a better way to do this?

When i try to do this:

this is the principal page:

@model List<GolTripulacao.WebApi.Areas.LOG.Controllers.HomeController.Campo>

@{
    ViewBag.Title = "Relatorio";
}

                <input type="text" id="" name="" />

                    @Html.Partial("~/Areas/LOG/Views/Home/PhonePreview.cshtml", Model)

who uses a partial view:

@{
    Layout = null;
}

        @if (Model != null)
        {

                        @ViewBag.Relatorio

            foreach (var campo in Model)
            {
                if (campo.Tipo == "Text")
                {
                    @Html.Partial("~/Areas/LOG/Views/Home/text.cshtml", campo)
                }

            }
        }

and this partial calls this another partial

            @model.Name:

            <input type="text" style="width:100%;" />

gives me an error:

'HtmlHelper<dynamic>' has no applicable method named 'RenderPartial' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax

regards!!

Rafael

Body:
You are getting that error because your partial views are not strongly typed.

You need to make them strongly typed to the data you are passing in.

You are passing the Model of your principal page to the first partial view. Your Model is a list of Campo. So your first partial view should also be strongly typed to that type (List<Campo>).

Add this line as the first line in your first partial view (PhonePreview.cshtml)

@model List<GolTripulacao.WebApi.Areas.LOG.Controllers.HomeController.Campo>

Inside your PhonePreview.cshtml partial view, you are looping through the items passed to it and calling the text.cshtml partial view when your if condition returns true. Here you are passing a simple Campo object to the text partial view. So it should be strongly typed to Campo type.

Add this line as the first line in your first partial view (text.cshtml)

@model GolTripulacao.WebApi.Areas.LOG.Controllers.HomeController.Campo

. Also you should be accessing the Name property like Model.Name , not model.Name

@model GolTripulacao.WebApi.Areas.LOG.Controllers.HomeController.Campo
    <div class="col-sm-4">
        @Model.Name
    </div>


问:
Oracle : copy result of SQL statement to clipboard
I need to copy result from SQL to clipboard - is this possible?

I need copy of qty to clipboard.

My code:

```<code>declare qty NUMBER;
        part_no varchar(16);

begin
    qty := (select qty from part_stock where part_no='012345');

    if qty > 0 then
        error_sys.Appl_General('', 'Item_no is on stock');
    else
        error_sys.Appl_General('', 'Item_no is not on stock');
    end if;
end;
</code>```

Thank you

答:
If you're using PLSQL developer, on an SQL window, this icon will let you copy results to the clipboard, in several different formats.
<img src="https://i.stack.imgur.com/8klB4.png" alt="enter image description here"> </p>

Body:
I need to copy result from SQL to clipboard - is this possible?

I need copy of qty to clipboard.

My code:

declare qty NUMBER;
        part_no varchar(16);

begin
    qty := (select qty from part_stock where part_no='012345');

    if qty > 0 then
        error_sys.Appl_General('', 'Item_no is on stock');
    else
        error_sys.Appl_General('', 'Item_no is not on stock');
    end if;
end;

Thank you


问:
jq: Change multiple values
I'm trying to change multiple json values with this line

```<code> jq '.two="newval", .three="newval"' my.json
</code>```

with this is the input

```<code>{
  "one": {
    "val": 1
  },
  "two": "val",
  "three": "val",
  "four": "val"
}
</code>```

but the output is 2 jsons:

```<code>{
  "one": {
    "val": 1
  },
  "two": "newval",
  "three": "val",
  "four": "val"
}
{
  "one": {
    "val": 1
  },
  "two": "val",
  "three": "newval",
  "four": "val"
}
</code>```

How can I change multiple values and output in one item?

答:
Here is a method which uses + object addition to update multiple members.

```<code>. + {two:"newtwo", three:"newthree"}
</code>```

Sample Run (assumes data in data.json)

```<code>$ jq -M '. + {two:"newtwo", three:"newthree"}' data.json
{
  "one": {
    "val": 1
  },
  "two": "newtwo",
  "three": "newthree",
  "four": "val"
}
</code>```

Try it online at jqplay.org

Title: jq: Change multiple values

Body:
I'm trying to change multiple json values with this line

 jq '.two="newval", .three="newval"' my.json

with this is the input

{
  "one": {
    "val": 1
  },
  "two": "val",
  "three": "val",
  "four": "val"
}

but the output is 2 jsons:

{
  "one": {
    "val": 1
  },
  "two": "newval",
  "three": "val",
  "four": "val"
}
{
  "one": {
    "val": 1
  },
  "two": "val",
  "three": "newval",
  "four": "val"
}

How can I change multiple values and output in one item?

Body:
Here is a method which uses + object addition to update multiple members.

. + {two:"newtwo", three:"newthree"}

Sample Run (assumes data in data.json)

$ jq -M '. + {two:"newtwo", three:"newthree"}' data.json
{
  "one": {
    "val": 1
  },
  "two": "newtwo",
  "three": "newthree",
  "four": "val"
}

Try it online at jqplay.org


问:
Angular 2 Property Does not exist on type
I have a Class Like

```<code>export class R {
constructor(
    public id: Number,
    public dte: Date,
    ) { }
</code>```

}

a service That return R[] the code is like :`

```<code>return this.http.get(this.serverLocal).map(this.formatDate);

  formatDate(res: Response) {
    const data = res.json() as R[];
        data.forEach(D => {
        D.dte = new Date(D.dte);
    })
    return data;
}
</code>```

I get the 2 errors: property 'dte' does not exist on type 'R'.
I changed a lot of code for no avail. It's working if I do some change with ID, but not with dte date. What am I doing wrong?

答:
Before answering, take a look at HttpClient if you are using Angular 5 as json() is no more needed. An http get already returns a json by default.

If your json response has only these two entries (id and dte) you simply have to do the following:

```<code>. . .

import { HttpClient } from '@angular/common/http';

/** rxjs **/
import { Observable } from 'rxjs/Observable';

getStuff(someUrl: string): Observable<Array<R>> {
    return this.http.get(someUrl);
}
</code>```

If you need some error handling or, for instance, retry if the request gives error your should do something like:

```<code>. . .

import { HttpClient } from '@angular/common/http';

/** rxjs **/
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/throw';
import {catchError} from 'rxjs/operators/catchError';

getStuff(someUrl: string): Observable<Array<R>> {
    return this.http.get(someUrl)
        .pipe(
            retryWhen(errors =>
                // Do Stuff
            ),
            catchError((error: Error)  => {
                return Observable.throw(error);
            })
        );
}
</code>```

There is no actual need of mapping data, but, if you would like to do it, you should do like":

```<code>data.map((dataEntry) => new R(dataEntry))
</code>```

If you are still using Angular 4.x.x, you should get it going with:

```<code>. . .

import { Http } from '@angular/http';

/** rxjs **/
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/throw';
import {catchError} from 'rxjs/operators/catchError';

getStuff(someUrl: string): Observable<Array<R>> {
    return this.http.get(someUrl)
        .pipe(
            map((response: Response) => response.json()),
            catchError((error: Error)  => {
                return Observable.throw(error);
            })
        );
}
</code>```

Body:
I have a Class Like

export class R {
constructor(
    public id: Number,
    public dte: Date,
    ) { }

}

a service That return R[] the code is like :`

return this.http.get(this.serverLocal).map(this.formatDate);

  formatDate(res: Response) {
    const data = res.json() as R[];
        data.forEach(D => {
        D.dte = new Date(D.dte);
    })
    return data;
}

I get the 2 errors: property 'dte' does not exist on type 'R'.
I changed a lot of code for no avail. It's working if I do some change with ID, but not with dte date. What am I doing wrong?

Body:
Before answering, take a look at HttpClient if you are using Angular 5 as json() is no more needed. An http get already returns a json by default.

If your json response has only these two entries (id and dte) you simply have to do the following:

. . .

import { HttpClient } from '@angular/common/http';

/** rxjs **/
import { Observable } from 'rxjs/Observable';

getStuff(someUrl: string): Observable<Array<R>> {
    return this.http.get(someUrl);
}

If you need some error handling or, for instance, retry if the request gives error your should do something like:

. . .

import { HttpClient } from '@angular/common/http';

/** rxjs **/
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/throw';
import {catchError} from 'rxjs/operators/catchError';

getStuff(someUrl: string): Observable<Array<R>> {
    return this.http.get(someUrl)
        .pipe(
            retryWhen(errors =>
                // Do Stuff
            ),
            catchError((error: Error)  => {
                return Observable.throw(error);
            })
        );
}

There is no actual need of mapping data, but, if you would like to do it, you should do like":

data.map((dataEntry) => new R(dataEntry))

If you are still using Angular 4.x.x, you should get it going with:

. . .

import { Http } from '@angular/http';

/** rxjs **/
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/throw';
import {catchError} from 'rxjs/operators/catchError';

getStuff(someUrl: string): Observable<Array<R>> {
    return this.http.get(someUrl)
        .pipe(
            map((response: Response) => response.json()),
            catchError((error: Error)  => {
                return Observable.throw(error);
            })
        );
}


问:
apostrophe in word not being recognized for string replace
I am having a problem replacing the word "you're" with regexp.

All of the other words are changing correctly just the word "you're".
I think it is not parsing after the apostrophe.

I have to replace the word "you" to "I" and "you're" to "I'm".
It will change "you" to "I" but "you're" becomes "I're" because it is not going past the apostrophe and it thinks that is the end of the word for some reason. I have to escape the apostrophe somehow.

Please see below for the code in question.

```<code>package main

import (
    "fmt"
    "math/rand"
    "regexp"
    "strings"
    "time"
)

//Function ElizaResponse to take in and return a string
func ElizaResponse(str string) string {

    //  replace := "How do you know you are"

    /*Regex MatchString function with isolation of the word "father"
    *with a boundry ignore case regex command.
     */
    if matched, _ := regexp.MatchString(`(?i)\bfather\b`, str);
    //Condition to replace the original string if it has the word "father"
    matched {
        return "Why don’t you tell me more about your father?"
    }
    r1 := regexp.MustCompile(`(?i)\bI'?\s*a?m\b`)

    //Match the words "I am" and capture for replacement
    matched := r1.MatchString(str)

    //condition if "I am" is matched
    if matched {

        capturedString := r1.ReplaceAllString(str, "$1")
        boundaries := regexp.MustCompile(`\b`)
        tokens := boundaries.Split(capturedString, -1)

        // List the reflections.
        reflections := [][]string{
            {`I`, `you`},
            {`you're`, `I'm`},
            {`your`, `my`},
            {`me`, `you`},
            {`you`, `I`},
            {`my`, `your`},
        }

        // Loop through each token, reflecting it if there's a match.
        for i, token := range tokens {
            for _, reflection := range reflections {
                if matched, _ := regexp.MatchString(reflection[0], token); matched {
                    tokens[i] = reflection[1]
                    break
                }
            }
        }

        // Put the tokens back together.
        return strings.Join(tokens, ``)

    }

    //Get random number from the length of the array of random struct
    //an array of strings for the random response
    response := []string{"I’m not sure what you’re trying to say. Could you explain it to me?",
        "How does that make you feel?",
        "Why do you say that?"}
    //Return a random index of the array
    return response[rand.Intn(len(response))]

}

func main() {
    rand.Seed(time.Now().UTC().UnixNano())

    fmt.Println("Im supposed to just take what you're saying at face value?")
    fmt.Println(ElizaResponse("Im supposed to just take what you're saying at face value?"))

}
</code>```

答:
I have found that i just needed to change these two lines of code.

```<code>boundaries := regexp.MustCompile(`(\b[^\w']|$)`)
return strings.Join(tokens, ` `)
</code>```

Its stops the split function from splitting at the ' character.
Then the return of tokens needs a space to put out the string otherwise it would be a continuous string.

Body:
I am having a problem replacing the word "you're" with regexp.

All of the other words are changing correctly just the word "you're".
I think it is not parsing after the apostrophe.

I have to replace the word "you" to "I" and "you're" to "I'm".
It will change "you" to "I" but "you're" becomes "I're" because it is not going past the apostrophe and it thinks that is the end of the word for some reason. I have to escape the apostrophe somehow.

Please see below for the code in question.

package main

import (
    "fmt"
    "math/rand"
    "regexp"
    "strings"
    "time"
)

//Function ElizaResponse to take in and return a string
func ElizaResponse(str string) string {

    //  replace := "How do you know you are"

    /*Regex MatchString function with isolation of the word "father"
    *with a boundry ignore case regex command.
     */
    if matched, _ := regexp.MatchString(`(?i)\bfather\b`, str);
    //Condition to replace the original string if it has the word "father"
    matched {
        return "Why don’t you tell me more about your father?"
    }
    r1 := regexp.MustCompile(`(?i)\bI'?\s*a?m\b`)

    //Match the words "I am" and capture for replacement
    matched := r1.MatchString(str)

    //condition if "I am" is matched
    if matched {

        capturedString := r1.ReplaceAllString(str, "$1")
        boundaries := regexp.MustCompile(`\b`)
        tokens := boundaries.Split(capturedString, -1)

        // List the reflections.
        reflections := [][]string{
            {`I`, `you`},
            {`you're`, `I'm`},
            {`your`, `my`},
            {`me`, `you`},
            {`you`, `I`},
            {`my`, `your`},
        }

        // Loop through each token, reflecting it if there's a match.
        for i, token := range tokens {
            for _, reflection := range reflections {
                if matched, _ := regexp.MatchString(reflection[0], token); matched {
                    tokens[i] = reflection[1]
                    break
                }
            }
        }

        // Put the tokens back together.
        return strings.Join(tokens, ``)

    }

    //Get random number from the length of the array of random struct
    //an array of strings for the random response
    response := []string{"I’m not sure what you’re trying to say. Could you explain it to me?",
        "How does that make you feel?",
        "Why do you say that?"}
    //Return a random index of the array
    return response[rand.Intn(len(response))]

}

func main() {
    rand.Seed(time.Now().UTC().UnixNano())

    fmt.Println("Im supposed to just take what you're saying at face value?")
    fmt.Println(ElizaResponse("Im supposed to just take what you're saying at face value?"))

}

Body:
I have found that i just needed to change these two lines of code.

boundaries := regexp.MustCompile(`(\b[^\w']|$)`)
return strings.Join(tokens, ` `)

Its stops the split function from splitting at the ' character.
Then the return of tokens needs a space to put out the string otherwise it would be a continuous string.


问:
Docker context in Container Builder. The Dockerfile must be within the build context
I'm not understanding the Docker context in Container Builder. I have a Dockerfile under services/device-registry/base/build/docker/php/Dockerfile but I want my build context to be services/device-registry My Container Builder step looks like this:

```<code>- name: 'gcr.io/cloud-builders/docker'
  args: [ 'build', '-f', './base/build/docker/php/Dockerfile', '-t', 'gcr.io/$PROJECT_ID/device-registry-php', '.' ]
  dir: 'services/device-registry'
  id: 'device-registry-php'
</code>```

And I get the error unable to prepare context: The Dockerfile (/workspace/services/device-registry/base/build/docker/php/Dockerfile) must be within the build context (.)

答:
You this is a docker build limitation/by-design. This is not related to Google Container Builder.

Files you're sending into to a docker build command has to be at the SAME or NESTED folders as the Dockerfile.  In your command above, it violates this.

Body:
I'm not understanding the Docker context in Container Builder. I have a Dockerfile under services/device-registry/base/build/docker/php/Dockerfile but I want my build context to be services/device-registry My Container Builder step looks like this:

- name: 'gcr.io/cloud-builders/docker'
  args: [ 'build', '-f', './base/build/docker/php/Dockerfile', '-t', 'gcr.io/$PROJECT_ID/device-registry-php', '.' ]
  dir: 'services/device-registry'
  id: 'device-registry-php'

And I get the error unable to prepare context: The Dockerfile (/workspace/services/device-registry/base/build/docker/php/Dockerfile) must be within the build context (.)


问:
Creating Image Carousel in Flutter
How can i create an Carousel of Containers Like the example below?

I looked at Pageview class but this only displays one Container and hides the others. But i want to see the Container partly on the left and right too. Is there anyway to do this in Flutter and how?

Note: The current Container should always stay in the center

Edit: Darky gave an very good Example but i have one problem with his given code:

The following ArgumentError was thrown building
AnimatedBuilder(animation: PageController#fc5f0(one client, offset
0.0), dirty, state: _AnimatedState#1ea5c): Invalid argument (lowerLimit): not a number: null –

This gets thrown at the Position where he calls controller.page. Does anyone know how i can fix this?

答:
Actually what you want is PageView.

PageView accept a PageController as argument. And that controller possess a viewportFraction property (default to 1.0) which represent in percent the main-size of displayed pages.

Which means that with a viewportFraction of 0.5, the main page will be centered. And you'll see half a page on both left and right (if there's one)

Example :

```<code>class Carroussel extends StatefulWidget {
  @override
  _CarrousselState createState() => new _CarrousselState();
}

class _CarrousselState extends State<Carroussel> {
  PageController controller;
  int currentpage = 0;

  @override
  initState() {
    super.initState();
    controller = PageController(
      initialPage: currentpage,
      keepPage: false,
      viewportFraction: 0.5,
    );
  }

  @override
  dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Container(
          child: PageView.builder(
              onPageChanged: (value) {
                setState(() {
                  currentpage = value;
                });
              },
              controller: controller,
              itemBuilder: (context, index) => builder(index)),
        ),
      ),
    );
  }

  builder(int index) {
    return AnimatedBuilder(
      animation: controller,
      builder: (context, child) {
        double value = 1.0;
        if (controller.position.haveDimensions) {
          value = controller.page - index;
          value = (1 - (value.abs() * .5)).clamp(0.0, 1.0);
        }

        return Center(
          child: SizedBox(
            height: Curves.easeOut.transform(value) * 300,
            width: Curves.easeOut.transform(value) * 250,
            child: child,
          ),
        );
      },
      child: Container(
        margin: const EdgeInsets.all(8.0),
        color: index % 2 == 0 ? Colors.blue : Colors.red,
      ),
    );
  }
}
</code>```

Title: Creating Image Carousel in Flutter

Body:
Actually what you want is PageView.

PageView accept a PageController as argument. And that controller possess a viewportFraction property (default to 1.0) which represent in percent the main-size of displayed pages.

Which means that with a viewportFraction of 0.5, the main page will be centered. And you'll see half a page on both left and right (if there's one)

Example :

class Carroussel extends StatefulWidget {
  @override
  _CarrousselState createState() => new _CarrousselState();
}

class _CarrousselState extends State<Carroussel> {
  PageController controller;
  int currentpage = 0;

  @override
  initState() {
    super.initState();
    controller = PageController(
      initialPage: currentpage,
      keepPage: false,
      viewportFraction: 0.5,
    );
  }

  @override
  dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Container(
          child: PageView.builder(
              onPageChanged: (value) {
                setState(() {
                  currentpage = value;
                });
              },
              controller: controller,
              itemBuilder: (context, index) => builder(index)),
        ),
      ),
    );
  }

  builder(int index) {
    return AnimatedBuilder(
      animation: controller,
      builder: (context, child) {
        double value = 1.0;
        if (controller.position.haveDimensions) {
          value = controller.page - index;
          value = (1 - (value.abs() * .5)).clamp(0.0, 1.0);
        }

        return Center(
          child: SizedBox(
            height: Curves.easeOut.transform(value) * 300,
            width: Curves.easeOut.transform(value) * 250,
            child: child,
          ),
        );
      },
      child: Container(
        margin: const EdgeInsets.all(8.0),
        color: index % 2 == 0 ? Colors.blue : Colors.red,
      ),
    );
  }
}


问:
Angular ng-version not updating
I create a new Angular app using dotnet new angular which currently specifies Angular 4.2.5 in the package.json. I run the app and view source and ng-version is 4.2.5 which is correct.

I then specify Angular to use 4.4.6 in the package.json:

```<code>"devDependencies": {
    "@angular/animations": "^4.4.6",
    "@angular/common": "^4.4.6",
    "@angular/compiler": "^4.4.6",
    "@angular/compiler-cli": "^4.4.6",
    "@angular/core": "^4.4.6",
    "@angular/forms": "^4.4.6",
    "@angular/http": "^4.4.6",
    "@angular/platform-browser": "^4.4.6",
    "@angular/platform-browser-dynamic": "^4.4.6",
    "@angular/platform-server": "^4.4.6",
    "@angular/router": "^4.4.6"
</code>```

I completely remove the node_modules folder and run npm install.  After install, I check .\node_modules\@angular\common\package.json and it shows a 4.4.6 version. However, when I run the app, ng-version still shows 4.2.5. Why does it still show 4.2.5? How do I fix this?

答: Appears to have been a caching issue. Doing a Ctrl+F5 made the correct version appear.</p>

Title: Angular ng-version not updating

Body:
I create a new Angular app using dotnet new angular which currently specifies Angular 4.2.5 in the package.json. I run the app and view source and ng-version is 4.2.5 which is correct.

I then specify Angular to use 4.4.6 in the package.json:

"devDependencies": {
    "@angular/animations": "^4.4.6",
    "@angular/common": "^4.4.6",
    "@angular/compiler": "^4.4.6",
    "@angular/compiler-cli": "^4.4.6",
    "@angular/core": "^4.4.6",
    "@angular/forms": "^4.4.6",
    "@angular/http": "^4.4.6",
    "@angular/platform-browser": "^4.4.6",
    "@angular/platform-browser-dynamic": "^4.4.6",
    "@angular/platform-server": "^4.4.6",
    "@angular/router": "^4.4.6"

I completely remove the node_modules folder and run npm install.  After install, I check .\node_modules\@angular\common\package.json and it shows a 4.4.6 version. However, when I run the app, ng-version still shows 4.2.5. Why does it still show 4.2.5? How do I fix this?


问:
Pickle database independent query in Django
First of all, I know that my question duplicate this question. But I supose it's not the same.

I need to save user "search filter". As I understand Django ORM create specific SQL query for different DB. So if I save SQL query I can't migrate on other database with different SQL syntax.
Am I wrong? If no, how can I save Django side of query, without accsesing to DB?

答:
If you can suggest better sulution I open for conversation

So... Pickle the function .filter() is not the best idea so as saving SQL string for specific DB. I think the best solution for this problem is saving search parameters. In my case it's GET string. I get it:

```<code>request.META["QUERY_STRING"]
</code>```

And save to DB.

If I need to get it, i just parse:

```<code>from django.http import QueryDict
QueryDict(request.META["QUERY_STRING"])
</code>```

Aditionally I use different form for validate this values (optional) SearchTrustedForm(), because if data structure has changed I can save backwards compatibility.

Body:
If you can suggest better sulution I open for conversation

So... Pickle the function .filter() is not the best idea so as saving SQL string for specific DB. I think the best solution for this problem is saving search parameters. In my case it's GET string. I get it:

request.META["QUERY_STRING"]

And save to DB.

If I need to get it, i just parse:

from django.http import QueryDict
QueryDict(request.META["QUERY_STRING"])

Aditionally I use different form for validate this values (optional) SearchTrustedForm(), because if data structure has changed I can save backwards compatibility.


问:
Rendering HTML rich text in Silvlerlight without using windowless mode
I'm trying to find a control for our project that will allow us to render HTML content in Silverlight, without having to use windowless mode or be an out-of-browser app. All of the controls I've found so far require windowless mode. For technical reasons, windowless mdoe and out of browser apps are not possible for us.

The intention is to use the control to show formatted text in our Help system, so if there's a control out there that does a partial implementation, it might still be useful to us. We are mostly looking for the ability for the help content to be defined in some kind of rich text format (most likely HTML) such that it can have formatting, bullets, perhaps tables, images, etc.

Can anyone suggest a control that can do this? We're currently using Silverlight 3, but Silverlight 4 is in the pipeline.

答: I've used the Vectorlight controls for this sort of thing for both displaying and editing HTML based content.  The one I've used is Rich Text Editor which is the original control that works in SL3 and 4.  A new one has been introduced called the Html RichTextArea.  Note both are actually HTML based. I don't know how well the newer one works, I suspect it is based on the SL4 rich text stuff however the original control works fine.</p>

ContentLicense: CC BY-SA 2.5


问:
vba intellisense very annoying behavior
Sometimes,  I could not pinpoint the cause of this behavior, but VBA intellisense on excel or access starts acting really fast/weird.
Examples :
I type a space and it removes it in the next 0.2 sec if I don't type anything, If i want to prevent mycodelookinglikethis I need to think of the next letter to type and do it quickly or manually add space afterward.
If I do ctrl-space to see object methods or properties, it only shows for about 2 seconds then the box disappear, I can't scroll down at all.

I tried to go in tools >> Option >> Editor and uncheck everything, yet the behavior stays, I can't seem to find a way to stop or restart intellisense.

I don't have privileges to install programs on my computer. This problem doesn't happen all the time and a reboot doesn't fix it.

答: For Access, it could be due to timers in your forms.  Once you disable the timers, the intellisense will not disappear no more.  Hope it helps.</p>

Title: vba intellisense very annoying behavior


问:
HTCondor gcc: error trying to exec 'cc1': execvp: No such file or directory
When I use HTCondor to submit a shell script which contains something like gcc code.c -o code.o, the error file says that error trying to exec 'cc1': execvp: No such file or directory.
However, when I just type gcc code.c -o code.o in the shell on the execute machine, everything works fine.
Anyone knows the reason? I am working on ubuntu-16.04.2-server-amd64.

答:
There may be environment variables defined in the HTCondor environment that set gcc off to search for cc1 (which is an internal compiler executable) in the wrong place, such as GCC_EXEC_PREFIX and COMPILER_PATH, or, gcc may be missing from the PATH in HTCondor (see here regarding influential GCC env. variables).

I would suggest the following troubleshooting procedure:

In the normal shell, check the location of gcc (which gcc).

Make sure that the folder where gcc is located is a part of the PATH in HTCondor - or append it to the begining of that PATH (export PATH=/path/to/gcc:$PATH).

Make sure that variables GCC_EXEC_PREFIX and COMPILER_PATH are not set in the HTCondor environment.

If the above doesn't work, you could try the other way around and set GCC_EXEC_PREFIX to the location of gcc in the HTCondor script.

Edit:

As per your findings, adding the getenv = true command to condor_submit (doc) resolves the issue:

getenv = (True | False)

  If getenv is set to True, then condor_submit will copy all of the user's current shell environment variables at the time of job submission into the job ClassAd. The job will therefore execute with the same set of environment variables that the user had at submit time.


问:
hapijs Joi when one field is non empty other fields must be required
When the password is non empty means other two fields are required. In some cases password will be present but that will be null, on that cases other two fields are not required. I tried with exist() and !empty() but it doesn't work.

password      : joi.string().trim().optional().description('Password'),
device_type   : joi.when('password', {is: (joi.exist() && !joi.empty()), then: joi.number().required().valid(validation.user.device_type.allowOnly).description('Device type')}),
device_token  : joi.when('password', {is: joi.exist(), then: joi.string().trim().required().description('Device token')})

But this won't works

答:
There are 2 parts to your question:

Treat an empty string for password the same as not having submitted a password at all.  See any.empty(...)

Require keys whenever another password is present. See object.with(...)

Putting them together and simplifying your schema for clarity (note all keys are optional by default):

```<code>const schema = joi.object({
    password      : joi.string().trim().empty(''),
    device_type   : joi.number(),
    device_token  : joi.string().trim()
}).with('password', ['device_type', 'device_token']);
</code>```

Body:
There are 2 parts to your question:

Treat an empty string for password the same as not having submitted a password at all.  See any.empty(...)

Require keys whenever another password is present. See object.with(...)

Putting them together and simplifying your schema for clarity (note all keys are optional by default):

const schema = joi.object({
    password      : joi.string().trim().empty(''),
    device_type   : joi.number(),
    device_token  : joi.string().trim()
}).with('password', ['device_type', 'device_token']);


问:
How to do inheritance @JsonFormat annotation in java?
I am working on JPA-Hibernate project. I have a date deserilaze problem but i have also solution in the below.

```<code>@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss.S")
private Date createdAt;
</code>```

When I use @JsonFormat annotation with date, i solved the problem but i don't want to use this annotation every Date variable. I want to use MyDate annotation, as you can see below.

```<code>import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import com.fasterxml.jackson.annotation.JsonFormat;

@Inherited
@Target({ ElementType.ANNOTATION_TYPE, ElementType.FIELD,  ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss.S")
public @interface MyDate {

}
</code>```

When i use @MyDate annotation, it doesn't work correctly. I keep failing like I've never used it. What is my mistake?

答:
¿Did you try Custom Jackson Annotation?

Check this out --> http://www.baeldung.com/jackson-annotations#highlighter_348118

Body:
I am working on JPA-Hibernate project. I have a date deserilaze problem but i have also solution in the below.

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss.S")
private Date createdAt;

When I use @JsonFormat annotation with date, i solved the problem but i don't want to use this annotation every Date variable. I want to use MyDate annotation, as you can see below.

import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import com.fasterxml.jackson.annotation.JsonFormat;

@Inherited
@Target({ ElementType.ANNOTATION_TYPE, ElementType.FIELD,  ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss.S")
public @interface MyDate {

}

When i use @MyDate annotation, it doesn't work correctly. I keep failing like I've never used it. What is my mistake?


问:
web request from the user browser
is it possible to send a web request from the user browser to another api and then process the result sent back??

im trying the following ajax code but its not working, i was wondering whether is it possible or not and if its a yes how can i implement it ...

```<code>$(document).ready(function() {

        $.ajax({
            type: "GET",
            url: "http://api.ipinfodb.com/v2/ip_query.php?key=a9a2b0ec2c4724dd95286761777b09f1c8e82894de277a5b9d7175fa5275f2da&ip=&output=xml",
            dataType: "xml",
            success: function(xml) {
                alert("sucess");
                $(xml).find('Ip').each(function() {
                    var ip = $(this).find('Ip').text();
                    alert(ip);

                });
            }
        });

    });
</code>```

答:
Just to add to what was already said: if you can't create your own JSONP proxy, you can use YQL service which creates that proxy for you. Note that YQL will wrap your data with it's own meta data (unless there is a way yo disable that...).

By the way, you should use JSON output instead of XML output from your API service. JSON is a more lightweight format and as such is more adapted for Web.

Below is a fully functional example with your API URL (outputting JSON this time) and YQL:

```<code>var apiRequestUrl = "http://api.ipinfodb.com/v2/ip_query.php?key=a9a2b0ec2c4724dd95286761777b09f1c8e82894de277a5b9d7175fa5275f2da&ip=&output=json";
var yqlRequestUrl = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%20%3D%20%22";
yqlRequestUrl += encodeURIComponent(apiRequestUrl);
yqlRequestUrl += "%22&format=json&callback=?";

$.getJSON(yqlRequestUrl,
    function(jsonData) {
        alert(jsonData.query.results.json.Ip);
    });
</code>```

Finally, this article can come handy: http://www.wait-till-i.com/2010/01/10/loading-external-content-with-ajax-using-jquery-and-yql/

Title: web request from the user browser

Body:
is it possible to send a web request from the user browser to another api and then process the result sent back??

im trying the following ajax code but its not working, i was wondering whether is it possible or not and if its a yes how can i implement it ...

$(document).ready(function() {

        $.ajax({
            type: "GET",
            url: "http://api.ipinfodb.com/v2/ip_query.php?key=a9a2b0ec2c4724dd95286761777b09f1c8e82894de277a5b9d7175fa5275f2da&ip=&output=xml",
            dataType: "xml",
            success: function(xml) {
                alert("sucess");
                $(xml).find('Ip').each(function() {
                    var ip = $(this).find('Ip').text();
                    alert(ip);

                });
            }
        });

    });

Body:
Just to add to what was already said: if you can't create your own JSONP proxy, you can use YQL service which creates that proxy for you. Note that YQL will wrap your data with it's own meta data (unless there is a way yo disable that...).

By the way, you should use JSON output instead of XML output from your API service. JSON is a more lightweight format and as such is more adapted for Web.

Below is a fully functional example with your API URL (outputting JSON this time) and YQL:

var apiRequestUrl = "http://api.ipinfodb.com/v2/ip_query.php?key=a9a2b0ec2c4724dd95286761777b09f1c8e82894de277a5b9d7175fa5275f2da&ip=&output=json";
var yqlRequestUrl = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%20%3D%20%22";
yqlRequestUrl += encodeURIComponent(apiRequestUrl);
yqlRequestUrl += "%22&format=json&callback=?";

$.getJSON(yqlRequestUrl,
    function(jsonData) {
        alert(jsonData.query.results.json.Ip);
    });

Finally, this article can come handy: http://www.wait-till-i.com/2010/01/10/loading-external-content-with-ajax-using-jquery-and-yql/


问:
Is there any event to notify when Environment.CurrentDirectory got changed?
In my code I am trying to read a file using File.Open() with relative path. But some times the current directory is getting changed and directory not found exception is coming.

I am trying to figure out where is Environment.CurrentDirectory is getting changed. I checked the Directory.SetCurrentDirectory method but its calling to native method.

Is there any event which will notify me when Environment.CurrentDirectory has changed? How do I find out where exactly is directory changed?

I have tried putting break point in all occurrence of Environment.CurrentDirectory and Directory.SetCurrentDirectory().

答: No, but you could check if the current directory is correct before the File.Open() call, or, store the correct directory you want to use and use an absolute path for File.Open()</p>