问:
First argument in form cannot contain nil or be empty (rails 5)
I've been following the rails blog tutorial (you know, that one ) and i've come to a point where every time i reference @articles on the update form, rails takes it as a nil, it says:

First argument in form cannot contain nil or be empty

Here's the form

```<code><h1>Edit article</h1>

<%= form_for @article do |f| %>

  <% if @article.errors.any? %>
    <div id="error_explanation">
      <h2>
        <%= pluralize(@article.errors.count, "error") %> prohibited
        this article from being saved:
      </h2>
      <ul>
        <% @article.errors.full_messages.each do |msg| %>
          <li><%= msg %></li>
        <% end %>
      </ul>
    </div>
  <% end %>

  <p>
    <%= f.label :title %><br>
    <%= f.text_field :title %>
  </p>

  <p>
    <%= f.label :text %><br>
    <%= f.text_area :text %>
  </p>

  <p>
    <%= f.submit %>
  </p>

<% end %>

<%= link_to 'Back', articles_path %>
</code>```

And the controller for the articles:

```<code>class ArticlesController < ApplicationController
  def new
    @article = Article.new
  end

  def create
    @article = Article.new(article_params)

    if  @article.save
    redirect_to @article
    else
    render 'new'
    end
  end

  def show
    @article = Article.find(params[:id])
  end

  def index
    @articles = Article.all
  end

  def update
    @article = Article.find(params[:id])

    if @article.update(article_params)
      redirect_to @article
    else
      render 'edit'
    end
  end

  private
    def article_params
      params.require(:article).permit(:title, :text)
    end
end
</code>```

答:
It does not look like you have an edit method in your Articles controller.

```<code>def edit
  @article = Article.find(params[:id])
end
</code>```

Just so it is clear.  The edit method is what is called with the GET route that shows the form.  Update is the PATCH/PUT route that takes the form in and updates the record.  So, the form is shown by the edit method via GET, and processed by the update method via PUT/PATCH.

Body:
I've been following the rails blog tutorial (you know, that one ) and i've come to a point where every time i reference @articles on the update form, rails takes it as a nil, it says:

First argument in form cannot contain nil or be empty

Here's the form

Edit article

<%= form_for @article do |f| %>

  <% if @article.errors.any? %>

        <%= pluralize(@article.errors.count, "error") %> prohibited
        this article from being saved:

        <% @article.errors.full_messages.each do |msg| %>

<%= msg %>

        <% end %>

  <% end %>

    <%= f.label :title %>

    <%= f.text_field :title %>

    <%= f.label :text %>

    <%= f.text_area :text %>

    <%= f.submit %>

<% end %>

<%= link_to 'Back', articles_path %>

And the controller for the articles:

class ArticlesController < ApplicationController
  def new
    @article = Article.new
  end

  def create
    @article = Article.new(article_params)

    if  @article.save
    redirect_to @article
    else
    render 'new'
    end
  end

  def show
    @article = Article.find(params[:id])
  end

  def index
    @articles = Article.all
  end

  def update
    @article = Article.find(params[:id])

    if @article.update(article_params)
      redirect_to @article
    else
      render 'edit'
    end
  end

  private
    def article_params
      params.require(:article).permit(:title, :text)
    end
end

Body:
It does not look like you have an edit method in your Articles controller.

def edit
  @article = Article.find(params[:id])
end

Just so it is clear.  The edit method is what is called with the GET route that shows the form.  Update is the PATCH/PUT route that takes the form in and updates the record.  So, the form is shown by the edit method via GET, and processed by the update method via PUT/PATCH.


来源: stackexchange

问:
Change Linux Bridge to Openvswitch in OpenWRT
I'm trying to change linux bridge in openwrt with openvswitch, with I compile openwrt with openvswitch package for tp-link tlwr1043nd, it's done... the problem is when I delete the br-lan (linux brige) and replace it with openvswitch, it's always error and bricked

This is the script that I use to change to ovs :
I run this with ((/root/ovs-tplink.sh > /dev/null 2&>1)&)& so that can be running in background,

```<code>#!/bin/sh
OVS_BR=ovslan
#IP Controller, Port for OvS Manager, Linux Bridge
IP_CONTROLLER=192.168.0.100
PORT_CONTROLLER=6633
LINUX_BRIDGE=br-lan
echo -e "\033[0;32m Declare Necessary Variable Successful"
# Add Bridge Open vSwitch
ovs-vsctl --may-exist add-br $OVS_BR
echo -e "\033[0;32m Add OvS Bridge $OVS_BR Succesful"
sleep 2
#Delete Port if added to $LINUX_BRIDGE
for i in eth0.1 eth0.2 eth0.3 eth0.4 eth0.5 eth0.6
do
  brctl delif $LINUX_BRIDGE $i
  echo -e "\033[0;32m Delete Port $i in $LINUX_BRIDGE successful"
  sleep 1
done
# Add Port to Bridge
for i in eth0.1 eth0.2 eth0.3 eth0.4 eth0.5 eth0.6 wlan0
do
  ovs-vsctl --may-exist add-port $OVS_BR $i
  echo -e "\033[0;32m Add OvS Port $i to $OVS_BR successful"
  sleep 1
done
# Up The Interface
for i in eth0.1 eth0.2 eth0.3 eth0.4 eth0.5 eth0.6 wlan0 ovslan
do
  ifconfig $i up
  echo -e "\033[0;32m Up interface $i"
  sleep 1
done
#Set All Options Necessary for Controller
ovs-vsctl set bridge $OVS_BR stp_enable=true
echo -e "\033[0;32m Set STP Enabled True in $OVS_BR Successful"
sleep 1
ovs-vsctl set-controller $OVS_BR tcp:$IP_CONTROLLER:$PORT_CONTROLLER
echo -e "\033[0;32m Set IP:$IP_CONTROLLER as Controller in $OVS_BR and Successful"
sleep 1
ovs-vsctl set-fail-mode $OVS_BR standalone
echo -e "\033[0;32m Set Standalone Mode in $OVS_BR and Successful"
sleep 1
ovs-vsctl set bridge $OVS_BR protocols=OpenFlow13
echo -e "\033[0;32m Set OpenFlow Protocol to 1.3 in $OVS_BR Successful"
sleep 1
ovs-vsctl set-manager ptcp:6640
sleep 1
ovs-ofctl del-flows $OVS_BR
echo -e "\033[0;32m Delete Previous Flows in $OVS_BR and Successful"
sleep 1
echo -e "\033[0;32m Restart Network Service. . . . . . "
/etc/init.d/network restart
echo -e "\033[0;32m Restart Network Service Successful"
# Check Result
echo -e "\033[0;32m Result : "
ovs-vsctl show
echo " "
reboot
exit 0
</code>```

And this is the network configuration in /etc/config/network:

```<code>config interface 'loopback'
    option ifname 'lo'
    option proto 'static'
    option ipaddr '127.0.0.1'
    option netmask '255.0.0.0'

config globals 'globals'
    option ula_prefix 'fded:6c7d:48c4::/48'

config interface 'lan'
    option type 'bridge'
    option ifname 'eth0.1 eth0.2 eth0.3 eth0.4 eth0.5 eth0.6'
    option proto 'static'
    option ipaddr '192.168.0.110'
    option netmask '255.255.255.0'
    option gateway '192.168.0.1'

config interface 'ovslan'
    option ifname 'ovslan'
    option proto 'static'
    option ipaddr '192.168.0.111'
    option netmask '255.255.255.0'
    option gateway '192.168.0.1'

config interface 'eth0_1'
    option ifname 'eth0.1'
    option proto 'static'

config interface 'wan'
    option ifname 'ovs-wan'
    option proto 'dhcp'

config interface 'eth0_2'
    option ifname 'eth0.2'
    option proto 'dhcp'

config interface 'ovs1'
    option proto 'static'
    option ifname 'eth0.3'
    option proto 'dhcp'

config interface 'ovs2'
    option proto 'static'
    option ifname 'eth0.4'
    option proto 'dhcp'

config interface 'ovs3'
    option proto 'static'
    option ifname 'eth0.5'
    option proto 'dhcp'

config interface 'ovs4'
    option proto 'static'
    option ifname 'eth0.6'
    option proto 'dhcp'

config switch
    option name 'switch0'
    option reset '1'
    option enable_vlan '1'

config switch_vlan
    option device 'switch0'
    option vlan '1'
    option ports '0t 6'
    option vid '1'

config switch_vlan
    option device 'switch0'
    option vlan '2'
    option ports '0t 5'
    option vid '2'

config switch_vlan
    option device 'switch0'
    option vlan '3'
    option vid '3'
    option ports '0t 4'

config switch_vlan
    option device 'switch0'
    option vlan '4'
    option vid '4'
    option ports '0t 3'

config switch_vlan
    option device 'switch0'
    option vlan '5'
    option vid '5'
    option ports '0t 2'

config switch_vlan
    option device 'switch0'
    option vlan '6'
    option vid '6'
    option ports '0t 1'
</code>```

I use ovslan to give statistic IP when using openvswitch bridge,
Please help me fix this everyone...

thanks for the answer...

答:
[Solved]
The script is fine, just edit manually the lan configuration via ssh with nano or vi /etc/config/network to be like this :

```<code>config interface 'lan'
    #option type 'bridge' <= delete this
    #option ifname 'eth0.1 eth0.2 eth0.3 eth0.4 eth0.5 eth0.6' <= edit
    option ifname 'ovslan' <= add this
    option proto 'static'
    option ipaddr '192.168.0.110'
    option netmask '255.255.255.0'
    option gateway '192.168.0.1'
</code>```

And then run the script above with ((/root/ovs-tplink.sh > /dev/null 2&>1)&)& , wait, and check with ovs-vsctl show

Bassically We :

Add vlan in our network configuration in /etc/config/network

Disabe our firewall and DHCP Server, to use parent configuration in our network because we use openvswitch ( We set Up a dump ap router)

Delete br-lan like above (delete option type 'bridge'), rename ifname with ovs bridge you like

Run the script above :

The script basically tell to :

Add Openvswitch Bridge

Delete port in linux bridge

Add port in to openvswitch

set necessary option in openvswitch

In this case, I use OpenWRT in TP-Link TL-WR1043nd v4, I think this same in v3 or v2,
Thanks everyone,

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to change linux bridge in openwrt with openvswitch, with I compile openwrt with openvswitch package for tp-link tlwr1043nd, it's done... the problem is when I delete the br-lan (linux brige) and replace it with openvswitch, it's always error and bricked

