问:
Is possible to reuse DOMString returned from HTMLCanvasElement.toDataURL() or canvas.toBlob()?
I am setting up an image Cropper, it will give me width and height,X and Y of cropped details. Using that I am creating a preview image (using canvas) but is it possible to store that data returned from HTMLCanvasElement.toDataURL() or canvas.toBlob() and reuse in other devices and browsers?

Refer below link (it uses canvas.toBlob() method)
https://codesandbox.io/s/72py4jlll6

答:
You can try use this lines of code:

```<code>if (!HTMLCanvasElement.prototype.toBlob) {
 Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', {
  value: function (callback, type, quality) {

    var binStr = atob( this.toDataURL(type, quality).split(',')[1] ),
        len = binStr.length,
        arr = new Uint8Array(len);

    for (var i=0; i<len; i++ ) {
     arr[i] = binStr.charCodeAt(i);
    }

    callback( new Blob( [arr], {type: type || 'image/png'} ) );
  }
 });
}
</code>```

Just change to your code.
Please LMK soon.

Body:
You can try use this lines of code:

if (!HTMLCanvasElement.prototype.toBlob) {
 Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', {
  value: function (callback, type, quality) {

    var binStr = atob( this.toDataURL(type, quality).split(',')[1] ),
        len = binStr.length,
        arr = new Uint8Array(len);

    for (var i=0; i<len; i++ ) {
     arr[i] = binStr.charCodeAt(i);
    }

    callback( new Blob( [arr], {type: type || 'image/png'} ) );
  }
 });
}

Just change to your code.
Please LMK soon.


来源: stackexchange

答:
Ypu can convert Blob to base64 string,
and save it on server side.

So you can serve this media later to different user/browser.

The way to do it is:

```<code>let reader = new FileReader();
reader.readAsDataURL(blob); // converts the blob to base64 and calls onload

reader.onload = function() {
  data = reader.result; // data url as base 64 encoded string.
};
</code>```

Decoding this string will get you the binary PNG data.

ContentLicense: CC BY-SA 4.0

Title: Is possible to reuse DOMString returned from HTMLCanvasElement.toDataURL() or canvas.toBlob()?

Body:
I am setting up an image Cropper, it will give me width and height,X and Y of cropped details. Using that I am creating a preview image (using canvas) but is it possible to store that data returned from HTMLCanvasElement.toDataURL() or canvas.toBlob() and reuse in other devices and browsers?

Refer below link (it uses canvas.toBlob() method)
https://codesandbox.io/s/72py4jlll6

Body:
Ypu can convert Blob to base64 string,
and save it on server side.

So you can serve this media later to different user/browser.

The way to do it is:

let reader = new FileReader();
reader.readAsDataURL(blob); // converts the blob to base64 and calls onload

reader.onload = function() {
  data = reader.result; // data url as base 64 encoded string.
};

Decoding this string will get you the binary PNG data.


问:
Convert TSV to CSV, where TSV field has commas in it
I have a TSV with fields that look like:

```<code>name   location   1,2,3,4,5
</code>```

When I use sed 's/\w/,/g'
i end up with a csv where 1,2,3,4 and 5 are considered seperate entrys.
I would like it to be '1 2 3 4 5'
I've tried converting commas to white space before running the above command using

```<code>sed 's/,/\w/g'
</code>```

however when converting the whitespace back to commas it includes single white spaces as well as the tabs, so what is the regex for just a single whitespace character?

Desired output:

```<code>name, location,1 2 3 4 5,
</code>```

答:
And in awk:

```<code>$ awk -v OFS="," '{for(i=1;i<=NF;i++)if($i~/,/)$i="\"" $i "\"";$1=$1}1' file
name,location,"1,2,3,4,5"
</code>```

Explained:

```<code>$ awk -v OFS="," '{          # output delimiter to a comma *
    for(i=1;i<=NF;i++)       # loop all fields
        if($i~/,/)           # if comma in field
            $i="\"" $i "\""  # surround with quotes **
    $1=$1                    # rebuild record
}1' file                     # output
</code>```

* if there is space in the record, consider input field separator to a tab with  awk -F"\t".

** also, if there are quotes in the fields with commas, maybe they should be duplicated or escaped.

Body:
I have a TSV with fields that look like:

name   location   1,2,3,4,5

When I use sed 's/\w/,/g'
i end up with a csv where 1,2,3,4 and 5 are considered seperate entrys.
I would like it to be '1 2 3 4 5'
I've tried converting commas to white space before running the above command using

sed 's/,/\w/g'

however when converting the whitespace back to commas it includes single white spaces as well as the tabs, so what is the regex for just a single whitespace character?

Desired output:

name, location,1 2 3 4 5,

Body:
And in awk:

$ awk -v OFS="," '{for(i=1;i<=NF;i++)if($i~/,/)$i="\"" $i "\"";$1=$1}1' file
name,location,"1,2,3,4,5"

Explained:

$ awk -v OFS="," '{          # output delimiter to a comma *
    for(i=1;i<=NF;i++)       # loop all fields
        if($i~/,/)           # if comma in field
            $i="\"" $i "\""  # surround with quotes **
    $1=$1                    # rebuild record
}1' file                     # output

* if there is space in the record, consider input field separator to a tab with  awk -F"\t".

** also, if there are quotes in the fields with commas, maybe they should be duplicated or escaped.


问:
UIImage imageNamed giving EXC_BAD_ACCESS the second time
I'm working on a game with a bunch of mini games. Inside one gameview, I have the following code:

```<code>UIImage* img = [UIImage imageNamed:@"foo.png"];
someImage = CGImageRetain(img.CGImage);
[img release];
</code>```

someImage is of type CGImageRef, and this has no issues the first time. After the user loses the mini game (or exits), the game and everything seems to get dealloc'd properly. Then, if they go back into the mini game, and the game gets constructed again, the line:

```<code>someImage = CGImageRetain(img.CGImage);
</code>```

causes an error of some kind...almost like my UIImage object got released already. I know there's some quirks to using [UIImage imageNamed], but I can't track this down at all. Any help would be greatly appreciated :)

答:
This line is your problem;

```<code>[img release];
</code>```

In Cocoa the general convention is that if a function returns an object and does not contain the words copy or alloc then you do not have to release it.

Functions that return objects usually add them to an autorelease pool. If you plan to keep the object then you should retain (and later release) it. If not then it will automatically be freed.

If you try to release one of these objects then it will cause badness. In this case I suspect it's deallocating a resource that the OS believes it still owns.

This thread contains more details about memory management under Cocoa.

OwnerDisplayName: Jonas

ContentLicense: CC BY-SA 2.5

Body:
I'm working on a game with a bunch of mini games. Inside one gameview, I have the following code:

UIImage* img = [UIImage imageNamed:@"foo.png"];
someImage = CGImageRetain(img.CGImage);
[img release];

someImage is of type CGImageRef, and this has no issues the first time. After the user loses the mini game (or exits), the game and everything seems to get dealloc'd properly. Then, if they go back into the mini game, and the game gets constructed again, the line:

someImage = CGImageRetain(img.CGImage);

causes an error of some kind...almost like my UIImage object got released already. I know there's some quirks to using [UIImage imageNamed], but I can't track this down at all. Any help would be greatly appreciated :)

LastEditorDisplayName: Chris Hanson

Body:
This line is your problem;

[img release];

In Cocoa the general convention is that if a function returns an object and does not contain the words copy or alloc then you do not have to release it.

Functions that return objects usually add them to an autorelease pool. If you plan to keep the object then you should retain (and later release) it. If not then it will automatically be freed.

If you try to release one of these objects then it will cause badness. In this case I suspect it's deallocating a resource that the OS believes it still owns.

This thread contains more details about memory management under Cocoa.

OwnerDisplayName: Andrew Grant

LastEditorDisplayName: Andrew Grant


问:
Retrieve XML from HTTP POST Request Payload
I have an ActiveX that POSTs to the server (HTTP Handler) with a payload of a certain XML document.

Is there a better way to retrieve the payload into XML than the below?

```<code>private static byte[] RequestPayload()
{
   int bytesToRead = HttpContext.Current.Request.TotalBytes;
   return (HttpContext.Current.Request.BinaryRead(bytesToRead));
}

using (var mem = new MemoryStream(RequestPayload()))
{
    var docu = XDocument.Load(mem);
}
</code>```

Once I have the "docu" I can query using LINQ to XML.

Thanks

答:
Simply load the XML from the InputStream of the Request e.g.

```<code>XDocument doc;
using (Stream input = HttpContext.Current.Request.InputStream)
{
  doc = XDocument.Load(input);
}
</code>```

there is no need for a MemoryStream in my view.

ContentLicense: CC BY-SA 3.0

Body:
I have an ActiveX that POSTs to the server (HTTP Handler) with a payload of a certain XML document.

Is there a better way to retrieve the payload into XML than the below?

private static byte[] RequestPayload()
{
   int bytesToRead = HttpContext.Current.Request.TotalBytes;
   return (HttpContext.Current.Request.BinaryRead(bytesToRead));
}

using (var mem = new MemoryStream(RequestPayload()))
{
    var docu = XDocument.Load(mem);
}

Once I have the "docu" I can query using LINQ to XML.

Thanks

Body:
Simply load the XML from the InputStream of the Request e.g.

XDocument doc;
using (Stream input = HttpContext.Current.Request.InputStream)
{
  doc = XDocument.Load(input);
}

there is no need for a MemoryStream in my view.


问:
Which is better to use: regex.containsMatchIn(String) or String.contains(regex) and why?
If i have a String called "text" and a Regex (called "regex" for ease) i want to check it against, should i use:

```<code>regex.containsMatchIn(text)
</code>```

or should i use:

```<code>text.contains(regex)
</code>```

Both seem to be successful but i am unsure of the best practices concerning this.

答:
Use whichever one makes your code easier to read. There is no difference between them because text.contains(regex) calls the regex.containsMatchIn(text) As per Strings.kt source code:

```<code>@kotlin.internal.InlineOnly
public inline operator fun CharSequence.contains(regex: Regex): Boolean = regex.containsMatchIn(this)
</code>```

Body:
If i have a String called "text" and a Regex (called "regex" for ease) i want to check it against, should i use:

regex.containsMatchIn(text)

or should i use:

text.contains(regex)

Both seem to be successful but i am unsure of the best practices concerning this.

Body:
Use whichever one makes your code easier to read. There is no difference between them because text.contains(regex) calls the regex.containsMatchIn(text) As per Strings.kt source code:

@kotlin.internal.InlineOnly
public inline operator fun CharSequence.contains(regex: Regex): Boolean = regex.containsMatchIn(this)


问:
idb2 connection not allowed with c#
i have a little problem with my connection with the AS400.I am using c#.
When i want to do an insert sql statement on a table, it pops this message

SystemInvalidOperationException : This operation cannot be successful
  because the connection is not allowed at
  IBM.Data.DB2.iSeries.iDB2Command.verifyConnection(); at
  IBM.Data.DB2.iSeries.iDB2Command.ExecuteNonQuery();

here is my definition of the connection string

