答:
Using a map you could get a more readable code and probably a more efficient program, O(n²) to O(n) assuming that accessing a map is in constant time :

var n = 0;
var map = {};
var xs = [
  ['LA', '2017-12-01'],
  ['LA', '2017-12-01'],
  ['NY', '2017-12-01'],
  ['NY', '2016-10-01'],
  ['LA', '2017-12-01'],
  ['LA', '2017-12-01'],
  ['LA', '2017-12-01']
];

xs = xs.map(function (x) {
  var label = x[0] + "-" + x[1];
  if (!map[label]) map[label] = ++n;
  return x.concat([map[label]]);
});

console.log(xs);```

Body:
Am comparing javascript array of elements with other elements within the same array. If elements are same means, i have to give same number for all the common elements. If the elements are different i have to give some different number for all the non identical elements in another element.

for example :

Array structure = [{Location, Date, Number}]

array = [{ 'LA','2017-12-01',1},
         { 'LA','2017-12-01',1},
         { 'NY','2017-12-01',2},
         { 'NY','2016-10-01',3},
         { 'LA','2017-12-01',1},
         { 'LA','2017-12-01',1},
         { 'LA','2017-12-01',1}]

In this array 'Number' is dynamic element, It should be populate on the following rules.

key1 = location + '-' +date;

Consider Key1 is the first element ( combination of location + date ). If the same key1 is present in the array, then 'Number' is common for all the same Key1.

In the above example {'LA','2017-12-01',1 } having the same number 1.

{ 'NY','2017-12-01',2} having the number 2. and
{ 'NY','2016-10-01',3}, having the number 3 because eventhough location is common but date is different.

Please find my code below.

var item = this.state.item;
var lines = item.order_items;
var count=1;
var key1;
var key2;

    for(var i=0;i<lines.length;i++)
        {
            key1 = lines[i].location + '-' + lines[i].date;

            for(var j=0;j<lines.length;j++)
                {
                    key2 = lines[j].location + '-' + lines[j].date;
                    if( key1 === key2 )
                        {
                            lines[i].number=count;
                            this.setState({item:item});
                        }
                    else
                        {
                            count++;
                            lines[j].number=count;
                            this.setState({item:item});
                        }
                }
        }

Problem is, for loop is iterating multiple times - its keep on comparing the same element multiple times. how do i can solve this issue.


来源: stackexchange

问:
Webpack: Issue loading external css files in production build
I am using webpack to create a production build which will contain minified JS and confined CSS. But when I try to run my build none of the external css sheets load, although build process was successful.

In my resultant build folder all of the assets like css, images are placed on root.

Here is my webpack.production.congig file:

```<code>var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
  entry:  __dirname + "/app/index.js",
  output: {
    path: __dirname + "/build",
    filename: "bundle.js"
  },

  module: {
    loaders: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
      },
      {
        test: /\.css$/,
        use: ExtractTextPlugin.extract({
          fallback: "style-loader",
          use: "css-loader"
        })
      },
      {
        test: /\.(gif|png|jpe?g|svg)$/i,
        use: [
          'file-loader',
          {
            loader: 'image-webpack-loader',
            options: {
              bypassOnDebug: true,
              mozjpeg: {
                progressive: true,
                quality: 65
              },
              // optipng.enabled: false will disable optipng
              optipng: {
                enabled: true,
              },
              pngquant: {
                quality: '65-90',
                speed: 4
              },
              gifsicle: {
                interlaced: false,
              },
              // the webp option will enable WEBP
              webp: {
                quality: 75
              }
            },
          },
        ]
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: __dirname + "/index.tmpl.html"
    }),
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.optimize.UglifyJsPlugin(),
    new ExtractTextPlugin("style.css")
  ]

}
</code>```

And here is what my index template look like:

```<code><html lang="en">
  <head>
    <meta charset="utf-8">
    <link rel="icon" href="./app/resources/images/favicon.ico" />
    <link type="text/css" src="style.css"/>

  </head>
  <body>
    <div id='root'>
    </div>
    <script src="bundle.js"></script>
  </body>
</html>
</code>```

My Build folder's content looks like:

答:
So the problem lies at my webpack configuration where while using css-loader I should have enable modules to true

Here's is updated part of my config.

```<code>{
        test: /\.css$/,
        use: ExtractTextPlugin.extract({
          fallback: "style-loader",
          use: [
            {
              loader: "css-loader",
              query: {
                modules: true,
                localIdentName: '[name]__[local]___[hash:base64:5]'
              }
            },
            {
             loader: "postcss-loader",
              options: {
                config: {
                  path: './postcss.config.js'
                }
              }
            }

          ]
        })
      }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am using webpack to create a production build which will contain minified JS and confined CSS. But when I try to run my build none of the external css sheets load, although build process was successful.

In my resultant build folder all of the assets like css, images are placed on root.

Here is my webpack.production.congig file:

var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
  entry:  __dirname + "/app/index.js",
  output: {
    path: __dirname + "/build",
    filename: "bundle.js"
  },

  module: {
    loaders: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
      },
      {
        test: /\.css$/,
        use: ExtractTextPlugin.extract({
          fallback: "style-loader",
          use: "css-loader"
        })
      },
      {
        test: /\.(gif|png|jpe?g|svg)$/i,
        use: [
          'file-loader',
          {
            loader: 'image-webpack-loader',
            options: {
              bypassOnDebug: true,
              mozjpeg: {
                progressive: true,
                quality: 65
              },
              // optipng.enabled: false will disable optipng
              optipng: {
                enabled: true,
              },
              pngquant: {
                quality: '65-90',
                speed: 4
              },
              gifsicle: {
                interlaced: false,
              },
              // the webp option will enable WEBP
              webp: {
                quality: 75
              }
            },
          },
        ]
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: __dirname + "/index.tmpl.html"
    }),
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.optimize.UglifyJsPlugin(),
    new ExtractTextPlugin("style.css")
  ]

}

And here is what my index template look like:

    <meta charset="utf-8">
    <link rel="icon" href="./app/resources/images/favicon.ico" />
    <link type="text/css" src="style.css"/>

My Build folder's content looks like:

Body:
So the problem lies at my webpack configuration where while using css-loader I should have enable modules to true

Here's is updated part of my config.

{
        test: /\.css$/,
        use: ExtractTextPlugin.extract({
          fallback: "style-loader",
          use: [
            {
              loader: "css-loader",
              query: {
                modules: true,
                localIdentName: '[name]__[local]___[hash:base64:5]'
              }
            },
            {
             loader: "postcss-loader",
              options: {
                config: {
                  path: './postcss.config.js'
                }
              }
            }

          ]
        })
      }


问:
React native router flux go back to root scene
In my current scene stack, I have 3 scenes A,B and C.
Going back and forth from A to B to C works fine. But I couldn't navigate back to scene A directly from scene C.
Is this possible?
My current code looks like this:

```<code><Scene key="root">
  <Scene key="aKey" component={A} />
  <Scene key="bKey" component={B} />
  <Scene key="cKey" component={C} />
</Scene>
</code>```

So far, I've tried adding this code in my C component:

```<code>Actions.pop
</code>```

But it only navigates back to previous scene(i.e. B component) and I am trying to navigate back directly to root scene (i.e. A component)

答:
You are using Actions.pop() ;
That means it will navigate to back screen .
Use

```<code>Actions.reset('akey')
</code>```

this will navigate to scene A directly.

Body:
In my current scene stack, I have 3 scenes A,B and C.
Going back and forth from A to B to C works fine. But I couldn't navigate back to scene A directly from scene C.
Is this possible?
My current code looks like this:

<Scene key="root">
  <Scene key="aKey" component={A} />
  <Scene key="bKey" component={B} />
  <Scene key="cKey" component={C} />
</Scene>

So far, I've tried adding this code in my C component:

Actions.pop

But it only navigates back to previous scene(i.e. B component) and I am trying to navigate back directly to root scene (i.e. A component)

Body:
You are using Actions.pop() ;
That means it will navigate to back screen .
Use

Actions.reset('akey')

this will navigate to scene A directly.


问:
Swift add icon/image in UITextField
I would like to add icon/image in UITextField. The icon/image should be left to placeholder.

I tried this:

```<code>var imageView = UIImageView();
var image = UIImage(named: "email.png");
imageView.image = image;
emailField.leftView = imageView;
</code>```

Thanks.

答:
You can put this function your global file or above your class so you can access it in entire application.
     After this procedure you can call this function as per your requirement in application.</p>

```<code>        func SetLeftSIDEImage(TextField: UITextField, ImageName: String){

                let leftImageView = UIImageView()
                leftImageView.contentMode = .scaleAspectFit

                let leftView = UIView()

                leftView.frame = CGRect(x: 20, y: 0, width: 30, height: 20)
                leftImageView.frame = CGRect(x: 13, y: 0, width: 15, height: 20)
                TextField.leftViewMode = .always
                TextField.leftView = leftView

                let image = UIImage(named: ImageName)?.withRenderingMode(.alwaysTemplate)
                leftImageView.image = image
                leftImageView.tintColor = UIColor(red: 106/255, green: 79/255, blue: 131/255, alpha: 1.0)
                leftImageView.tintColorDidChange()

                leftView.addSubview(leftImageView)
            }

            SetLeftSIDEImage(TextField: Your_textField, ImageName: “YourImageName”) // call function
</code>```

Title: Swift add icon/image in UITextField

Body:
I would like to add icon/image in UITextField. The icon/image should be left to placeholder.

I tried this:

var imageView = UIImageView();
var image = UIImage(named: "email.png");
imageView.image = image;
emailField.leftView = imageView;

Thanks.

Body:
You can put this function your global file or above your class so you can access it in entire application.
     After this procedure you can call this function as per your requirement in application.

        func SetLeftSIDEImage(TextField: UITextField, ImageName: String){

                let leftImageView = UIImageView()
                leftImageView.contentMode = .scaleAspectFit

                let leftView = UIView()

                leftView.frame = CGRect(x: 20, y: 0, width: 30, height: 20)
                leftImageView.frame = CGRect(x: 13, y: 0, width: 15, height: 20)
                TextField.leftViewMode = .always
                TextField.leftView = leftView

                let image = UIImage(named: ImageName)?.withRenderingMode(.alwaysTemplate)
                leftImageView.image = image
                leftImageView.tintColor = UIColor(red: 106/255, green: 79/255, blue: 131/255, alpha: 1.0)
                leftImageView.tintColorDidChange()

                leftView.addSubview(leftImageView)
            }

            SetLeftSIDEImage(TextField: Your_textField, ImageName: “YourImageName”) // call function