This is the script that I use to change to ovs :
I run this with ((/root/ovs-tplink.sh > /dev/null 2&>1)&)& so that can be running in background,

#!/bin/sh
OVS_BR=ovslan
#IP Controller, Port for OvS Manager, Linux Bridge
IP_CONTROLLER=192.168.0.100
PORT_CONTROLLER=6633
LINUX_BRIDGE=br-lan
echo -e "\033[0;32m Declare Necessary Variable Successful"
# Add Bridge Open vSwitch
ovs-vsctl --may-exist add-br $OVS_BR
echo -e "\033[0;32m Add OvS Bridge $OVS_BR Succesful"
sleep 2
#Delete Port if added to $LINUX_BRIDGE
for i in eth0.1 eth0.2 eth0.3 eth0.4 eth0.5 eth0.6
do
  brctl delif $LINUX_BRIDGE $i
  echo -e "\033[0;32m Delete Port $i in $LINUX_BRIDGE successful"
  sleep 1
done
# Add Port to Bridge
for i in eth0.1 eth0.2 eth0.3 eth0.4 eth0.5 eth0.6 wlan0
do
  ovs-vsctl --may-exist add-port $OVS_BR $i
  echo -e "\033[0;32m Add OvS Port $i to $OVS_BR successful"
  sleep 1
done
# Up The Interface
for i in eth0.1 eth0.2 eth0.3 eth0.4 eth0.5 eth0.6 wlan0 ovslan
do
  ifconfig $i up
  echo -e "\033[0;32m Up interface $i"
  sleep 1
done
#Set All Options Necessary for Controller
ovs-vsctl set bridge $OVS_BR stp_enable=true
echo -e "\033[0;32m Set STP Enabled True in $OVS_BR Successful"
sleep 1
ovs-vsctl set-controller $OVS_BR tcp:$IP_CONTROLLER:$PORT_CONTROLLER
echo -e "\033[0;32m Set IP:$IP_CONTROLLER as Controller in $OVS_BR and Successful"
sleep 1
ovs-vsctl set-fail-mode $OVS_BR standalone
echo -e "\033[0;32m Set Standalone Mode in $OVS_BR and Successful"
sleep 1
ovs-vsctl set bridge $OVS_BR protocols=OpenFlow13
echo -e "\033[0;32m Set OpenFlow Protocol to 1.3 in $OVS_BR Successful"
sleep 1
ovs-vsctl set-manager ptcp:6640
sleep 1
ovs-ofctl del-flows $OVS_BR
echo -e "\033[0;32m Delete Previous Flows in $OVS_BR and Successful"
sleep 1
echo -e "\033[0;32m Restart Network Service. . . . . . "
/etc/init.d/network restart
echo -e "\033[0;32m Restart Network Service Successful"
# Check Result
echo -e "\033[0;32m Result : "
ovs-vsctl show
echo " "
reboot
exit 0

And this is the network configuration in /etc/config/network:

config interface 'loopback'
    option ifname 'lo'
    option proto 'static'
    option ipaddr '127.0.0.1'
    option netmask '255.0.0.0'

config globals 'globals'
    option ula_prefix 'fded:6c7d:48c4::/48'

config interface 'lan'
    option type 'bridge'
    option ifname 'eth0.1 eth0.2 eth0.3 eth0.4 eth0.5 eth0.6'
    option proto 'static'
    option ipaddr '192.168.0.110'
    option netmask '255.255.255.0'
    option gateway '192.168.0.1'

config interface 'ovslan'
    option ifname 'ovslan'
    option proto 'static'
    option ipaddr '192.168.0.111'
    option netmask '255.255.255.0'
    option gateway '192.168.0.1'

config interface 'eth0_1'
    option ifname 'eth0.1'
    option proto 'static'

config interface 'wan'
    option ifname 'ovs-wan'
    option proto 'dhcp'

config interface 'eth0_2'
    option ifname 'eth0.2'
    option proto 'dhcp'

config interface 'ovs1'
    option proto 'static'
    option ifname 'eth0.3'
    option proto 'dhcp'

config interface 'ovs2'
    option proto 'static'
    option ifname 'eth0.4'
    option proto 'dhcp'

config interface 'ovs3'
    option proto 'static'
    option ifname 'eth0.5'
    option proto 'dhcp'

config interface 'ovs4'
    option proto 'static'
    option ifname 'eth0.6'
    option proto 'dhcp'

config switch
    option name 'switch0'
    option reset '1'
    option enable_vlan '1'

config switch_vlan
    option device 'switch0'
    option vlan '1'
    option ports '0t 6'
    option vid '1'

config switch_vlan
    option device 'switch0'
    option vlan '2'
    option ports '0t 5'
    option vid '2'

config switch_vlan
    option device 'switch0'
    option vlan '3'
    option vid '3'
    option ports '0t 4'

config switch_vlan
    option device 'switch0'
    option vlan '4'
    option vid '4'
    option ports '0t 3'

config switch_vlan
    option device 'switch0'
    option vlan '5'
    option vid '5'
    option ports '0t 2'

config switch_vlan
    option device 'switch0'
    option vlan '6'
    option vid '6'
    option ports '0t 1'

I use ovslan to give statistic IP when using openvswitch bridge,
Please help me fix this everyone...

thanks for the answer...

Body:
[Solved]
The script is fine, just edit manually the lan configuration via ssh with nano or vi /etc/config/network to be like this :

config interface 'lan'
    #option type 'bridge' <= delete this
    #option ifname 'eth0.1 eth0.2 eth0.3 eth0.4 eth0.5 eth0.6' <= edit
    option ifname 'ovslan' <= add this
    option proto 'static'
    option ipaddr '192.168.0.110'
    option netmask '255.255.255.0'
    option gateway '192.168.0.1'

And then run the script above with ((/root/ovs-tplink.sh > /dev/null 2&>1)&)& , wait, and check with ovs-vsctl show

Bassically We :

Add vlan in our network configuration in /etc/config/network

Disabe our firewall and DHCP Server, to use parent configuration in our network because we use openvswitch ( We set Up a dump ap router)

Delete br-lan like above (delete option type 'bridge'), rename ifname with ovs bridge you like

Run the script above :

The script basically tell to :

Add Openvswitch Bridge

Delete port in linux bridge

Add port in to openvswitch

set necessary option in openvswitch

In this case, I use OpenWRT in TP-Link TL-WR1043nd v4, I think this same in v3 or v2,
Thanks everyone,


问:
Parameter Paradox? (not sure how to word)
So I'm not sure how to word this so I'll just give an example here:

```<code>public class test {
    private Object1 o1;
    private Object2 o2;
    private Object3 o3;

    public test() {
        o1 = new Object1(o2, o3);
        o2 = new Object2(o1);
        o3 = new Object3(o1);
    }
}
</code>```

So my problem is that I need to give these 3 objects parameters these ways and I get problems because when I put o2 and o3 for o1, they are null. If I try to instantiate o2 and o3 above o1, o1 is null and problems occur again. Could someone help me find a solution to this. I would also like to keep these 3 objects separate (ie. not give o2 or o3 an o1 field).

答:
Simple solution of this problem is to use method to initiate instead of constructor.

Define methods let's say init & use the default constructor or no argument constructor. Now create all the objects & call the method init on all the objects in proper sequence.

You can do one more thing here. Let's see...

You can define constructor with two argument & define method instead of one argument constructor & call that method from the two argument constructor.
 First of all define init method in Object2 & Object3. Constructor of Object1..

```<code>Object1(Object2 o2, Object3 o3){
    //Some code
    o2.init(this);
    o3.init(this);
    //Some code
}
</code>```

Now your code to create objects looks like...

```<code>public class test {
    private Object1 o1;
    private Object2 o2;
    private Object3 o3;
    public test() {
        o2 = new Object2();
        o3 = new Object3();
        o1 = new Object1(o2, o3);
    }
}
</code>```

Body:
So I'm not sure how to word this so I'll just give an example here:

public class test {
    private Object1 o1;
    private Object2 o2;
    private Object3 o3;

    public test() {
        o1 = new Object1(o2, o3);
        o2 = new Object2(o1);
        o3 = new Object3(o1);
    }
}

So my problem is that I need to give these 3 objects parameters these ways and I get problems because when I put o2 and o3 for o1, they are null. If I try to instantiate o2 and o3 above o1, o1 is null and problems occur again. Could someone help me find a solution to this. I would also like to keep these 3 objects separate (ie. not give o2 or o3 an o1 field).

Body:
Simple solution of this problem is to use method to initiate instead of constructor.

Define methods let's say init & use the default constructor or no argument constructor. Now create all the objects & call the method init on all the objects in proper sequence.

You can do one more thing here. Let's see...

You can define constructor with two argument & define method instead of one argument constructor & call that method from the two argument constructor.
 First of all define init method in Object2 & Object3. Constructor of Object1..

Object1(Object2 o2, Object3 o3){
    //Some code
    o2.init(this);
    o3.init(this);
    //Some code
}

Now your code to create objects looks like...

public class test {
    private Object1 o1;
    private Object2 o2;
    private Object3 o3;
    public test() {
        o2 = new Object2();
        o3 = new Object3();
        o1 = new Object1(o2, o3);
    }
}


问:
Which is better for efficiency? variabels for repeated selectors or more concise selectors
I'm trying to use variables to store static selectors I use more than once in a specific scope.

These vars would be global variables in that they as all the function definitions and event listeners are directly in jquery's $(function(){ }); scope.

I could make some singular items ids, which I believe is the fastest selector, although too many ids can be bad and don't serve when more than one element needs to be selected.

For any non class nor id (rare), I'm using slightly more complex selectors in jQuery or as js traversing the DOM.

For efficiency, is it best to store all repeated selectors in the highest scope where they will be needed, not always global, or for some of the quicker ones like IDs and Classes, should I make new selectors each time?

I've noticed and heard that tagName selectors can be inefficient, should I give those IDs/classes or make a tagName selector once, store it in a var and use that var repeatedly.

This is only concerning static elements and changes to the DOM would require a new selector to include the new elements.

答:
Caching is always better. So var selected = $("#selected") will always be better than selecting it with jquery every time $("#selected").doSomething().

From: https://code.tutsplus.com/tutorials/10-ways-to-instantly-increase-your-jquery-performance--net-5551

As for storing it in higher scope, the efficiency/speed probably depends how often its called. So if it's used lots, put it in higher scope.


问:
Laravel How to make download link only for authenticate user?
I have some files on public directory files folder. I want to send the user the link of a specific file.Right now I'm giving the link by following way.

