问:
Get user products with using user_id in codeigniter
Hey guys I'm making a website in codeigniter and I'm trying to make the page for another user profile. On the profile of another user I want to show all the products that that user uploaded. I tried to do it like the same as you're own user profile but with that I'm using the session user_id.

This is what I have right now:

Controller function:

```<code>public function userdetails($user_id)
 {
  //load the model
  $this->load->model('User_model');

  $data['userdetail_list'] = $this->User_model->getdata($user_id);
  $data['products'] = $this->User_model->userproducts();
  $this->load->view('profiel_user',$data);

 }
</code>```

function in model:

```<code>public function userproducts($user_id)
{
    $this->db->where('user_id',$user_id);
    $query = $this->db->get('products');
    if($query->num_rows()>0)
    {
       return $query->result_array();
    }
    return array();
}
</code>```

So when I'm on a user profile page, I want to show all the products that belong to the profile user_id I clicked on.

I also have this function already to get the user_id of that profile page I'm on:

```<code>function getdata($user_id){
  $this->db->select("*");
  $this->db->from('users');
  $this->db->where('user_id', $user_id);
  $query = $this->db->get();
  return $query->result();
 }
</code>```

Anyone got model code of how I can do it?
thanks

database information:

Table 1 : products:

```<code>product_id
product_naam
product_beschrijving
user_id
ophaal_plaats
product_foto
product_foto_thumb
date_created
date_updated
category_id

table 2 : users:

user_id
email
voornaam
achternaam
beschrijving
profiel_foto
</code>```

答:
You can modify your function as below</p>

```<code>function getdata($user_id){
  $this->db->select("products.*,users.*");
  $this->db->from('products');
  $this->db->join('users','users.user_id = products.user_id','left');
  $this->db->where('users.user_id', $user_id);
  $query = $this->db->get();
  return $query->result();
 }
</code>```

Body:
Hey guys I'm making a website in codeigniter and I'm trying to make the page for another user profile. On the profile of another user I want to show all the products that that user uploaded. I tried to do it like the same as you're own user profile but with that I'm using the session user_id.

This is what I have right now:

Controller function:

public function userdetails($user_id)
 {
  //load the model
  $this->load->model('User_model');

  $data['userdetail_list'] = $this->User_model->getdata($user_id);
  $data['products'] = $this->User_model->userproducts();
  $this->load->view('profiel_user',$data);

 }

function in model:

public function userproducts($user_id)
{
    $this->db->where('user_id',$user_id);
    $query = $this->db->get('products');
    if($query->num_rows()>0)
    {
       return $query->result_array();
    }
    return array();
}

So when I'm on a user profile page, I want to show all the products that belong to the profile user_id I clicked on.

I also have this function already to get the user_id of that profile page I'm on:

function getdata($user_id){
  $this->db->select("*");
  $this->db->from('users');
  $this->db->where('user_id', $user_id);
  $query = $this->db->get();
  return $query->result();
 }

Anyone got model code of how I can do it?
thanks

database information:

Table 1 : products:

product_id
product_naam
product_beschrijving
user_id
ophaal_plaats
product_foto
product_foto_thumb
date_created
date_updated
category_id

table 2 : users:

user_id
email
voornaam
achternaam
beschrijving
profiel_foto

Body:
You can modify your function as below

function getdata($user_id){
  $this->db->select("products.*,users.*");
  $this->db->from('products');
  $this->db->join('users','users.user_id = products.user_id','left');
  $this->db->where('users.user_id', $user_id);
  $query = $this->db->get();
  return $query->result();
 }


来源: stackexchange

问:
Can not read property 'push' of undefined
I can not read property of push of undefined. Why is it undefined? When I do console.log(columnsArray[i]) it shows me the value. I don't understand.

```<code>var columnsArray = ["col1","col2","col3"];
var indexArray = [];
function submitIndex() {
  for (var i = 0; i <= columnsArray.length ; i++) {
    if ($("#" + columnsArray[i]).is(":checked") === true) {
      indexArray.push(columnsArray[i]);
    } else {
      console.log(columnsArray[i] + "is not checked");
    }
  }
  var indexArray = indexArray.filter(onlyUnique);
  console.log(indexArray);
}
</code>```

答:
Problem:

In the line:

```<code>var indexArray = indexArray.filter(onlyUnique);
</code>```

You are trying to redeclare the indexArray variable after it was already declared before the loop.

It will cause the variable to be hoisted so the first declaration before the loop will be ignored so indexArray will be undefined inside the loop .
Please take a look at Hoisting and var keyword  MDN References for further details about it.

Solution:

To fix that you need to remove var keyword in this line:

```<code>indexArray = indexArray.filter(onlyUnique);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I can not read property of push of undefined. Why is it undefined? When I do console.log(columnsArray[i]) it shows me the value. I don't understand.

var columnsArray = ["col1","col2","col3"];
var indexArray = [];
function submitIndex() {
  for (var i = 0; i <= columnsArray.length ; i++) {
    if ($("#" + columnsArray[i]).is(":checked") === true) {
      indexArray.push(columnsArray[i]);
    } else {
      console.log(columnsArray[i] + "is not checked");
    }
  }
  var indexArray = indexArray.filter(onlyUnique);
  console.log(indexArray);
}

Body:
Problem:

In the line:

var indexArray = indexArray.filter(onlyUnique);

You are trying to redeclare the indexArray variable after it was already declared before the loop.

It will cause the variable to be hoisted so the first declaration before the loop will be ignored so indexArray will be undefined inside the loop .
Please take a look at Hoisting and var keyword  MDN References for further details about it.

Solution:

To fix that you need to remove var keyword in this line:

indexArray = indexArray.filter(onlyUnique);


问:
Correctly loading a model to resume training (meta graph, ckpts)
I'm having trouble loading a model to resume training.
I'm using a simple two-layered-NN (Fully connected) on a cifar data set for practice.

NN Setup:

```<code>#full_connected_layers

import tensorflow as tf
import numpy as np

#input _-> hidden ->

def inference(data_samples, image_pixels, hidden_units, classes, reg_constant):

        with tf.variable_scope('Layer1'):
        # Define the variables
                weights = tf.get_variable(
                  name='weights',
                  shape=[image_pixels, hidden_units],
                  initializer=tf.truncated_normal_initializer(
                    stddev=1.0 / np.sqrt(float(image_pixels))),
                  regularizer=tf.contrib.layers.l2_regularizer(reg_constant)
                )

                biases = tf.Variable(tf.zeros([hidden_units]), name='biases')

                # Define the layer's output
                hidden = tf.nn.relu(tf.matmul(data_samples, weights) + biases)

        with tf.variable_scope('Layer2'):
        # Define variables
                weights = tf.get_variable('weights', [hidden_units, classes],
                  initializer=tf.truncated_normal_initializer(
                    stddev=1.0 / np.sqrt(float(hidden_units))),
                  regularizer=tf.contrib.layers.l2_regularizer(reg_constant))

                biases = tf.Variable(tf.zeros([classes]), name='biases')

        # Define the layer's output
                logits = tf.matmul(hidden, weights) + biases

        # Define summery-operation for 'logits'-variable
        tf.summary.histogram('logits', logits)

        return logits

def loss(logits, labels):
  '''Calculates the loss from logits and labels.

  Args:
    logits: Logits tensor, float - [batch size, number of classes].
    labels: Labels tensor, int64 - [batch size].

  Returns:
    loss: Loss tensor of type float.
  '''

  with tf.name_scope('Loss'):
    # Operation to determine the cross entropy between logits and labels
    cross_entropy = tf.reduce_mean(
      tf.nn.sparse_softmax_cross_entropy_with_logits(
        logits=logits, labels=labels, name='cross_entropy'))

    # Operation for the loss function
    loss = cross_entropy + tf.add_n(tf.get_collection(
      tf.GraphKeys.REGULARIZATION_LOSSES))

    # Add a scalar summary for the loss
    tf.summary.scalar('loss', loss)

  return loss

def training(loss, learning_rate):

  # Create a variable to track the global step
  global_step = tf.Variable(0, name='global_step', trainable=False)

  train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(
    loss, global_step=global_step)

  #train_step = tf.train.AdamOptimizer(learning_rate, beta1, beta2, epsilon).minimize(
    #loss, global_step=global_step)

  return train_step

def evaluation(logits, labels):

  with tf.name_scope('Accuracy'):
    # Operation comparing prediction with true label
    correct_prediction = tf.equal(tf.argmax(logits,1), labels)

    # Operation calculating the accuracy of the predictions
    accuracy =  tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

    # Summary operation for the accuracy
    tf.summary.scalar('train_accuracy', accuracy)

  return accuracy
</code>```

Saved model like this:

```<code>if (i + 1) % 500 == 0:
      saver.save(sess, MODEL_DIR, global_step=i)
      print('Saved checkpoint')
</code>```

Saved model files

Within this directory:
C:\Users\Moondra\Desktop\CIFAR - PROJECT\parameters_no_changes

I have the following files as well as model.ckpt-499.index etc:

```<code>model.ckpt-999.meta
model.ckpt-999.index
model.ckpt-999.data-00000-of-00001
</code>```

My attempt at loading the model

```<code>import numpy as np
import tensorflow as tf
import time
from datetime import datetime
import os
import data_helpers
import full_connected_layers
import itertools

learning_rate = .0001
max_steps = 3000
batch_size = 400

checkpoint = r'C:\Users\Moondra\Desktop\CIFAR - PROJECT\parameters_no_changes\model.ckpt-999'

with tf.Session() as sess:
    saver = tf.train.import_meta_graph(r'C:\Users\Moondra\Desktop\CIFAR - PROJECT' +
                                    '\\parameters_no_changes\model.ckpt-999.meta')
    saver.restore(sess, checkpoint)

data_sets = data_helpers.load_data()

images = tf.get_default_graph().get_tensor_by_name('images:0') #image placeholder
labels = tf.get_default_graph().get_tensor_by_name('image-labels:0') #placeholder
loss = tf.get_default_graph().get_tensor_by_name('Loss/add:0')
#global_step = tf.get_default_graph().get_tensor_by_name('global_step/initial_value_1:0')

train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(
    loss)

accuracy = tf.get_default_graph().get_tensor_by_name('Accuracy/Mean:0')

with tf.Session() as sess:

  #sess.run(tf.global_variables_initializer())
  zipped_data = zip(data_sets['images_train'], data_sets['labels_train'])
  batches = data_helpers.gen_batch(list(zipped_data), batch_size,
    max_steps)

  for i in range(max_steps):

    # Get next input data batch
    batch = next(batches)
    images_batch, labels_batch = zip(*batch)
    feed_dict = {
      images: images_batch,
      labels: labels_batch

       }

    if i % 100 == 0:
      train_accuracy = sess.run(accuracy, feed_dict=feed_dict)
      print('Step {:d}, training accuracy {:g}'.format(i, train_accuracy))

    ts,loss_  =sess.run([train_step, loss], feed_dict=feed_dict)
</code>```

Errors and confusion

1) Should I be using this command latest_checkpoint to restore:
`