问:
How to use the ajax() function in JQuery?
In my javascript file I have the following:

```<code><script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">

$.ajax({

    type: 'post',
    url: 'script.php',
    data: '',
    success: function(output) {
        alert(output[0])
    }

});

</script>
</code>```

In my PHP file I have the following:

```<code><?php

echo 'dog';
echo 'cat';

?>
</code>```

Now I know I'm not passing any data through the ajax function, I just wrote the above to test one thing, that is:

When I alert output[0] I get the letter "d". Instead I want to be able to get "dog" and when I alert output[1] I want to be able to get "cat". How to achieve this?

答:
By default, given the response your call is receiving, jQuery is simply handing you the output as a string, in which case you'd have to do whatever string splitting/parsing as appropriate.

See http://api.jquery.com/jQuery.ajax/ and specifically the dataType property for more information.  Depending on what you eventually intend to return from that service (JSON, XML, etc.), you'll want to set that property accordingly in the object you pass to the $.ajax call.

ContentLicense: CC BY-SA 2.5

Body:
In my javascript file I have the following:

In my PHP file I have the following:

<?php

echo 'dog';
echo 'cat';

?>

Now I know I'm not passing any data through the ajax function, I just wrote the above to test one thing, that is:

When I alert output[0] I get the letter "d". Instead I want to be able to get "dog" and when I alert output[1] I want to be able to get "cat". How to achieve this?


问:
Cannot find symbol when already declared
Please someone help me on this error :

```<code>import java.util.*;
class Cinema
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        int cat;
        System.out.println("Choose your category : \n 1)Premium - Rs.150 \n 2)Gold - Rs.200 \n 3)Business Class - Rs.400");
        cat = sc.nextInt();
        switch(cat)
        {
            case 1:
            {
                System.out.println("You have selected Premium");
                int t = 150;   /* VARIABLE DECLARED */
                break;
            }
            case 2:
            {
                System.out.println("You have selected Gold");
                int t = 200;  /* VARIABLE DECLARED */
                break;
            }
            case 3:
            {
                System.out.println("You have selected Business Class");
                int t = 400;  /* VARIABLE DECLARED */
                break;
            }
            default:
            System.out.println("Invalid Option");
            break;
        }
        Scanner num = new Scanner(System.in);
        int n, amt;
        System.out.println("Choose number of tickets");
        n = num.nextInt();
        amt = t * n;      /* ERROR : cannot find symbol - variable t */
        System.out.println("You are buying " +n+ " tickets of " +cat+ " for Rs." +amt);
    }
}
</code>```

I have already declared the variable t in a case block but it cant find it.
I looked through many answers to similar questions but i cant seem to solve it

答:
Ok i figured it out, i had to put int t = 0; after the switch block not before.
When i put it before the switch block, it said variable t is already defined in main(Java.lang.String[]). The correct code is as following :</p>

```<code>import java.util.*;
class Cinema
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        int cat;
        System.out.println("Choose your category : \n 1)Premium - Rs.150 \n 2)Gold - Rs.200 \n 3)Business Class - Rs.400");
        cat = sc.nextInt();
        switch(cat)
        {
            case 1:
            {
                System.out.println("You have selected Premium");
                int t = 150;   /* VARIABLE DECLARED */
                break;
            }
            case 2:
            {
                System.out.println("You have selected Gold");
                int t = 200;  /* VARIABLE DECLARED */
                break;
            }
            case 3:
            {
                System.out.println("You have selected Business Class");
                int t = 400;  /* VARIABLE DECLARED */
                break;
            }
            default:
            System.out.println("Invalid Option");
            break;
        }
        Scanner num = new Scanner(System.in);
        int n, amt;
        int t = 0;
        System.out.println("Choose number of tickets");
        n = num.nextInt();
        amt = t * n;      /* ERROR : cannot find symbol - variable t */
        System.out.println("You are buying " +n+ " tickets of " +cat+ " for Rs." +amt);
    }
}
</code>```

Body:
Please someone help me on this error :

import java.util.*;
class Cinema
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        int cat;
        System.out.println("Choose your category : \n 1)Premium - Rs.150 \n 2)Gold - Rs.200 \n 3)Business Class - Rs.400");
        cat = sc.nextInt();
        switch(cat)
        {
            case 1:
            {
                System.out.println("You have selected Premium");
                int t = 150;   /* VARIABLE DECLARED */
                break;
            }
            case 2:
            {
                System.out.println("You have selected Gold");
                int t = 200;  /* VARIABLE DECLARED */
                break;
            }
            case 3:
            {
                System.out.println("You have selected Business Class");
                int t = 400;  /* VARIABLE DECLARED */
                break;
            }
            default:
            System.out.println("Invalid Option");
            break;
        }
        Scanner num = new Scanner(System.in);
        int n, amt;
        System.out.println("Choose number of tickets");
        n = num.nextInt();
        amt = t * n;      /* ERROR : cannot find symbol - variable t */
        System.out.println("You are buying " +n+ " tickets of " +cat+ " for Rs." +amt);
    }
}

I have already declared the variable t in a case block but it cant find it.
I looked through many answers to similar questions but i cant seem to solve it

Body:
Ok i figured it out, i had to put int t = 0; after the switch block not before.
When i put it before the switch block, it said variable t is already defined in main(Java.lang.String[]). The correct code is as following :

import java.util.*;
class Cinema
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        int cat;
        System.out.println("Choose your category : \n 1)Premium - Rs.150 \n 2)Gold - Rs.200 \n 3)Business Class - Rs.400");
        cat = sc.nextInt();
        switch(cat)
        {
            case 1:
            {
                System.out.println("You have selected Premium");
                int t = 150;   /* VARIABLE DECLARED */
                break;
            }
            case 2:
            {
                System.out.println("You have selected Gold");
                int t = 200;  /* VARIABLE DECLARED */
                break;
            }
            case 3:
            {
                System.out.println("You have selected Business Class");
                int t = 400;  /* VARIABLE DECLARED */
                break;
            }
            default:
            System.out.println("Invalid Option");
            break;
        }
        Scanner num = new Scanner(System.in);
        int n, amt;
        int t = 0;
        System.out.println("Choose number of tickets");
        n = num.nextInt();
        amt = t * n;      /* ERROR : cannot find symbol - variable t */
        System.out.println("You are buying " +n+ " tickets of " +cat+ " for Rs." +amt);
    }
}


问:
Rails Cocoon gem not working

Trying to use to Cocoon gem to create nested forms for a recipe app, but doesn't allow me to save new recipes although I've added the ingredient name and recipe steps.

I keep getting the following errors in my localhost:

2 Prevented this recipe from saving

Ingredients recipe must exist

Directions recipe must exist

I followed a tutorial, have read the Cocoon documentation and research about this issue on Google and SO, but still can't find it. I've been trying to solve this for a few days. Would really appreciate some help please.

Model

```<code>class Recipe < ActiveRecord::Base
belongs_to :user

has_many :ingredients
has_many :directions

accepts_nested_attributes_for :ingredients,
                                                        reject_if: proc { |attributes| attributes['name'].blank? },
                                                        allow_destroy: true
accepts_nested_attributes_for :directions,
                                                        reject_if: proc { |attributes| attributes['step'].blank? },
                                                        allow_destroy: true

validates :title, :description, :image, presence: true

has_attached_file :image, styles: { :medium => "400x400#" }
validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/

end
</code>```

views/recipes/_form

```<code><%= simple_form_for @recipe do |f| %>
<% if @recipe.errors.any? %>
    <div id="error">
        <p><%= @recipe.errors.count %> Prevented this recipe from saving</p>
        <ul>
            <% @recipe.errors.full_messages.each do |message| %>
            <li><%= message %></li>
            <% end %>
        </ul>
    </div>
<% end %>

<div class="panel-body">
    <%= f.input :title %>
    <%= f.input :description %>
    <%= f.input :image %>
</div>

<div class="row">
    <div class="col-md-6">
        <h3>Ingredients</h3>
        <div id="ingredients">
            <%= f.simple_fields_for :ingredients do |ingredient| %>
                <%= render 'ingredient_fields', f: ingredient %>
            <% end %>
            <div class="links">
                <%= link_to_add_association 'Add Ingredient', f, :ingredients, partial: 'ingredient_fields', class: "btn btn-default add-button" %>
            </div>
        </div>
    </div>
    <div class="col-md-6">
        <h3>Directions</h3>
        <div id="directions">
            <%= f.simple_fields_for :directions do |direction| %>
                <%= render 'direction_fields', f: direction %>
            <% end %>
            <div class="links">
                <%= link_to_add_association 'Add Step', f, :directions, partial: 'direction_fields', class: "btn btn-default add-button" %>
            </div>
        </div>
    </div>
</div>

<div>
    <%= f.button :submit, class: "btn btn-primary" %>
</div>
</code>```

views/recipes/_ingredient_fields

```<code><div class="form-inline clearfix">
    <div class="nested-fields">
        <%= f.input :name, class: "form-control" %>
        <%= link_to_remove_association 'Remove', f, class: "btn btn-default" %>
    </div>
</div>
</code>```

views/recipes/_direction_fields

```<code><div class="form-inline clearfix">
    <div class="nested-fields">
        <%= f.input :step, class: "form-control" %>
        <%= link_to_remove_association 'Remove Step', f, class: "btn btn-default" %>
    </div>
</div>
</code>```

controller

```<code>class RecipesController < ApplicationController
before_action :find_recipe, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!, except: [:index, :show]

def index
    @recipe = Recipe.all.order("created_at DESC")
end

def show
end

def new
    @recipe = current_user.recipes.build
end

def create
    @recipe = current_user.recipes.build(recipe_params)

    if @recipe.save
        redirect_to @recipe, notice: "Successfully created new recipe"
    else
        render 'new'
    end
end

def edit
end

def update
    if @recipe.update(recipe_params)
        redirect_to @recipe
    else
        render 'edit'
    end
end

def destroy
    @recipe.destroy
    redirect_to root_path, notice: "Successfully deleted recipe"
end

private

    def recipe_params
        params.require(:recipe).permit(:title, :description, :image, ingredients_attributes: [:id, :name, :_destroy], directions_attributes: [:id, :step, :_destroy])
    end

    def find_recipe
        @recipe = Recipe.find(params[:id])
    end
end
</code>```

