问:
Entity framework self referencing loop detected
I have a strange error. I'm experimenting with a .NET 4.5 Web API, Entity Framework and MS SQL Server. I've already created the database and set up the correct primary and foreign keys and relationships.

I've created a .edmx model and imported two tables: Employee and Department. A department can have many employees and this relationship exists. I created a new controller called EmployeeController using the scaffolding options to create an API controller with read/write actions using Entity Framework. In the wizard, selected Employee as the model and the correct entity for the data context.

The method that is created looks like this:

```<code>public IEnumerable<Employee> GetEmployees()
{
    var employees = db.Employees.Include(e => e.Department);
    return employees.AsEnumerable();
}
</code>```

When I call my API via /api/Employee, I get this error:

The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; ...System.InvalidOperationException","StackTrace":null,"InnerException":{"Message":"An error has occurred.","ExceptionMessage":"Self referencing loop detected with type 'System.Data.Entity.DynamicProxies.Employee_5D80AD978BC68A1D8BD675852F94E8B550F4CB150ADB8649E8998B7F95422552'. Path '[0].Department.Employees'.","ExceptionType":"Newtonsoft.Json.JsonSerializationException","StackTrace":"   ...

Why is it self referencing [0].Department.Employees? That doesn't make a whole lot of sense. I would expect this to happen if I had circular referencing in my database but this is a very simple example. What could be going wrong?

答:
I'm aware that question is quite old, but it's still popular and I can't see any solution for ASP.net Core.

I case of ASP.net Core, you need to add new JsonOutputFormatter in Startup.cs file:

```<code>    public void ConfigureServices(IServiceCollection services)
    {

        services.AddMvc(options =>
        {
            options.OutputFormatters.Clear();
            options.OutputFormatters.Add(new JsonOutputFormatter(new JsonSerializerSettings()
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
            }, ArrayPool<char>.Shared));
        });

        //...
    }
</code>```

After implementing it, JSON serializer will simply ignore loop references. What it means is: it will return null instead of infinitely loading objects referencing each other.

Without above solution using:

```<code>var employees = db.Employees.ToList();
</code>```

Would load Employees and related to them Departments.

After setting ReferenceLoopHandling to Ignore, Departments will be set to null unless you include it in your query:

```<code>var employees = db.Employees.Include(e => e.Department);
</code>```

Also, keep in mind that it will clear all OutputFormatters, if you don't want that you can try removing this line:

```<code>options.OutputFormatters.Clear();
</code>```

But removing it causes again self referencing loop exception in my case for some reason.

Body:
I have a strange error. I'm experimenting with a .NET 4.5 Web API, Entity Framework and MS SQL Server. I've already created the database and set up the correct primary and foreign keys and relationships.

I've created a .edmx model and imported two tables: Employee and Department. A department can have many employees and this relationship exists. I created a new controller called EmployeeController using the scaffolding options to create an API controller with read/write actions using Entity Framework. In the wizard, selected Employee as the model and the correct entity for the data context.

The method that is created looks like this:

public IEnumerable<Employee> GetEmployees()
{
    var employees = db.Employees.Include(e => e.Department);
    return employees.AsEnumerable();
}

When I call my API via /api/Employee, I get this error:

The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; ...System.InvalidOperationException","StackTrace":null,"InnerException":{"Message":"An error has occurred.","ExceptionMessage":"Self referencing loop detected with type 'System.Data.Entity.DynamicProxies.Employee_5D80AD978BC68A1D8BD675852F94E8B550F4CB150ADB8649E8998B7F95422552'. Path '[0].Department.Employees'.","ExceptionType":"Newtonsoft.Json.JsonSerializationException","StackTrace":"   ...

Why is it self referencing [0].Department.Employees? That doesn't make a whole lot of sense. I would expect this to happen if I had circular referencing in my database but this is a very simple example. What could be going wrong?

Body:
I'm aware that question is quite old, but it's still popular and I can't see any solution for ASP.net Core.

I case of ASP.net Core, you need to add new JsonOutputFormatter in Startup.cs file:

    public void ConfigureServices(IServiceCollection services)
    {

        services.AddMvc(options =>
        {
            options.OutputFormatters.Clear();
            options.OutputFormatters.Add(new JsonOutputFormatter(new JsonSerializerSettings()
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
            }, ArrayPool<char>.Shared));
        });

        //...
    }

After implementing it, JSON serializer will simply ignore loop references. What it means is: it will return null instead of infinitely loading objects referencing each other.

Without above solution using:

var employees = db.Employees.ToList();

Would load Employees and related to them Departments.

After setting ReferenceLoopHandling to Ignore, Departments will be set to null unless you include it in your query:

var employees = db.Employees.Include(e => e.Department);

Also, keep in mind that it will clear all OutputFormatters, if you don't want that you can try removing this line:

options.OutputFormatters.Clear();

But removing it causes again self referencing loop exception in my case for some reason.


来源: stackexchange

问:
FDTI libMPSSE I2C- Getting FT_IO_ERROR while using separate Reader & Writer Threads to read and write

    I am trying to communicate with I2C device using FT232HL(libMPSSE dll). Separate threads are used for reading and writing the data. First write cycle happens successfully but then it gives FT_IO_ERROR.
</p>

<p>
    I have followed AN_177_User_Guide_For_LibMPSSE-I2C.pdf while coding and have used semaphores for synchronization of threads.
    I couldn't find document on FT_IO_ERROR over the Internet. Please help me if you know about it.
</p>

答:
The I2C bus is half duplex.
It is thought that it is not necessary to distinguish read thread from write thread.

FT_IO_ERROR is a data transfer failure.
This is described on page 13 of the document you explained.

It is probably not a problem of the interface chip or the library, but whether the communication control is performed according to the command/response sequence of the device connected to the I2C bus.

Please check the communication specification of the I2C device being used.
In addition, make sure that the interface chip and the I2C device are correctly connected and communication is possible.

ContentLicense: CC BY-SA 3.0

Body:
    I am trying to communicate with I2C device using FT232HL(libMPSSE dll). Separate threads are used for reading and writing the data. First write cycle happens successfully but then it gives FT_IO_ERROR.

    I have followed AN_177_User_Guide_For_LibMPSSE-I2C.pdf while coding and have used semaphores for synchronization of threads.
    I couldn't find document on FT_IO_ERROR over the Internet. Please help me if you know about it.


问:
res.send() not able to send entire base64 string to client
Basically, I'm trying to capture screenshots of websites and at the same time trying to store them into local storage of the browser. So I am taking help of webshot(which is an npm package and a light wrapper around phantomjs).But unfortunately, res.send() is not able to send the entire data to the client. That's why my image appears as only 25% of the original image, as it sends only some amount of the base64 encoded string. specificData which is the base64 encoded string of the actual buffer data fetched by webshot is not sent at whole over to the client. Below is my server side code

```<code>const express = require("express");
const app = express();

let webshot = require('webshot');
let specificData;

app.get('/',(req,res)=>{
    res.send("let's get started");
});

app.get('/imageViewer',(req,res)=>{
    res.sendFile(__dirname+'/index.html');
});

app.get('/storeImageToLocalStorage',(req,res,next)=>{
    let renderStream = webshot('stackoverflow.com');
    renderStream.on('data', function(data) {
        specificData=data.toString('base64');
        next();
    });
},(req,res)=>{
    res.send(specificData);
});

app.listen(5676,()=>{
console.log("listening at http://localhost:5676");});
</code>```

Below is my index File which is sent when get request is received from the client. Then the specificData is fetched from the server which is actually a chunk received from the server end due to the shortcoming of res.send(). I have searched all over the net of how to fix this but I couldn't find any relevant solution. That is why I have turned to stackoverflow to get my question answered.

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script
            src="https://code.jquery.com/jquery-3.2.1.js"
            integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
            crossorigin="anonymous">
    </script>
</head>
<body>
<img id="tableBanner" style="height: 40vh;width: 40vw">
<script>
    $(()=>{
        let bannerImg = document.getElementById('tableBanner');
        $.get('/storeImageToLocalStorage',(specificData)=>{
            localStorage.setItem('specificData',specificData);
            bannerImg.src = 'data:image/png;base64,'+localStorage.getItem('specificData');
        });

    });
</script>
</body>
</html>
</code>```

答:
Thats because you are overwriting everytime data is received and passing to next middleware on first chunk of data receive:</p>

```<code>renderStream.on('data', function(data) {
        specificData += data.toString('base64');  //append
});