```<code>saver.restore(sess,tf.train.latest_checkpoint('./'))`
</code>```

I see some tutorials that just point to the folder holding the
.data, .index files.

2) Which brings me to the second question:  What should I be using as the second parameter of saver.restore.
Currently I'm just pointing to the folder/dir that holds those files

3) I'm not purposely initializing any variables as I was told, that would overwrite the stored weight and bias values. This seems to be leading to this error:

FailedPreconditionError (see above for traceback): Attempting to use uninitialized value Layer1/weights
     [[Node: Layer1/weights/read = Identity[T=DT_FLOAT, _class=["loc:@Layer1/weights"], _device="/job:localhost/replica:0/task:0/cpu:0"](Layer1/weights)]]

4) However, If I do initialize all variables via this code:

sess.run(tf.global_variables_initializer())

My model seems to start training from scratch (and not resuming training)

Does that mean I'm supposed to load all weights and biases via
get_tensor explicitly? If so , how I deal with layers with 20 plus layers?

5) When I run this command

```<code>for i in tf.get_default_graph().get_operations():
    print(i.values)
</code>```

I see many global_steps tensors/operations,

```<code>'global_step/initial_value' type=Const>>
'global_step' type=VariableV2>>
<'global_step/Assign' type=Assign>>

global_step/read' type=Identity>>
</code>```

I was trying to load this variable into my current graph, but
didn't know which one I'm supposed to get using the command
get_tensor_by_name. Most of them were resulting in a does not exist error.

6) Same with loss which loss am I supposed to load into my graph with get_tensor

These are the options:

```<code><bound method Operation.values of <tf.Operation 'Loss/Const' type=Const>>
<bound method Operation.values of <tf.Operation 'Loss/Mean' type=Mean>>
<bound method Operation.values of <tf.Operation 'Loss/AddN' type=AddN>>
<bound method Operation.values of <tf.Operation 'Loss/add' type=Add>>
<bound method Operation.values of <tf.Operation 'Loss/loss/tags' type=Const>>
<bound method Operation.values of <tf.Operation 'Loss/loss' type=ScalarSummary>>
</code>```

6) Lastly, I see a lot of gradient operations when I look at all
the nodes of the graph but I don't see any nodes related to train_step (the
python variable I created that points to the Gradient Dsecent Optimizer). Does that mean I don't need to load it into this graph via get_tensor?

Thank  you.

答:
I usually did this sequence of operations:

Initialize

Restore

This translates to this kind of code:

```<code>saver = tf.train.Saver()
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    saver.restore(sess, tf.train.latest_checkpoint('./'))
    ...
</code>```

It will avoid the non-initialized error, and the restore will overwrite with the values from the checkpoint.

Body:
I'm having trouble loading a model to resume training.
I'm using a simple two-layered-NN (Fully connected) on a cifar data set for practice.

NN Setup:

#full_connected_layers

import tensorflow as tf
import numpy as np

#input _-> hidden ->

def inference(data_samples, image_pixels, hidden_units, classes, reg_constant):

        with tf.variable_scope('Layer1'):
        # Define the variables
                weights = tf.get_variable(
                  name='weights',
                  shape=[image_pixels, hidden_units],
                  initializer=tf.truncated_normal_initializer(
                    stddev=1.0 / np.sqrt(float(image_pixels))),
                  regularizer=tf.contrib.layers.l2_regularizer(reg_constant)
                )

                biases = tf.Variable(tf.zeros([hidden_units]), name='biases')

                # Define the layer's output
                hidden = tf.nn.relu(tf.matmul(data_samples, weights) + biases)

        with tf.variable_scope('Layer2'):
        # Define variables
                weights = tf.get_variable('weights', [hidden_units, classes],
                  initializer=tf.truncated_normal_initializer(
                    stddev=1.0 / np.sqrt(float(hidden_units))),
                  regularizer=tf.contrib.layers.l2_regularizer(reg_constant))

                biases = tf.Variable(tf.zeros([classes]), name='biases')

        # Define the layer's output
                logits = tf.matmul(hidden, weights) + biases

        # Define summery-operation for 'logits'-variable
        tf.summary.histogram('logits', logits)

        return logits

def loss(logits, labels):
  '''Calculates the loss from logits and labels.

  Args:
    logits: Logits tensor, float - [batch size, number of classes].
    labels: Labels tensor, int64 - [batch size].

  Returns:
    loss: Loss tensor of type float.
  '''

  with tf.name_scope('Loss'):
    # Operation to determine the cross entropy between logits and labels
    cross_entropy = tf.reduce_mean(
      tf.nn.sparse_softmax_cross_entropy_with_logits(
        logits=logits, labels=labels, name='cross_entropy'))

    # Operation for the loss function
    loss = cross_entropy + tf.add_n(tf.get_collection(
      tf.GraphKeys.REGULARIZATION_LOSSES))

    # Add a scalar summary for the loss
    tf.summary.scalar('loss', loss)

  return loss

def training(loss, learning_rate):

  # Create a variable to track the global step
  global_step = tf.Variable(0, name='global_step', trainable=False)

  train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(
    loss, global_step=global_step)

  #train_step = tf.train.AdamOptimizer(learning_rate, beta1, beta2, epsilon).minimize(
    #loss, global_step=global_step)

  return train_step

def evaluation(logits, labels):

  with tf.name_scope('Accuracy'):
    # Operation comparing prediction with true label
    correct_prediction = tf.equal(tf.argmax(logits,1), labels)

    # Operation calculating the accuracy of the predictions
    accuracy =  tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

    # Summary operation for the accuracy
    tf.summary.scalar('train_accuracy', accuracy)

  return accuracy

Saved model like this:

if (i + 1) % 500 == 0:
      saver.save(sess, MODEL_DIR, global_step=i)
      print('Saved checkpoint')

Saved model files

Within this directory:
C:\Users\Moondra\Desktop\CIFAR - PROJECT\parameters_no_changes

I have the following files as well as model.ckpt-499.index etc:

model.ckpt-999.meta
model.ckpt-999.index
model.ckpt-999.data-00000-of-00001

My attempt at loading the model

import numpy as np
import tensorflow as tf
import time
from datetime import datetime
import os
import data_helpers
import full_connected_layers
import itertools

learning_rate = .0001
max_steps = 3000
batch_size = 400

checkpoint = r'C:\Users\Moondra\Desktop\CIFAR - PROJECT\parameters_no_changes\model.ckpt-999'

with tf.Session() as sess:
    saver = tf.train.import_meta_graph(r'C:\Users\Moondra\Desktop\CIFAR - PROJECT' +
                                    '\\parameters_no_changes\model.ckpt-999.meta')
    saver.restore(sess, checkpoint)

data_sets = data_helpers.load_data()

images = tf.get_default_graph().get_tensor_by_name('images:0') #image placeholder
labels = tf.get_default_graph().get_tensor_by_name('image-labels:0') #placeholder
loss = tf.get_default_graph().get_tensor_by_name('Loss/add:0')
#global_step = tf.get_default_graph().get_tensor_by_name('global_step/initial_value_1:0')

train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(
    loss)

accuracy = tf.get_default_graph().get_tensor_by_name('Accuracy/Mean:0')

with tf.Session() as sess:

  #sess.run(tf.global_variables_initializer())
  zipped_data = zip(data_sets['images_train'], data_sets['labels_train'])
  batches = data_helpers.gen_batch(list(zipped_data), batch_size,
    max_steps)

  for i in range(max_steps):

    # Get next input data batch
    batch = next(batches)
    images_batch, labels_batch = zip(*batch)
    feed_dict = {
      images: images_batch,
      labels: labels_batch

       }

    if i % 100 == 0:
      train_accuracy = sess.run(accuracy, feed_dict=feed_dict)
      print('Step {:d}, training accuracy {:g}'.format(i, train_accuracy))

    ts,loss_  =sess.run([train_step, loss], feed_dict=feed_dict)

Errors and confusion

1) Should I be using this command latest_checkpoint to restore:
`

saver.restore(sess,tf.train.latest_checkpoint('./'))`

I see some tutorials that just point to the folder holding the
.data, .index files.

2) Which brings me to the second question:  What should I be using as the second parameter of saver.restore.
Currently I'm just pointing to the folder/dir that holds those files

3) I'm not purposely initializing any variables as I was told, that would overwrite the stored weight and bias values. This seems to be leading to this error:

FailedPreconditionError (see above for traceback): Attempting to use uninitialized value Layer1/weights
     [[Node: Layer1/weights/read = Identity[T=DT_FLOAT, _class=["loc:@Layer1/weights"], _device="/job:localhost/replica:0/task:0/cpu:0"](Layer1/weights)]]

4) However, If I do initialize all variables via this code:

sess.run(tf.global_variables_initializer())

My model seems to start training from scratch (and not resuming training)

Does that mean I'm supposed to load all weights and biases via
get_tensor explicitly? If so , how I deal with layers with 20 plus layers?

5) When I run this command

for i in tf.get_default_graph().get_operations():
    print(i.values)

I see many global_steps tensors/operations,

'global_step/initial_value' type=Const>>
'global_step' type=VariableV2>>
<'global_step/Assign' type=Assign>>

global_step/read' type=Identity>>

I was trying to load this variable into my current graph, but
didn't know which one I'm supposed to get using the command
get_tensor_by_name. Most of them were resulting in a does not exist error.

6) Same with loss which loss am I supposed to load into my graph with get_tensor

These are the options:

<bound method Operation.values of <tf.Operation 'Loss/Const' type=Const>>
<bound method Operation.values of <tf.Operation 'Loss/Mean' type=Mean>>
<bound method Operation.values of <tf.Operation 'Loss/AddN' type=AddN>>
<bound method Operation.values of <tf.Operation 'Loss/add' type=Add>>
<bound method Operation.values of <tf.Operation 'Loss/loss/tags' type=Const>>
<bound method Operation.values of <tf.Operation 'Loss/loss' type=ScalarSummary>>

6) Lastly, I see a lot of gradient operations when I look at all
the nodes of the graph but I don't see any nodes related to train_step (the
python variable I created that points to the Gradient Dsecent Optimizer). Does that mean I don't need to load it into this graph via get_tensor?

Thank  you.

Body:
I usually did this sequence of operations:

Initialize

Restore

This translates to this kind of code:

saver = tf.train.Saver()
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    saver.restore(sess, tf.train.latest_checkpoint('./'))
    ...

It will avoid the non-initialized error, and the restore will overwrite with the values from the checkpoint.


问:
Block UI thread and not display the label message
I have the following Thread method:

```<code>public void messageDelay()
{
    Thread.Sleep(5000);
}
</code>```

But when I call it, it hand the UI interface and I can not done any operation until the thread is finished.

```<code>private  void Porcessing_Click(object sender, EventArgs e)
{
    label1.Text = "start under process..";
    messageDelay();
    label1.Text = "Result";
}
</code>```

This is my main method. Any idea whats wrong I do?

答:
You can use BackgroundWorker. This class create another thread, so UI thread will not block. For example:

```<code>private  void Porcessing_Click(object sender, EventArgs e)
{
    var worker = new BackgroudWorker();
    label1.Text = "start under process..";
    worker.DoWork+=BackgroudAction;
    worker.RunWorkerCompleted+=BackgroudActionEnd;
    worker.RunWorkerAsync();
}
private void BackgroudAction(object sender, DoWorkEventArgs e)
{
    Thread.Sleep(5000);
}