Here is a link to the repository if it helps debugging: https://github.com/rchrdchn/rails-projects/tree/master/recipe_box

答:
When you're creating a new recipe, you don't have the recipe object, because it's in the server memory. But when you're updating it, the recipe object is persisted.

That's why you're getting the Ingredients recipe must exist and directions recipe must exist error.

To fix that you have to add the inverse_of in the associations.

```<code>class Recipe
  has_many :ingredients, inverse_of: :recipe
  has_many :directions, inverse_of: :recipe

class Ingredient
  belongs_to :recipe, inverse_of: :ingredients

class Direction
  belongs_to :recipe, inverse_of: :directions
</code>```

Title: Rails Cocoon gem not working

Body:
Trying to use to Cocoon gem to create nested forms for a recipe app, but doesn't allow me to save new recipes although I've added the ingredient name and recipe steps.

I keep getting the following errors in my localhost:

2 Prevented this recipe from saving

Ingredients recipe must exist

Directions recipe must exist

I followed a tutorial, have read the Cocoon documentation and research about this issue on Google and SO, but still can't find it. I've been trying to solve this for a few days. Would really appreciate some help please.

Model

class Recipe < ActiveRecord::Base
belongs_to :user

has_many :ingredients
has_many :directions

accepts_nested_attributes_for :ingredients,
                                                        reject_if: proc { |attributes| attributes['name'].blank? },
                                                        allow_destroy: true
accepts_nested_attributes_for :directions,
                                                        reject_if: proc { |attributes| attributes['step'].blank? },
                                                        allow_destroy: true

validates :title, :description, :image, presence: true

has_attached_file :image, styles: { :medium => "400x400#" }
validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/

end

views/recipes/_form

<%= simple_form_for @recipe do |f| %>
<% if @recipe.errors.any? %>

<%= @recipe.errors.count %> Prevented this recipe from saving

            <% @recipe.errors.full_messages.each do |message| %>

<%= message %>

            <% end %>

<% end %>

    <%= f.input :title %>
    <%= f.input :description %>
    <%= f.input :image %>

Ingredients

            <%= f.simple_fields_for :ingredients do |ingredient| %>
                <%= render 'ingredient_fields', f: ingredient %>
            <% end %>

                <%= link_to_add_association 'Add Ingredient', f, :ingredients, partial: 'ingredient_fields', class: "btn btn-default add-button" %>

Directions

            <%= f.simple_fields_for :directions do |direction| %>
                <%= render 'direction_fields', f: direction %>
            <% end %>

                <%= link_to_add_association 'Add Step', f, :directions, partial: 'direction_fields', class: "btn btn-default add-button" %>

    <%= f.button :submit, class: "btn btn-primary" %>

views/recipes/_ingredient_fields

        <%= f.input :name, class: "form-control" %>
        <%= link_to_remove_association 'Remove', f, class: "btn btn-default" %>

views/recipes/_direction_fields

        <%= f.input :step, class: "form-control" %>
        <%= link_to_remove_association 'Remove Step', f, class: "btn btn-default" %>

controller

class RecipesController < ApplicationController
before_action :find_recipe, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!, except: [:index, :show]

def index
    @recipe = Recipe.all.order("created_at DESC")
end

def show
end

def new
    @recipe = current_user.recipes.build
end

def create
    @recipe = current_user.recipes.build(recipe_params)

    if @recipe.save
        redirect_to @recipe, notice: "Successfully created new recipe"
    else
        render 'new'
    end
end

def edit
end

def update
    if @recipe.update(recipe_params)
        redirect_to @recipe
    else
        render 'edit'
    end
end

def destroy
    @recipe.destroy
    redirect_to root_path, notice: "Successfully deleted recipe"
end

private

    def recipe_params
        params.require(:recipe).permit(:title, :description, :image, ingredients_attributes: [:id, :name, :_destroy], directions_attributes: [:id, :step, :_destroy])
    end

    def find_recipe
        @recipe = Recipe.find(params[:id])
    end
end

Here is a link to the repository if it helps debugging: https://github.com/rchrdchn/rails-projects/tree/master/recipe_box

Body:
When you're creating a new recipe, you don't have the recipe object, because it's in the server memory. But when you're updating it, the recipe object is persisted.

That's why you're getting the Ingredients recipe must exist and directions recipe must exist error.

To fix that you have to add the inverse_of in the associations.

class Recipe
  has_many :ingredients, inverse_of: :recipe
  has_many :directions, inverse_of: :recipe

class Ingredient
  belongs_to :recipe, inverse_of: :ingredients

class Direction
  belongs_to :recipe, inverse_of: :directions


问:
How i can add logo on any location on ffmpeg stream? This is my command :
ffmpeg -y -i input.mp4 -i "logo2.png" -filter_complex "[0:v]setpts=PTS/1.15,boxblur=2:1,scale=iw/1.75:-1,pad=iw+26:ih+26:13:13:color=blue [v1]; movie=bgmu.mp4:loop=999,setpts=N/(FRAME_RATE*TB) [v2]; [v2][v1]overlay=shortest=1:x=W-w-30:y=H-h-22 [v3]; [v3][1:v]overlay=0:0,setdar=16/9; [0:a]atempo=1.15, aecho=0.4:0.66:2:0.2, chorus=0.5:0.9:50|80:0.4|0.42:0.25|0.4:2|1.4, firequalizer=gain_entry='entry(100,0); entry(400, -4); entry(1000, -6); entry(2000, 0)',equalizer = f = 1000: width_type = q: width = 1: g = 2, equalizer = f = 100: width_type = q: width = 2: g = 5,pan=stereo|c0

答:
In [v3][1:v]overlay=0:0, the first 0 is x-coordinate measured from left edge of [v3] and 2nd 0 is y-coordinate measured from top of [v3]. So change those values. You can use W, H, w and h in your expressions, which are the width and height of [v3] and [1:v] respectively.

[v3][1:v]overlay=(W-w)/2:H-h-10 means to overlay it horizontally center and vertically at the bottom leaving a margin of 10 pixels.

Body: <p>ffmpeg -y -i input.mp4 -i "logo2.png" -filter_complex "[0:v]setpts=PTS/1.15,boxblur=2:1,scale=iw/1.75:-1,pad=iw+26:ih+26:13:13:color=blue [v1]; movie=bgmu.mp4:loop=999,setpts=N/(FRAME_RATE*TB) [v2]; [v2][v1]overlay=shortest=1:x=W-w-30:y=H-h-22 [v3]; [v3][1:v]overlay=0:0,setdar=16/9; [0:a]atempo=1.15, aecho=0.4:0.66:2:0.2, chorus=0.5:0.9:50|80:0.4|0.42:0.25|0.4:2|1.4, firequalizer=gain_entry='entry(100,0); entry(400, -4); entry(1000, -6); entry(2000, 0)',equalizer = f = 1000: width_type = q: width = 1: g = 2, equalizer = f = 100: width_type = q: width = 2: g = 5,pan=stereo|c0


问:
How can I pass fixtures to pytest.mark.parameterize?
I am trying to pass three different fixtures to my pytest.mark.parameterize decorator, like this:

```<code>@pytest.mark.parametrize("credentials, return_code", [
    (user1, 200),
    #(user2, 200),
    #(user3, 401)
])
def test_login():
    assert True
# Actual test uses response.return_code == return_code
</code>```

However, I get an error that reads:

```<code>NameError: name 'user1' is not defined
</code>```

This isn't correct though, I have defined it in conftest.py:

```<code>user1_info = [('user1', 'password')]
@pytest.fixture(params=user1_info)
def user1(request):
    return request.param
</code>```

The fixture works if I change my test to be like this:

```<code>def test_login(user1):
    assert True
# Actual test uses response.return_code == return_code
</code>```

The problem is that if I do it this way, I have to write three separate tests, one for each fixture, and for each status_code check. If I could use parameterize, I could use one function and check the user/expected return code.

How can I utilize my fixtures are part of the pytest.mark.parameterize decorator?

答:
To pass fixtures as parametrized arguments, reference them as strings and use the keyword arguments indirect=['arg_name', ...].

Then use the parameter names credentials and return_code as arguments to your test function.

@pytest.mark.parametrize(
    "credentials, return_code",
    [
        ("user1", 200),
        ("user2", 200),
        ("user3", 401),
    ],
    # Only the `credentials` parameter is a reference to the
    # fixture. The `return_code` should be passed as is.
    indirect=["credentials"],
)
def test_login(credentials, return_code):
    return True
```

The documentation for pytest's parametrize magic with indirect can be found here:
https://docs.pytest.org/en/stable/example/parametrize.html#apply-indirect-on-particular-arguments

Body:
I am trying to pass three different fixtures to my pytest.mark.parameterize decorator, like this:

@pytest.mark.parametrize("credentials, return_code", [
    (user1, 200),
    #(user2, 200),
    #(user3, 401)
])
def test_login():
    assert True
# Actual test uses response.return_code == return_code

However, I get an error that reads:

NameError: name 'user1' is not defined

This isn't correct though, I have defined it in conftest.py:

user1_info = [('user1', 'password')]
@pytest.fixture(params=user1_info)
def user1(request):
    return request.param

The fixture works if I change my test to be like this:

def test_login(user1):
    assert True
# Actual test uses response.return_code == return_code

The problem is that if I do it this way, I have to write three separate tests, one for each fixture, and for each status_code check. If I could use parameterize, I could use one function and check the user/expected return code.

How can I utilize my fixtures are part of the pytest.mark.parameterize decorator?

Body:
To pass fixtures as parametrized arguments, reference them as strings and use the keyword arguments indirect=['arg_name', ...].

Then use the parameter names credentials and return_code as arguments to your test function.

@pytest.mark.parametrize(
    "credentials, return_code",
    [
        ("user1", 200),
        ("user2", 200),
        ("user3", 401),
    ],
    # Only the `credentials` parameter is a reference to the
    # fixture. The `return_code` should be passed as is.
    indirect=["credentials"],
)
def test_login(credentials, return_code):
    return True

The documentation for pytest's parametrize magic with indirect can be found here:
https://docs.pytest.org/en/stable/example/parametrize.html#apply-indirect-on-particular-arguments

ContentLicense: CC BY-SA 4.0


问:
Connecting to MSSQL Server 2017 from Apache HTTP Server via python script
What should be my configuration to connect with Apache from the below configuration:

```<code>SERVER    :   DESKTOP-C6RS3DO
User Name :   (Default:blank)
Password  :   (Default:blank)
Connection:   DESKTOP-C6RS3DO\Vitriv-Desktop
</code>```

Even server Authentication is set to "SQL Server and Windows Authentication mode"

```<code>cnxn = pypyodbc.connect(driver='{ODBC Driver 13 for SQL Server}', server='DESKTOP-C6RS3DO', database='demo2016', Trusted_Connection='Yes')
</code>```

OR

```<code>cnxn = pypyodbc.connect(
    r'DRIVER={ODBC Driver 13 for SQL Server};'
    r'SERVER=DESKTOP-C6RS3DO;'
    r'DATABASE=demo2016;'
    #r'UID=Vitriv-Desktop;'
    #r'PWD='
    r'Trusted_Connection=yes;'
    )