```<code><a href="{{asset('files/'.$row->file_path)}}">
    <button class="btn btn-success">Download</button>
</a>
</code>```

By which actually user know where my directory is..Can i make the download link that way in which only authenticate user can download the file or i can hide the directory from url?

答:
First, move all the files from the publicly accessible directory to private, for example, to storage_path('private/') folder.

Secondly, create a method that will receive in any way a file name from the URL (decoding it from query, or load from database by id), make authorization / some other things checks, and if it's all right, give it to the client for download.
This can be done as follows: return response()->download($pathToFile);

Then, instead of using asset() with a direct link to the file, give users a link to the route that executes the created method.

Body:
I have some files on public directory files folder. I want to send the user the link of a specific file.Right now I'm giving the link by following way.

file_path)}}">
    <button class="btn btn-success">Download</button>

By which actually user know where my directory is..Can i make the download link that way in which only authenticate user can download the file or i can hide the directory from url?


问:
How to set spring bootstrap.properties at execution time
Is it possible to set the contents of Spring's bootstrap.properties at execution time?

I have a client application for Spring's cloud config which holds a line to point to the config server:

```<code>spring.cloud.config.url = http://localhost:8888
</code>```

And I would like to set this config. I tried setting it like application.properties can be set:

```<code>java -jar ./config-client.jar --spring.cloud.config.url=http://localhost:8888
</code>```

But it didn't work. So my question is, how can I set this property at execution time?

答:
It seems to be caused by wrong properties name. url should be uri.
Try to change your property in bootstrap.properties like below.

```<code>spring.cloud.config.uri = http://localhost:8888
</code>```

And then try again like below.

```<code>java -jar ./config-client.jar --spring.cloud.config.uri=<something else>
</code>```

http://localhost:8888 is the default value of spring.cloud.config.uri. That's probably the reason why you didn't recognize the wrong property name.

Body:
Is it possible to set the contents of Spring's bootstrap.properties at execution time?

I have a client application for Spring's cloud config which holds a line to point to the config server:

spring.cloud.config.url = http://localhost:8888

And I would like to set this config. I tried setting it like application.properties can be set:

java -jar ./config-client.jar --spring.cloud.config.url=http://localhost:8888

But it didn't work. So my question is, how can I set this property at execution time?

Body:
It seems to be caused by wrong properties name. url should be uri.
Try to change your property in bootstrap.properties like below.

spring.cloud.config.uri = http://localhost:8888

And then try again like below.

java -jar ./config-client.jar --spring.cloud.config.uri=<something else>

http://localhost:8888 is the default value of spring.cloud.config.uri. That's probably the reason why you didn't recognize the wrong property name.


问:
How to toggle a view based on a state in vuex?
I have a button <Button> Log me in! </Button>, and I would like to change its css class based on the state of my current vuex app. (state.user is not null)

What is the proper way to write this code?

I can create a field in the state that is the classname of this view and change that accordingly in actions/mutations. But are there better places that I should be placing this logic? As this field is completely component dependent, I don't think it should "leak" out to the global state.

答:
Just use the typical object binding syntax.

```<code><button :class={someClass: !$store.state.user}>Log me in!</button>
</code>```

Or define a getter in Vuex and use that in your class definition.

Body:
Just use the typical object binding syntax.

<button :class={someClass: !$store.state.user}>Log me in!</button>

Or define a getter in Vuex and use that in your class definition.


问:
Extend Scala Set with concrete type
Really struggling to figure out extending the immutable Set with a class that will represent a Set of concrete type.  I'm doing this to try and create a nice DSL.

I'd like to have a class Thing, and when you add 'things' together you get a ThingSet object, which extends Set.

```<code>class Thing(val name:String){
  def +(other: Thing):ThingSet = new ThingSet() + other
}
</code>```

I just can't figure out how to make the ThingSet object.  I know I need to mix in traits like GenericSetTemplate, SetLike etc.  But I just can't make it work.

Please, can anybody give me some pointers, as I can't find anything explicit enough to learn from.  I've tried looking at the BitSet and HashSet implementations, but get lost.

答:
Adapting from this Daily Scala post as well as the source to BitSet, which is a wonderful example here because it is not a parameterized collection, and is rather short and simple.

```<code>import scala.collection.SetLike
import scala.collection.generic.{GenericSetTemplate, GenericCompanion, CanBuildFrom}
import scala.collection.mutable.{Builder, SetBuilder}

class ThingSet(seq : Thing*) extends Set[Thing]
                             with SetLike[Thing, ThingSet]
                             with Serializable {
    override def empty: ThingSet = new ThingSet()
    def + (elem: Thing) : ThingSet = if (seq contains elem) this
        else new ThingSet(elem +: seq: _*)
    def - (elem: Thing) : ThingSet = if (!(seq contains elem)) this
        else new ThingSet(seq filterNot (elem ==): _*)
    def contains (elem: Thing) : Boolean = seq exists (elem ==)
    def iterator : Iterator[Thing] = seq.iterator
}

object ThingSet {
    def empty: ThingSet = new ThingSet()
    def newBuilder: Builder[Thing, ThingSet] = new SetBuilder[Thing, ThingSet](empty)
    def apply(elems: Thing*): ThingSet = (empty /: elems) (_ + _)
    def thingSetCanBuildFrom = new CanBuildFrom[ThingSet, Thing, ThingSet] {
        def apply(from: ThingSet) = newBuilder
        def apply() = newBuilder
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Extend Scala Set with concrete type

Body:
Really struggling to figure out extending the immutable Set with a class that will represent a Set of concrete type.  I'm doing this to try and create a nice DSL.

I'd like to have a class Thing, and when you add 'things' together you get a ThingSet object, which extends Set.

class Thing(val name:String){
  def +(other: Thing):ThingSet = new ThingSet() + other
}

I just can't figure out how to make the ThingSet object.  I know I need to mix in traits like GenericSetTemplate, SetLike etc.  But I just can't make it work.

Please, can anybody give me some pointers, as I can't find anything explicit enough to learn from.  I've tried looking at the BitSet and HashSet implementations, but get lost.

Body:
Adapting from this Daily Scala post as well as the source to BitSet, which is a wonderful example here because it is not a parameterized collection, and is rather short and simple.

import scala.collection.SetLike
import scala.collection.generic.{GenericSetTemplate, GenericCompanion, CanBuildFrom}
import scala.collection.mutable.{Builder, SetBuilder}

class ThingSet(seq : Thing*) extends Set[Thing]
                             with SetLike[Thing, ThingSet]
                             with Serializable {
    override def empty: ThingSet = new ThingSet()
    def + (elem: Thing) : ThingSet = if (seq contains elem) this
        else new ThingSet(elem +: seq: _*)
    def - (elem: Thing) : ThingSet = if (!(seq contains elem)) this
        else new ThingSet(seq filterNot (elem ==): _*)
    def contains (elem: Thing) : Boolean = seq exists (elem ==)
    def iterator : Iterator[Thing] = seq.iterator
}

object ThingSet {
    def empty: ThingSet = new ThingSet()
    def newBuilder: Builder[Thing, ThingSet] = new SetBuilder[Thing, ThingSet](empty)
    def apply(elems: Thing*): ThingSet = (empty /: elems) (_ + _)
    def thingSetCanBuildFrom = new CanBuildFrom[ThingSet, Thing, ThingSet] {
        def apply(from: ThingSet) = newBuilder
        def apply() = newBuilder
    }
}


问:
How do you find the average of three numbers with input and output dialog boxes with JAVA?
I've been playing around with this code for a little bit now and can't seem to find the correct way to sort it out. I used a program without JOptionPane and it worked and tried to use the same sequence but it didn't work. Do I need to add something else? The assignment is to have the user enter 3 integers and print the average with input and output dialog boxes. I've done the average and input/output dialog boxes before but putting it all together is harder than I thought.</p>

```<code>import java.util.Scanner;
import javax.swing.JOptionPane;
import java.text.*;
import java.text.DecimalFormat;
public class Number3
{

  public static void main(String[] args)
  {
    System.out.println("Enter 3 numbers: ");
    Scanner input = new Scanner (System.in);
    DecimalFormat decimalFormat = new DecimalFormat("0.00##");

    int num1;
    int num2;
    int num3;
    double avg;

    num1=input.nextInt();
    num2=input.nextInt();
    num3=input.nextInt();

    avg=(double)(num1+num2+num3)/3.0;
    System.out.println("The average is: " + decimalFormat.format(avg));

  }
}
</code>```

答: It's really not that much harder.  On the input side, using one of the showInputDialog(...) methods of JOptionPane is almost an exact replacement for input.nextInt();.  The only difference it that showInputDialog(...) returns the user's input as String, not an int, so you'll have to use Integer.parseInt to convert the returned String into an int.  As for the output, showMessageDialog(...) is an almost exact replacement for System.out.println(...); just use the --- as the message text argument.

Body:
I've been playing around with this code for a little bit now and can't seem to find the correct way to sort it out. I used a program without JOptionPane and it worked and tried to use the same sequence but it didn't work. Do I need to add something else? The assignment is to have the user enter 3 integers and print the average with input and output dialog boxes. I've done the average and input/output dialog boxes before but putting it all together is harder than I thought.

import java.util.Scanner;
import javax.swing.JOptionPane;
import java.text.*;
import java.text.DecimalFormat;
public class Number3
{

  public static void main(String[] args)
  {
    System.out.println("Enter 3 numbers: ");
    Scanner input = new Scanner (System.in);
    DecimalFormat decimalFormat = new DecimalFormat("0.00##");

    int num1;
    int num2;
    int num3;
    double avg;

    num1=input.nextInt();
    num2=input.nextInt();
    num3=input.nextInt();

    avg=(double)(num1+num2+num3)/3.0;
    System.out.println("The average is: " + decimalFormat.format(avg));

  }
}


问:
New to Excel VBA: #Value error on string creation
Sorry all, I assume the error is basic but I am not sure what I am doing incorrectly.

I am attempting to write a function that takes a cell and converts the characters marked in red to lowercase. I do this by reconstructing the string in a new variable.

This reconstructed string is then returned. However, when I try to use this function in Excel on a string, it returns a #Value error. The code has no compilation errors so I am at a loss. Any help would be appreciated.

```<code>
    Function Convert_Red(rng As Range)

    If (rng.Cells.Count > 1) Then
         AcceptOneCell = "Only allow 1 cell"
         Exit Function
    End If

    Dim i As Long
    Dim text As String
    Dim new_text As String
    Dim placeholder As String

    text = rng.Cells(1, 1).Value

    For i = 1 To Len(text)
        If rng.Cells(1, 1).Characters(Start:=i, Length:=1).Font.Color  vbRed
    Then
        new_text = new_text + LCase(rng.Cells(1, 1).Characters(Start:=i,
    Length:=1))
        Else
            new_text = new_text + rng.Cells(1, 1).Characters(Start:=i, Length:=1)
       End If
       i = i + 1
    Next

    Convert_Red = new_text

    End Function