private void BackgroudActionEnd( object sender,RunWorkerCompletedEventArgs e)
{
    label1.Text="Result";
}
</code>```

Body:
I have the following Thread method:

public void messageDelay()
{
    Thread.Sleep(5000);
}

But when I call it, it hand the UI interface and I can not done any operation until the thread is finished.

private  void Porcessing_Click(object sender, EventArgs e)
{
    label1.Text = "start under process..";
    messageDelay();
    label1.Text = "Result";
}

This is my main method. Any idea whats wrong I do?

Body:
You can use BackgroundWorker. This class create another thread, so UI thread will not block. For example:

private  void Porcessing_Click(object sender, EventArgs e)
{
    var worker = new BackgroudWorker();
    label1.Text = "start under process..";
    worker.DoWork+=BackgroudAction;
    worker.RunWorkerCompleted+=BackgroudActionEnd;
    worker.RunWorkerAsync();
}
private void BackgroudAction(object sender, DoWorkEventArgs e)
{
    Thread.Sleep(5000);
}

private void BackgroudActionEnd( object sender,RunWorkerCompletedEventArgs e)
{
    label1.Text="Result";
}


问:
difficulty in printing in a 5x3
this is the output i want to do :/

i uploaded an image :/ why doesnt preview

sample output:
1)AUD  6)     11)

2)     7)     12)

3)     8     13
4)     9     14
5)     10    11)PHP

hi im making a table for choices and im kinda stuck in this part(finishing touch)

```<code>#include<iostream>
#include<fstream>
#include<string>
using namespace std;

int main()
{
    const int ROW = 15;
    const int COL = 15;
    float magicArray1[ROW][COL];
    int choice1,choice2;
    float amount,result;
    //

    char currency_name[15][5] =
    {   "AUD","BRL","CAD","CNY","DKK","EUR","HKD","INR","JPY","RUR","SGD","SEK",
    "CHF","USD","PHP"

    };

    //

    cout << "Available Currencies:" << endl;
        cout << "---------------------" << endl;

    for(int j = 0; j <5; j++)
        {
        for (int i=0; i<5; i++)
            {
            cout << i+1 << ". " << currency_name[i][j] <<endl;
            }
        }
    //

    return 0;
}
</code>```

can someone point out my error :D and give me a hint :D
im kinda puzzled right now
this is all i have now

答:
```<code>#include<iostream>
#include<string>
using namespace std;

int main()
{
    string currency_name[15][5] =
    {
        "AUD","BRL","CAD","CNY","DKK","EUR","HKD","INR","JPY","RUR","SGD","SEK",
        "CHF","USD","PHP"
    };

    cout << "Available Currencies:" << endl;
    cout << "---------------------" << endl;

    for (int i=0; i<3; i++)
    {
        for( int j=0; j<5; j++)
        {
            cout << j+1 << ". " << currency_name[i][j] <<"\t";
        }
        cout<<endl;
    }
}
</code>```

yey!!! my problem is the numbering now :/

Title: difficulty in printing in a 5x3

Body:
this is the output i want to do :/

i uploaded an image :/ why doesnt preview

sample output:
1)AUD  6)     11)

2)     7)     12)

3)     8     13
4)     9     14
5)     10    11)PHP

hi im making a table for choices and im kinda stuck in this part(finishing touch)

#include<iostream>
#include<fstream>
#include<string>
using namespace std;

int main()
{
    const int ROW = 15;
    const int COL = 15;
    float magicArray1[ROW][COL];
    int choice1,choice2;
    float amount,result;
    //

    char currency_name[15][5] =
    {   "AUD","BRL","CAD","CNY","DKK","EUR","HKD","INR","JPY","RUR","SGD","SEK",
    "CHF","USD","PHP"

    };

    //

    cout << "Available Currencies:" << endl;
        cout << "---------------------" << endl;

    for(int j = 0; j <5; j++)
        {
        for (int i=0; i<5; i++)
            {
            cout << i+1 << ". " << currency_name[i][j] <<endl;
            }
        }
    //

    return 0;
}

can someone point out my error :D and give me a hint :D
im kinda puzzled right now
this is all i have now

Body:
#include<iostream>
#include<string>
using namespace std;

int main()
{
    string currency_name[15][5] =
    {
        "AUD","BRL","CAD","CNY","DKK","EUR","HKD","INR","JPY","RUR","SGD","SEK",
        "CHF","USD","PHP"
    };

    cout << "Available Currencies:" << endl;
    cout << "---------------------" << endl;

    for (int i=0; i<3; i++)
    {
        for( int j=0; j<5; j++)
        {
            cout << j+1 << ". " << currency_name[i][j] <<"\t";
        }
        cout<<endl;
    }
}

yey!!! my problem is the numbering now :/


问:
Fragments not responding to buttonclicks
I have a problem with my app. Firstly, I made two Tabs using fragments which inflates an activity. The tabs implemented is working fine. Secondly i have  displayed the XAML right. However there is not possible to interact with the buttons, but it's possible to write in the text fields. The text fields will however not respond when i try to update them with the buttons.

The activities work properly not using the fragments, any clue what I can do? Any help is greatly appreciated! Thanks

Here is my code:

MainActivity Code:

```<code>public class TabActivity : AppCompatActivity
    {
        private DrawerLayout mDrawerLayout;
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.Main);

            //Toolbar
            SupportToolbar toolbar = FindViewById<SupportToolbar>(Resource.Id.toolBar);
            SetSupportActionBar(toolbar);

            //ActionBar
            SupportActionBar actionBar = SupportActionBar;
            actionBar.SetHomeAsUpIndicator(Resource.Drawable.ic_menu);
            actionBar.SetDisplayHomeAsUpEnabled(true);
            //Drawer
            mDrawerLayout = FindViewById<DrawerLayout>(Resource.Id.drawer_layout);
            NavigationView navigationView = FindViewById<NavigationView>(Resource.Id.nav_view);
            if(navigationView != null)
            {
                setUpDrawerContent(navigationView);
            }
            //Tabs
            TabLayout tabs = FindViewById<TabLayout>(Resource.Id.tabs);

            ViewPager viewPager = FindViewById<ViewPager>(Resource.Id.viewpager);
            setUpViewPager(viewPager);

            tabs.SetupWithViewPager(viewPager);
            };
    }

    // What Actually sets my tabs
        private void setUpViewPager(ViewPager viewPager)
        {
        //====================================
            //SET THE FRAGMENTS HERE.
        //====================================
            TabAdapter adapter = new TabAdapter(SupportFragmentManager);
            adapter.AddFragment(new Fragment1(), "Inventar");
            adapter.AddFragment(new Fragment2(), "Onskeliste");

            viewPager.Adapter = adapter;
        }
        public override bool OnOptionsItemSelected(IMenuItem item)
        {
            switch (item.ItemId)
            {
                //Checks if the drawer is opened all the way up
                case Android.Resource.Id.Home:
                    mDrawerLayout.OpenDrawer((int)GravityFlags.Left);
                    return true;
                default:
                    return base.OnOptionsItemSelected(item);
            }
        }
        private void setUpDrawerContent(NavigationView navigationView)
        {
            navigationView.NavigationItemSelected += (object sender, NavigationView.NavigationItemSelectedEventArgs e) =>
            {
                e.MenuItem.SetChecked(true);
                mDrawerLayout.CloseDrawers();
            };
        }

        //===================================
        // Creating a tab adapter which inherrit from a fragment adaper, is used to adapt the viewpager and tabs together
        //===================================
        public class TabAdapter : FragmentPagerAdapter
        {

            public List<SupportFragment> Fragments { get; set; }
            public List<string> FragmentNames { get; set; }

            public TabAdapter (SupportoFragmentManager sfm) : base (sfm)
            {
                Fragments = new List<SupportFragment>();
                FragmentNames = new List<string>();
            }

            public void AddFragment(SupportFragment fragment, string name)
            {
                Fragments.Add(fragment);
                FragmentNames.Add(name);
            }

            public override int Count
            {
                get
                {
                    return Fragments.Count;
                }
            }

            //Gets the item of the fragemnt at the specific possition
            public override SupportFragment GetItem(int position)
            {
                return Fragments[position];
            }

            //Sets the title of the fragment
            public override ICharSequence GetPageTitleFormatted(int position)
            {
                return new Java.Lang.String(FragmentNames[position]);
            }
        }
    }`
</code>```

Fragment 1

```<code>public class Fragment1 : SupportFragment
    {
        public override void OnInflate(Activity activity, IAttributeSet attrs, Bundle savedInstanceState)
        {
            base.OnInflate(activity, attrs, savedInstanceState);
        }

        public override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
        }

        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            //Inflates the view under the tabs
            View view = inflater.Inflate(Resource.Layout.Inventory, container, false);

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

XML File

```<code><?xml version="1.0" encoding="utf-8"?>
    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/scroll2"
        android:padding="16dp"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#FBC855">
        <RelativeLayout
            android:id="@+id/activity_my_cellar_page"
            android:padding="16dp"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:focusable="true"
            android:focusableInTouchMode="true">
            <android.support.design.widget.TextInputLayout
                android:layout_below="@+id/signup_color"
                android:id="@+id/signup_number"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
                <EditText
                    android:id="@+id/number"
                    android:hint="Enter the amount of beer"
                    android:inputType="textCapWords"
                    android:maxLines="1"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content" />
            </android.support.design.widget.TextInputLayout>
            <LinearLayout
                android:layout_below="@+id/signup_number"
                android:id="@+id/registration"
                android:gravity="center"
                android:orientation="horizontal"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
                <Button
                    android:id="@+id/Btn_lagre"
                    android:text="Lagre"
                    android:background="#6C2334"
                    style="@style/Widget.AppCompat.Button.Colored"
                    android:layout_width="50dp"
                    android:layout_height="35dp" />
            </LinearLayout>
            <ListView
                android:id="@+id/list_data"
                android:layout_below="@+id/registration"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
            <ProgressBar
                android:layout_below="@+id/list_data"
                android:id="@+id/circularProgress"
                android:visibility="invisible"
                android:layout_centerInParent="true"
                android:theme="@style/CircularProgress"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                style="@style/Widget.AppCompat.ProgressBar" />
            <LinearLayout
                android:layout_below="@+id/circularProgress"
                android:id="@+id/mycellar_inventory3"
                android:gravity="center"
                android:orientation="horizontal"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
                <View
                    android:layout_width="50dp"
                    android:layout_height="1dp"
                    android:background="#6C2334"
                    android:layout_margin="5dp" />
                <Button
                    android:id="@+id/Btn_inventartilbake"
                    android:text="Tilbake"
                    android:background="#6C2334"
                    style="@style/Widget.AppCompat.Button.Colored"
                    android:layout_width="150dp"
                    android:layout_height="50dp" />
                <View
                    android:layout_width="50dp"
                    android:layout_height="1dp"
                    android:background="#6C2334"
                    android:layout_margin="5dp" />
            </LinearLayout>
        </RelativeLayout>
    </ScrollView>