```<code>    public static string userID;
    public static string passwd;
    public static string system;
    public string query;
    public iDB2Connection conn = new iDB2Connection("DataSource=" + system + ";UserID=" + userID + ";Password=" + passwd + ";DataCompression=true;");
</code>```

and the code that contains the insert statement

```<code>       public  void insert(Programs prog, int nbfiche)
        {
        //conn.Open();
        try
        {

            string sqlQuery = "INSERT INTO DIIAB.FICDET(MTPRO,MTFICH,MTPGM,MTNSRC,MTLSRC,MTTYP,MTOBJT) VALUES('" + Progiciel + "','" + nbfiche + "','" + prog.program_name +
                "','" + prog.source_program + "','" + LIB + "','" + prog.element_type + "','" + prog.program_type + "')";

            iDB2Command iDB2Command = conn.CreateCommand();
            iDB2Command.CommandText = sqlQuery;
            iDB2Command.ExecuteNonQuery();
            sqlQuery = "select MTFICH from DIIAB.FICDET where MTFICH='" + nbfiche + "'";
            iDB2Command command = conn.CreateCommand();
            command.CommandText = sqlQuery;
            iDB2DataReader reader = command.ExecuteReader();
            while (reader.Read())
            {

                if (reader[0].ToString().Contains(nbfiche.ToString()))
                {
                    System.Windows.MessageBox.Show("Un programme à été rajouté à la fiche.");
                }

            }

            System.Windows.MessageBox.Show("Les programmes ont été rajouté à la fiche", "Information");

        }
        catch (Exception e)
        {
            System.Windows.MessageBox.Show(e.ToString());
        }

    }
</code>```

and the code that call the method insert with the parameters

```<code>         edit.userID = userID;
                            edit.passwd = passwd;
                            edit.system = system;
                            edit editeur = new edit();

                            editeur.nbfiche = Convert.ToInt32(daoficnbr.fICNBR.nb_fiche);
                            editeur.fiche_status = Statuss.Text;
                            editeur.Progiciel = PRO.Text;
                            editeur.getpgm(arcad.lib,daoficnbr.fICNBR.nb_fiche);
                            foreach (Programs p in editeur.content)
                            {
                                editeur.insert(p, editeur.nbfiche);
                            }
</code>```

Could help me please it's been already 2 days i am stuck on this one

答: Solution was to ensure that the connection string was terminated by a semi-colon and that the conn.Open() completed successfully before running commands or queries.</p>

Title: idb2 connection not allowed with c#

Body:
i have a little problem with my connection with the AS400.I am using c#.
When i want to do an insert sql statement on a table, it pops this message

SystemInvalidOperationException : This operation cannot be successful
  because the connection is not allowed at
  IBM.Data.DB2.iSeries.iDB2Command.verifyConnection(); at
  IBM.Data.DB2.iSeries.iDB2Command.ExecuteNonQuery();

here is my definition of the connection string

    public static string userID;
    public static string passwd;
    public static string system;
    public string query;
    public iDB2Connection conn = new iDB2Connection("DataSource=" + system + ";UserID=" + userID + ";Password=" + passwd + ";DataCompression=true;");

and the code that contains the insert statement

       public  void insert(Programs prog, int nbfiche)
        {
        //conn.Open();
        try
        {

            string sqlQuery = "INSERT INTO DIIAB.FICDET(MTPRO,MTFICH,MTPGM,MTNSRC,MTLSRC,MTTYP,MTOBJT) VALUES('" + Progiciel + "','" + nbfiche + "','" + prog.program_name +
                "','" + prog.source_program + "','" + LIB + "','" + prog.element_type + "','" + prog.program_type + "')";

            iDB2Command iDB2Command = conn.CreateCommand();
            iDB2Command.CommandText = sqlQuery;
            iDB2Command.ExecuteNonQuery();
            sqlQuery = "select MTFICH from DIIAB.FICDET where MTFICH='" + nbfiche + "'";
            iDB2Command command = conn.CreateCommand();
            command.CommandText = sqlQuery;
            iDB2DataReader reader = command.ExecuteReader();
            while (reader.Read())
            {

                if (reader[0].ToString().Contains(nbfiche.ToString()))
                {
                    System.Windows.MessageBox.Show("Un programme à été rajouté à la fiche.");
                }

            }

            System.Windows.MessageBox.Show("Les programmes ont été rajouté à la fiche", "Information");

        }
        catch (Exception e)
        {
            System.Windows.MessageBox.Show(e.ToString());
        }

    }

and the code that call the method insert with the parameters

         edit.userID = userID;
                            edit.passwd = passwd;
                            edit.system = system;
                            edit editeur = new edit();

                            editeur.nbfiche = Convert.ToInt32(daoficnbr.fICNBR.nb_fiche);
                            editeur.fiche_status = Statuss.Text;
                            editeur.Progiciel = PRO.Text;
                            editeur.getpgm(arcad.lib,daoficnbr.fICNBR.nb_fiche);
                            foreach (Programs p in editeur.content)
                            {
                                editeur.insert(p, editeur.nbfiche);
                            }

Could help me please it's been already 2 days i am stuck on this one


问:
how can I change kiwi template text on test case?
I would like to ask if it is possible to edit the predefined text when creating a new test case? See. attachment.

Thanks,
Tomas

答: At the moment it is not possible to do this. Please file a RFE on GitHub so we can track this feature. We've got an idea to make it possible to select a TestCase/TestPlan as a template which can solve this request as well as a few other issues that we have open.</p>


问:
ImportError: No module named appJar
I am very new to coding and was trying to create a gui using appJar in atom.
I followed the steps on the appJar website but whenever I run the code this is the message it gives:

ImportError: No module named appJar

What do i do? Also am I using appJar correctly?

答: if you have windows you can open cmd and type pip install appjar or if you are using a IDE that has terminal it is not important which operating system you are using. just type pip install appjar in IDE terminal.

Title: ImportError: No module named appJar


问:
Couldn't find Product with 'id'=test
Basically working on setting up a favorite product situation but I'm stuck on actually setting it up

This is what I got so far

I think it's because I'm using Friendly URL - I've added friendly.find.. but I still get another error there as well (see second image)

Controller

  def update
    khollection = Khollection.where(cproduct: Cproduct.find(params[:cproduct]), user: current_user)
    if khollection == []
        # Create the khollection
        Khollection.create(cproduct: Cproduct.find(params[:cproduct]), user: current_user)
        @khollection_exists = true
    else
        # Delete the khollection
        khollection.destory_all
        @khollection_exists = false
    end
    respond_to do |format|
        format.html {}
        format.js {}
    end
  end

```

<p><strong>View</strong></p>

```<%= link_to 'Favorite', khollections_update_path(cproduct: @cproduct.title) %>
```

<p>Below With Friendly .friendly.find(params...</p>

<pre class="lang-rb prettyprint-override"><code>  def update
    khollection = Khollection.where(cproduct: Cproduct.friendly.find(params[:cproduct]), user: current_user)
    if khollection == []
        # Create the khollection
        Khollection.create(cproduct: Cproduct.friendly.find(params[:cproduct]), user: current_user)
</code>```

MODEL

class Khollection < ApplicationRecord
  belongs_to :cproduct
  belongs_to :user
end
```

<p><strong>Schema.rb</strong></p>

<pre class="lang-rb prettyprint-override"><code># This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.

ActiveRecord::Schema.define(version: 2019_05_28_112623) do

  create_table "active_storage_attachments", force: :cascade do |t|
    t.string "name", null: false
    t.string "record_type", null: false
    t.integer "record_id", null: false
    t.integer "blob_id", null: false
    t.datetime "created_at", null: false
    t.index ["blob_id"], name: "index_active_storage_attachments_on_blob_id"
    t.index ["record_type", "record_id", "name", "blob_id"], name: "index_active_storage_attachments_uniqueness", unique: true
  end

  create_table "active_storage_blobs", force: :cascade do |t|
    t.string "key", null: false
    t.string "filename", null: false
    t.string "content_type"
    t.text "metadata"
    t.bigint "byte_size", null: false
    t.string "checksum", null: false
    t.datetime "created_at", null: false
    t.index ["key"], name: "index_active_storage_blobs_on_key", unique: true
  end

  create_table "cproducts", force: :cascade do |t|
    t.string "title"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer "user_id"
    t.string "slug"
    t.index ["slug"], name: "index_cproducts_on_slug", unique: true
  end

  create_table "friendly_id_slugs", force: :cascade do |t|
    t.string "slug", null: false
    t.integer "sluggable_id", null: false
    t.string "sluggable_type", limit: 50
    t.string "scope"
    t.datetime "created_at"
    t.index ["slug", "sluggable_type", "scope"], name: "index_friendly_id_slugs_on_slug_and_sluggable_type_and_scope", unique: true
    t.index ["slug", "sluggable_type"], name: "index_friendly_id_slugs_on_slug_and_sluggable_type"
    t.index ["sluggable_type", "sluggable_id"], name: "index_friendly_id_slugs_on_sluggable_type_and_sluggable_id"
  end

  create_table "khollections", force: :cascade do |t|
    t.integer "Cproduct_id"
    t.integer "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["Cproduct_id"], name: "index_khollections_on_Cproduct_id"
    t.index ["user_id"], name: "index_khollections_on_user_id"
  end

  create_table "users", force: :cascade do |t|
    t.string "email"
    t.string "encrypted_password", default: "", null: false
    t.string "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.text "full_company_logo"
    t.text "domain"
    t.string "business_name"
    t.string "tags"
    t.text "social_media"
    t.text "our_story"
    t.text "location_address"
    t.string "location_city"
    t.string "location_state"
    t.integer "phone"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.boolean "admin"
    t.boolean "company"
    t.boolean "judge"
    t.boolean "blogger"
    t.string "username"
    t.string "slug"
    t.string "avatar"
    t.string "company_logo"
    t.index ["email"], name: "index_users_on_email", unique: true
    t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
    t.index ["slug"], name: "index_users_on_slug", unique: true
  end

end

</code>```

CURRENT ERROR

答:
this is where error is

```<code>create_table "khollections", force: :cascade do |t|
    t.integer "Cproduct_id"
    t.integer "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["Cproduct_id"], name: "index_khollections_on_Cproduct_id"
    t.index ["user_id"], name: "index_khollections_on_user_id"
  end
</code>```

replace with

```<code>create_table "khollections", force: :cascade do |t|
    t.integer "cproduct_id"
    t.integer "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["cproduct_id"], name: "index_khollections_on_cproduct_id"
    t.index ["user_id"], name: "index_khollections_on_user_id"
  end
</code>```

and

```<code>khollection = Khollection.where(cproduct: Cproduct.find_by(title: params[:cproduct]), user: current_user)

Khollection.create(cproduct: Cproduct.find_by(title: params[:cproduct]), user: current_user)

<%= link_to 'Favorite', khollections_update_path(cproduct: @cproduct.title) %>
</code>```

Title: Couldn't find Product with 'id'=test

Body:
Basically working on setting up a favorite product situation but I'm stuck on actually setting it up

This is what I got so far

I think it's because I'm using Friendly URL - I've added friendly.find.. but I still get another error there as well (see second image)