//calling next() when data has stopped listening
renderStream.on('end', function() {
       next();
})
</code>```

Body:
Basically, I'm trying to capture screenshots of websites and at the same time trying to store them into local storage of the browser. So I am taking help of webshot(which is an npm package and a light wrapper around phantomjs).But unfortunately, res.send() is not able to send the entire data to the client. That's why my image appears as only 25% of the original image, as it sends only some amount of the base64 encoded string. specificData which is the base64 encoded string of the actual buffer data fetched by webshot is not sent at whole over to the client. Below is my server side code

const express = require("express");
const app = express();

let webshot = require('webshot');
let specificData;

app.get('/',(req,res)=>{
    res.send("let's get started");
});

app.get('/imageViewer',(req,res)=>{
    res.sendFile(__dirname+'/index.html');
});

app.get('/storeImageToLocalStorage',(req,res,next)=>{
    let renderStream = webshot('stackoverflow.com');
    renderStream.on('data', function(data) {
        specificData=data.toString('base64');
        next();
    });
},(req,res)=>{
    res.send(specificData);
});

app.listen(5676,()=>{
console.log("listening at http://localhost:5676");});

Below is my index File which is sent when get request is received from the client. Then the specificData is fetched from the server which is actually a chunk received from the server end due to the shortcoming of res.send(). I have searched all over the net of how to fix this but I couldn't find any relevant solution. That is why I have turned to stackoverflow to get my question answered.

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

Body:
Thats because you are overwriting everytime data is received and passing to next middleware on first chunk of data receive:

renderStream.on('data', function(data) {
        specificData += data.toString('base64');  //append
});

//calling next() when data has stopped listening
renderStream.on('end', function() {
       next();
})


问:
JQuery - trigger call on div becoming visible
I have a div that is shown / hidden through CSS media queries.

I want to trigger a JQuery call when this div becomes visible - triggering once if the div changes from

```<code>display: none;
</code>```

to

```<code>display: block;
</code>```

Is this possible to do?

Something like the onclick call, but on the div property changing to visible?

```<code>$(document).on('click', '#mydiv', function() {
}
</code>```

答:
$(document).ready(function(){
function myFunction(){
setTimeout(function(){ console.log('foo foo') }, 2000)
}
$(document).click(function(){
$('#demo').css('display','block');
//after div is visible myFunction is triggered
myFunction();
})

})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>click</h1>
<div id='demo' style='display:none'>
<p>hello world</p>
</div></code>```

Body:
I have a div that is shown / hidden through CSS media queries.

I want to trigger a JQuery call when this div becomes visible - triggering once if the div changes from

display: none;

to

display: block;

Is this possible to do?

Something like the onclick call, but on the div property changing to visible?

$(document).on('click', '#mydiv', function() {
}

Body:
$(document).ready(function(){
function myFunction(){
setTimeout(function(){ console.log('foo foo') }, 2000)
}
$(document).click(function(){
$('#demo').css('display','block');
//after div is visible myFunction is triggered
myFunction();
})

})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>click</h1>
<div id='demo' style='display:none'>
<p>hello world</p>
</div>


问:
How to get TextView of an activity in an Adapter class while that TextView is not in row of recyclerView?
How to get TextView of an Activity  in  RecyclerViewAdapter class and TextView is not in layout of row For  RecyclerView  item.As in RecyclerViewAdapter we override method

```<code>onBindViewHolder(ViewHolder holder, int position){
   NewsModel newsModel=values.get(position);  //to get the current object
        holder.news_title.setText(newsModel.getTitle());
        holder.news_body.setText(newsModel.getDescription());
        holder.news_published_at.setText("Date "+GiveMeDate(values.get(position).getDate()));}
</code>```

and as it get only those which are declared in ViewHolder extends RecyclerView.ViewHolder   and ViewHolder  will only get ui that are in View v = inflater.inflate(R.layout.news_item, parent, false);but I want to get ui from activity's layout so that I can update TextView value in Adapter So please Help to do that work. Image to reflect Layout is as follows:

答:
I find that the UI of Activity to be used in Adapter class. We should make
 it static in Activity  and then  make a static method to update its value, after that whenever we want to change its value from Adapter  we will call that static method with actual parameter and it will be updated .I do it as follows

In Activity

```<code>  public static TextView counter_value;
   public static  void update_counter(String value){
        try{
            counter_value.setText(value);
        }
        catch (Exception ex){
            Log.d("Exception","Exception of type"+ex.getMessage());
        }
    }
</code>```

In Adapter class just call that static method

```<code>News.update_counter(String.valueOf(counter));
</code>```

Body:
How to get TextView of an Activity  in  RecyclerViewAdapter class and TextView is not in layout of row For  RecyclerView  item.As in RecyclerViewAdapter we override method

onBindViewHolder(ViewHolder holder, int position){
   NewsModel newsModel=values.get(position);  //to get the current object
        holder.news_title.setText(newsModel.getTitle());
        holder.news_body.setText(newsModel.getDescription());
        holder.news_published_at.setText("Date "+GiveMeDate(values.get(position).getDate()));}

and as it get only those which are declared in ViewHolder extends RecyclerView.ViewHolder   and ViewHolder  will only get ui that are in View v = inflater.inflate(R.layout.news_item, parent, false);but I want to get ui from activity's layout so that I can update TextView value in Adapter So please Help to do that work. Image to reflect Layout is as follows:

Body:
I find that the UI of Activity to be used in Adapter class. We should make
 it static in Activity  and then  make a static method to update its value, after that whenever we want to change its value from Adapter  we will call that static method with actual parameter and it will be updated .I do it as follows

In Activity

  public static TextView counter_value;
   public static  void update_counter(String value){
        try{
            counter_value.setText(value);
        }
        catch (Exception ex){
            Log.d("Exception","Exception of type"+ex.getMessage());
        }
    }

In Adapter class just call that static method

News.update_counter(String.valueOf(counter));


问:
Copying weights from one Conv2D layer to another

Context

I have trained a model on MNIST using Keras. My goal is to print images after the first layer with the first layer being a Conv2D layer. To go about this I'm creating a new model with a single Conv2D layer in which I'll copy the weights from the trained network into the new one.

```<code># Visualization for image ofter first convolution
model_temp = Sequential()
model_temp.add(Conv2D(32, (3, 3),
                         activation='relu',
                         input_shape=(28,28,1,)))

trained_weights = model.layers[0].get_weights()[0]

model_temp.layers[0].set_weights(trained_weights)

activations = model_temp._predict(X_test)
</code>```

The variable model holds the trained data from the full network. Also, the input parameters to Conv2D are exactly the same as the ones in the original model.

I have checked the shape of both the weights for model and model_temp and both return as (3, 3, 1, 32). In theory I should be able to get the weights from the original and input them directly into the set_weights() call on the single Conv2D layer in the new model.

After this convolution, variable named 'activations' would be a tensor that holds 32 (layers), 26 by 26 matrices of output values for each input image.

Error

So when I run this code, I get this error:

```<code>---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-152-4ae260f0fe89> in <module>()
      7 trained_weights = model.layers[0].get_weights()[0]
      8 print(trained_weights.shape)
----> 9 model_test = model_test.layers[0].set_weights(trained_weights)
     10
     11 activations = model_test._predict(X_test[1, 28, 28, 1])

/usr/local/lib/python2.7/dist-packages/keras/engine/topology.pyc in set_weights(self, weights)
   1189                              str(len(params)) +
   1190                              ' weights. Provided weights: ' +
-> 1191                              str(weights)[:50] + '...')
   1192         if not params:
   1193             return

ValueError: You called `set_weights(weights)` on layer "conv2d_60" with a  weight list of length 3, but the layer was expecting 2 weights. Provided weights: [[[[ -6.22274876e-01  -2.18614027e-01   5.29607059...
</code>```

On the last line, why is set_weights(weights) looking for a length of two instead of three? This error message is slightly cryptic to me so if not a length of two what does "expecting two weights" mean?

Also i'm open to suggestions on an easier way to go about this.

After Further Investigation

After inspecting the source code for get_weights() (line 1168), the error is raised in this section:

```<code> params = self.weights
    if len(params) != len(weights):
        raise ValueError('You called `set_weights(weights)` on layer "' +
                         self.name +
                         '" with a  weight list of length ' +
                         str(len(weights)) +
                         ', but the layer was expecting ' +
                         str(len(params)) +
                         ' weights. Provided weights: ' +
                         str(weights)[:50] + '...')
</code>```

This condition check determines if the length of what I passed in (the (3, 3, 1, 32) tensor from above) is equivalent to the weights property of this class. So I tested these properties as follows:

```<code># Print contents of weights property
print(model.layers[0].weights)
print(model_test.layers[0].weights)

# Length test of tensors from get_weights call
len_test  = len(model.layers[0].get_weights()[0])
len_test2 = len(model_test.layers[0].get_weights()[0])
print("\nLength get_weights():")
print("Trained Model: ", len_test, "Test Model: ", len_test2)

# Length test of wights attributes from both models
len_test3 = len(model.layers[0].weights)
len_test4 = len(model_test.layers[0].weights)
print("\nLength weights attribute:")
print("Trained Model: ", len_test3, "Test Model: ", len_test4)
</code>```

Output:

```<code>[<tf.Variable 'conv2d_17/kernel:0' shape=(3, 3, 1, 32) dtype=float32_ref>,         <tf.Variable 'conv2d_17/bias:0' shape=(32,) dtype=float32_ref>]
[<tf.Variable 'conv2d_97/kernel:0' shape=(3, 3, 1, 32) dtype=float32_ref>, <tf.Variable 'conv2d_97/bias:0' shape=(32,) dtype=float32_ref>]

Length get_weights():
('Trained Model: ', 3, 'Test Model: ', 3)

Length weights attribute:
('Trained Model: ', 2, 'Test Model: ', 2)
</code>```

This output makes one hundred percent sense to me as these convolutions in each model are constructed exactly the same. It's also now obvious why it wants a length of two. This is because the weights property is a list of two elements of tf.Variable.

Further investigating this source file, at line 213 we see that weights holds "The concatenation of the lists trainable_weights and non_trainable_weights (in this order)".

So then sure I can grab the weights attribute from the Conv2D layer of the original trained model and pass that in to satisfy this condition but then this condition isn't checking the shape of the passed in data at all. If I do pass in weights from my original model I get a setting an array element with a sequence error from numpy.

Thoughts

I think this is a bug in the source code. I would be awesome if someone could verify this.

答:
You are forgetting about bias vectors. Get_weights() and set_weights() functions for conv2d returns a list with weights matrix as first element and bias vector as second. So the error rightly suggests it expects a list with 2 members. Doing the following should thus work

```<code>trained_weights = model.layers[0].get_weights()
model_temp.layers[0].set_weights(trained_weights)
</code>```

Also if you want to get output from an intermediate layer you dont need to manually transfer weights. Doing something like following is much more convenieant

```<code>get_layer_output = K.function([model.input],
                                  [model.layers[0].output])
layer_output = get_layer_output([x])[0]
</code>```

or

```<code>intermediate_layer_model = Model(inputs=model.input,
                                 outputs=model.get_layer(layer_name).output)
intermediate_output = intermediate_layer_model.predict(data)
</code>```

Body:
Context

I have trained a model on MNIST using Keras. My goal is to print images after the first layer with the first layer being a Conv2D layer. To go about this I'm creating a new model with a single Conv2D layer in which I'll copy the weights from the trained network into the new one.

# Visualization for image ofter first convolution
model_temp = Sequential()
model_temp.add(Conv2D(32, (3, 3),
                         activation='relu',
                         input_shape=(28,28,1,)))

trained_weights = model.layers[0].get_weights()[0]

model_temp.layers[0].set_weights(trained_weights)

activations = model_temp._predict(X_test)

The variable model holds the trained data from the full network. Also, the input parameters to Conv2D are exactly the same as the ones in the original model.

I have checked the shape of both the weights for model and model_temp and both return as (3, 3, 1, 32). In theory I should be able to get the weights from the original and input them directly into the set_weights() call on the single Conv2D layer in the new model.

After this convolution, variable named 'activations' would be a tensor that holds 32 (layers), 26 by 26 matrices of output values for each input image.

Error

So when I run this code, I get this error:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-152-4ae260f0fe89> in <module>()
      7 trained_weights = model.layers[0].get_weights()[0]
      8 print(trained_weights.shape)
----> 9 model_test = model_test.layers[0].set_weights(trained_weights)
     10
     11 activations = model_test._predict(X_test[1, 28, 28, 1])

/usr/local/lib/python2.7/dist-packages/keras/engine/topology.pyc in set_weights(self, weights)
   1189                              str(len(params)) +
   1190                              ' weights. Provided weights: ' +
-> 1191                              str(weights)[:50] + '...')
   1192         if not params:
   1193             return

ValueError: You called `set_weights(weights)` on layer "conv2d_60" with a  weight list of length 3, but the layer was expecting 2 weights. Provided weights: [[[[ -6.22274876e-01  -2.18614027e-01   5.29607059...

On the last line, why is set_weights(weights) looking for a length of two instead of three? This error message is slightly cryptic to me so if not a length of two what does "expecting two weights" mean?

Also i'm open to suggestions on an easier way to go about this.

After Further Investigation

After inspecting the source code for get_weights() (line 1168), the error is raised in this section:

 params = self.weights
    if len(params) != len(weights):
        raise ValueError('You called `set_weights(weights)` on layer "' +
                         self.name +
                         '" with a  weight list of length ' +
                         str(len(weights)) +
                         ', but the layer was expecting ' +
                         str(len(params)) +
                         ' weights. Provided weights: ' +
                         str(weights)[:50] + '...')

This condition check determines if the length of what I passed in (the (3, 3, 1, 32) tensor from above) is equivalent to the weights property of this class. So I tested these properties as follows:

# Print contents of weights property
print(model.layers[0].weights)
print(model_test.layers[0].weights)

# Length test of tensors from get_weights call
len_test  = len(model.layers[0].get_weights()[0])
len_test2 = len(model_test.layers[0].get_weights()[0])
print("\nLength get_weights():")
print("Trained Model: ", len_test, "Test Model: ", len_test2)

# Length test of wights attributes from both models
len_test3 = len(model.layers[0].weights)
len_test4 = len(model_test.layers[0].weights)
print("\nLength weights attribute:")
print("Trained Model: ", len_test3, "Test Model: ", len_test4)

Output:

[<tf.Variable 'conv2d_17/kernel:0' shape=(3, 3, 1, 32) dtype=float32_ref>,         <tf.Variable 'conv2d_17/bias:0' shape=(32,) dtype=float32_ref>]
[<tf.Variable 'conv2d_97/kernel:0' shape=(3, 3, 1, 32) dtype=float32_ref>, <tf.Variable 'conv2d_97/bias:0' shape=(32,) dtype=float32_ref>]

Length get_weights():
('Trained Model: ', 3, 'Test Model: ', 3)

Length weights attribute:
('Trained Model: ', 2, 'Test Model: ', 2)

This output makes one hundred percent sense to me as these convolutions in each model are constructed exactly the same. It's also now obvious why it wants a length of two. This is because the weights property is a list of two elements of tf.Variable.

Further investigating this source file, at line 213 we see that weights holds "The concatenation of the lists trainable_weights and non_trainable_weights (in this order)".

So then sure I can grab the weights attribute from the Conv2D layer of the original trained model and pass that in to satisfy this condition but then this condition isn't checking the shape of the passed in data at all. If I do pass in weights from my original model I get a setting an array element with a sequence error from numpy.

Thoughts

I think this is a bug in the source code. I would be awesome if someone could verify this.

Body:
You are forgetting about bias vectors. Get_weights() and set_weights() functions for conv2d returns a list with weights matrix as first element and bias vector as second. So the error rightly suggests it expects a list with 2 members. Doing the following should thus work

trained_weights = model.layers[0].get_weights()
model_temp.layers[0].set_weights(trained_weights)

Also if you want to get output from an intermediate layer you dont need to manually transfer weights. Doing something like following is much more convenieant

get_layer_output = K.function([model.input],
                                  [model.layers[0].output])
layer_output = get_layer_output([x])[0]

or

intermediate_layer_model = Model(inputs=model.input,
                                 outputs=model.get_layer(layer_name).output)
intermediate_output = intermediate_layer_model.predict(data)


问:
Unwanted Empty Modal on Page Load
Am working in PHP using a jquery dialogue as a modal to display my form errors.
Everything works fine and displays corrrectly except on page load... an empty modal is displayed.
If you close it then proceed to fill-in the form the modal works as it is intended, displaying errors (if any) when the submit button it clicked.
For the sake of brevity I've included only the relavent code.

Am seeking help on how to prevent the empty modal from displaying on page load. I've reviewed dozens of related submissions and attempted to try implementing them, with dismal results. In most cases they either have no effect, or end-up disabling the modal all together.

Thanks in advance for any suggestions.

```<code><?php

/// php error checking and form processing here ///

?>

<!DOCTYPE HTML>
<html>
<head>
<title>Page Title</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" media="screen" />
</head>
<body>

<form action="<?=$_SERVER['PHP_SELF']?>" name="inquiry" method="post">

/// form fields here ///

<ul class="actions">
<li><input type="submit" class="button small" name="submit" id="submit" value="Send Inquiry" /></li>
</ul>

</form>

<div id="error" title="Form Errors:">
<?php
if (!empty($errors))
{
echo "<div style=\"padding:15px 15px 0 15px\">";
echo "<ul style=\"margin-bottom:20px\">";
foreach ($errors as $error)
echo "<li style=\"font-size:15px; padding:5px\">$error</li>";
echo "</ul></div>";
}
?>
</div>

<!-- JS at the end -->

<script src="/assets/js/jquery.min.js"></script><!-- ver: 1.11.3 -->

<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<script>
$('#error').dialog({
height: 380,
width: 260,
modal: true,
resizable: false,
dialogClass: 'no-close error-dialog'
});
</script>

</body>
</html>
</code>```

答:
You could prevent this by calling the dialog init just when the form is submitted using $_POST["submit"] like :

```<code><script>
     <?php if( isset( $_POST["submit"] ) ){ ?>
         $('#error').dialog({
             height: 380,
             width: 260,
             modal: true,
             resizable: false,
             dialogClass: 'no-close error-dialog'
         });
     <?php } ?>
</script>
</code>```

Title: Unwanted Empty Modal on Page Load

Body:
Am working in PHP using a jquery dialogue as a modal to display my form errors.
Everything works fine and displays corrrectly except on page load... an empty modal is displayed.
If you close it then proceed to fill-in the form the modal works as it is intended, displaying errors (if any) when the submit button it clicked.
For the sake of brevity I've included only the relavent code.

Am seeking help on how to prevent the empty modal from displaying on page load. I've reviewed dozens of related submissions and attempted to try implementing them, with dismal results. In most cases they either have no effect, or end-up disabling the modal all together.

Thanks in advance for any suggestions.

<?php

/// php error checking and form processing here ///

?>

<!DOCTYPE HTML>

<title>Page Title</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" media="screen" />

<form action="<?=$_SERVER['PHP_SELF']?>" name="inquiry" method="post">

/// form fields here ///

<input type="submit" class="button small" name="submit" id="submit" value="Send Inquiry" />

</form>

<?php
if (!empty($errors))
{
echo "
";
echo "
";
foreach ($errors as $error)
echo "
$error
";
echo "

";
}
?>

Body:
You could prevent this by calling the dialog init just when the form is submitted using $_POST["submit"] like :

<script>
     <?php if( isset( $_POST["submit"] ) ){ ?>
         $('#error').dialog({
             height: 380,
             width: 260,
             modal: true,
             resizable: false,
             dialogClass: 'no-close error-dialog'
         });
     <?php } ?>
</script>


问:
That A-Ha Moment for Understanding OO Design in C#
I've been studying C# for a couple of years, reading voraciously, even taking a few C# data access courses from Microsoft.  I've also been reading books on OOP.  I'm coding a web-based database application at work.  While my job title is not "programmer", I'm fortunate enough to be able to work on this as a side project.  I coded in Basic in the early 80's and was even good at utilizing pokes and peeks to manipulate the Apple ][ + and the TRS-80 to astound and amaze my friends.  But that was a very linear approach to coding.

All this being said, something is just not clicking with me.  I haven't had that a-ha moment with either C# or OOP that gives me the ability to sit down, open up VS2008, and start coding.  I have to study other people's code so much that it simply seems like I'm not doing anything on my own.  I'm getting discouraged.

It's not like I'm not capable of it.  I picked up t-sql really quickly.  Someone can tell me what information they want out of the database and I can code out the tsql in a matter of a few minutes to give them what they want.  SQL is something that I get.  This isn't happening for me with OOP or C#.  Granted, C# is inherently more complex, but at some point it has to click.  Right?

I read over stackoverflow and I'm overwhelmed at how infinitely smart you all are.

What was it for you that made it click?

Edited to add:
A lot of the answers here were outstanding.  However, one in particular seemed to have risen to the top and that's the one I marked as the "answer".  I also hate not marking my questions with the answer.

答: There are lots of good suggestions here, though only Mr. Sampson has hinted that it would be beneficial to find the right people to answer questions.  I can't count how many times I've been watching someone work, interrupted them to ask a question along the lines of, "why did you do X?" and have an a-ha moment shortly thereafter.  Not always, but ask enough people enough questions, and the mind-meld will happen, and it's great when it does.

OwnerDisplayName: GregD

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: GregD

OwnerDisplayName: jbm


问:
File handling operetions in C
Can anyone point me to a reference or a beginner's tutorial for file handling in C.</p>

答:
```<code>$ man fopen
$ man fclose
$ man fread
$ man fwrite
$ man fprintf
$ man fscanf
$ man fflush
</code>```

And probably all the "see also" parts.

Title: File handling operetions in C

Body:
$ man fopen
$ man fclose
$ man fread
$ man fwrite
$ man fprintf
$ man fscanf
$ man fflush

And probably all the "see also" parts.


问:
Python + scrape strong within ul
I'm trying to scrape the information under the strong tag within ul.
I'm using the following code to extract strong:

```<code>stats = soup.find('ul', attrs = {'class' : 'inline-stats section'})
print(stats)
</code>```

The print is shown in the image below.
Now, I need to extract the information within strong; that is 8.0 , 49.41 and 6.10.

I tried to loop over values in stats but always get errors and got stuck.

Can anyone help me with this?

```<code><ul class="inline-stats section">
<li>
<strong>8.0<abbr class="unit" title="kilometers">km</abbr></strong>
<div class="label">Distance</div>
</li>
<li>
<strong>49:41</strong>
<div class="label">
<span class="glossary-link run-version" data-glossary-term="definition-moving-
time"></span>
Moving Time
</div>
</li>
<li>
<strong>6:10<abbr class="unit" title="minutes per kilometer">/km</abbr></strong>
<div class="label">
<span class="glossary-link run-version" data-glossary-term="definition-moving-
time">
Pace
</span>
</div>
</li>
</ul>
</code>```

答:
Try this:

```<code>stats = soup.find('ul', attrs = {'class' : 'inline-stats section'}).findAll("strong")
</code>```

Add:

```<code>for i in stats:
    print i
</code>```

Title: Python + scrape strong within ul

Body:
I'm trying to scrape the information under the strong tag within ul.
I'm using the following code to extract strong:

stats = soup.find('ul', attrs = {'class' : 'inline-stats section'})
print(stats)

The print is shown in the image below.
Now, I need to extract the information within strong; that is 8.0 , 49.41 and 6.10.

I tried to loop over values in stats but always get errors and got stuck.

Can anyone help me with this?

8.0km

Distance

49:41

Moving Time

6:10/km

Pace

Body:
Try this:

stats = soup.find('ul', attrs = {'class' : 'inline-stats section'}).findAll("strong")

Add:

for i in stats:
    print i


问:
How to define multiple relationships between two entities?
I have the scenario where a user can upload multiple photos (One-to-Many). The user also can have a default photo (One-to-One). However, I entity framework core 2.0 tells that he cannot recognize the relationship when I use the following code:

```<code>public class User
{
    public Guid Id { get; set; }

    public ICollection<Photo> Photos{ get; set; }

    public Photo DefaultPhoto { get; set; }
    [ForeignKey("DefaultPhoto")]
    public Guid DefaultPhotoId { get; set; }
}

public class Photo
{
    public Guid Id { get; set; }

    public User Owner { get; set; }
}
</code>```

How may I achieve these multiple relationships?

There error shown by EF-Core:

System.InvalidOperationException: 'Unable to determine the relationship represented by navigation property 'Photo.Owner' of type 'User'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.'

UPDATE:

Adding [InverseProperty("Photos")] to the navigation property Owner in File Model seems to be working. I am not sure if that is the correct way?

In this image File=Photo; Uploader=Owner (to be comparable with the above model).

UPDATE 2:

I confirm what @Ivan said in the comments, with DataAnnotation approach, I get One-to-Many in two directions instead of One-to-Many and One-to-One. This figure shows the generated database by using InverseProperty (the connection between the to entities show the bi-directional One-to-Many relationship):

In this image File=Photo; Uploader=Owner (to be comparable with the above model).

答:
Use the Fluent API to establish the one-to-one relationship:

```<code>protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    // Establish a one to one relationship with the
    // User as the dependent End
    modelBuilder.Entity<User>()
        .HasOne(u => u.DefaultPhoto)
        .WithOne(p => p.Owner)
        .HasForeignKey<User>(u => u.DefaultPhotoId);
}
</code>```

For a relationship to be a one-to-one (1:0..1) relationship, the relationship must be established between two primary keys or two candidate keys. (Check this blog post for more info on this.)

EF has no way of setting a candidate key (also called unique or alternate key) via Annotations right now, so this is your only option. Check the EF docs here at Microsoft Docs: One to One relationships

Update: The earlier code would automatically generate a UserId column and sets up relationships correctly. I've added the OwnerId field to the Photo entity to manually set the relationship, like you wanted:

```<code>public class User
{
    public Guid Id { get; set; }

    [InverseProperty("Owner")]
    public ICollection<Photo> Photos{ get; set; }

    public Photo DefaultPhoto { get; set; }
    public Guid DefaultPhotoId { get; set; }
}

public class Photo
{
    public Guid Id { get; set; }

    public Guid OwnerId { get; set; }
    public User Owner { get; set; }
}

public class MyDbContext : DbContext
{
    public DbSet<User> Users { get; set; }
    public DbSet<Photo> Photos { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // You may use this instead of the inverse property
        // // The One to Many relationship between
        // // User.Id (Principal End) and Photo.OwnerId
        // modelBuilder.Entity<Photo>()
        //     .HasOne(p => p.Owner)
        //     .WithMany(u => u.Photos)
        //     .HasForeignKey(p => p.OwnerId);

        // Establishes 1:0..1 relationship between
        // Photo.Id (Principal End) and User.DefaultPhoto (Dependent end)
        modelBuilder.Entity<User>()
            .HasOne(u => u.DefaultPhoto)
            .WithOne() // we leave this empty because it doesn't correspond to a navigation property in the Photos table
            .HasForeignKey<User>(u => u.DefaultPhotoId);
    }
}
</code>```

The trick is in figuring the relationships (especially the principal end and the dependent ends) and in figuring which ones require navigation properties.

The Inverse property is required because EF doesn't know which property to map to Photo.Owner. It's just a way of making a relationship explicit in cases like these.

Body:
I have the scenario where a user can upload multiple photos (One-to-Many). The user also can have a default photo (One-to-One). However, I entity framework core 2.0 tells that he cannot recognize the relationship when I use the following code:

public class User
{
    public Guid Id { get; set; }

    public ICollection<Photo> Photos{ get; set; }

    public Photo DefaultPhoto { get; set; }
    [ForeignKey("DefaultPhoto")]
    public Guid DefaultPhotoId { get; set; }
}

public class Photo
{
    public Guid Id { get; set; }

    public User Owner { get; set; }
}

How may I achieve these multiple relationships?

There error shown by EF-Core:

System.InvalidOperationException: 'Unable to determine the relationship represented by navigation property 'Photo.Owner' of type 'User'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.'

UPDATE:

Adding [InverseProperty("Photos")] to the navigation property Owner in File Model seems to be working. I am not sure if that is the correct way?

In this image File=Photo; Uploader=Owner (to be comparable with the above model).

UPDATE 2:

I confirm what @Ivan said in the comments, with DataAnnotation approach, I get One-to-Many in two directions instead of One-to-Many and One-to-One. This figure shows the generated database by using InverseProperty (the connection between the to entities show the bi-directional One-to-Many relationship):

In this image File=Photo; Uploader=Owner (to be comparable with the above model).

Body:
Use the Fluent API to establish the one-to-one relationship:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    // Establish a one to one relationship with the
    // User as the dependent End
    modelBuilder.Entity<User>()
        .HasOne(u => u.DefaultPhoto)
        .WithOne(p => p.Owner)
        .HasForeignKey<User>(u => u.DefaultPhotoId);
}

For a relationship to be a one-to-one (1:0..1) relationship, the relationship must be established between two primary keys or two candidate keys. (Check this blog post for more info on this.)

EF has no way of setting a candidate key (also called unique or alternate key) via Annotations right now, so this is your only option. Check the EF docs here at Microsoft Docs: One to One relationships

Update: The earlier code would automatically generate a UserId column and sets up relationships correctly. I've added the OwnerId field to the Photo entity to manually set the relationship, like you wanted:

public class User
{
    public Guid Id { get; set; }

    [InverseProperty("Owner")]
    public ICollection<Photo> Photos{ get; set; }

    public Photo DefaultPhoto { get; set; }
    public Guid DefaultPhotoId { get; set; }
}

public class Photo
{
    public Guid Id { get; set; }

    public Guid OwnerId { get; set; }
    public User Owner { get; set; }
}

public class MyDbContext : DbContext
{
    public DbSet<User> Users { get; set; }
    public DbSet<Photo> Photos { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // You may use this instead of the inverse property
        // // The One to Many relationship between
        // // User.Id (Principal End) and Photo.OwnerId
        // modelBuilder.Entity<Photo>()
        //     .HasOne(p => p.Owner)
        //     .WithMany(u => u.Photos)
        //     .HasForeignKey(p => p.OwnerId);

        // Establishes 1:0..1 relationship between
        // Photo.Id (Principal End) and User.DefaultPhoto (Dependent end)
        modelBuilder.Entity<User>()
            .HasOne(u => u.DefaultPhoto)
            .WithOne() // we leave this empty because it doesn't correspond to a navigation property in the Photos table
            .HasForeignKey<User>(u => u.DefaultPhotoId);
    }
}

The trick is in figuring the relationships (especially the principal end and the dependent ends) and in figuring which ones require navigation properties.

The Inverse property is required because EF doesn't know which property to map to Photo.Owner. It's just a way of making a relationship explicit in cases like these.


问:
Run multiple recursive functions in C
I'm trying to do the "boggle" game, I have a 2D matrix with letters and I have to find words.
Matrix: contains this letters: { {'C','A','R','T'}, {'E', 'T', 'A', 'K'}, {'E','S','M','E'}, {'L', 'L', 'P', 'N'} };
input: this matrix
output: all the words that found in matrix, from dictionary "isWord".

the code should take the matrix, index, index, word, and bool matrix.
every letter that I go on should marked in bool matrix as true, and then I continue with recursion untill its going out lengths. I go on 4 paths every time. I can't go back only forward.
the main problem with code that is running only in one path and not continuing with the rests of paths. [calling to "checkword" few times and it seems like its stick the first command].

Anyone ideas? pretty new in C.

```<code>#include <stdio.h>
        #include <string.h>
        #include <stdbool.h>
        bool isWord(char *s);

        void check(char mat[4][4]) {
            int i,j;
            int counter=0;
            for(i=0; i<4; i++) {
                for(j =0; j<4; j++) {
                    char str[12] = "";
                    //append(str, mat[i][j]);
                    bool checker[4][4]={{false}};
                    //printf("mat[%d][%d]: %s\n", i, j, str);
                    checkword(mat,i,j, str, checker);
                    counter++;
                     fflush(stdout);
                }
            }
        }
        void append(char* s, char c)
        {
                int len = strlen(s);
                s[len] = c;
                s[len+1] = '\0';
        }
        void checkword(char mat[4][4], int i, int j, char word[], bool checker[4][4])
        {
          if(i >= 0 && i<4 && j >= 0 && j < 4)
          {
              if(!checker[i][j])
              {
                 // Mark current cell as visited and append current character
            // to str
            checker[i][j] = true;
            append(word, mat[i][j]);
            printf("%s\n", word);
            // If str is present in dictionary, then print it
            if (isWord(word))
                printf("Found word: %s\n", word);

            checkword(mat, i+1, j, word, checker);
            checkword(mat, i, j+1, word, checker);
            checkword(mat, i, j-1, word, checker);
            checkword(mat, i-1, j, word, checker);
              }

         }
        }

        bool isWord(char* s) {
                return (!strcmp(s,"CAT") |
                    !strcmp(s,"CATS") |
                    !strcmp(s,"TRAM") |
                    !strcmp(s,"TRAMS") |
                    !strcmp(s,"TAME") |
                    !strcmp(s,"CAR") |
                    !strcmp(s,"CARS") |
                    !strcmp(s,"RAT") |
                    !strcmp(s,"RATS") |
                    !strcmp(s,"RAMP") |
                    !strcmp(s,"ART") |
                    !strcmp(s,"CART") |
                    !strcmp(s,"STAMP") |
                    !strcmp(s,"TAKEN") |
                    !strcmp(s,"MEN") |
                    !strcmp(s,"MAKE") |
                    !strcmp(s,"TAKE") |
                    !strcmp(s,"ATE") |
                    !strcmp(s,"SELL") |
                    !strcmp(s,"STEEL") |
                    !strcmp(s,"RAKE") );
        }

        int main() {
            char mat[4][4] = { {'C','A','R','T'}, {'E', 'T', 'A', 'K'}, {'E','S','M','E'}, {'L', 'L', 'P', 'N'} };
            check(mat);
         //   printf("Numbers of cells : %d", count);
        }
</code>```

答:
lets go through what will happen if it runs:

for every starting point you do the same. e.g. (0,0)

checkword(mat, 1, 0, word, checker); -> (0,0) -> marked as checked

checkword(mat, 2, 0, word, checker); -> (1,0) -> marked as checked

checkword(mat, 3, 0, word, checker); -> (2,0) -> marked as checked

checkword(mat, 4, 0, word, checker); -> illegal

checkword(mat, 3, 1, word, checker); -> (3,0) -> marked as checked

this means you are only going through one path per starting point and checking for legal words.

What you want to do is go down every path from the starting point. you achieve this by unmarking the field as checked when you are finished going down all paths of recursion.

So add :

```<code>checkword(mat, i+1, j, word, checker);
checkword(mat, i, j+1, word, checker);
checkword(mat, i, j-1, word, checker);
checkword(mat, i-1, j, word, checker);
checker[i][j]=false; // <-- clear path for other paths
shortenByOne(word);
</code>```

edit:
also you will need to shorten the word once you're done- I forgot about that:

```<code>void shortenByOne(char* s)
{
        int len = strlen(s);
        if(len==0) return;
        s[len-1] = '\0';
}
</code>```

Title: Run multiple recursive functions in C

Body:
I'm trying to do the "boggle" game, I have a 2D matrix with letters and I have to find words.
Matrix: contains this letters: { {'C','A','R','T'}, {'E', 'T', 'A', 'K'}, {'E','S','M','E'}, {'L', 'L', 'P', 'N'} };
input: this matrix
output: all the words that found in matrix, from dictionary "isWord".

the code should take the matrix, index, index, word, and bool matrix.
every letter that I go on should marked in bool matrix as true, and then I continue with recursion untill its going out lengths. I go on 4 paths every time. I can't go back only forward.
the main problem with code that is running only in one path and not continuing with the rests of paths. [calling to "checkword" few times and it seems like its stick the first command].

Anyone ideas? pretty new in C.

#include <stdio.h>
        #include <string.h>
        #include <stdbool.h>
        bool isWord(char *s);

        void check(char mat[4][4]) {
            int i,j;
            int counter=0;
            for(i=0; i<4; i++) {
                for(j =0; j<4; j++) {
                    char str[12] = "";
                    //append(str, mat[i][j]);
                    bool checker[4][4]={{false}};
                    //printf("mat[%d][%d]: %s\n", i, j, str);
                    checkword(mat,i,j, str, checker);
                    counter++;
                     fflush(stdout);
                }
            }
        }
        void append(char* s, char c)
        {
                int len = strlen(s);
                s[len] = c;
                s[len+1] = '\0';
        }
        void checkword(char mat[4][4], int i, int j, char word[], bool checker[4][4])
        {
          if(i >= 0 && i<4 && j >= 0 && j < 4)
          {
              if(!checker[i][j])
              {
                 // Mark current cell as visited and append current character
            // to str
            checker[i][j] = true;
            append(word, mat[i][j]);
            printf("%s\n", word);
            // If str is present in dictionary, then print it
            if (isWord(word))
                printf("Found word: %s\n", word);

            checkword(mat, i+1, j, word, checker);
            checkword(mat, i, j+1, word, checker);
            checkword(mat, i, j-1, word, checker);
            checkword(mat, i-1, j, word, checker);
              }

         }
        }

        bool isWord(char* s) {
                return (!strcmp(s,"CAT") |
                    !strcmp(s,"CATS") |
                    !strcmp(s,"TRAM") |
                    !strcmp(s,"TRAMS") |
                    !strcmp(s,"TAME") |
                    !strcmp(s,"CAR") |
                    !strcmp(s,"CARS") |
                    !strcmp(s,"RAT") |
                    !strcmp(s,"RATS") |
                    !strcmp(s,"RAMP") |
                    !strcmp(s,"ART") |
                    !strcmp(s,"CART") |
                    !strcmp(s,"STAMP") |
                    !strcmp(s,"TAKEN") |
                    !strcmp(s,"MEN") |
                    !strcmp(s,"MAKE") |
                    !strcmp(s,"TAKE") |
                    !strcmp(s,"ATE") |
                    !strcmp(s,"SELL") |
                    !strcmp(s,"STEEL") |
                    !strcmp(s,"RAKE") );
        }

        int main() {
            char mat[4][4] = { {'C','A','R','T'}, {'E', 'T', 'A', 'K'}, {'E','S','M','E'}, {'L', 'L', 'P', 'N'} };
            check(mat);
         //   printf("Numbers of cells : %d", count);
        }

Body:
lets go through what will happen if it runs:

for every starting point you do the same. e.g. (0,0)

checkword(mat, 1, 0, word, checker); -> (0,0) -> marked as checked

checkword(mat, 2, 0, word, checker); -> (1,0) -> marked as checked

checkword(mat, 3, 0, word, checker); -> (2,0) -> marked as checked

checkword(mat, 4, 0, word, checker); -> illegal

checkword(mat, 3, 1, word, checker); -> (3,0) -> marked as checked

this means you are only going through one path per starting point and checking for legal words.

What you want to do is go down every path from the starting point. you achieve this by unmarking the field as checked when you are finished going down all paths of recursion.

So add :

checkword(mat, i+1, j, word, checker);
checkword(mat, i, j+1, word, checker);
checkword(mat, i, j-1, word, checker);
checkword(mat, i-1, j, word, checker);
checker[i][j]=false; // <-- clear path for other paths
shortenByOne(word);

edit:
also you will need to shorten the word once you're done- I forgot about that:

void shortenByOne(char* s)
{
        int len = strlen(s);
        if(len==0) return;
        s[len-1] = '\0';
}


问:
How to extract a sample of pairs in grouping variable
My data looks like this:

```<code>x  y
1  1
2  2
3  2
4  4
5  5
6  6
7  6
8  8
9  9
10  9
11  11
12  12
13  13
14  13
15  14
16  15
17  14
18  16
19  17
20  18
</code>```

y is a grouping variable. I would like to see how well this grouping went.
Because of this I want to extract a sample of n pairs of cases that are grouped together by variable y
and n pairs of cases that are not grouped together by variable y. In order to calculate the number of
false positives and false negatives (either falsly grouped or not). How do I extract a sample of grouped pairs
and a sample of not-grouped pairs?

I would like the samples to look like this (for n=6) :
Grouped sample:

```<code>x  y
2  2
3  2
9  9
10  9
15  14
17  14
</code>```

Not-grouped sample:

```<code>x  y
1  1
2  2
6  8
6  8
11  11
19  17
</code>```

How would I go about this in R?

答:
I'm not entirely clear on what you like to do, partly because I feel there is some context missing as to what you're trying to achieve. I also don't quite understand your expected output (for example, the not-grouped sample contains an entry 6 8 that does not exist in your original data...)

That aside, here is a possible approach.

```<code># Maximum number of samples per group
n <- 3;

# Set fixed RNG seed for reproducibility
set.seed(2017);

# Grouped samples
df.grouped <- do.call(rbind.data.frame, lapply(split(df, df$y),
    function(x) if (nrow(x) > 1) x[sample(min(n, nrow(x))), ]));
df.grouped;
#       x  y
#2.3    3  2
#2.2    2  2
#6.6    6  6
#6.7    7  6
#9.10  10  9
#9.9    9  9
#13.13 13 13
#13.14 14 13
#14.15 15 14
#14.17 17 14

# Ungrouped samples
df.ungrouped <- df[sample(nrow(df.grouped)), ];
df.ungrouped;
#    x y
#7   7 6
#1   1 1
#9   9 9
#4   4 4
#3   3 2
#2   2 2
#5   5 5
#6   6 6
#10 10 9
#8   8 8
</code>```

Explanation: Split df based on y, then draw min(n, nrow(x)) samples from subset x containing >1 rows; rbinding gives the grouped df.grouped. We then draw nrow(df.grouped) samples from df to produce the ungrouped df.ungrouped.

Sample data

```<code>df <- read.table(text =
    "x  y
     1  1
     2  2
     3  2
     4  4
     5  5
     6  6
     7  6
     8  8
     9  9
     10  9
     11  11
     12  12
     13  13
     14  13
     15  14
     16  15
     17  14
     18  16
     19  17
     20  18", header = T)
</code>```

Body:
My data looks like this:

x  y
1  1
2  2
3  2
4  4
5  5
6  6
7  6
8  8
9  9
10  9
11  11
12  12
13  13
14  13
15  14
16  15
17  14
18  16
19  17
20  18

y is a grouping variable. I would like to see how well this grouping went.
Because of this I want to extract a sample of n pairs of cases that are grouped together by variable y
and n pairs of cases that are not grouped together by variable y. In order to calculate the number of
false positives and false negatives (either falsly grouped or not). How do I extract a sample of grouped pairs
and a sample of not-grouped pairs?

I would like the samples to look like this (for n=6) :
Grouped sample:

x  y
2  2
3  2
9  9
10  9
15  14
17  14

Not-grouped sample:

x  y
1  1
2  2
6  8
6  8
11  11
19  17

How would I go about this in R?

Body:
I'm not entirely clear on what you like to do, partly because I feel there is some context missing as to what you're trying to achieve. I also don't quite understand your expected output (for example, the not-grouped sample contains an entry 6 8 that does not exist in your original data...)

That aside, here is a possible approach.

# Maximum number of samples per group
n <- 3;

# Set fixed RNG seed for reproducibility
set.seed(2017);

# Grouped samples
df.grouped <- do.call(rbind.data.frame, lapply(split(df, df$y),
    function(x) if (nrow(x) > 1) x[sample(min(n, nrow(x))), ]));
df.grouped;
#       x  y
#2.3    3  2
#2.2    2  2
#6.6    6  6
#6.7    7  6
#9.10  10  9
#9.9    9  9
#13.13 13 13
#13.14 14 13
#14.15 15 14
#14.17 17 14

# Ungrouped samples
df.ungrouped <- df[sample(nrow(df.grouped)), ];
df.ungrouped;
#    x y
#7   7 6
#1   1 1
#9   9 9
#4   4 4
#3   3 2
#2   2 2
#5   5 5
#6   6 6
#10 10 9
#8   8 8

Explanation: Split df based on y, then draw min(n, nrow(x)) samples from subset x containing >1 rows; rbinding gives the grouped df.grouped. We then draw nrow(df.grouped) samples from df to produce the ungrouped df.ungrouped.

Sample data

df <- read.table(text =
    "x  y
     1  1
     2  2
     3  2
     4  4
     5  5
     6  6
     7  6
     8  8
     9  9
     10  9
     11  11
     12  12
     13  13
     14  13
     15  14
     16  15
     17  14
     18  16
     19  17
     20  18", header = T)


问:
OpenAL Soft - Loop with Intro
I have been using OpenAL soft for Win32, and I I ran into a particular problem.

My goal is to play a looping sound that has a one-shot intro portion, similar to a .WAV file with a loop marker.  As I understand it, this must be achieved in OpenAL by using multiple buffers on a source.  In general, my approach is to queue up both buffers, then wait until the second buffer is playing, and set the source to loop.  This works, but the problem is that once I am ready to stop the sound, I don't seem to be able to unqueue the last buffer.  My code looks roughly like this:

```<code>// set up the sound
alSourceQueueBuffers(source, 1, &buffer1);
alSourceQueueBuffers(source, 1, &buffer2);
alSourcePlay(source);

...

// check to loop sound in update
ALint buffer;
alGetSourcei(source, AL_BUFFER, &buffer);
if (buffer == buffer2)
{
    alSourcei(source, AL_LOOPING, true);
}

..

// check to stop sound in update
if (shouldStop)
{
    alSourcei(source, AL_LOOPING, false);
    alSourceStop(source);

    alSourceUnqueueBuffers(source, 1, &buffer1);
    alSourceUnqueueBuffers(source, 1, &buffer2); // AL_INVALID_OPERATION
}
</code>```

The result seems to be that the buffer is not properly unqueued, and will be heard the next time I play this source.  I know that typically you can only unqueue a buffer after it finished playing, but I would think that I could freely unqueue any buffers on a stopped sound.  I am wondering if perhaps my use of the loop flag is causing this behavior?

I'd greatly appreciate any advice.

Thank you,
Mike

答:
I believe the proper use of alSourceUnqueueBuffers(source, 1, &buffer1); is to create an array of your buffers and send it in, instead of calling it twice, you call it once on the array like so:

```<code>ALuint buffers[2] = { buffer1, buffer2 };
alSourceUnqueueBuffers(source, 2, buffers);
</code>```

Note we are using a size of 2 to indicate 2 buffers.

Title: OpenAL Soft - Loop with Intro

Body:
I have been using OpenAL soft for Win32, and I I ran into a particular problem.

My goal is to play a looping sound that has a one-shot intro portion, similar to a .WAV file with a loop marker.  As I understand it, this must be achieved in OpenAL by using multiple buffers on a source.  In general, my approach is to queue up both buffers, then wait until the second buffer is playing, and set the source to loop.  This works, but the problem is that once I am ready to stop the sound, I don't seem to be able to unqueue the last buffer.  My code looks roughly like this:

// set up the sound
alSourceQueueBuffers(source, 1, &buffer1);
alSourceQueueBuffers(source, 1, &buffer2);
alSourcePlay(source);

...

// check to loop sound in update
ALint buffer;
alGetSourcei(source, AL_BUFFER, &buffer);
if (buffer == buffer2)
{
    alSourcei(source, AL_LOOPING, true);
}

..

// check to stop sound in update
if (shouldStop)
{
    alSourcei(source, AL_LOOPING, false);
    alSourceStop(source);

    alSourceUnqueueBuffers(source, 1, &buffer1);
    alSourceUnqueueBuffers(source, 1, &buffer2); // AL_INVALID_OPERATION
}

The result seems to be that the buffer is not properly unqueued, and will be heard the next time I play this source.  I know that typically you can only unqueue a buffer after it finished playing, but I would think that I could freely unqueue any buffers on a stopped sound.  I am wondering if perhaps my use of the loop flag is causing this behavior?

I'd greatly appreciate any advice.

Thank you,
Mike

Body:
I believe the proper use of alSourceUnqueueBuffers(source, 1, &buffer1); is to create an array of your buffers and send it in, instead of calling it twice, you call it once on the array like so:

ALuint buffers[2] = { buffer1, buffer2 };
alSourceUnqueueBuffers(source, 2, buffers);

Note we are using a size of 2 to indicate 2 buffers.


问:
How can I add a condition inside a php object?
I have n php object like this:

```<code>        $test
        ->key1(1)
        ->key2(1)
        ->key3(1);
</code>```

Is it possible to add a condition inside it?

like this:

```<code>   $test
   if(true) ->key1(1)
   ->key2(1)
   if(true) ->key3(1);
</code>```

答:
what you want is

```<code>if (condition) {
    code to be executed if this condition is true;
} elseif (condition) {
    code to be executed if this condition is true;
} else {
    code to be executed if all conditions are false;
}
</code>```

for example

```<code>if ($YOUR_KEY == "key1") {
    //if key1 then do something
} elseif ($YOUR_KEY == "key2") {
    //if key2 then do something
} else {
    //if none condition work than do something else
}
</code>```

here $YOUR_KEY is your variable and "key1" is your value

check www.w3schools.com and http://php.net/manual for reference

Body:
I have n php object like this:

        $test
        ->key1(1)
        ->key2(1)
        ->key3(1);

Is it possible to add a condition inside it?

like this:

   $test
   if(true) ->key1(1)
   ->key2(1)
   if(true) ->key3(1);

Body:
what you want is

if (condition) {
    code to be executed if this condition is true;
} elseif (condition) {
    code to be executed if this condition is true;
} else {
    code to be executed if all conditions are false;
}

for example

if ($YOUR_KEY == "key1") {
    //if key1 then do something
} elseif ($YOUR_KEY == "key2") {
    //if key2 then do something
} else {
    //if none condition work than do something else
}

here $YOUR_KEY is your variable and "key1" is your value

check www.w3schools.com and http://php.net/manual for reference


问:
Nginx forward to tomcat failing
I was trying to forward my nginx server to tomcat (on the same server).

I followed the following tutorials:

https://www.digitalocean.com/community/tutorials/how-to-secure-nginx-with-let-s-encrypt-on-centos-7
https://www.digitalocean.com/community/tutorials/how-to-encrypt-tomcat-8-connections-with-apache-or-nginx-on-centos-7

But it still doesn't seem to work, although it did on my previous server.

Here is my nginx configuration

```<code>....

Load modular configuration files from the /etc/nginx/conf.d directory.
# See http://nginx.org/en/docs/ngx_core_module.html#include
# for more information.
include /etc/nginx/conf.d/*.conf;

upstream tomcat {
server 127.0.0.1:8080 fail_timeout=0;
}

server {
    listen       80 default_server;
    listen       [::]:80 default_server;
    server_name  mywebsite.be demo.mywebsite.be;
    root         /usr/share/nginx/html;

    # Load configuration files for the default server block.
    include /etc/nginx/default.d/*.conf;

    location / {
       #try_files $uri $uri/ =404;
    proxy_pass http://tomcat/;
    proxy_set_header Host $http_host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    }
    ....
</code>```

When I restart nginx and go to my website, I get the following error:

"The page you are looking for is temporarily unavailable. Please try again later."

While my tomcat server is online and working.

I have no idea what is going wrong, I already reinstalled nginx and tomcat a couple of times.

The nginx error logs gives the following errors

```<code>2017/12/09 13:33:53 [crit] 1288#0: *73 connect() to 127.0.0.1:8080 failed (13: Permission denied) while connecting to
     upstream, client: 87.**.***.244, server: mywebsite.be, request: "GET / HTTP/1.1", upstream: "http://127.0.0
    .1:8080/", host: "demo.mywebsite.be"

2017/12/09 13:33:53 [crit] 1288#0: *73 connect() to 127.0.0.1:8080 failed (13: Permission denied) while connecting to
 upstream, client: 87.**.***.244, server: mywebsite.be, request: "GET /nginx-logo.png HTTP/1.1", upstream: "
http://127.0.0.1:8080/nginx-logo.png", host: "demo.mywebsite.be", referrer: "https://demo.mywebsite.be/"

2017/12/09 13:33:53 [crit] 1288#0: *74 connect() to 127.0.0.1:8080 failed (13: Permission denied) while connecting to
 upstream, client: 87.**.***.244, server: mywebsite.be, request: "GET /poweredby.png HTTP/1.1", upstream: "h
ttp://127.0.0.1:8080/poweredby.png", host: "demo.mywebsite.be", referrer: "https://demo.mywebsite.be/"

2017/12/09 13:33:53 [crit] 1288#0: *74 connect() to 127.0.0.1:8080 failed (13: Permission denied) while connecting to upstream, client: 87.**.***.244, server: mywebsite.be, request: "GET /favicon.ico HTTP/1.1", upstream: "http://127.0.0.1:8080/favicon.ico", host: "demo.mywebsite.be", referrer: "https://demo.mywebsite.be/"
</code>```

答:
Thanks to Richard Smith for the idea of the error log

I have solved this by running the following command:

```<code>/usr/sbin/setsebool httpd_can_network_connect true
</code>```

Like explained on:

nginx proxy server localhost permission denied

Title: Nginx forward to tomcat failing

Body:
I was trying to forward my nginx server to tomcat (on the same server).

I followed the following tutorials:

https://www.digitalocean.com/community/tutorials/how-to-secure-nginx-with-let-s-encrypt-on-centos-7
https://www.digitalocean.com/community/tutorials/how-to-encrypt-tomcat-8-connections-with-apache-or-nginx-on-centos-7

But it still doesn't seem to work, although it did on my previous server.

Here is my nginx configuration

....

Load modular configuration files from the /etc/nginx/conf.d directory.
# See http://nginx.org/en/docs/ngx_core_module.html#include
# for more information.
include /etc/nginx/conf.d/*.conf;

upstream tomcat {
server 127.0.0.1:8080 fail_timeout=0;
}

server {
    listen       80 default_server;
    listen       [::]:80 default_server;
    server_name  mywebsite.be demo.mywebsite.be;
    root         /usr/share/nginx/html;

    # Load configuration files for the default server block.
    include /etc/nginx/default.d/*.conf;

    location / {
       #try_files $uri $uri/ =404;
    proxy_pass http://tomcat/;
    proxy_set_header Host $http_host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    }
    ....

When I restart nginx and go to my website, I get the following error:

"The page you are looking for is temporarily unavailable. Please try again later."

While my tomcat server is online and working.

I have no idea what is going wrong, I already reinstalled nginx and tomcat a couple of times.

The nginx error logs gives the following errors

2017/12/09 13:33:53 [crit] 1288#0: *73 connect() to 127.0.0.1:8080 failed (13: Permission denied) while connecting to
     upstream, client: 87.**.***.244, server: mywebsite.be, request: "GET / HTTP/1.1", upstream: "http://127.0.0
    .1:8080/", host: "demo.mywebsite.be"

2017/12/09 13:33:53 [crit] 1288#0: *73 connect() to 127.0.0.1:8080 failed (13: Permission denied) while connecting to
 upstream, client: 87.**.***.244, server: mywebsite.be, request: "GET /nginx-logo.png HTTP/1.1", upstream: "
http://127.0.0.1:8080/nginx-logo.png", host: "demo.mywebsite.be", referrer: "https://demo.mywebsite.be/"

2017/12/09 13:33:53 [crit] 1288#0: *74 connect() to 127.0.0.1:8080 failed (13: Permission denied) while connecting to
 upstream, client: 87.**.***.244, server: mywebsite.be, request: "GET /poweredby.png HTTP/1.1", upstream: "h
ttp://127.0.0.1:8080/poweredby.png", host: "demo.mywebsite.be", referrer: "https://demo.mywebsite.be/"

2017/12/09 13:33:53 [crit] 1288#0: *74 connect() to 127.0.0.1:8080 failed (13: Permission denied) while connecting to upstream, client: 87.**.***.244, server: mywebsite.be, request: "GET /favicon.ico HTTP/1.1", upstream: "http://127.0.0.1:8080/favicon.ico", host: "demo.mywebsite.be", referrer: "https://demo.mywebsite.be/"

Body:
Thanks to Richard Smith for the idea of the error log

I have solved this by running the following command:

/usr/sbin/setsebool httpd_can_network_connect true

Like explained on:

nginx proxy server localhost permission denied


答:
You should pass Textview as a parameter in adapter when you pass from activity

Second you should done this by using interface.

Another option is you can get textview by using Object of Activity.

like this MyActivity.java

```<code> MyActivity myActivity;
 public TextView tv_name;
</code>```

Adapter.java

```<code>myActivity.tv_name.setText("InsaneCat");
</code>```

Hope this help you

Title: How to get TextView of an activity in an Adapter class while that TextView is not in row of recyclerView?

Body:
How to get TextView of an Activity  in  RecyclerViewAdapter class and TextView is not in layout of row For  RecyclerView  item.As in RecyclerViewAdapter we override method

onBindViewHolder(ViewHolder holder, int position){
   NewsModel newsModel=values.get(position);  //to get the current object
        holder.news_title.setText(newsModel.getTitle());
        holder.news_body.setText(newsModel.getDescription());
        holder.news_published_at.setText("Date "+GiveMeDate(values.get(position).getDate()));}

and as it get only those which are declared in ViewHolder extends RecyclerView.ViewHolder   and ViewHolder  will only get ui that are in View v = inflater.inflate(R.layout.news_item, parent, false);but I want to get ui from activity's layout so that I can update TextView value in Adapter So please Help to do that work. Image to reflect Layout is as follows:

Body:
You should pass Textview as a parameter in adapter when you pass from activity

Second you should done this by using interface.

Another option is you can get textview by using Object of Activity.

like this MyActivity.java

 MyActivity myActivity;
 public TextView tv_name;

Adapter.java

myActivity.tv_name.setText("InsaneCat");

Hope this help you


问:
laravel mutator increment number when we get the record
I have a model called Alsolike , i want when we get the data from the database i want to increment number of views, to know how many times the record viewed  , here is what i tried to do , also if there is a good approche, suggest </p>

```<code>    <?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Alsolike extends Model
{
    public function getMealidAttribute($value)
    {
        $user = App\Alsolike::first()->increment('view');;
        $user->save();
    }
}
</code>```

答:
...also if there is a good [approach], suggest...

I think the middleware approach fits better in your scenario. Create a middleware, like IncrementViews, that will increment the number of views for your AlsoLike model every time a route is visited.

You may also want to limit or filter how your views will be incremented, maybe try to create a table to save the ip addresses of your users then check if the same ip address has already visited the page for a number of minutes.

Body:
I have a model called Alsolike , i want when we get the data from the database i want to increment number of views, to know how many times the record viewed  , here is what i tried to do , also if there is a good approche, suggest

    <?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Alsolike extends Model
{
    public function getMealidAttribute($value)
    {
        $user = App\Alsolike::first()->increment('view');;
        $user->save();
    }
}


问:
PHP - isolate first letter from a text
I have a set of articles, in which I want to style the first letter from each article (with CSS).

the articles usually start with a paragrah, like:

```<code><p> bla bla </p>
</code>```

So how could I wrap the first letter from this text within a <span> tag ?

答:
You can do this in all CSS.

CSS supports "Pseudo-Elements" where you can choose the first letter / first word and format it differently from the rest of the document.

http://www.w3schools.com/CSS/CSS_pseudo_elements.asp

There's a compatibility chart; some of these may not work in IE 6

http://kimblim.dk/css-tests/selectors/

Title: PHP - isolate first letter from a text

Body:
I have a set of articles, in which I want to style the first letter from each article (with CSS).

the articles usually start with a paragrah, like:

 bla bla

So how could I wrap the first letter from this text within a <span> tag ?


问:
Netcoreapp2.0 won't start in Azure App Service with Error 500 and no logs
All of a sudden my  Azure App Service can't start a aspnetcore2.0 and there is no logs. Just error 500 and no logs in Application Insights or Streaming Servicecs in Kudu.

App works perfectly on localhost, but standalone and with IIS Express and was working fine before in Azure yesterday.

How can I troubleshoot this?

答:
TL;DR;  Azure is probably having issues with binding redirects due to other runtimes and .NET versions. Add this to your csproj in the calling code (usually your web project).

```<code><PropertyGroup>
    <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
</PropertyGroup>
</code>```

Troubleshooting steps:

Enable startup logging

```<code>public static IWebHost BuildWebHost(string[] args) => WebHost
    .CreateDefaultBuilder(args)
    .CaptureStartupErrors(true)
    [...]
</code>```

Open Kudu tools and watch the streaming log service

https://.scm.azurewebsites.net/api/logstream

where you might find an error like:

```<code>2017-12-09 11:53:33.304 +00:00 [Error] Microsoft.AspNetCore.Server.Kestrel: Connection id "0HL9UVDQACN2F", Request id "0HL9UVDQACN2F:00000002": An unhandled exception was thrown by the application.
System.IO.FileNotFoundException: Could not load file or assembly 'System.Net.Http.WebRequest, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. The system cannot find the file specified.
File name: 'System.Net.Http.WebRequest, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
   at Microsoft.Rest.ServiceClient`1.CreateRootHandler()
</code>```

[..]

Look for places where your code might load an assembly, I found out that:

```<code>File name: 'System.Net.Http.WebRequest, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
   at Microsoft.Rest.ServiceClient`1.CreateRootHandler()
   at MyApp.MiddleLayer.Services.AzureSearch.DependencyInjection.<>c.<AddAzureSearch>b__0_1(IServiceProvider x) in C:\<Path>.Services.AzureSearch\DependencyInjection.cs:line 27
</code>```

Which is where I add my Azure Search code in my app.

Either add missing assemblies, or as in my case where Azure Search SDK was referencing old assembly, enable AutoGenerateBindingRedirects as described in top of this post.

Body:
TL;DR;  Azure is probably having issues with binding redirects due to other runtimes and .NET versions. Add this to your csproj in the calling code (usually your web project).

<PropertyGroup>
    <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
</PropertyGroup>

Troubleshooting steps:

Enable startup logging

public static IWebHost BuildWebHost(string[] args) => WebHost
    .CreateDefaultBuilder(args)
    .CaptureStartupErrors(true)
    [...]

Open Kudu tools and watch the streaming log service

https://.scm.azurewebsites.net/api/logstream

where you might find an error like:

2017-12-09 11:53:33.304 +00:00 [Error] Microsoft.AspNetCore.Server.Kestrel: Connection id "0HL9UVDQACN2F", Request id "0HL9UVDQACN2F:00000002": An unhandled exception was thrown by the application.
System.IO.FileNotFoundException: Could not load file or assembly 'System.Net.Http.WebRequest, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. The system cannot find the file specified.
File name: 'System.Net.Http.WebRequest, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
   at Microsoft.Rest.ServiceClient`1.CreateRootHandler()

[..]

Look for places where your code might load an assembly, I found out that:

File name: 'System.Net.Http.WebRequest, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
   at Microsoft.Rest.ServiceClient`1.CreateRootHandler()
   at MyApp.MiddleLayer.Services.AzureSearch.DependencyInjection.<>c.<AddAzureSearch>b__0_1(IServiceProvider x) in C:\<Path>.Services.AzureSearch\DependencyInjection.cs:line 27

Which is where I add my Azure Search code in my app.

Either add missing assemblies, or as in my case where Azure Search SDK was referencing old assembly, enable AutoGenerateBindingRedirects as described in top of this post.


问:
Divider on Ionic lists not showing
I'm trying to replicate the sliding list as seen on the Official Docs. The list shows up but there is no divider. The docs says that the divider/border shows by default, but it is not showing.

This is the template:

```<code><ion-content padding>
 <ion-list>
  <ion-item-sliding>
    <ion-item>
      <ion-avatar item-start>
        <img src="../assets/imgs/logo.png">
      </ion-avatar>
      <h2>Slimer</h2>
    </ion-item>
    <ion-item-options side="left">
      <button ion-button color="primary">
        <ion-icon name="text"></ion-icon>
        Text
      </button>
      <button ion-button color="secondary">
        <ion-icon name="call"></ion-icon>
        Call
      </button>
    </ion-item-options>
    <ion-item-options side="right">
      <button ion-button color="primary">
        <ion-icon name="mail"></ion-icon>
        Email
      </button>
    </ion-item-options>
  </ion-item-sliding>
</ion-list>
<ion-list>
  <ion-item-sliding>
    <ion-item>
      <ion-avatar item-start>
        <img src="../assets/imgs/logo.png">
      </ion-avatar>
      <h2>Slimer</h2>
    </ion-item>
    <ion-item-options side="left">
      <button ion-button color="primary">
        <ion-icon name="text"></ion-icon>
        Text
      </button>
      <button ion-button color="secondary">
        <ion-icon name="call"></ion-icon>
        Call
      </button>
    </ion-item-options>
    <ion-item-options side="right">
      <button ion-button color="primary">
        <ion-icon name="mail"></ion-icon>
        Email
      </button>
    </ion-item-options>
  </ion-item-sliding>
</ion-list>
Hello DevApp!
</ion-content>
</code>```

This is what I get:

答:
You are using ion-list for each ion-item-sliding. May be this is a typo. All ion-item-sliding should have single parent ion-list

<ion-content padding>
      <ion-list>
         <ion-item-sliding>
          <ion-item>
            <ion-avatar item-start>

      </ion-avatar>

Slimer

    </ion-item>
    <ion-item-options side="left">
      <button ion-button color="primary">
        <ion-icon name="text"></ion-icon>
        Text
      </button>
      <button ion-button color="secondary">
        <ion-icon name="call"></ion-icon>
        Call
      </button>
    </ion-item-options>
    <ion-item-options side="right">
      <button ion-button color="primary">
        <ion-icon name="mail"></ion-icon>
        Email
      </button>
    </ion-item-options>
    </ion-item-sliding>

  <ion-item-sliding>
    <ion-item>
      <ion-avatar item-start>

      </ion-avatar>

Slimer

    </ion-item>
    <ion-item-options side="left">
      <button ion-button color="primary">
        <ion-icon name="text"></ion-icon>
        Text
      </button>
      <button ion-button color="secondary">
        <ion-icon name="call"></ion-icon>
        Call
      </button>
    </ion-item-options>
    <ion-item-options side="right">
      <button ion-button color="primary">
        <ion-icon name="mail"></ion-icon>
        Email
      </button>
    </ion-item-options>
  </ion-item-sliding>
</ion-list>
Hello DevApp!
</ion-content>```

Title: Divider on Ionic lists not showing

Body:
I'm trying to replicate the sliding list as seen on the Official Docs. The list shows up but there is no divider. The docs says that the divider/border shows by default, but it is not showing.

This is the template:

<ion-content padding>
 <ion-list>
  <ion-item-sliding>
    <ion-item>
      <ion-avatar item-start>

      </ion-avatar>

Slimer

    </ion-item>
    <ion-item-options side="left">
      <button ion-button color="primary">
        <ion-icon name="text"></ion-icon>
        Text
      </button>
      <button ion-button color="secondary">
        <ion-icon name="call"></ion-icon>
        Call
      </button>
    </ion-item-options>
    <ion-item-options side="right">
      <button ion-button color="primary">
        <ion-icon name="mail"></ion-icon>
        Email
      </button>
    </ion-item-options>
  </ion-item-sliding>
</ion-list>
<ion-list>
  <ion-item-sliding>
    <ion-item>
      <ion-avatar item-start>

      </ion-avatar>

Slimer

    </ion-item>
    <ion-item-options side="left">
      <button ion-button color="primary">
        <ion-icon name="text"></ion-icon>
        Text
      </button>
      <button ion-button color="secondary">
        <ion-icon name="call"></ion-icon>
        Call
      </button>
    </ion-item-options>
    <ion-item-options side="right">
      <button ion-button color="primary">
        <ion-icon name="mail"></ion-icon>
        Email
      </button>
    </ion-item-options>
  </ion-item-sliding>
</ion-list>
Hello DevApp!
</ion-content>

This is what I get:

Body:
You are using ion-list for each ion-item-sliding. May be this is a typo. All ion-item-sliding should have single parent ion-list

<ion-content padding>
      <ion-list>
         <ion-item-sliding>
          <ion-item>
            <ion-avatar item-start>
        <img src="../assets/imgs/logo.png">
      </ion-avatar>
      <h2>Slimer</h2>
    </ion-item>
    <ion-item-options side="left">
      <button ion-button color="primary">
        <ion-icon name="text"></ion-icon>
        Text
      </button>
      <button ion-button color="secondary">
        <ion-icon name="call"></ion-icon>
        Call
      </button>
    </ion-item-options>
    <ion-item-options side="right">
      <button ion-button color="primary">
        <ion-icon name="mail"></ion-icon>
        Email
      </button>
    </ion-item-options>
    </ion-item-sliding>
    <!-- Remove these lines -->
    <!-- </ion-list> -->
    <!-- <ion-list> -->
  <ion-item-sliding>
    <ion-item>
      <ion-avatar item-start>
        <img src="../assets/imgs/logo.png">
      </ion-avatar>
      <h2>Slimer</h2>
    </ion-item>
    <ion-item-options side="left">
      <button ion-button color="primary">
        <ion-icon name="text"></ion-icon>
        Text
      </button>
      <button ion-button color="secondary">
        <ion-icon name="call"></ion-icon>
        Call
      </button>
    </ion-item-options>
    <ion-item-options side="right">
      <button ion-button color="primary">
        <ion-icon name="mail"></ion-icon>
        Email
      </button>
    </ion-item-options>
  </ion-item-sliding>
</ion-list>
Hello DevApp!
</ion-content>


问:
How to create a new text file dynamically using BCP command
Currently What I have is:

```<code>bcp "select * from TEST.dbo.HPA_1 WITH (NOLOCK)" queryout D:\Gift_Voucher\HPA\test1.txt -T -c -t
</code>```

When I run the above code for the first time it works fine and it creates the textfile test1.txt, but When new data is added in the table I want to create new textfile something like test2.txt and test3.txt and so on without changing the code in bcp. Is there anything we can do here?

答:
Change your BAT file to replace the output file path with a command-line parameter:

```<code>bcp "select * from TEST.dbo.HPA_1 WITH (NOLOCK)" queryout "%1" -T -c -t
</code>```

In the SSIS package, create a string variable for the desired output file path.  Set the Execute Process Task Executable property to "cmd.exe". On the Expressions page, set the Arguments property to an expression that builds the command with the BAT file path plus the output file argument. The example below also encloses the values in quotes to handle whitespace in the paths:

Set the variable value to the output file path variable in your package prior to executing the task. This can be done in package code or set the value via SSIS configuration.

Note that you could accomplish the same functionality in a Data Flow task instead of shelling out to BCP. That leverages the native export capability of SSIS.

Body:
Currently What I have is:

bcp "select * from TEST.dbo.HPA_1 WITH (NOLOCK)" queryout D:\Gift_Voucher\HPA\test1.txt -T -c -t

When I run the above code for the first time it works fine and it creates the textfile test1.txt, but When new data is added in the table I want to create new textfile something like test2.txt and test3.txt and so on without changing the code in bcp. Is there anything we can do here?

Body:
Change your BAT file to replace the output file path with a command-line parameter:

bcp "select * from TEST.dbo.HPA_1 WITH (NOLOCK)" queryout "%1" -T -c -t

In the SSIS package, create a string variable for the desired output file path.  Set the Execute Process Task Executable property to "cmd.exe". On the Expressions page, set the Arguments property to an expression that builds the command with the BAT file path plus the output file argument. The example below also encloses the values in quotes to handle whitespace in the paths:

Set the variable value to the output file path variable in your package prior to executing the task. This can be done in package code or set the value via SSIS configuration.

Note that you could accomplish the same functionality in a Data Flow task instead of shelling out to BCP. That leverages the native export capability of SSIS.


问:
What does exactly mean by the term repository in git?
I'm trying to learn git.

I read few tutorials. Everywhere I got confused with the actual meaning of this term called 'Repository'.

See the below definitions :

A repository contains a directory named .git, where git keeps all of
  its metadata for the repository. The content of the .git directory are
  private to git.

So, my question is whether the directory which contains entire project (i.e. all the files of my project) along with the .git directory (usually it's hidden by default) is called the Repository of only the .git folder present within my project folder is called the Repository?

答:
I believe both are right.

In Pro Git, it says, "This leads us to the three main sections of a Git project: the Git directory, the working tree, and the staging area." There is a picture which says ".git directory (Repository)". From this we can say a repository is .git, where Git stores the metadata and object database for your project.

However, there is evidence that proves a repository includes more than .git. A Git repository can be either bare or non-bare. What is a bare repository? It is a repository that doesn’t contain a working directory. So a non-bare repository contains a working directory. Besides, let's take a look at a Git submodule. What is a submodule? A submodule is a repository embedded inside another repository. A bare repository can't be added as a submodule. And the operation to add a submodule must be in a work tree of the super project.

As to the difference between a working directory and a work tree, it's another story. There are some answers.


答: Unless you need to do something extremely fancy, there's also the :first-letter CSS selector.

Title: PHP - isolate first letter from a text


问:
Ordering and binding in for loop r
I want my for loop to store data in rows, based on the correct order as specified in the for loop, but somehow the data is bound randomly in a new dataframe.

Background information:

I have a dataframe with data from the FMCG industry, amongst this are the prices for products.

My dataframe consists of the top 3 brands of 55 different product categories

In my econometric (marketing) model I also accommodate for competition, so what I do is calculating average prices of the competition of Brand A, B and C based on conditions.

When I run the loop for one category, say category 5 (from my total dataset), I get the right averages in order and stack these, so I can bind them to my main dataframe. This main dataframe has all the brands listed from top to bottom, for every category, for every week.

THE PROBLEM: when I run the for loop, it does calculate the averages, but the final stacked dataframe to bind shuffled all the values so that they are not in order anymore.

So, I need to find a command that keeps my calculated averages in order (so average of competition Category 5 Brand A week 1 as the first row and average of Category 550 Brand C week 208 as last), as happens when I do it for one category, but not in the for loop.

The code:

```<code>##for loop for all competitor average prices accross all categories
    for(X in c("5", "24", "32", "43", "49", "56", "63", "81", "94", "96", "102", "105", "115", "122", "129", "133", "145", "154", "180", "189", "201", "210", "219", "226", "231", "245", "264", "277", "280", "301", "313", "335", "346", "361", "397", "409", "410", "411", "413", "437", "443", "480", "488", "493", "500", "516", "526", "533", "535", "536", "542", "543", "549", "550")){
  PriceX <- read.table(paste0("/Users/censored",X,".csv"), header=TRUE, sep=",")
  PriceX <- transpose(PriceX)
  PriceX <- PriceX[-c(1), ] #deleting the first column of df, contains brand names
  PriceX <- transpose(PriceX)
  PriceX <- sapply(PriceX, as.numeric)
  PriceX <- data.frame(PriceX)
  CompPriceXa <- PriceX[-c(1:2), ] #delete first and second row, contains totals and Brand A
  CompPriceXa <- CompPriceXa %>%  mutate_if(is.numeric, funs(ifelse(. == 0, NA, .))) #Make all zeros NA, otherwise the means are calculated over rows.
  CompPriceXa <- colMeans(CompPriceXa, na.rm=T) #calculate the mean of competitor prices when Brand A is focal brand
  CompPriceXa <- as.matrix(CompPriceXa)
  CompPriceXb <- PriceX[-c(1, 3), ]
   CompPriceXb <- CompPriceXb %>%  mutate_if(is.numeric, funs(ifelse(. == 0, NA, .)))
  CompPriceXb <- colMeans(CompPriceXb, na.rm=T)
  CompPriceXb <- as.matrix(CompPriceXb)
  CompPriceXc <- PriceX[-c(1, 4), ]
  CompPriceXc <- CompPriceXc %>%  mutate_if(is.numeric, funs(ifelse(. == 0, NA, .)))
  CompPriceXc <- colMeans(CompPriceXc, na.rm=T)
  CompPriceXc <- as.matrix(CompPriceXc)
  StackedCompPrice <- rbind(CompPriceXa, CompPriceXb, CompPriceXc) #stack the average competitor prices of Brand A, B and C.
  StackedCompPrice <- as.data.frame(StackedCompPrice)
  ALLStackedCompPrice <- rbind(StackedCompPrice, ALLStackedCompPrice)}

ALLStackedCompPrice <- StackedCompPrice[NULL,] #first run the for loop, then run this command outside loop to create empty df, then run the forloop again and it will be filled with all the values from all categories
</code>```

Hope you guys can help me out!

答: The whole issue is solved! It was something very simple... just reversing the for loop, so category '550' as first and '5' as last and there you go. The for loop is maybe a bit big and could be done quicker, but as long as it works it is fine, haha. Thanks for your quick responses and help! </p>

Title: Ordering and binding in for loop r

Body:
I want my for loop to store data in rows, based on the correct order as specified in the for loop, but somehow the data is bound randomly in a new dataframe.

Background information:

I have a dataframe with data from the FMCG industry, amongst this are the prices for products.

My dataframe consists of the top 3 brands of 55 different product categories

In my econometric (marketing) model I also accommodate for competition, so what I do is calculating average prices of the competition of Brand A, B and C based on conditions.

When I run the loop for one category, say category 5 (from my total dataset), I get the right averages in order and stack these, so I can bind them to my main dataframe. This main dataframe has all the brands listed from top to bottom, for every category, for every week.

THE PROBLEM: when I run the for loop, it does calculate the averages, but the final stacked dataframe to bind shuffled all the values so that they are not in order anymore.

So, I need to find a command that keeps my calculated averages in order (so average of competition Category 5 Brand A week 1 as the first row and average of Category 550 Brand C week 208 as last), as happens when I do it for one category, but not in the for loop.

The code:

##for loop for all competitor average prices accross all categories
    for(X in c("5", "24", "32", "43", "49", "56", "63", "81", "94", "96", "102", "105", "115", "122", "129", "133", "145", "154", "180", "189", "201", "210", "219", "226", "231", "245", "264", "277", "280", "301", "313", "335", "346", "361", "397", "409", "410", "411", "413", "437", "443", "480", "488", "493", "500", "516", "526", "533", "535", "536", "542", "543", "549", "550")){
  PriceX <- read.table(paste0("/Users/censored",X,".csv"), header=TRUE, sep=",")
  PriceX <- transpose(PriceX)
  PriceX <- PriceX[-c(1), ] #deleting the first column of df, contains brand names
  PriceX <- transpose(PriceX)
  PriceX <- sapply(PriceX, as.numeric)
  PriceX <- data.frame(PriceX)
  CompPriceXa <- PriceX[-c(1:2), ] #delete first and second row, contains totals and Brand A
  CompPriceXa <- CompPriceXa %>%  mutate_if(is.numeric, funs(ifelse(. == 0, NA, .))) #Make all zeros NA, otherwise the means are calculated over rows.
  CompPriceXa <- colMeans(CompPriceXa, na.rm=T) #calculate the mean of competitor prices when Brand A is focal brand
  CompPriceXa <- as.matrix(CompPriceXa)
  CompPriceXb <- PriceX[-c(1, 3), ]
   CompPriceXb <- CompPriceXb %>%  mutate_if(is.numeric, funs(ifelse(. == 0, NA, .)))
  CompPriceXb <- colMeans(CompPriceXb, na.rm=T)
  CompPriceXb <- as.matrix(CompPriceXb)
  CompPriceXc <- PriceX[-c(1, 4), ]
  CompPriceXc <- CompPriceXc %>%  mutate_if(is.numeric, funs(ifelse(. == 0, NA, .)))
  CompPriceXc <- colMeans(CompPriceXc, na.rm=T)
  CompPriceXc <- as.matrix(CompPriceXc)
  StackedCompPrice <- rbind(CompPriceXa, CompPriceXb, CompPriceXc) #stack the average competitor prices of Brand A, B and C.
  StackedCompPrice <- as.data.frame(StackedCompPrice)
  ALLStackedCompPrice <- rbind(StackedCompPrice, ALLStackedCompPrice)}

ALLStackedCompPrice <- StackedCompPrice[NULL,] #first run the for loop, then run this command outside loop to create empty df, then run the forloop again and it will be filled with all the values from all categories

Hope you guys can help me out!