</code>```

答:
I'm guessing at what your current code is, because the posted code won't compile.  I believe you are after the following:

```<code>Function Convert_Red(rng As Range)

    If (rng.Cells.Count > 1) Then
        'Use the correct function name when returning a result
        'AcceptOneCell = "Only allow 1 cell"
        Convert_Red = "Only allow 1 cell"
        Exit Function
    End If

    Dim i As Long
    Dim text As String
    Dim new_text As String
    Dim placeholder As String

    text = rng.Cells(1, 1).Value

    For i = 1 To Len(text)
        'Fix syntax errors
        'If rng.Cells(1, 1).Characters(Start:=i, Length:=1).Font.Color  vbRed
        'Then
        If rng.Cells(1, 1).Characters(Start:=i, Length:=1).Font.Color = vbRed Then
            ' 1) Fix syntax errors
            ' 2) Use & for string concatenation
            ' 3) A Characters object has no default property - specify Text
            'new_text = new_text + LCase(rng.Cells(1, 1).Characters(Start:=i,
            'Length:=1))
            new_text = new_text & LCase(rng.Cells(1, 1).Characters(Start:=i, Length:=1).Text)
        Else
            ' 1) Use & for string concatenation
            ' 2) A Characters object has no default property - specify Text
            'new_text = new_text + rng.Cells(1, 1).Characters(Start:=i, Length:=1)
            new_text = new_text & rng.Cells(1, 1).Characters(Start:=i, Length:=1).Text
        End If
        'Don't mess with the loop counter
        'i = i + 1
    Next

    Convert_Red = new_text

End Function
</code>```

Note that using Characters will not work if the source range contains a formula, a numeric value, or a date.

Body:
Sorry all, I assume the error is basic but I am not sure what I am doing incorrectly.

I am attempting to write a function that takes a cell and converts the characters marked in red to lowercase. I do this by reconstructing the string in a new variable.

This reconstructed string is then returned. However, when I try to use this function in Excel on a string, it returns a #Value error. The code has no compilation errors so I am at a loss. Any help would be appreciated.

    Function Convert_Red(rng As Range)

    If (rng.Cells.Count > 1) Then
         AcceptOneCell = "Only allow 1 cell"
         Exit Function
    End If

    Dim i As Long
    Dim text As String
    Dim new_text As String
    Dim placeholder As String

    text = rng.Cells(1, 1).Value

    For i = 1 To Len(text)
        If rng.Cells(1, 1).Characters(Start:=i, Length:=1).Font.Color  vbRed
    Then
        new_text = new_text + LCase(rng.Cells(1, 1).Characters(Start:=i,
    Length:=1))
        Else
            new_text = new_text + rng.Cells(1, 1).Characters(Start:=i, Length:=1)
       End If
       i = i + 1
    Next

    Convert_Red = new_text

    End Function

Body:
I'm guessing at what your current code is, because the posted code won't compile.  I believe you are after the following:

Function Convert_Red(rng As Range)

    If (rng.Cells.Count > 1) Then
        'Use the correct function name when returning a result
        'AcceptOneCell = "Only allow 1 cell"
        Convert_Red = "Only allow 1 cell"
        Exit Function
    End If

    Dim i As Long
    Dim text As String
    Dim new_text As String
    Dim placeholder As String

    text = rng.Cells(1, 1).Value

    For i = 1 To Len(text)
        'Fix syntax errors
        'If rng.Cells(1, 1).Characters(Start:=i, Length:=1).Font.Color  vbRed
        'Then
        If rng.Cells(1, 1).Characters(Start:=i, Length:=1).Font.Color = vbRed Then
            ' 1) Fix syntax errors
            ' 2) Use & for string concatenation
            ' 3) A Characters object has no default property - specify Text
            'new_text = new_text + LCase(rng.Cells(1, 1).Characters(Start:=i,
            'Length:=1))
            new_text = new_text & LCase(rng.Cells(1, 1).Characters(Start:=i, Length:=1).Text)
        Else
            ' 1) Use & for string concatenation
            ' 2) A Characters object has no default property - specify Text
            'new_text = new_text + rng.Cells(1, 1).Characters(Start:=i, Length:=1)
            new_text = new_text & rng.Cells(1, 1).Characters(Start:=i, Length:=1).Text
        End If
        'Don't mess with the loop counter
        'i = i + 1
    Next

    Convert_Red = new_text

End Function

Note that using Characters will not work if the source range contains a formula, a numeric value, or a date.


问:
Responsive Web Design Not working
I'm new to responsive web design, so I'm not sure why this isn't working, but it definitely has something to do with me. I'm not exactly sure how to make this current website "responsive", and I've been trying for a good while. Code shown below. It may help to run it via browser. NOTE: I would like to not use a 3rd party css library like Bootstrap

HTML

```<code>    <!doctype html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/style.css" rel="stylesheet" type="text/css">
<link rel="icon" href="img/favicon.ico" sizes="16x16" type="image/ico">
<head>
<meta charset="utf-8">
<title>OneClickLearn - Home</title>
</head>

<body>
<ul>
  <li><a href="#home">Home</a></li>
  <li><a href="#news">News</a></li>
  <li><a href="#contact">Contact</a></li>
  <li><a href="#about">About</a></li>
</ul>

<div class="head">
<center>
  <h1 class="centered-divcontent txt-jumbo">OneClickLearn</h1>
  </center>
</div>

<div class="sidecontentleft">

  <div class="sidecontent">
        <h3 class="txt-marginall">Learn how to construct the blocks of a website!<br><br>Start Learning HTML <em>now</em></h3>
        <button class="green-btn txt-marginall">Learn HTML5!</button>
        </div>
    </div>

<div class="sidecontentleft">

  <div class="sidecontent"><h3>Learn the Cascading Style Sheet of web development!<br><br>Start Learning CSS <em>now</em></h3>
        <button class="blue-btn txt-marginall">Learn CSS!</button>
        </div>
    </div>

<div class="sidecontentleft">

  <div class="sidecontent">
        <h3 class="txt-marginall">Learn data storing in web development!<br><br>Start Learning PHP <em>now</em></h3>
        <button class="green-btn txt-marginall">Learn PHP!</button>
        </div>
    </div>

<div class="sidecontentleft">

  <div class="sidecontent">
    <h3>Create actions and animations!<br>
      <br>
      Start Learning Javascript <em>now</em></h3>
    <button class="blue-btn txt-marginall">Learn Javascript!</button>
        </div>
    </div>
<div class="sidecontentleft">

  <div class="sidecontent">
        <h3 class="txt-marginall">Learn how to construct the blocks of a website!<br><br>Start Learning HTML5 <em>now</em></h3>
        <button class="green-btn txt-marginall">Learn HTML5!</button>
        </div>
    </div>
</body>
</html>
</code>```

CSS

```<code>    @import url('https://fonts.googleapis.com/css?family=Source+Code+Pro');

body {
    margin:0;
    padding:0;
    }

/*nav*/
@media (min-width:600px) {
    .txt-jumbo {
        font-size:-40px;
    }
}

ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #333;
}

li {
    float:left;
}

li a {
    display: block;
    color: white;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
}

li a:hover {
    background-color: #111;
}

/*divs*/

.sidecontentleft {
    align-self:center;
    height:300px;
    width:300px;
    float:left;
    }

.sidecontentright {
    align-self:center;
    height:300px;
    width:300px;
    float:right;
    }

.sidecontent {
    text-align:center;
    height: 300px;
    display: table-cell;
    vertical-align: middle;
    }

.head {
    width:100%;
    height:350px;
    background-color:#05D7C6;
    color:white;
    text-align:center;
    }

.centered-divcontent {
    text-align:center;
    height: 350px;
    display: table-cell;
    vertical-align: middle;
    }

/*buttons*/

.green-btn {
    height:40px;
    width:auto;
    border-radius:5px;
    background-color:#04D43C;
    border:none;
    color:white;
    }

.green-btn:hover {
    height:40px;
    width:auto;
    border-radius:5px;
    background-color:#00F040;
    border:none;
    color:white;
    cursor:pointer;
    }

.blue-btn {
    height:40px;
    width:auto;
    border-radius:5px;
    background-color:#05D7C6;
    border:none;
    color:white;
    }

.blue-btn:hover {
    height:40px;
    width:auto;
    border-radius:5px;
    background-color:#00E9D6;
    border:none;
    color:white;
    cursor:pointer;
    }

.white-btn {
    border-radius:5px;
    height:40px;
    width:auto;
    text-align:center;
    border: #BFBFBF 1px solid;
    text-decoration:none;
    color:black;
    background-color:white;
    }

/*Fonts*/

.txt-jumbo {
    font-size:100px;
    }

.txt-centered {
    text-align:center;
    }

.txt-margin {
    margin-left:25px;
    }

.txt-marginall {
    margin-left:15px;
    margin-right:15px;
    margin-top:15px;
    margin-bottom:15px;
    }

