问:
Split lines in clojure while reading from file
I am learning clojure at school and I have an exam coming up. I was just working on a few things to make sure I get the hang of it.

I am trying to read from a file line by line and as I do, I want to split the line whenever there is a ";".

Here is my code so far

```<code>(defn readFile []
  (map (fn [line] (clojure.string/split line #";"))
  (with-open [rdr (reader "C:/Users/Rohil/Documents/work.txt.txt")]
    (doseq [line (line-seq rdr)]
      (clojure.string/split line #";")
        (println line)))))
</code>```

When I do this, I still get the output:

```<code>"I;Am;A;String;"
</code>```

Am I missing something?

答:
I would keep it simple, and code it like this:

```<code>(ns tst.demo.core
  (:use tupelo.test)
  (:require [tupelo.core :as t]
            [clojure.string :as str] ))
(def text
 "I;am;a;line;
  This;is;another;one
  Followed;by;this;")

(def tmp-file-name "/tmp/lines.txt")

(dotest
  (spit tmp-file-name text) ; write it to a tmp file
  (let [lines       (str/split-lines (slurp tmp-file-name))
        result      (for [line lines]
                      (for [word (str/split line #";")]
                        (str/trim word)))
        result-flat (flatten result)]
(is= result
  [["I" "am" "a" "line"]
   ["This" "is" "another" "one"]
   ["Followed" "by" "this"]])
</code>```

Notice that result is a doubly-nested (2D) matrix of words. The simplest way to undo this is the flatten function to produce result-flat:

```<code>(is= result-flat
  ["I" "am" "a" "line" "This" "is" "another" "one" "Followed" "by" "this"])))
</code>```

You could also use apply concat as in:

```<code>(is= (apply concat result) result-flat)
</code>```

If you want to avoid building up a 2D matrix in the first place, you can use a generator function (a la Python) via lazy-gen and yield from the Tupelo library:

```<code>(dotest
  (spit tmp-file-name text) ; write it to a tmp file
  (let [lines  (str/split-lines (slurp tmp-file-name))
        result (t/lazy-gen
                 (doseq [line lines]
                   (let [words (str/split line #";")]
                     (doseq [word words]
                       (t/yield (str/trim word))))))]

(is= result
  ["I" "am" "a" "line" "This" "is" "another" "one" "Followed" "by" "this"])))
</code>```

In this case, lazy-gen creates the generator function.
Notice that for has been replaced with doseq, and the yield function places each word into the output lazy sequence.

Body:
I am learning clojure at school and I have an exam coming up. I was just working on a few things to make sure I get the hang of it.

I am trying to read from a file line by line and as I do, I want to split the line whenever there is a ";".

Here is my code so far

