问:
JSON encoding NDB entities with keys
I'm trying to create a CRUD application with Google Cloud ndb and REST architecture.

Therefore I have different API calls for creating and retrieving.

Now to update the entities I need to display them in the front end but also give an identifier, so ndb knows which entity to update later.

I try to get the entities with model.query and then encode them to JSON with an extended encoder to serialize datetime and ndb.Key:

```<code># JSONEncoder extension to handle datetime & ndb.Key
class CustomJsonEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.strftime('%Y-%m-%d-%H-%M-%S')
        if isinstance(obj, ndb.Key):
            return obj.urlsafe()
        return json.JSONEncoder.default(self, obj)

# Get JSON data from ndb
query = Card.query(Card.category==category, ancestor=ancestor_key()).fetch()
cards = json.dumps([c.to_dict() for c in query], cls=CustomJsonEncoder)
                self.response.headers['Content-Type'] = 'application/json'
                self.response.out.write(cards)
</code>```

My problem now is that the entity key just disappears and isn't shown in the json.dump anymore. I don't get any errors, it's just not encoded and passed along.

The datetime object is shown correctly when printed. Any ideas on how I can send the URL safe ndb key along with the json.dump?

答:
You're dumping Card entity objects, which do not include the respective object keys. To confirm this just temporarily add a logging statement like this to your CustomJsonEncoder:

```<code>if isinstance(obj, ndb.Key):
    logging.error('key found: %s' % obj.urlsafe())
    return obj.urlsafe()
</code>```

You need to explicitly add the entity keys to the data to be json-encoded if you want them.

Or you could use a ComputedProperty in that entity's model (but then you'd be wasting some storage):

```<code>key_str = ndb.ComputedProperty(lambda self: self.key.urlsafe())
</code>```

Title: JSON encoding NDB entities with keys

Body:
I'm trying to create a CRUD application with Google Cloud ndb and REST architecture.

Therefore I have different API calls for creating and retrieving.

Now to update the entities I need to display them in the front end but also give an identifier, so ndb knows which entity to update later.

I try to get the entities with model.query and then encode them to JSON with an extended encoder to serialize datetime and ndb.Key:

# JSONEncoder extension to handle datetime & ndb.Key
class CustomJsonEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.strftime('%Y-%m-%d-%H-%M-%S')
        if isinstance(obj, ndb.Key):
            return obj.urlsafe()
        return json.JSONEncoder.default(self, obj)

# Get JSON data from ndb
query = Card.query(Card.category==category, ancestor=ancestor_key()).fetch()
cards = json.dumps([c.to_dict() for c in query], cls=CustomJsonEncoder)
                self.response.headers['Content-Type'] = 'application/json'
                self.response.out.write(cards)

My problem now is that the entity key just disappears and isn't shown in the json.dump anymore. I don't get any errors, it's just not encoded and passed along.

The datetime object is shown correctly when printed. Any ideas on how I can send the URL safe ndb key along with the json.dump?

Body:
You're dumping Card entity objects, which do not include the respective object keys. To confirm this just temporarily add a logging statement like this to your CustomJsonEncoder:

if isinstance(obj, ndb.Key):
    logging.error('key found: %s' % obj.urlsafe())
    return obj.urlsafe()

You need to explicitly add the entity keys to the data to be json-encoded if you want them.

Or you could use a ComputedProperty in that entity's model (but then you'd be wasting some storage):

key_str = ndb.ComputedProperty(lambda self: self.key.urlsafe())


来源: stackexchange

问:
implementing emberjs with laravel project
i am trying to implement ember.js in a laravel project, so that laravel will be an API server and the front end would be rendered by ember.js any advice on how to go about it ?</p>

答:
I suggest you to watch this video. It's great and helpful with any combination of frameworks.

In general, you should first install ember-cli and create a fron-end app. Use ember-cli-mirage to simulate an API server. While doing this you can write API documentation as well. Then implement an api using laravel. Deploy both parts somewhere. That's all.

Others may suggest to begin with API, but I insist on implementing frontend first. Because ember is an opinionated framework, especially it's data layer - Ember Data, and it is easier to create API according to ember's standards than adjust ember app to work with API. Other way is possible too, just somewhat harder (more code to write and maintain, more headache).

Someone may as well suggest to create an api and front in the same time. As for me, I think it's easier when you concentrate on each part separately.

ContentLicense: CC BY-SA 3.0


问:
Setting Dynamic Env variable in Docker
I am trying to set dynamic env variable in Docker but somehow it resets.
I want to set an ENV variable which has value :

```<code>export EC2_Region=$(curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone)
</code>```

so i cant just use ENV in Dockerfile since its not static.

I tried making an init.sh and used CMD["init.sh"] in Dockerfile but when i attach to the docker process, the env variable is empty.

I am fairy new to docker and still exploring options.

Thanks in advance !

答:
You can use ENTRYPOINT instead of CMD.

Example Dockerfile:

```<code>FROM ubuntu:14.04
COPY init.sh /
RUN chmod +x /init.sh
ENTRYPOINT ["/init.sh"]
</code>```

init.sh:

```<code>export EC2_Region=$(curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone)
</code>```

Title: Setting Dynamic Env variable in Docker

Body:
I am trying to set dynamic env variable in Docker but somehow it resets.
I want to set an ENV variable which has value :

export EC2_Region=$(curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone)

so i cant just use ENV in Dockerfile since its not static.

I tried making an init.sh and used CMD["init.sh"] in Dockerfile but when i attach to the docker process, the env variable is empty.

I am fairy new to docker and still exploring options.

Thanks in advance !

Body:
You can use ENTRYPOINT instead of CMD.

Example Dockerfile:

FROM ubuntu:14.04
COPY init.sh /
RUN chmod +x /init.sh
ENTRYPOINT ["/init.sh"]

init.sh:

export EC2_Region=$(curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone)


问:
select all checkboxes of a form
In my rails application, i am displaying some records. I am using pagination for records..
i have a javascript function to select all the checkboxes associated with a record..But it selects checkboxes of only current page. I want to have a feature where i can select all the checboxes of current page and then move to next page selec there and then submit all of them together.</p>

答: Recently I have done the same task as you. I am using table with Ajax pagination, so I can remember all checked positions in array or other object. Then I've added on-click handler to submit button where hidden fields are adding to form to make the same effect as missing checkboxes. </p>

ContentLicense: CC BY-SA 2.5

Title: select all checkboxes of a form


问:
DSE 5 docvalues supported?
Does DSE 5 support docvalues and, if so, is it going to be supported in 5.1? As this piece of documentation has conflicting information, indicating support throughout the article but having this note at the end:

Note: docValues are not supported

答:
This is a documentation bug, docValues are supported. There may be a specific edge case that the docs meant to convey that somehow got cut off.

I will investigate and update both this answer and the docs.

Update

It looks like the current limitation is the combination of boolean fields and docvalues. Docs will be updated.

Title: DSE 5 docvalues supported?


问:
Vue ElementUI MessageBox with HTML Message?
I'm trying to use the MessageBox of ElementUI in my Vue app to show dynamic HTML content.  The content is coming from JSON data as an HTML string, that essentially needs to be parsed into HTML.  Normally, you could do this using the directive v-html, but there's no such apparent option with the MessageBox component.

Apparently, you can render HTML in the message, but you have to use the VNode method(?).  The examples I've seen show how to do this if you write the HTML in the script, but as I'm pulling preformatted HTML as a string from JSON data I don't see how I can use this to my advantage.

I might just have to switch to another modal component, but as I'm using several of the ElementUI components already I'd rather keep it all part of the same system.

Here's my script:

```<code><template>
    <div>
        <el-button
            v-if="body"
            type="text"
            @click="openModal"
        >More Info
        </el-button>
    </div>
</template>

<script>
export default {

    methods: {
        openModal() {
            const h = this.$createElement;

            this.$msgbox( {
                title: this.title,
                message: this.body,
                confirmButtonText: 'OK',
                closeOnClickModal: true,
                showCancelButton: false
            } );
        }
    },
    props: {
        body: String, // The MessageBox message
        title: String // The MessageBox title
    }
}
</script>
</code>```

答:
One potential solution is to compile the HTML into a render function and pass that to Vue's createElement.

```<code>message: this.$createElement(Vue.compile(this.body))
</code>```

Here is an example based of the documentation.

Body:
I'm trying to use the MessageBox of ElementUI in my Vue app to show dynamic HTML content.  The content is coming from JSON data as an HTML string, that essentially needs to be parsed into HTML.  Normally, you could do this using the directive v-html, but there's no such apparent option with the MessageBox component.

Apparently, you can render HTML in the message, but you have to use the VNode method(?).  The examples I've seen show how to do this if you write the HTML in the script, but as I'm pulling preformatted HTML as a string from JSON data I don't see how I can use this to my advantage.

I might just have to switch to another modal component, but as I'm using several of the ElementUI components already I'd rather keep it all part of the same system.

Here's my script:

<template>

        <el-button
            v-if="body"
            type="text"
            @click="openModal"
        >More Info
        </el-button>

</template>

Body:
One potential solution is to compile the HTML into a render function and pass that to Vue's createElement.

message: this.$createElement(Vue.compile(this.body))

Here is an example based of the documentation.


问:
My button's background-color us not working in IE
I have a button with a background-color that is not working in IE 11.

This one is what it should like look (Firefox)

And in IE:

.loginButton {
    width: 100% !important;
    background-color: rgb(0, 148, 146, 0.8) !important;
    border: 0px !important;
    font-size: 2em !important;
    letter-spacing: 1px !important;
    border: 0px !important;
    margin-bottom: 5% !important;
    filter: none !important;
    overflow: hidden !important;
}

.loginButton span {
    cursor: pointer !important;
    display: inline-block !important;
    position: relative !important;
    transition: 2.5s !important;
}

.loginButton span:after {
    font-family: FontAwesome !important;
    content: "\f101" !important;
    position: absolute !important;
    opacity: 0 !important;
    top: 0 !important;
    right: -20px !important;
    transition: 0.5s !important;
}