</code>```

errors.log

```<code>[Wed Dec 06 14:40:05.679511 2017] [cgi:error] [pid 5592:tid 1340] [client ::1:52581] AH01215:

Traceback (most recent call last):\r: C:/Apache24/htdocs/vitriv.py, referer: http://localhost/signup_page.html
   File "C:/Apache24/htdocs/vitriv.py", line 37, in <module>\r: C:/Apache24/htdocs/vitriv.py, referer: http://localhost/signup_page.html
     r'DRIVER={ODBC Driver 13 for SQL Server};'\r: C:/Apache24/htdocs/vitriv.py, referer: http://localhost/signup_page.html
   File "C:/Users/Vitriv-Desktop/AppData/Local/Programs/Python/Python36-32/Lib/site-packages\\pypyodbc.py", line 2454, in __init__\r: C:/Apache24/htdocs/vitriv.py, referer: http://localhost/signup_page.html
     self.connect(connectString, autocommit, ansi, timeout, unicode_results, readonly)\r: C:/Apache24/htdocs/vitriv.py, referer: http://localhost/signup_page.html
   File "C:/Users/Vitriv-Desktop/AppData/Local/Programs/Python/Python36-32/Lib/site-packages\\pypyodbc.py", line 2507, in connect\r: C:/Apache24/htdocs/vitriv.py, referer: http://localhost/signup_page.html
     check_success(self, ret)\r: C:/Apache24/htdocs/vitriv.py, referer: http://localhost/signup_page.html
   File "C:/Users/Vitriv-Desktop/AppData/Local/Programs/Python/Python36-32/Lib/site-packages\\pypyodbc.py", line 1009, in check_success\r: C:/Apache24/htdocs/vitriv.py, referer: http://localhost/signup_page.html
     ctrl_err(SQL_HANDLE_DBC, ODBC_obj.dbc_h, ret, ODBC_obj.ansi)\r: C:/Apache24/htdocs/vitriv.py, referer: http://localhost/signup_page.html
   File "C:/Users/Vitriv-Desktop/AppData/Local/Programs/Python/Python36-32/Lib/site-packages\\pypyodbc.py", line 987, in ctrl_err\r: C:/Apache24/htdocs/vitriv.py, referer: http://localhost/signup_page.html
     raise DatabaseError(state,err_text)\r: C:/Apache24/htdocs/vitriv.py, referer: http://localhost/signup_page.html
 pypyodbc.DatabaseError: ('28000', "[28000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Login failed for user 'WORKGROUP\\\\DESKTOP-C6RS3DO$'.")\r: C:/Apache24/htdocs/vitriv.py, referer: http://localhost/signup_page.html
</code>```

Connecting via python shell executes successfully but not through web browser. why?

答:
ANSWER</p>

```<code>try:
    cnxn = pypyodbc.connect('Driver={ODBC Driver 13 for SQL Server};'
                        'Server=DESKTOP-C6RS3DO;'
                        'Database=demo2016;'
                        'uid=sa;pwd=sa')

    print('connected <br/>')
    cursor = cnxn.cursor()

except :
    print("could not connect")
    cursor.close()
    cnxn.close()
</code>```

Body:
What should be my configuration to connect with Apache from the below configuration:

SERVER    :   DESKTOP-C6RS3DO
User Name :   (Default:blank)
Password  :   (Default:blank)
Connection:   DESKTOP-C6RS3DO\Vitriv-Desktop

Even server Authentication is set to "SQL Server and Windows Authentication mode"

cnxn = pypyodbc.connect(driver='{ODBC Driver 13 for SQL Server}', server='DESKTOP-C6RS3DO', database='demo2016', Trusted_Connection='Yes')

OR

cnxn = pypyodbc.connect(
    r'DRIVER={ODBC Driver 13 for SQL Server};'
    r'SERVER=DESKTOP-C6RS3DO;'
    r'DATABASE=demo2016;'
    #r'UID=Vitriv-Desktop;'
    #r'PWD='
    r'Trusted_Connection=yes;'
    )

errors.log

[Wed Dec 06 14:40:05.679511 2017] [cgi:error] [pid 5592:tid 1340] [client ::1:52581] AH01215:

Traceback (most recent call last):\r: C:/Apache24/htdocs/vitriv.py, referer: http://localhost/signup_page.html
   File "C:/Apache24/htdocs/vitriv.py", line 37, in <module>\r: C:/Apache24/htdocs/vitriv.py, referer: http://localhost/signup_page.html
     r'DRIVER={ODBC Driver 13 for SQL Server};'\r: C:/Apache24/htdocs/vitriv.py, referer: http://localhost/signup_page.html
   File "C:/Users/Vitriv-Desktop/AppData/Local/Programs/Python/Python36-32/Lib/site-packages\\pypyodbc.py", line 2454, in __init__\r: C:/Apache24/htdocs/vitriv.py, referer: http://localhost/signup_page.html
     self.connect(connectString, autocommit, ansi, timeout, unicode_results, readonly)\r: C:/Apache24/htdocs/vitriv.py, referer: http://localhost/signup_page.html
   File "C:/Users/Vitriv-Desktop/AppData/Local/Programs/Python/Python36-32/Lib/site-packages\\pypyodbc.py", line 2507, in connect\r: C:/Apache24/htdocs/vitriv.py, referer: http://localhost/signup_page.html
     check_success(self, ret)\r: C:/Apache24/htdocs/vitriv.py, referer: http://localhost/signup_page.html
   File "C:/Users/Vitriv-Desktop/AppData/Local/Programs/Python/Python36-32/Lib/site-packages\\pypyodbc.py", line 1009, in check_success\r: C:/Apache24/htdocs/vitriv.py, referer: http://localhost/signup_page.html
     ctrl_err(SQL_HANDLE_DBC, ODBC_obj.dbc_h, ret, ODBC_obj.ansi)\r: C:/Apache24/htdocs/vitriv.py, referer: http://localhost/signup_page.html
   File "C:/Users/Vitriv-Desktop/AppData/Local/Programs/Python/Python36-32/Lib/site-packages\\pypyodbc.py", line 987, in ctrl_err\r: C:/Apache24/htdocs/vitriv.py, referer: http://localhost/signup_page.html
     raise DatabaseError(state,err_text)\r: C:/Apache24/htdocs/vitriv.py, referer: http://localhost/signup_page.html
 pypyodbc.DatabaseError: ('28000', "[28000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Login failed for user 'WORKGROUP\\\\DESKTOP-C6RS3DO$'.")\r: C:/Apache24/htdocs/vitriv.py, referer: http://localhost/signup_page.html

Connecting via python shell executes successfully but not through web browser. why?

Body:
ANSWER

try:
    cnxn = pypyodbc.connect('Driver={ODBC Driver 13 for SQL Server};'
                        'Server=DESKTOP-C6RS3DO;'
                        'Database=demo2016;'
                        'uid=sa;pwd=sa')

    print('connected <br/>')
    cursor = cnxn.cursor()

except :
    print("could not connect")
    cursor.close()
    cnxn.close()


问:
yii2 : attribute being taken as string
I am trying to execute this code

```<code>->andWhere(['like','a.id','b.id']);
</code>```

But this takes b.id as a string to compare with directly instead of comparing it as a table attribute.

Any ideas on how to fix this. I am new to yii2.

答:
Just changed it with

```<code>->andWhere('a.id = b.id');
</code>```

Thank you.

Title: yii2 : attribute being taken as string

Body:
I am trying to execute this code

->andWhere(['like','a.id','b.id']);

But this takes b.id as a string to compare with directly instead of comparing it as a table attribute.

Any ideas on how to fix this. I am new to yii2.

Body:
Just changed it with

->andWhere('a.id = b.id');

Thank you.


问:
Overloading function int vs double
I just played with overloading function in c++.

Firstly, I tried

```<code>#include <iostream>
void foo(int x) {std::cout << "foo(int)" << x << std::endl;}
void foo(double x) {std::cout << "foo(double)" << x << std::endl;}
void foo(int x,double y) {std::cout << "foo(int,double)" << x << y << std::endl;}
int main() {
    foo(1);
}
</code>```

It worked.

If I added the default arguments.

```<code>void foo(int x=1,double y=1.1) {std::cout << "foo(int,double)" << x << y << std::endl;}
</code>```

It gives the error: call to 'foo' is ambiguous. Well, I understand that the compiler doesn't know which to choose between foo(int) and foo(int,double). But if I change the main like this

```<code>int main()
{
     foo(1.2);
}
</code>```

Well, it compiled and I get output foo(double) 1.2. I don't understand why it is different between two cases. I google the same question but there is only question int vs float.

答:
You need to declare and define a variable with double type to call and override successfully the foo(int) with foo(double).</p>

```<code>#include <iostream>

using namespace std;

void foo(int x) {std::cout << "foo(int)" << x << std::endl;}
void foo(double x) {std::cout << "foo(double)" << x << std::endl;}
void foo(int x,double y) {std::cout << "foo(int,double)" << x << y << std::endl;}