h1 {font-family: 'Source Code Pro', monospace;}
h2 {font-family: 'Source Code Pro', monospace;}
h3 {font-family: 'Source Code Pro', monospace;}
h4 {font-family: 'Source Code Pro', monospace;}
h5{font-family: 'Source Code Pro', monospace;}
h6 {font-family: 'Source Code Pro', monospace;}
a {font-family: 'Source Code Pro', monospace;}
p {font-family: 'Source Code Pro', monospace;}
</code>```

Your help would be appreciated! Thanks!

答:
.txt-jumbo, which styles the header font, has a default value of 100px. The media query you used specified font-size: -40px for screens wider than 600px. font-size cannot take a negative value.

To make the font smaller on small screens, try something like:

```<code>@media (max-width: 600px) {
    .txt-jumbo {
        font-size: 50px;
    }
}
</code>```

where max-width: 600px means that the styles contained apply to screens less than 600px wide.

There are several ways to make the navigation "collapse". To make the links stack, make them inline-block elements and set their widths to 100%.

```<code>@media (max-width: 600px) {
    li {
        display: inline-block;
        width: 100%;
    }
}
</code>```

When using a screen less than 600px wide, the links will now take up the entire width of the screen. display: inline-block allows them to stack.

Title: Responsive Web Design Not working

Body:
I'm new to responsive web design, so I'm not sure why this isn't working, but it definitely has something to do with me. I'm not exactly sure how to make this current website "responsive", and I've been trying for a good while. Code shown below. It may help to run it via browser. NOTE: I would like to not use a 3rd party css library like Bootstrap

HTML

    <!doctype html>

<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/style.css" rel="stylesheet" type="text/css">
<link rel="icon" href="img/favicon.ico" sizes="16x16" type="image/ico">

<meta charset="utf-8">
<title>OneClickLearn - Home</title>

Home

News

Contact

About

OneClickLearn

Learn how to construct the blocks of a website!

Start Learning HTML now

        <button class="green-btn txt-marginall">Learn HTML5!</button>

Learn the Cascading Style Sheet of web development!

Start Learning CSS now

        <button class="blue-btn txt-marginall">Learn CSS!</button>

Learn data storing in web development!

Start Learning PHP now

        <button class="green-btn txt-marginall">Learn PHP!</button>

Create actions and animations!

      Start Learning Javascript now

    <button class="blue-btn txt-marginall">Learn Javascript!</button>

Learn how to construct the blocks of a website!

Start Learning HTML5 now

        <button class="green-btn txt-marginall">Learn HTML5!</button>

CSS

    @import url('https://fonts.googleapis.com/css?family=Source+Code+Pro');

body {
    margin:0;
    padding:0;
    }

/*nav*/
@media (min-width:600px) {
    .txt-jumbo {
        font-size:-40px;
    }
}

ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #333;
}

li {
    float:left;
}

li a {
    display: block;
    color: white;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
}

li a:hover {
    background-color: #111;
}

/*divs*/

.sidecontentleft {
    align-self:center;
    height:300px;
    width:300px;
    float:left;
    }

.sidecontentright {
    align-self:center;
    height:300px;
    width:300px;
    float:right;
    }

.sidecontent {
    text-align:center;
    height: 300px;
    display: table-cell;
    vertical-align: middle;
    }

.head {
    width:100%;
    height:350px;
    background-color:#05D7C6;
    color:white;
    text-align:center;
    }

.centered-divcontent {
    text-align:center;
    height: 350px;
    display: table-cell;
    vertical-align: middle;
    }

/*buttons*/

.green-btn {
    height:40px;
    width:auto;
    border-radius:5px;
    background-color:#04D43C;
    border:none;
    color:white;
    }

.green-btn:hover {
    height:40px;
    width:auto;
    border-radius:5px;
    background-color:#00F040;
    border:none;
    color:white;
    cursor:pointer;
    }

.blue-btn {
    height:40px;
    width:auto;
    border-radius:5px;
    background-color:#05D7C6;
    border:none;
    color:white;
    }

.blue-btn:hover {
    height:40px;
    width:auto;
    border-radius:5px;
    background-color:#00E9D6;
    border:none;
    color:white;
    cursor:pointer;
    }

.white-btn {
    border-radius:5px;
    height:40px;
    width:auto;
    text-align:center;
    border: #BFBFBF 1px solid;
    text-decoration:none;
    color:black;
    background-color:white;
    }

/*Fonts*/

.txt-jumbo {
    font-size:100px;
    }

.txt-centered {
    text-align:center;
    }

.txt-margin {
    margin-left:25px;
    }

.txt-marginall {
    margin-left:15px;
    margin-right:15px;
    margin-top:15px;
    margin-bottom:15px;
    }

h1 {font-family: 'Source Code Pro', monospace;}
h2 {font-family: 'Source Code Pro', monospace;}
h3 {font-family: 'Source Code Pro', monospace;}
h4 {font-family: 'Source Code Pro', monospace;}
h5{font-family: 'Source Code Pro', monospace;}
h6 {font-family: 'Source Code Pro', monospace;}
a {font-family: 'Source Code Pro', monospace;}
p {font-family: 'Source Code Pro', monospace;}

Your help would be appreciated! Thanks!

Body:
.txt-jumbo, which styles the header font, has a default value of 100px. The media query you used specified font-size: -40px for screens wider than 600px. font-size cannot take a negative value.

To make the font smaller on small screens, try something like:

@media (max-width: 600px) {
    .txt-jumbo {
        font-size: 50px;
    }
}

where max-width: 600px means that the styles contained apply to screens less than 600px wide.

There are several ways to make the navigation "collapse". To make the links stack, make them inline-block elements and set their widths to 100%.

@media (max-width: 600px) {
    li {
        display: inline-block;
        width: 100%;
    }
}

When using a screen less than 600px wide, the links will now take up the entire width of the screen. display: inline-block allows them to stack.


问:
Use RSA private key to generate public key?
I don't really understand this one:

According to https://www.madboa.com/geek/openssl/#key-rsa, you can generate a public key from a private key.

```<code>openssl genrsa -out mykey.pem 1024
openssl rsa -in mykey.pem -pubout > mykey.pub
</code>```

My initial thinking was that they are generated in a pair together.

Does the RSA private key contain the sum? Or the public key?

答:
My answer below is a bit lengthy, but hopefully it provides some details that are missing in previous answers. I'll start with some related statements and finally answer the initial question.

To encrypt something using RSA algorithm you need modulus and encryption (public) exponent pair (n, e). That's your public key. To decrypt something using RSA algorithm you need modulus and decryption (private) exponent pair (n, d). That's your private key.

To encrypt something using RSA public key you treat your plaintext as a number and raise it to the power of e modulus n:

```<code>ciphertext = ( plaintext^e ) mod n
</code>```

To decrypt something using RSA private key you treat your ciphertext as a number and raise it to the power of d modulus n:

```<code>plaintext = ( ciphertext^d ) mod n
</code>```

To generate private (d,n) key using openssl you can use the following command:

```<code>openssl genrsa -out private.pem 1024
</code>```

To generate public (e,n) key from the private key using openssl you can use the following command:

```<code>openssl rsa -in private.pem -out public.pem -pubout
</code>```

To dissect the contents of the private.pem private RSA key generated by the openssl command above run the following (output truncated to labels here):

```<code>openssl rsa -in private.pem -text -noout | less

modulus         - n
privateExponent - d
publicExponent  - e
prime1          - p
prime2          - q
exponent1       - d mod (p-1)
exponent2       - d mod (q-1)
coefficient     - (q^-1) mod p
</code>```

Shouldn't private key consist of (n, d) pair only? Why are there 6 extra components? It contains e (public exponent) so that public RSA key can be generated/extracted/derived from the private.pem private RSA key. The rest 5 components are there to speed up the decryption process. It turns out that by pre-computing and storing those 5 values it is possible to speed the RSA decryption by the factor of 4. Decryption will work without those 5 components, but it can be done faster if you have them handy. The speeding up algorithm is based on the Chinese Remainder Theorem.

Yes, private.pem RSA private key actually contains all of those 8 values; none of them are generated on the fly when you run the previous command. Try running the following commands and compare output:

```<code># Convert the key from PEM to DER (binary) format
openssl rsa -in private.pem -outform der -out private.der

# Print private.der private key contents as binary stream
xxd -p private.der

# Now compare the output of the above command with output
# of the earlier openssl command that outputs private key
# components. If you stare at both outputs long enough
# you should be able to confirm that all components are
# indeed lurking somewhere in the binary stream
openssl rsa -in private.pem -text -noout | less
</code>```

This structure of the RSA private key is recommended by the PKCS#1 v1.5 as an alternative (second) representation. PKCS#1 v2.0 standard excludes e and d exponents from the alternative representation altogether. PKCS#1 v2.1 and v2.2 propose further changes to the alternative representation, by optionally including more CRT-related components.

To see the contents of the public.pem public RSA key run the following (output truncated to labels here):

```<code>openssl rsa -in public.pem -text -pubin -noout