</code>```

答:
EDIT: I assume that your XML file is for your activity.

Well you need to declare your buttens, if you want to interact with them. If the butten is in your activity, your need to declare it in your activity... otherwise, if your butten is in your fragment you need to declare it in your fragment.. in the Code below,i got a fragment where i have a butten declared in the fragments XML - inflate the fragement and afterwards i use the butten from the inflated fragment:

```<code>public class FragmentSettings : SupportFragment
{
    private Button mBtnOk;

    public FragmentSettings(Context context)
    {
        mContext = context;
    }

    public override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
    }

    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        //Inflate the fragment XML
        View view = inflater.Inflate(Resource.Layout.FragmentSettings, container, false);

        //Grab the butten from the inflated fragment
        mBtnOk = view.FindViewById<Button>(Resource.Id.mBtnOk);
        mBtnOk.Click += (object sender, EventArgs e) =>
        {
            //DO stuff
        };

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

Hope it helps - ask if there is somthing you dont understand?

Body:
I have a problem with my app. Firstly, I made two Tabs using fragments which inflates an activity. The tabs implemented is working fine. Secondly i have  displayed the XAML right. However there is not possible to interact with the buttons, but it's possible to write in the text fields. The text fields will however not respond when i try to update them with the buttons.

The activities work properly not using the fragments, any clue what I can do? Any help is greatly appreciated! Thanks

Here is my code:

MainActivity Code:

public class TabActivity : AppCompatActivity
    {
        private DrawerLayout mDrawerLayout;
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.Main);

            //Toolbar
            SupportToolbar toolbar = FindViewById<SupportToolbar>(Resource.Id.toolBar);
            SetSupportActionBar(toolbar);

            //ActionBar
            SupportActionBar actionBar = SupportActionBar;
            actionBar.SetHomeAsUpIndicator(Resource.Drawable.ic_menu);
            actionBar.SetDisplayHomeAsUpEnabled(true);
            //Drawer
            mDrawerLayout = FindViewById<DrawerLayout>(Resource.Id.drawer_layout);
            NavigationView navigationView = FindViewById<NavigationView>(Resource.Id.nav_view);
            if(navigationView != null)
            {
                setUpDrawerContent(navigationView);
            }
            //Tabs
            TabLayout tabs = FindViewById<TabLayout>(Resource.Id.tabs);

            ViewPager viewPager = FindViewById<ViewPager>(Resource.Id.viewpager);
            setUpViewPager(viewPager);

            tabs.SetupWithViewPager(viewPager);
            };
    }

    // What Actually sets my tabs
        private void setUpViewPager(ViewPager viewPager)
        {
        //====================================
            //SET THE FRAGMENTS HERE.
        //====================================
            TabAdapter adapter = new TabAdapter(SupportFragmentManager);
            adapter.AddFragment(new Fragment1(), "Inventar");
            adapter.AddFragment(new Fragment2(), "Onskeliste");

            viewPager.Adapter = adapter;
        }
        public override bool OnOptionsItemSelected(IMenuItem item)
        {
            switch (item.ItemId)
            {
                //Checks if the drawer is opened all the way up
                case Android.Resource.Id.Home:
                    mDrawerLayout.OpenDrawer((int)GravityFlags.Left);
                    return true;
                default:
                    return base.OnOptionsItemSelected(item);
            }
        }
        private void setUpDrawerContent(NavigationView navigationView)
        {
            navigationView.NavigationItemSelected += (object sender, NavigationView.NavigationItemSelectedEventArgs e) =>
            {
                e.MenuItem.SetChecked(true);
                mDrawerLayout.CloseDrawers();
            };
        }

        //===================================
        // Creating a tab adapter which inherrit from a fragment adaper, is used to adapt the viewpager and tabs together
        //===================================
        public class TabAdapter : FragmentPagerAdapter
        {

            public List<SupportFragment> Fragments { get; set; }
            public List<string> FragmentNames { get; set; }

            public TabAdapter (SupportoFragmentManager sfm) : base (sfm)
            {
                Fragments = new List<SupportFragment>();
                FragmentNames = new List<string>();
            }

            public void AddFragment(SupportFragment fragment, string name)
            {
                Fragments.Add(fragment);
                FragmentNames.Add(name);
            }

            public override int Count
            {
                get
                {
                    return Fragments.Count;
                }
            }

            //Gets the item of the fragemnt at the specific possition
            public override SupportFragment GetItem(int position)
            {
                return Fragments[position];
            }

            //Sets the title of the fragment
            public override ICharSequence GetPageTitleFormatted(int position)
            {
                return new Java.Lang.String(FragmentNames[position]);
            }
        }
    }`

Fragment 1

public class Fragment1 : SupportFragment
    {
        public override void OnInflate(Activity activity, IAttributeSet attrs, Bundle savedInstanceState)
        {
            base.OnInflate(activity, attrs, savedInstanceState);
        }

        public override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
        }

        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            //Inflates the view under the tabs
            View view = inflater.Inflate(Resource.Layout.Inventory, container, false);

            return view;
        }
    }

XML File

<?xml version="1.0" encoding="utf-8"?>
    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/scroll2"
        android:padding="16dp"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#FBC855">
        <RelativeLayout
            android:id="@+id/activity_my_cellar_page"
            android:padding="16dp"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:focusable="true"
            android:focusableInTouchMode="true">
            <android.support.design.widget.TextInputLayout
                android:layout_below="@+id/signup_color"
                android:id="@+id/signup_number"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
                <EditText
                    android:id="@+id/number"
                    android:hint="Enter the amount of beer"
                    android:inputType="textCapWords"
                    android:maxLines="1"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content" />
            </android.support.design.widget.TextInputLayout>
            <LinearLayout
                android:layout_below="@+id/signup_number"
                android:id="@+id/registration"
                android:gravity="center"
                android:orientation="horizontal"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
                <Button
                    android:id="@+id/Btn_lagre"
                    android:text="Lagre"
                    android:background="#6C2334"
                    style="@style/Widget.AppCompat.Button.Colored"
                    android:layout_width="50dp"
                    android:layout_height="35dp" />
            </LinearLayout>
            <ListView
                android:id="@+id/list_data"
                android:layout_below="@+id/registration"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
            <ProgressBar
                android:layout_below="@+id/list_data"
                android:id="@+id/circularProgress"
                android:visibility="invisible"
                android:layout_centerInParent="true"
                android:theme="@style/CircularProgress"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                style="@style/Widget.AppCompat.ProgressBar" />
            <LinearLayout
                android:layout_below="@+id/circularProgress"
                android:id="@+id/mycellar_inventory3"
                android:gravity="center"
                android:orientation="horizontal"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
                <View
                    android:layout_width="50dp"
                    android:layout_height="1dp"
                    android:background="#6C2334"
                    android:layout_margin="5dp" />
                <Button
                    android:id="@+id/Btn_inventartilbake"
                    android:text="Tilbake"
                    android:background="#6C2334"
                    style="@style/Widget.AppCompat.Button.Colored"
                    android:layout_width="150dp"
                    android:layout_height="50dp" />
                <View
                    android:layout_width="50dp"
                    android:layout_height="1dp"
                    android:background="#6C2334"
                    android:layout_margin="5dp" />
            </LinearLayout>
        </RelativeLayout>
    </ScrollView>

Body:
EDIT: I assume that your XML file is for your activity.

Well you need to declare your buttens, if you want to interact with them. If the butten is in your activity, your need to declare it in your activity... otherwise, if your butten is in your fragment you need to declare it in your fragment.. in the Code below,i got a fragment where i have a butten declared in the fragments XML - inflate the fragement and afterwards i use the butten from the inflated fragment:

public class FragmentSettings : SupportFragment
{
    private Button mBtnOk;

    public FragmentSettings(Context context)
    {
        mContext = context;
    }

    public override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
    }

    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        //Inflate the fragment XML
        View view = inflater.Inflate(Resource.Layout.FragmentSettings, container, false);

        //Grab the butten from the inflated fragment
        mBtnOk = view.FindViewById<Button>(Resource.Id.mBtnOk);
        mBtnOk.Click += (object sender, EventArgs e) =>
        {
            //DO stuff
        };

        return view;
    }
}

Hope it helps - ask if there is somthing you dont understand?


问:
Using nested objects in redux initial state and reducers
I have dashboard that have a sections which is separated by react-router.

Sections are:

Categories

Exams

Reports

Lets take a look at Exam section. we have this state as the initial state.

```<code>{
        ID: null,
        RandomizeQuestions: false,
        RandomizeAnswers: false,
        Pages: [
            {
                ID: 1,
                Title: 'Page one',
                Blocks: [
                    {
                        ID: 1,
                        Title: 'Block One',
                        Questions: [
                            {
                                ID: 1,
                                Title: "Quesiton title is here",
                                Answers: [
                                    {
                                        ID: 1,
                                        Title: "Answer 1"
                                    },
                                    {
                                        ID: 2,
                                        Title: "Answer 2"
                                    }
                                ]
                            }
                        ]
                    }
                ]
            }
        ]
    }
</code>```

I know that the state should be flatten and normalized when I use redux. but that is my exact problem. if i try to normalize my state it should be like this :

```<code>{
Exam: {
    ID: null,
    RandomizeQuestions: false,
    RandomizeAnswers: false
},
ExamPages: [
    {
        ExamId: 1,
        ID: 1,
        Title: 'Page One'
    }
],
ExamBlocks: [
    {
        ID: 1,
        Title: 'The New Block',
        Questions: []
    }
],
ExamQuestions: [],
ExamAnswers: []
}
</code>```

lets assume that its ok and I wont have problem with it. but when happen to the other sections ?

Categories have its own states which is big too and report too. ( there are other section that I didn't mention )

and then my combineReducer would be looks like this :

```<code>import {combineReducers} from 'redux'
import Exam from './redc.exams.jsx'
import ExamBlocks from './redc.blocks.jsx'

const rootReducer = combineReducers({
    Exam,
    ExamBlocks
})

export default rootReducer
</code>```

and of course I should have a reducer for every array in that object.

so my main question is how can I at lest have this structure:

```<code>const initialState = {
    Exams: {
        Blocks: [],
        Questions: [],
        Answers: []
    },
    Categories: {
        Menus: [],
        Users: []
    },
    Report: {
        MainReports: [],
        SideReports: []
    }
}
</code>```

remember that I want to have separate reducers for each of them.
a reducer for Blocks , reducer for Questions and so on...

UPDATE #1

I tried @Tom Fenech said in the answers but cannot combine reducers before final combineReducers.
right now my root reducers is looks like this:

```<code>import {combineReducers} from 'redux'

//Exams
import Exams from './ExamsReducers/redc.exams.jsx'
import Blocks from './ExamsReducers/redc.blocks.jsx'