int main()
{
    double x = 5;
    foo(x);

    return 0;
}
</code>```

Title: Overloading function int vs double

Body:
I just played with overloading function in c++.

Firstly, I tried

#include <iostream>
void foo(int x) {std::cout << "foo(int)" << x << std::endl;}
void foo(double x) {std::cout << "foo(double)" << x << std::endl;}
void foo(int x,double y) {std::cout << "foo(int,double)" << x << y << std::endl;}
int main() {
    foo(1);
}

It worked.

If I added the default arguments.

void foo(int x=1,double y=1.1) {std::cout << "foo(int,double)" << x << y << std::endl;}

It gives the error: call to 'foo' is ambiguous. Well, I understand that the compiler doesn't know which to choose between foo(int) and foo(int,double). But if I change the main like this

int main()
{
     foo(1.2);
}

Well, it compiled and I get output foo(double) 1.2. I don't understand why it is different between two cases. I google the same question but there is only question int vs float.

Body:
You need to declare and define a variable with double type to call and override successfully the foo(int) with foo(double).

#include <iostream>

using namespace std;

void foo(int x) {std::cout << "foo(int)" << x << std::endl;}
void foo(double x) {std::cout << "foo(double)" << x << std::endl;}
void foo(int x,double y) {std::cout << "foo(int,double)" << x << y << std::endl;}

int main()
{
    double x = 5;
    foo(x);

    return 0;
}


问:
How to tune parameters of Bagging in R?
I was wondering when we use the Bagging to do the classification, what parameters can be tuned and can we use the cross-validation to tune it?

In the Bagging function in R, it says we can use the nbagg to change the number of bootstrap replications. And use rpart.control.

Here's my code
bagging(income ~., data = training3, coob= T)

答:
When to use bagging in classification?

Bagging is essentially taking repeated samples from the single training set in order to generate x number of different bootstrapped training data sets. We then train our method on these training sets and average all the predictions in case of regression, we use voting in case of classification. Bagging helps in reducing the variance of an outcome so in cases where your you have a very high variance in your results you often choose bagging, often bagging techniques are outperformed by random forest and boosting.

What parameters can be tuned and can we use the cross-validation to tune it ?

nbagg: The nbagg parameter is used to control the number of decision trees voting
in the ensemble (with a default value of 25). Depending on the difficulty of the learning task and the amount of training data, increasing this number may improve the model's performance but it rquires additional
computational expense.

cp: cp is the complexity parameter when tuned properly gives a pruned tree, The complexity parameter (cp) is used to control the size of the decision tree and to select the optimal tree size. In cases where the cost of adding another variable to the decision tree from the current node is above the value of cp, then tree building does not continue, you can hit and trial to plot it and see what fits for you.

Can we use cross validation?

Yes you can, you should use however caret package to do it(just to make your life simple)

```<code>library(caret)
set.seed(1729)
cntrl <- trainControl(method = "cv", number = 10)
train(dependent_variable ~ ., data = mydata, method = "treebag",
        trControl = cntrl)
</code>```

Title: How to tune parameters of Bagging in R?

Body:
When to use bagging in classification?

Bagging is essentially taking repeated samples from the single training set in order to generate x number of different bootstrapped training data sets. We then train our method on these training sets and average all the predictions in case of regression, we use voting in case of classification. Bagging helps in reducing the variance of an outcome so in cases where your you have a very high variance in your results you often choose bagging, often bagging techniques are outperformed by random forest and boosting.

What parameters can be tuned and can we use the cross-validation to tune it ?

nbagg: The nbagg parameter is used to control the number of decision trees voting
in the ensemble (with a default value of 25). Depending on the difficulty of the learning task and the amount of training data, increasing this number may improve the model's performance but it rquires additional
computational expense.

cp: cp is the complexity parameter when tuned properly gives a pruned tree, The complexity parameter (cp) is used to control the size of the decision tree and to select the optimal tree size. In cases where the cost of adding another variable to the decision tree from the current node is above the value of cp, then tree building does not continue, you can hit and trial to plot it and see what fits for you.

Can we use cross validation?

Yes you can, you should use however caret package to do it(just to make your life simple)

library(caret)
set.seed(1729)
cntrl <- trainControl(method = "cv", number = 10)
train(dependent_variable ~ ., data = mydata, method = "treebag",
        trControl = cntrl)


问:
Bootstrap 4 aligning row to the bottom of a container
How do I align a bootstrap row to the bottom of a container?

Like this:

HTML

```<code><main class="bd-masthead container-fluid" id="" role="main" style="padding-top:5rem;">
  <div class="row">
    <div class="col">
      <h1 class="text-light">
        LukeBank
      </h1>
    </div>
  </div>
  <div class="row" style="padding-top:10px">
    <div class="col">
      <button type="button" class="btn btn-outline-light">Button</button>
    </div>
  </div>
</main>
</code>```

CSS

```<code>html, body {
  height: 100%;
  width: 100%;
}

main {
  height: 100%;
  background-image: url(/img/frontpage.bg.jpg);
  background-position: center center;
  background-size: cover;
}

.otherpart {
  height: 100%;
  background-color: white;
  background-position: center bottom;
  background-size: cover;
}
</code>```

I tried to use .align-bottom, but it didn't work.

答:
you can do this with

position:absolute;
bottom:0;```

But it's not a proper way to do this. You can add near to your col class

align-self-center

Body:
How do I align a bootstrap row to the bottom of a container?

Like this:

HTML

        LukeBank

      <button type="button" class="btn btn-outline-light">Button</button>

CSS

html, body {
  height: 100%;
  width: 100%;
}

main {
  height: 100%;
  background-image: url(/img/frontpage.bg.jpg);
  background-position: center center;
  background-size: cover;
}

.otherpart {
  height: 100%;
  background-color: white;
  background-position: center bottom;
  background-size: cover;
}

I tried to use .align-bottom, but it didn't work.

Body:
you can do this with

position:absolute;
bottom:0;

But it's not a proper way to do this. You can add near to your col class

align-self-center


问:
XAML WebBrowser emulation without registry change
I am trying to render some HTML page of mine hosted on a NodeJS in a WPF app.

I have tried few things and the following option seems the most convenient:
C# webbrowser Ajax call

However it is modifying the registry which I cannot (company policy).

Therefore would there be a way to do the same on the fly? ie. load the WebBrowser with this setup without updating the registry?

Thank you

答:
You might be able to do this with the XUA compatible meta tag.

```<code><meta http-equiv="x-ua-compatible" content="IE=11">
</code>```

I don't know if you have access to the site's content or not. If you do, then just put in right there in the HTML.

If you do not own the page, there are ways modify the page and dynamically inject this tag with a bit of com interop from mshtml.

Body:
You might be able to do this with the XUA compatible meta tag.

<meta http-equiv="x-ua-compatible" content="IE=11">

I don't know if you have access to the site's content or not. If you do, then just put in right there in the HTML.

If you do not own the page, there are ways modify the page and dynamically inject this tag with a bit of com interop from mshtml.


答:
The PHP script is returning the string 'dogcat'. So when you're printing output[0], you'd obviously get the first character in the string.

You need to separate your words echoed from the PHP script with some kind of separator, such "|", and have the javascript split the output by that.

Title: How to use the ajax() function in JQuery?

Body:
In my javascript file I have the following:

In my PHP file I have the following:

<?php

echo 'dog';
echo 'cat';

?>

Now I know I'm not passing any data through the ajax function, I just wrote the above to test one thing, that is:

When I alert output[0] I get the letter "d". Instead I want to be able to get "dog" and when I alert output[1] I want to be able to get "cat". How to achieve this?


问:
Setting content of named router-outlet in child route
In my application I want to display content in two router-outlets, the primary one and a named one. If I place both outlets on the root level, I am able to set the content of the named outlet like this:

```<code>this.router.navigate([{ outlets: { rootSecondary: ['rootSecondaryPath'] } }]);
</code>```

However, I want the general layout of the application to provide a single router-outlet and be able to use a different router-outlet structure in the child routes.

If I create a child route, that also has a primary and a named outlet, I am unable to set the content of the secondary outlet. The error that is reported is:

Cannot match any routes.

The routes are defined as follows:

```<code>const appRoutes: Routes = [
  { path: '', component: RootPrimaryComponent },
  { path: 'rootSecondaryPath', component: RootSecondaryComponent, outlet: 'rootSecondary' },
  {
    path: 'child', component: ChildComponent, children:
      [
        { path: '', component: ChildPrimaryComponent },
        { path: 'childSecondaryPath', component: ChildSecondaryComponent, outlet: 'childSecondary' },
      ]
  },
];
const appRouting = RouterModule.forRoot(appRoutes);
</code>```

The template of app.component.html contains a primary outlet and - for testing purposes - a named secondary one:

```<code><router-outlet></router-outlet>
<div style="border: solid 1px green">
  <router-outlet name="rootSecondary"></router-outlet>
</div>
</code>```

The code above is called from a button and sets the rootSecondary outlet without any problem.

The template child.component.html defines two outlets that are placed inside of the root primary outlet:

```<code><router-outlet></router-outlet>
<div style="border:solid 1px red">
  <router-outlet name="childSecondary"></router-outlet>
</div>
</code>```

child.primary.component.html contains a button that calls the code to set the secondary outlet:

```<code><div>
  child-primary works!
  <button (click)="setChildSecondary()">Set child secondary</button>
</div>
</code>```

When clicked, the following code is run:

```<code>setChildSecondary() {
  this.router.navigate([{ outlets: { childSecondary: ['childSecondaryPath'] } }]);
}
</code>```

How do I have to change the code so that the router-outlet childSecondary is filled?

答:
In order to solve this, I needed to set the relativeTo param to the parent of the currently active route:

```<code>export class ChildPrimaryComponent {

  constructor(private readonly router: Router,
    private readonly route: ActivatedRoute) { }

  setChildSecondary() {
    this.router.navigate([{ outlets: { childSecondary: ['childSecondaryPath'] } }],
      { relativeTo: this.route.parent });
  }
}
</code>```

Body:
In my application I want to display content in two router-outlets, the primary one and a named one. If I place both outlets on the root level, I am able to set the content of the named outlet like this:

this.router.navigate([{ outlets: { rootSecondary: ['rootSecondaryPath'] } }]);

However, I want the general layout of the application to provide a single router-outlet and be able to use a different router-outlet structure in the child routes.

If I create a child route, that also has a primary and a named outlet, I am unable to set the content of the secondary outlet. The error that is reported is:

Cannot match any routes.

The routes are defined as follows:

const appRoutes: Routes = [
  { path: '', component: RootPrimaryComponent },
  { path: 'rootSecondaryPath', component: RootSecondaryComponent, outlet: 'rootSecondary' },
  {
    path: 'child', component: ChildComponent, children:
      [
        { path: '', component: ChildPrimaryComponent },
        { path: 'childSecondaryPath', component: ChildSecondaryComponent, outlet: 'childSecondary' },
      ]
  },
];
const appRouting = RouterModule.forRoot(appRoutes);