.loginButton:hover {
    border-color: rgb(31, 153, 214) !important;
    padding-right: 30px !important;
    color: #ffffff !important;
    transition: all 0.9s ease !important;
}

.loginButton:hover span {
    padding-right: 30px !important;
    color: #ffffff !important;
    letter-spacing: 3px !important;
    transition: all 0.9s ease !important;
}

.loginButton:hover span:after {
    opacity: 1 !important;
    right: 0px !important;
}

.loginButton:after {
    width: 100% !important;
    background-color: white !important;
    border: 0px !important;
    font-size: 2em !important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><b:commandButton styleClass="loginButton" tooltip-position="right" tooltip="Melde dich beim IUBH-Ticketssystem an">
    <span>Anmelden </span>
</b:commandButton></code>```

答:
I can't understand why your background-color working on Firefox.
In my demo, i got error invalid value

```<code>background-color: rgb(0, 148, 146, 0.8) !important;
</code>```

should be changed to

```<code>background-color: rgba(0, 148, 146, 0.8) !important;
</code>```

https://jsfiddle.net/5qbbmx4z/6/

And You should NOT use !important as much as possible.

Body:
I have a button with a background-color that is not working in IE 11.

This one is what it should like look (Firefox)

And in IE:

.loginButton {
    width: 100% !important;
    background-color: rgb(0, 148, 146, 0.8) !important;
    border: 0px !important;
    font-size: 2em !important;
    letter-spacing: 1px !important;
    border: 0px !important;
    margin-bottom: 5% !important;
    filter: none !important;
    overflow: hidden !important;
}

.loginButton span {
    cursor: pointer !important;
    display: inline-block !important;
    position: relative !important;
    transition: 2.5s !important;
}

.loginButton span:after {
    font-family: FontAwesome !important;
    content: "\f101" !important;
    position: absolute !important;
    opacity: 0 !important;
    top: 0 !important;
    right: -20px !important;
    transition: 0.5s !important;
}

.loginButton:hover {
    border-color: rgb(31, 153, 214) !important;
    padding-right: 30px !important;
    color: #ffffff !important;
    transition: all 0.9s ease !important;
}

.loginButton:hover span {
    padding-right: 30px !important;
    color: #ffffff !important;
    letter-spacing: 3px !important;
    transition: all 0.9s ease !important;
}

.loginButton:hover span:after {
    opacity: 1 !important;
    right: 0px !important;
}

.loginButton:after {
    width: 100% !important;
    background-color: white !important;
    border: 0px !important;
    font-size: 2em !important;
}

    Anmelden

Body:
I can't understand why your background-color working on Firefox.
In my demo, i got error invalid value

background-color: rgb(0, 148, 146, 0.8) !important;

should be changed to

background-color: rgba(0, 148, 146, 0.8) !important;

https://jsfiddle.net/5qbbmx4z/6/

And You should NOT use !important as much as possible.


问:
Error: premature end of file for XML document?
I have to generate XML and XSD from this diagram:

But an error: premature end of file pops up.
I also encounter another error: xsd:all must terminate with end tag
Is my code correct?

Entity Relation Constraints:

```<code>1. A theater can have at least 1 screen but not more than 3.
2. A screen may have many shows and sometimes it may not have any show.
   show-time example - 10 AM, 12 PM etc.
3. A show has information on the movie which has the director name, title
   and the release date which can occur in any order.
4. A movie will have actors and actors may have many actor's name.
</code>```

Code:

```<code><?xml version="1.0" encoding="UTF-8"?>
<theater>
<name>rajat</name>
<address>mumbai</address>
<phone>987654</phone>
    <screen>
        <seats>30</seats>
        <width>30</width>
            <show>
                <show-time>10 AM</show-time>
                    <movie>
                        <director>jade</director>
                        <title>game</title>
                        <release-date>10/10/2017</release-date>
                            <actors>
                                <name>james</name>
                                <name>aaron</name>
                            </actors>
                    </movie>
            </show>
    </screen>
</theater>
</code>```

XSD:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="https://www.w3.org/2001/XMLSchema"
attributeFormDefault="unqualified" elementFormDefault="qualified">
<xsd:element name="theater">
<xsd:complexType>
<xsd:sequence>
    <xsd:element name="name" type="xsd:string"/>
    <xsd:element name="address" type="xsd:string"/>
    <xsd:element name="phone" type="xsd:long"/>
    <xsd:element name="screen" maxOccurs="3"/>
<xsd:complexType>
<xsd:sequence>
    <xsd:element name="seats" type="xsd:byte"/>
    <xsd:element name="width" type="xsd:byte"/>
    <xsd:element name="show" minOccurs="0"/>
<xsd:complexType>
<xsd:sequence>
    <xsd:element name="show-time" type="xsd:string" maxOccurs="unbounded"
    minOccurs="0"/>
    <xsd:element name="movie"/>
<xsd:complexType>
<xsd:all>
    <xsd:element name="director" type="xsd:string"/>
    <xsd:element name="title" type="xsd:string"/>
    <xsd:element name="release-date" type="xsd:string"/>
    <xsd:element name="actors"/>
<xsd:complexType>
<xsd:sequence>
    <xsd:element name="name" type="xsd:string" maxOccurs="unbounded"
    minOccurs="0"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:all>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
</code>```

答:
First:

```<code>xmlns:xsd="https://www.w3.org/2001/XMLSchema"
</code>```

must instead be

```<code>xmlns:xsd="http://www.w3.org/2001/XMLSchema"
</code>```

Second:

```<code>    <xsd:element name="screen" maxOccurs="3"/>
      <xsd:complexType>
</code>```

must instead be

```<code>    <xsd:element name="screen" maxOccurs="3">
      <xsd:complexType>
</code>```

The above type of error occurs in multiple places.

Third:

Finally, use an XML editor and balance your closing tags.

Altogether, here is your XSD fixed to be syntactically valid:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            attributeFormDefault="unqualified" elementFormDefault="qualified">
  <xsd:element name="theater">
    <xsd:complexType>
      <xsd:sequence>
        <xsd:element name="name" type="xsd:string"/>
        <xsd:element name="address" type="xsd:string"/>
        <xsd:element name="phone" type="xsd:long"/>
        <xsd:element name="screen" maxOccurs="3">
          <xsd:complexType>
            <xsd:sequence>
              <xsd:element name="seats" type="xsd:byte"/>
              <xsd:element name="width" type="xsd:byte"/>
              <xsd:element name="show" minOccurs="0">
                <xsd:complexType>
                  <xsd:sequence>
                    <xsd:element name="show-time" type="xsd:string"
                                 maxOccurs="unbounded"
                                 minOccurs="0"/>
                    <xsd:element name="movie">
                      <xsd:complexType>
                        <xsd:all>
                          <xsd:element name="director" type="xsd:string"/>
                          <xsd:element name="title" type="xsd:string"/>
                          <xsd:element name="release-date" type="xsd:string"/>
                          <xsd:element name="actors">
                          <xsd:complexType>
                            <xsd:sequence>
                              <xsd:element name="name" type="xsd:string"
                                           maxOccurs="unbounded"
                                           minOccurs="0"/>
                            </xsd:sequence>
                          </xsd:complexType>
                          </xsd:element>
                        </xsd:all>
                      </xsd:complexType>
                    </xsd:element>
                  </xsd:sequence>
                </xsd:complexType>
              </xsd:element>
            </xsd:sequence>
          </xsd:complexType>
        </xsd:element>
      </xsd:sequence>
    </xsd:complexType>
  </xsd:element>
</xsd:schema>
</code>```

Validation against your XML document is left as an exercise for you to do.

Body:
I have to generate XML and XSD from this diagram:

But an error: premature end of file pops up.
I also encounter another error: xsd:all must terminate with end tag
Is my code correct?

Entity Relation Constraints:

1. A theater can have at least 1 screen but not more than 3.
2. A screen may have many shows and sometimes it may not have any show.
   show-time example - 10 AM, 12 PM etc.
3. A show has information on the movie which has the director name, title
   and the release date which can occur in any order.
4. A movie will have actors and actors may have many actor's name.

Code:

<?xml version="1.0" encoding="UTF-8"?>
<theater>
<name>rajat</name>
<address>mumbai</address>
<phone>987654</phone>
    <screen>
        <seats>30</seats>
        <width>30</width>
            <show>
                <show-time>10 AM</show-time>
                    <movie>
                        <director>jade</director>
                        <title>game</title>
                        <release-date>10/10/2017</release-date>
                            <actors>
                                <name>james</name>
                                <name>aaron</name>
                            </actors>
                    </movie>
            </show>
    </screen>
</theater>

XSD:

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="https://www.w3.org/2001/XMLSchema"
attributeFormDefault="unqualified" elementFormDefault="qualified">
<xsd:element name="theater">
<xsd:complexType>
<xsd:sequence>
    <xsd:element name="name" type="xsd:string"/>
    <xsd:element name="address" type="xsd:string"/>
    <xsd:element name="phone" type="xsd:long"/>
    <xsd:element name="screen" maxOccurs="3"/>
<xsd:complexType>
<xsd:sequence>
    <xsd:element name="seats" type="xsd:byte"/>
    <xsd:element name="width" type="xsd:byte"/>
    <xsd:element name="show" minOccurs="0"/>
<xsd:complexType>
<xsd:sequence>
    <xsd:element name="show-time" type="xsd:string" maxOccurs="unbounded"
    minOccurs="0"/>
    <xsd:element name="movie"/>
<xsd:complexType>
<xsd:all>
    <xsd:element name="director" type="xsd:string"/>
    <xsd:element name="title" type="xsd:string"/>
    <xsd:element name="release-date" type="xsd:string"/>
    <xsd:element name="actors"/>
<xsd:complexType>
<xsd:sequence>
    <xsd:element name="name" type="xsd:string" maxOccurs="unbounded"
    minOccurs="0"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:all>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>

Body:
First:

xmlns:xsd="https://www.w3.org/2001/XMLSchema"

must instead be

xmlns:xsd="http://www.w3.org/2001/XMLSchema"

Second:

    <xsd:element name="screen" maxOccurs="3"/>
      <xsd:complexType>

must instead be

    <xsd:element name="screen" maxOccurs="3">
      <xsd:complexType>

The above type of error occurs in multiple places.

Third:

Finally, use an XML editor and balance your closing tags.

Altogether, here is your XSD fixed to be syntactically valid:

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            attributeFormDefault="unqualified" elementFormDefault="qualified">
  <xsd:element name="theater">
    <xsd:complexType>
      <xsd:sequence>
        <xsd:element name="name" type="xsd:string"/>
        <xsd:element name="address" type="xsd:string"/>
        <xsd:element name="phone" type="xsd:long"/>
        <xsd:element name="screen" maxOccurs="3">
          <xsd:complexType>
            <xsd:sequence>
              <xsd:element name="seats" type="xsd:byte"/>
              <xsd:element name="width" type="xsd:byte"/>
              <xsd:element name="show" minOccurs="0">
                <xsd:complexType>
                  <xsd:sequence>
                    <xsd:element name="show-time" type="xsd:string"
                                 maxOccurs="unbounded"
                                 minOccurs="0"/>
                    <xsd:element name="movie">
                      <xsd:complexType>
                        <xsd:all>
                          <xsd:element name="director" type="xsd:string"/>
                          <xsd:element name="title" type="xsd:string"/>
                          <xsd:element name="release-date" type="xsd:string"/>
                          <xsd:element name="actors">
                          <xsd:complexType>
                            <xsd:sequence>
                              <xsd:element name="name" type="xsd:string"
                                           maxOccurs="unbounded"
                                           minOccurs="0"/>
                            </xsd:sequence>
                          </xsd:complexType>
                          </xsd:element>
                        </xsd:all>
                      </xsd:complexType>
                    </xsd:element>
                  </xsd:sequence>
                </xsd:complexType>
              </xsd:element>
            </xsd:sequence>
          </xsd:complexType>
        </xsd:element>
      </xsd:sequence>
    </xsd:complexType>
  </xsd:element>
</xsd:schema>

Validation against your XML document is left as an exercise for you to do.


问:
Looking for ways to simplify my code
I'm having trouble adding another function in that macro I used to activate or deactivate columns in a Excel Workbook we are using at work. I'm getting the Out of stack space error when running it just adding one of the following function.

Mostly, I've used an If( ;1;0) to manage the activation part and an If(;TRUE;FALSE) for the locked/unlocked part. The function I want to had is based on the same idea using a verification code to Clearcontents of a cell and locked it. If the verification code is false, then, I want the cell to be unlocked so the user can write the value. Here is the code line I want to had times 15 as already done for the locked, unlocked function.

```<code>If Range("AS16") = "Vrai" Then
Range("AA16").ClearContents
Range("AA16").Locked = True
Else:
Range("AA16").Locked = False
End If
</code>```

Here is the code I'm using right now.

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
ActiveSheet.Unprotect ("Francis")
Dim Cell As Range
Set Cell = ActiveCell
Application.ScreenUpdating = False

For Each cellule In Range("S50:X50")
If cellule.Value = "1" Then cellule.EntireColumn.Hidden = False
Next cellule

For Each cellule In Range("S50:X50")
If cellule.Value = "0" Then cellule.EntireColumn.Hidden = True
Next cellule

For Each cellule In Range("I50:J50")
If cellule.Value = "1" Then cellule.EntireColumn.Hidden = False
Next cellule

For Each cellule In Range("I50:J50")
If cellule.Value = "0" Then cellule.EntireColumn.Hidden = True
Next cellule

If Range("AR16") = "Vrai" Then
Range("K16").Locked = False
Range("O16").Locked = False
Else:
Range("K16").Locked = True
Range("O16").Locked = True
End If

If Range("AR18") = "Vrai" Then
Range("K18").Locked = False
Range("O18").Locked = False
Else:
Range("K18").Locked = True
Range("O18").Locked = True
End If

If Range("AR20") = "Vrai" Then
Range("K20").Locked = False
Range("O20").Locked = False
Else:
Range("K20").Locked = True
Range("O20").Locked = True
End If

If Range("AR22") = "Vrai" Then
Range("K22").Locked = False
Range("O22").Locked = False
Else:
Range("K22").Locked = True
Range("O22").Locked = True
End If

If Range("AR24") = "Vrai" Then
Range("K24").Locked = False
Range("O24").Locked = False
Else:
Range("K24").Locked = True
Range("O24").Locked = True
End If

If Range("AR26") = "Vrai" Then
Range("K26").Locked = False
Range("O26").Locked = False
Else:
Range("K26").Locked = True
Range("O26").Locked = True
End If

If Range("AR28") = "Vrai" Then
Range("K28").Locked = False
Range("O28").Locked = False
Else:
Range("K28").Locked = True
Range("O28").Locked = True
End If

If Range("AR30") = "Vrai" Then
Range("K30").Locked = False
Range("O30").Locked = False
Else:
Range("K30").Locked = True
Range("O30").Locked = True
End If

If Range("AR32") = "Vrai" Then
Range("K32").Locked = False
Range("O32").Locked = False
Else:
Range("K32").Locked = True
Range("O32").Locked = True
End If

If Range("AR34") = "Vrai" Then
Range("K34").Locked = False
Range("O34").Locked = False
Else:
Range("K34").Locked = True
Range("O34").Locked = True
End If

If Range("AR36") = "Vrai" Then
Range("K36").Locked = False
Range("O36").Locked = False
Else:
Range("K36").Locked = True
Range("O36").Locked = True
End If

If Range("AR38") = "Vrai" Then
Range("K38").Locked = False
Range("O38").Locked = False
Else:
Range("K38").Locked = True
Range("O38").Locked = True
End If

If Range("AR40") = "Vrai" Then
Range("K40").Locked = False
Range("O40").Locked = False
Else:
Range("K40").Locked = True
Range("O40").Locked = True
End If

If Range("AR42") = "Vrai" Then
Range("K42").Locked = False
Range("O42").Locked = False
Else:
Range("K42").Locked = True
Range("O42").Locked = True
End If

If Range("AR44") = "Vrai" Then
Range("K44").Locked = False
Range("O44").Locked = False
Else:
Range("K44").Locked = True
Range("O44").Locked = True
End If

Application.ScreenUpdating = True
Application.Goto Cell

'ActiveSheet.Protect Password:="Francis"
End Sub
</code>```

Thanks a lot for your help.

Have a nice day!

答:
You typically don't want to have performance-expensive code running in that specific handler. Worksheet_Change gets invoked every time a cell changes... and that includes changing a cell's Locked property value.

So that's how you run out of stack space: your handler is modifying cells' Locked state, which triggers the Worksheet_Change event, which modifies cells' Locked state, which triggers the Worksheet_Change event, which modifies cells' Locked state, which triggers the Worksheet_Change event, which... which eventually blows the call stack.

So prevent this accidental recursion, you need to prevent Excel from firing worksheet events when you're handling one:

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
    On Error GoTo CleanFail
    Application.EnableEvents = False
    'do stuff
CleanExit:
    Application.EnableEvents = True
    Exit Sub
CleanFail:
    'handle errors here...
    Resume CleanExit
End Sub
</code>```

As for simplifying the code, that's more of a mandate for Code Review Stack Exchange, once your code works as intended.

If any C# dev is reading this, this particular situation now has an up-for-grabs issue on Rubberduck's GitHub repository: #3109 Prevent accidental recursion in Worksheet_Change and Workbook_SheetChange handlers; once that inspection is implemented, Rubberduck will be able to warn you when you handle Worksheet_Change without disabling application events.

Title: Looking for ways to simplify my code

Body:
I'm having trouble adding another function in that macro I used to activate or deactivate columns in a Excel Workbook we are using at work. I'm getting the Out of stack space error when running it just adding one of the following function.

Mostly, I've used an If( ;1;0) to manage the activation part and an If(;TRUE;FALSE) for the locked/unlocked part. The function I want to had is based on the same idea using a verification code to Clearcontents of a cell and locked it. If the verification code is false, then, I want the cell to be unlocked so the user can write the value. Here is the code line I want to had times 15 as already done for the locked, unlocked function.

If Range("AS16") = "Vrai" Then
Range("AA16").ClearContents
Range("AA16").Locked = True
Else:
Range("AA16").Locked = False
End If

Here is the code I'm using right now.

Private Sub Worksheet_Change(ByVal Target As Range)
ActiveSheet.Unprotect ("Francis")
Dim Cell As Range
Set Cell = ActiveCell
Application.ScreenUpdating = False

For Each cellule In Range("S50:X50")
If cellule.Value = "1" Then cellule.EntireColumn.Hidden = False
Next cellule

For Each cellule In Range("S50:X50")
If cellule.Value = "0" Then cellule.EntireColumn.Hidden = True
Next cellule

For Each cellule In Range("I50:J50")
If cellule.Value = "1" Then cellule.EntireColumn.Hidden = False
Next cellule

For Each cellule In Range("I50:J50")
If cellule.Value = "0" Then cellule.EntireColumn.Hidden = True
Next cellule

If Range("AR16") = "Vrai" Then
Range("K16").Locked = False
Range("O16").Locked = False
Else:
Range("K16").Locked = True
Range("O16").Locked = True
End If

If Range("AR18") = "Vrai" Then
Range("K18").Locked = False
Range("O18").Locked = False
Else:
Range("K18").Locked = True
Range("O18").Locked = True
End If

If Range("AR20") = "Vrai" Then
Range("K20").Locked = False
Range("O20").Locked = False
Else:
Range("K20").Locked = True
Range("O20").Locked = True
End If

If Range("AR22") = "Vrai" Then
Range("K22").Locked = False
Range("O22").Locked = False
Else:
Range("K22").Locked = True
Range("O22").Locked = True
End If

If Range("AR24") = "Vrai" Then
Range("K24").Locked = False
Range("O24").Locked = False
Else:
Range("K24").Locked = True
Range("O24").Locked = True
End If

If Range("AR26") = "Vrai" Then
Range("K26").Locked = False
Range("O26").Locked = False
Else:
Range("K26").Locked = True
Range("O26").Locked = True
End If

If Range("AR28") = "Vrai" Then
Range("K28").Locked = False
Range("O28").Locked = False
Else:
Range("K28").Locked = True
Range("O28").Locked = True
End If

If Range("AR30") = "Vrai" Then
Range("K30").Locked = False
Range("O30").Locked = False
Else:
Range("K30").Locked = True
Range("O30").Locked = True
End If

If Range("AR32") = "Vrai" Then
Range("K32").Locked = False
Range("O32").Locked = False
Else:
Range("K32").Locked = True
Range("O32").Locked = True
End If

If Range("AR34") = "Vrai" Then
Range("K34").Locked = False
Range("O34").Locked = False
Else:
Range("K34").Locked = True
Range("O34").Locked = True
End If

If Range("AR36") = "Vrai" Then
Range("K36").Locked = False
Range("O36").Locked = False
Else:
Range("K36").Locked = True
Range("O36").Locked = True
End If

If Range("AR38") = "Vrai" Then
Range("K38").Locked = False
Range("O38").Locked = False
Else:
Range("K38").Locked = True
Range("O38").Locked = True
End If

If Range("AR40") = "Vrai" Then
Range("K40").Locked = False
Range("O40").Locked = False
Else:
Range("K40").Locked = True
Range("O40").Locked = True
End If

If Range("AR42") = "Vrai" Then
Range("K42").Locked = False
Range("O42").Locked = False
Else:
Range("K42").Locked = True
Range("O42").Locked = True
End If

If Range("AR44") = "Vrai" Then
Range("K44").Locked = False
Range("O44").Locked = False
Else:
Range("K44").Locked = True
Range("O44").Locked = True
End If

Application.ScreenUpdating = True
Application.Goto Cell

'ActiveSheet.Protect Password:="Francis"
End Sub

Thanks a lot for your help.

Have a nice day!

Body:
You typically don't want to have performance-expensive code running in that specific handler. Worksheet_Change gets invoked every time a cell changes... and that includes changing a cell's Locked property value.

So that's how you run out of stack space: your handler is modifying cells' Locked state, which triggers the Worksheet_Change event, which modifies cells' Locked state, which triggers the Worksheet_Change event, which modifies cells' Locked state, which triggers the Worksheet_Change event, which... which eventually blows the call stack.

So prevent this accidental recursion, you need to prevent Excel from firing worksheet events when you're handling one:

Private Sub Worksheet_Change(ByVal Target As Range)
    On Error GoTo CleanFail
    Application.EnableEvents = False
    'do stuff
CleanExit:
    Application.EnableEvents = True
    Exit Sub
CleanFail:
    'handle errors here...
    Resume CleanExit
End Sub

As for simplifying the code, that's more of a mandate for Code Review Stack Exchange, once your code works as intended.

If any C# dev is reading this, this particular situation now has an up-for-grabs issue on Rubberduck's GitHub repository: #3109 Prevent accidental recursion in Worksheet_Change and Workbook_SheetChange handlers; once that inspection is implemented, Rubberduck will be able to warn you when you handle Worksheet_Change without disabling application events.


问:
Get month name from date in Oracle
How to fetch month name from a given date in Oracle?

If the given date is '15-11-2010' then I want November from this date.

答:
```<code>select to_char(sysdate, 'Month') from dual
</code>```

in your example will be:

```<code>select to_char(to_date('15-11-2010', 'DD-MM-YYYY'), 'Month') from dual
</code>```

Title: Get month name from date in Oracle

Body:
select to_char(sysdate, 'Month') from dual

in your example will be:

select to_char(to_date('15-11-2010', 'DD-MM-YYYY'), 'Month') from dual


问:
Changing Tables in Highcharts Missing Row
I have an HTML table with some data, from that table I'm creating a chart:

```<code>var chart = Highcharts.chart('graph_user_1', {
    data: {
        table: 'table_user_1',
        startColumn: 0,
        endColumn: 1
    },
    chart: {
        type: 'column'
    },
    title: {
        text: 'Coverage'
    },
    yAxis: {
        allowDecimals: true,
        title: {
            text: 'Hours'
        }
    },
    tooltip: {
        formatter: function() {
            return '<b>' + this.series.name + '</b><br/>' +
                this.point.y + ' Points - ' + this.point.name.toLowerCase();
        }
    },
    plotOptions: {
        column: {
            colorByPoint: true
        }
    },
    series: [{
        id: 'series1'
    }],
    colors: [
        '#ff0000',
        '#00ff00',
        '#0000ff',
        '#3A8BEE',
        '#F9B342',
        '#DC4008'
    ]
});
</code>```

I also have a filter, it lets me select some dates and filter the table, these rows of data that are not hidden, are appended to a hidden table on the page:

```<code>$("#to_date").on("change", function() {
    var from = parseDate($('#from_date').val());
    var to = parseDate($('#to_date').val());
    var loop_count = 0;
    var hidden_count = 0;
    $("#body tr").each(function() {
        var row = $(this);
        var date_from = parseDate(row.find("td").eq(7).text());
        var date_to = parseDate(row.find("td").eq(8).text());
        var show = true;
        show = isContained(date_from, date_to, from, to);
        if (show) {
            row.show();
            legendArray.push(row); //pushes row to array
        } else {
            row.hide();
            hidden_count++;
        }
        loop_count++;
    });
    if (hidden_count === loop_count) {
        warning.prop("hidden", false);
        warning.append("<strong>No results.</strong>");
    }
    restore(legendArray, chart);
});
</code>```

The restore function at the end gets the array with rows and a chart reference, it appends the rows from the array to the new table, then changes the source of the data from the original to the hidden table (id="aux") and redraws it.

```<code>function restore(array) {
var table = document.getElementById('auxBody');
for (var i = 0; i <= array.length - 1; i++) {
    table.appendChild(array[i][0].cloneNode(true));
}
var complete = function(options) {
    var chart = $('#graph_user_1').highcharts();
    var series1 = chart.get('series1');
    series1.setData(options.series[0].data, false);
    chart.redraw();
};

Highcharts.data({
    table: 'aux',
    complete: complete
});
</code>```

}

After this, the graph IS updated, but it's always missing one row, the last one. I've printed the array, the new table, the nodes that are being appended, inspected, etc. All of this show the table with all the rows, but the graph is always missing the last one, I thought it was an index problem in the loop that adds the nodes but that doesn't seems to be the case.

答:
As I posted earlier, it was a header issue with the table.
At creation I was appending the outerHTML of the copied table head:

```<code>newTable.append(newTHead[0].outerHTML);
</code>```

Of course this caused an issue and the table had no headers, (even though it still showed on inspect) solution was removing the outerHTML and just appending the node, just a dumb conceptual mistake.

```<code>newTable.append(newTHead[0]);
</code>```

Body:
I have an HTML table with some data, from that table I'm creating a chart:

var chart = Highcharts.chart('graph_user_1', {
    data: {
        table: 'table_user_1',
        startColumn: 0,
        endColumn: 1
    },
    chart: {
        type: 'column'
    },
    title: {
        text: 'Coverage'
    },
    yAxis: {
        allowDecimals: true,
        title: {
            text: 'Hours'
        }
    },
    tooltip: {
        formatter: function() {
            return '' + this.series.name + '
' +
                this.point.y + ' Points - ' + this.point.name.toLowerCase();
        }
    },
    plotOptions: {
        column: {
            colorByPoint: true
        }
    },
    series: [{
        id: 'series1'
    }],
    colors: [
        '#ff0000',
        '#00ff00',
        '#0000ff',
        '#3A8BEE',
        '#F9B342',
        '#DC4008'
    ]
});

I also have a filter, it lets me select some dates and filter the table, these rows of data that are not hidden, are appended to a hidden table on the page:

$("#to_date").on("change", function() {
    var from = parseDate($('#from_date').val());
    var to = parseDate($('#to_date').val());
    var loop_count = 0;
    var hidden_count = 0;
    $("#body tr").each(function() {
        var row = $(this);
        var date_from = parseDate(row.find("td").eq(7).text());
        var date_to = parseDate(row.find("td").eq(8).text());
        var show = true;
        show = isContained(date_from, date_to, from, to);
        if (show) {
            row.show();
            legendArray.push(row); //pushes row to array
        } else {
            row.hide();
            hidden_count++;
        }
        loop_count++;
    });
    if (hidden_count === loop_count) {
        warning.prop("hidden", false);
        warning.append("No results.");
    }
    restore(legendArray, chart);
});

The restore function at the end gets the array with rows and a chart reference, it appends the rows from the array to the new table, then changes the source of the data from the original to the hidden table (id="aux") and redraws it.

function restore(array) {
var table = document.getElementById('auxBody');
for (var i = 0; i <= array.length - 1; i++) {
    table.appendChild(array[i][0].cloneNode(true));
}
var complete = function(options) {
    var chart = $('#graph_user_1').highcharts();
    var series1 = chart.get('series1');
    series1.setData(options.series[0].data, false);
    chart.redraw();
};

Highcharts.data({
    table: 'aux',
    complete: complete
});

}

After this, the graph IS updated, but it's always missing one row, the last one. I've printed the array, the new table, the nodes that are being appended, inspected, etc. All of this show the table with all the rows, but the graph is always missing the last one, I thought it was an index problem in the loop that adds the nodes but that doesn't seems to be the case.

Body:
As I posted earlier, it was a header issue with the table.
At creation I was appending the outerHTML of the copied table head:

newTable.append(newTHead[0].outerHTML);

Of course this caused an issue and the table had no headers, (even though it still showed on inspect) solution was removing the outerHTML and just appending the node, just a dumb conceptual mistake.

newTable.append(newTHead[0]);


问:
Generating random numbers with Swift
I need to generate a random number.

It appears the arc4random function no longer exists as well as the arc4random_uniform function.

The options I have are arc4random_stir(),   arc4random_buf(UnsafeMutablePointer<Void>, Int), and   arc4random_addrandom(UnsafeMutablePointer<UInt8>, Int32).

I can't find any docs on the functions and no comments in the header files give hints.

答:
Don't forget that some numbers will repeat! so you need to do something like....

my totalQuestions was 47.

```<code>func getRandomNumbers(totalQuestions:Int) -> NSMutableArray
{

    var arrayOfRandomQuestions: [Int] = []

    print("arraySizeRequired = 40")
    print("totalQuestions = \(totalQuestions)")

    //This will output a 40 random numbers between 0 and totalQuestions (47)
    while arrayOfRandomQuestions.count < 40
    {

        let limit: UInt32 = UInt32(totalQuestions)

        let theRandomNumber = (Int(arc4random_uniform(limit)))

            if arrayOfRandomQuestions.contains(theRandomNumber)
            {
                print("ping")

            }
            else
            {
            //item not found
                arrayOfRandomQuestions.append(theRandomNumber)
            }

    }

    print("Random Number set = \(arrayOfRandomQuestions)")
    print("arrayOutputCount = \(arrayOfRandomQuestions.count)")

    return arrayOfRandomQuestions as! NSMutableArray

}
</code>```

Title: Generating random numbers with Swift

Body:
Don't forget that some numbers will repeat! so you need to do something like....

my totalQuestions was 47.

func getRandomNumbers(totalQuestions:Int) -> NSMutableArray
{

    var arrayOfRandomQuestions: [Int] = []

    print("arraySizeRequired = 40")
    print("totalQuestions = \(totalQuestions)")

    //This will output a 40 random numbers between 0 and totalQuestions (47)
    while arrayOfRandomQuestions.count < 40
    {

        let limit: UInt32 = UInt32(totalQuestions)

        let theRandomNumber = (Int(arc4random_uniform(limit)))

            if arrayOfRandomQuestions.contains(theRandomNumber)
            {
                print("ping")

            }
            else
            {
            //item not found
                arrayOfRandomQuestions.append(theRandomNumber)
            }

    }

    print("Random Number set = \(arrayOfRandomQuestions)")
    print("arrayOutputCount = \(arrayOfRandomQuestions.count)")

    return arrayOfRandomQuestions as! NSMutableArray

}


问:
javascript i++ vs ++i
In javascript I have seen i++ used in many cases, and I understand that it adds one to the preceding value:

for (var i=1; i<=10; i++) {
  console.log(i);
}```
</div>
</div>
</p>

<p>But what happens when I do this:</p>

```++i;
```

And is it any different using the -- operator (besides of course that it's subtraction rather than addition)?

答:
++variable : Increment variable before using variable

variable++ : Increment variable after using variable

I figured it could be useful to include an answer with a snippet to confirm how they behave in a for loop.

Just to verify in your browser that there's really no difference when using a ++i versus a i++ in the for loop declaration.

And throwing --i versus i-- while we're at it.

console.log("-- with looping --");

console.log("using ++i in a for loop");
for (var i=1; i<=3; ++i) {
  console.log(i);
}

console.log("using i++ in a for loop");
for (var i=1; i<=3; i++) {
  console.log(i);
}

console.log("using --i in a for loop");
for (var i=3; i>=1; --i) {
  console.log(i);
}

console.log("using i-- in a for loop");
for (var i=3; i>=1; i--) {
  console.log(i);
}

console.log("-- without looping --");
var i = 1;
console.log("i: "+ i);
console.log("i++: "+ i++);
console.log("i: "+ i);
console.log("++i: "+ ++i);
console.log("i: "+ i);
console.log("--i: "+ --i);
console.log("i: "+ i);
console.log("i--: "+ i--);
console.log("i: "+ i);```

Title: javascript i++ vs ++i

Body:
In javascript I have seen i++ used in many cases, and I understand that it adds one to the preceding value:

for (var i=1; i<=10; i++) {
  console.log(i);
}

But what happens when I do this:

++i;

And is it any different using the -- operator (besides of course that it's subtraction rather than addition)?

ContentLicense: CC BY-SA 4.0


问:
providing values to Crypto-js
I've got CyryptoJs working (as a service), but I don't think I'm observing best practices with it.

```<code>import { Injectable } from '@angular/core';
import * as CryptoJS from "crypto-js";

@Injectable()
export class EncryptionService {

    constructor() {
    }

    secretKey: string = "fnord";

    encrypt(jsonObj) {
        return CryptoJS.AES.encrypt(JSON.stringify(jsonObj), this.secretKey);
    }

    decrypt(data) {
        if (data !==null && data.length > 0) {
            var bytes = CryptoJS.AES.decrypt(data.toString(), this.secretKey);
            return bytes.toString(CryptoJS.enc.Utf8);
        } else {
            return "";
        }
    }
}
</code>```

secretKey should probably not be exposed like that. What would be a smart way to deliver that value?

答:
There are a few security issues.

The encryption key needs to be unique for each user.

Use a full length key: 128, 192 or 256 bits for AES.

It is best to use a full length encryption key of random bytes obtained from a CSPRNG (Cryptographically Secure Random Number Generator).

Using a string for the key, especially a short one is not secure. If you need the user to enter a password use a key derivation function such as PBKDF2 (Password Based Key Derivation Function 2) function to derive a secure encryption key.

There needs to an IV (Initialization Vector) supplied and it needs to be a random byte array from a CSPRNG unique for each encryption. Just prefix the encrypted data with the IV for use during decryption, it does not need to be secret.

It is best to fully specify all encryptions parameters such as mode and padding for interoperability.

If there is the possibility of entering an incorrect key or an attacker replacing a file add encryption authentication.

Add a version indicator to the encrypted data so changes can be made in the future if necessary.

Finally, how are you going to store the encryption key, there is no easy answer to that.

Title: providing values to Crypto-js

Body:
I've got CyryptoJs working (as a service), but I don't think I'm observing best practices with it.

import { Injectable } from '@angular/core';
import * as CryptoJS from "crypto-js";

@Injectable()
export class EncryptionService {

    constructor() {
    }

    secretKey: string = "fnord";

    encrypt(jsonObj) {
        return CryptoJS.AES.encrypt(JSON.stringify(jsonObj), this.secretKey);
    }

    decrypt(data) {
        if (data !==null && data.length > 0) {
            var bytes = CryptoJS.AES.decrypt(data.toString(), this.secretKey);
            return bytes.toString(CryptoJS.enc.Utf8);
        } else {
            return "";
        }
    }
}

secretKey should probably not be exposed like that. What would be a smart way to deliver that value?


问:
How do I split an array into smaller arrays bsaed on a condition?
Ruby 2.4.  I have an array of strings

```<code>2.4.0 :007 > arr = ["a", "b", "g", "e", "f", "i"]
 => ["a", "b", "g", "e", "f", "h", "i"]
</code>```

How do I split my array into smaller arrays based on a condition?  I have a function -- "contains_vowel," which returns true if a string contains "a", "e", "i", "o", or "u".  How would I take an array of strings and split it into smaller arrays, using a divider function of "contains_vowel"?  That is, for the above, the resulting array of smaller arrays would be

```<code>[["a"], ["b", "g"], ["e"], ["f", "h"], ["i"]]
</code>```

If an element of the larger array satisfies the condition, it would become an array of one element.

答:
```<code>contains_vowel = ->(str) { !(str.split('') & %w|a e i o u|).empty? }

_, result = ["a", "b", "g", "e", "f", "h", "i"].
                 each_with_object([false, []]) do |e, acc|
   cv, acc[0] = acc[0], contains_vowel.(e)
   cv ^ acc.first ? acc.last << [e] : (acc.last[-1] ||= []) << e
end
result
#⇒ [["a"], ["b", "g"], ["e"], ["f", "h"], ["i"]]
</code>```

What we do here:

contains_vowel is a lambda to check whether the string contains a vowel or not.

we reduce the input array, collecting the last value (contained the previously handled string the vowel or not,) and the result.

cv ^ acc.first checks whether it was a flip-flop of vowel on the last step.

whether is was, we append a new array to the result

whether is was not, we append the string to the last array in the result.

Body:
Ruby 2.4.  I have an array of strings

2.4.0 :007 > arr = ["a", "b", "g", "e", "f", "i"]
 => ["a", "b", "g", "e", "f", "h", "i"]

How do I split my array into smaller arrays based on a condition?  I have a function -- "contains_vowel," which returns true if a string contains "a", "e", "i", "o", or "u".  How would I take an array of strings and split it into smaller arrays, using a divider function of "contains_vowel"?  That is, for the above, the resulting array of smaller arrays would be

[["a"], ["b", "g"], ["e"], ["f", "h"], ["i"]]

If an element of the larger array satisfies the condition, it would become an array of one element.

Body:
contains_vowel = ->(str) { !(str.split('') & %w|a e i o u|).empty? }

_, result = ["a", "b", "g", "e", "f", "h", "i"].
                 each_with_object([false, []]) do |e, acc|
   cv, acc[0] = acc[0], contains_vowel.(e)
   cv ^ acc.first ? acc.last << [e] : (acc.last[-1] ||= []) << e
end
result
#⇒ [["a"], ["b", "g"], ["e"], ["f", "h"], ["i"]]

What we do here:

contains_vowel is a lambda to check whether the string contains a vowel or not.

we reduce the input array, collecting the last value (contained the previously handled string the vowel or not,) and the result.

cv ^ acc.first checks whether it was a flip-flop of vowel on the last step.

whether is was, we append a new array to the result

whether is was not, we append the string to the last array in the result.


问:
How can I use Fluent API in Entity Framework 6 to Map a List of One To Many objects without a foreign key property?
I have the following classes (that i'm not able to update, add properties or add annotations to):

```<code>public class ApprovalRuleset
{
    public Guid Id { get; set; }
    public List<ApprovalRule> ApprovalRules { get; protected internal set; }
}

public class ApprovalRule
{
    public Guid Id { get; set; }
    public string Value { get; protected internal set; }
}
</code>```

I'm trying to write some Fluent API code with Entity Framework 6 to map these to two tables.

This is the ApprovalRule configuration:

```<code>public class ApprovalRuleEntityConfiguration : EntityTypeConfiguration<ApprovalRule>
{
    public ApprovalRuleEntityConfiguration()
    {
        HasKey(x => x.Id);
        Property(x => x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        Property(x => x.Value).IsRequired().HasMaxLength(450);
    }
}
</code>```

So far I've got:

```<code>public class ApprovalRulesetEntityConfiguration : EntityTypeConfiguration<ApprovalRuleset>
{
    public ApprovalRulesetEntityConfiguration()
    {
        HasKey(x => x.Id);
        Property(x => x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        HasMany(x => x.ApprovalRules);
    }
}
</code>```

The Foreign Key on table 'ApprovalRules' with columns
  'ApprovalRuleset_Id' could not be created because the principal key
  columns could not be determined. Use the AddForeignKey fluent API to
  fully specify the Foreign Key.

```<code>public class ApprovalRulesetEntityConfiguration : EntityTypeConfiguration<ApprovalRuleset>
{
    public ApprovalRulesetEntityConfiguration()
    {
        HasKey(x => x.Id);
        Property(x => x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        HasRequired(x => x.ApprovalRules)
            .WithMany()
            .HasForeignKey(x => x.Id);
    }
}
</code>```

Multiplicity conflicts with the referential constraint in Role
  'ApprovalRuleset_ApprovalRules_Target' in relationship
  'ApprovalRuleset_ApprovalRules'. Because all of the properties in the
  Dependent Role are non-nullable, multiplicity of the Principal Role
  must be '1'.

What am I missing?  I've spent ages searching stack overflow and google.

答:
You will need to add two properties in ApprovalRule class. Then mapping would be like this - </p>

```<code>public class ApprovalRuleset
{
    public Guid Id { get; set; }
    public List<ApprovalRule> ApprovalRules { get; protected internal set; }
}

public class ApprovalRule
{
    public Guid Id { get; set; }
    public string Value { get; protected internal set; }

    public int ApprovalRulesetId { get; set; }
    public virtual ApprovalRuleset ApprovalRuleset { get; set; }
}

public class ApprovalRulesetEntityConfiguration : EntityTypeConfiguration<ApprovalRuleset>
{
    public ApprovalRulesetEntityConfiguration()
    {
        HasKey(t => t.Id);
    }
}

public class ApprovalRuleEntityConfiguration : EntityTypeConfiguration<ApprovalRule>
{
    public ApprovalRuleEntityConfiguration()
    {
        HasKey(t => t.Id);

        /*Property(t => t.Value)
            .HasMaxLength(100);*/

        HasRequired(t => t.ApprovalRuleset)
            .WithMany(t => t.ApprovalRules)
            .HasForeignKey(d => d.ApprovalRulesetId);
    }
}
</code>```

Body:
I have the following classes (that i'm not able to update, add properties or add annotations to):

public class ApprovalRuleset
{
    public Guid Id { get; set; }
    public List<ApprovalRule> ApprovalRules { get; protected internal set; }
}

public class ApprovalRule
{
    public Guid Id { get; set; }
    public string Value { get; protected internal set; }
}

I'm trying to write some Fluent API code with Entity Framework 6 to map these to two tables.

This is the ApprovalRule configuration:

public class ApprovalRuleEntityConfiguration : EntityTypeConfiguration<ApprovalRule>
{
    public ApprovalRuleEntityConfiguration()
    {
        HasKey(x => x.Id);
        Property(x => x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        Property(x => x.Value).IsRequired().HasMaxLength(450);
    }
}

So far I've got:

public class ApprovalRulesetEntityConfiguration : EntityTypeConfiguration<ApprovalRuleset>
{
    public ApprovalRulesetEntityConfiguration()
    {
        HasKey(x => x.Id);
        Property(x => x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        HasMany(x => x.ApprovalRules);
    }
}

The Foreign Key on table 'ApprovalRules' with columns
  'ApprovalRuleset_Id' could not be created because the principal key
  columns could not be determined. Use the AddForeignKey fluent API to
  fully specify the Foreign Key.

public class ApprovalRulesetEntityConfiguration : EntityTypeConfiguration<ApprovalRuleset>
{
    public ApprovalRulesetEntityConfiguration()
    {
        HasKey(x => x.Id);
        Property(x => x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        HasRequired(x => x.ApprovalRules)
            .WithMany()
            .HasForeignKey(x => x.Id);
    }
}

Multiplicity conflicts with the referential constraint in Role
  'ApprovalRuleset_ApprovalRules_Target' in relationship
  'ApprovalRuleset_ApprovalRules'. Because all of the properties in the
  Dependent Role are non-nullable, multiplicity of the Principal Role
  must be '1'.

What am I missing?  I've spent ages searching stack overflow and google.

Body:
You will need to add two properties in ApprovalRule class. Then mapping would be like this -

public class ApprovalRuleset
{
    public Guid Id { get; set; }
    public List<ApprovalRule> ApprovalRules { get; protected internal set; }
}

public class ApprovalRule
{
    public Guid Id { get; set; }
    public string Value { get; protected internal set; }

    public int ApprovalRulesetId { get; set; }
    public virtual ApprovalRuleset ApprovalRuleset { get; set; }
}

public class ApprovalRulesetEntityConfiguration : EntityTypeConfiguration<ApprovalRuleset>
{
    public ApprovalRulesetEntityConfiguration()
    {
        HasKey(t => t.Id);
    }
}

public class ApprovalRuleEntityConfiguration : EntityTypeConfiguration<ApprovalRule>
{
    public ApprovalRuleEntityConfiguration()
    {
        HasKey(t => t.Id);

        /*Property(t => t.Value)
            .HasMaxLength(100);*/

        HasRequired(t => t.ApprovalRuleset)
            .WithMany(t => t.ApprovalRules)
            .HasForeignKey(d => d.ApprovalRulesetId);
    }
}


问:
Testing Delegation in Playground giving 'nil'
I have the following code in Playground -I'm learning delegation-...

```<code>import UIKit

protocol FollowThisProtocol {

    func passingTheValue(aValue: String)
}

class IPassTheValues{

    var aDelegate: FollowThisProtocol!

    func runThisFunc(){

       aDelegate.passingTheValue(aValue: "I like this game")

    }

}

class IReceiveTheValues: FollowThisProtocol{

    var localString: String!
        var instanceOfClass: IPassTheValues!

    func runReceivefunc(){

            instanceOfClass.aDelegate = self

    }

    func passingTheValue(aValue: String) {
        localString = aValue

    }

}
</code>```

When I attempt to

```<code>print(IReceiveTheValues().localString)
</code>```

it's giving me nil

It also gives me nil if I run the following lines before attempting to  print(IReceiveTheValues().localString)...

```<code>IPassTheValues()

IReceiveTheValues()
</code>```

could you please help me understand why the value is not being passed from the 1st class to the 2nd..?

Or if you can spot something in my code that is contradicting itself, could you please point it out..?

Appreciate your time and help.

答:
You need to create the IPassTheValues object before assigning yourself as the delegate, and then call runThisFunc() on the instance:

```<code>func runReceivefunc(){

    instanceOfClass = IPassTheValues()
    instanceOfClass.aDelegate = self
    instanceOfClass.runThisFunc()

}
</code>```

Then test:

```<code>// Create the `IReceiveTheValues` object
let irtv = IReceiveTheValues()

// Run the method
irtv.runReceivefunc()

// Get the resulting string
print(irtv.localString)
</code>```

I suggest 2 other changes. Make your delegate weak so that you don't get a retain cycle which makes it impossible to delete either object. In order to do that, you will need to add : class to your protocol declaration because only reference objects (instances of a class) can be weak.

Here's the modified code.  Try it and see what happens when you delete weak.

```<code>protocol FollowThisProtocol: class {
    func passingTheValue(aValue: String)
}

class IPassTheValues{
    weak var aDelegate: FollowThisProtocol!

    func runThisFunc(){
        print("Calling delegate...")
        aDelegate.passingTheValue(aValue: "I like this game")
    }

    deinit {
        print("IPassTheValues deinitialized")
    }
}

class IReceiveTheValues: FollowThisProtocol{
    var localString: String!
    var instanceOfClass: IPassTheValues!

    func runReceivefunc(){
        instanceOfClass = IPassTheValues()
        instanceOfClass.aDelegate = self
        instanceOfClass.runThisFunc()
    }

    func passingTheValue(aValue: String) {
        print("Receiving value from helper object...")
        localString = aValue
    }

    deinit {
        print("IReceiveTheValues deinitialized")
    }
}

func test() {
    let irtv = IReceiveTheValues()
    irtv.runReceivefunc()
    print(irtv.localString)
}

test()
</code>```

Body:
I have the following code in Playground -I'm learning delegation-...

import UIKit

protocol FollowThisProtocol {

    func passingTheValue(aValue: String)
}

class IPassTheValues{

    var aDelegate: FollowThisProtocol!

    func runThisFunc(){

       aDelegate.passingTheValue(aValue: "I like this game")

    }

}

class IReceiveTheValues: FollowThisProtocol{

    var localString: String!
        var instanceOfClass: IPassTheValues!

    func runReceivefunc(){

            instanceOfClass.aDelegate = self

    }

    func passingTheValue(aValue: String) {
        localString = aValue

    }

}

When I attempt to

print(IReceiveTheValues().localString)

it's giving me nil

It also gives me nil if I run the following lines before attempting to  print(IReceiveTheValues().localString)...

IPassTheValues()

IReceiveTheValues()

could you please help me understand why the value is not being passed from the 1st class to the 2nd..?

Or if you can spot something in my code that is contradicting itself, could you please point it out..?

Appreciate your time and help.

Body:
You need to create the IPassTheValues object before assigning yourself as the delegate, and then call runThisFunc() on the instance:

func runReceivefunc(){

    instanceOfClass = IPassTheValues()
    instanceOfClass.aDelegate = self
    instanceOfClass.runThisFunc()

}

Then test:

// Create the `IReceiveTheValues` object
let irtv = IReceiveTheValues()

// Run the method
irtv.runReceivefunc()

// Get the resulting string
print(irtv.localString)

I suggest 2 other changes. Make your delegate weak so that you don't get a retain cycle which makes it impossible to delete either object. In order to do that, you will need to add : class to your protocol declaration because only reference objects (instances of a class) can be weak.

Here's the modified code.  Try it and see what happens when you delete weak.

protocol FollowThisProtocol: class {
    func passingTheValue(aValue: String)
}

class IPassTheValues{
    weak var aDelegate: FollowThisProtocol!

    func runThisFunc(){
        print("Calling delegate...")
        aDelegate.passingTheValue(aValue: "I like this game")
    }

    deinit {
        print("IPassTheValues deinitialized")
    }
}

class IReceiveTheValues: FollowThisProtocol{
    var localString: String!
    var instanceOfClass: IPassTheValues!

    func runReceivefunc(){
        instanceOfClass = IPassTheValues()
        instanceOfClass.aDelegate = self
        instanceOfClass.runThisFunc()
    }

    func passingTheValue(aValue: String) {
        print("Receiving value from helper object...")
        localString = aValue
    }

    deinit {
        print("IReceiveTheValues deinitialized")
    }
}

func test() {
    let irtv = IReceiveTheValues()
    irtv.runReceivefunc()
    print(irtv.localString)
}

test()


问:
Design decisions / advice for a simple game on Android
I need your advice on the best way to implement a scrollable playing field in a simple game. The field consists of multiple rows, with 9 cells in each row. The rows can be dynamically added and removed during the course of the game. Each cell has a digit in it, and optionally several overlayed images, like selection, selector over, crossed out, etc. (see the pic below). The user should be able to click on individual cells of a row to select/deselect/cross the touched cells. At any point in the game there can be from 0 to 3000 cells (0 to about 333 rows). The field should scroll up and down smoothly.

I was thinking about having a ListView with its each row being a row on the field. That way i could add/remove rows dynamically during the game. However, how exactly should i implement a row: have one bitmap representing a row, and then when the user touches it -- get the coordinates of the touch area, and find out what cell was affected, and then act upon that. Is it possible to get the touch coordinates of a row in ListView? If not, should I place 9 dummy image placeholders in each row, and then act on user touching those? What about performance?

Or should I have one huge bitmap / canvas representing the entire field, place it inside a ScrollView and then calculate all the coordinates and update it as the user interacts with it? Is it going to be faster or slower than the ListView?

Any other solutions?

I prefer it to be a "regular" app type game, not a loop-based game, as I don't think I really need to redraw 30 times a second.

I am pretty new to Android. Thank you for your suggestions.

答:
I dont know if you can create a game like you described with good performance. I would look into basic tile game programming.

But by avoiding the standard view components are have to write all the logic yourself requires quite some work. Things like handling "click" events on different rows needs to be calculated by the tile position relative to the game camera. So theres alot of new stuff in learning to develop game at a lower level.

You also have to take the rendering of your game into your own hands by developing a game loop that constantly updates and draw's your tiles from a background thread to reflect the scroll / state of your game.
You can get more infomation on the basics of a game loop at:

http://www.rbgrn.net/content/54-getting-started-android-game-development

If you want to learn more you should see the following keynotes from android.

http://developer.android.com/videos/index.html#v=U4Bk5rmIpic
http://developer.android.com/videos/index.html#v=7-62tRHLcHk

Those give you a very good insight in developing games for andriod at a low level where you can fine tune for performance.


问:
bash read stdin after piped input
I am having trouble getting bash to relinquish control of the pipe to stdin. I want to pass in the username and password to a program and then have that same program read from stdin rather than the pipe! This is what I have tried:

```<code>alias pandora='echo -e "$(cat ~/.musik/name)\n$(cat ~/.musik/pass | base64 --decode)" | pianobar'
</code>```

That's in my .bashrc. First, it cat's the username/password files and then pipes that into pianobar (pandora in the terminal). The username and password get in there, however, pianobar is expecting more input. Pianobar is asking for a number (to be able to play, for example, station 12), but when I type and hit enter, nothing happens because for some reason, it isn't expecting it to come from there.

How do I get the pipe to "relinquish" control?

Note: I have also tried

```<code>echo "$(cat ~/.musik/name)
$(cat ~/.musik/pass | base64 --decode)
" >>> pianobar
</code>```

答:
This is the proper way to configure pianobar auto login:

```<code>    mkdir ~/.config/pianobar/ && cd ~/.config/pianobar/ && touch config
</code>```

Run ^^^ in your command line then put the following in your new config file

```<code>    # User
    user = (Your Pandora email)
    password = (Your Pandora password)
</code>```

https://github.com/PromyLOPh/pianobar/blob/e945578ab22912049f1e547ce7b25b01089f7590/contrib/config-example

Title: bash read stdin after piped input

Body:
I am having trouble getting bash to relinquish control of the pipe to stdin. I want to pass in the username and password to a program and then have that same program read from stdin rather than the pipe! This is what I have tried:

alias pandora='echo -e "$(cat ~/.musik/name)\n$(cat ~/.musik/pass | base64 --decode)" | pianobar'

That's in my .bashrc. First, it cat's the username/password files and then pipes that into pianobar (pandora in the terminal). The username and password get in there, however, pianobar is expecting more input. Pianobar is asking for a number (to be able to play, for example, station 12), but when I type and hit enter, nothing happens because for some reason, it isn't expecting it to come from there.

How do I get the pipe to "relinquish" control?

Note: I have also tried

echo "$(cat ~/.musik/name)
$(cat ~/.musik/pass | base64 --decode)
" >>> pianobar

Body:
This is the proper way to configure pianobar auto login:

    mkdir ~/.config/pianobar/ && cd ~/.config/pianobar/ && touch config

Run ^^^ in your command line then put the following in your new config file

    # User
    user = (Your Pandora email)
    password = (Your Pandora password)

https://github.com/PromyLOPh/pianobar/blob/e945578ab22912049f1e547ce7b25b01089f7590/contrib/config-example


问:
ios - Error when hiding button through code Objective-c
I'm trying to hide a button through code, but the program crashes every time I try to hide it.

The error I get:

```<code>'NSInvalidArgumentException', reason: '-[UIBarButtonItem setHidden:]: unrecognized selector sent to instance 0x14ef8f30'
</code>```

.h file code:

```<code>@property (strong) UIButton *takeAll;
</code>```

.m code:

```<code>    @synthesize takeAll;

// function

   [self.takeAll setHidden:YES];
</code>```

答: UIBarButtonItem does not have a setHidden: selector. You may want to set the tint color of the button to a clear color and disable it, which will essentially provide the same functionality.

Body:
I'm trying to hide a button through code, but the program crashes every time I try to hide it.

The error I get:

'NSInvalidArgumentException', reason: '-[UIBarButtonItem setHidden:]: unrecognized selector sent to instance 0x14ef8f30'

.h file code:

@property (strong) UIButton *takeAll;

.m code:

    @synthesize takeAll;

// function

   [self.takeAll setHidden:YES];


问:
android studio duplicate zip entry transformClassesAndResourcesWithProguard
I have a problem, gradle downloads two times library: commons-io-1.3.2.jar and I have in external libraries: commons-io-1.3.2 and 1_commons-io-1.3.2

I see in logs:

.gradle/caches/modules-2/files-2.1/commons-io/commons-io/1.3.2/b6dde38349ba9bb5e6ea6320531eae969985dae5/commons-io-1.3.2.jar
    gradle/caches/modules-2/files-2.1/org.apache.commons/commons-io/1.3.2/b6dde38349ba9bb5e6ea6320531eae969985dae5/commons-io-1.3.2.jar

end error:

```<code>Warning:Exception while processing task java.io.IOException: Can't write [/Users/**/jars/3/1f/main.jar] (Can't read [/Users/**/.gradle/caches/modules-2/files-2.1/org.apache.commons/commons-io/1.3.2/b6dde38349ba9bb5e6ea6320531eae969985dae5/commons-io-1.3.2.jar(;;;;;;**.class)] (Duplicate zip entry [commons-io-1.3.2.jar:org/apache/commons/io/CopyUtils.class]))
</code>```

Error:Execution failed for task ':VFWallet:transformClassesAndResourcesWithProguardForApp'.

Job failed, see logs for details

答:
I fixed it by updating the apache library:

```<code>'org.apache.commons:commons-io:1.3.2'
</code>```

This post helped me

Body:
I have a problem, gradle downloads two times library: commons-io-1.3.2.jar and I have in external libraries: commons-io-1.3.2 and 1_commons-io-1.3.2

I see in logs:

.gradle/caches/modules-2/files-2.1/commons-io/commons-io/1.3.2/b6dde38349ba9bb5e6ea6320531eae969985dae5/commons-io-1.3.2.jar
    gradle/caches/modules-2/files-2.1/org.apache.commons/commons-io/1.3.2/b6dde38349ba9bb5e6ea6320531eae969985dae5/commons-io-1.3.2.jar

end error:

Warning:Exception while processing task java.io.IOException: Can't write [/Users/**/jars/3/1f/main.jar] (Can't read [/Users/**/.gradle/caches/modules-2/files-2.1/org.apache.commons/commons-io/1.3.2/b6dde38349ba9bb5e6ea6320531eae969985dae5/commons-io-1.3.2.jar(;;;;;;**.class)] (Duplicate zip entry [commons-io-1.3.2.jar:org/apache/commons/io/CopyUtils.class]))

Error:Execution failed for task ':VFWallet:transformClassesAndResourcesWithProguardForApp'.

Job failed, see logs for details

Body:
I fixed it by updating the apache library:

'org.apache.commons:commons-io:1.3.2'

This post helped me


问:
Codahale Metrics: using @Timed metrics annotation in plain Java
I am trying to add metrics to a plain Java application using codahale metrics. I'd like to use the @Timed annotation, but it is unclear to me which MetricRegistry it uses, or how to tell it which MetricRegistry to use. The application is a plain Java 8 application, built with Maven 3, no Spring, no Hibernate.

I can not find any documentation on how to implement @Timed in the dropwizard documentation: https://dropwizard.github.io/metrics/3.1.0/manual/

I've added these dependencies:

```<code><dependency>
  <groupId>io.dropwizard.metrics</groupId>
  <artifactId>metrics-core</artifactId>
  <version>3.1.0</version>
</dependency>
<dependency>
  <groupId>com.codahale.metrics</groupId>
  <artifactId>metrics-annotation</artifactId>
  <version>3.0.2</version>
</dependency>
</code>```

When I use a programatic call to Timer, I can get reports because I know which MetricsRegistry is used:

```<code>static final MetricRegistry metrics = new MetricRegistry();
private void update() throws SQLException {
  Timer.Context time = metrics.timer("domainobject.update").time();
  try {
    [...]
  } finally {
    time.stop();
  }
}
</code>```

But when I use the much more elegant @Timed annotation, I have no idea which registry is used, and therefore I can not create a reporter, which means I can not get the metrics reported (I'm not even sure if this actually does anything):

```<code>@Timed(name = "domainobject.update")
private void update() throws SQLException {
    [...]
}
</code>```

Please advise on how to make the @Timed and other Metrics annotations work in a regular Java application.

Additional info: The reason I am finding this strange is that I have added the Lombok framework and the @Slf4j annotations do work. I added Lombok as a dependency in the maven pom.xml:

```<code><dependency>
  <groupId>org.projectlombok</groupId>
  <artifactId>lombok</artifactId>
  <version>1.14.8</version>
</dependency>
</code>```

And I can use the @Sl4fj class annotation to add a logger to the class without cluttering up the member variables:

```<code>@Slf4j
public class App {
  public void logsome(){
    log.info("Hello there");
  }
}
</code>```

So if that's possible by just adding a dependency, I reckon I am just missing a dependency or configuration to get the codahale @Timed annotation work, as described above.

(by the way, check out Lombok, it will make your life easier: http://projectlombok.org/ )

答:
In newer Dropwizard versions (I am using 0.9.2), you can access the default MetricRegistry through the setup environment io.dropwizard.setup.Environment. This default MetricRegistry already has an InstrumentedResourceMethodApplicationListener associated with it, which listens to all the metrics of your resources.

If you have registered a resource with the JerseyEnvironment as under,

```<code>environment.jersey().register(resource);
</code>```

you need only annotate your resource method (or class) with @Timed, @Metered or @ExceptionMetered to register the respective metrics.

```<code>@POST
@Timed
public String show() {
    return "yay";
}
</code>```

You can assign a Reporter (like an Slf4jReporter or JmxReporter) to the default MetricRegistry as under

```<code>Slf4jReporter.forRegistry(environment.metrics()).build();
</code>```

As a quick test to see if your metrics have actually been registered, you can make a GET call to the URL http://localhost:8081/metrics or the corresponding Admin Metrics URL in your test environment.

Some other versions require you to explicitly register an InstrumentedResourceMethodApplicationListener as shown in this Doc

Body:
I am trying to add metrics to a plain Java application using codahale metrics. I'd like to use the @Timed annotation, but it is unclear to me which MetricRegistry it uses, or how to tell it which MetricRegistry to use. The application is a plain Java 8 application, built with Maven 3, no Spring, no Hibernate.

I can not find any documentation on how to implement @Timed in the dropwizard documentation: https://dropwizard.github.io/metrics/3.1.0/manual/

I've added these dependencies:

<dependency>
  <groupId>io.dropwizard.metrics</groupId>
  <artifactId>metrics-core</artifactId>
  <version>3.1.0</version>
</dependency>
<dependency>
  <groupId>com.codahale.metrics</groupId>
  <artifactId>metrics-annotation</artifactId>
  <version>3.0.2</version>
</dependency>

When I use a programatic call to Timer, I can get reports because I know which MetricsRegistry is used:

static final MetricRegistry metrics = new MetricRegistry();
private void update() throws SQLException {
  Timer.Context time = metrics.timer("domainobject.update").time();
  try {
    [...]
  } finally {
    time.stop();
  }
}

But when I use the much more elegant @Timed annotation, I have no idea which registry is used, and therefore I can not create a reporter, which means I can not get the metrics reported (I'm not even sure if this actually does anything):

@Timed(name = "domainobject.update")
private void update() throws SQLException {
    [...]
}

Please advise on how to make the @Timed and other Metrics annotations work in a regular Java application.

Additional info: The reason I am finding this strange is that I have added the Lombok framework and the @Slf4j annotations do work. I added Lombok as a dependency in the maven pom.xml:

<dependency>
  <groupId>org.projectlombok</groupId>
  <artifactId>lombok</artifactId>
  <version>1.14.8</version>
</dependency>

And I can use the @Sl4fj class annotation to add a logger to the class without cluttering up the member variables:

@Slf4j
public class App {
  public void logsome(){
    log.info("Hello there");
  }
}

So if that's possible by just adding a dependency, I reckon I am just missing a dependency or configuration to get the codahale @Timed annotation work, as described above.

(by the way, check out Lombok, it will make your life easier: http://projectlombok.org/ )

Body:
In newer Dropwizard versions (I am using 0.9.2), you can access the default MetricRegistry through the setup environment io.dropwizard.setup.Environment. This default MetricRegistry already has an InstrumentedResourceMethodApplicationListener associated with it, which listens to all the metrics of your resources.

If you have registered a resource with the JerseyEnvironment as under,

environment.jersey().register(resource);

you need only annotate your resource method (or class) with @Timed, @Metered or @ExceptionMetered to register the respective metrics.

@POST
@Timed
public String show() {
    return "yay";
}

You can assign a Reporter (like an Slf4jReporter or JmxReporter) to the default MetricRegistry as under

Slf4jReporter.forRegistry(environment.metrics()).build();

As a quick test to see if your metrics have actually been registered, you can make a GET call to the URL http://localhost:8081/metrics or the corresponding Admin Metrics URL in your test environment.

Some other versions require you to explicitly register an InstrumentedResourceMethodApplicationListener as shown in this Doc


问:
Why do we need connection pool in node.js when node is single threaded?
Node.js is single threaded. The Javascript V8 engine and some of the internal libraries are multi threaded. For I/O, node delegates I/O to OS which may be multi-threaded.

If my node.js application is connecting to redis or ,sql/mariadb server, I assume I should not need a connection pool for redis or mysql.

As a developer, I create 1 redis or mysql connection and reuse it to send/get data. When data arrives, node will invoke the callback to process the data.

I understand connection pooling with Java/.NET but they are multi-threaded and so connection pooling in Java/.NET has clear benefit.

My question is: Why do we need connection pool in node.js when node is single threaded? Is there any benefit of it? Will node not leverage the multi-threading features of underlying OS and javascript engine without the developer having to do it?

Thanks

答:
Node runs your code single threaded. However, Node.js actually has a thread pool at its disposal that your code does not have access to. The threading mechanisms are implemented with libuv. Take a look at libuv book its in-depth and explains the inner workings of libuv.

Basically, your code is run within the context of the Event Loop (single thread). Any asynchronous work is then offloaded to an available thread from the pool and the Event Loop will just poll until that asynchronous work is completed by one of the threads. Once done, the callback function registered by your async call is then invoked and will get worked on during the next I/O Callback Phase of the event loop. You can read more about the Event Loop and its phases in the Node.js docs.

One of the benefits of building an application with this Event Loop style,  is the abstraction of critical section coding (mutexs, semaphores, etc.) that is normally associated with multi-threaded applications.


问:
conflicting ruby gems
I need to use two gems in my project that both claim the PDF namespace:  pdf-reader and htmldoc.

Is there any way to get them to play nice together?  The only way I can think of is to rewrite my own version of htmldoc to give it a different namespace.

答:
There's probably no elegant solution to the problem. If you really need the two gems working side by side I think your best option is to fork one of them (or possibly both) and use your fork. This is how I'd go about it:

If either gem is hosted on Github then fork it, or if both are on Github fork the one that seems to be the least work.

If neither gem is on Github, see if you can get hold of the source (grabbing it from the gem is a possibility, but finding the real repository might be helpful as there may be other files there that are not included in the gem), and put it in a repository on Github. Make sure the gem's license allows this (which it almost certainly does if it's one of the common open source licenses).

Make your changes.

Make sure there is a .gemspec file in the root of the repository, the next step will not work otherwise.

Use Bundler to manage your projects dependencies. Instead of specifying the dependency to the library you've modified as

```<code>gem 'the_gem'
</code>```

specify it like this:

```<code>gem 'the_gem', :git => 'git://github.com/you/the_gem.git'
</code>```

(but change the URL to the repository to the actual one)

Send an e-mail to the maintainer of the gem you modified and ask him or her to consider merging in your changes in the next release.

Bundler makes it really easy to use alternative versions of gems with minimal hassle. I often fork gems, fix bugs or add features, change my Gemfile to point to my version, then ask the maintainer to merge in my changes. When, or if, that happens I simply change my Gemfile back to just refer to the official version of the gem.

An alternative strategy, if the maintainer does not want to merge in your changes and you want to distribute your version to others is to push up your version to Rubygems as a new gem, but in that case prefix the gem name with your name, or some other string that identifies your gem as a variant.

Title: conflicting ruby gems

Body:
There's probably no elegant solution to the problem. If you really need the two gems working side by side I think your best option is to fork one of them (or possibly both) and use your fork. This is how I'd go about it:

If either gem is hosted on Github then fork it, or if both are on Github fork the one that seems to be the least work.

If neither gem is on Github, see if you can get hold of the source (grabbing it from the gem is a possibility, but finding the real repository might be helpful as there may be other files there that are not included in the gem), and put it in a repository on Github. Make sure the gem's license allows this (which it almost certainly does if it's one of the common open source licenses).

Make your changes.

Make sure there is a .gemspec file in the root of the repository, the next step will not work otherwise.

Use Bundler to manage your projects dependencies. Instead of specifying the dependency to the library you've modified as

gem 'the_gem'

specify it like this:

gem 'the_gem', :git => 'git://github.com/you/the_gem.git'

(but change the URL to the repository to the actual one)

Send an e-mail to the maintainer of the gem you modified and ask him or her to consider merging in your changes in the next release.

Bundler makes it really easy to use alternative versions of gems with minimal hassle. I often fork gems, fix bugs or add features, change my Gemfile to point to my version, then ask the maintainer to merge in my changes. When, or if, that happens I simply change my Gemfile back to just refer to the official version of the gem.

An alternative strategy, if the maintainer does not want to merge in your changes and you want to distribute your version to others is to push up your version to Rubygems as a new gem, but in that case prefix the gem name with your name, or some other string that identifies your gem as a variant.