Controller

  def update
    khollection = Khollection.where(cproduct: Cproduct.find(params[:cproduct]), user: current_user)
    if khollection == []
        # Create the khollection
        Khollection.create(cproduct: Cproduct.find(params[:cproduct]), user: current_user)
        @khollection_exists = true
    else
        # Delete the khollection
        khollection.destory_all
        @khollection_exists = false
    end
    respond_to do |format|
        format.html {}
        format.js {}
    end
  end

View

<%= link_to 'Favorite', khollections_update_path(cproduct: @cproduct.title) %>

Below With Friendly .friendly.find(params...

  def update
    khollection = Khollection.where(cproduct: Cproduct.friendly.find(params[:cproduct]), user: current_user)
    if khollection == []
        # Create the khollection
        Khollection.create(cproduct: Cproduct.friendly.find(params[:cproduct]), user: current_user)

MODEL

class Khollection < ApplicationRecord
  belongs_to :cproduct
  belongs_to :user
end

Schema.rb

# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.

ActiveRecord::Schema.define(version: 2019_05_28_112623) do

  create_table "active_storage_attachments", force: :cascade do |t|
    t.string "name", null: false
    t.string "record_type", null: false
    t.integer "record_id", null: false
    t.integer "blob_id", null: false
    t.datetime "created_at", null: false
    t.index ["blob_id"], name: "index_active_storage_attachments_on_blob_id"
    t.index ["record_type", "record_id", "name", "blob_id"], name: "index_active_storage_attachments_uniqueness", unique: true
  end

  create_table "active_storage_blobs", force: :cascade do |t|
    t.string "key", null: false
    t.string "filename", null: false
    t.string "content_type"
    t.text "metadata"
    t.bigint "byte_size", null: false
    t.string "checksum", null: false
    t.datetime "created_at", null: false
    t.index ["key"], name: "index_active_storage_blobs_on_key", unique: true
  end

  create_table "cproducts", force: :cascade do |t|
    t.string "title"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer "user_id"
    t.string "slug"
    t.index ["slug"], name: "index_cproducts_on_slug", unique: true
  end

  create_table "friendly_id_slugs", force: :cascade do |t|
    t.string "slug", null: false
    t.integer "sluggable_id", null: false
    t.string "sluggable_type", limit: 50
    t.string "scope"
    t.datetime "created_at"
    t.index ["slug", "sluggable_type", "scope"], name: "index_friendly_id_slugs_on_slug_and_sluggable_type_and_scope", unique: true
    t.index ["slug", "sluggable_type"], name: "index_friendly_id_slugs_on_slug_and_sluggable_type"
    t.index ["sluggable_type", "sluggable_id"], name: "index_friendly_id_slugs_on_sluggable_type_and_sluggable_id"
  end

  create_table "khollections", force: :cascade do |t|
    t.integer "Cproduct_id"
    t.integer "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["Cproduct_id"], name: "index_khollections_on_Cproduct_id"
    t.index ["user_id"], name: "index_khollections_on_user_id"
  end

  create_table "users", force: :cascade do |t|
    t.string "email"
    t.string "encrypted_password", default: "", null: false
    t.string "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.text "full_company_logo"
    t.text "domain"
    t.string "business_name"
    t.string "tags"
    t.text "social_media"
    t.text "our_story"
    t.text "location_address"
    t.string "location_city"
    t.string "location_state"
    t.integer "phone"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.boolean "admin"
    t.boolean "company"
    t.boolean "judge"
    t.boolean "blogger"
    t.string "username"
    t.string "slug"
    t.string "avatar"
    t.string "company_logo"
    t.index ["email"], name: "index_users_on_email", unique: true
    t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
    t.index ["slug"], name: "index_users_on_slug", unique: true
  end

end

CURRENT ERROR

Body:
this is where error is

create_table "khollections", force: :cascade do |t|
    t.integer "Cproduct_id"
    t.integer "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["Cproduct_id"], name: "index_khollections_on_Cproduct_id"
    t.index ["user_id"], name: "index_khollections_on_user_id"
  end

replace with

create_table "khollections", force: :cascade do |t|
    t.integer "cproduct_id"
    t.integer "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["cproduct_id"], name: "index_khollections_on_cproduct_id"
    t.index ["user_id"], name: "index_khollections_on_user_id"
  end

and

khollection = Khollection.where(cproduct: Cproduct.find_by(title: params[:cproduct]), user: current_user)

Khollection.create(cproduct: Cproduct.find_by(title: params[:cproduct]), user: current_user)

<%= link_to 'Favorite', khollections_update_path(cproduct: @cproduct.title) %>


答:
Not sure what's going on behind the scenes with the friendly id, but you should be able to query by the product name:

```<code>  product = Cproduct.find_by(title: params[:cproduct]).take
  if product
    khollection = Khollection.where(cproduct_id: product.id), user: current_user).take
    if khollection.blank?
      # Create the khollection
      Khollection.create(cproduct: product, user: current_user)
      @khollection_exists = true
    else
      # Delete the khollection
      khollection.destory_all
      @khollection_exists = false
    end
  else
    # maybe return an error status "Product not found"
  end

  respond_to do |format|
    format.html {}
    format.js {}
  end
</code>```

The point is that you can always fall back on the column names instead of relying on a gem.

Title: Couldn't find Product with 'id'=test

Body:
Not sure what's going on behind the scenes with the friendly id, but you should be able to query by the product name:

  product = Cproduct.find_by(title: params[:cproduct]).take
  if product
    khollection = Khollection.where(cproduct_id: product.id), user: current_user).take
    if khollection.blank?
      # Create the khollection
      Khollection.create(cproduct: product, user: current_user)
      @khollection_exists = true
    else
      # Delete the khollection
      khollection.destory_all
      @khollection_exists = false
    end
  else
    # maybe return an error status "Product not found"
  end

  respond_to do |format|
    format.html {}
    format.js {}
  end

The point is that you can always fall back on the column names instead of relying on a gem.


问:
TCP Socket What is the "flow of events" when two nodes talk
Relating to my previous question here, Previous Question, let me try to ask my question in laymen's terms (As I understand things in order to ask my question).

I am building a TCP client <--> server app.

Help me to understand what the correct protocol of events (should be) for my client and server to have a conversation.

What I expect to be able to do:

Server listens.

Client connects to server.

Client sends a string to server.

Server Receives data

Server replies back (I manually send an "<ok>" string)

Here now, I expect my client to chill, hang out and do nothing until I fire it's send method to send new data to the server.

I then expect the server to receive said data, and repeat step 5 (Reply).

In my example, I am using code for the asynchronous sockets example provided by Microsoft. I can send the string and my server can reply back.

I then intentionally don't send anything back to the server, until I need to (think chat application). When I eventually decide to send data to the server, my client socket sends the data, but the server never receives this new incoming data.  (Receive never fires)

I am assuming the server is still waiting for the callback from the client after it send the "<ok>" string in the previous data exchange. I never did send anything back after the "<ok>", as I was done doing whatever work I wanted to do. (Like send a "hello" string).

In the example the client and server are wired with a callback after sending data, to receive data back from the other side. Is this a must for sockets? Or is this something to do with Asynchronous sockets?

If so, do I need to reply back immediately after receiving any data, which is not always my intention? Do I have to ping <--> pong back and forth untill I eventually have work for the socket connection to do?

I hope my question makes sense. I am looking for a better understanding as to what is "expected" to happen when two nodes talk...

答:
On a socket, the send and receive pipes are completely disconnected and independent; as long as the code is written correctly, you can process both completely independently, and there is no specific dependency between sends and receives - you can be send only, receive only, or you can send and receive separately without any expectation that you always do one then the other. In very simple scenarios, clients tend to send then receive, and servers tend to receive then send, but this is merely because that's the request/response pattern (when client-initiated), not because of anything intrinsic to sockets.

So: if what you want to do isn't working, the problem is somewhere in your code (or whatever library you are using to abstract over the socket). What you describe can be done just fine.


问:
XCode 4 CpResource error
When I build my app with Xcode 4 it always show this error message:

```<code> CpResource "Color Calculator/X.png"
 "/Users/mauro/Library/Developer/Xcode/DerivedData/Color_Calculator-eomtenpvfeomibgervrskkupofrx/Build/Products/Debug-iphonesimulator/Color Calculator.app/X.png"
</code>```

It seems that Xcode wants to copy X.png in the DerivedData.

But I don't have X.png in my project. I use to have it, but it was deleted some versions ago (with many other png).
In order to verify, I deleted all the objects in project's xibs. So now I have two empty xib, however the error message continues to appear.

Thank you.

答: In my case I removed the icon and added my "LAUNCH SCREEN and MAIN STRORY BOARD".

Title: XCode 4 CpResource error

Body:
When I build my app with Xcode 4 it always show this error message:

 CpResource "Color Calculator/X.png"
 "/Users/mauro/Library/Developer/Xcode/DerivedData/Color_Calculator-eomtenpvfeomibgervrskkupofrx/Build/Products/Debug-iphonesimulator/Color Calculator.app/X.png"

It seems that Xcode wants to copy X.png in the DerivedData.

But I don't have X.png in my project. I use to have it, but it was deleted some versions ago (with many other png).
In order to verify, I deleted all the objects in project's xibs. So now I have two empty xib, however the error message continues to appear.

Thank you.


问:
writting scala object to json file through jackson API
I'm getting the output {} like this only. I am not understanding why I am not getting the correct output

I have tried upto with the all API's of JSON to convert my  scala object to JSON but I am failed.

```<code>package com.sathya
import org.codehaus.jackson.map.{ObjectMapper, SerializationConfig}
import org.codehaus.jackson.map.SerializationConfig

case class Employee(empNo:Int,empName:String,salary:Int)

class NewClass{
  val mapper: ObjectMapper = new ObjectMapper();
  mapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false)

  def convertJavaToJason(obj:Employee):String={
      var output:String=mapper.writeValueAsString(obj);
    return output;
  }
}
object JSONObjectClass1{
  def main(args: Array[String]): Unit = {
    var emp=new Employee(101,"Piyush",1000);
    var nc=new NewClass();
    var zp:String=nc.convertJavaToJason(emp);
    println(zp);
  }
}
</code>```

答:
First, I strongly recommend to switch com.fasterxml.jackson.

org.codehaus.jackson is an older version of Jackson, while com.fasterxml.jackson represents the new project and package.

The reason is, Jackson has moved from Codehaus to Github when releasing Jackson 2.

You need to use:
libraryDependencies ++= Seq(
 "com.fasterxml.jackson.core" % "jackson-databind" % "2.9.9",
 "com.fasterxml.jackson.module" %% "jackson-module-scala" % "2.9.9"
)

and change your code to (maybe more imports should be added):

```<code>import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper

case class Employee(empNo:Int,empName:String,salary:Int)

class NewClass {
  val objectMapper = new ObjectMapper() with ScalaObjectMapper
  objectMapper.registerModule(DefaultScalaModule)

  def convertJavaToJason(obj:Employee):String = {
    val out = new ByteArrayOutputStream()
    objectMapper.writeValue(out, obj)
    out.toString
}

object JSONObjectClass1{
  def main(args: Array[String]): Unit = {
    val emp=new Employee(101,"Piyush",1000);
    val nc = new NewClass();
    val zp:String = nc.convertJavaToJason(emp);
    println(zp);
  }
}
</code>```