The template of app.component.html contains a primary outlet and - for testing purposes - a named secondary one:

<router-outlet></router-outlet>

  <router-outlet name="rootSecondary"></router-outlet>

The code above is called from a button and sets the rootSecondary outlet without any problem.

The template child.component.html defines two outlets that are placed inside of the root primary outlet:

<router-outlet></router-outlet>

  <router-outlet name="childSecondary"></router-outlet>

child.primary.component.html contains a button that calls the code to set the secondary outlet:

  child-primary works!
  <button (click)="setChildSecondary()">Set child secondary</button>

When clicked, the following code is run:

setChildSecondary() {
  this.router.navigate([{ outlets: { childSecondary: ['childSecondaryPath'] } }]);
}

How do I have to change the code so that the router-outlet childSecondary is filled?

Body:
In order to solve this, I needed to set the relativeTo param to the parent of the currently active route:

export class ChildPrimaryComponent {

  constructor(private readonly router: Router,
    private readonly route: ActivatedRoute) { }

  setChildSecondary() {
    this.router.navigate([{ outlets: { childSecondary: ['childSecondaryPath'] } }],
      { relativeTo: this.route.parent });
  }
}


问:
Getting value from firebase returns error

Problem

With a social media app created by React Native I am trying to use a snapshot function to get data off of my firebase server, then add 1 to that value, then update that value on the server. The code I am doing that with is:

```<code>    this.setState({
      comments: firebase.database().ref('posts/'+this.state.passKey).once('value', function(snapshot) {snapshot.val().comments})
        })

    firebase.database().ref('posts').child(this.state.passKey).update({
      comments: this.state.comments+1
        })
</code>```

When I run this code though, I get an error, saying:

```<code>Reference.update failed:
First argument contains NaN in property 'posts.randompostkey.comments'
</code>```

My Server

答:
The solution is to properly synchronize access to the data: first ensure that everything is loaded, only then update the score.

Look at this solution

Body:
Problem

With a social media app created by React Native I am trying to use a snapshot function to get data off of my firebase server, then add 1 to that value, then update that value on the server. The code I am doing that with is:

    this.setState({
      comments: firebase.database().ref('posts/'+this.state.passKey).once('value', function(snapshot) {snapshot.val().comments})
        })

    firebase.database().ref('posts').child(this.state.passKey).update({
      comments: this.state.comments+1
        })

When I run this code though, I get an error, saying:

Reference.update failed:
First argument contains NaN in property 'posts.randompostkey.comments'

My Server


问:
can somebody explain what exactly is going on with python functions?
what i know in python is i can write something like this  </p>

```<code>blabla = Classname().somefunctions()
</code>```

<p>but in this case both the "np.arange" and "reshape" are functions and it confuses me because  "np.arange" is a function and is treated like a class.   the question is how is this possible??  </p>

```<code>import numpy as np
a = np.arange(15).reshape(3, 5)
print(a)
</code>```

答:
Python is an object oriented language, where every variable is an object. np.arange returns ndarray object. And then, you could call reshape method of ndarray object.

```<code>import numpy as np

a = np.arange(15)

type(a)
Out[148]: numpy.ndarray

a
Out[149]: array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14])

a = a.reshape(3, 5)

type(a)
Out[151]: numpy.ndarray

a
Out[152]:
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])
</code>```

Body:
what i know in python is i can write something like this

blabla = Classname().somefunctions()

but in this case both the "np.arange" and "reshape" are functions and it confuses me because  "np.arange" is a function and is treated like a class.   the question is how is this possible??

import numpy as np
a = np.arange(15).reshape(3, 5)
print(a)

Body:
Python is an object oriented language, where every variable is an object. np.arange returns ndarray object. And then, you could call reshape method of ndarray object.

import numpy as np

a = np.arange(15)

type(a)
Out[148]: numpy.ndarray

a
Out[149]: array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14])

a = a.reshape(3, 5)

type(a)
Out[151]: numpy.ndarray

a
Out[152]:
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])


问:
How to write data to firestore through firebase functions?
I can quite easily find how to add triggers for firestore events but I can't find any documentation on how to use firebase functions to write to firestore.

For example I have the following:

```<code>export const listener = functions.auth.user().onCreate((x)=>{
    //firestore function to add an entry for user with fields...
})
</code>```

There doesn't seem to be a way to do this? Is it that the logic for adding data to firestore should be written client side? If so wouldn't that mean I would need to re-write that functionality for every platform?

答:
You can use the Firebase Admin SDK to read and write Firestore in the same way you'd use it to read and write Realtime Database.  There are plenty of official examples, especially this quickstart.</p>

```<code>const admin = require('firebase-admin');
admin.initializeApp();

admin.firestore().collection('messages').add({original: original}).then(writeResult => {
    // write is complete here
});
</code>```

Body:
I can quite easily find how to add triggers for firestore events but I can't find any documentation on how to use firebase functions to write to firestore.

For example I have the following:

export const listener = functions.auth.user().onCreate((x)=>{
    //firestore function to add an entry for user with fields...
})

There doesn't seem to be a way to do this? Is it that the logic for adding data to firestore should be written client side? If so wouldn't that mean I would need to re-write that functionality for every platform?

Body:
You can use the Firebase Admin SDK to read and write Firestore in the same way you'd use it to read and write Realtime Database.  There are plenty of official examples, especially this quickstart.

const admin = require('firebase-admin');
admin.initializeApp();

admin.firestore().collection('messages').add({original: original}).then(writeResult => {
    // write is complete here
});


问:
How do you display "%5d" in C?
How do you display the string "%5d" in C? I tried putting a backslash in front of the percent, but it won't print (and gave warnings). I tried Googling but to no avail. I guess this is too wide for me to find a specific answer.

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

int main(void)
{
    int test = 40;
    printf("\%5.1d %5.1d", test); //this is the one
    printf("%5.1d", test);
    return 0;
}
</code>```

Any help?

答:
As an alternative to the other two (at least) perfectly correct answers, you could also use fputs() like this:

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

int main(void)
{
    int test = 40;
    fputs("%5d ", stdout);
    printf("%5.1d\n", test);
    return 0;
}
</code>```

Note that I added a newline to the output; that is important as the output is not flushed to the terminal until you output a newline.  Note too that I used fputs() and not puts() because puts() emits a newline that you do not want emitted.

However, knowing the general solution of using double-% for a real percent in both the printf() and scanf() families of functions will stand you in good stead for the future.

Title: How do you display "%5d" in C?

Body:
How do you display the string "%5d" in C? I tried putting a backslash in front of the percent, but it won't print (and gave warnings). I tried Googling but to no avail. I guess this is too wide for me to find a specific answer.

#include <stdio.h>

int main(void)
{
    int test = 40;
    printf("\%5.1d %5.1d", test); //this is the one
    printf("%5.1d", test);
    return 0;
}

Any help?

Body:
As an alternative to the other two (at least) perfectly correct answers, you could also use fputs() like this:

#include <stdio.h>

int main(void)
{
    int test = 40;
    fputs("%5d ", stdout);
    printf("%5.1d\n", test);
    return 0;
}

Note that I added a newline to the output; that is important as the output is not flushed to the terminal until you output a newline.  Note too that I used fputs() and not puts() because puts() emits a newline that you do not want emitted.

However, knowing the general solution of using double-% for a real percent in both the printf() and scanf() families of functions will stand you in good stead for the future.


问:
How can I create a UITableViewCell with subview of set height using autolayout?
I have a table view cell (yellow) with one subview (red):

The subview should have a fixed height of 100. And should have a border of 5 top, and 5 bottom to the cell.

The table row needs to be dynamic:

```<code>table.rowHeight = UITableViewAutomaticDimension
table.estimatedRowHeight = 110
</code>```

What I have tried: I set the height of the subview to 100, and set the top and bottom to 5 away from the superview. But Interface Builder complains that either Y position or height constraints are missing.

All I want to accomplish is this. 5 at top. 5 at bottom. redview = 100.
How can I resolve this?

EDIT: Here is the sample file -> https://github.com/patchthecode/Autolayout

答: Adding center y align to the super view(cell) will satisfy the interface builder.</p>

Body:
I have a table view cell (yellow) with one subview (red):

The subview should have a fixed height of 100. And should have a border of 5 top, and 5 bottom to the cell.

The table row needs to be dynamic:

table.rowHeight = UITableViewAutomaticDimension
table.estimatedRowHeight = 110

What I have tried: I set the height of the subview to 100, and set the top and bottom to 5 away from the superview. But Interface Builder complains that either Y position or height constraints are missing.

All I want to accomplish is this. 5 at top. 5 at bottom. redview = 100.
How can I resolve this?

EDIT: Here is the sample file -> https://github.com/patchthecode/Autolayout


问:
Why doesn't app.component.html render?
I have the following Angular plnkr.co: https://plnkr.co/edit/xA8jU4QYDGxzohNg5NFj?p=preview.

//app.component.ts

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html'
})
export class AppComponent { name = 'Angular'; }
</code>```

//app.component.html

```<code>testing...
<router-outlet></router-outlet>
</code>```

The oputput in the browser is:

```<code>Loading AppComponent content here ...
</code>```

Why doesn't it see the app.component.html file? Or is this some other issue?

答:
Here you were missing correct routing implementation several errors are there in console please refer to them.

app.component.html:

```<code>testing...
<div routeLink="x" routerLinkActive="active">
  Click
</div>
<router-outlet></router-outlet>
</code>```

app.route.ts:

```<code>    import {Component, NgModule} from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

@Component({
  selector: 'x',
  templateUrl: './route.html'
})

export class X{

}

const routes1: Routes = [
    {path : '', redirectTo: '/x', pathMatch: 'full'},
    {path : 'x', component: X}
  ]