//Categories
import Categories from './CategoriesReducers/redc.categories.jsx'

const rootReducer = combineReducers({
        Exams,
        Categories,
        Blocks,
})

export default rootReducer
</code>```

I tried with what he says and here is my code after the changes:

```<code>import {combineReducers} from 'redux'

//Exams
import Exams from './ExamsReducers/redc.exams.jsx'
import Blocks from './ExamsReducers/redc.blocks.jsx'

//Categories
import Categories from './CategoriesReducers/redc.categories.jsx'

const examRedc = combineReducers(Exams,Blocks )
const catsRedc = combineReducers(Categories)

const rootReducer = combineReducers(examRedc, catsRedc)

export default rootReducer
</code>```

i get this error :

```<code>Store does not have a valid reducer. Make sure the argument passed to combineReducers is an object whose values are reducers.
</code>```

and when i log the state in one of the components like this

```<code>var mapDispatchToProps = function (dispatch) {
    return {
        AddBlock: function () {
            dispatch(addBlock());
        }
    }
};

const mapStateToProps = function (state) {
    console.log(state); //////HERE
    return {Blocks: state.Blocks};
}

export default connect(mapStateToProps, mapDispatchToProps)(Blocks)
</code>```

I get this state which is not what I want finally.

答:
You can have nested reducer structure like</p>

```<code>// block_reducer.js
export const reducer = (state = [], action) => {
   switch (action.type) {
   case BLOCK_ACTION:
     return [{a:1}, {b:2}]
 }
  return state
}

// exam_reducer.js
import {combineReducers} from 'redux'
import {reducer as BlockReducer} from './block_reducer'

export const reducer = combineReducers({
    Blocks: BlockReducer,
    Sections: .....,
    Answers: .......
})

// root_reducer.js
import {combineReducers} from 'redux'
import {reducer as examReducers} from './exam_reducers'

export const reducer = combineReducers({
    Exams: examReducers,
    Categories: .....,
    Report: ......
})
</code>```

Body:
I have dashboard that have a sections which is separated by react-router.

Sections are:

Categories

Exams

Reports

Lets take a look at Exam section. we have this state as the initial state.

{
        ID: null,
        RandomizeQuestions: false,
        RandomizeAnswers: false,
        Pages: [
            {
                ID: 1,
                Title: 'Page one',
                Blocks: [
                    {
                        ID: 1,
                        Title: 'Block One',
                        Questions: [
                            {
                                ID: 1,
                                Title: "Quesiton title is here",
                                Answers: [
                                    {
                                        ID: 1,
                                        Title: "Answer 1"
                                    },
                                    {
                                        ID: 2,
                                        Title: "Answer 2"
                                    }
                                ]
                            }
                        ]
                    }
                ]
            }
        ]
    }

I know that the state should be flatten and normalized when I use redux. but that is my exact problem. if i try to normalize my state it should be like this :

{
Exam: {
    ID: null,
    RandomizeQuestions: false,
    RandomizeAnswers: false
},
ExamPages: [
    {
        ExamId: 1,
        ID: 1,
        Title: 'Page One'
    }
],
ExamBlocks: [
    {
        ID: 1,
        Title: 'The New Block',
        Questions: []
    }
],
ExamQuestions: [],
ExamAnswers: []
}

lets assume that its ok and I wont have problem with it. but when happen to the other sections ?

Categories have its own states which is big too and report too. ( there are other section that I didn't mention )

and then my combineReducer would be looks like this :

import {combineReducers} from 'redux'
import Exam from './redc.exams.jsx'
import ExamBlocks from './redc.blocks.jsx'

const rootReducer = combineReducers({
    Exam,
    ExamBlocks
})

export default rootReducer

and of course I should have a reducer for every array in that object.

so my main question is how can I at lest have this structure:

const initialState = {
    Exams: {
        Blocks: [],
        Questions: [],
        Answers: []
    },
    Categories: {
        Menus: [],
        Users: []
    },
    Report: {
        MainReports: [],
        SideReports: []
    }
}

remember that I want to have separate reducers for each of them.
a reducer for Blocks , reducer for Questions and so on...

UPDATE #1

I tried @Tom Fenech said in the answers but cannot combine reducers before final combineReducers.
right now my root reducers is looks like this:

import {combineReducers} from 'redux'

//Exams
import Exams from './ExamsReducers/redc.exams.jsx'
import Blocks from './ExamsReducers/redc.blocks.jsx'

//Categories
import Categories from './CategoriesReducers/redc.categories.jsx'

const rootReducer = combineReducers({
        Exams,
        Categories,
        Blocks,
})

export default rootReducer

I tried with what he says and here is my code after the changes:

import {combineReducers} from 'redux'

//Exams
import Exams from './ExamsReducers/redc.exams.jsx'
import Blocks from './ExamsReducers/redc.blocks.jsx'

//Categories
import Categories from './CategoriesReducers/redc.categories.jsx'

const examRedc = combineReducers(Exams,Blocks )
const catsRedc = combineReducers(Categories)

const rootReducer = combineReducers(examRedc, catsRedc)

export default rootReducer

i get this error :

Store does not have a valid reducer. Make sure the argument passed to combineReducers is an object whose values are reducers.

and when i log the state in one of the components like this

var mapDispatchToProps = function (dispatch) {
    return {
        AddBlock: function () {
            dispatch(addBlock());
        }
    }
};

const mapStateToProps = function (state) {
    console.log(state); //////HERE
    return {Blocks: state.Blocks};
}

export default connect(mapStateToProps, mapDispatchToProps)(Blocks)

I get this state which is not what I want finally.

Body:
You can have nested reducer structure like

// block_reducer.js
export const reducer = (state = [], action) => {
   switch (action.type) {
   case BLOCK_ACTION:
     return [{a:1}, {b:2}]
 }
  return state
}

// exam_reducer.js
import {combineReducers} from 'redux'
import {reducer as BlockReducer} from './block_reducer'

export const reducer = combineReducers({
    Blocks: BlockReducer,
    Sections: .....,
    Answers: .......
})

// root_reducer.js
import {combineReducers} from 'redux'
import {reducer as examReducers} from './exam_reducers'

export const reducer = combineReducers({
    Exams: examReducers,
    Categories: .....,
    Report: ......
})


问:
jxbrowser WARNING: Could not open/create prefs root node Software\JavaSoft\Prefs
I am a new JxBrowser user who is experimenting with replacing the UI in a portion of an existing Swing application with modern web-based UI technology.  I am able to get a basic "Hello World" message display in a window within this application.  All looks fine, except that I notice this message on the console:

```<code>Nov 14, 2017 4:24:34 PM java.util.prefs.WindowsPreferences <init>
WARNING: Could not open/create prefs root node Software\JavaSoft\Prefs at root 0x80000002. Windows RegCreateKeyEx(...) returned error code 5.
-- Product name: JxBrowser
-- Licensed version: 6.x
-- Licensed to:
-- License type: Evaluation
-- Generation date: Nov 14, 2017
-- Expiration date: Dec 14, 2017
-- License info: Single-user license
-- Current date: Nov 14, 2017
JxBrowser license valid.
</code>```

I am asking about the first 2 lines, and specifically whether they indicate some sort of problem with JxBrowser, or whether I can ignore them.

I searched the web for this problem, and found this, which I bet is related: https://bugs.openjdk.java.net/browse/JDK-8139507

I am on Windows 7 64-bit.  "java -version" says the following.  This is a 32-bit version of Java.

```<code>> java -version
java version "1.8.0_144"
Java(TM) SE Runtime Environment (build 1.8.0_144-b01)
Java HotSpot(TM) Client VM (build 25.144-b01, mixed mode)
</code>```

答: You can safely ignore this warning. Such warnings are usually reproducible when UAC does not allow Java to access this registry node, but JxBrowser will work properly even without having access to it.  </p>

Body:
I am a new JxBrowser user who is experimenting with replacing the UI in a portion of an existing Swing application with modern web-based UI technology.  I am able to get a basic "Hello World" message display in a window within this application.  All looks fine, except that I notice this message on the console:

Nov 14, 2017 4:24:34 PM java.util.prefs.WindowsPreferences <init>
WARNING: Could not open/create prefs root node Software\JavaSoft\Prefs at root 0x80000002. Windows RegCreateKeyEx(...) returned error code 5.
-- Product name: JxBrowser
-- Licensed version: 6.x
-- Licensed to:
-- License type: Evaluation
-- Generation date: Nov 14, 2017
-- Expiration date: Dec 14, 2017
-- License info: Single-user license
-- Current date: Nov 14, 2017
JxBrowser license valid.

I am asking about the first 2 lines, and specifically whether they indicate some sort of problem with JxBrowser, or whether I can ignore them.

I searched the web for this problem, and found this, which I bet is related: https://bugs.openjdk.java.net/browse/JDK-8139507

I am on Windows 7 64-bit.  "java -version" says the following.  This is a 32-bit version of Java.

> java -version
java version "1.8.0_144"
Java(TM) SE Runtime Environment (build 1.8.0_144-b01)
Java HotSpot(TM) Client VM (build 25.144-b01, mixed mode)


问:
Given an input array find all subarrays with given sum K
Given an input array we can find a single sub-array which sums to K (given) in linear time, by keeping track of sum found so far and the start position. If the current sum becomes greater than the K we keep removing elements from start position until we get current sum <= K.

I found sample code from geeksforgeeks and updated it to return all such possible sets. But the assumption is that the input array consists of only +ve numbers.

```<code>bool subArraySum(int arr[], int n, int sum)
{
    int curr_sum = 0, start = 0, i;
    bool found = false;

    for (i = 0; i <= n; i++)
    {
        while (curr_sum > sum && start < i)
        {
            curr_sum = curr_sum - arr[start];
            start++;
        }

        if (curr_sum == sum)
        {
            cout<<"Sum found in b/w indices: "<<start<<" & "<<(i-1)<<"\n";
            curr_sum -= arr[start];
            start++;
            found = true;
        }

        // Add this element to curr_sum
        if (i < n) {
          curr_sum = curr_sum + arr[i];
        }
    }

    return found;
}
</code>```

My question is do we have such a solution for mixed set of numbers too (both positive and negative numbers)?

答:
Solution as given by @Evgeny Kluev coded in c++ </p>

```<code>#include<bits/stdc++.h>
using namespace std;
int c=0;
// Function to print subarray with sum as given sum
void subArraySum(int arr[], int n, int k)
{
   map<int,vector<int>>m1;
   m1[0].push_back(-1);
   int curr_sum=0;
   for(int i=0;i<n;i++){
       curr_sum=curr_sum+arr[i];
       if(m1.find(curr_sum-k)!=m1.end()){
           vector<int>a=m1[curr_sum-k];
           c+=m1[curr_sum-k].size();
           for(int j=0;j<a.size();j++){  // printing all indexes with sum=k
              cout<<a[j]+1<<" "<<i<<endl;
            }
        }
        m1[curr_sum].push_back(i);
    }
 }