A more easier way is to use Gson:

Add the dependencies:
libraryDependencies += "com.google.code.gson" % "gson" % "2.8.5"

And your code will be like:

```<code>import com.google.gson.Gson

case class Employee(empNo:Int,empName:String,salary:Int)

class NewClass {
  val gson = new Gson()

  def convertJavaToJason(obj:Employee):String = {
    gson.toJson(obj)
}

object JSONObjectClass1{
  def main(args: Array[String]): Unit = {
    val emp=new Employee(101,"Piyush",1000);
    val nc = new NewClass();
    val zp:String = nc.convertJavaToJason(emp);
    println(zp);
  }
}
</code>```

Body:
I'm getting the output {} like this only. I am not understanding why I am not getting the correct output

I have tried upto with the all API's of JSON to convert my  scala object to JSON but I am failed.

package com.sathya
import org.codehaus.jackson.map.{ObjectMapper, SerializationConfig}
import org.codehaus.jackson.map.SerializationConfig

case class Employee(empNo:Int,empName:String,salary:Int)

class NewClass{
  val mapper: ObjectMapper = new ObjectMapper();
  mapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false)

  def convertJavaToJason(obj:Employee):String={
      var output:String=mapper.writeValueAsString(obj);
    return output;
  }
}
object JSONObjectClass1{
  def main(args: Array[String]): Unit = {
    var emp=new Employee(101,"Piyush",1000);
    var nc=new NewClass();
    var zp:String=nc.convertJavaToJason(emp);
    println(zp);
  }
}

Body:
First, I strongly recommend to switch com.fasterxml.jackson.

org.codehaus.jackson is an older version of Jackson, while com.fasterxml.jackson represents the new project and package.

The reason is, Jackson has moved from Codehaus to Github when releasing Jackson 2.

You need to use:
libraryDependencies ++= Seq(
 "com.fasterxml.jackson.core" % "jackson-databind" % "2.9.9",
 "com.fasterxml.jackson.module" %% "jackson-module-scala" % "2.9.9"
)

and change your code to (maybe more imports should be added):

import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper

case class Employee(empNo:Int,empName:String,salary:Int)

class NewClass {
  val objectMapper = new ObjectMapper() with ScalaObjectMapper
  objectMapper.registerModule(DefaultScalaModule)

  def convertJavaToJason(obj:Employee):String = {
    val out = new ByteArrayOutputStream()
    objectMapper.writeValue(out, obj)
    out.toString
}

object JSONObjectClass1{
  def main(args: Array[String]): Unit = {
    val emp=new Employee(101,"Piyush",1000);
    val nc = new NewClass();
    val zp:String = nc.convertJavaToJason(emp);
    println(zp);
  }
}

A more easier way is to use Gson:

Add the dependencies:
libraryDependencies += "com.google.code.gson" % "gson" % "2.8.5"

And your code will be like:

import com.google.gson.Gson

case class Employee(empNo:Int,empName:String,salary:Int)

class NewClass {
  val gson = new Gson()