@NgModule({
  imports:      [ RouterModule.forRoot(routes1) ],
  exports: [RouterModule]
})
export class AppRoutingModule{

}
</code>```

Please find working example very close to your requirement below:
https://plnkr.co/edit/xA8jU4QYDGxzohNg5NFj?p=preview

Title: Why doesn't app.component.html render?

Body:
I have the following Angular plnkr.co: https://plnkr.co/edit/xA8jU4QYDGxzohNg5NFj?p=preview.

//app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html'
})
export class AppComponent { name = 'Angular'; }

//app.component.html

testing...
<router-outlet></router-outlet>

The oputput in the browser is:

Loading AppComponent content here ...

Why doesn't it see the app.component.html file? Or is this some other issue?

Body:
Here you were missing correct routing implementation several errors are there in console please refer to them.

app.component.html:

testing...
<div routeLink="x" routerLinkActive="active">
  Click
</div>
<router-outlet></router-outlet>

app.route.ts:

    import {Component, NgModule} from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

@Component({
  selector: 'x',
  templateUrl: './route.html'
})

export class X{

}

const routes1: Routes = [
    {path : '', redirectTo: '/x', pathMatch: 'full'},
    {path : 'x', component: X}
  ]

@NgModule({
  imports:      [ RouterModule.forRoot(routes1) ],
  exports: [RouterModule]
})
export class AppRoutingModule{

}

Please find working example very close to your requirement below:
https://plnkr.co/edit/xA8jU4QYDGxzohNg5NFj?p=preview


问:
Qt C++ using constraints in function templates
Using Qt I tried to declare function template for calculate some values only for quint8, quint16 and quint32.
I wrote:

```<code>template<typename T>
concept CrcCompatible = typeid(T) == typeid(quint8) || typeid(T) == typeid(quint16) || typeid(T) == typeid(quint32);

template<typename T> requires CrcCompatible<T>
T crc(T initial, T polynomial, T *pcBlock, T len, bool isFinalXor);
</code>```

Butconcept and requires keywords doesn't highlighted as part of the syntax. When I try compile this code folowing errors occured:

```<code>concept does not name a type
...
requires does not name a type
</code>```

I try use templates in Qt very first time. I doesn't understand how to fix this error, and why compiler can't understand keywords.

In project file I add QMAKE_CXXFLAGS += -std=c++11 and CONFIG += c++11
but nothing changed.

I can't understand what I should ask in google, so I couldn't find answer...

答: I guess the problem is that concepts are not supported in C++11. From what I can see in documentation, the concepts will only be available in C++20. Anyway, if the are supported by some compiller right now you should enable this support by some other flag than --std=c++11.

Body:
Using Qt I tried to declare function template for calculate some values only for quint8, quint16 and quint32.
I wrote:

template<typename T>
concept CrcCompatible = typeid(T) == typeid(quint8) || typeid(T) == typeid(quint16) || typeid(T) == typeid(quint32);

template<typename T> requires CrcCompatible<T>
T crc(T initial, T polynomial, T *pcBlock, T len, bool isFinalXor);

Butconcept and requires keywords doesn't highlighted as part of the syntax. When I try compile this code folowing errors occured:

concept does not name a type
...
requires does not name a type

I try use templates in Qt very first time. I doesn't understand how to fix this error, and why compiler can't understand keywords.

In project file I add QMAKE_CXXFLAGS += -std=c++11 and CONFIG += c++11
but nothing changed.

I can't understand what I should ask in google, so I couldn't find answer...


答:
Try to add align-self-end class to the div with col class

```

Title: Bootstrap 4 aligning row to the bottom of a container

Body:
How do I align a bootstrap row to the bottom of a container?

Like this:

HTML

        LukeBank

      <button type="button" class="btn btn-outline-light">Button</button>

CSS

html, body {
  height: 100%;
  width: 100%;
}

main {
  height: 100%;
  background-image: url(/img/frontpage.bg.jpg);
  background-position: center center;
  background-size: cover;
}

.otherpart {
  height: 100%;
  background-color: white;
  background-position: center bottom;
  background-size: cover;
}

I tried to use .align-bottom, but it didn't work.

Body:
Try to add align-self-end class to the div with col class

<div class="col align-self-center">


问:
Method return statement vs try-catch
As far as I know in Java errors can be reported in two ways: return values and exceptions.

For example, code below:

int methodName(int i, int j) {
    int result;

    try {
        result =  i / j;
        return result;
        // in the case of j = 0, ArtithmeticException() will be thrown
    }
    catch (Exception e) {
        System.out.println("Some message");
    }

    //return result;
}
```

In the case of j = 0, an exception will be thrown and caught (by the catch), and "Some message" will be printed.

The question is: If I do not want to return any result from this method in the case of a divide by zero, MUST I return some value or there is another way? I.e. using a 'throw' in the catch clause?

And another observation: if I uncomment the last 'return result' statement I get the error message:

variable result might not have been initialized

And if I comment last 'return result' I get the error message:

missing return statement

But I've already included the return statement in the try clause.

Thanks!

答:
One thing that you are probably observing is the scope of the variable.

When one wants to call a void method so that its returning nothing; yet, still have it changing the values of a variable, one can put the variable they want changed in the global scope.

An example of how this looks is demo below:

```<code>public class MyClassName{
    //global scope int
    public static int result;
    //main method
    public static void main(String[] args){
        //Let's see what we start at
        System.out.println("By default im at: " + result);
        //Attempt to set global variable as the result of a 0 division
        methodName(1,0);
        System.out.println("I tried to divide by zero but I'm still at: "+result);
        //Attempt to perform normal calculation 25/5
        methodName(25, 5);
        System.out.println("25 divided by 5 is: "+result);
    }
    //method that changes global variable - void means it returns nothing
    public static void methodName(int i, int j) {
            try {
                //try 1 / 0
                result =  i / j;
            }
            catch (Exception e) {
                System.out.println("CATCH:I failed to divide by zero.");
            }
        }
}
</code>```

Output:

```<code>By default im at: 0
CATCH:I failed to divide by zero.
I tried to divide by zero but I'm still at: 0
25 divided by 5 is: 5
</code>```

Please note the positioning of the global variable, outside the main method.
In this example, the value of the variable result is still changed, but is not necessarily returned.

Title: Method return statement vs try-catch

Body:
As far as I know in Java errors can be reported in two ways: return values and exceptions.

For example, code below:

int methodName(int i, int j) {
    int result;

    try {
        result =  i / j;
        return result;
        // in the case of j = 0, ArtithmeticException() will be thrown
    }
    catch (Exception e) {
        System.out.println("Some message");
    }

    //return result;
}

In the case of j = 0, an exception will be thrown and caught (by the catch), and "Some message" will be printed.

The question is: If I do not want to return any result from this method in the case of a divide by zero, MUST I return some value or there is another way? I.e. using a 'throw' in the catch clause?

And another observation: if I uncomment the last 'return result' statement I get the error message:

variable result might not have been initialized

And if I comment last 'return result' I get the error message:

missing return statement

But I've already included the return statement in the try clause.

Thanks!

Body:
One thing that you are probably observing is the scope of the variable.

When one wants to call a void method so that its returning nothing; yet, still have it changing the values of a variable, one can put the variable they want changed in the global scope.

An example of how this looks is demo below:

public class MyClassName{
    //global scope int
    public static int result;
    //main method
    public static void main(String[] args){
        //Let's see what we start at
        System.out.println("By default im at: " + result);
        //Attempt to set global variable as the result of a 0 division
        methodName(1,0);
        System.out.println("I tried to divide by zero but I'm still at: "+result);
        //Attempt to perform normal calculation 25/5
        methodName(25, 5);
        System.out.println("25 divided by 5 is: "+result);
    }
    //method that changes global variable - void means it returns nothing
    public static void methodName(int i, int j) {
            try {
                //try 1 / 0
                result =  i / j;
            }
            catch (Exception e) {
                System.out.println("CATCH:I failed to divide by zero.");
            }
        }
}

Output:

By default im at: 0
CATCH:I failed to divide by zero.
I tried to divide by zero but I'm still at: 0
25 divided by 5 is: 5

Please note the positioning of the global variable, outside the main method.
In this example, the value of the variable result is still changed, but is not necessarily returned.


问:
Undo set-branches on git remote
I've currently set up my git remote to restrict which branches are fetched:

```<code>git remote set-branches myOrigin myBranch
</code>```

This adds the proper entries to .git/config:

```<code>[remote "myOrigin"]
    fetch = +refs/heads/myBranch:refs/remotes/myOrigin/myBranch