int main()
{
   int arr[] =  {10,2,0,10,0,10};
   int n = sizeof(arr)/sizeof(arr[0]);
   int sum = 10;
   subArraySum(arr, n, sum);
   cout<<c<<endl; //count of subarrays with given sum
   return 0;
}
</code>```

Body:
Given an input array we can find a single sub-array which sums to K (given) in linear time, by keeping track of sum found so far and the start position. If the current sum becomes greater than the K we keep removing elements from start position until we get current sum <= K.

I found sample code from geeksforgeeks and updated it to return all such possible sets. But the assumption is that the input array consists of only +ve numbers.

bool subArraySum(int arr[], int n, int sum)
{
    int curr_sum = 0, start = 0, i;
    bool found = false;

    for (i = 0; i <= n; i++)
    {
        while (curr_sum > sum && start < i)
        {
            curr_sum = curr_sum - arr[start];
            start++;
        }

        if (curr_sum == sum)
        {
            cout<<"Sum found in b/w indices: "<<start<<" & "<<(i-1)<<"\n";
            curr_sum -= arr[start];
            start++;
            found = true;
        }

        // Add this element to curr_sum
        if (i < n) {
          curr_sum = curr_sum + arr[i];
        }
    }

    return found;
}

My question is do we have such a solution for mixed set of numbers too (both positive and negative numbers)?

Body:
Solution as given by @Evgeny Kluev coded in c++

#include<bits/stdc++.h>
using namespace std;
int c=0;
// Function to print subarray with sum as given sum
void subArraySum(int arr[], int n, int k)
{
   map<int,vector<int>>m1;
   m1[0].push_back(-1);
   int curr_sum=0;
   for(int i=0;i<n;i++){
       curr_sum=curr_sum+arr[i];
       if(m1.find(curr_sum-k)!=m1.end()){
           vector<int>a=m1[curr_sum-k];
           c+=m1[curr_sum-k].size();
           for(int j=0;j<a.size();j++){  // printing all indexes with sum=k
              cout<<a[j]+1<<" "<<i<<endl;
            }
        }
        m1[curr_sum].push_back(i);
    }
 }
int main()
{
   int arr[] =  {10,2,0,10,0,10};
   int n = sizeof(arr)/sizeof(arr[0]);
   int sum = 10;
   subArraySum(arr, n, sum);
   cout<<c<<endl; //count of subarrays with given sum
   return 0;
}


问:
how to correct auto-complete div which is rolling behind an input tag

auto-complete div is linked with the first input but the div is rolling behind the second input.how do i correct the problem ?

```<code>#suggesstion_box{
    position: absolute;
    left: 163px;
    top: 25px;
    border: 1px solid #222;
    width: 164px;
    background-color: white;
    cursor: default;
}
</code>```

this is the css

答:
Give z-index to #suggesstion_box</p>

```<code>#suggesstion_box{
z-index:9;
position: absolute;
    left: 163px;
    top: 25px;
    border: 1px solid #222;
    width: 164px;
    background-color: white;
    cursor: default;
}
</code>```

Body:
auto-complete div is linked with the first input but the div is rolling behind the second input.how do i correct the problem ?

#suggesstion_box{
    position: absolute;
    left: 163px;
    top: 25px;
    border: 1px solid #222;
    width: 164px;
    background-color: white;
    cursor: default;
}

this is the css

Body:
Give z-index to #suggesstion_box

#suggesstion_box{
z-index:9;
position: absolute;
    left: 163px;
    top: 25px;
    border: 1px solid #222;
    width: 164px;
    background-color: white;
    cursor: default;
}


问:
Getting "type or namespace name could not be found" but everything seems ok?
I'm getting a:

type or namespace name could not be found

error for a C# WPF app in VS2010. This area of code was compiling fine, but suddenly I'm getting this error. I've tried removing the Project Reference and the using statement, shutting VS2010 and restarting, but still I have this issue.

Any ideas why this might be occurring, where it seems like I'm doing the right thing re Reference & using statement?

I also noted in VS2010 that intellisense for that namespace is working ok, so it seems like VS2010 has the project reference and is seeing the namespace on one hand, but during compile doesn't see it?

答: Remove the assembly from GAC(C:\WINDOWS\assembly folder - select your assebly and right click and uninstall). because solution keeps refference using guid and if that guid is in GAC, it will keep taking GAC version for compilation.</p>

ContentLicense: CC BY-SA 4.0


问:
nul byte character in Rcpp function
I'm looking for a way of comparing short strings for overlap.

I thought I might find a reasonable method using the stringdist package using the lcs method, but it appears to be doing something different.

The accepted answer to this C-tagged stackoverflow question:

Detecting length of overlap between two strings

```<code>int overlap(const char *s1, const char *s2){
    int i = 0;
    while (*s1 != '\0' && *s2 != '\0') {
        if (*s1++ == *s2++) i++;
    }
    return i;
}
</code>```

involves using nul byte character to represent empty strings.

How could I translate this into something that works in Rcpp? When I try wrapping it up in cppFunction, I get an error saying that this character is not allowed.

答:
This is because when you use cppFunction to define your C++ functions, you need to escape the \, i.e. if you want to have \0 in the C++ code, you need to write \\0 in the string you give to cppFunction:

```<code>Rcpp::cppFunction( "
int overlap(const char* s1, const char* s2){

  int i = 0;
  while (*s1 != '\\0' && *s2 != '\\0') {
    if (*s1++ == *s2++) i++;
  }
  return i;

}")
</code>```

Which gives you:

```<code>> overlap( "foo", "foooo")
[1] 3
</code>```

Note that you don't need that if you put your function in a .cpp file, which is what is recommended:

```<code>#include <Rcpp.h>
using namespace Rcpp ;

// [[Rcpp::export]]
int overlap(const char* s1, const char* s2 ){

  int i = 0;
  while (*s1 != '\0' && *s2 != '\0') {
    if (*s1++ == *s2++) i++;
  }
  return i;
}
</code>```

Title: nul byte character in Rcpp function

Body:
I'm looking for a way of comparing short strings for overlap.

I thought I might find a reasonable method using the stringdist package using the lcs method, but it appears to be doing something different.

The accepted answer to this C-tagged stackoverflow question:

Detecting length of overlap between two strings

int overlap(const char *s1, const char *s2){
    int i = 0;
    while (*s1 != '\0' && *s2 != '\0') {
        if (*s1++ == *s2++) i++;
    }
    return i;
}

involves using nul byte character to represent empty strings.

How could I translate this into something that works in Rcpp? When I try wrapping it up in cppFunction, I get an error saying that this character is not allowed.

Body:
This is because when you use cppFunction to define your C++ functions, you need to escape the \, i.e. if you want to have \0 in the C++ code, you need to write \\0 in the string you give to cppFunction:

Rcpp::cppFunction( "
int overlap(const char* s1, const char* s2){

  int i = 0;
  while (*s1 != '\\0' && *s2 != '\\0') {
    if (*s1++ == *s2++) i++;
  }
  return i;

}")

Which gives you:

> overlap( "foo", "foooo")
[1] 3

Note that you don't need that if you put your function in a .cpp file, which is what is recommended:

#include <Rcpp.h>
using namespace Rcpp ;

// [[Rcpp::export]]
int overlap(const char* s1, const char* s2 ){

  int i = 0;
  while (*s1 != '\0' && *s2 != '\0') {
    if (*s1++ == *s2++) i++;
  }
  return i;
}


问:
Elasticsearch sorting by array column
How to sort records by column with array of numbers?
For example:

```<code>[1, 32, 26, 16]
[1, 32, 10, 1500]
[1, 32, 1,  16]
[1, 32, 2,  17]
</code>```

The result that is to be expected:

```<code>[1, 32, 1,  16]
[1, 32, 2,  17]
[1, 32, 10, 1500]
[1, 32, 26, 16]
</code>```

Elasticsearch has sort mode option: https://www.elastic.co/guide/en/elasticsearch/reference/1.4/search-request-sort.html#_sort_mode_option. But no one variant is not appropriated.

Language Ruby can sort arrays of numbers' array, ruby has method Array.<=>, which description says "Each object in each array is compared"

How to do the same with elasticsearch?

P.S. Sorry for my English

答:
In ElasticSearch arrays of objects do not work as you would expect:

Arrays of objects do not work as you would expect: you cannot query
  each object independently of the other objects in the array. If you
  need to be able to do this then you should use the nested datatype
  instead of the object datatype.

This is explained in more detail in Nested datatype.

It is not possible to access array elements at sort time by their indices since they are stored in a Lucene index, which allows basically only set operations ("give docs that have array element = x" or "give docs that do not have array element = x").

However, by default the initial JSON document inserted into the index is stored on the disk and is available for scripting access in the field _source.

You have two options:

use script based sorting

store value for sorting explicitly as string

Let's discuss these options in a bit more detail.

1. Script based sorting

The first option is more like a hack. Let's assume you have a mapping like this:

```<code>PUT my_index
{
  "mappings": {
    "my_type": {
      "properties": {
        "my_array": {
          "type": "integer"
        }
      }
    }
  }
}
</code>```

Then you can achieve intended behavior with a scripted sort:

```<code>POST my_index/my_type/_search
{
      "sort" : {
        "_script" : {
            "script" : "String s = ''; for(int i = 0; i < params._source.my_array.length; ++i) {s += params._source.my_array[i] + ','}  s",
            "type" : "string",
            "order" : "asc"
        }
    }
}
</code>```

(I tested the code on ElasticSearch 5.4, I believe there should be something equivalent for the earlier versions. Please consult relevant documentation in the case you need info for earlier versions, like for 1.4.)

The output will be:

```<code>  "hits": {
    "total": 2,
    "max_score": null,
    "hits": [
      {
        "_index": "my_index",
        "_type": "my_type",
        "_id": "2",
        "_score": null,
        "_source": {
          "my_array": [
            1,
            32,
            1,
            16
          ]
        },
        "sort": [
          "1,32,1,16,"
        ]
      },
      {
        "_index": "my_index",
        "_type": "my_type",
        "_id": "1",
        "_score": null,
        "_source": {
          "my_array": [
            1,
            32,
            10,
            1500
          ]
        },
        "sort": [
          "1,32,10,1500,"
        ]
      }
    ]   }
</code>```

Note that this solution will be slow and memory consuming since it will have to read _source for all documents under sort from disk and to load them into memory.

2. Denormalization

Storing the value for sorting explicitly as string is more like ElasticSearch approach, which favors denormalization. Here the idea would be to do the concatenation before inserting the document into the index and use robust sorting by a string field.

Please select the solution more appropriate for your needs.

Hope that helps!

Title: Elasticsearch sorting by array column

Body:
How to sort records by column with array of numbers?
For example:

[1, 32, 26, 16]
[1, 32, 10, 1500]
[1, 32, 1,  16]
[1, 32, 2,  17]

The result that is to be expected:

[1, 32, 1,  16]
[1, 32, 2,  17]
[1, 32, 10, 1500]
[1, 32, 26, 16]

Elasticsearch has sort mode option: https://www.elastic.co/guide/en/elasticsearch/reference/1.4/search-request-sort.html#_sort_mode_option. But no one variant is not appropriated.

Language Ruby can sort arrays of numbers' array, ruby has method Array.<=>, which description says "Each object in each array is compared"

How to do the same with elasticsearch?

P.S. Sorry for my English

Body:
In ElasticSearch arrays of objects do not work as you would expect:

Arrays of objects do not work as you would expect: you cannot query
  each object independently of the other objects in the array. If you
  need to be able to do this then you should use the nested datatype
  instead of the object datatype.

This is explained in more detail in Nested datatype.

It is not possible to access array elements at sort time by their indices since they are stored in a Lucene index, which allows basically only set operations ("give docs that have array element = x" or "give docs that do not have array element = x").

However, by default the initial JSON document inserted into the index is stored on the disk and is available for scripting access in the field _source.

You have two options:

use script based sorting

store value for sorting explicitly as string

Let's discuss these options in a bit more detail.

1. Script based sorting

The first option is more like a hack. Let's assume you have a mapping like this:

PUT my_index
{
  "mappings": {
    "my_type": {
      "properties": {
        "my_array": {
          "type": "integer"
        }
      }
    }
  }
}

Then you can achieve intended behavior with a scripted sort:

POST my_index/my_type/_search
{
      "sort" : {
        "_script" : {
            "script" : "String s = ''; for(int i = 0; i < params._source.my_array.length; ++i) {s += params._source.my_array[i] + ','}  s",
            "type" : "string",
            "order" : "asc"
        }
    }
}

(I tested the code on ElasticSearch 5.4, I believe there should be something equivalent for the earlier versions. Please consult relevant documentation in the case you need info for earlier versions, like for 1.4.)

The output will be:

  "hits": {
    "total": 2,
    "max_score": null,
    "hits": [
      {
        "_index": "my_index",
        "_type": "my_type",
        "_id": "2",
        "_score": null,
        "_source": {
          "my_array": [
            1,
            32,
            1,
            16
          ]
        },
        "sort": [
          "1,32,1,16,"
        ]
      },
      {
        "_index": "my_index",
        "_type": "my_type",
        "_id": "1",
        "_score": null,
        "_source": {
          "my_array": [
            1,
            32,
            10,
            1500
          ]
        },
        "sort": [
          "1,32,10,1500,"
        ]
      }
    ]   }

Note that this solution will be slow and memory consuming since it will have to read _source for all documents under sort from disk and to load them into memory.

2. Denormalization

Storing the value for sorting explicitly as string is more like ElasticSearch approach, which favors denormalization. Here the idea would be to do the concatenation before inserting the document into the index and use robust sorting by a string field.

Please select the solution more appropriate for your needs.

Hope that helps!


问:
Laravel Mail: Too few arguments to function Swift_Transport_EsmtpTransport::__construct()
When I try to send mails via Laravel Mail class, I get the following error:

Symfony \ Component \ Debug \ Exception \ FatalThrowableError

(E_RECOVERABLE_ERROR) Type error: Too few arguments to function
Swift_Transport_EsmtpTransport::__construct(), 0 passed in
/[...]/CustomerCenter/database/factories/vendor/swiftmailer/swiftmailer/lib/classes/Swift/SmtpTransport.php
on line 37 and at least 3 expected

I have created a mail class using php artisan make:mail Contact, created the blade view 'contact' in the directory mails and created a controller, called in web.php route file.

The Contact class looks like this:

```<code>namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;

class Contact extends Mailable {
    use Queueable, SerializesModels;

    /**
     * Create a new message instance.
     *
     */
    public function __construct() {
        //
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build() {
        return $this->view('emails.contact');
    }
}
</code>```

This is my email configuration - used Config::get('mail')

```<code>array:9 [▼
  "driver" => "smtp"
  "host" => "xxx.kasserver.com"
  "port" => "25"
  "from" => array:2 [▼
    "address" => "mail@example.com"
    "name" => "Example"
  ]
  "encryption" => null
  "username" => "xxx"
  "password" => "***"
  "sendmail" => "/usr/sbin/sendmail -bs"
  "markdown" => array:2 [▼
    "theme" => "default"
    "paths" => array:1 [▼
      0 => "/[...]/resources/views/vendor/mail"
]
  ]
]
</code>```

In the Controller file I call the Mail class this way:

```<code>\Mail::to('mail@example.com')->send( new Contact );
</code>```

I already checked those questions:

Too few arguments to function Db::__construct(), 0 passed in

Laravel: Too few arguments to function Illuminate\Support\Manager::createDriver()

I already executed:

php artisan config:clear

php artisan vendor:publish

I'm confused, I did the same a explained in this tutorial video:
https://laracasts.com/series/laravel-from-scratch-2017/episodes/26

答:
Ok, for some reason the include path was:
database/factories/vendor/swiftmailer
but it should have been vendor/swiftmailer.

I did not realize that. I guess my FTP sync program copied all the vendor stuff to database/factories. Deleting the stuff made laravel to throw an exception of the missing file. So now I knew what to do:

A simple

composer dump-autoload

fixed the problem...

Body:
When I try to send mails via Laravel Mail class, I get the following error:

Symfony \ Component \ Debug \ Exception \ FatalThrowableError

(E_RECOVERABLE_ERROR) Type error: Too few arguments to function
Swift_Transport_EsmtpTransport::__construct(), 0 passed in
/[...]/CustomerCenter/database/factories/vendor/swiftmailer/swiftmailer/lib/classes/Swift/SmtpTransport.php
on line 37 and at least 3 expected

I have created a mail class using php artisan make:mail Contact, created the blade view 'contact' in the directory mails and created a controller, called in web.php route file.

The Contact class looks like this:

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;

class Contact extends Mailable {
    use Queueable, SerializesModels;

    /**
     * Create a new message instance.
     *
     */
    public function __construct() {
        //
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build() {
        return $this->view('emails.contact');
    }
}

This is my email configuration - used Config::get('mail')

array:9 [▼
  "driver" => "smtp"
  "host" => "xxx.kasserver.com"
  "port" => "25"
  "from" => array:2 [▼
    "address" => "mail@example.com"
    "name" => "Example"
  ]
  "encryption" => null
  "username" => "xxx"
  "password" => "***"
  "sendmail" => "/usr/sbin/sendmail -bs"
  "markdown" => array:2 [▼
    "theme" => "default"
    "paths" => array:1 [▼
      0 => "/[...]/resources/views/vendor/mail"
]
  ]
]

In the Controller file I call the Mail class this way:

\Mail::to('mail@example.com')->send( new Contact );

I already checked those questions:

Too few arguments to function Db::__construct(), 0 passed in

Laravel: Too few arguments to function Illuminate\Support\Manager::createDriver()

I already executed:

php artisan config:clear

php artisan vendor:publish

I'm confused, I did the same a explained in this tutorial video:
https://laracasts.com/series/laravel-from-scratch-2017/episodes/26


问:
How change tableview section header size dynamically in ios 11 using swift 4?
i am creating an expandable tableview. i have added section and row for every section. created a xib file for styling sections and it works right in iphone 5s.but when i switch to iphone 8s my sections remain size of iphone 5s and width don't change to tableview. i have set constraint and some of my codes are as below:

```<code>override func viewDidLoad() {
    super.viewDidLoad()
            self.homeMenuTableView.backgroundColor = UIColor(red: 0.0196, green: 0.1059, blue: 0.1647, alpha: 1.0)
            let px = 1 / UIScreen.main.scale
            let frame = CGRect(x:0,y:0,width: self.homeMenuTableView.frame.size.width,height: px)
            let line = UIView(frame: frame)
            self.homeMenuTableView.tableHeaderView = line
            line.backgroundColor = self.homeMenuTableView.separatorColor
            homeMenuTableView.tableFooterView = UIView()
            homeMenuTableView.dataSource=self
            homeMenuTableView.delegate=self
}

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 44
}

   func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let header = ExpandableHeaderView()
    header.customInit(title: sections[section].menuCellLabel, section: section, delegate: self)
    return header
}