(defn readFile []
  (map (fn [line] (clojure.string/split line #";"))
  (with-open [rdr (reader "C:/Users/Rohil/Documents/work.txt.txt")]
    (doseq [line (line-seq rdr)]
      (clojure.string/split line #";")
        (println line)))))

When I do this, I still get the output:

"I;Am;A;String;"

Am I missing something?

Body:
I would keep it simple, and code it like this:

(ns tst.demo.core
  (:use tupelo.test)
  (:require [tupelo.core :as t]
            [clojure.string :as str] ))
(def text
 "I;am;a;line;
  This;is;another;one
  Followed;by;this;")

(def tmp-file-name "/tmp/lines.txt")

(dotest
  (spit tmp-file-name text) ; write it to a tmp file
  (let [lines       (str/split-lines (slurp tmp-file-name))
        result      (for [line lines]
                      (for [word (str/split line #";")]
                        (str/trim word)))
        result-flat (flatten result)]
(is= result
  [["I" "am" "a" "line"]
   ["This" "is" "another" "one"]
   ["Followed" "by" "this"]])

Notice that result is a doubly-nested (2D) matrix of words. The simplest way to undo this is the flatten function to produce result-flat:

(is= result-flat
  ["I" "am" "a" "line" "This" "is" "another" "one" "Followed" "by" "this"])))

You could also use apply concat as in:

(is= (apply concat result) result-flat)

If you want to avoid building up a 2D matrix in the first place, you can use a generator function (a la Python) via lazy-gen and yield from the Tupelo library:

(dotest
  (spit tmp-file-name text) ; write it to a tmp file
  (let [lines  (str/split-lines (slurp tmp-file-name))
        result (t/lazy-gen
                 (doseq [line lines]
                   (let [words (str/split line #";")]
                     (doseq [word words]
                       (t/yield (str/trim word))))))]

(is= result
  ["I" "am" "a" "line" "This" "is" "another" "one" "Followed" "by" "this"])))

In this case, lazy-gen creates the generator function.
Notice that for has been replaced with doseq, and the yield function places each word into the output lazy sequence.


来源: stackexchange

问:
OnMouseOver event triggered by non existing elements with ID = blank and ID = undefined
I have a menu that appears when the user hovers on an icon. I would like it to close when the user hovers out of that menu, or its parent DIV. In order to do that, I thought of using the onMouseOver and hiding it when the ID is not one of those I want. However, when I move the mouse, the cursor seems to enter and exit elements I didn't put there myself, with undefined ID or ID = '' (  blank ). Can anybody explain what is causing it, and, possibly, how to stop that from happening?

This is the menu, with its elements

```<code><div class = "desktopToolbarSearchBoxWithoutOptions" id = "toolbarSearchBox">
    <img src = "${webAppRoot}images/sandwich.png" class = "menuSearchSelector pointer" onMouseOver = "showSearchOptions ()" id = "menuSearchSelector"/>

    <span class="toolbarMenuItem pointer" id = "option1">
        Subject
    </span>

    <span class="toolbarMenuItem pointer" id = "option2">
        Name
    </span>

    <span class="toolbarMenuItem pointer" id = "option3">
        Location
    </span>
</div>
</code>```

This is how I make all the elements respond to the onmouseover event. I have to admit that I am more of a server person and can't make any sense of that for loop expression, I copied it from another forum where it said it does what I need. Maybe that's where the problem lies?

```<code>function startClickListener()
{
    document.addEventListener
    (
        "mouseover", function ( e )
        {
            for ( var element = e.target; element; element = element.parentNode )
            {
                console.log ( "> > > Element ID : " + element.id );
            }
        }
    );
}
</code>```

I would like the menu to disappear every time the ID is not one of those I want. However, even when moving between option1, option2 and option3 span I get those ghost elements

```<code>8BM_js.jsp:688 > > > Element ID : toolbarSearchBox
8BM_js.jsp:688 > > > Element ID :
8BM_js.jsp:688 > > > Element ID : desktopToolbar
( 2 x ) 8BM_js.jsp:688 > > > Element ID :
8BM_js.jsp:688 > > > Element ID : undefined
8BM_js.jsp:688 > > > Element ID : menuSearchSelector
8BM_js.jsp:688 > > > Element ID : toolbarSearchBox
8BM_js.jsp:688 > > > Element ID :
8BM_js.jsp:688 > > > Element ID : desktopToolbar
( 2 x ) 8BM_js.jsp:688 > > > Element ID :
8BM_js.jsp:688 > > > Element ID : undefined
8BM_js.jsp:688 > > > Element ID : toolbarSearchBox
8BM_js.jsp:688 > > > Element ID :
8BM_js.jsp:688 > > > Element ID : desktopToolbar
( 2 x ) 8BM_js.jsp:688 > > > Element ID :
8BM_js.jsp:688 > > > Element ID : undefined
8BM_js.jsp:688 > > > Element ID : option1
8BM_js.jsp:688 > > > Element ID : toolbarSearchBox
8BM_js.jsp:688 > > > Element ID :
8BM_js.jsp:688 > > > Element ID : desktopToolbar
( 2 x ) 8BM_js.jsp:688 > > > Element ID :
8BM_js.jsp:688 > > > Element ID : undefined
8BM_js.jsp:688 > > > Element ID : option2
8BM_js.jsp:688 > > > Element ID : toolbarSearchBox
8BM_js.jsp:688 > > > Element ID :
8BM_js.jsp:688 > > > Element ID : desktopToolbar
( 2 x ) 8BM_js.jsp:688 > > > Element ID :
8BM_js.jsp:688 > > > Element ID : undefined
8BM_js.jsp:688 > > > Element ID : option3
</code>```

Then I thought I could use the ID of the parentNode, as long as it's an element inside the DIV with ID = 'toolbarSearchBox', I am happy. It seems that those ghost elements do not even belong to that DIV though. Maybe the error message I get is a clue?

```<code>function startClickListener()
{
    document.addEventListener
    (
        "mouseover", function ( e )
        {
            for ( var element = e.target; element; element = element.parentNode )
            {
                console.log ( "> > > Element ID : " + element.id );
                console.log ( "> > > Parent  ID : " + element.parentNode.id );
            }
        }
    );
}
</code>```

This is the outcome

```<code>8BM_js.jsp:686 > > > Element ID : toolbarSearchBox
8BM_js.jsp:687 > > > Parent  ID :
8BM_js.jsp:686 > > > Element ID :
8BM_js.jsp:687 > > > Parent  ID : desktopToolbar
8BM_js.jsp:686 > > > Element ID : desktopToolbar
8BM_js.jsp:687 > > > Parent  ID :
8BM_js.jsp:686 > > > Element ID :
8BM_js.jsp:687 > > > Parent  ID :
8BM_js.jsp:686 > > > Element ID :
8BM_js.jsp:687 > > > Parent  ID : undefined
8BM_js.jsp:686 > > > Element ID : undefined
8BM_js.jsp:687 Uncaught TypeError: Cannot read property 'id' of null at HTMLDocument.<anonymous> (8BM_js.jsp:687) (anonymous) @ 8BM_js.jsp:687
8BM_js.jsp:686 > > > Element ID : menuSearchSelector
8BM_js.jsp:687 > > > Parent  ID : toolbarSearchBox
8BM_js.jsp:686 > > > Element ID : toolbarSearchBox
8BM_js.jsp:687 > > > Parent  ID :
8BM_js.jsp:686 > > > Element ID :
8BM_js.jsp:687 > > > Parent  ID : desktopToolbar
8BM_js.jsp:686 > > > Element ID : desktopToolbar
8BM_js.jsp:687 > > > Parent  ID :
8BM_js.jsp:686 > > > Element ID :
8BM_js.jsp:687 > > > Parent  ID :
8BM_js.jsp:686 > > > Element ID :
8BM_js.jsp:687 > > > Parent  ID : undefined
8BM_js.jsp:686 > > > Element ID : undefined
8BM_js.jsp:687 Uncaught TypeError: Cannot read property 'id' of null at HTMLDocument.<anonymous> (8BM_js.jsp:687) (anonymous) @ 8BM_js.jsp:687
8BM_js.jsp:686 > > > Element ID : toolbarSearchBox
8BM_js.jsp:687 > > > Parent  ID :
8BM_js.jsp:686 > > > Element ID :
8BM_js.jsp:687 > > > Parent  ID : desktopToolbar
8BM_js.jsp:686 > > > Element ID : desktopToolbar
8BM_js.jsp:687 > > > Parent  ID :
8BM_js.jsp:686 > > > Element ID :
8BM_js.jsp:687 > > > Parent  ID :
8BM_js.jsp:686 > > > Element ID :
8BM_js.jsp:687 > > > Parent  ID : undefined
8BM_js.jsp:686 > > > Element ID : undefined
8BM_js.jsp:687 Uncaught TypeError: Cannot read property 'id' of null at HTMLDocument.<anonymous> (8BM_js.jsp:687) (anonymous) @ 8BM_js.jsp:687
8BM_js.jsp:686 > > > Element ID : option1
8BM_js.jsp:687 > > > Parent  ID : toolbarSearchBox
8BM_js.jsp:686 > > > Element ID : toolbarSearchBox
8BM_js.jsp:687 > > > Parent  ID :
8BM_js.jsp:686 > > > Element ID :
8BM_js.jsp:687 > > > Parent  ID : desktopToolbar
8BM_js.jsp:686 > > > Element ID : desktopToolbar
8BM_js.jsp:687 > > > Parent  ID :
8BM_js.jsp:686 > > > Element ID :
8BM_js.jsp:687 > > > Parent  ID :
8BM_js.jsp:686 > > > Element ID :
8BM_js.jsp:687 > > > Parent  ID : undefined
8BM_js.jsp:686 > > > Element ID : undefined
8BM_js.jsp:687 Uncaught TypeError: Cannot read property 'id' of null at HTMLDocument.<anonymous> (8BM_js.jsp:687) (anonymous) @ 8BM_js.jsp:687
8BM_js.jsp:686 > > > Element ID : option2
8BM_js.jsp:687 > > > Parent  ID : toolbarSearchBox
8BM_js.jsp:686 > > > Element ID : toolbarSearchBox
8BM_js.jsp:687 > > > Parent  ID :
8BM_js.jsp:686 > > > Element ID :
8BM_js.jsp:687 > > > Parent  ID : desktopToolbar
8BM_js.jsp:686 > > > Element ID : desktopToolbar
8BM_js.jsp:687 > > > Parent  ID :
8BM_js.jsp:686 > > > Element ID :
8BM_js.jsp:687 > > > Parent  ID :
8BM_js.jsp:686 > > > Element ID :
8BM_js.jsp:687 > > > Parent  ID : undefined
8BM_js.jsp:686 > > > Element ID : undefined
8BM_js.jsp:687 Uncaught TypeError: Cannot read property 'id' of null at HTMLDocument.<anonymous> (8BM_js.jsp:687) (anonymous) @ 8BM_js.jsp:687
8BM_js.jsp:686 > > > Element ID : option3
8BM_js.jsp:687 > > > Parent  ID : toolbarSearchBox
8BM_js.jsp:686 > > > Element ID : toolbarSearchBox
8BM_js.jsp:687 > > > Parent  ID :
8BM_js.jsp:686 > > > Element ID :
8BM_js.jsp:687 > > > Parent  ID : desktopToolbar
8BM_js.jsp:686 > > > Element ID : desktopToolbar
8BM_js.jsp:687 > > > Parent  ID :
8BM_js.jsp:686 > > > Element ID :
8BM_js.jsp:687 > > > Parent  ID :
8BM_js.jsp:686 > > > Element ID :
8BM_js.jsp:687 > > > Parent  ID : undefined
8BM_js.jsp:686 > > > Element ID : undefined
</code>```

答: OnMouseOver and OnMouseOut events are triggered by children of the elements too, and sometimes by other elements too - couldn't quite understand when and why. OnMouseLeave doesn't have the same problem and is only triggered when the mouse leaves the element it's attached to</p>

ContentLicense: CC BY-SA 3.0

Body:
I have a menu that appears when the user hovers on an icon. I would like it to close when the user hovers out of that menu, or its parent DIV. In order to do that, I thought of using the onMouseOver and hiding it when the ID is not one of those I want. However, when I move the mouse, the cursor seems to enter and exit elements I didn't put there myself, with undefined ID or ID = '' (  blank ). Can anybody explain what is causing it, and, possibly, how to stop that from happening?

This is the menu, with its elements

        Subject

        Name

        Location

This is how I make all the elements respond to the onmouseover event. I have to admit that I am more of a server person and can't make any sense of that for loop expression, I copied it from another forum where it said it does what I need. Maybe that's where the problem lies?

function startClickListener()
{
    document.addEventListener
    (
        "mouseover", function ( e )
        {
            for ( var element = e.target; element; element = element.parentNode )
            {
                console.log ( "> > > Element ID : " + element.id );
            }
        }
    );
}

I would like the menu to disappear every time the ID is not one of those I want. However, even when moving between option1, option2 and option3 span I get those ghost elements

8BM_js.jsp:688 > > > Element ID : toolbarSearchBox
8BM_js.jsp:688 > > > Element ID :
8BM_js.jsp:688 > > > Element ID : desktopToolbar
( 2 x ) 8BM_js.jsp:688 > > > Element ID :
8BM_js.jsp:688 > > > Element ID : undefined
8BM_js.jsp:688 > > > Element ID : menuSearchSelector
8BM_js.jsp:688 > > > Element ID : toolbarSearchBox
8BM_js.jsp:688 > > > Element ID :
8BM_js.jsp:688 > > > Element ID : desktopToolbar
( 2 x ) 8BM_js.jsp:688 > > > Element ID :
8BM_js.jsp:688 > > > Element ID : undefined
8BM_js.jsp:688 > > > Element ID : toolbarSearchBox
8BM_js.jsp:688 > > > Element ID :
8BM_js.jsp:688 > > > Element ID : desktopToolbar
( 2 x ) 8BM_js.jsp:688 > > > Element ID :
8BM_js.jsp:688 > > > Element ID : undefined
8BM_js.jsp:688 > > > Element ID : option1
8BM_js.jsp:688 > > > Element ID : toolbarSearchBox
8BM_js.jsp:688 > > > Element ID :
8BM_js.jsp:688 > > > Element ID : desktopToolbar
( 2 x ) 8BM_js.jsp:688 > > > Element ID :
8BM_js.jsp:688 > > > Element ID : undefined
8BM_js.jsp:688 > > > Element ID : option2
8BM_js.jsp:688 > > > Element ID : toolbarSearchBox
8BM_js.jsp:688 > > > Element ID :
8BM_js.jsp:688 > > > Element ID : desktopToolbar
( 2 x ) 8BM_js.jsp:688 > > > Element ID :
8BM_js.jsp:688 > > > Element ID : undefined
8BM_js.jsp:688 > > > Element ID : option3

Then I thought I could use the ID of the parentNode, as long as it's an element inside the DIV with ID = 'toolbarSearchBox', I am happy. It seems that those ghost elements do not even belong to that DIV though. Maybe the error message I get is a clue?

function startClickListener()
{
    document.addEventListener
    (
        "mouseover", function ( e )
        {
            for ( var element = e.target; element; element = element.parentNode )
            {
                console.log ( "> > > Element ID : " + element.id );
                console.log ( "> > > Parent  ID : " + element.parentNode.id );
            }
        }
    );
}

This is the outcome

8BM_js.jsp:686 > > > Element ID : toolbarSearchBox
8BM_js.jsp:687 > > > Parent  ID :
8BM_js.jsp:686 > > > Element ID :
8BM_js.jsp:687 > > > Parent  ID : desktopToolbar
8BM_js.jsp:686 > > > Element ID : desktopToolbar
8BM_js.jsp:687 > > > Parent  ID :
8BM_js.jsp:686 > > > Element ID :
8BM_js.jsp:687 > > > Parent  ID :
8BM_js.jsp:686 > > > Element ID :
8BM_js.jsp:687 > > > Parent  ID : undefined
8BM_js.jsp:686 > > > Element ID : undefined
8BM_js.jsp:687 Uncaught TypeError: Cannot read property 'id' of null at HTMLDocument.<anonymous> (8BM_js.jsp:687) (anonymous) @ 8BM_js.jsp:687
8BM_js.jsp:686 > > > Element ID : menuSearchSelector
8BM_js.jsp:687 > > > Parent  ID : toolbarSearchBox
8BM_js.jsp:686 > > > Element ID : toolbarSearchBox
8BM_js.jsp:687 > > > Parent  ID :
8BM_js.jsp:686 > > > Element ID :
8BM_js.jsp:687 > > > Parent  ID : desktopToolbar
8BM_js.jsp:686 > > > Element ID : desktopToolbar
8BM_js.jsp:687 > > > Parent  ID :
8BM_js.jsp:686 > > > Element ID :
8BM_js.jsp:687 > > > Parent  ID :
8BM_js.jsp:686 > > > Element ID :
8BM_js.jsp:687 > > > Parent  ID : undefined
8BM_js.jsp:686 > > > Element ID : undefined
8BM_js.jsp:687 Uncaught TypeError: Cannot read property 'id' of null at HTMLDocument.<anonymous> (8BM_js.jsp:687) (anonymous) @ 8BM_js.jsp:687
8BM_js.jsp:686 > > > Element ID : toolbarSearchBox
8BM_js.jsp:687 > > > Parent  ID :
8BM_js.jsp:686 > > > Element ID :
8BM_js.jsp:687 > > > Parent  ID : desktopToolbar
8BM_js.jsp:686 > > > Element ID : desktopToolbar
8BM_js.jsp:687 > > > Parent  ID :
8BM_js.jsp:686 > > > Element ID :
8BM_js.jsp:687 > > > Parent  ID :
8BM_js.jsp:686 > > > Element ID :
8BM_js.jsp:687 > > > Parent  ID : undefined
8BM_js.jsp:686 > > > Element ID : undefined
8BM_js.jsp:687 Uncaught TypeError: Cannot read property 'id' of null at HTMLDocument.<anonymous> (8BM_js.jsp:687) (anonymous) @ 8BM_js.jsp:687
8BM_js.jsp:686 > > > Element ID : option1
8BM_js.jsp:687 > > > Parent  ID : toolbarSearchBox
8BM_js.jsp:686 > > > Element ID : toolbarSearchBox
8BM_js.jsp:687 > > > Parent  ID :
8BM_js.jsp:686 > > > Element ID :
8BM_js.jsp:687 > > > Parent  ID : desktopToolbar
8BM_js.jsp:686 > > > Element ID : desktopToolbar
8BM_js.jsp:687 > > > Parent  ID :
8BM_js.jsp:686 > > > Element ID :
8BM_js.jsp:687 > > > Parent  ID :
8BM_js.jsp:686 > > > Element ID :
8BM_js.jsp:687 > > > Parent  ID : undefined
8BM_js.jsp:686 > > > Element ID : undefined
8BM_js.jsp:687 Uncaught TypeError: Cannot read property 'id' of null at HTMLDocument.<anonymous> (8BM_js.jsp:687) (anonymous) @ 8BM_js.jsp:687
8BM_js.jsp:686 > > > Element ID : option2
8BM_js.jsp:687 > > > Parent  ID : toolbarSearchBox
8BM_js.jsp:686 > > > Element ID : toolbarSearchBox
8BM_js.jsp:687 > > > Parent  ID :
8BM_js.jsp:686 > > > Element ID :
8BM_js.jsp:687 > > > Parent  ID : desktopToolbar
8BM_js.jsp:686 > > > Element ID : desktopToolbar
8BM_js.jsp:687 > > > Parent  ID :
8BM_js.jsp:686 > > > Element ID :
8BM_js.jsp:687 > > > Parent  ID :
8BM_js.jsp:686 > > > Element ID :
8BM_js.jsp:687 > > > Parent  ID : undefined
8BM_js.jsp:686 > > > Element ID : undefined
8BM_js.jsp:687 Uncaught TypeError: Cannot read property 'id' of null at HTMLDocument.<anonymous> (8BM_js.jsp:687) (anonymous) @ 8BM_js.jsp:687
8BM_js.jsp:686 > > > Element ID : option3
8BM_js.jsp:687 > > > Parent  ID : toolbarSearchBox
8BM_js.jsp:686 > > > Element ID : toolbarSearchBox
8BM_js.jsp:687 > > > Parent  ID :
8BM_js.jsp:686 > > > Element ID :
8BM_js.jsp:687 > > > Parent  ID : desktopToolbar
8BM_js.jsp:686 > > > Element ID : desktopToolbar
8BM_js.jsp:687 > > > Parent  ID :
8BM_js.jsp:686 > > > Element ID :
8BM_js.jsp:687 > > > Parent  ID :
8BM_js.jsp:686 > > > Element ID :
8BM_js.jsp:687 > > > Parent  ID : undefined
8BM_js.jsp:686 > > > Element ID : undefined


问:
convert Promise based function to an observable based function
What is the simplest way to do something like this in an observable approach way?</p>

```<code>async function promiseBased {
    await // wait for some jobs to be done
}

await promisebased();
// then do other jobs
</code>```

答:
not sure if it is what you're looking for, but there's a built in operator to transform a promise to an observable

```<code>var result = Rx.Observable.fromPromise(yourPromiseFunction());
result.subscribe(el => console.log(el));
</code>```

link to doc

Body:
What is the simplest way to do something like this in an observable approach way?

async function promiseBased {
    await // wait for some jobs to be done
}

await promisebased();
// then do other jobs

Body:
not sure if it is what you're looking for, but there's a built in operator to transform a promise to an observable

var result = Rx.Observable.fromPromise(yourPromiseFunction());
result.subscribe(el => console.log(el));

link to doc


问:
ActiveRecord Query: Create an instance method using scope chaining
I am having difficulty creating a class method through an ActiveRecord query:

I have created a class method called popular_users to sort users by their number of followers, but it is not returning any results. The problem lies with friend_id: self I believe. If I test in the rails console using friend_id: User.first it works. (friend_id is the id of the person being followed)

```<code>class User < ApplicationRecord

  # received friend (ie a follower): other user sends a request which has been accepted by current user
  has_many :friendships
  has_many :received_friendships, class_name: "Friendship", foreign_key: "friend_id"
  has_many :received_friends, -> { where(friendships: { accepted: true}) }, through: :received_friendships, source: :user

  def self.popular_users
    self.joins(:friendships)
        .where(friendships: {accepted: true, friend_id: self})
        .group("users.id")
        .select("users.id, count(friendships) AS followers_count")
        .order("followers_count DESC")
  end
</code>```

I have tried the below method but it results in this error:

ActiveRecord::StatementInvalid: PG::SyntaxError: ERROR:  syntax error
  at or near "SELECT"

```<code>  def self.popular_users
    self.joins(:friendships)
        .group("users.id")
        .select("SELECT COUNT(friend_id) FROM friendships WHERE (user_id = :user_id AND accepted = 't')) AS followers_count")
        .order("followers_count DESC")
  end
</code>```

Schema:

```<code>  create_table "friendships", force: :cascade do |t|
    t.integer "user_id"
    t.integer "friend_id"
    t.boolean "accepted", default: false
  end

  create_table "users", force: :cascade do |t|
    t.string "email", default: "", null: false
    t.string "encrypted_password", default: "", null: false
    t.string "name"
  end
</code>```

UPDATE: This is my answer

```<code>  def self.popular_users
    self.joins("RIGHT JOIN friendships ON friendships.friend_id = users.id AND friendships.accepted = 't'")
        .group("users.id")
        .select("users.id, count(users.id) AS followers_count")
        .order("followers_count DESC")
  end
</code>```

Eg testing in rails console:

```<code>Friendship.create(user_id: 1, friend_id: 2, accepted: true)
Friendship.create(user_id: 4, friend_id: 2, accepted: true)
Friendship.create(user_id: 5, friend_id: 2, accepted: true)
Friendship.create(user_id: 1, friend_id: 3, accepted: true)
Friendship.create(user_id: 2, friend_id: 3, accepted: true)
</code>```

Result returned after typing User.popular_users in console is #<ActiveRecord::Relation [#<User id: 2, followers_count: 3>, #<User id: 3, followers_count: 2>]>

答:
self in the context of a class method will be the class object itself.

```<code>class Test
  def self.test
    self
  end

  def test
    self
  end
end

Test.test
#=> Test

Test.new.test
#=> #<Test:0x0000010f624bb0>
</code>```

You'll need to pass the desired id into your class method, something like:

```<code>User.popular_users_for(friend_id)
</code>```

Body:
I am having difficulty creating a class method through an ActiveRecord query:

I have created a class method called popular_users to sort users by their number of followers, but it is not returning any results. The problem lies with friend_id: self I believe. If I test in the rails console using friend_id: User.first it works. (friend_id is the id of the person being followed)

class User < ApplicationRecord

  # received friend (ie a follower): other user sends a request which has been accepted by current user
  has_many :friendships
  has_many :received_friendships, class_name: "Friendship", foreign_key: "friend_id"
  has_many :received_friends, -> { where(friendships: { accepted: true}) }, through: :received_friendships, source: :user

  def self.popular_users
    self.joins(:friendships)
        .where(friendships: {accepted: true, friend_id: self})
        .group("users.id")
        .select("users.id, count(friendships) AS followers_count")
        .order("followers_count DESC")
  end

I have tried the below method but it results in this error:

ActiveRecord::StatementInvalid: PG::SyntaxError: ERROR:  syntax error
  at or near "SELECT"

  def self.popular_users
    self.joins(:friendships)
        .group("users.id")
        .select("SELECT COUNT(friend_id) FROM friendships WHERE (user_id = :user_id AND accepted = 't')) AS followers_count")
        .order("followers_count DESC")
  end

Schema:

  create_table "friendships", force: :cascade do |t|
    t.integer "user_id"
    t.integer "friend_id"
    t.boolean "accepted", default: false
  end

  create_table "users", force: :cascade do |t|
    t.string "email", default: "", null: false
    t.string "encrypted_password", default: "", null: false
    t.string "name"
  end

UPDATE: This is my answer

  def self.popular_users
    self.joins("RIGHT JOIN friendships ON friendships.friend_id = users.id AND friendships.accepted = 't'")
        .group("users.id")
        .select("users.id, count(users.id) AS followers_count")
        .order("followers_count DESC")
  end

Eg testing in rails console:

Friendship.create(user_id: 1, friend_id: 2, accepted: true)
Friendship.create(user_id: 4, friend_id: 2, accepted: true)
Friendship.create(user_id: 5, friend_id: 2, accepted: true)
Friendship.create(user_id: 1, friend_id: 3, accepted: true)
Friendship.create(user_id: 2, friend_id: 3, accepted: true)

Result returned after typing User.popular_users in console is #<ActiveRecord::Relation [#<User id: 2, followers_count: 3>, #<User id: 3, followers_count: 2>]>

Body:
self in the context of a class method will be the class object itself.

class Test
  def self.test
    self
  end

  def test
    self
  end
end

Test.test
#=> Test

Test.new.test
#=> #<Test:0x0000010f624bb0>

You'll need to pass the desired id into your class method, something like:

User.popular_users_for(friend_id)


问:
How to find the mean of certain values in a large dataframe using loop
In R, I have a data frame that looks like this:

```<code>         Female.ID    Mate.ID  relatedness
    1           A1         C1       0.0000
    2           A1         D1       0.0000
    3           A1         E1       0.5062
    4           A1         F1           NA
    5           B1         G1       0.0425
    6           B1         H1       0.0000
    7           B1         I1       0.0349
    8           B1         J1       0.0000
    9           B1         K1       0.0000
    10          B1         L1       0.0887
    11          B1         M1       0.1106
    12          B1         N1       0.0000
</code>```

I want to create a new dataframe and find the mean relatedness of all the mates for female.ID A1 and the mean relatedness for all the mates of female.ID
B1, etc.

I want something like this:

```<code>    Female.ID    mean.relatedness
           A1              0.1687
           B1              0.0346
</code>```

This dataframe is much bigger than this example one, which is why I'm not just subsetting for the female one by one and finding the mean relatedness. I was thinking of doing some kind of for loop, but I'm not sure how to start it off.

答:
You could use dplyr:</p>

```<code>library(dplyr)

themeans  <- df %>%
    group_by(Female.ID) %>%
    summarize(mean.relatedness = mean(relatedness, na.rm = T)
</code>```

Body:
In R, I have a data frame that looks like this:

         Female.ID    Mate.ID  relatedness
    1           A1         C1       0.0000
    2           A1         D1       0.0000
    3           A1         E1       0.5062
    4           A1         F1           NA
    5           B1         G1       0.0425
    6           B1         H1       0.0000
    7           B1         I1       0.0349
    8           B1         J1       0.0000
    9           B1         K1       0.0000
    10          B1         L1       0.0887
    11          B1         M1       0.1106
    12          B1         N1       0.0000

I want to create a new dataframe and find the mean relatedness of all the mates for female.ID A1 and the mean relatedness for all the mates of female.ID
B1, etc.

I want something like this:

    Female.ID    mean.relatedness
           A1              0.1687
           B1              0.0346

This dataframe is much bigger than this example one, which is why I'm not just subsetting for the female one by one and finding the mean relatedness. I was thinking of doing some kind of for loop, but I'm not sure how to start it off.

Body:
You could use dplyr:

library(dplyr)

themeans  <- df %>%
    group_by(Female.ID) %>%
    summarize(mean.relatedness = mean(relatedness, na.rm = T)


问:
App Crash while trying to share information through slack using UIActivityViewController
I am using an UIActivityViewController to show share options. The information I am trying to share consists of two pieces (a plain string and an url). The share is working through all the extensions like iMessages, Mail, Notes, Twitter, Facebook etc, but the app is crashing when I try to share through Slack. The weird thing is that the crash only happens if I am not debugging and it never crashes while debugging.

Code:

```<code>UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:@[title, self] applicationActivities:nil];
[self presentViewController:activityVC animated:YES completion:nil];

# UIActivityItemSource methods
- (id)activityViewControllerPlaceholderItem:(UIActivityViewController *)activityViewController {
    return url;
}

- (id)activityViewController:(UIActivityViewController *)activityViewController itemForActivityType:(NSString *)activityType {
    return url;
}

- (NSString*)activityViewController:(UIActivityViewController *)activityViewController subjectForActivityType:(NSString *)activityType {
    return title;
}

- (NSString *)activityViewController:(UIActivityViewController *)activityViewController dataTypeIdentifierForActivityType:(NSString *)activityType {
    return @"com.test.url";
}

- (UIImage *)activityViewController:(UIActivityViewController *)activityViewController thumbnailImageForActivityType:(NSString *)activityType suggestedSize:(CGSize)size {
    return image;
}
</code>```

I also noticed that this crash is happening on the Flipboard app and it's working fine on the Twitter app.

Did anyone run into this issue? If so can you please let me know what's the issue and how this can be fixed?

答:
This worked for me. Created a class for UIActivityItemSource. Instead of passing in self to the activityItems/initWithActivityItems array, I just passed in the itemSource.

```<code>ActivityItemSource *itemSource = [[ActivityItemSource alloc] initWithTitle:title url:url thumbnail:thumbnail];
UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:@[title, itemSource] applicationActivities:nil];
[self presentViewController:activityVC animated:YES completion:nil];

ActivityItemSource.m

@interface ActivityItemSource() <UIActivityItemSource>

@property (strong, nonatomic) NSString *title;
@property (strong, nonatomic) NSURL *url;
@property (strong, nonatomic) UIImage *thumbnail;
@end

@implementation ActivityItemSource

- (instancetype)initWithTitle:(NSString *)title url:(NSURL *)url thumbnail:(UIImage *)thumbnail {
    self = [self init];
    if (self) {
        self.title = title;
        self.url = url;
        self.thumbnail = thumbnail;
    }

    return self;
}

- (id)activityViewControllerPlaceholderItem:(UIActivityViewController *)activityViewController {
    return self.url;
}

- (id)activityViewController:(UIActivityViewController *)activityViewController itemForActivityType:(NSString *)activityType {
    return self.url;
}

- (NSString*)activityViewController:(UIActivityViewController *)activityViewController subjectForActivityType:(NSString *)activityType {
    return self.title;
}

- (UIImage *) activityViewController:(UIActivityViewController *)activityViewController thumbnailImageForActivityType:(NSString *)activityType suggestedSize:(CGSize)size {
    return self.thumbnail;
}

@end
</code>```

Body:
I am using an UIActivityViewController to show share options. The information I am trying to share consists of two pieces (a plain string and an url). The share is working through all the extensions like iMessages, Mail, Notes, Twitter, Facebook etc, but the app is crashing when I try to share through Slack. The weird thing is that the crash only happens if I am not debugging and it never crashes while debugging.

Code:

UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:@[title, self] applicationActivities:nil];
[self presentViewController:activityVC animated:YES completion:nil];

# UIActivityItemSource methods
- (id)activityViewControllerPlaceholderItem:(UIActivityViewController *)activityViewController {
    return url;
}

- (id)activityViewController:(UIActivityViewController *)activityViewController itemForActivityType:(NSString *)activityType {
    return url;
}

- (NSString*)activityViewController:(UIActivityViewController *)activityViewController subjectForActivityType:(NSString *)activityType {
    return title;
}

- (NSString *)activityViewController:(UIActivityViewController *)activityViewController dataTypeIdentifierForActivityType:(NSString *)activityType {
    return @"com.test.url";
}

- (UIImage *)activityViewController:(UIActivityViewController *)activityViewController thumbnailImageForActivityType:(NSString *)activityType suggestedSize:(CGSize)size {
    return image;
}

I also noticed that this crash is happening on the Flipboard app and it's working fine on the Twitter app.

Did anyone run into this issue? If so can you please let me know what's the issue and how this can be fixed?

Body:
This worked for me. Created a class for UIActivityItemSource. Instead of passing in self to the activityItems/initWithActivityItems array, I just passed in the itemSource.

ActivityItemSource *itemSource = [[ActivityItemSource alloc] initWithTitle:title url:url thumbnail:thumbnail];
UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:@[title, itemSource] applicationActivities:nil];
[self presentViewController:activityVC animated:YES completion:nil];

ActivityItemSource.m

@interface ActivityItemSource() <UIActivityItemSource>

@property (strong, nonatomic) NSString *title;
@property (strong, nonatomic) NSURL *url;
@property (strong, nonatomic) UIImage *thumbnail;
@end

@implementation ActivityItemSource

- (instancetype)initWithTitle:(NSString *)title url:(NSURL *)url thumbnail:(UIImage *)thumbnail {
    self = [self init];
    if (self) {
        self.title = title;
        self.url = url;
        self.thumbnail = thumbnail;
    }

    return self;
}

- (id)activityViewControllerPlaceholderItem:(UIActivityViewController *)activityViewController {
    return self.url;
}

- (id)activityViewController:(UIActivityViewController *)activityViewController itemForActivityType:(NSString *)activityType {
    return self.url;
}

- (NSString*)activityViewController:(UIActivityViewController *)activityViewController subjectForActivityType:(NSString *)activityType {
    return self.title;
}

- (UIImage *) activityViewController:(UIActivityViewController *)activityViewController thumbnailImageForActivityType:(NSString *)activityType suggestedSize:(CGSize)size {
    return self.thumbnail;
}

@end


问:
single-class or multi-class object detection for a specific class object?
One thing that I was wondering for a long time is the performance of a CNN-based object detector in single class and multi-class.

For example, If I want to design a pedestrian detector using the famous Faster R-CNN(VGG-16). The official version could detect pedestrian with 76.7 AP (PASCAL 07 test) if the training data is PASCAL VOC07+12 trainval.

However, I am quite satisfied with the detection results but what if I just revise its framework into a single class pedestrian detector and the training data will only contain pedestrian so both training and testing data will be fewer.

I know the computational power will consume less than the original 20-class one but I am curious about the detection performance.
has anybody tried to compare single-class and multi-class detector in the same class?

答:
Yes, but the results vary quite a bit according to model and application.  I've done this with several SVM applications and one CNN.  As expected, the single-class consumed less resource in every case.

However, the results were quite different.  One SVM actually did better in single-class training; two were significantly worse, and the other 3-4 were about the same (within expected error range).

The CNN didn't fare so well; it needed some tweaks to the topology.


问:
openpyxl color cells based on value from another column
```<code>import pandas as pd
from openpyxl import Workbook
from pandas import ExcelWriter import openpyxl

wb = Workbook()
sheet = wb.active
writer = ExcelWriter('path\\test.xlsx')

list1 = [1,1,1,2,3,3,4,5]
list2 = [1,2,2,2,3,4,4,5]

comparison = [i == j for i,j in zip(list1,list2)]
comparison Out[76]: [True, False, False, True, True, False, True, True]

df = pd.DataFrame(list1,list2)

dataframe_spotovi.to_excel(writer,'Jazler spotovi')
writer.save()
</code>```

I would like to color rows in my 1st column based on their value - all the same values in one color (1,1,1 in red, then 2 in separate color, 3,3 in some other color, 4 in another color etc.).
I made the list2, so i can check if rows in list1 have same values (comparison).

I tried something like this:

```<code>for rows in sheet.iter_rows():
    for cell in rows:
        for a, b in zip(mirko, darko):
            if a == b:
                cell.fill = PatternFill(bgColor="FFC7CE", fill_type = "solid")
    else:
        color = 'FFBB00'
</code>```

Nothing. I tried dataframe styler, but styler cannot iterate.

Any thoughts? Much appreciated.

答:
The following creates a dataframe from some data, creates an openpyxl ExcelWriter. It then uses a colourmap from Matplotlib to give you a range of colours. For each unique value it assigns the next value from the colormap, starting with red:

```<code>import pandas as pd
import openpyxl
from openpyxl.styles import PatternFill
import matplotlib
import matplotlib.cm as cm
import numpy as np

data = [
    [1, 'test', 1],
    [1, 'test', 2],
    [1, 'test', 3],
    [2, 'test', 4],
    [3, 'test', 5],
    [3, 'test', 6],
    [4, 'test', 7],
    [5, 'test', 8]]

write_path = "output.xlsx"
df = pd.DataFrame(data, columns=["value", "comment", "index"])
unique = np.unique(df['value']).shape[0] + 1

with pd.ExcelWriter(write_path) as writer:
    df.to_excel(writer, sheet_name="Sheet1", index=False)

wb = openpyxl.load_workbook(write_path)
ws = wb.get_sheet_by_name("Sheet1")

# Create a color map
tohex = lambda r,g,b,a: '%02X%02X%02X%02X' % (a,r,g,b)
gist_rainbow = cm.gist_rainbow(np.linspace(0, 1, unique))
gist_rainbow = np.array(gist_rainbow * 255, dtype=int)
gist_rainbow = iter([tohex(*gist_rainbow[i,:]) for i in range(unique)])
colours = {}
next_colour = next(gist_rainbow)    # get the next colour in the colormap

for cells in ws.iter_rows(min_row=2, min_col=1, max_col=1):
    cell = cells[0]

    try:
        colour = colours[cell.value]
    except KeyError:
        colours[cell.value] = next_colour
        colour = next_colour
        next_colour = next(gist_rainbow)    # get the next colour in the colormap

    cell.fill = PatternFill(start_color=colour, end_color=colour, fill_type='solid')

wb.save(write_path)
</code>```

This would give you an Excel spreadsheet something looking like:

Body:
import pandas as pd
from openpyxl import Workbook
from pandas import ExcelWriter import openpyxl

wb = Workbook()
sheet = wb.active
writer = ExcelWriter('path\\test.xlsx')

list1 = [1,1,1,2,3,3,4,5]
list2 = [1,2,2,2,3,4,4,5]

comparison = [i == j for i,j in zip(list1,list2)]
comparison Out[76]: [True, False, False, True, True, False, True, True]

df = pd.DataFrame(list1,list2)

dataframe_spotovi.to_excel(writer,'Jazler spotovi')
writer.save()

I would like to color rows in my 1st column based on their value - all the same values in one color (1,1,1 in red, then 2 in separate color, 3,3 in some other color, 4 in another color etc.).
I made the list2, so i can check if rows in list1 have same values (comparison).

I tried something like this:

for rows in sheet.iter_rows():
    for cell in rows:
        for a, b in zip(mirko, darko):
            if a == b:
                cell.fill = PatternFill(bgColor="FFC7CE", fill_type = "solid")
    else:
        color = 'FFBB00'

Nothing. I tried dataframe styler, but styler cannot iterate.

Any thoughts? Much appreciated.

Body:
The following creates a dataframe from some data, creates an openpyxl ExcelWriter. It then uses a colourmap from Matplotlib to give you a range of colours. For each unique value it assigns the next value from the colormap, starting with red:

import pandas as pd
import openpyxl
from openpyxl.styles import PatternFill
import matplotlib
import matplotlib.cm as cm
import numpy as np

data = [
    [1, 'test', 1],
    [1, 'test', 2],
    [1, 'test', 3],
    [2, 'test', 4],
    [3, 'test', 5],
    [3, 'test', 6],
    [4, 'test', 7],
    [5, 'test', 8]]

write_path = "output.xlsx"
df = pd.DataFrame(data, columns=["value", "comment", "index"])
unique = np.unique(df['value']).shape[0] + 1

with pd.ExcelWriter(write_path) as writer:
    df.to_excel(writer, sheet_name="Sheet1", index=False)

wb = openpyxl.load_workbook(write_path)
ws = wb.get_sheet_by_name("Sheet1")

# Create a color map
tohex = lambda r,g,b,a: '%02X%02X%02X%02X' % (a,r,g,b)
gist_rainbow = cm.gist_rainbow(np.linspace(0, 1, unique))
gist_rainbow = np.array(gist_rainbow * 255, dtype=int)
gist_rainbow = iter([tohex(*gist_rainbow[i,:]) for i in range(unique)])
colours = {}
next_colour = next(gist_rainbow)    # get the next colour in the colormap

for cells in ws.iter_rows(min_row=2, min_col=1, max_col=1):
    cell = cells[0]

    try:
        colour = colours[cell.value]
    except KeyError:
        colours[cell.value] = next_colour
        colour = next_colour
        next_colour = next(gist_rainbow)    # get the next colour in the colormap

    cell.fill = PatternFill(start_color=colour, end_color=colour, fill_type='solid')

wb.save(write_path)

This would give you an Excel spreadsheet something looking like:


问:
Chrome opacity transition z-index issue
I'm working on an angular app and I'm having an issue when adding a '.active' class to a nav item.

Here is a stackblitz link that demonstrates the issue:

https://stackblitz.com/edit/angular-jjqyft?file=app%2Fapp.component.css

Basically, when I click a box, it scales but part of the next box is showing, almost like the active box is transparent.  My active class has a z-index of 1 and an opacity of 1.

On Firefox, this doesn't seem to be an issue.  Also, I've done something similar using the same technique before (but without any frameworks).  This link will show you an example from that project.

I'm not sure if I'm doing something wrong or if it's a Chrome issue.  I appreciate any feedback.

EDIT:  Just checked on Edge and the same issue is there.  So far it seems like Firefox is the only browser where this issue doesn't exist.

答:
Just add position:relative to either the .section a or .active

Such as:

```<code>.section a {
  display: block;
  width: 120px;
  height: 80px;
  opacity: .5;
  transition: all .5s;
  position:relative;
}
</code>```

The reason the clicked element seems as if it has opacity <1 is that the next element is actually "above" it, while having opacity: 0.5;. By "above it" I mean that the next element is further down the DOM tree, hence having a higher stacking order than the previous (currently the clicked one).

Title: Chrome opacity transition z-index issue

Body:
Just add position:relative to either the .section a or .active

Such as:

.section a {
  display: block;
  width: 120px;
  height: 80px;
  opacity: .5;
  transition: all .5s;
  position:relative;
}

The reason the clicked element seems as if it has opacity <1 is that the next element is actually "above" it, while having opacity: 0.5;. By "above it" I mean that the next element is further down the DOM tree, hence having a higher stacking order than the previous (currently the clicked one).


问:
Split large txt file into more txtfiles
I'm having an txt file approximately 1000kb big. Now I want to use objective-c split it into 10 txt files of 100kb.

I haven't really worked with NSRange. Well I know how it works, but then to read from a given location with the length: 'to end of file'... I've no idea how to do that.

Some code on how to split this into multiple 100kb txt file would really help me out here.

Thank you in advance.

答:
HW:

In that you tagged this question with "iphone" I would suggest that your best approach is to NOT read in the big file first and then go about segmenting it. You don't want to be a memory bully .

Other than that, this question has already been asked and answered in Here

ContentLicense: CC BY-SA 2.5

Title: Split large txt file into more txtfiles


问:
How to match complex unknown patterns in perl, when the pattern is in a variable?
There is a config file, that contains patterns, provided by user. Basically the pattern could be anything, a combination of alphabets,numbers, spaces, braces that too not necessarily closed, and special characters.
Patterns For Example: <Error my (error** fail& 345% ?+[+?>

I am very new to perl and struggling to handle this.

my piece of code:

```<code>for (<FH>) {
    for ( my $j = 0 ; $j < $num_pat ; $j = $j + 1 ) {
        print "This is the pattern : $pat_array[$j] \n";
        if ( $_ =~ m/'$pat_array[$j]'/ ) {
            print "$_ : match found for $pat_array[$j] \n";
            #print "KPI for the pattern is : $kpi_array[$match] : array style \n";
            $match_count[$j] = ( $match_count[$j] + 1 );
        }
    }
}
</code>```

Pattern array has multiple patterns.
I am trying to find matches using : if ($_ =~ m/'$pat_array[$j]'/)
It works for simple patterns, but not for the ones in example.

Please help me to proceed further.

答:
You need to quote the special characters.
See perldoc -f quotemeta

You can also use the shorthand \Q$variable\E syntax like that:

```<code>if ($string =~ m/\Q$pattern\E/) { ... }
</code>```

Any special char will be matched literally now.

Body:
There is a config file, that contains patterns, provided by user. Basically the pattern could be anything, a combination of alphabets,numbers, spaces, braces that too not necessarily closed, and special characters.
Patterns For Example: <Error my (error** fail& 345% ?+[+?>

I am very new to perl and struggling to handle this.

my piece of code:

for (<FH>) {
    for ( my $j = 0 ; $j < $num_pat ; $j = $j + 1 ) {
        print "This is the pattern : $pat_array[$j] \n";
        if ( $_ =~ m/'$pat_array[$j]'/ ) {
            print "$_ : match found for $pat_array[$j] \n";
            #print "KPI for the pattern is : $kpi_array[$match] : array style \n";
            $match_count[$j] = ( $match_count[$j] + 1 );
        }
    }
}

Pattern array has multiple patterns.
I am trying to find matches using : if ($_ =~ m/'$pat_array[$j]'/)
It works for simple patterns, but not for the ones in example.

Please help me to proceed further.

Body:
You need to quote the special characters.
See perldoc -f quotemeta

You can also use the shorthand \Q$variable\E syntax like that:

if ($string =~ m/\Q$pattern\E/) { ... }

Any special char will be matched literally now.


问:
 element not working between div and input
Below is the code that I am using. For some reason I cannot get the br in between the div.chatBox and input to show. Can anyone give me any suggestions.

```<code><div class="container-fluid col-xs-12">
    <div class="row">
        <br>
        <div class="chatBox col-xs-5 col-xs-offset-3" id="chatBox">
        </div>

        <br>

        <input type="text" class="col-xs-offset-4 col-xs-3">
    </div>
</div>
</code>```

答:
The way you have used
 tag will have no effect as
 is already a block element, that's the reason, you are feeling that
 tag is not working.

If you want to add some space then use

Title: <br> element not working between div and input

Body:
Below is the code that I am using. For some reason I cannot get the br in between the div.chatBox and input to show. Can anyone give me any suggestions.

        <input type="text" class="col-xs-offset-4 col-xs-3">

Body:
The way you have used  <br/> tag will have no effect as <div> is already a block element, that's the reason, you are feeling that <br> tag is not working.

If you want to add some space then use &nbsp;


问:
"Gradle error after Android Studio update"

Today I updated Android  Studio to version 3.0

And after that I couldn't build project successfully.

I got these errors:

```<code>Unable to resolve dependency for ':app@release/compileClasspath': could not resolve com.android.support:appcompat-v7:27.0.1.
</code>```

I tried using VPN or proxy etc. but none of them worked.

It's been a long day. I hope you may help me.

This is my build.gradle(app) :

```<code>apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
compileSdkVersion 27
defaultConfig {
    applicationId "ir.hetbo.kotlin_tutorial"
    minSdkVersion 15
    targetSdkVersion 27
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner
"android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
    }
}
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation"org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
implementation 'com.android.support:appcompat-v7:27.0.1'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
}
</code>```

and this is build.gradle(project):

```<code>// Top-level build file where you can add configuration options common to
all sub-projects/modules.

buildscript {
ext.kotlin_version = '1.1.60'
repositories {
    google()
    jcenter()
    maven {
        url "https://maven.google.com"
    }
}
dependencies {
    classpath 'com.android.tools.build:gradle:3.0.0'
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}

allprojects {
repositories {
    google()
    jcenter()
    maven {
        url "https://maven.google.com"
    }
}
}

task clean(type: Delete) {
delete rootProject.buildDir
}
</code>```

I did a lot of things to fix it but every time it failed.

I use gradle 4.3.1

And here is gradle wrapper properties :

```<code>#Sat Nov 18 10:16:45 IRST 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.3.1-all.zip
</code>```

答:
As of the new versions, the libraries are now inside the maven not inside Jcenter.

So inside your gradle file, you have to add maven like the below:

```<code>allprojects {
repositories {
    jcenter()
    maven {
        url "https://maven.google.com"
    }
}
 }
</code>```

This link may help you: Adding support libraries

ContentLicense: CC BY-SA 4.0

Body:
Today I updated Android  Studio to version 3.0

And after that I couldn't build project successfully.

I got these errors:

Unable to resolve dependency for ':app@release/compileClasspath': could not resolve com.android.support:appcompat-v7:27.0.1.

I tried using VPN or proxy etc. but none of them worked.

It's been a long day. I hope you may help me.

This is my build.gradle(app) :

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
compileSdkVersion 27
defaultConfig {
    applicationId "ir.hetbo.kotlin_tutorial"
    minSdkVersion 15
    targetSdkVersion 27
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner
"android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
    }
}
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation"org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
implementation 'com.android.support:appcompat-v7:27.0.1'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
}

and this is build.gradle(project):

// Top-level build file where you can add configuration options common to
all sub-projects/modules.

buildscript {
ext.kotlin_version = '1.1.60'
repositories {
    google()
    jcenter()
    maven {
        url "https://maven.google.com"
    }
}
dependencies {
    classpath 'com.android.tools.build:gradle:3.0.0'
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}

allprojects {
repositories {
    google()
    jcenter()
    maven {
        url "https://maven.google.com"
    }
}
}

task clean(type: Delete) {
delete rootProject.buildDir
}

I did a lot of things to fix it but every time it failed.

I use gradle 4.3.1

And here is gradle wrapper properties :

#Sat Nov 18 10:16:45 IRST 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.3.1-all.zip

Body:
As of the new versions, the libraries are now inside the maven not inside Jcenter.

So inside your gradle file, you have to add maven like the below:

allprojects {
repositories {
    jcenter()
    maven {
        url "https://maven.google.com"
    }
}
 }

This link may help you: Adding support libraries


问:
Trying to check if username already exists in MySQL database using PHP
I've looked at the many other posts that were similar to my issue and implemented their solutions (as far as I can tell) as exactly as I could. However, every time I execute this script, the code in the else block is executed (even when the username inputted is one that is already present).

The table name is 'Users' and the column that I am trying to search is 'username'.
The input from my form was read into $username and I verified that it was read in properly using echo. $con contains the connection to the server.

At some point I also put in echo $query (nothing was printed) and echo mysql_num_rows($query) (nothing was printed).

Here's the relevant segment of the code. Would really appreciate some tips.

```<code>$query = mysql_query("SELECT username FROM Users WHERE username=$username", $con);

  if (mysql_num_rows($query) != 0)
  {
      echo "Username already exists";
  }

  else
  {
    ...
  }
</code>```

EDIT: Apparently I was supposed to be using mysqli for my server and the way I checked the num_rows for that was by doing $query->num_rows since it was a property of the object. Thanks for all the help!

答:
PHP 7 improved query.........

$sql = mysqli_query($conn, "SELECT * from users WHERE user_uid = '$uid'");
      if (mysqli_num_rows($sql) > 0) {
         echo 'Username taken.';
      }

Body:
I've looked at the many other posts that were similar to my issue and implemented their solutions (as far as I can tell) as exactly as I could. However, every time I execute this script, the code in the else block is executed (even when the username inputted is one that is already present).

The table name is 'Users' and the column that I am trying to search is 'username'.
The input from my form was read into $username and I verified that it was read in properly using echo. $con contains the connection to the server.

At some point I also put in echo $query (nothing was printed) and echo mysql_num_rows($query) (nothing was printed).

Here's the relevant segment of the code. Would really appreciate some tips.

$query = mysql_query("SELECT username FROM Users WHERE username=$username", $con);

  if (mysql_num_rows($query) != 0)
  {
      echo "Username already exists";
  }

  else
  {
    ...
  }

EDIT: Apparently I was supposed to be using mysqli for my server and the way I checked the num_rows for that was by doing $query->num_rows since it was a property of the object. Thanks for all the help!


问:
How to get system date in SQL Server with the format of 'MM dd, yyyy'
How to get the system date in SQL Server with the format of MM dd, yyyy?

I tried everything but I couldn't get the correct format MM dd, yyyy

答:
Here's one way:</p>

```<code>DECLARE @mydate date = getdate()

SELECT CAST(DATEPART(MONTH, @mydate) as varchar)
      + ' '
      + CAST(DATEPART(DAY, @mydate) as varchar)
      + ', '
      + CAST(DATEPART(YEAR, @mydate) as varchar)
</code>```

Body:
Here's one way:

DECLARE @mydate date = getdate()

SELECT CAST(DATEPART(MONTH, @mydate) as varchar)
      + ' '
      + CAST(DATEPART(DAY, @mydate) as varchar)
      + ', '
      + CAST(DATEPART(YEAR, @mydate) as varchar)


问:
Access command line arguments in C++
Is it possible to get the command line arguments without receiving them via int main(int, char**)? I don't want to pass the arguments to multiple methods, so a global function would be perfect. Also, I do not want to store the arguments by myself via global variables. I'm running Windows and Linux.

edit:
Example:

```<code>int main()
{
   int argc = GetArgumentCount();
   char ** argv = GetArguments();
   return 0;
}
</code>```

edit:
It's possible to use LPTSTR WINAPI GetCommandLine(void); in win32.

https://msdn.microsoft.com/en-us/library/ms683156(v=vs.85).aspx

I'm looking for equivalent functions in Linux.

答:
Is it possible to get the command line arguments without receiving them via int main(int, char**) ?

No (at least, not in portable manner), however you could put the usual argc, argv into some global variable (or other global data, often after parsing). And that could also be into some static data with other functions in  the same translation unit retrieving it. Hence a reasonable (readable and portable) approach would be:

```<code>static int myargc;
static char **myargv;
int GetArgumentCount(void) {
  return myargc;
}
char**GetArguments(void) {
  return myargv;
}
int main(int argc, char**argv) {
   myargc= argc;
   myargv= argv;
   /// etc....
</code>```

Notice that on some systems or some implementations you might access to the command line arguments in some other ways.

dirty Linux specific tricks

For example, on Linux, using proc(5), you might parse /proc/self/cmdline but it is unreasonable to do that (on your Linux system, try to run od -cx /proc/self/cmdline in your terminal to guess what I mean), so I still recommend using int main(int argc, char**argv) and storing, in some global or static data, the argc and argv, or more probably, do some parsing of program arguments.

So on Linux, you might code your GetArgumentCount and GetArguments functions (by parsing /proc/self/cmdline, see also this) but it would be foolish to do so without using argc and argv from main (even if it is technically doable). Coding such a crazy GetArgumentCount and GetArguments which parses /proc/self/cmdline is left as an exercise to the masochistic reader.

Perhaps you need that because some static data's constructor -running before main and called before it from crt0- uses them; but in that case, your program's design is IMHO very wrong. I have no idea if similar dirty tricks are doable in Windows.

Title: Access command line arguments in C++

Body:
Is it possible to get the command line arguments without receiving them via int main(int, char**)? I don't want to pass the arguments to multiple methods, so a global function would be perfect. Also, I do not want to store the arguments by myself via global variables. I'm running Windows and Linux.

edit:
Example:

int main()
{
   int argc = GetArgumentCount();
   char ** argv = GetArguments();
   return 0;
}

edit:
It's possible to use LPTSTR WINAPI GetCommandLine(void); in win32.

https://msdn.microsoft.com/en-us/library/ms683156(v=vs.85).aspx

I'm looking for equivalent functions in Linux.

Body:
Is it possible to get the command line arguments without receiving them via int main(int, char**) ?

No (at least, not in portable manner), however you could put the usual argc, argv into some global variable (or other global data, often after parsing). And that could also be into some static data with other functions in  the same translation unit retrieving it. Hence a reasonable (readable and portable) approach would be:

static int myargc;
static char **myargv;
int GetArgumentCount(void) {
  return myargc;
}
char**GetArguments(void) {
  return myargv;
}
int main(int argc, char**argv) {
   myargc= argc;
   myargv= argv;
   /// etc....

Notice that on some systems or some implementations you might access to the command line arguments in some other ways.

dirty Linux specific tricks

For example, on Linux, using proc(5), you might parse /proc/self/cmdline but it is unreasonable to do that (on your Linux system, try to run od -cx /proc/self/cmdline in your terminal to guess what I mean), so I still recommend using int main(int argc, char**argv) and storing, in some global or static data, the argc and argv, or more probably, do some parsing of program arguments.

So on Linux, you might code your GetArgumentCount and GetArguments functions (by parsing /proc/self/cmdline, see also this) but it would be foolish to do so without using argc and argv from main (even if it is technically doable). Coding such a crazy GetArgumentCount and GetArguments which parses /proc/self/cmdline is left as an exercise to the masochistic reader.

Perhaps you need that because some static data's constructor -running before main and called before it from crt0- uses them; but in that case, your program's design is IMHO very wrong. I have no idea if similar dirty tricks are doable in Windows.


问:
How can i add more than on paralel corpus or monolingual model into my custom model ? - Multiple inheritance
When I create a new model, how can I add more than one MonolingualCorpus or Parallel Corpus in Java because the method only accepts one InputStream for each model.

```<code>TranslationModel modelFirst = new CreateModelOptions.Builder()
  .baseModelId("en-fr")
  .name(p.getName())
  .forcedGlossary(new FileInputStream(new File("forced1")))
  .parallelCorpus(new FileInputStream(new File("paralel1")))
  .monolingualCorpus(new FileInputStream(new File("mono1")))
  .build();
</code>```

Because otherwise, I don't understand the utility to create each time a new model if when I want to make a translation, I need to specify the ID of my custom model.

If I create a model with a forcedGlossary and a ParallelCorpus, the function returns me a new Model ID, for example, 12345.

After that, I want to add one ParallelCorpus and one Monolingual Model to this same model (ModelFirst). So I need to recreate a new model...

```<code>TranslationModel modelSecond = new CreateModelOptions.Builder()
  .baseModelId(12345)
  .name(p.getName())
  .parallelCorpus(new FileInputStream(new File("paralel2")))
  .monolingualCorpus(new FileInputStream(new File("mono2.txt")))
  .build();
</code>```

Now id of ModelSecond = 4567.

If I translate with the ModelFirst(12345), will Watson use the model from the ModelFirst AND from the ModelSecond or ONLY from the ModelFirst ??

If I translate with ModelSecond, Will it inherit my ModelFirst and basic model?

Can a model have multiple inheritance ?

答:
You can create a model with only 1 Monolingual Corpus. If you need to add more than one I would suggest you combine the models into one.

Custom models can only be created out of base models. There is no such thing as an inheritance for custom models.

Body:
When I create a new model, how can I add more than one MonolingualCorpus or Parallel Corpus in Java because the method only accepts one InputStream for each model.

TranslationModel modelFirst = new CreateModelOptions.Builder()
  .baseModelId("en-fr")
  .name(p.getName())
  .forcedGlossary(new FileInputStream(new File("forced1")))
  .parallelCorpus(new FileInputStream(new File("paralel1")))
  .monolingualCorpus(new FileInputStream(new File("mono1")))
  .build();

Because otherwise, I don't understand the utility to create each time a new model if when I want to make a translation, I need to specify the ID of my custom model.

If I create a model with a forcedGlossary and a ParallelCorpus, the function returns me a new Model ID, for example, 12345.

After that, I want to add one ParallelCorpus and one Monolingual Model to this same model (ModelFirst). So I need to recreate a new model...

TranslationModel modelSecond = new CreateModelOptions.Builder()
  .baseModelId(12345)
  .name(p.getName())
  .parallelCorpus(new FileInputStream(new File("paralel2")))
  .monolingualCorpus(new FileInputStream(new File("mono2.txt")))
  .build();

Now id of ModelSecond = 4567.

If I translate with the ModelFirst(12345), will Watson use the model from the ModelFirst AND from the ModelSecond or ONLY from the ModelFirst ??

If I translate with ModelSecond, Will it inherit my ModelFirst and basic model?

Can a model have multiple inheritance ?


问:
Adding hook to model creation in rails
I have a model class Person, and I create instances of them using:

```<code>person = Person.create!
</code>```

Now I want to say that this person was born in California, USA, but in this peculiar way:

```<code>person = Person.create!({:name => "Matt", :born => "USCA"})
</code>```

This means there are two characters to identify the country and another two characters to identify the state.
But I don't want to store the string in the database, I want to store in a structured way, like:

| Name | Country | State      |

| Matt | USA     | California |

Where can I parse the string to assign the country and state based on it? Which method in the model?

Thanks in advance

答: Check out the ActiveRecord Callbacks module</p>

Title: Adding hook to model creation in rails

Body:
I have a model class Person, and I create instances of them using:

person = Person.create!

Now I want to say that this person was born in California, USA, but in this peculiar way:

person = Person.create!({:name => "Matt", :born => "USCA"})

This means there are two characters to identify the country and another two characters to identify the state.
But I don't want to store the string in the database, I want to store in a structured way, like:

| Name | Country | State      |

| Matt | USA     | California |

Where can I parse the string to assign the country and state based on it? Which method in the model?

Thanks in advance