</code>```

Now I want to undo this, and go back to the default configuration:

```<code>[remote "myOrigin"]
    fetch = +refs/heads/*:refs/remotes/myOrigin/*
</code>```

How can I do this without manually modifying my .git/config? Is there a git command I can run?

答:
One of the solutions:</p>

```<code>git config remote.myOrigin.fetch +refs/heads/*:refs/remotes/myOrigin/*
</code>```

Title: Undo set-branches on git remote

Body:
I've currently set up my git remote to restrict which branches are fetched:

git remote set-branches myOrigin myBranch

This adds the proper entries to .git/config:

[remote "myOrigin"]
    fetch = +refs/heads/myBranch:refs/remotes/myOrigin/myBranch

Now I want to undo this, and go back to the default configuration:

[remote "myOrigin"]
    fetch = +refs/heads/*:refs/remotes/myOrigin/*

How can I do this without manually modifying my .git/config? Is there a git command I can run?

Body:
One of the solutions:

git config remote.myOrigin.fetch +refs/heads/*:refs/remotes/myOrigin/*


问:
Is there any way to get resque-web to work with Redis To Go hosted redis instance?
Is there any way to get resque-web to work with a Redis To Go hosted redis instance?

UPDATE:

@Nemo157's suggestion was correct. Ended up creating a test-evn.rb containing:

```<code>uri = URI.parse(" redis://XXXX@catfish.redistogo.com:9122")
Resque.redis = Redis.new(:host => uri.host, :port => uri.port, :password => uri.password)
</code>```

答:
Pass it the config file you're using to setup redis in the app, e.g.

```<code>resque-web ./environment.rb
</code>```

where environment.rb contains something like:

```<code>Resque.redis = Redis.new(:host => "path.to.host", :port => 6379)
</code>```

Note: I haven't tested this since all my redis instances have been on localhost, but that's my understanding of how it works.

Body:
Is there any way to get resque-web to work with a Redis To Go hosted redis instance?

UPDATE:

@Nemo157's suggestion was correct. Ended up creating a test-evn.rb containing:

uri = URI.parse(" redis://XXXX@catfish.redistogo.com:9122")
Resque.redis = Redis.new(:host => uri.host, :port => uri.port, :password => uri.password)

Body:
Pass it the config file you're using to setup redis in the app, e.g.

resque-web ./environment.rb

where environment.rb contains something like:

Resque.redis = Redis.new(:host => "path.to.host", :port => 6379)

Note: I haven't tested this since all my redis instances have been on localhost, but that's my understanding of how it works.


答:
I think you are confusing this behavior:

```<code>blabla = Classname().somefunctions()
</code>```

Which is assigning the value returned by calling the method somefunctions() located in class Classname() to the variable blabla

with the chaining of two functions in the numpy module:

The first a = np.arange(15) creates and array of size 15, and assigns it to a variable named a, and:

the second a.reshape(3, 5) that reshapes the array a to an array of 3 arrays containing 5 elements each.

```<code>import numpy as np
a = np.arange(15)    #-> [ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14]
a = a.reshape(3, 5)  #-> [[ 0  1  2  3  4] [ 5  6  7  8  9] [10 11 12 13 14]]
print(a)
</code>```

Title: can somebody explain what exactly is going on with python functions?

Body:
what i know in python is i can write something like this

blabla = Classname().somefunctions()

but in this case both the "np.arange" and "reshape" are functions and it confuses me because  "np.arange" is a function and is treated like a class.   the question is how is this possible??

import numpy as np
a = np.arange(15).reshape(3, 5)
print(a)

Body:
I think you are confusing this behavior:

blabla = Classname().somefunctions()

Which is assigning the value returned by calling the method somefunctions() located in class Classname() to the variable blabla

with the chaining of two functions in the numpy module:

The first a = np.arange(15) creates and array of size 15, and assigns it to a variable named a, and:

the second a.reshape(3, 5) that reshapes the array a to an array of 3 arrays containing 5 elements each.

import numpy as np
a = np.arange(15)    #-> [ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14]
a = a.reshape(3, 5)  #-> [[ 0  1  2  3  4] [ 5  6  7  8  9] [10 11 12 13 14]]
print(a)


问:
mysqlclient 1.3.3 or newer is required; you have 0.7.11.None
I'm using python version 3.6.3 and django version 2.0.1.

I got the result below when I entered py manage.py migrate in cmd.

(mysqlclient 1.3.3 or newer is required; you have 0.7.11.None)

I was trying to link a mysql database to my django project.

```<code>init.py codes:

import pymysql
pymysql.install_as_MySQLdb()

settings.py codes:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': os.path.join(BASE_DIR, 'mysite'),
        'USER': 'root',
        'PASSWORD': '',
        'HOST': 'localhost',
        'PORT': '8000',
    }
}
</code>```

答:
remove your code

```<code>#import pymysql
#pymysql.install_as_MySQLdb()
</code>```

install python package "mysqlclient"

```<code>pip install mysqlclient
</code>```

Body:
I'm using python version 3.6.3 and django version 2.0.1.

I got the result below when I entered py manage.py migrate in cmd.

(mysqlclient 1.3.3 or newer is required; you have 0.7.11.None)

I was trying to link a mysql database to my django project.

init.py codes:

import pymysql
pymysql.install_as_MySQLdb()

settings.py codes:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': os.path.join(BASE_DIR, 'mysite'),
        'USER': 'root',
        'PASSWORD': '',
        'HOST': 'localhost',
        'PORT': '8000',
    }
}

Body:
remove your code

#import pymysql
#pymysql.install_as_MySQLdb()

install python package "mysqlclient"

pip install mysqlclient


问:
Dapper UpdateAsync ignore column
I am trying to update with Dapper.Contrib this table:

```<code>public class MyTable
{
    public int ID { get; set; }
    public int SomeColumn1 { get; set; }
    public int SomeColumn2 { get; set; }
    public int CreateUserID { get; set; }
    public int UpdateUserID { get; set; }
}
</code>```

I don't want to update the CreateUserID column because it is an update method so that I want to ignore this column while calling the Dapper - Update.Async(entity) method.

I tried using [NotMapped] and [UpdateIgnore] attributes but no help.

Note: I still want this column to be passed on insert operations, therefore, [Computed] and [Write(false)] is not appropriate.

Can someone help me figure out how to ignore this column when updating the table in the database?

答:
As @Evk already mentioned in his answer, there is no solution implemented yet. He have also mentioned the workarounds.

Apart from that, you can choose to use Dapper (IDbConnection.Execute(...)) directly bypassing Dapper.Contrib for this particular case.

I had a similar problem (with DapperExtensions though) with particular column update and other complex queries those DapperExtensions either cannot generate at all or need much work to make it happen with it.

I used Dapper directly instead of DapperExtensions for that particular case; other part of project still take benefit of DapperExtensions. This is like tread-off. Such cases are very limited. I found this is better solution instead of tweaking/forcing DapperExtensions for this. This also saved me on time and efforts.

Title: Dapper UpdateAsync ignore column

Body:
I am trying to update with Dapper.Contrib this table:

public class MyTable
{
    public int ID { get; set; }
    public int SomeColumn1 { get; set; }
    public int SomeColumn2 { get; set; }
    public int CreateUserID { get; set; }
    public int UpdateUserID { get; set; }
}

I don't want to update the CreateUserID column because it is an update method so that I want to ignore this column while calling the Dapper - Update.Async(entity) method.

I tried using [NotMapped] and [UpdateIgnore] attributes but no help.

Note: I still want this column to be passed on insert operations, therefore, [Computed] and [Write(false)] is not appropriate.

Can someone help me figure out how to ignore this column when updating the table in the database?


答:
numpy.arange returns an ndarray object.

What may have been confusing though is that numpy.reshape is a classmethod that takes an array as an input. However there is an equivalent method numpy.ndarray.reshape that is a method available to ndarray objects. In your case, it is the latter method that has been used.


问:
why is flash media server taking so long to load large files
We purchased FMIS and we are encoding large 15+ hour MP4 recordings using flash media encoder. When opening these large files for playback, which have not been opened recently  the player displays the loading indicator for up to 4 minutes! Once it has apparently been cached on the server it opens immediately from any browser even after clearing local browser cache. So a few questions for the experts

Why is it taking so long to load the file. Is it because the MP4 metadata is in the wrong format and the file is so huge? I read somewhere that Media Encoder records with incorrect MP4 metadata is that still the case?

Once its cached on the server, exactly how much of it is cached. Some of these files are larger than 500mb.

What fms settings do you suggest I change. FMIS is running on windows server R2 64 bit, but FMIS itself is 32 bit. We have not upgraded to the 64 bit version. We have 8GB of ram. Is it OK to set FMS cache to 3GB. And would that only have enough room for 3-4 large files, because we have hundreds of them.

best,

Tuviah

答:
Adobe answered it as follows

MP4 is a fine format, and I won't speak ill of it, but it does have weaknesses.  In FMS implementation those weaknesses tend to manifest around the combination of recording and very large files, so some of these things are a known issue.

The problem is that MP4 recording is achieved through what's called MP4 fragmentation.  It's a part of the MP4 spec that not every vendor supports, but has a very particular purpose, namely the ability to continually grow an MP4 style file efficiently.  Without fragments one has the problem that a large file must be constantly rewritten as a whole for updating the MOOV box (index of files) - fragments allow simple appending.  In other words it's tricky to make mp4 recording scalable (like for a server  ) and still have the basic MP4 format - so fragments.

There's a tradeoff to this however, in that the index of the file is broken up over the whole file.  Also likely these large files are tucked away on a NAS for you or something similar.  Normal as you likely can't store all of them locally.  However that has the bad combo of needing to index the file (touching parts of the whole thing) and doing network reads to do it.  This is likely the cause of the long delay you're facing - here are some things you can do to help.

Post process the F4V/MP4 files into non fragmented format - this may help significantly in load time, though it could still be considered slow it should increase in speed.  Cheap to try it out on a few files. (F4V and MP4 are the same thing for this purpose - so don't worry about the tool naming)

http://www.adobe.com/products/flashmediaserver/tool_downloads/

Alternatively this is why we created the raw: format.  For long recording mp4 is just unideal and raw format solves many of the problems involved in doing this kind of recording.  Check it out

http://help.adobe.com/en_US/flashmediaserver/devguide/WSecdb3a64785bec8751534fae12a16ad0277-8000.html

You may also want to check out FMS HTTP Dynamic Streaming - it also solves this problem, along with others like content protection and DVR and it's our most recent offering in tech, so it has a lot of strengths the other areas don't.

http://www.adobe.com/products/httpdynamicstreaming/


问:
Deploying to appEngine auth
I use the following command to deploy a java app to AppEngine standard for the first time:

```<code>mvn appengine:update
</code>```

Then I get an output saying I should use the following use the following url to authenticate. Pressing the URL opens the web browser and displays the following:

What application and where should I switch to?

答: I needed to copy the code (more like hash) into the console I was using to deploy.</p>

Title: Deploying to appEngine auth

Body:
I use the following command to deploy a java app to AppEngine standard for the first time:

mvn appengine:update

Then I get an output saying I should use the following use the following url to authenticate. Pressing the URL opens the web browser and displays the following:

What application and where should I switch to?


问:
React native router flux go back to root scene
In my current scene stack, I have 3 scenes A,B and C.
Going back and forth from A to B to C works fine. But I couldn't navigate back to scene A directly from scene C.
Is this possible?
My current code looks like this:

```<code><Scene key="root">
  <Scene key="aKey" component={A} />
  <Scene key="bKey" component={B} />
  <Scene key="cKey" component={C} />
</Scene>
</code>```

So far, I've tried adding this code in my C component:

```<code>Actions.pop
</code>```

But it only navigates back to previous scene(i.e. B component) and I am trying to navigate back directly to root scene (i.e. A component)

答:
As Rahul mentioned, one way of doing it is

```<code>Actions.reset('aKey')
</code>```

The other approach that I figured out is

```<code>Actions.popTo('aKey')
</code>```

Body:
In my current scene stack, I have 3 scenes A,B and C.
Going back and forth from A to B to C works fine. But I couldn't navigate back to scene A directly from scene C.
Is this possible?
My current code looks like this:

<Scene key="root">
  <Scene key="aKey" component={A} />
  <Scene key="bKey" component={B} />
  <Scene key="cKey" component={C} />
</Scene>

So far, I've tried adding this code in my C component:

Actions.pop

But it only navigates back to previous scene(i.e. B component) and I am trying to navigate back directly to root scene (i.e. A component)

Body:
As Rahul mentioned, one way of doing it is

Actions.reset('aKey')

The other approach that I figured out is

Actions.popTo('aKey')