  def convertJavaToJason(obj:Employee):String = {
    gson.toJson(obj)
}

object JSONObjectClass1{
  def main(args: Array[String]): Unit = {
    val emp=new Employee(101,"Piyush",1000);
    val nc = new NewClass();
    val zp:String = nc.convertJavaToJason(emp);
    println(zp);
  }
}


问:
MySQL date comparison query
I have this table in my database:

```<code>table t

id   |  a   | b  | date_x

1    |  81  | 12 | 2018-03-16
2    |  9   | 54 | 2025-04-21
3    |  81  | 67 | 2018-03-16
4    |  763 | 81 | 2018-03-16
5    |  90  | 22 | 2025-12-08
</code>```

date_x is type DATE

I would like to select the rows where a = 81 or b = 81 and date_x is before 2019-05-28 .

So I perform the following query in MySQL Workbench:

```<code>SELECT * FROM t
WHERE a = '81' OR b = '81'
AND date_x > '2019-05-28';
</code>```

This is what I get:

```<code>1    |  81  | 12 | 2018-03-16
3    |  81  | 67 | 2018-03-16
</code>```

I would expect that 2018-03-16 is not later than 2019-05-28 . Moreover, why only 2 rows returned? There is another with same date in date_x column.

This query return the same:

```<code>SELECT * FROM t
WHERE a = '81' OR b = '81'
AND date_x > str_to_date('2019-05-28', '%Y-$m-%d');
</code>```

I have performed the following query for debug:

```<code>SELECT * FROM t
WHERE a = '81' OR b = '81'
AND date_x < '2019-05-28';
</code>```

and

```<code>SELECT * FROM t
WHERE a = '81' OR b = '81'
AND date_x < str_to_date('2019-05-28', '%Y-$m-%d');
</code>```

then both return, as expected:

```<code>1    |  81  | 12 | 2018-03-16
3    |  81  | 67 | 2018-03-16
4    |  763 | 81 | 2018-03-16
</code>```

I read the following Q/A but I'm still missing something:

MySQL date comparison function

MySQL date comparison issue

MySQL date/author comparison

MySQL Date comparison advice

MySQL date comparison

Any hint? Thank you

答:
Your query has the form

SELECT * FROM t WHERE condition_a OR condition_b AND condition_c

The AND operator binds more strongly than OR, therefore you end up with

SELECT * FROM t WHERE condition_a OR (condition_b AND condition_c)

This is where I think the confusion comes from. Nothing to do with dates as such.

Title: MySQL date comparison query

Body:
I have this table in my database:

table t

id   |  a   | b  | date_x

1    |  81  | 12 | 2018-03-16
2    |  9   | 54 | 2025-04-21
3    |  81  | 67 | 2018-03-16
4    |  763 | 81 | 2018-03-16
5    |  90  | 22 | 2025-12-08

date_x is type DATE

I would like to select the rows where a = 81 or b = 81 and date_x is before 2019-05-28 .

So I perform the following query in MySQL Workbench:

SELECT * FROM t
WHERE a = '81' OR b = '81'
AND date_x > '2019-05-28';

This is what I get:

1    |  81  | 12 | 2018-03-16
3    |  81  | 67 | 2018-03-16

I would expect that 2018-03-16 is not later than 2019-05-28 . Moreover, why only 2 rows returned? There is another with same date in date_x column.

This query return the same:

SELECT * FROM t
WHERE a = '81' OR b = '81'
AND date_x > str_to_date('2019-05-28', '%Y-$m-%d');

I have performed the following query for debug:

SELECT * FROM t
WHERE a = '81' OR b = '81'
AND date_x < '2019-05-28';

and

SELECT * FROM t
WHERE a = '81' OR b = '81'
AND date_x < str_to_date('2019-05-28', '%Y-$m-%d');

then both return, as expected:

1    |  81  | 12 | 2018-03-16
3    |  81  | 67 | 2018-03-16
4    |  763 | 81 | 2018-03-16

I read the following Q/A but I'm still missing something:

MySQL date comparison function

MySQL date comparison issue

MySQL date/author comparison

MySQL Date comparison advice

MySQL date comparison

Any hint? Thank you


答:
You should wrap your select in brackets. Because of it you get WHERE a = '81' OR (b = '81' AND date_x >'2019-05-28').

```<code>SELECT * FROM t
WHERE (a = '81' OR b = '81')
AND date_x > '2019-05-28';
</code>```

Title: MySQL date comparison query

Body:
You should wrap your select in brackets. Because of it you get WHERE a = '81' OR (b = '81' AND date_x >'2019-05-28').

SELECT * FROM t
WHERE (a = '81' OR b = '81')
AND date_x > '2019-05-28';


问:
Search Specific TD in Table
I have code to search the whole of a table, but I want to add a secondary search that will just look at the first column of the table. I'm not sure how best to adapt the code to do this.

$(document).ready(function() {
  $("#myInput").on("keyup", function() {
    var value = $(this).val().toLowerCase();
    $("#glossary-table tr").not('thead tr').filter(function() {
      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
    });
  });
});```

答:
Change your selector to get only the first td of the rows  td:first-child

$(document).ready(function() {
  $("#myInput").on("keyup", function() {

    var value = $(this).val().toLowerCase();
    $("table tr td:first-child").not('thead tr').filter(function() {
      $(this).parent().toggle($(this).text().toLowerCase().indexOf(value) > -1)
    });
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td>1</td>
    <td>2</td>
    <td>7</td>
  </tr>
  <tr>
    <td>4</td>
    <td>5</td>
    <td>7</td>
  </tr>
  <tr>
    <td>7</td>
    <td>4</td>
    <td>9</td>
  </tr>
</table>
<input id="myInput"></code>```

Title: Search Specific TD in Table

Body:
Change your selector to get only the first td of the rows  td:first-child

$(document).ready(function() {
  $("#myInput").on("keyup", function() {

    var value = $(this).val().toLowerCase();
    $("table tr td:first-child").not('thead tr').filter(function() {
      $(this).parent().toggle($(this).text().toLowerCase().indexOf(value) > -1)
    });
  });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td>1</td>
    <td>2</td>
    <td>7</td>
  </tr>
  <tr>
    <td>4</td>
    <td>5</td>
    <td>7</td>
  </tr>
  <tr>
    <td>7</td>
    <td>4</td>
    <td>9</td>
  </tr>
</table>
<input id="myInput">


问:
Overflowing a child element outside the parent element
I have a simple card which contains an image .menu-card__header-image. On hover, I wish to lift that image up by some pixels. However, when I do lift the image, the image is not visible outside the parent container .menu-card.

.menu-card {
  font-family: sans-serif;
  color: red;
  margin-left: auto;
  margin-right: auto;
  width: 80%;
  overflow: hidden;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
  transition: 0.3s;
  border-bottom-left-radius: 5px;
  border-bottom-right-radius: 5px;
  padding-bottom: 20px;
  max-width: 400px;
}
.menu-card:hover {
  box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2);
  overflow: visible;
}
.menu-card__header {
  background-color: orange;
  clip-path: polygon(0 0, 100% 0, 100% calc(100% - 6vw), 0 100%);
  max-height: 300px;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
  overflow: hidden;
  text-align: center;
}
.menu-card__header-image {
  margin-left: auto;
  margin-right: auto;
  z-index: 33;
  position: relative;
  bottom: 0px;
  transition: bottom 0.5s ease-in-out;
}
.menu-card:hover .menu-card__header-image {
  bottom: 80px;
}
.menu-card:first-child {
  margin-bottom: 50px;
}
.menu-card:last-child {
  margin-top: 50px;
}
.menu-card__title {
  padding: 0 12px;
}
.menu-card__description {
  padding: 0 12px;
}

.menu-card__title {
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="menu-card">
  <div class="menu-card__header">
    <img src="http://lorempixel.com/250/635" alt="" class="menu-card__header-image" height="400px" />
  </div>
  <h2 class="menu-card__title">
    Lorem Ipsum
  </h2>
  <p class="menu-card__description">
    Lorem ipsum, dolor sit amet consectetur adipisicing elit. Corrupti, architecto. Repudiandae dolorum incidunt sint ex
  </p>
</div></code>```

Here is the relevant pen:  https://codepen.io/saifalfalah/pen/gJKNBE?editors=1100

How do I make the image be visible outside the parent container on hover without changing the markup (preferably)?

答:
Need to just change two correction on styles.

1, Remove overflow property from ".menu-card__header"

```<code>.menu-card__header { /* overflow: hidden; */}
</code>```

2, Add below property on hover

```<code>&:hover  .menu-card__header {
clip-path: polygon(0 -80px, 100% -80px, 100% calc(100% - 6vw), 0 100%);
</code>```

}

See below jsfiddle example
here

Body:
I have a simple card which contains an image .menu-card__header-image. On hover, I wish to lift that image up by some pixels. However, when I do lift the image, the image is not visible outside the parent container .menu-card.

.menu-card {
  font-family: sans-serif;
  color: red;
  margin-left: auto;
  margin-right: auto;
  width: 80%;
  overflow: hidden;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
  transition: 0.3s;
  border-bottom-left-radius: 5px;
  border-bottom-right-radius: 5px;
  padding-bottom: 20px;
  max-width: 400px;
}
.menu-card:hover {
  box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2);
  overflow: visible;
}
.menu-card__header {
  background-color: orange;
  clip-path: polygon(0 0, 100% 0, 100% calc(100% - 6vw), 0 100%);
  max-height: 300px;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
  overflow: hidden;
  text-align: center;
}
.menu-card__header-image {
  margin-left: auto;
  margin-right: auto;
  z-index: 33;
  position: relative;
  bottom: 0px;
  transition: bottom 0.5s ease-in-out;
}
.menu-card:hover .menu-card__header-image {
  bottom: 80px;
}
.menu-card:first-child {
  margin-bottom: 50px;
}
.menu-card:last-child {
  margin-top: 50px;
}
.menu-card__title {
  padding: 0 12px;
}
.menu-card__description {
  padding: 0 12px;
}

.menu-card__title {
  text-align: center;
}

    Lorem Ipsum

    Lorem ipsum, dolor sit amet consectetur adipisicing elit. Corrupti, architecto. Repudiandae dolorum incidunt sint ex

Here is the relevant pen:  https://codepen.io/saifalfalah/pen/gJKNBE?editors=1100

How do I make the image be visible outside the parent container on hover without changing the markup (preferably)?

Body:
Need to just change two correction on styles.

1, Remove overflow property from ".menu-card__header"

.menu-card__header { /* overflow: hidden; */}

2, Add below property on hover

&:hover  .menu-card__header {
clip-path: polygon(0 -80px, 100% -80px, 100% calc(100% - 6vw), 0 100%);

}

See below jsfiddle example
here


问:
How to connect Kafka consumer with SSL setup with any of Node JS modules
I want to connect external kafka topic provided by vendor; as we are already developed service on top of Node JS.

So I am looking for

NodeJS kafka consumer and with SSL setup;

as the kafka-server needs the details while handshake;

This what I tried with kafkajs module already

```<code>var fs = require('fs');
var Kafka = require('kafkajs').Kafka;
var logLevel = require('kafkajs').logLevel;

var _kafka = new Kafka({
    clientId: 'my-app',
    brokers: ['broker:9093'],
    logLevel: logLevel.DEBUG,
    ssl: {
        rejectUnauthorized: false,
        ca: [fs.readFileSync('./cert/ca.trust.certificate.pem', 'utf-8')],
        cert: fs.readFileSync('./cert/client-cert-signed.pem', 'utf-8'),
    }
});

try {
    const consumer = _kafka.consumer({ groupId: 'test-group' }, { maxWaitTimeInMs: 3000 });

    consumer.connect();
    consumer.subscribe({ topic: 'external-topic', fromBeginning: true });

    consumer.run({
        eachMessage: async({ topic, partition, message }) => {
            console.log({
                partition: 2,
                offset: message.offset,
                value: message.value.toString(),
            })
        },
    })
} catch (err) {
    console.log('Error while connect : ' + err);
}
</code>```

It is giving

Connection error: 101057795:error:1408E0F4:SSL routines:ssl3_get_message:unexpected message:openssl\ssl\s3_both.c:408:\
   while connecting;

Could you please help me with resolution or suggest me any npm module, so that I can give a try examples are so welcome.

答: Forgot to add key attribute in ssl Options; as this one is the mandatory while handshake;

Body:
I want to connect external kafka topic provided by vendor; as we are already developed service on top of Node JS.

So I am looking for

NodeJS kafka consumer and with SSL setup;

as the kafka-server needs the details while handshake;

This what I tried with kafkajs module already

var fs = require('fs');
var Kafka = require('kafkajs').Kafka;
var logLevel = require('kafkajs').logLevel;

var _kafka = new Kafka({
    clientId: 'my-app',
    brokers: ['broker:9093'],
    logLevel: logLevel.DEBUG,
    ssl: {
        rejectUnauthorized: false,
        ca: [fs.readFileSync('./cert/ca.trust.certificate.pem', 'utf-8')],
        cert: fs.readFileSync('./cert/client-cert-signed.pem', 'utf-8'),
    }
});

try {
    const consumer = _kafka.consumer({ groupId: 'test-group' }, { maxWaitTimeInMs: 3000 });

    consumer.connect();
    consumer.subscribe({ topic: 'external-topic', fromBeginning: true });

    consumer.run({
        eachMessage: async({ topic, partition, message }) => {
            console.log({
                partition: 2,
                offset: message.offset,
                value: message.value.toString(),
            })
        },
    })
} catch (err) {
    console.log('Error while connect : ' + err);
}

It is giving

Connection error: 101057795:error:1408E0F4:SSL routines:ssl3_get_message:unexpected message:openssl\ssl\s3_both.c:408:\
   while connecting;

Could you please help me with resolution or suggest me any npm module, so that I can give a try examples are so welcome.


问:
How to remove empty strings from the end of a list of strings (only at the end)
i have some list of strings. I want to remove empty strings from the end of the list (i.e.  each list should end with a non empty element).

```<code>input
list1= ['a1','b1','c1','d1','']
list2 = ['a2','','b2','','c2','d2','']
list3 = ['a3','','b3','','','']
list4 = ['','','','','']
</code>```

output

```<code>list1= ['a1','b1','c1','d1']
list2 = ['a2','','b2','','c2','d2']
list3 = ['a3','','b3']
list4 = ['']
</code>```

if all the elements are empty strings , only one empty string should remain (eg. list4).

答:
You can use recursion</p>

```<code>def remove_empty(l):
    if l[-1] != "" or len(l) <= 1:
        return l
    return remove_empty(l[:-1])

print(remove_empty(list1)) # ['a1', 'b1', 'c1', 'd1']
print(remove_empty(list2)) # ['a2', '', 'b2', '', 'c2', 'd2']
print(remove_empty(list3)) # ['a3', '', 'b3']
print(remove_empty(list4)) # ['']
</code>```

Body:
i have some list of strings. I want to remove empty strings from the end of the list (i.e.  each list should end with a non empty element).

input
list1= ['a1','b1','c1','d1','']
list2 = ['a2','','b2','','c2','d2','']
list3 = ['a3','','b3','','','']
list4 = ['','','','','']

output

list1= ['a1','b1','c1','d1']
list2 = ['a2','','b2','','c2','d2']
list3 = ['a3','','b3']
list4 = ['']

if all the elements are empty strings , only one empty string should remain (eg. list4).

Body:
You can use recursion

def remove_empty(l):
    if l[-1] != "" or len(l) <= 1:
        return l
    return remove_empty(l[:-1])

print(remove_empty(list1)) # ['a1', 'b1', 'c1', 'd1']
print(remove_empty(list2)) # ['a2', '', 'b2', '', 'c2', 'd2']
print(remove_empty(list3)) # ['a3', '', 'b3']
print(remove_empty(list4)) # ['']


问:
Vector option in Java
I am using vector of object. My issue is the removal from vector is expensive operation( O(n^2)). What would be the replacement of vector in Java. In my uses addition and removal is extensively happens.

i am C++ person don't know much Java

答: You can use ArrayList instead of vector in Java.</p>

Title: Vector option in Java


问:
Jquery Span click find next div
I try to toogle div class from a span click i tried

```<code>$(this).closest(".div").find(".list-type-demandes").toggle();
</code>```

but it doesn't work.

if i use :

```<code>$(".list-type-demandes").toggle();
</code>```

it's works but it's showing me the two div and i need to display the div from "this" span

here HTML  :

```<code><label style="color: #1c5081">
        <span id="toolbar-open" name="toolbar_open" class="toogle-toobar-open" onclick="toogleListTypeDemande(this)"><b>+</b>
        </span> Organisation, support et services
      </label>

      <div class="list-type-demandes" style="padding-left: ; display: none">
         <label style="display: inline">
         <input type="radio" class="checkbox_type_demande" data-appel-projet="474" name="appel_projet[type_demande_list]" value="54" id="appel_projet_type_demande_list_54"> Architecture d'entreprise
        </label>
      </div>

      <label style="color: #1c5081">
        <span id="toolbar-open" name="toolbar_open" class="toogle-toobar-open" onclick="toogleListTypeDemande(this)"><b>+</b></span> Applications
      </label>

      <div class="list-type-demandes" style="padding-left: ; display: none">
        <label style="display: inline">
        <input type="radio" class="checkbox_type_demande" data-appel-projet="474" name="appel_projet[type_demande_list]" value="52" id="appel_projet_type_demande_list_52"> Système d'information activités recherche
        </label>
      </div>
</code>```

here the script :

```<code>function toogleListTypeDemande(element) {
        $(this).closest(".div").find(".list-type-demandes").toggle();
    }
</code>```

答:
Use ID unique and check below code,

You can use directly click also

```<code>$('.toogle-toobar-open').click(function(){
  $(this).closest("label").next(".list-type-demandes").toggle();
});
</code>```

label{
  display:block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script>
function toogleListTypeDemande(element) {
    $(element).closest("label").next(".list-type-demandes").toggle();
}
</script>
<label style="color: #1c5081">
        <span id="toolbar-open" name="toolbar_open" class="toogle-toobar-open" onclick="toogleListTypeDemande(this)"><b>+</b>Organisation, support et services
        </span>
      </label>

      <div class="list-type-demandes" style="padding-left: ; display: none">
         <label style="display: inline">
         <input type="radio" class="checkbox_type_demande" data-appel-projet="474" name="appel_projet[type_demande_list]" value="54" id="appel_projet_type_demande_list_54"> Architecture d'entreprise
        </label>
      </div>

      <label style="color: #1c5081">
        <span id="toolbar-open2" name="toolbar_open" class="toogle-toobar-open" onclick="toogleListTypeDemande(this)"><b>+</b> Applications</span>
      </label>

      <div class="list-type-demandes" style="padding-left: ; display: none">
        <label style="display: inline">
        <input type="radio" class="checkbox_type_demande" data-appel-projet="474" name="appel_projet[type_demande_list]" value="52" id="appel_projet_type_demande_list_52"> Système d'information activités recherche
        </label>
      </div></code>```

Title: Jquery Span click find next div

Body:
I try to toogle div class from a span click i tried

$(this).closest(".div").find(".list-type-demandes").toggle();

but it doesn't work.

if i use :

$(".list-type-demandes").toggle();

it's works but it's showing me the two div and i need to display the div from "this" span

here HTML  :

        +
         Organisation, support et services

         <input type="radio" class="checkbox_type_demande" data-appel-projet="474" name="appel_projet[type_demande_list]" value="54" id="appel_projet_type_demande_list_54"> Architecture d'entreprise

        + Applications

        <input type="radio" class="checkbox_type_demande" data-appel-projet="474" name="appel_projet[type_demande_list]" value="52" id="appel_projet_type_demande_list_52"> Système d'information activités recherche

here the script :

function toogleListTypeDemande(element) {
        $(this).closest(".div").find(".list-type-demandes").toggle();
    }

Body:
Use ID unique and check below code,

You can use directly click also

$('.toogle-toobar-open').click(function(){
  $(this).closest("label").next(".list-type-demandes").toggle();
});

label{
  display:block;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script>
function toogleListTypeDemande(element) {
    $(element).closest("label").next(".list-type-demandes").toggle();
}
</script>
<label style="color: #1c5081">
        <span id="toolbar-open" name="toolbar_open" class="toogle-toobar-open" onclick="toogleListTypeDemande(this)"><b>+</b>Organisation, support et services
        </span>
      </label>

      <div class="list-type-demandes" style="padding-left: ; display: none">
         <label style="display: inline">
         <input type="radio" class="checkbox_type_demande" data-appel-projet="474" name="appel_projet[type_demande_list]" value="54" id="appel_projet_type_demande_list_54"> Architecture d'entreprise
        </label>
      </div>

      <label style="color: #1c5081">
        <span id="toolbar-open2" name="toolbar_open" class="toogle-toobar-open" onclick="toogleListTypeDemande(this)"><b>+</b> Applications</span>
      </label>

      <div class="list-type-demandes" style="padding-left: ; display: none">
        <label style="display: inline">
        <input type="radio" class="checkbox_type_demande" data-appel-projet="474" name="appel_projet[type_demande_list]" value="52" id="appel_projet_type_demande_list_52"> Système d'information activités recherche
        </label>
      </div>


问:
DialogFragment focus EditText on dialog open for API 28
I want to focus the first TextInputEditText in layout and automatically  display the soft keyboard when dialog is shown

I'm targeting API level 28.

Layout:

```<code>        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/d_add_edit_name_til"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="@dimen/activity_vertical_margin"
            android:layout_marginTop="@dimen/activity_vertical_margin"
            android:layout_marginEnd="@dimen/activity_vertical_margin"
            android:theme="@style/TextInputLayoutAppearance"
            >
            <com.google.android.material.textfield.TextInputEditText
                android:id="@+id/d_add_edit_name_et"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="User email"
                android:imeOptions="actionDone"
                android:inputType="textCapSentences"
                android:singleLine="true"
                android:focusableInTouchMode="true"
                android:focusable="true"
            >
                <requestFocus />
            </com.google.android.material.textfield.TextInputEditText>
        </com.google.android.material.textfield.TextInputLayout>
</code>```

DialogFragment code:

```<code>@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
    final Dialog dialog = super.onCreateDialog(savedInstanceState);
    dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
    dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    return dialog;
}

....

@Override
public void onResume(){
    super.onResume();

    int dialogWidth = Functions.convertDpToPixel(300,activity);
    int dialogHeight = Functions.convertDpToPixel(250,activity);

    new Handler().post(() -> {
        getDialog().getWindow().setLayout(dialogWidth, dialogHeight);
    });
}
</code>```

The answers from this thread helped me solve the issue for API < 28.

I know from Android 9 changes documentation that:

Additionally, activities no longer implicitly assign initial focus in touch-mode. Instead, it is up to you to explicitly request initial focus, if desired.

One of the ways to explicitly request initial focus (as discussed here) is by adding <requestFocus /> tag inside EditText, but still no success for API level 28 + DialogFragment

*Note that DialogFragment is from andoridx library (androidx.fragment.app.DialogFragment)

Anyone else having this issue?

Edit:
The only way I managed to make this work is by adding the following code to onViewCreated:

```<code>    new Handler().postDelayed(() -> {
        nameEt.requestFocus();
        InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(nameEt, InputMethodManager.SHOW_IMPLICIT);
    },200);
</code>```

I don't consider this to be a valid answer as using threads in this manner makes the code unpredictable. Still waiting for a good answer

答:
```<code>EditText yourEditText= (EditText) findViewById(R.id.yourEditText);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(yourEditText, InputMethodManager.SHOW_IMPLICIT);
</code>```

Body:
I want to focus the first TextInputEditText in layout and automatically  display the soft keyboard when dialog is shown

I'm targeting API level 28.

Layout:

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/d_add_edit_name_til"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="@dimen/activity_vertical_margin"
            android:layout_marginTop="@dimen/activity_vertical_margin"
            android:layout_marginEnd="@dimen/activity_vertical_margin"
            android:theme="@style/TextInputLayoutAppearance"
            >
            <com.google.android.material.textfield.TextInputEditText
                android:id="@+id/d_add_edit_name_et"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="User email"
                android:imeOptions="actionDone"
                android:inputType="textCapSentences"
                android:singleLine="true"
                android:focusableInTouchMode="true"
                android:focusable="true"
            >
                <requestFocus />
            </com.google.android.material.textfield.TextInputEditText>
        </com.google.android.material.textfield.TextInputLayout>

DialogFragment code:

@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
    final Dialog dialog = super.onCreateDialog(savedInstanceState);
    dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
    dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    return dialog;
}

....

@Override
public void onResume(){
    super.onResume();

    int dialogWidth = Functions.convertDpToPixel(300,activity);
    int dialogHeight = Functions.convertDpToPixel(250,activity);

    new Handler().post(() -> {
        getDialog().getWindow().setLayout(dialogWidth, dialogHeight);
    });
}

The answers from this thread helped me solve the issue for API < 28.

I know from Android 9 changes documentation that:

Additionally, activities no longer implicitly assign initial focus in touch-mode. Instead, it is up to you to explicitly request initial focus, if desired.

One of the ways to explicitly request initial focus (as discussed here) is by adding <requestFocus /> tag inside EditText, but still no success for API level 28 + DialogFragment

*Note that DialogFragment is from andoridx library (androidx.fragment.app.DialogFragment)

Anyone else having this issue?

Edit:
The only way I managed to make this work is by adding the following code to onViewCreated:

    new Handler().postDelayed(() -> {
        nameEt.requestFocus();
        InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(nameEt, InputMethodManager.SHOW_IMPLICIT);
    },200);

I don't consider this to be a valid answer as using threads in this manner makes the code unpredictable. Still waiting for a good answer


问:
Sum of all odd fibonacci numbers upto n
I am stuck in summing up to number 10. Can't get it right.
What i am getting is the total sum from 10 digits (after filtering odd only 7). Where should i make <= num ?

function sumFibs(num) {
  var fib = [1, 1];
  for (var i = 2; i < num; i++) {
    var next = fib[i - 1] + fib[i - 2];
    var fibi = fib.push(next);
  }

  return fib.filter(function(a) {
      return (a % 2 != 0);
    })
    .reduce(function(a, z) {
      return a + z;
    })
}
console.log(sumFibs(10));```

Expected output 10, but getting 99

答:
Add a < num to your filter callback test, so you get a % 2 && a < num

function sumFibs(num) {
 var fib = [0, 1];
 for (var i = 2; i < num; i++) {
  var next = fib[i - 1] + fib[i - 2];
  var fibi = fib.push(next);
 }
 return fib.filter(function (a) {
  return a % 2 && a < num;
 }).reduce(function (a, z) {
  return a + z;
 }, 0);
}

console.log(sumFibs(0))
console.log(sumFibs(1))
console.log(sumFibs(10))
console.log(sumFibs(9000))```
</div>
</div>
</p>

<p>You don't need to use array at all if you need only sum of those numbers</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function sumFibs(num) {
  if(num <= 1) return 0;
  var a = 0, b = 1, sum = a + b;
  while(true) {
    var next = a + b;
    if(next >= num) {
      break;
    }
    if(next % 2) {
      sum += next;
    }
    a = b;
    b = next;
  }
  return sum
}
console.log(sumFibs(0))
console.log(sumFibs(1))
console.log(sumFibs(10))
console.log(sumFibs(9000))</code>```

Title: Sum of all odd fibonacci numbers upto n

Body:
I am stuck in summing up to number 10. Can't get it right.
What i am getting is the total sum from 10 digits (after filtering odd only 7). Where should i make <= num ?

function sumFibs(num) {
  var fib = [1, 1];
  for (var i = 2; i < num; i++) {
    var next = fib[i - 1] + fib[i - 2];
    var fibi = fib.push(next);
  }

  return fib.filter(function(a) {
      return (a % 2 != 0);
    })
    .reduce(function(a, z) {
      return a + z;
    })
}
console.log(sumFibs(10));

Expected output 10, but getting 99

Body:
Add a < num to your filter callback test, so you get a % 2 && a < num

function sumFibs(num) {
 var fib = [0, 1];
 for (var i = 2; i < num; i++) {
  var next = fib[i - 1] + fib[i - 2];
  var fibi = fib.push(next);
 }
 return fib.filter(function (a) {
  return a % 2 && a < num;
 }).reduce(function (a, z) {
  return a + z;
 }, 0);
}

console.log(sumFibs(0))
console.log(sumFibs(1))
console.log(sumFibs(10))
console.log(sumFibs(9000))

You don't need to use array at all if you need only sum of those numbers

function sumFibs(num) {
  if(num <= 1) return 0;
  var a = 0, b = 1, sum = a + b;
  while(true) {
    var next = a + b;
    if(next >= num) {
      break;
    }
    if(next % 2) {
      sum += next;
    }
    a = b;
    b = next;
  }
  return sum
}
console.log(sumFibs(0))
console.log(sumFibs(1))
console.log(sumFibs(10))
console.log(sumFibs(9000))


问:
Why won't Flutter mobX store code generate?
I have a mobx store and it's really hit and miss getting my storename.g.dart generated.

The first time, I copied an example from medium and just kept running the generator until eventually it gave code.

The second time, I wrote my own store forgot the abstract keyword. Added it in and it worked.

I thought that was the problem.

Now, third project, I think I have all my code down but it's still not generating. Many actions but no output.

What makes it work or fail? This is my current mobx

```<code>import 'package:mobx/mobx.dart';
import 'package:firebase_auth/firebase_auth.dart';

// have this line
// then generate with
// flutter packages pub run build_runner build
// or
// flutter packages pub run build_runner clean; flutter packages pub run build_runner build --delete-conflicting-outputs

// todo edit this file name
part 'usermodel.g.dart';

class UserModel = UserModelBase with _$UserModel;

abstract class UserModelBase implements Store {
  @observable
  FirebaseUser user;

  @action
  setUser(FirebaseUser u){
    user = u;
  }

  dispose() {}
}
</code>```

答:
I wanted to add an answer in addition to the helpful one @Remi Posted.

When I copied the example, I had copied the entries in pubspec.yaml and it specified mobx 0.1.4 which defined Store as an

abstract class Store {}

However, when I did my third project, I added mobx: without the version and it became 0.2.0 which defined Store as a

```<code>mixin Store {
  void dispose() {}
}
</code>```

Which then required the change of keyword implements to with. Thanks for figuring that out!

Body:
I have a mobx store and it's really hit and miss getting my storename.g.dart generated.

The first time, I copied an example from medium and just kept running the generator until eventually it gave code.

The second time, I wrote my own store forgot the abstract keyword. Added it in and it worked.

I thought that was the problem.

Now, third project, I think I have all my code down but it's still not generating. Many actions but no output.

What makes it work or fail? This is my current mobx

import 'package:mobx/mobx.dart';
import 'package:firebase_auth/firebase_auth.dart';

// have this line
// then generate with
// flutter packages pub run build_runner build
// or
// flutter packages pub run build_runner clean; flutter packages pub run build_runner build --delete-conflicting-outputs

// todo edit this file name
part 'usermodel.g.dart';

class UserModel = UserModelBase with _$UserModel;

abstract class UserModelBase implements Store {
  @observable
  FirebaseUser user;

  @action
  setUser(FirebaseUser u){
    user = u;
  }

  dispose() {}
}

Body:
I wanted to add an answer in addition to the helpful one @Remi Posted.

When I copied the example, I had copied the entries in pubspec.yaml and it specified mobx 0.1.4 which defined Store as an

abstract class Store {}

However, when I did my third project, I added mobx: without the version and it became 0.2.0 which defined Store as a

mixin Store {
  void dispose() {}
}

Which then required the change of keyword implements to with. Thanks for figuring that out!


问:
How navbar-toggle, collapse, navbar-collapse classes work together?
I am new to the world of CSS and Bootstrap 3.0.  Below is code which I can find at many places and now I can write it without any problem.  But I really don't know how things are working behind the scenes.

```<code><div class="navbar navbar-static-top navbar-inverse" role="navigation">
        <a class="navbar-brand">Company</a>
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".top-nav">
                <span class="sr-only">Toggle Navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
        </div>
        <div class="collapse navbar-collapse top-nav">
            <ul class="nav navbar-nav">
                <li class="active"><a href="#">Home</a></li>
                <li><a href="#">News</a></li>
                <li><a href="#">About Us</a></li>
                <li><a href="#">Contact</a></li>
            </ul>
        </div>
    </div>
</code>```

Above code will provide me a dynamic UI. Can someone answer my below queries

How connection is established between button and navbar. Ans: In
this case I know class named 'top-nave' connect these two
components. But then what is significance of other classes (
collapse navbar-collapse ). I have learned that we need to have both
the classes i.e. collapse and navbar-collapse.  Dont know why?

Is all magic done by CSS or we do have some javascript code that is
manipulating code? ( I guess yes since there exists data- attribute)

Can anyone suggest other usage of data-toggle and data-target
attribute in bootstrap 3 to understand concept clearly?

Regards,
Hemant

答:
This is far, far easier to fix now in Bootstrap 4.x. Just tweak the navbar class in your html like...

```<code>    <nav class="navbar navbar-expand-sm navbar-dark bg-dark">
</code>```

Mess with the navbar-expand-sm: Change ending -xs, -sm, -md, -lg, -xl, until the navbar collapses where you want it to. Took me a while on this so I thought I'd share :-)

Body:
I am new to the world of CSS and Bootstrap 3.0.  Below is code which I can find at many places and now I can write it without any problem.  But I really don't know how things are working behind the scenes.

        Company

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".top-nav">
                Toggle Navigation

            </button>

Home

News

About Us

Contact

Above code will provide me a dynamic UI. Can someone answer my below queries

How connection is established between button and navbar. Ans: In
this case I know class named 'top-nave' connect these two
components. But then what is significance of other classes (
collapse navbar-collapse ). I have learned that we need to have both
the classes i.e. collapse and navbar-collapse.  Dont know why?

Is all magic done by CSS or we do have some javascript code that is
manipulating code? ( I guess yes since there exists data- attribute)

Can anyone suggest other usage of data-toggle and data-target
attribute in bootstrap 3 to understand concept clearly?

Regards,
Hemant

Body:
This is far, far easier to fix now in Bootstrap 4.x. Just tweak the navbar class in your html like...

    <nav class="navbar navbar-expand-sm navbar-dark bg-dark">

Mess with the navbar-expand-sm: Change ending -xs, -sm, -md, -lg, -xl, until the navbar collapses where you want it to. Took me a while on this so I thought I'd share :-)


问:
Format Date() for express-handlebars
I want to display the date in the format "YYYY MM DD".

I have tried with expresss-handlebars code, {{this.createdAt.toDateString()}}

DB/Post.js

```<code>username: String,
    createdAt: {
        type: Date,
        default: new Date()
    }
</code>```

index.js

```<code>app.get('/', async (req, res)=>{
    const posts = await Post.find().sort({"createdAt": -1})
    res.render('index', {
        posts
    });
})
</code>```

post.handlebars

```<code>{{this.createdAt.toDateString()}}
</code>```

答:
Use:

```<code>{{this.createdAt.toLocaleDateString('EU'))}};
</code>```

this will return YYYY-MM-DD, if you want to drop the - add split and join:

{{this.createdAt.toLocaleDateString('EU')).split('-').join(' ')}};

Title: Format Date() for express-handlebars

Body:
I want to display the date in the format "YYYY MM DD".

I have tried with expresss-handlebars code, {{this.createdAt.toDateString()}}

DB/Post.js

username: String,
    createdAt: {
        type: Date,
        default: new Date()
    }

index.js

app.get('/', async (req, res)=>{
    const posts = await Post.find().sort({"createdAt": -1})
    res.render('index', {
        posts
    });
})

post.handlebars

{{this.createdAt.toDateString()}}

Body:
Use:

{{this.createdAt.toLocaleDateString('EU'))}};

this will return YYYY-MM-DD, if you want to drop the - add split and join:

{{this.createdAt.toLocaleDateString('EU')).split('-').join(' ')}};


问:
Tweenmax Scale with ThreeJS Mesh
Trying to incorporate a scale translation to my mesh[0] using TweenMax. I'm not having any problems with certain animations, such as rotation, or even scaling when I use 'mesh[0].set.scale' as the first argument. However, in this situation I'm getting 'Uncaught TypeError: Cannot assign to read only property 'scale' of object '#'' errors from the console.

I'm guessing that this is to do with the combination of using GSAP and ThreeJS, because I've tried out the same code in plain javascript and it works OK.

I've tried to include minimal code, so please let me know if more is needed!

```<code>const geometry = new THREE.IcosahedronBufferGeometry( 1, 0 );
materialRed = new THREE.MeshStandardMaterial({
  color: 0xFF0000
});

mesh[0] = new THREE.Mesh( geometry, materialRed );

scene.add(mesh[0]);

TweenMax.to(mesh[0], 1,
{
  scale: 2,
  ease: Elastic.easeOut,
  yoyo: true,
  repeat: -1,
  yoyoEase: Bounce.easeOut,
  delay: 1,
}
);
</code>```

答:
Repeat method call has been updated:

https://greensock.com/docs/TimelineMax/repeat()

```<code>   var t = Math.random() * 0.6 + 0.3;

  TweenMax.to( box.scale, t, {
                    x: 1 + Math.random() * 3,
                    y: 1 + Math.random() * 20,
                    z: 1 + Math.random() * 3,
                    ease: Power2.easeInOut
                } ).repeat(-1);
</code>```

Demo:

https://codepen.io/MAKIO135/pen/vmBzMv?editors=0010

Title: Tweenmax Scale with ThreeJS Mesh

Body:
Trying to incorporate a scale translation to my mesh[0] using TweenMax. I'm not having any problems with certain animations, such as rotation, or even scaling when I use 'mesh[0].set.scale' as the first argument. However, in this situation I'm getting 'Uncaught TypeError: Cannot assign to read only property 'scale' of object '#'' errors from the console.

I'm guessing that this is to do with the combination of using GSAP and ThreeJS, because I've tried out the same code in plain javascript and it works OK.

I've tried to include minimal code, so please let me know if more is needed!

const geometry = new THREE.IcosahedronBufferGeometry( 1, 0 );
materialRed = new THREE.MeshStandardMaterial({
  color: 0xFF0000
});

mesh[0] = new THREE.Mesh( geometry, materialRed );

scene.add(mesh[0]);

TweenMax.to(mesh[0], 1,
{
  scale: 2,
  ease: Elastic.easeOut,
  yoyo: true,
  repeat: -1,
  yoyoEase: Bounce.easeOut,
  delay: 1,
}
);

Body:
Repeat method call has been updated:

https://greensock.com/docs/TimelineMax/repeat()

   var t = Math.random() * 0.6 + 0.3;

  TweenMax.to( box.scale, t, {
                    x: 1 + Math.random() * 3,
                    y: 1 + Math.random() * 20,
                    z: 1 + Math.random() * 3,
                    ease: Power2.easeInOut
                } ).repeat(-1);

Demo:

https://codepen.io/MAKIO135/pen/vmBzMv?editors=0010


问:
Migrating Angular JS 1.6.10 to 1.7.8
I need to migrate my AngularJS version from 1.6.10 to 1.7.8. I would like to know will there be any code breakage after migration?

If anyone could provide the list of differences between 1.6.x and 1.7.x would be much more helpful.

答:
Migrating from (AngularJS) 1.6 to 1.7 contains the information you're looking for. The most notable changes are:

$resource has now support for request and requestError interceptors

Several deprecated features have been removed:

the $controllerProvider.allowGlobals() flag

the $compileProvider.preAssignBindingsEnabled() flag

the angular.lowercase and angular.uppercase methods

the $cookieStore service from the ngCookies module

the ngClick override directive and corresponding services from the ngTouch module

the complete ngScenario module

In the linked resource there is also the full list of breaking changes.

The link for the specific version 1.7.8 is: https://code.angularjs.org/1.7.8/docs/guide/migration

Title: Migrating Angular JS 1.6.10 to 1.7.8


问:
My API request code produces a bug I can't debug or understand
I am not sure where to identify the problem in this code

```<code>var events = [Events]()

    let URL_GET_DATA = "http://192.168.100.4/PrototypeWebService/api/getevents.php"

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        Alamofire.request(URL_GET_DATA).responseJSON{ response in
            if let json = response.result.value {
                print(json)
                let swiftvar = JSON(json).array
                for i in 0..<(swiftvar?.count)! {
                    let jsonObject = swiftvar?[i].object
                    self.events.append(jsonObject as! Events)
                }
                self.EventTable.reloadData()
            }
        }
    }
</code>```

I expect it to create an array of objects of type Events but it produces this error :

Thread 1: EXC_BREAKPOINT (code=1, subcode=0x102ca0f4c

答:
First of all you are encouraged to drop SwiftyJSON in favor of Codable.

The error occurs because a (Swifty)JSON object cannot be cast to a custom struct or class.

You have to pass the JSON value to an initializer of the custom struct.

```<code>struct Event { // it's highly recommended to name this kind of object in singular form
   let varA : String
   let varB : Int

   init(json: JSON) {
      self.varA = json["varA"].string ?? ""
      self.varB = json["varB"].int ?? 0
   }
}
</code>```

And please never use index based loops if you actually don't need the index at all. Create an Event instance from the JSON object and append it

```<code>guard let swiftvar = JSON(json).array else { return }
for item in swiftvar {
     let event = Event(json: item)
     self.events.append(event)
}
</code>```

or even simpler

```<code>guard let swiftvar = JSON(json).array else { return }
self.events = swiftvar.map{ Event(json: $0) }
</code>```

Body:
I am not sure where to identify the problem in this code

var events = [Events]()

    let URL_GET_DATA = "http://192.168.100.4/PrototypeWebService/api/getevents.php"

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        Alamofire.request(URL_GET_DATA).responseJSON{ response in
            if let json = response.result.value {
                print(json)
                let swiftvar = JSON(json).array
                for i in 0..<(swiftvar?.count)! {
                    let jsonObject = swiftvar?[i].object
                    self.events.append(jsonObject as! Events)
                }
                self.EventTable.reloadData()
            }
        }
    }

I expect it to create an array of objects of type Events but it produces this error :

Thread 1: EXC_BREAKPOINT (code=1, subcode=0x102ca0f4c

Body:
First of all you are encouraged to drop SwiftyJSON in favor of Codable.

The error occurs because a (Swifty)JSON object cannot be cast to a custom struct or class.

You have to pass the JSON value to an initializer of the custom struct.

struct Event { // it's highly recommended to name this kind of object in singular form
   let varA : String
   let varB : Int

   init(json: JSON) {
      self.varA = json["varA"].string ?? ""
      self.varB = json["varB"].int ?? 0
   }
}

And please never use index based loops if you actually don't need the index at all. Create an Event instance from the JSON object and append it

guard let swiftvar = JSON(json).array else { return }
for item in swiftvar {
     let event = Event(json: item)
     self.events.append(event)
}

or even simpler

guard let swiftvar = JSON(json).array else { return }
self.events = swiftvar.map{ Event(json: $0) }


问:
how can i change the checkbox attribute which are in the 9th column of a table
How to modify the checkbox attribute (checkbok in the 9th cells of the table MyTab) ?

MyTab contains 9 columns and the last is a checkbox.

None of the following code is working.

```<code>$('#MyTab tr').filter(':visible').each(function( index,element) {

     element.cells[8].attr('checked', true);

     $(this).attr('checked',true);

     $(this).prop('checked',true);

     $(element "input[type='checkbox']").attr('checked',true) ;

     element.cells[8].attr('checked', true);

     element.cells[8].prop('checked', true);

 });

HTML part = exemple with one row =
<table id="MyTab"  border=0 width=1400 cellspacing=2 cellpadding=2 class="table" >
<tr class='impair' onMouseOver="this.className='ModuleCorpsColorOver';" onMouseOut="this.className='impair';">
   <td>USER</td>
   <td>964469597</td>
   <td>17231215</td>
   <td>450,60</td>
   <td>22-11-18</td>
   <td>08-10-18</td>
   <td>DOCUMENT1</td>
   <td>LIBELLE1</td>
   <td><input type='checkbox' class='inputNoBord' name='upd_statut[]' value='1' enable></td>
</tr>

<tr>
    ....
</tr>
</table>

I am also using following jquery =
<script src="../lib/jquery-1.11.1.min.js"></script>
<script src="../lib/sorttable.js"></script>
<script src="../lib/jquery.filtertable.min.js"></script>
</code>```

答:
You can either add a class to the columns and directly access that element by class.

JQuery provides multiple ways to access any element in the DOM. I think the following should work for you.

```<code>$('tr.t-detail-row').find('td.t-detail-cell').prop("checked", true);
</code>```

Body:
How to modify the checkbox attribute (checkbok in the 9th cells of the table MyTab) ?

MyTab contains 9 columns and the last is a checkbox.

None of the following code is working.

$('#MyTab tr').filter(':visible').each(function( index,element) {

     element.cells[8].attr('checked', true);

     $(this).attr('checked',true);

     $(this).prop('checked',true);

     $(element "input[type='checkbox']").attr('checked',true) ;

     element.cells[8].attr('checked', true);

     element.cells[8].prop('checked', true);

 });

HTML part = exemple with one row =

   USER
   964469597
   17231215
   450,60
   22-11-18
   08-10-18
   DOCUMENT1
   LIBELLE1
   <input type='checkbox' class='inputNoBord' name='upd_statut[]' value='1' enable>

    ....

I am also using following jquery =

Body:
You can either add a class to the columns and directly access that element by class.

JQuery provides multiple ways to access any element in the DOM. I think the following should work for you.

$('tr.t-detail-row').find('td.t-detail-cell').prop("checked", true);


问:
MongoDb : Storing aggregates and domain events atomically
I'm using DDD and MongoDb for the underlying storage.
I'm not using event sourcing. I need to persist the aggregate's state and domain events it's publishing in the same transaction, before publishing those events elsewhere - for resilience reasons.

Mongo allows transactions but only in replica sets configuration.
How can I achieve the same level of resilience without mongo transactions?

答:
As far as I can tell, the usual answer is that you store the domain events in the same document that stores the aggregate state (a single representation that includes all of the information you need for both).

See Data on the Outside vs Data on the Inside, by Pat Helland.


问:
How can I convert Int32 to Int in Swift?
It should be easy but I can only find the reverse conversion.
How can I convert Int32 to Int in Swift?
Unless the problem is different?

I have a value stored in Core Data and I want to return it as an Int.

Here is the code I am using, which does not work:

```<code>func myNumber () -> Int {
    var myUnit:NSManagedObject
    myUnit=self.getObject(“EntityName”) // This is working.

    return Int(myUnit.valueForKey(“theNUMBER”)?.intValue!)
 }
</code>```

答:
Sometimes "?" make things twisted ,
adding "!" to Int32 and then convert it to int works</p>

```<code>let number1 = someInt32!
let number2 = Int(number1)
</code>```

Body:
It should be easy but I can only find the reverse conversion.
How can I convert Int32 to Int in Swift?
Unless the problem is different?

I have a value stored in Core Data and I want to return it as an Int.

Here is the code I am using, which does not work:

func myNumber () -> Int {
    var myUnit:NSManagedObject
    myUnit=self.getObject(“EntityName”) // This is working.

    return Int(myUnit.valueForKey(“theNUMBER”)?.intValue!)
 }

Body:
Sometimes "?" make things twisted ,
adding "!" to Int32 and then convert it to int works

let number1 = someInt32!
let number2 = Int(number1)


问:
How do I set the default browser as chrome in Visual Studio Code?
I am setting up my VS Code environment for the first time, but I can't figure out how to set Chrome as the default browser for the workspace.</p>

答:
This Alternate Way helped me:)

```<code>GoTo-->Google Chrome-->Settings-->Default browser-->Set Google Chrome as default browser
</code>```

Body:
This Alternate Way helped me:)

GoTo-->Google Chrome-->Settings-->Default browser-->Set Google Chrome as default browser


问:
ObjectionJS - Group models in a data layer file
I have a NodeJS app running fastify with fastify-objectionjs.

For tidiness, I'd like to group all models in a single file called _main.js, where I export an array of the models inside the models folder.

Since the fastify-objectionjs registration requires an array of models, I thought I could just import the array from my _main.js and feed it as it is to the registration function.

But ObjectionJS is telling me that The supplied models are invalid.

/app.js (node entry point)

const fastify = require('fastify')({
    logger: true
})

const knexConfig = require('./knexfile')
const dataLayer = require('./models/_main')
fastify.register(require('fastify-objectionjs'), {
    knexConfig: knexConfig,
    models: dataLayer
})

// Also tried:
// fastify.register(require('fastify-objectionjs'), {
//     knexConfig: knexConfig,
//     models: [dataLayer]
// })

```

<p><strong>/models/_main.js</strong></p>

<pre class="lang-js prettyprint-override"><code>const User = require('./user.model')

var dataLayer = [User]

module.exports = dataLayer

// Also tried without var:
// module.exports = {
//     dataLayer: [
//         User
//     ]
// }
</code>```

/models/user.model.js

const Knex = require('knex')
const connection = require('../knexfile')
const { Model } = require('objection')
const knexConnection = Knex(connection)
Model.knex(knexConnection)

class User extends Model {
  static get tableName () {
    return 'users'
  }
}

module.exports = { User }

```

<p>I can't seem to find a problem in the file flow, but if I create the models array on the fly, the app starts smoothly:</p>

<p><strong>/app.js</strong> (node entry point)</p>

<pre class="lang-js prettyprint-override"><code>const fastify = require('fastify')({
    logger: true
})

const knexConfig = require('./knexfile')
const User = require('./models/user.model') // changed
fastify.register(require('fastify-objectionjs'), {
    knexConfig: knexConfig,
    models: [User] // changed
})
</code>```

Any idea why this isn't working?
Thanks in advance for your time.

答:
Found the gotcha, I just needed to use destructuring in the require of User, like this:

/models/_main.js

// BAD
// const User = require('./user.model')

// GOOD
const { User } = require('./user.model')

module.exports = [User]
```

Works like a charm.

Useful question that explains the difference:
Curly brackets (braces) in node require statement

Body:
I have a NodeJS app running fastify with fastify-objectionjs.

For tidiness, I'd like to group all models in a single file called _main.js, where I export an array of the models inside the models folder.

Since the fastify-objectionjs registration requires an array of models, I thought I could just import the array from my _main.js and feed it as it is to the registration function.

But ObjectionJS is telling me that The supplied models are invalid.

/app.js (node entry point)

const fastify = require('fastify')({
    logger: true
})

const knexConfig = require('./knexfile')
const dataLayer = require('./models/_main')
fastify.register(require('fastify-objectionjs'), {
    knexConfig: knexConfig,
    models: dataLayer
})

// Also tried:
// fastify.register(require('fastify-objectionjs'), {
//     knexConfig: knexConfig,
//     models: [dataLayer]
// })

/models/_main.js

const User = require('./user.model')

var dataLayer = [User]

module.exports = dataLayer

// Also tried without var:
// module.exports = {
//     dataLayer: [
//         User
//     ]
// }

/models/user.model.js

const Knex = require('knex')
const connection = require('../knexfile')
const { Model } = require('objection')
const knexConnection = Knex(connection)
Model.knex(knexConnection)

class User extends Model {
  static get tableName () {
    return 'users'
  }
}

module.exports = { User }

I can't seem to find a problem in the file flow, but if I create the models array on the fly, the app starts smoothly:

/app.js (node entry point)

const fastify = require('fastify')({
    logger: true
})

const knexConfig = require('./knexfile')
const User = require('./models/user.model') // changed
fastify.register(require('fastify-objectionjs'), {
    knexConfig: knexConfig,
    models: [User] // changed
})

Any idea why this isn't working?
Thanks in advance for your time.

Body:
Found the gotcha, I just needed to use destructuring in the require of User, like this:

/models/_main.js

// BAD
// const User = require('./user.model')

// GOOD
const { User } = require('./user.model')

module.exports = [User]

Works like a charm.

Useful question that explains the difference:
Curly brackets (braces) in node require statement