func customInit(title: String, section: Int, delegate: ExpandableHeaderViewDelegate) {
    let cell = Bundle.main.loadNibNamed("MenuTableViewCell", owner: self, options: nil)?.first as! MenuTableViewCell
            let menucell = DataService.instance.getMenuCells()[section]
            cell.updateViews(menuCell: menucell)
    self.addSubview(cell)
    self.section = section
    self.delegate = delegate
}
</code>```

答:
You are loading cell from xib but you are not assigning frame to it. due to which it takes width of cell in XIB   </p>

```<code>func customInit(title: String, section: Int, delegate: ExpandableHeaderViewDelegate) {
        let cell = Bundle.main.loadNibNamed("MenuTableViewCell", owner: self, options: nil)?.first as! MenuTableViewCell
                let menucell = DataService.instance.getMenuCells()[section]
                cell.updateViews(menuCell: menucell)
    //Add this line in your code width issue will resolve
    cell.frame.size.width = tableView.frame.width

        self.addSubview(cell)
        self.section = section
        self.delegate = delegate
    }
</code>```

Body:
i am creating an expandable tableview. i have added section and row for every section. created a xib file for styling sections and it works right in iphone 5s.but when i switch to iphone 8s my sections remain size of iphone 5s and width don't change to tableview. i have set constraint and some of my codes are as below:

override func viewDidLoad() {
    super.viewDidLoad()
            self.homeMenuTableView.backgroundColor = UIColor(red: 0.0196, green: 0.1059, blue: 0.1647, alpha: 1.0)
            let px = 1 / UIScreen.main.scale
            let frame = CGRect(x:0,y:0,width: self.homeMenuTableView.frame.size.width,height: px)
            let line = UIView(frame: frame)
            self.homeMenuTableView.tableHeaderView = line
            line.backgroundColor = self.homeMenuTableView.separatorColor
            homeMenuTableView.tableFooterView = UIView()
            homeMenuTableView.dataSource=self
            homeMenuTableView.delegate=self
}

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 44
}

   func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let header = ExpandableHeaderView()
    header.customInit(title: sections[section].menuCellLabel, section: section, delegate: self)
    return header
}

func customInit(title: String, section: Int, delegate: ExpandableHeaderViewDelegate) {
    let cell = Bundle.main.loadNibNamed("MenuTableViewCell", owner: self, options: nil)?.first as! MenuTableViewCell
            let menucell = DataService.instance.getMenuCells()[section]
            cell.updateViews(menuCell: menucell)
    self.addSubview(cell)
    self.section = section
    self.delegate = delegate
}

Body:
You are loading cell from xib but you are not assigning frame to it. due to which it takes width of cell in XIB

func customInit(title: String, section: Int, delegate: ExpandableHeaderViewDelegate) {
        let cell = Bundle.main.loadNibNamed("MenuTableViewCell", owner: self, options: nil)?.first as! MenuTableViewCell
                let menucell = DataService.instance.getMenuCells()[section]
                cell.updateViews(menuCell: menucell)
    //Add this line in your code width issue will resolve
    cell.frame.size.width = tableView.frame.width

        self.addSubview(cell)
        self.section = section
        self.delegate = delegate
    }


问:
JQuery cycle plugin code with SharePoint
I'm trying to replicate this functionality in SharePoint 2010. I've added "Content Editor" web part and modifying the source html. However, I'm not getting the desire result, something I'm missing in the code . My output is coming something like ,

Here is my code,

```<code>    <IMG ID="slideshowPicturePlaceholder" src="/_layouts/images/GEARS_AN.GIF" style="display:none"/>
<center><div id="slideshowContentArea" style="display:none"> </div></center>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