Modulus             - n
Exponent (public)   - e
</code>```

No surprises here. It's just (n, e) pair, as promised.

Now finally answering the initial question: As was shown above private RSA key generated using openssl contains components of both public and private keys and some more. When you generate/extract/derive public key from the private key, openssl copies two of those components (e,n) into a separate file which becomes your public key.

ContentLicense: CC BY-SA 4.0

Body:
I don't really understand this one:

According to https://www.madboa.com/geek/openssl/#key-rsa, you can generate a public key from a private key.

openssl genrsa -out mykey.pem 1024
openssl rsa -in mykey.pem -pubout > mykey.pub

My initial thinking was that they are generated in a pair together.

Does the RSA private key contain the sum? Or the public key?

Body:
My answer below is a bit lengthy, but hopefully it provides some details that are missing in previous answers. I'll start with some related statements and finally answer the initial question.

To encrypt something using RSA algorithm you need modulus and encryption (public) exponent pair (n, e). That's your public key. To decrypt something using RSA algorithm you need modulus and decryption (private) exponent pair (n, d). That's your private key.

To encrypt something using RSA public key you treat your plaintext as a number and raise it to the power of e modulus n:

ciphertext = ( plaintext^e ) mod n

To decrypt something using RSA private key you treat your ciphertext as a number and raise it to the power of d modulus n:

plaintext = ( ciphertext^d ) mod n

To generate private (d,n) key using openssl you can use the following command:

openssl genrsa -out private.pem 1024

To generate public (e,n) key from the private key using openssl you can use the following command:

openssl rsa -in private.pem -out public.pem -pubout

To dissect the contents of the private.pem private RSA key generated by the openssl command above run the following (output truncated to labels here):

openssl rsa -in private.pem -text -noout | less

modulus         - n
privateExponent - d
publicExponent  - e
prime1          - p
prime2          - q
exponent1       - d mod (p-1)
exponent2       - d mod (q-1)
coefficient     - (q^-1) mod p

Shouldn't private key consist of (n, d) pair only? Why are there 6 extra components? It contains e (public exponent) so that public RSA key can be generated/extracted/derived from the private.pem private RSA key. The rest 5 components are there to speed up the decryption process. It turns out that by pre-computing and storing those 5 values it is possible to speed the RSA decryption by the factor of 4. Decryption will work without those 5 components, but it can be done faster if you have them handy. The speeding up algorithm is based on the Chinese Remainder Theorem.

Yes, private.pem RSA private key actually contains all of those 8 values; none of them are generated on the fly when you run the previous command. Try running the following commands and compare output:

# Convert the key from PEM to DER (binary) format
openssl rsa -in private.pem -outform der -out private.der

# Print private.der private key contents as binary stream
xxd -p private.der

# Now compare the output of the above command with output
# of the earlier openssl command that outputs private key
# components. If you stare at both outputs long enough
# you should be able to confirm that all components are
# indeed lurking somewhere in the binary stream
openssl rsa -in private.pem -text -noout | less

This structure of the RSA private key is recommended by the PKCS#1 v1.5 as an alternative (second) representation. PKCS#1 v2.0 standard excludes e and d exponents from the alternative representation altogether. PKCS#1 v2.1 and v2.2 propose further changes to the alternative representation, by optionally including more CRT-related components.

To see the contents of the public.pem public RSA key run the following (output truncated to labels here):

openssl rsa -in public.pem -text -pubin -noout

Modulus             - n
Exponent (public)   - e

No surprises here. It's just (n, e) pair, as promised.

Now finally answering the initial question: As was shown above private RSA key generated using openssl contains components of both public and private keys and some more. When you generate/extract/derive public key from the private key, openssl copies two of those components (e,n) into a separate file which becomes your public key.


问:
How to get scroll spy to work?
I cant get my scroll spy to work, and I have tried everything, what am I doing wrong?  I have looked at countless examples and I seem to have everything correct. Here is the whole file, Im thinking there are maybe some conflicting css?</p>

```<code>    <DOCTYPE html>
    <html lang="en">

  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>TCS Event Rentals</title>
    <!-- Latest compiled and minified CSS -->
    <link href="css/bootstrap.min.css" rel="stylesheet">

    <style>
      body {
       position: relative;

      }

      .jumbotron img {
        width: 100%;
       height: auto;

      }

      .jumbotron {
        margin-top: 85px;
        padding-top: 20px;
        height: 550px;
        background-image:
url(https://thumb1.shutterstock.com/display_pic_with_logo/1447/98829743/stock-photo-wedding-tent-set-up-for-an-outdoor-wedding-or-other-event-chairs-set-up-for-an-outdoor-ceremony-98829743.jpg);
        background-size: 100% 100%;
      }

      .jumbotron h2 {
        color: white;
        margin-top: 100px;
      }

       .navbar-fixed-top {
      min-height: 125px;
      }

      .navbar-header {
        height: 125px;
      }

      a.navbar-brand {
        height: 125px;
      }

      a.navbar-brand > img {
        margin-top: -13px;
      }

      ul.nav {
        margin-top: 60px;
      }

      @media (max-width: 767px) {
      .navbar-nav > li > a {
        line-height: 20px;
        padding-top: 10px;
        padding-bottom: 10px;
      }

      div#bs-example-navbar-collapse-1 {
        margin-top: 10px;
      }

      .navbar-toggle {
        margin-top: 30px;
      }

      ul.nav {
        margin-top: 10px;
      }

    </style>

</head>

<body data-spy="scroll" data-target="#my-navbar">

    <!-- Navbar -->
    <nav class="navbar navbar-default navbar-fixed-top" id="my-navbar">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>

                <a class="navbar-brand" href="#"><img src="img/logo.jpg"></a>
            </div>

            <!-- Collect the nav links, forms, and other content for toggling -->
            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">

            <!-- <a href="#contact" class="btn btn-primary navbar-btn navbar-right">Contact Us</a> -->
              <ul class="nav navbar-nav navbar-right">
                <li><a href="#aboutus">About Us</a></li>
                <li><a href="#eventrental">Event Rental Products</a></li>
                <li><a href="#eventserved">Events Served</a></li>
                <li><a href="#gallery">Gallery</a></li>
                <li><a href="#contact">Contact</a></li>
              </ul>
            </div><!-- /.navbar-collapse -->
        </div><!-- /.container-fluid -->
    </nav><!-- End Navbar -->

    <!-- Jumbotron -->

    <div class="Jumbotron">
        <div class="container text-center">
            <!--<img src="https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcQNHBdJdFb6Chukad-YBtL4RXRY0uyR_TI5-hvVYuIHZjQwZB-j" class="img-responsive" alt="Responsive image"> -->

            <h2>Serving the Special Events Industry</h2>

            <div class="btn-group">
            <a href="#gallery"  class="btn btn-lg btn-primary">View Our Gallery</a>
            </div>

        </div><!-- End Container -->
    </div><!-- End Jumbotron -->

    <div class="container">
        <section>
            <div class="page-header" id="aboutus">
                <h2>About Us<small> Check out the feedback</small></h2>
            </div>

            <div class="row">
                <div class="col-lg-4">
                  <blockquote>
                      <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
                      tempor incididunt ut labore et dolore magna aliqua.</p>
                      <footer>John Doe</footer>
                  </blockquote>
                </div>

            <div class="col-lg-4">
                  <blockquote>
                      <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
                      tempor incididunt ut labore et dolore magna aliqua.</p>
                      <footer>John Doe</footer>
                  </blockquote>
                </div>

            <div class="col-lg-4">
                  <blockquote>
                      <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
                      tempor incididunt ut labore et dolore magna aliqua.</p>
                      <footer>John Doe</footer>
                  </blockquote>
                </div>
            </div><!--End Row -->
        </section>
    </div> <!-- End Container -->

    <!--call to action -->
    <section>
        <div class="well">
            <div class="container text-center">
                <h3>Contact Us to plan your next event</h3>
                <p>Enter your name and email</p>

                <form action="" class="form-inline">
                    <div class="form-group">
                        <label form="subscription">Contact Us</label>
                        <input type="text" class="form-control" id="subscription" placeholder="Your name">
                    </div>
                    <div class="form-group">
                        <label form="email">Email Address</label>
                        <input type="text" class="form-control" id="email" placeholder="Enter your Email">
                    </div>
                    <button type="submit" class="btn btn-primary">Contact Us</button>
                    <hr>
                </form>
            </div><!--end container -->
        </div><!-- end well -->
    </section><!-- end Call to action -->

    <!-- Gallery -->
    <div class="container">
        <section>
            <div class="page-header" id="gallery">
                <h2>Gallery<small> Check out our Gallery</small></h2>
            </div>

            <div class="carousel slide" id="screenshot-carousel" data-ride="carousel">
                <ol class="carousel-indicators">
                    <li data-target="#screenshot-carousel" data-slide-to="0" class="active"></li>
                    <li data-target="#screenshot-carousel" data-slide-to="1"></li>
                    <li data-target="#screenshot-carousel" data-slide-to="2"></li>
                    <li data-target="#screenshot-carousel" data-slide-to="3"></li>
                </ol>
                <div class="carousel-inner">
                    <div class="item active">
                        <img src="https://partytimerental.com/wp-content/uploads/2013/12/100-x-380-Century-Tent-Denver-View-3.x30701.jpg" alt="text of image">
                    </div>
                    <div class="item">
                        <img src="https://partytimerental.com/wp-content/uploads/2013/12/100-Wide-Century-Tent-Rocky-Mountains-CO-View-5.x30701.jpg" alt="text of image">
                    </div>
                    <div class="item">
                        <img src="https://partytimerental.com/wp-content/uploads/2013/12/100-x-380-Century-Tent-Denver-View-3.x30701.jpg" alt="text of image">
                    </div>
                    <div class="item">
                        <img src="https://partytimerental.com/wp-content/uploads/2013/12/100-x-380-Century-Tent-Denver-View-3.x30701.jpg" alt="text of image">
                    </div>

                </div><!-- End Carousel Inner -->
                <a href="#screenshot-carousel" class="left carousel-control" data-slide="prev">
                    <span class="glyphicon glyphicon-chevron-left"></span>
                </a>
                <a href="#screenshot-carousel" class="right carousel-control" data-slide="next">
                    <span class="glyphicon glyphicon-chevron-right"></span>
                </a>
            </div><!-- end carousel -->

        </section>
    </div>

    <!-- Event Rental Products -->
    <div class="container">
        <section>
            <div class="page-header" id="eventrental">
                <h2>Event Rental Products<small>Browse our selection of rental products</small></h2>
            </div><!-- End Page Header -->

            <div class="row">
                <div class="col-lg-8">
                    <h3>This is the heading</h3>
                    <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed. </p>
                </div>
                <div class="col-lg-4">
                    <img src="img/imac.jpg" class="img-responsive" alt="image">
                </div>
            </div><!-- End Row -->
            <div class="row">
                <div class="col-lg-8">
                    <h3>This is the heading</h3>
                    <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed. </p>
                </div>
                <div class="col-lg-4">
                    <img src="https://s3.amazonaws.com/homestratosphere/wp-content/uploads/2014/07/5Way-AccentChairs100.jpg" class="img-responsive" alt="image">
                </div>
            </div><!-- End Row -->
            <div class="row">
                <div class="col-lg-8">
                    <h3>This is the heading</h3>
                    <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed. </p>
                </div>
                <div class="col-lg-4">
                    <img src="http://target.scene7.com/is/image/Target/16513837?wid=360&hei=360&qlt=80&fmt=pjpeg" class="img-responsive" alt="image">
                </div>
            </div><!-- End Row -->

            <hr>

            <div class="row">
                <div class="col-lg-4">
                    <div class="panel panel-default text-center">
                        <div class="panel-body">
                            <span class="glyphicon glyphicon-ok"></span>
                            <h4>This is the heading</h4>
                            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
                            tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
                            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
                            consequat.</p>
                        </div>
                    </div>
                </div>
                <div class="col-lg-4">
                    <div class="panel panel-default text-center">
                        <div class="panel-body">
                            <span class="glyphicon glyphicon-cutlery"></span>
                            <h4>This is the heading</h4>
                            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
                            tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
                            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
                            consequat.</p>
                        </div>
                    </div>
                </div>
                <div class="col-lg-4">
                    <div class="panel panel-default text-center">
                        <div class="panel-body">
                            <span class="glyphicon glyphicon-leaf"></span>
                            <h4>This is the heading</h4>
                            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
                            tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
                            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
                            consequat.</p>
                        </div>
                    </div>
                </div>
            </div><!-- End Row -->

        </section>
    </div><!-- End Container -->

    <!-- Events Served -->

    <div class="container">
        <section>
            <div class="page-header" id="eventserved">
                <h2>Events Served<small>Past events we served</small></h2>
            </div><!-- End Page Header -->
        </section>
    </div><!-- End Container -->

    <!-- Contact -->

    <div class="container">
        <section>
            <div class="page-header" id="contact">
                <h2>Contact Us<small>Contact us for more</small></h2>
            </div><!-- End Page Header -->

            <div class="row">
                <div class="col-lg-4">
                    <p>Send us a message, or contact us from the address below</p>

                    <address>
                        <strong>TCS Event Rentals</strong></br>
                        Lear Dr</br>
                        Burlington, NC 27310</br>
                        P: 1-800-888-8888
                    </address>
                </div>

                <div class="col-lg-8">
                    <form action="" class="form-horizontal">
                        <div class="form-group">
                            <label for="user-name" class="col-lg-2 control-label">Name</label>
                            <div class="col-lg-10">
                                <input type="text" class="form-control" id="user-name" placeholder="Enter your Name">
                            </div>
                        </div><!-- End Form Group -->
                        <div class="form-group">
                            <label for="user-email" class="col-lg-2 control-label">Email</label>
                            <div class="col-lg-10">
                                <input type="text" class="form-control" id="user-email" placeholder="Enter your Email Address">
                            </div>
                        </div><!-- End Form Group -->
                        <div class="form-group">
                            <label for="user-url" class="col-lg-2 control-label">Your Website</label>
                            <div class="col-lg-10">
                                <input type="text" class="form-control" id="user-url" placeholder="If you have any">
                            </div>
                        </div><!-- End Form Group -->
                        <div class="form-group">
                            <label for="user-message" class="col-lg-2 control-label">Any Message</label>
                            <div class="col-lg-10">
                                <textarea name="user-message" id="user-message" class="form-control" cols="20" rows="10" placeholder="Enter your Message"></textarea>
                            </div>
                        </div><!-- End Form Group -->

                        <div class="form-group">
                            <div class="col-lg-10 col-lg-offset-2">
                                <button type="submit" class="btn btn-primary">Submit</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div><!-- End Row -->

        </section>
    </div><!-- End Container -->

    <!-- Footer -->

        <footer>
          <hr>
            <div class="container text-center">
                <h3>Contact Us to plan your next event</h3>
                <p>Enter your name and email</p>

                <form action="" class="form-inline">
                    <div class="form-group">
                        <label form="subscription">Contact Us</label>
                        <input type="text" class="form-control" id="subscription" placeholder="Your name">
                    </div>
                    <div class="form-group">
                        <label form="email">Email Address</label>
                        <input type="text" class="form-control" id="email" placeholder="Enter your Email">
                    </div>
                        <button type="submit" class="btn btn-primary">Contact Us</button>
                </form>

                <hr>
                <ul class="list-inline">
                    <li><a href="http://www.twitter.com/slmwebdesignco">Twitter</a></li>
                    <li><a href="http://www.twitter.com/slmwebdesignco">Facebook</a></li>
                    <li><a href="http://www.twitter.com/slmwebdesignco">Youtube</a></li>
                </ul>

                <p>©Copyright 2017</p>
            </div><!--end container -->

        </footer>

      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
      <script src="js/bootstrap.min.js"></script>
</body>

</html>
</code>```

答: I finally discovered the solution through more research, I simply had to add css: height: 100%; to the body element. Everything works perfectly now.</p>

Title: How to get scroll spy to work?

Body:
I cant get my scroll spy to work, and I have tried everything, what am I doing wrong?  I have looked at countless examples and I seem to have everything correct. Here is the whole file, Im thinking there are maybe some conflicting css?

    <DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>TCS Event Rentals</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                    Toggle navigation

                </button>

About Us

Event Rental Products

Events Served

Gallery

Contact

Serving the Special Events Industry

            View Our Gallery

About Us Check out the feedback

 Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
                      tempor incididunt ut labore et dolore magna aliqua.

                      John Doe

 Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
                      tempor incididunt ut labore et dolore magna aliqua.

                      John Doe

 Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
                      tempor incididunt ut labore et dolore magna aliqua.

                      John Doe

Contact Us to plan your next event

Enter your name and email

                <form action="" class="form-inline">

                        Contact Us
                        <input type="text" class="form-control" id="subscription" placeholder="Your name">

                        Email Address
                        <input type="text" class="form-control" id="email" placeholder="Enter your Email">

                    <button type="submit" class="btn btn-primary">Contact Us</button>

                </form>

Gallery Check out our Gallery

Event Rental ProductsBrowse our selection of rental products

This is the heading

 Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed.

This is the heading

 Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed.

This is the heading

 Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed.

This is the heading

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
                            tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
                            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
                            consequat.

This is the heading

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
                            tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
                            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
                            consequat.

This is the heading

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
                            tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
                            quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
                            consequat.

Events ServedPast events we served

Contact UsContact us for more

Send us a message, or contact us from the address below

                    <address>
                        TCS Event Rentals

                        Lear Dr

                        Burlington, NC 27310

                        P: 1-800-888-8888
                    </address>

                    <form action="" class="form-horizontal">

                            Name

                                <input type="text" class="form-control" id="user-name" placeholder="Enter your Name">

                            Email

                                <input type="text" class="form-control" id="user-email" placeholder="Enter your Email Address">

                            Your Website

                                <input type="text" class="form-control" id="user-url" placeholder="If you have any">

                            Any Message

                                <textarea name="user-message" id="user-message" class="form-control" cols="20" rows="10" placeholder="Enter your Message"></textarea>

                                <button type="submit" class="btn btn-primary">Submit</button>

                    </form>

Contact Us to plan your next event

Enter your name and email

                <form action="" class="form-inline">

                        Contact Us
                        <input type="text" class="form-control" id="subscription" placeholder="Your name">

                        Email Address
                        <input type="text" class="form-control" id="email" placeholder="Enter your Email">

                        <button type="submit" class="btn btn-primary">Contact Us</button>
                </form>

Twitter

Facebook

Youtube

©Copyright 2017


答: I think the correct way is to use a computed function and bind a v-show directive that way.</p>

Title: How to toggle a view based on a state in vuex?

Body:
I have a button <Button> Log me in! </Button>, and I would like to change its css class based on the state of my current vuex app. (state.user is not null)

What is the proper way to write this code?

I can create a field in the state that is the classname of this view and change that accordingly in actions/mutations. But are there better places that I should be placing this logic? As this field is completely component dependent, I don't think it should "leak" out to the global state.


问:
Binding to multiple button clicks
To bind to the 1 key I use:

```<code>hs.hotkey.bind(hyper, '1'
</code>```

How to bind to multiple presses of 1 key? Something like:

```<code>hs.hotkey.bind(hyper, '1+1'
</code>```

Reading the documentation, this functionality is not mentioned.

By multiple presses I mean press 1 twice to run some code and press 1 three times to run a separate piece of code.

答:
You can not bind all keys or multiple keys with bind. Instead you can use this function: http://www.hammerspoon.org/docs/hs.eventtap.html#keyStroke

So the most straight forward programming language agnostic approach is as follows:

Call your function for any key stroke.

Within the function keep a static instance variable that will keep previous key strokes.

As the first task of your function append the new coming character to that variable.

Check the last 3 characters if they are the desired "11" string.

Extra for extreme conditions:

If the variable length pass a certain point reduce it to length 1 so that it does not keep unnecessary place in memory.

Title: Binding to multiple button clicks

Body:
To bind to the 1 key I use:

hs.hotkey.bind(hyper, '1'

How to bind to multiple presses of 1 key? Something like:

hs.hotkey.bind(hyper, '1+1'

Reading the documentation, this functionality is not mentioned.

By multiple presses I mean press 1 twice to run some code and press 1 three times to run a separate piece of code.


问:
Laravel 5.4: Storing the 'Where' clause in a variable
I want to write a dynamic update query in Laravel which accepts arguments and can be used in whole project.

Following is my Controller function:

```<code>public function editquery(Request $request)
    {

    $city_id   = $request->input('city_id');
    $city_name = $request->input('city_name');

    $tbl  = 'city';
    $data = ['city_name'=>$city_name];
    $wher = ('city_id',1);

    General_model::editrecord($data,$wher,$tbl);

    return redirect()->action('Admin_controller@cities_page')->with('status','Record Updated Successfully!');;

    }
</code>```

Below is my Model function:

```<code>public static function editrecord($data,$wher,$tbl)
    {
      return DB::table($tbl)->where($wher)->update($data);
    }
</code>```

The only problem here is that I cannot store the value ('city_id',1) in the $wher variable. This is the screenshot of the error:
link to the image file

Is there any other way to do this. Please Help.

答:
You can't do this

```<code>public static function editrecord($data,$wher,$tbl)
{
  return DB::table($tbl)->where($wher)->update($data);
}
</code>```

Since, where is a function; it expects 2 or 3 arguments and not just 1 argument.

You will have to pass both the arguments like so

```<code>public static function editrecord($data, $where_column, $where_val, $tbl)
{
  return DB::table($tbl)->where($where_column, $where_val)
                        ->update($data);
}
</code>```

Then, in your controller function

```<code>$where_column = 'city_id';
$where_val = 1;

General_model::editrecord($data,$where_column,$where_val,$tbl);
</code>```

Body:
I want to write a dynamic update query in Laravel which accepts arguments and can be used in whole project.

Following is my Controller function:

public function editquery(Request $request)
    {

    $city_id   = $request->input('city_id');
    $city_name = $request->input('city_name');

    $tbl  = 'city';
    $data = ['city_name'=>$city_name];
    $wher = ('city_id',1);

    General_model::editrecord($data,$wher,$tbl);

    return redirect()->action('Admin_controller@cities_page')->with('status','Record Updated Successfully!');;

    }

Below is my Model function:

public static function editrecord($data,$wher,$tbl)
    {
      return DB::table($tbl)->where($wher)->update($data);
    }

The only problem here is that I cannot store the value ('city_id',1) in the $wher variable. This is the screenshot of the error:
link to the image file

Is there any other way to do this. Please Help.

Body:
You can't do this

public static function editrecord($data,$wher,$tbl)
{
  return DB::table($tbl)->where($wher)->update($data);
}

Since, where is a function; it expects 2 or 3 arguments and not just 1 argument.

You will have to pass both the arguments like so

public static function editrecord($data, $where_column, $where_val, $tbl)
{
  return DB::table($tbl)->where($where_column, $where_val)
                        ->update($data);
}

Then, in your controller function

$where_column = 'city_id';
$where_val = 1;

General_model::editrecord($data,$where_column,$where_val,$tbl);


问:
I want my background image's opacity become .2 when I hover over an element on top of it
So I have a movie poster image and a play icon on it. How do I make my poster's opacity down WHEN I hover over the play image/icon that is positioned on it?</p>

答:
You can do this using jQuery as follows:</p>

```<code>$(function() {
  $('#myImage').hover(function() {
    // changing the opacity of the poster when hovering over image
    $('#myPoster').css('opacity', '0.2');
  }, function() {
    // resetting opacity when mouse leaves image
    $('#myPoster').css('opacity', '1.0');
  });
});
</code>```

Body:
You can do this using jQuery as follows:

$(function() {
  $('#myImage').hover(function() {
    // changing the opacity of the poster when hovering over image
    $('#myPoster').css('opacity', '0.2');
  }, function() {
    // resetting opacity when mouse leaves image
    $('#myPoster').css('opacity', '1.0');
  });
});


问:
Programming with Microsoft Kinect
Does anyone know if an end user purchases the Kinect sensor, he can program using it to make own games. Or is the API only for professional game studios?</p>

答:
Link to MSFT SDK

Update:

Just in from ZD.NET "Microsoft readies hobbyist Kinect development kit; promises commercial version later" link

Prior Post

The makers/OEM of the Kinect is PrimeSense.  They make both the kinect and an independent devkit.  They recently released open source drivers that are compatible with both XBox's Kinect and the smaller DevKit.  You might as well get the drivers straight from the source.  I'm not sure what value a 3rd party library (openKinect) will offer.

Get the unified Kinect and DevKit drivers here: http://www.openni.org/  Windows and Unix support is available.

Title: Programming with Microsoft Kinect


问:
How do I create a URL shortener?
I want to create a URL shortener service where you can write a long URL into an input field and the service shortens the URL to "http://www.example.org/abcdef".

Instead of "abcdef" there can be any other string with six characters containing a-z, A-Z and 0-9. That makes 56~57 billion possible strings.

My approach:

I have a database table with three columns:

id, integer, auto-increment

long, string, the long URL the user entered

short, string, the shortened URL (or just the six characters)

I would then insert the long URL into the table. Then I would select the auto-increment value for "id" and build a hash of it. This hash should then be inserted as "short". But what sort of hash should I build? Hash algorithms like MD5 create too long strings. I don't use these algorithms, I think. A self-built algorithm will work, too.

My idea:

For "http://www.google.de/" I get the auto-increment id 239472. Then I do the following steps:

```<code>short = '';
if divisible by 2, add "a"+the result to short
if divisible by 3, add "b"+the result to short
... until I have divisors for a-z and A-Z.
</code>```

That could be repeated until the number isn't divisible any more. Do you think this is a good approach? Do you have a better idea?

Due to the ongoing interest in this topic, I've published an efficient solution to GitHub, with implementations for JavaScript, PHP, Python and Java. Add your solutions if you like :)

答:
For a quality Node.js / JavaScript solution, see the id-shortener module, which is thoroughly tested and has been used in production for months.

It provides an efficient id / URL shortener backed by pluggable storage defaulting to Redis, and you can even customize your short id character set and whether or not shortening is idempotent. This is an important distinction that not all URL shorteners take into account.

In relation to other answers here, this module implements the Marcel Jackwerth's excellent accepted answer above.

The core of the solution is provided by the following Redis Lua snippet:

```<code>local sequence = redis.call('incr', KEYS[1])

local chars = '0123456789ABCDEFGHJKLMNPQRSTUVWXYZ_abcdefghijkmnopqrstuvwxyz'
local remaining = sequence
local slug = ''

while (remaining > 0) do
  local d = (remaining % 60)
  local character = string.sub(chars, d + 1, d + 1)

  slug = character .. slug
  remaining = (remaining - d) / 60
end

redis.call('hset', KEYS[2], slug, ARGV[1])

return slug
</code>```

Title: How do I create a URL shortener?

Body:
I want to create a URL shortener service where you can write a long URL into an input field and the service shortens the URL to "http://www.example.org/abcdef".

Instead of "abcdef" there can be any other string with six characters containing a-z, A-Z and 0-9. That makes 56~57 billion possible strings.

My approach:

I have a database table with three columns:

id, integer, auto-increment

long, string, the long URL the user entered

short, string, the shortened URL (or just the six characters)

I would then insert the long URL into the table. Then I would select the auto-increment value for "id" and build a hash of it. This hash should then be inserted as "short". But what sort of hash should I build? Hash algorithms like MD5 create too long strings. I don't use these algorithms, I think. A self-built algorithm will work, too.

My idea:

For "http://www.google.de/" I get the auto-increment id 239472. Then I do the following steps:

short = '';
if divisible by 2, add "a"+the result to short
if divisible by 3, add "b"+the result to short
... until I have divisors for a-z and A-Z.

That could be repeated until the number isn't divisible any more. Do you think this is a good approach? Do you have a better idea?

Due to the ongoing interest in this topic, I've published an efficient solution to GitHub, with implementations for JavaScript, PHP, Python and Java. Add your solutions if you like :)

Body:
For a quality Node.js / JavaScript solution, see the id-shortener module, which is thoroughly tested and has been used in production for months.

It provides an efficient id / URL shortener backed by pluggable storage defaulting to Redis, and you can even customize your short id character set and whether or not shortening is idempotent. This is an important distinction that not all URL shorteners take into account.

In relation to other answers here, this module implements the Marcel Jackwerth's excellent accepted answer above.

The core of the solution is provided by the following Redis Lua snippet:

local sequence = redis.call('incr', KEYS[1])

local chars = '0123456789ABCDEFGHJKLMNPQRSTUVWXYZ_abcdefghijkmnopqrstuvwxyz'
local remaining = sequence
local slug = ''

while (remaining > 0) do
  local d = (remaining % 60)
  local character = string.sub(chars, d + 1, d + 1)

  slug = character .. slug
  remaining = (remaining - d) / 60
end

redis.call('hset', KEYS[2], slug, ARGV[1])

return slug


问:
AWS Beanstalk, how to reboot (or terminate) automatically an instance that is not responding
I have my Beanstalk environment with a "Scaling Trigger" using "CPUUtilization" and it works well.

The problem is that I can not combine this with a system that automatically reboots (or terminate) instances that have been considered "OutOfService" for a certain amount of time.

Into the "Scaling > Scaling Trigger > Trigger measurement" there is the option of "UnHealthyHostCount". But this won't solve my problem optimally, because it will create new instances as far there is one unhealthy, this will provoque my environment to grow until the limit without a real reason. Also, I can not combine 2 "Trigger measurements" and I need the CPU one.

The problem becomes crucial when there is only one instance in the environment, and it becomes OutOfService. The whole environment dies, the Trigger measurement is never triggered.

答:
You can setup a CloudWatch alarm to reboot the unhealthy instance using StatusCheckFailed_Instance metric.

For detailed information on each step, go through the Adding Reboot Actions to Amazon CloudWatch Alarms section in the following AWS Documentation.


问:
What does this.function = this.function.bind(this) do in the following context? ReactJS
I am following a tutorial series on udemy and the instructor hasn't really explained the following line of code:

```<code>this.getrandomnum = this.getrandomnum.bind(this);
</code>```

So I am a bit confused as to what it does and was hoping to get some help. My code works with or without the above line.

Here is the full code:

```<code>class App extends Component {
  render() {
    return (
      <div className="App">
      <h1> Hello</h1>
      <Body />
      </div>
    );
  }
}

class Body extends Component{
  constructor(props){
    super(props);
    this.state = {};
    this.getRandomNumber = this.getRandomNumber.bind(this);
  }
  getRandomNumber(){
    console.log('some random number')
  }
  render(){
    return (
      <button onClick={this.getRandomNumber}>Random Number</button>
      )
  }
}
</code>```

答:
It binds this to the function in the class when it's called. It's importance is to retain the context of this when it's called. Typically this is done on callbacks such as the onClick handler in the Body component.

Your code still works because you're not referencing any type of context (other than the window.console function, which is the this in this case). If you didn't bind this in the constructor and had this:

```<code><button onClick={this.getRandomNumber}>Random Number</button>
</code>```

and in the getRandomNumber:

```<code>getRandomNumber(e){
    console.log(e)
}
</code>```

it would return an error that e is undefined because the context of this function is bound to the window object. In this case e does not exist.

Read more about: handling events in the React docs and bind

Body:
I am following a tutorial series on udemy and the instructor hasn't really explained the following line of code:

this.getrandomnum = this.getrandomnum.bind(this);

So I am a bit confused as to what it does and was hoping to get some help. My code works with or without the above line.

Here is the full code:

class App extends Component {
  render() {
    return (

 Hello

    );
  }
}

class Body extends Component{
  constructor(props){
    super(props);
    this.state = {};
    this.getRandomNumber = this.getRandomNumber.bind(this);
  }
  getRandomNumber(){
    console.log('some random number')
  }
  render(){
    return (
      <button onClick={this.getRandomNumber}>Random Number</button>
      )
  }
}

Body:
It binds this to the function in the class when it's called. It's importance is to retain the context of this when it's called. Typically this is done on callbacks such as the onClick handler in the Body component.

Your code still works because you're not referencing any type of context (other than the window.console function, which is the this in this case). If you didn't bind this in the constructor and had this:

<button onClick={this.getRandomNumber}>Random Number</button>

and in the getRandomNumber:

getRandomNumber(e){
    console.log(e)
}

it would return an error that e is undefined because the context of this function is bound to the window object. In this case e does not exist.

Read more about: handling events in the React docs and bind


问:
Dynamic w/ memory pool VS Static
I've been under the impression that dynamic memory allocation is slower than static memory allocation, I then read about memory pools, but I'm confused

When we compare allocations, we are talking about using malloc vs initializing a variable. But then If one were to allocate a big array with malloc and access it, would we get the same performance as If we allocated it statically? Let's say you had:

```<code>int i[100];
j = malloc(sizeof(int) * 100);

// Would these two lines yield the same performance?
i[1] = 10;
j[1] = 100;
</code>```

Thank you for reading...

答: Memory is memory. Once's its allocated, it all behaves the same. Only the allocation is slower.</p>

Title: Dynamic w/ memory pool VS Static

Body:
I've been under the impression that dynamic memory allocation is slower than static memory allocation, I then read about memory pools, but I'm confused

When we compare allocations, we are talking about using malloc vs initializing a variable. But then If one were to allocate a big array with malloc and access it, would we get the same performance as If we allocated it statically? Let's say you had:

int i[100];
j = malloc(sizeof(int) * 100);

// Would these two lines yield the same performance?
i[1] = 10;
j[1] = 100;

Thank you for reading...