<script type="text/javascript" src="http://malsup.github.com/chili-1.7.pack.js"></script>

<script type="text/javascript" src="http://cloud.github.com/downloads/malsup/cycle/jquery.cycle.all.2.72.js"></script>

<script>
 function GetAllImages()
{
$("#slideshowPicturePlaceholder").css("display", "block");
var soapEnv = "<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'><soapenv:Body><GetListItems xmlns='http://schemas.microsoft.com/sharepoint/soap/'>";
    //The name of the image library is called 'SlideShow'. Replace the name bewlo with the name of your image library
 soapEnv += "<listName>SlideShow</listName>";
    soapEnv += "<query><Query><OrderBy Override='TRUE'><FieldRef Name='Created' Ascending='FALSE' /></OrderBy></Query></query>";
    soapEnv += "<viewFields><ViewFields><FieldRef Name='Title'/><FieldRef Name='ows_FileLeafRef'/></ViewFields></viewFields><rowLimit></rowLimit>";
    soapEnv += "</GetListItems></soapenv:Body></soapenv:Envelope>";

var port = window.location.port;
if (port.length <= 0)
 port = "";
else
 port = ":"+port;
var webservice = window.location.protocol+"//"+window.location.hostname+port+L_Menu_BaseUrl+"/_vti_bin/lists.asmx";

    $.ajax({
        url: webservice,
        type: "POST",
        dataType: "xml",
        data: soapEnv,
        complete: processQueryResults,
        contentType: "text/xml; charset=utf-8",
         error: function(xhr) {
        alert('Error!  Status = ' + xhr.status);}
    });
}

function processQueryResults(xData, status)
{
var port = window.location.port;
if (port.length <= 0)
 port = "";
else
 port = ":"+port;
//Change the below to point to your image library
var imageURL = window.location.protocol+"//"+window.location.hostname+port+L_Menu_BaseUrl+"/SlideShow/";
var itemURL = window.location.protocol+"//"+window.location.hostname+port+L_Menu_BaseUrl+"/SlideShow/Forms/DispForm.aspx?ID=";

$("#slideshowContentArea").html("")
$("#slideshowContentArea").html("<table cellspacing='20'><tr><td>")
$("#slideshowContentArea").html("<div class='nav'><a id='prev href='#'>Prev</a><a id='next' href='#'>Next</a></div>")

$(xData.responseXML).find("z\\:row").each(function() {
  var title = $(this).attr("ows_Title");
  var imageLink = imageURL+$(this).attr("ows_FileLeafRef").substring($(this).attr("ows_FileLeafRef").indexOf('#')+1);
  var itemLink = itemURL+$(this).attr("ows_ID");
  var Html ="<div style='padding: 10px;border:1px solid #ccc;background-color:#eee;width:270px;height: 270px;top:0;left: 0;'><a target='_blank' border='0' href='"+itemLink+"'><img width='250' height='250'  src='"+ imageLink +"'/></a><p align='center'></p></div>```$('#slideshow').cycle({fx:'scrollHorz',prev:'#prev',next:'#next',after:onAfter,timeout:0});```</td></tr></table>";

        $("#slideshowContentArea").append(Html);
    });

$("#slideshowPicturePlaceholder").css("display", "none");
$("#slideshowContentArea").css("display", "block");

}

GetAllImages();
</script>
</code>```

Where am I missing ?

答:
Try this:</p>

```<code><IMG ID="slideshowPicturePlaceholder" src="/_layouts/images/GEARS_AN.GIF" style="display:none"/>
<center><div id="slideshowContentArea" style="display:none; width:255px;">
    <div class='nav'><a id='prev' href='#'>Prev</a><a id='next' href='#'>Next</a></div>
    <div id="slideshow" class="pics" style="position: relative; overflow-x: hidden; overflow-y: hidden; height:255px; width:255px"> </div>
</div></center>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

<script type="text/javascript" src="http://malsup.github.com/chili-1.7.pack.js"></script>

<script type="text/javascript" src="http://cloud.github.com/downloads/malsup/cycle/jquery.cycle.all.2.72.js"></script>

<script>
 function GetAllImages()
{
$("#slideshowPicturePlaceholder").css("display", "block");
var soapEnv = "<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'><soapenv:Body><GetListItems xmlns='http://schemas.microsoft.com/sharepoint/soap/'>";
    //The name of the image library is called 'SlideShow'. Replace the name bewlo with the name of your image library
 soapEnv += "<listName>SlideShow</listName>";
    soapEnv += "<query><Query><OrderBy Override='TRUE'><FieldRef Name='Created' Ascending='FALSE' /></OrderBy></Query></query>";
    soapEnv += "<viewFields><ViewFields><FieldRef Name='Title'/><FieldRef Name='ows_FileLeafRef'/></ViewFields></viewFields><rowLimit></rowLimit>";
    soapEnv += "</GetListItems></soapenv:Body></soapenv:Envelope>";

var port = window.location.port;
if (port.length <= 0)
 port = "";
else
 port = ":"+port;
var webservice = window.location.protocol+"//"+window.location.hostname+port+L_Menu_BaseUrl+"/_vti_bin/lists.asmx";

    $.ajax({
        url: webservice,
        type: "POST",
        dataType: "xml",
        data: soapEnv,
        complete: processQueryResults,
        contentType: "text/xml; charset=utf-8",
         error: function(xhr) {
        alert('Error!  Status = ' + xhr.status);}
    });
}

function onAfter(curr, next, opts) {
    var index = opts.currSlide;
    $('#prev')[index == 0 ? 'hide' : 'show']();
    $('#next')[index == opts.slideCount - 1 ? 'hide' : 'show']();
}

function processQueryResults(xData, status)
{
var port = window.location.port;
if (port.length <= 0)
 port = "";
else
 port = ":"+port;
//Change the below to point to your image library
var imageURL = window.location.protocol+"//"+window.location.hostname+port+L_Menu_BaseUrl+"/SlideShow/";
var itemURL = window.location.protocol+"//"+window.location.hostname+port+L_Menu_BaseUrl+"/SlideShow/Forms/DispForm.aspx?ID=";

$(xData.responseXML).find("z\\:row").each(function() {
  var title = $(this).attr("ows_Title");
  var imageLink = imageURL+$(this).attr("ows_FileLeafRef").substring($(this).attr("ows_FileLeafRef").indexOf('#')+1);
  var itemLink = itemURL+$(this).attr("ows_ID");
  var Html ="<a target='_blank' border='0' href='"+itemLink+"'><img width='250' height='250'  src='"+ imageLink +"'/></a>";

        $("#slideshow").append(Html);
    });

$("#slideshowPicturePlaceholder").css("display", "none");
$("#slideshowContentArea").css("display", "block");
$('#slideshow').cycle({fx:'scrollHorz',prev:'#prev',next:'#next',after:onAfter,timeout:0});

}

GetAllImages();
</script>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to replicate this functionality in SharePoint 2010. I've added "Content Editor" web part and modifying the source html. However, I'm not getting the desire result, something I'm missing in the code . My output is coming something like ,

Here is my code,

Where am I missing ?

Body:
Try this:

<IMG ID="slideshowPicturePlaceholder" src="/_layouts/images/GEARS_AN.GIF" style="display:none"/>
<center><div id="slideshowContentArea" style="display:none; width:255px;">
    <div class='nav'><a id='prev' href='#'>Prev</a><a id='next' href='#'>Next</a></div>
    <div id="slideshow" class="pics" style="position: relative; overflow-x: hidden; overflow-y: hidden; height:255px; width:255px">&nbsp;</div>
</div></center>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

<script type="text/javascript" src="http://malsup.github.com/chili-1.7.pack.js"></script>

<script type="text/javascript" src="http://cloud.github.com/downloads/malsup/cycle/jquery.cycle.all.2.72.js"></script>

<script>
 function GetAllImages()
{
$("#slideshowPicturePlaceholder").css("display", "block");
var soapEnv = "<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'><soapenv:Body><GetListItems xmlns='http://schemas.microsoft.com/sharepoint/soap/'>";
    //The name of the image library is called 'SlideShow'. Replace the name bewlo with the name of your image library
 soapEnv += "<listName>SlideShow</listName>";
    soapEnv += "<query><Query><OrderBy Override='TRUE'><FieldRef Name='Created' Ascending='FALSE' /></OrderBy></Query></query>";
    soapEnv += "<viewFields><ViewFields><FieldRef Name='Title'/><FieldRef Name='ows_FileLeafRef'/></ViewFields></viewFields><rowLimit></rowLimit>";
    soapEnv += "</GetListItems></soapenv:Body></soapenv:Envelope>";

var port = window.location.port;
if (port.length <= 0)
 port = "";
else
 port = ":"+port;
var webservice = window.location.protocol+"//"+window.location.hostname+port+L_Menu_BaseUrl+"/_vti_bin/lists.asmx";

    $.ajax({
        url: webservice,
        type: "POST",
        dataType: "xml",
        data: soapEnv,
        complete: processQueryResults,
        contentType: "text/xml; charset=utf-8",
         error: function(xhr) {
        alert('Error!  Status = ' + xhr.status);}
    });
}

function onAfter(curr, next, opts) {
    var index = opts.currSlide;
    $('#prev')[index == 0 ? 'hide' : 'show']();
    $('#next')[index == opts.slideCount - 1 ? 'hide' : 'show']();
}

function processQueryResults(xData, status)
{
var port = window.location.port;
if (port.length <= 0)
 port = "";
else
 port = ":"+port;
//Change the below to point to your image library
var imageURL = window.location.protocol+"//"+window.location.hostname+port+L_Menu_BaseUrl+"/SlideShow/";
var itemURL = window.location.protocol+"//"+window.location.hostname+port+L_Menu_BaseUrl+"/SlideShow/Forms/DispForm.aspx?ID=";

$(xData.responseXML).find("z\\:row").each(function() {
  var title = $(this).attr("ows_Title");
  var imageLink = imageURL+$(this).attr("ows_FileLeafRef").substring($(this).attr("ows_FileLeafRef").indexOf('#')+1);
  var itemLink = itemURL+$(this).attr("ows_ID");
  var Html ="<a target='_blank' border='0' href='"+itemLink+"'><img width='250' height='250'  src='"+ imageLink +"'/></a>";

        $("#slideshow").append(Html);
    });

$("#slideshowPicturePlaceholder").css("display", "none");
$("#slideshowContentArea").css("display", "block");
$('#slideshow').cycle({fx:'scrollHorz',prev:'#prev',next:'#next',after:onAfter,timeout:0});

}

GetAllImages();
</script>