问:
How do I map nested class into single database table using hibernate?
I only have table name called Employee, that table has all address attributes and I want to map using hibernate employee table and inner class of address attributes.

```<code><property name="clientMark" column="CLIENT_MARK"/>
<property name="Address.street1" column="B_STREET_ADDRESS_1"/>
<property name="Address.street2" column="B_STREET_ADDRESS_2"/>
<property name="Address.city" column="B_CITY"/>
<property name="Address.state" column="B_STATE"/>
<property name="Address.postalCode" column="B_POSTAL_CODE"/>
<property name="Address.country" column="B_COUNTRY"/>
</code>```

答:
If I understand you correctly, you have to do something like this:

```<code>public class Employee {
    private String clientMark;
    private Address address;

    public String getClientMark() {
        return clientMark;
    }

    public void setClientMark(String clientMark) {
        this.clientMark = clientMark;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public static class Address {
        private String street1;
        private String street2;

        public String getStreet1() {
            return street1;
        }

        public void setStreet1(String street1) {
            this.street1 = street1;
        }

        public String getStreet2() {
            return street2;
        }

        public void setStreet2(String street2) {
            this.street2 = street2;
        }
    }
}
</code>```

Make inner class public and static that you would be able to create new object from other classes. Then add setter and getter method for inner class in outer class that the hibernate will be able to set and get the object. Next you need to edit your .hbm.xml file:

```<code>    <property name="clientMark" column="CLIENT_MARK"/>
    <component name="address">
        <property name="street1" column="B_STREET_ADDRESS_1"/>
    </component>
    <component name="address">
        <property name="street2" column="B_STREET_ADDRESS_2"/>
    </component>
</code>```

Hibernate annotation <component> says that the named variable will be class which has some variables (<property> in hbm.xml file). After this you can test your code like this:

```<code>    Employee entity = new Employee();
    entity.setClientMark("client_mark");
    Employee.Address address = new Employee.Address();
    address.setStreet1("street1");
    address.setStreet2("street2");
    entity.setAddress(address);
    // entity is ready to be saved
</code>```

And your result in your database will be:

```<code>|------------------------------------------------------------|
| id | CLIENT_MARK | B_STREET_ADDRESS_1 | B_STREET_ADDRESS_2 |
|------------------------------------------------------------|
| 1  | client_mark | street1            | street2            |
|------------------------------------------------------------|
</code>```

I hope it helps you... ☺

Body:
I only have table name called Employee, that table has all address attributes and I want to map using hibernate employee table and inner class of address attributes.

<property name="clientMark" column="CLIENT_MARK"/>
<property name="Address.street1" column="B_STREET_ADDRESS_1"/>
<property name="Address.street2" column="B_STREET_ADDRESS_2"/>
<property name="Address.city" column="B_CITY"/>
<property name="Address.state" column="B_STATE"/>
<property name="Address.postalCode" column="B_POSTAL_CODE"/>
<property name="Address.country" column="B_COUNTRY"/>

Body:
If I understand you correctly, you have to do something like this:

public class Employee {
    private String clientMark;
    private Address address;

    public String getClientMark() {
        return clientMark;
    }

    public void setClientMark(String clientMark) {
        this.clientMark = clientMark;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public static class Address {
        private String street1;
        private String street2;

        public String getStreet1() {
            return street1;
        }

        public void setStreet1(String street1) {
            this.street1 = street1;
        }

        public String getStreet2() {
            return street2;
        }

        public void setStreet2(String street2) {
            this.street2 = street2;
        }
    }
}

Make inner class public and static that you would be able to create new object from other classes. Then add setter and getter method for inner class in outer class that the hibernate will be able to set and get the object. Next you need to edit your .hbm.xml file:

    <property name="clientMark" column="CLIENT_MARK"/>
    <component name="address">
        <property name="street1" column="B_STREET_ADDRESS_1"/>
    </component>
    <component name="address">
        <property name="street2" column="B_STREET_ADDRESS_2"/>
    </component>

Hibernate annotation <component> says that the named variable will be class which has some variables (<property> in hbm.xml file). After this you can test your code like this:

    Employee entity = new Employee();
    entity.setClientMark("client_mark");
    Employee.Address address = new Employee.Address();
    address.setStreet1("street1");
    address.setStreet2("street2");
    entity.setAddress(address);
    // entity is ready to be saved

And your result in your database will be:

|------------------------------------------------------------|
| id | CLIENT_MARK | B_STREET_ADDRESS_1 | B_STREET_ADDRESS_2 |
|------------------------------------------------------------|
| 1  | client_mark | street1            | street2            |
|------------------------------------------------------------|

I hope it helps you... ☺


来源: stackexchange

问:
Error in <servlet-mapping> <url-pattern> in web.xml in Eclipse Helios for Java EE developers
I am providing an attribute() in  in web.xml which is

```<code><servlet-mapping>
    <servlet-name>SpringMVCTutorial</servlet-name>
    <url-pattern>*.htm</url-pattern>
</servlet-mapping>
</code>```

but I am getting an error "The word 'htm' is not correctly spelled". Please let me know if I am making a mistake.

Thank you,
Sid

答: That is probably a warning. Ignore it.</p>

ContentLicense: CC BY-SA 2.5

Body:
I am providing an attribute() in  in web.xml which is

<servlet-mapping>
    <servlet-name>SpringMVCTutorial</servlet-name>
    <url-pattern>*.htm</url-pattern>
</servlet-mapping>

but I am getting an error "The word 'htm' is not correctly spelled". Please let me know if I am making a mistake.

Thank you,
Sid

Body: That is probably a warning. Ignore it.


问:
Rails join table in Trestle/Admin
I'm rewriting an old PHP application in Rails 5.1 and migrating the database, too.

I have the two tables with data:

```<code>table: jobs
id   library
-------------
20   foo-20
200  bar-200

table: manuscripts
id    job_id  shelfmark
-----------------------
743   200     MS0403
</code>```

What I'm trying to achieve is to display:

```<code>library    shelfmark
---------------------
bar-200        MS0403
</code>```

But I'm getting foo-20 instead of bar-200 for library:

```<code>library    shelfmark
--------------------
foo-20     MS0403
</code>```

The foreign key job_id seems to be wrongly referenced.

and the models:

```<code>class Job < ApplicationRecord
  has_one :manuscripts
end

class Manuscript < ApplicationRecord
  has_one :job
  belongs_to :job
end
</code>```

In TrestleAdmin app/admin/manuscripts_admin.rb

```<code>Trestle.resource(:manuscripts) do

  table do
    column :library, ->(ob) { ob.job.library }
    column :shelfmark
  end
end
</code>```

How can I correct that?

答:
Short Answer

You should be using a belongs_to relationship on the Manuscript table and remove the has_one relationship:

```<code>class Manuscript < ApplicationRecord
  belongs_to :job
end
</code>```

Explanation

The belongs_to association tells Rails to look for the foreign key in the current model's table.  In your case belongs_to :job tells Rails to look for a job_id in the manuscripts table.  This is the table schema you are using, and is therefore the correct association.

Conversely, the has_one association tells Rails to look for the foreign key in the associated (other) table.  In this case has_one :job tells Rails to look for a manuscript_id in the jobs table.  Based on the schema you provided, this in incorrect.

You can read more about this in the Ruby on Rails Associations Guide.

Caveat

Based on the error you are experiencing, you may also have corrupt data in your database.  You will need to fix any corrupt data to make this work. But, removing the has_one may solve your problem.

ContentLicense: CC BY-SA 3.0

Title: Rails join table in Trestle/Admin

Body:
I'm rewriting an old PHP application in Rails 5.1 and migrating the database, too.

I have the two tables with data:

table: jobs
id   library
-------------
20   foo-20
200  bar-200

table: manuscripts
id    job_id  shelfmark
-----------------------
743   200     MS0403

What I'm trying to achieve is to display:

library    shelfmark
---------------------
bar-200        MS0403

But I'm getting foo-20 instead of bar-200 for library:

library    shelfmark
--------------------
foo-20     MS0403

The foreign key job_id seems to be wrongly referenced.

and the models:

class Job < ApplicationRecord
  has_one :manuscripts
end

class Manuscript < ApplicationRecord
  has_one :job
  belongs_to :job
end

In TrestleAdmin app/admin/manuscripts_admin.rb

Trestle.resource(:manuscripts) do

  table do
    column :library, ->(ob) { ob.job.library }
    column :shelfmark
  end
end

How can I correct that?

Body:
Short Answer

You should be using a belongs_to relationship on the Manuscript table and remove the has_one relationship:

class Manuscript < ApplicationRecord
  belongs_to :job
end

Explanation

The belongs_to association tells Rails to look for the foreign key in the current model's table.  In your case belongs_to :job tells Rails to look for a job_id in the manuscripts table.  This is the table schema you are using, and is therefore the correct association.

Conversely, the has_one association tells Rails to look for the foreign key in the associated (other) table.  In this case has_one :job tells Rails to look for a manuscript_id in the jobs table.  Based on the schema you provided, this in incorrect.

You can read more about this in the Ruby on Rails Associations Guide.

Caveat

Based on the error you are experiencing, you may also have corrupt data in your database.  You will need to fix any corrupt data to make this work. But, removing the has_one may solve your problem.


问:
Insert a datetime value with SSIS to an datetime column in a table on a IBM AS/400 library/system
I have the following problem.

I want make a SSIS flow that inserts values from a table in a MS SQL server database to a table in a AS/400 library.

This works for all the values but the datetime2 value. I tried to insert a datetime2 value and a varchar value in the datetime2 format. Both ways did not work.

It gives the following error:

[TABLENAME [11566]] Error: SSIS Error Code DTS_E_OLEDBERROR.  An OLE DB error has occurred. Error code: 0x80040E21.
  An OLE DB record is available.  Source: "IBMDA400 Command"  Hresult: 0x80004005  Description: "CWBZZ5014 Value of parameter COLUMNNAME could not be converted to the host data type.".
  An OLE DB record is available.  Source: "IBMDA400 Command"  Hresult: 0x80004005  Description: "CWBZZ5014 Value of parameter COLUMNNAME could not be converted to the host data type.".

[TABLENAME [11566]] Error: There was an error with input column "COLUMNAME" (12245) on input "OLE DB Destination Input" (11579). The column status returned was: "The value could not be converted because of a potential loss of data.".

Does someone knows how to get this done?

答:
I assume conversion in sql scripting could be better way of mapping destination column in IBM , try this.

CONVERT(TIMESTAMP, @DateTimeVariable ) or

use derived column expression and there by use data conversion.

I would like to try db_timestamp

Data Conversion


问:
How do you get a part of webpage from remote by using php?
Id like to get a part of webpage.
Let me show you what id like to do.

For example, http:// www.xxxxxx.com/page=2

As you can see there is a list, and this list shows 50 ads. Please ignore other ones. Every ads have an unique id in their links.

for example:

http:// xxx.com/-iid-155546130

the id number is : 155546130

Okay, id like to get unique id numbers from that page, and echo them to the screen. So, i need to get 50 unique ids from that page. Only id numbers.

well, could you please kindly give me some advice? which functions should i use? how can i do that job?

Regards.

答: You will have to get the HTML and parse it for those IDs. In that case you will have to know exactly where those IDs exist. You can use regular expressions to find links to other pages(websites) and then look for IDs.</p>


问:
Change select width to fit div container
I have defined a dropdwon as fellow:

```<code>    <div class="form-group">
        <select class="form-control">
            <option>small option</option>
            <option>mediummmmmmmmmmmmmmmmmmmm option</option>
            <option>large eeeeeeeeeeeeeeeeeeeeee eeeeeeeeeeeeeee eeeeeeeeeeeee eeee option</option>
        </select>
    </div>
</code>```

I want to change select width to be minimum of container width and option text width. If option text is bigger than div container, truncate  option's text and put ellipsis at the end. So the option stays inside the container. Also select must be responsive, When resizing window, select width should be updated to fit new window width.

How can I achieve that using bootstrap CSS?

答:
I took this answer from this stackoverflow answer

.dropdown{
 width:150px;
 border: 1px solid #cfcfcf;
 height: auto;
 border-radius: 5px;
 padding:3px 4px 4px;
 position: relative;
 z-index: 0;
 overflow:hidden;
 }

.dropdown select{
 border: none;
 background-color: transparent;
 outline: none;
 padding: 0;
 width:150px;
    /* background: url(http://i57.tinypic.com/nnmgpy_th.png) no-repeat right; */
    /* background-position: 55%; */
 }

/* not 100% sure this next option rule is needed */
.dropdown option {
    width:150px
}

/* this places an arbitrary element inside the dropdown but before it's children elements */
/* We use it to cover half the select box as well as display the custom arrow */```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="dropdown">
    <select>
       <option value="">Some Text</option>
        <option value="">Some More Text2</option>
        <option value="">Some More More More Longer Text</option>
    </select>

    </div></code>```

Body:
I have defined a dropdwon as fellow:

        <select class="form-control">
            <option>small option</option>
            <option>mediummmmmmmmmmmmmmmmmmmm option</option>
            <option>large eeeeeeeeeeeeeeeeeeeeee eeeeeeeeeeeeeee eeeeeeeeeeeee eeee option</option>
        </select>

I want to change select width to be minimum of container width and option text width. If option text is bigger than div container, truncate  option's text and put ellipsis at the end. So the option stays inside the container. Also select must be responsive, When resizing window, select width should be updated to fit new window width.

How can I achieve that using bootstrap CSS?

Body:
I took this answer from this stackoverflow answer

.dropdown{
 width:150px;
 border: 1px solid #cfcfcf;
 height: auto;
 border-radius: 5px;
 padding:3px 4px 4px;
 position: relative;
 z-index: 0;
 overflow:hidden;
 }

.dropdown select{
 border: none;
 background-color: transparent;
 outline: none;
 padding: 0;
 width:150px;
    /* background: url(http://i57.tinypic.com/nnmgpy_th.png) no-repeat right; */
    /* background-position: 55%; */
 }

/* not 100% sure this next option rule is needed */
.dropdown option {
    width:150px
}

/* this places an arbitrary element inside the dropdown but before it's children elements */
/* We use it to cover half the select box as well as display the custom arrow */

<div class="dropdown">
    <select>
       <option value="">Some Text</option>
        <option value="">Some More Text2</option>
        <option value="">Some More More More Longer Text</option>
    </select>

    </div>


答: PHP has a built-in DOM parser. Poke around the class of functions to reveal what you're looking for.</p>

Title: How do you get a part of webpage from remote by using php?

Body:
Id like to get a part of webpage.
Let me show you what id like to do.

For example, http:// www.xxxxxx.com/page=2

As you can see there is a list, and this list shows 50 ads. Please ignore other ones. Every ads have an unique id in their links.

for example:

http:// xxx.com/-iid-155546130

the id number is : 155546130

Okay, id like to get unique id numbers from that page, and echo them to the screen. So, i need to get 50 unique ids from that page. Only id numbers.

well, could you please kindly give me some advice? which functions should i use? how can i do that job?

Regards.


问:
Published Winform Issue
I have a winform app which reads sqlite database from a specific folder inside the machine's Document folder. So basically what I'm doing is importing data from mobile database to Sql server. The feature is running smoothly when debugging but after I published the app, installed it and run it, it throws sqlite.interop.dll is not found. I just downloaded x86 and x64 version of the dll and tried to inlcude it in the project and published again. But still the error persists.

My question: What could be the way to make the interop.dll be detected by the app?

Here's the code:

```<code>try
{
    var directory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    var cn = "Data Source=" + directory + @"\Samplefolder\" + txtfilename.Text;

    using (SQLiteConnection conn = new SQLiteConnection(cn))
    {
        conn.Open();
        using (SQLiteCommand cmd = new SQLiteCommand())
        {
            cmd.Connection = conn;
            cmd.CommandText = "SELECT * FROM Tablr";

            using (SQLiteDataReader dr = cmd.ExecuteReader())
            {
                while (dr.Read())
                {
                    // getting values from dr and assigning to a property of a class
                }
            }
        }
    }

    MessageBox.Show("Successful");
}
catch(Exception message)
{
    MessageBox.Show("Failed");
}
</code>```

答:
I fixed this after downloading both SQlite.Interop.dll x86 and x64 here. Then
created x86 and x64 folders in my project and placed the dlls into the folders correspondingly. Then edited the project properties and unchecked prefer 32-bit</p>

Title: Published Winform Issue

Body:
I have a winform app which reads sqlite database from a specific folder inside the machine's Document folder. So basically what I'm doing is importing data from mobile database to Sql server. The feature is running smoothly when debugging but after I published the app, installed it and run it, it throws sqlite.interop.dll is not found. I just downloaded x86 and x64 version of the dll and tried to inlcude it in the project and published again. But still the error persists.

My question: What could be the way to make the interop.dll be detected by the app?

Here's the code:

try
{
    var directory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    var cn = "Data Source=" + directory + @"\Samplefolder\" + txtfilename.Text;

    using (SQLiteConnection conn = new SQLiteConnection(cn))
    {
        conn.Open();
        using (SQLiteCommand cmd = new SQLiteCommand())
        {
            cmd.Connection = conn;
            cmd.CommandText = "SELECT * FROM Tablr";

            using (SQLiteDataReader dr = cmd.ExecuteReader())
            {
                while (dr.Read())
                {
                    // getting values from dr and assigning to a property of a class
                }
            }
        }
    }

    MessageBox.Show("Successful");
}
catch(Exception message)
{
    MessageBox.Show("Failed");
}


问:
AWS hosted data storage for storing simple entities
I need to choose data storage for simple system. The main purpose of the system is storing events - simple entities with timestamp, user id and type. No joins. Just single table.

Stored data will be fetched rarely (compared with writes). I expect following read operations:

get latest events for a list of users

get latest events of a type for a list of users

I expect about 0.5-1 million writes a day. Data older than 2 years can be removed.

I'm looking for best fitted service provided by AWS. I wonder if using redshift is like taking a sledgehammer to crack a nut?

答:
For your requirement you can use AWS DynamoDB and also define the TTL values to remove the older items automatically. You get the following advantages.

Fully managed data storage

Able to scale with the need for write throughput (Though it can be costly)

Use sort key with timestamp to query latest items.


问:
Puppeteer video automatically downloading instead of displaying player
Basically I have this piece of code below

```<code>;(async () => {
  const browser = await puppeteer.launch({
    args: ['--no-sandbox'],
    headless: false
  })

  const page = await browser.newPage()

  await page.goto('https://www.w3schools.com/html/mov_bbb.mp4', {waitUntil: 'load'})
})()
</code>```

and for some reason when I execute the script chromium just automatically starts downloading the video instead of showing the player.

Is there any way I could prevent this?

答:
At the time of writing this answer, Unfortunately Chromium does not support playing .mp4, Learn more: https://www.chromium.org/audio-video

How can you bypass this action?
You can download the latest chrome dev version from here,
https://www.chromium.org/getting-involved/dev-channel

And then use that chrome path like this,

```<code>const browser = await puppeteer.launch({
    args: ["--no-sandbox"],
    headless: false,
    executablePath: "./chrome-unstable/chrome" // <-- chrome path here
});
</code>```

You'll see it loads properly without downloading,

There is one major drawback, the browser doesn't know when the page is loaded, Should it wait until the whole video is loaded? Should it autoplay?

Puppeteer still does not have any good way to deal with media files except to download it. Same goes with .ppt, .doc, .pdf and any other kind of files.

You can look for other media related issue here: https://github.com/GoogleChrome/puppeteer/issues?utf8=%E2%9C%93&q=is%3Aissue%20mp4

Body:
Basically I have this piece of code below

;(async () => {
  const browser = await puppeteer.launch({
    args: ['--no-sandbox'],
    headless: false
  })

  const page = await browser.newPage()

  await page.goto('https://www.w3schools.com/html/mov_bbb.mp4', {waitUntil: 'load'})
})()

and for some reason when I execute the script chromium just automatically starts downloading the video instead of showing the player.

Is there any way I could prevent this?

Body:
At the time of writing this answer, Unfortunately Chromium does not support playing .mp4, Learn more: https://www.chromium.org/audio-video

How can you bypass this action?
You can download the latest chrome dev version from here,
https://www.chromium.org/getting-involved/dev-channel

And then use that chrome path like this,

const browser = await puppeteer.launch({
    args: ["--no-sandbox"],
    headless: false,
    executablePath: "./chrome-unstable/chrome" // <-- chrome path here
});

You'll see it loads properly without downloading,

There is one major drawback, the browser doesn't know when the page is loaded, Should it wait until the whole video is loaded? Should it autoplay?

Puppeteer still does not have any good way to deal with media files except to download it. Same goes with .ppt, .doc, .pdf and any other kind of files.

You can look for other media related issue here: https://github.com/GoogleChrome/puppeteer/issues?utf8=%E2%9C%93&q=is%3Aissue%20mp4


问:
Vue datatable row q-input not persisting values of model object
Please refer to the azure link for the built code and github link for the source code. To explain the scenario, I have a q-datatable from Quasar Framework. Since I have nested data, I am populating primary data in a collapsible for loop and secondary data in the content of collapsible as a datatable. The page also features an Edit/View Mode toggle just below the filters on the right. I have formatted the columns of the datatable to show q-input when in Edit Mode and just text in View Mode. Please do the following operation to reproduce the error. Steps 5 and onward are the steps producing unexpected behavior.

Expand one of the rows at the link(open in new window manually).

Toggle the Edit/View toggle which can be found just below the filters.

Trying editing any row. Observed Result: The values do persist in the text boxes on leaving focus, and also in the labels when page mode is changed back to View mode.

Add a new row by clicking on Add button found just below the row header.

Try typing in any of the text boxes in the newly added row and move to the ext text box. Observed Result: The values do not persist in the text box neither do they show in the labels when changed to View Mode.

Change mode back to View Mode and then back to Edit Mode. Observed Result: Values do show in the text boxes in edit mode but not in the View Mode.

Add a new row. Observed Result: Now the previously added row values show in both Edit and View Modes.

答: The problem was in the AddRow method. It is stated in the documentation that vue can only track changes to objects with defined properties. In the AddRow method I was adding an empty data object to the model. Adding properties with null values fixed the issue.</p>


问:
New divs inside pre-existing div with slanted borders
I am trying to make a header as shown in the image attached. I tried the other answers on this website too but none actually helped very much.
I already have figured out the text and logo parts but need someone to help with the slanting div borders.

The effect that I want:

答:
Try This:

header {
  border:1Px solid;
  height: 200px;
  position: relative;
}

header:before, header:after {
  position: absolute;
  width: 0;
  height: 0;
  content: '';
  border-width: 100px;
  border-style: solid;
}

header:before {
  left: 0;
  border-color: transparent transparent transparent #000;
}

header:after {
  right: 0;
  border-color:transparent #000 transparent transparent ;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header></header></code>```

Body:
Try This:

header {
  border:1Px solid;
  height: 200px;
  position: relative;
}

header:before, header:after {
  position: absolute;
  width: 0;
  height: 0;
  content: '';
  border-width: 100px;
  border-style: solid;
}

header:before {
  left: 0;
  border-color: transparent transparent transparent #000;
}

header:after {
  right: 0;
  border-color:transparent #000 transparent transparent ;
}

<header></header>


问:
Php Symfony framework culture URL
I need to create different URL for different cultures.

Example:
localhost/trips   should be localhost/matkat in finish culture ,

but localhost/trips must be not available in finish culture.

Tried such configuration in routing.yml but no success

destination_en:
  url:   /trips
  param: { module: destination, action: index }
  requirements: { sf_culture: en  }

答: There's a an i18n routing plugin in the Symfony plugins repo: http://www.symfony-project.org/plugins/zxI18nRoutingPlugin</p>

Title: Php Symfony framework culture URL


问:
Clear sidekiq queue
I've this worker that runs for ever.

```<code>class Worker
  include Sidekiq::Worker
  sidekiq_options queue: "infinity", retry: true

  def perform(params)
    # ...
    self.class.perform_in(30.seconds, params)
  end
end
</code>```

The problem is that I load workers on start up, like this. config/initializers/load_workers.rb

```<code>Rails.application.config.after_initialize do
  if ENV["SIDEKIQ"] == "1"
    Worker.perform_async({})
  end
end
</code>```

Using this to start sidekiq SIDEKIQ=1 sidekiq --verbose --environment production -C config/sidekiq.yml.

This means that old workers as to stop, both those currently running but also the ones being rescheduled.

I tried running this on start up (just before loading new works), but that didn't work.

```<code>q = []
q += Sidekiq::RetrySet.new.select { |job| job.klass.match(/Worker/) }
q += Sidekiq::Queue.new("infinity").select { |job| job.klass.match(/Worker/) }
q += Sidekiq::ScheduledSet.new.select { |job| job.klass.match(/Worker/) }
q.each(&:delete)
</code>```

After 5-ish deploys there are bunch of duplicate workers in the queue scheduled for later. So, is there a way to clear everyting in one queue and prevent already running jobs from rescheduling?

I'm using sidekiq 3.0.

答:
This will clear all queues, schedules and retries:</p>
```<code>require 'sidekiq/api'
Sidekiq::Queue.all.each(&:clear)
Sidekiq::RetrySet.new.clear
Sidekiq::ScheduledSet.new.clear
Sidekiq::DeadSet.new.clear
</code>```

Title: Clear sidekiq queue

Body:
I've this worker that runs for ever.

class Worker
  include Sidekiq::Worker
  sidekiq_options queue: "infinity", retry: true

  def perform(params)
    # ...
    self.class.perform_in(30.seconds, params)
  end
end

The problem is that I load workers on start up, like this. config/initializers/load_workers.rb

Rails.application.config.after_initialize do
  if ENV["SIDEKIQ"] == "1"
    Worker.perform_async({})
  end
end

Using this to start sidekiq SIDEKIQ=1 sidekiq --verbose --environment production -C config/sidekiq.yml.

This means that old workers as to stop, both those currently running but also the ones being rescheduled.

I tried running this on start up (just before loading new works), but that didn't work.

q = []
q += Sidekiq::RetrySet.new.select { |job| job.klass.match(/Worker/) }
q += Sidekiq::Queue.new("infinity").select { |job| job.klass.match(/Worker/) }
q += Sidekiq::ScheduledSet.new.select { |job| job.klass.match(/Worker/) }
q.each(&:delete)

After 5-ish deploys there are bunch of duplicate workers in the queue scheduled for later. So, is there a way to clear everyting in one queue and prevent already running jobs from rescheduling?

I'm using sidekiq 3.0.

Body:
This will clear all queues, schedules and retries:

require 'sidekiq/api'
Sidekiq::Queue.all.each(&:clear)
Sidekiq::RetrySet.new.clear
Sidekiq::ScheduledSet.new.clear
Sidekiq::DeadSet.new.clear

ContentLicense: CC BY-SA 4.0


问:
Angular 4 - Bootstrap Modal throws an exception
I get the 'Uncaught (in promise): Error: No provider for ComponentLoaderFactory!' error while trying to access a component that imports Bootstrap ModalModule.

app.module.ts:

```<code>import { ModalModule } from 'ngx-bootstrap/modal';

@NgModule({
    imports: [BrowserModule, RouterModule, ModalModule.forRoot()],
...
</code>```

template.component.ts (where the error occurs):

```<code>import {  TemplateRef } from '@angular/core';
import { BsModalService } from 'ngx-bootstrap/modal';
import { BsModalRef } from 'ngx-bootstrap/modal/bs-modal-ref.service';

@Component({
    selector: 'templateController',
    templateUrl: './templateController.component.html',
    providers: [BsModalService]
})

export class TemplateControllerComponent implements OnInit {

    modalRef: BsModalRef;

    constructor(private modalService: BsModalService) {
</code>```

Here I provide a path to ngx-bootstrap/modal, without it, it fails to find the required js file and throws a 404.
systemjs.config.js:

```<code>(function (global) {
    System.config({
        paths: {
            // paths serve as alias
            'npm:': 'node_modules/'
        },
        // map tells the System loader where to look for things
        map: {
            // our app is within the app folder
            'app': '/src/app',

            // angular bundles
            '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
            '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
            '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
            '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
            '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
            '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
            '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
            '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
            'tslib': 'npm:tslib/tslib.js',
            '@angular/common/http': 'npm:@angular/common/bundles/common-http.umd.js',

            // other libraries
            'rxjs': 'npm:rxjs',
            'moment': 'node_modules/moment/moment.js',
            'ngx-bootstrap': 'node_modules/ngx-bootstrap/bundles/ngx-bootstrap.umd.js',
            'ngx-bootstrap/modal': 'node_modules/ngx-bootstrap/bundles/ngx-bootstrap.umd.js'

        },
        // packages tells the System loader how to load when no filename and/or no extension
        packages: {
            app: {
                defaultExtension: 'js',
                meta: {
                    './*.js': {
                        loader: 'src/systemjs-angular-loader.js'
                    }
                }
            },
            rxjs: {
                defaultExtension: 'js'
            }
            //,
            //"ngx-bootstrap/modal": {
            //    "defaultExtension": "js"
            //}

        }
    });
})(this);
</code>```

答:
Try to add forRoot() in module import(module from ngx-bootstrap).

If it doesn't work then you need to provide entry component.

In your app.module:

You need a entryComponent field in @NgModule() in your module file because you are loading your Bootstrap Components dynamically. Add your bootstrap components in the entryComponents array as shown below :

```<code>@NgModule({
declaration: [],
imports: [],
  entryComponents: [ModalComponent,..]
})
</code>```

Body:
I get the 'Uncaught (in promise): Error: No provider for ComponentLoaderFactory!' error while trying to access a component that imports Bootstrap ModalModule.

app.module.ts:

import { ModalModule } from 'ngx-bootstrap/modal';

@NgModule({
    imports: [BrowserModule, RouterModule, ModalModule.forRoot()],
...

template.component.ts (where the error occurs):

import {  TemplateRef } from '@angular/core';
import { BsModalService } from 'ngx-bootstrap/modal';
import { BsModalRef } from 'ngx-bootstrap/modal/bs-modal-ref.service';

@Component({
    selector: 'templateController',
    templateUrl: './templateController.component.html',
    providers: [BsModalService]
})

export class TemplateControllerComponent implements OnInit {

    modalRef: BsModalRef;

    constructor(private modalService: BsModalService) {

Here I provide a path to ngx-bootstrap/modal, without it, it fails to find the required js file and throws a 404.
systemjs.config.js:

(function (global) {
    System.config({
        paths: {
            // paths serve as alias
            'npm:': 'node_modules/'
        },
        // map tells the System loader where to look for things
        map: {
            // our app is within the app folder
            'app': '/src/app',

            // angular bundles
            '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
            '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
            '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
            '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
            '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
            '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
            '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
            '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
            'tslib': 'npm:tslib/tslib.js',
            '@angular/common/http': 'npm:@angular/common/bundles/common-http.umd.js',

            // other libraries
            'rxjs': 'npm:rxjs',
            'moment': 'node_modules/moment/moment.js',
            'ngx-bootstrap': 'node_modules/ngx-bootstrap/bundles/ngx-bootstrap.umd.js',
            'ngx-bootstrap/modal': 'node_modules/ngx-bootstrap/bundles/ngx-bootstrap.umd.js'

        },
        // packages tells the System loader how to load when no filename and/or no extension
        packages: {
            app: {
                defaultExtension: 'js',
                meta: {
                    './*.js': {
                        loader: 'src/systemjs-angular-loader.js'
                    }
                }
            },
            rxjs: {
                defaultExtension: 'js'
            }
            //,
            //"ngx-bootstrap/modal": {
            //    "defaultExtension": "js"
            //}

        }
    });
})(this);

Body:
Try to add forRoot() in module import(module from ngx-bootstrap).

If it doesn't work then you need to provide entry component.

In your app.module:

You need a entryComponent field in @NgModule() in your module file because you are loading your Bootstrap Components dynamically. Add your bootstrap components in the entryComponents array as shown below :

@NgModule({
declaration: [],
imports: [],
  entryComponents: [ModalComponent,..]
})


问:
Refresh Implementation of RIDL does not generate OLE Control Proxy class declaration
I have converted a Delphi 2005 OCX project to XE2, which caused the original TLB to be changed to a RIDL. Using View | Type Library in XE2 is similar to Delphi 2005, and I can see all the interfaces and properties/methods.

The original 2005 project already had a _TLB.pas unit generated from the original TLB, but I needed to add a new property, so I went ahead and did that to the RIDL and chose the "Refresh Implementation" option.

However, while the original _TLB.pas contained a section near the end like this:

```<code>// *********************************************************************//
// OLE Control Proxy class declaration
// Control Name     : TTransControlSHX
// Help String      : TransControlSHX Control
// Default Interface: ITransControlSHX
// Def. Intf. DISP? : No
// Event   Interface: ITransControlSHXEvents
// TypeFlags        : (34) CanCreate Control
// *********************************************************************//
  TTransControlSHX = class(TOleControl)
</code>```

The new _TLB.pas file generated from the RIDL does not contain this section.

How do I get it back? Without it, my applications using the OCX all complain that the TTransControlSHX is an Undeclared Identifier.

答: The older versions of Delphi created the OLE proxy class in the COM's TLB pas file, however when you want to write the client code to use that COM object, you must import the type library (select "as unit") and you will have your OLE proxy class in THAT TLB pas file.</p>

Body:
I have converted a Delphi 2005 OCX project to XE2, which caused the original TLB to be changed to a RIDL. Using View | Type Library in XE2 is similar to Delphi 2005, and I can see all the interfaces and properties/methods.

The original 2005 project already had a _TLB.pas unit generated from the original TLB, but I needed to add a new property, so I went ahead and did that to the RIDL and chose the "Refresh Implementation" option.

However, while the original _TLB.pas contained a section near the end like this:

// *********************************************************************//
// OLE Control Proxy class declaration
// Control Name     : TTransControlSHX
// Help String      : TransControlSHX Control
// Default Interface: ITransControlSHX
// Def. Intf. DISP? : No
// Event   Interface: ITransControlSHXEvents
// TypeFlags        : (34) CanCreate Control
// *********************************************************************//
  TTransControlSHX = class(TOleControl)

The new _TLB.pas file generated from the RIDL does not contain this section.

How do I get it back? Without it, my applications using the OCX all complain that the TTransControlSHX is an Undeclared Identifier.


问:
Is it possible to filter Apache Kafka messages by retention time?
At an abstract point of view Apache Kafka stores data in topics. This data could be read by a consumer.

I'd like to have a (monitor)-consumer which greps data with a certain age. The monitor should send a warning to subsystems that records are still unread and would be discarded by Kafka if they reach retention time.

I couldn't find a suitable way until now.

答:
You can use KafkaConsumer.offsetsForTimes() to map messages to dates.

For example, if you call it with the date of yesterday and it returns offset X, then any messages with an offset smaller than X are older than yesterday.

Then your logic can figure out from the current positions of your consumers if you are at risk of having unprocessed records discarded.

Note that there is currently a KIP under discussion to expose metrics to track that: https://cwiki.apache.org/confluence/display/KAFKA/KIP-223+-+Add+per-topic+min+lead+and+per-partition+lead+metrics+to+KafkaConsumer

http://kafka.apache.org/10/javadoc/org/apache/kafka/clients/consumer/KafkaConsumer.html#offsetsForTimes-java.util.Map-


问:
Sails.JS - Created user wont return user object
I have a function in my Sails 1.0 application that adds a new user to the MongoDB and then at the end should return the User object as JSON...

The User does get added to the collection but it throws an error when trying to get the _id of the new User object. When I attempt to console.log() the createdUser it comes back as Undefined. Trying to figure out how the user can get created in Mongo but not be returned as an object in the same function?

In short the Register() function does the following:

Validates some inputs

Checks for valid email address

Encrypts the password

Finds Gravatar URL if applicable

Inserts User into collection

Set user._id in req.session (ERROR IS OCCURRING HERE)

Return User object as JSON

Error:

```<code>info: ·• Auto-migrating...  (alter)
info:    Hold tight, this could take a moment.
info:  ✓ Auto-migration complete.

warn: Ignored attempt to bind route (/resend-username) to unknown action :: UserController.resendUsername
info:
info:                .-..-.
info:
info:    Sails              <|    .-..-.
info:    v1.0.0-37           |\
info:                       /|.\
info:                      / || \
info:                    ,'  |'  \
info:                 .-'.-==|/_--'
info:                 `--'-------'
info:    __---___--___---___--___---___--___
info:  ____---___--___---___--___---___--___-__
info:
info: Server lifted in `D:\Development\Sails\goknack-sails-1.0`
info: To shut down Sails, press <CTRL> + C at any time.

debug: -------------------------------------------------------
debug: :: Tue Sep 05 2017 18:08:33 GMT-0500 (Central Daylight Time)

debug: Environment : development
debug: Port        : 1337
debug: -------------------------------------------------------
undefined
D:\Development\Sails\goknack-sails-1.0\node_modules\mongodb\lib\utils.js:123
    process.nextTick(function() { throw err; });
                                  ^

TypeError: Cannot read property '_id' of undefined
    at D:\Development\Sails\goknack-sails-1.0\api\controllers\UserController.js:259:47
    at D:\Development\Sails\goknack-sails-1.0\node_modules\parley\lib\private\Deferred.js:232:16
    at _afterTalkingToAdapter (D:\Development\Sails\goknack-sails-1.0\node_modules\waterline\lib\waterline\methods\create.js:282:22)
    at D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\lib\private\do-with-connection.js:223:16
    at D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\lib\private\do-with-connection.js:123:18
    at Object.success (D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\lib\private\build-std-adapter-method.js:61:47)
    at afterMaybeArtificiallyWaiting (D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\node_modules\machine\lib\private\intercept-exit-callbacks.js:406:21)
    at maybeArtificiallyWait (D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\node_modules\machine\lib\private\intercept-exit-callbacks.js:220:20)
    at afterPotentiallyCaching (D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\node_modules\machine\lib\private\intercept-exit-callbacks.js:240:11)
    at _cacheIfAppropriate (D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\node_modules\machine\lib\private\intercept-exit-callbacks.js:98:18)
    at Function._interceptExit [as success] (D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\node_modules\machine\lib\private\intercept-exit-callbacks.js:111:9)
    at D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\lib\private\machines\create-record.js:99:22
    at D:\Development\Sails\goknack-sails-1.0\node_modules\mongodb\lib\collection.js:437:18
    at handleCallback (D:\Development\Sails\goknack-sails-1.0\node_modules\mongodb\lib\utils.js:120:56)
    at D:\Development\Sails\goknack-sails-1.0\node_modules\mongodb\lib\collection.js:743:5
    at D:\Development\Sails\goknack-sails-1.0\node_modules\mongodb-core\lib\connection\pool.js:461:18
                              ^
</code>```

I have tried switching id to _id since it is Mongo but no luck, when I try to console.log createdUser it is Undefined.

The record is being created in the database... Any help on where I might be screwing up would be appreciated.

The full Register function I am using:

```<code>  register: function (req, res) {

    if (_.isUndefined(req.param('first'))) {
      return res.badRequest('A first name is required!');
    }

    if (_.isUndefined(req.param('last'))) {
      return res.badRequest('A last name is required!');
    }

    if (_.isUndefined(req.param('phone'))) {
      return res.badRequest('A phone number is required!');
    }

    if (_.isUndefined(req.param('email'))) {
      return res.badRequest('An email address is required!');
    }

    if (req.param('email') !== req.param('emailConfirm')) {
      return res.badRequest('Email addresses do not match!');
    }

    if (_.isUndefined(req.param('password'))) {
      return res.badRequest('A password is required!');
    }

    if (req.param('password').length < 6) {
      return res.badRequest('Password must be at least 6 characters!');
    }

    if (req.param('password') !== req.param('confirmPassword')) {
      return res.badRequest('Passwords do not match!');
    }

    if (_.isUndefined(req.param('tos'))) {
      return res.badRequest('You must review and accept the Goknack Terms of Service & Privacy policy.');
    }

    Emailaddresses.validate({
      string: req.param('email'),
    }).exec({
      // An unexpected error occurred.
      error: function (err) {
        return res.serverError(err);
      },
      // The provided string is not an email address.
      invalid: function () {
        return res.badRequest('Doesn\'t look like an email address to me!');
      },
      // OK.
      success: function () {

        Passwords.encryptPassword({
          password: req.param('password'),
        }).exec({

          error: function (err) {
            return res.serverError(err);
          },

          success: function (result) {

            var options = {};

            // gravitar image for user, if present
            try {

              options.gravatarURL = Gravatar.getImageUrl({
                emailAddress: req.param('email')
              }).execSync();

            } catch (err) {
              return res.serverError(err);
            }

            options.email = req.param('email');
            options.username = req.param('username');
            options.encryptedPassword = result;
            options.deleted = false;
            options.deletedDate = '';
            options.admin = false;
            options.banned = false;
            options.paypalEmail = '';

            // validate that email address has not been used before
            User.find({email: req.param('email')}).exec(function(err, user) {
              if (err) {
                return res.negotiate(err);
              }

              if (user.length > 0) {
                return res.badRequest('Invalid email, this email address is already in use.');
              } else {
                // create new user
                User.create(options).exec(function (err, createdUser) {

                  if (err) {
                    console.log('the error is: ', err.invalidAttributes);
                    return res.negotiate(err);
                  }

                  // Log the user in
                  console.log(createdUser);
                  req.session.userId = createdUser._id;

                  // NOTHING IS BEING RETURNED IN createdUser

                  return res.json(createdUser);
                });

              }
            });

          }
        });
      }
    });
  },
</code>```

答:
My answer is late, but this might help someone in the future. This syntax:

```<code>User.find({email: req.param('email')}, function(err, user) {
    //...
});
</code>```

is the syntax used by Mike McNeil in the book Sails.js in action. It actually does work, at least in V0.12.

Concerning the error, the only reason I could think of to cause this problem, where the record is created but not returned is if you have created your own create() method on the UserController and you do not return the object once created.

Body:
I have a function in my Sails 1.0 application that adds a new user to the MongoDB and then at the end should return the User object as JSON...

The User does get added to the collection but it throws an error when trying to get the _id of the new User object. When I attempt to console.log() the createdUser it comes back as Undefined. Trying to figure out how the user can get created in Mongo but not be returned as an object in the same function?

In short the Register() function does the following:

Validates some inputs

Checks for valid email address

Encrypts the password

Finds Gravatar URL if applicable

Inserts User into collection

Set user._id in req.session (ERROR IS OCCURRING HERE)

Return User object as JSON

Error:

info: ·• Auto-migrating...  (alter)
info:    Hold tight, this could take a moment.
info:  ✓ Auto-migration complete.

warn: Ignored attempt to bind route (/resend-username) to unknown action :: UserController.resendUsername
info:
info:                .-..-.
info:
info:    Sails              <|    .-..-.
info:    v1.0.0-37           |\
info:                       /|.\
info:                      / || \
info:                    ,'  |'  \
info:                 .-'.-==|/_--'
info:                 `--'-------'
info:    __---___--___---___--___---___--___
info:  ____---___--___---___--___---___--___-__
info:
info: Server lifted in `D:\Development\Sails\goknack-sails-1.0`
info: To shut down Sails, press <CTRL> + C at any time.

debug: -------------------------------------------------------
debug: :: Tue Sep 05 2017 18:08:33 GMT-0500 (Central Daylight Time)

debug: Environment : development
debug: Port        : 1337
debug: -------------------------------------------------------
undefined
D:\Development\Sails\goknack-sails-1.0\node_modules\mongodb\lib\utils.js:123
    process.nextTick(function() { throw err; });
                                  ^

TypeError: Cannot read property '_id' of undefined
    at D:\Development\Sails\goknack-sails-1.0\api\controllers\UserController.js:259:47
    at D:\Development\Sails\goknack-sails-1.0\node_modules\parley\lib\private\Deferred.js:232:16
    at _afterTalkingToAdapter (D:\Development\Sails\goknack-sails-1.0\node_modules\waterline\lib\waterline\methods\create.js:282:22)
    at D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\lib\private\do-with-connection.js:223:16
    at D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\lib\private\do-with-connection.js:123:18
    at Object.success (D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\lib\private\build-std-adapter-method.js:61:47)
    at afterMaybeArtificiallyWaiting (D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\node_modules\machine\lib\private\intercept-exit-callbacks.js:406:21)
    at maybeArtificiallyWait (D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\node_modules\machine\lib\private\intercept-exit-callbacks.js:220:20)
    at afterPotentiallyCaching (D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\node_modules\machine\lib\private\intercept-exit-callbacks.js:240:11)
    at _cacheIfAppropriate (D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\node_modules\machine\lib\private\intercept-exit-callbacks.js:98:18)
    at Function._interceptExit [as success] (D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\node_modules\machine\lib\private\intercept-exit-callbacks.js:111:9)
    at D:\Development\Sails\goknack-sails-1.0\node_modules\sails-mongo\lib\private\machines\create-record.js:99:22
    at D:\Development\Sails\goknack-sails-1.0\node_modules\mongodb\lib\collection.js:437:18
    at handleCallback (D:\Development\Sails\goknack-sails-1.0\node_modules\mongodb\lib\utils.js:120:56)
    at D:\Development\Sails\goknack-sails-1.0\node_modules\mongodb\lib\collection.js:743:5
    at D:\Development\Sails\goknack-sails-1.0\node_modules\mongodb-core\lib\connection\pool.js:461:18
                              ^

I have tried switching id to _id since it is Mongo but no luck, when I try to console.log createdUser it is Undefined.

The record is being created in the database... Any help on where I might be screwing up would be appreciated.

The full Register function I am using:

  register: function (req, res) {

    if (_.isUndefined(req.param('first'))) {
      return res.badRequest('A first name is required!');
    }

    if (_.isUndefined(req.param('last'))) {
      return res.badRequest('A last name is required!');
    }

    if (_.isUndefined(req.param('phone'))) {
      return res.badRequest('A phone number is required!');
    }

    if (_.isUndefined(req.param('email'))) {
      return res.badRequest('An email address is required!');
    }

    if (req.param('email') !== req.param('emailConfirm')) {
      return res.badRequest('Email addresses do not match!');
    }

    if (_.isUndefined(req.param('password'))) {
      return res.badRequest('A password is required!');
    }

    if (req.param('password').length < 6) {
      return res.badRequest('Password must be at least 6 characters!');
    }

    if (req.param('password') !== req.param('confirmPassword')) {
      return res.badRequest('Passwords do not match!');
    }

    if (_.isUndefined(req.param('tos'))) {
      return res.badRequest('You must review and accept the Goknack Terms of Service & Privacy policy.');
    }

    Emailaddresses.validate({
      string: req.param('email'),
    }).exec({
      // An unexpected error occurred.
      error: function (err) {
        return res.serverError(err);
      },
      // The provided string is not an email address.
      invalid: function () {
        return res.badRequest('Doesn\'t look like an email address to me!');
      },
      // OK.
      success: function () {

        Passwords.encryptPassword({
          password: req.param('password'),
        }).exec({

          error: function (err) {
            return res.serverError(err);
          },

          success: function (result) {

            var options = {};

            // gravitar image for user, if present
            try {

              options.gravatarURL = Gravatar.getImageUrl({
                emailAddress: req.param('email')
              }).execSync();

            } catch (err) {
              return res.serverError(err);
            }

            options.email = req.param('email');
            options.username = req.param('username');
            options.encryptedPassword = result;
            options.deleted = false;
            options.deletedDate = '';
            options.admin = false;
            options.banned = false;
            options.paypalEmail = '';

            // validate that email address has not been used before
            User.find({email: req.param('email')}).exec(function(err, user) {
              if (err) {
                return res.negotiate(err);
              }

              if (user.length > 0) {
                return res.badRequest('Invalid email, this email address is already in use.');
              } else {
                // create new user
                User.create(options).exec(function (err, createdUser) {

                  if (err) {
                    console.log('the error is: ', err.invalidAttributes);
                    return res.negotiate(err);
                  }

                  // Log the user in
                  console.log(createdUser);
                  req.session.userId = createdUser._id;

                  // NOTHING IS BEING RETURNED IN createdUser

                  return res.json(createdUser);
                });

              }
            });

          }
        });
      }
    });
  },

Body:
My answer is late, but this might help someone in the future. This syntax:

User.find({email: req.param('email')}, function(err, user) {
    //...
});

is the syntax used by Mike McNeil in the book Sails.js in action. It actually does work, at least in V0.12.

Concerning the error, the only reason I could think of to cause this problem, where the record is created but not returned is if you have created your own create() method on the UserController and you do not return the object once created.


问:
Load all items in android RecyclerView at once
I'm too tired for searched this question in two day's , but i got false answer , I implement RecyclerView and it worked well, but my RecycleView have many items like photo's and video's like Instagram . it mean my adapter will invoke onBindViewHolder for all items to start download and loading image's and video's . but RecycleView just invoked onBindViewHolder for each item's when item is visible (scroll show it) . it's impossible ? if not how instagram can do that . pay attention : i don't want to using database for save image's and video's</p>

```<code> @Override
public void onBindViewHolder(RecyclerView.ViewHolder h, int position) {

    Log.e("position",position+" ");

    thread t = new Thread(new Runnable(){
       public void run(){
           Bitmap bitmap = downloadPhoto();//it mean photo downloaded and converted to Bitmap
           runOnUiThread(new Runnable(){
               holder.imageView.setImageBitmap(bitmap);
           ));
       }

    });
    t.start();

}
</code>```

答:
As you describe, you only want to load photos when the item is visible. In fact RecyclerView adapter will only invoke onBindViewHolder when the item appears(visible) so you can start download photos then update UI when photo ready for you. And you now do not load all item's photo at once, you just load when you need.

ps: If the item's photo url is known, you can use Glide or Picasso library.

Body:
I'm too tired for searched this question in two day's , but i got false answer , I implement RecyclerView and it worked well, but my RecycleView have many items like photo's and video's like Instagram . it mean my adapter will invoke onBindViewHolder for all items to start download and loading image's and video's . but RecycleView just invoked onBindViewHolder for each item's when item is visible (scroll show it) . it's impossible ? if not how instagram can do that . pay attention : i don't want to using database for save image's and video's

 @Override
public void onBindViewHolder(RecyclerView.ViewHolder h, int position) {

    Log.e("position",position+" ");

    thread t = new Thread(new Runnable(){
       public void run(){
           Bitmap bitmap = downloadPhoto();//it mean photo downloaded and converted to Bitmap
           runOnUiThread(new Runnable(){
               holder.imageView.setImageBitmap(bitmap);
           ));
       }

    });
    t.start();

}


问:
Require js optimizer minifying my project but not concatenating into bundled file
It's not clear to me how to bundle many js files into one file.  When I run the optimizer the result is an output directory with a structure mirroring my source directory.  All files in it are minified.  That's good.  But what I was looking for was one minified file.  I don't see that.  So my project is optimized but not concatenated.

I must be misunderstanding something about how to configure the process.  Here's what I'm doing:

I have r.js and build.js in a directory.  In a folder off that directory I have sourcejs.  That sourcejs folder has application.js (the module I want the optimizer to trace).  That module "requires" lots of stuff in nested folders below it.

Here's the build file:

```<code>({
  appDir: "sourcejs",
  baseUrl: ".",
  dir: "sourcejs-build",
  mainConfigFile: 'sourcejs/application.js',
  modules: [
    {
      name: "application"
    }
  ]
})
</code>```

I'm assuming pointing the optimizer to the main module, application.js, will be all that's necessary to produce the desired output from there.  It will trace dependencies therein and find its way to all sub-folders and files.  The optimizer does appear to find all source.  I get output:

```<code>Tracing dependencies for: application
Uglify file: C:/o/sourcejs-build/application.js
Uglify file: C:/o/sourcejs-build/controller.js
Uglify file: C:/o/sourcejs-build/modules/controllers/auxcontroller.js
Uglify file: C:/o/sourcejs-build/modules/controllers/documentcontroller.js
...long list of files

application.js
----------------
application.js
</code>```

The output file application.js is not a concatenated version of the project but rather just a minified version of itself.

What is my misunderstanding here?

答:
By default all the js files get minified in the optimized directory. As far I understand according to the configuration you supplied it would bundle application.js and the modules it depends into the same file.

Aplication.js and it's dependencies goes into the Application.js.
Optimiziation process bundles only files that are mentioned in the modules and leaves other files as minified. If you want files to be bundles you have to provide the bundled file names (most probably you would be generating new files. ) You have to say create: true in the modules to create new files during build process.

```<code>{
   name : bundle1,
   create : true,
   include: ['dep1', 'dep2']
},
{
   name : bundle12,
   create : true,
   include: ['depA', 'depB']
}
</code>```

Like this you have to specify the bundle configuration so that they are created during the build process.

Body:
It's not clear to me how to bundle many js files into one file.  When I run the optimizer the result is an output directory with a structure mirroring my source directory.  All files in it are minified.  That's good.  But what I was looking for was one minified file.  I don't see that.  So my project is optimized but not concatenated.

I must be misunderstanding something about how to configure the process.  Here's what I'm doing:

I have r.js and build.js in a directory.  In a folder off that directory I have sourcejs.  That sourcejs folder has application.js (the module I want the optimizer to trace).  That module "requires" lots of stuff in nested folders below it.

Here's the build file:

({
  appDir: "sourcejs",
  baseUrl: ".",
  dir: "sourcejs-build",
  mainConfigFile: 'sourcejs/application.js',
  modules: [
    {
      name: "application"
    }
  ]
})

I'm assuming pointing the optimizer to the main module, application.js, will be all that's necessary to produce the desired output from there.  It will trace dependencies therein and find its way to all sub-folders and files.  The optimizer does appear to find all source.  I get output:

Tracing dependencies for: application
Uglify file: C:/o/sourcejs-build/application.js
Uglify file: C:/o/sourcejs-build/controller.js
Uglify file: C:/o/sourcejs-build/modules/controllers/auxcontroller.js
Uglify file: C:/o/sourcejs-build/modules/controllers/documentcontroller.js
...long list of files

application.js
----------------
application.js

The output file application.js is not a concatenated version of the project but rather just a minified version of itself.

What is my misunderstanding here?

Body:
By default all the js files get minified in the optimized directory. As far I understand according to the configuration you supplied it would bundle application.js and the modules it depends into the same file.

Aplication.js and it's dependencies goes into the Application.js.
Optimiziation process bundles only files that are mentioned in the modules and leaves other files as minified. If you want files to be bundles you have to provide the bundled file names (most probably you would be generating new files. ) You have to say create: true in the modules to create new files during build process.

{
   name : bundle1,
   create : true,
   include: ['dep1', 'dep2']
},
{
   name : bundle12,
   create : true,
   include: ['depA', 'depB']
}

Like this you have to specify the bundle configuration so that they are created during the build process.


问:
Node.JS run function for each item in fs.readdir array
I have a fs.readdir() function that I want to run every few hours. the reason for this is a bunch of files are sent to my box every so often and I have to run a script for each file to upload them to a db.

```<code>fs.readdir('some/location/',(err,files) => {
    if (files.indexOf('someFile') > -1) {
        console.log('file found')
        function1()
    }else{
        Console.log('file not found')
})
</code>```

now I don't want to have to do the readdir for all 13 files that get dropped is there a way to create a list like

```<code>someFile = function1()
someFile2 = function2()
</code>```

So it runs each files dedicated function for each file present on the readdir array?

```<code>var function1 = function........

var function2 = function... do.somethng.diferent
</code>```

答:
You can:

Create an object {} called fileFunctions that maps each file name to the function to apply.

Iterate over the files of the directory and apply the function matching this file name, using the object you just built, if this file name matches an entry in fileFunctions:

```<code>fileFunctions = {
  'file1' => function() {/*function to apply to file1*/},
  'file2' => function() {/*function to apply to file2*/},
   //etc..
};
fs.readdir('some/location/',(err,files) => {
    files.map((file) => {
       if(file in fileFunctions) {
            fileFunctions[file1](file1);
       }
     });
});
</code>```

Body:
I have a fs.readdir() function that I want to run every few hours. the reason for this is a bunch of files are sent to my box every so often and I have to run a script for each file to upload them to a db.

fs.readdir('some/location/',(err,files) => {
    if (files.indexOf('someFile') > -1) {
        console.log('file found')
        function1()
    }else{
        Console.log('file not found')
})

now I don't want to have to do the readdir for all 13 files that get dropped is there a way to create a list like

someFile = function1()
someFile2 = function2()

So it runs each files dedicated function for each file present on the readdir array?

var function1 = function........

var function2 = function... do.somethng.diferent

Body:
You can:

Create an object {} called fileFunctions that maps each file name to the function to apply.

Iterate over the files of the directory and apply the function matching this file name, using the object you just built, if this file name matches an entry in fileFunctions:

fileFunctions = {
  'file1' => function() {/*function to apply to file1*/},
  'file2' => function() {/*function to apply to file2*/},
   //etc..
};
fs.readdir('some/location/',(err,files) => {
    files.map((file) => {
       if(file in fileFunctions) {
            fileFunctions[file1](file1);
       }
     });
});


问:
The name 'ViewBag' does not exist in the current context - Visual Studio 2015
I'm starting to develop in ASP.NET again and I ran into a small error within Visual Studio. My .cshtml files show errors when using a few razor functions. For example "The name 'ViewBag' does not exist in the current context". Here is a picture:

I am using a demo project. You can find the project here: https://github.com/Wintellect/Angular-MVC-Cookbook/tree/master/BasicProject

I have looked through several other threads and most suggest to update the web.config file(s). These 2 config files are already present and since it's a pretty popular demo I assume it has all the required configuration in it. I have of course looked through these config files and they do indeed include the suggested solutions.

Other details:

I have already used clean & rebuild on the solution but that changed nothing.

When I create a completely new MVC project it does work

My friend has the same problem and we both use VS 2015 and Windows 10

I can still run the application and it does work.

答: I accidentally removed web.config from the Views folder, thinking that it was unnecessary. When I put it back it started working.


问:
How do you get a part of webpage from remote by using php?
Id like to get a part of webpage.
Let me show you what id like to do.

For example, http:// www.xxxxxx.com/page=2

As you can see there is a list, and this list shows 50 ads. Please ignore other ones. Every ads have an unique id in their links.

for example:

http:// xxx.com/-iid-155546130

the id number is : 155546130

Okay, id like to get unique id numbers from that page, and echo them to the screen. So, i need to get 50 unique ids from that page. Only id numbers.

well, could you please kindly give me some advice? which functions should i use? how can i do that job?

Regards.

答:
Fetch the page with:

```<code>$html = file_get_contents($url);  // or curl if you like it cumbersome
</code>```

And use a regex to get the numbers:

```<code>preg_match_all("/-iid-(\d+)/", $html, $m);  // could be more precise
print_r($m[1]);
</code>```

Body:
Fetch the page with:

$html = file_get_contents($url);  // or curl if you like it cumbersome

And use a regex to get the numbers:

preg_match_all("/-iid-(\d+)/", $html, $m);  // could be more precise
print_r($m[1]);


问:
Angular is working, but $scope not showing up
I'm walking through a tutorial on Angular. I've tried following their Dev Guide and searching SO, I'm a little confused with all the versions of Angular.

I have a small app, a to-do app, and I can't get the $scope from my HomeCtrl to appear when the app loads the home template. When I load the home template, it's showing everything except the scope calls in the curly brackets {{ }}.

Here's what I have for my HomeCtrl.js:

```<code> blocitoff.controller('HomeCtrl', ['$scope', '$firebaseArray', '$firebaseObject', function HomCtrl ($scope, $firebaseObject, $firebaseArray) {
    alert("hello");
    var ref = firebase.database().ref();
    var list = $firebaseArray(ref);
    $scope.data = $firebaseObject(ref);
    $scope.hello = "no way bill it worked!";
}]);
</code>```

Here's what I have for my home.html:

```<code><body ng-controller="HomeCtrl">
<div>
    <h2> hello there </h2>
    <h3> {{2+5}} </h3>
      I can add: {{ 1 + 2 }}.

    <p> {{$scope.hello}}</p>
    <p> {{ hello }} </p>
</div>
</body>
</code>```

Thank you for any help or tips.

答:
You can't use the $scope identifier in the view (the HTML). $scope is only accessible within the JavaScript.

The whole point of $scope is that expressions in the view will, by default, refer to values on the scope. So if you want to access $scope.hello, refer to it as hello, as you are already doing:

```<code><p> {{ hello }} </p>
</code>```

Working example:

var blocitoff = angular.module('blocitoff', []);

blocitoff.controller('HomeCtrl', ['$scope', function HomCtrl ($scope) {
    $scope.hello = "no way bill it worked!";
}]);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="blocitoff" ng-controller="HomeCtrl">
<div>
    <h2> hello there </h2>
    <h3> {{2+5}} </h3>
      I can add: {{ 1 + 2 }}.

    <p> {{ hello }} </p>
</div>
</body></code>```

Body:
I'm walking through a tutorial on Angular. I've tried following their Dev Guide and searching SO, I'm a little confused with all the versions of Angular.

I have a small app, a to-do app, and I can't get the $scope from my HomeCtrl to appear when the app loads the home template. When I load the home template, it's showing everything except the scope calls in the curly brackets {{ }}.

Here's what I have for my HomeCtrl.js:

 blocitoff.controller('HomeCtrl', ['$scope', '$firebaseArray', '$firebaseObject', function HomCtrl ($scope, $firebaseObject, $firebaseArray) {
    alert("hello");
    var ref = firebase.database().ref();
    var list = $firebaseArray(ref);
    $scope.data = $firebaseObject(ref);
    $scope.hello = "no way bill it worked!";
}]);

Here's what I have for my home.html:

 hello there

 {{2+5}}

      I can add: {{ 1 + 2 }}.

 {{$scope.hello}}

 {{ hello }}

Thank you for any help or tips.

Body:
You can't use the $scope identifier in the view (the HTML). $scope is only accessible within the JavaScript.

The whole point of $scope is that expressions in the view will, by default, refer to values on the scope. So if you want to access $scope.hello, refer to it as hello, as you are already doing:

<p> {{ hello }} </p>

Working example:

var blocitoff = angular.module('blocitoff', []);

blocitoff.controller('HomeCtrl', ['$scope', function HomCtrl ($scope) {
    $scope.hello = "no way bill it worked!";
}]);

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="blocitoff" ng-controller="HomeCtrl">
<div>
    <h2> hello there </h2>
    <h3> {{2+5}} </h3>
      I can add: {{ 1 + 2 }}.

    <p> {{ hello }} </p>
</div>
</body>


问:
Given a base and an exponent parameter, I want to create my own expt function
I'm trying to create a "slow" exponent function in racket that takes in a base and an exponent, n. I want create this function and multiply the base by itself n times to get my answer. I think creating a list is the best way to get my answer but I'm running into some issues:

```<code>(define (slow-expt base n)
  (local [(define listn (make-list n base))]
    (cons (* (- base 1) (first listn))
          (slow-expt base (rest listn)))))
</code>```

my error is that * expects the second argument to be a number, but it should be given (first listn). Any words of advice?

答:
Lists have nothing to do with this problem, simply multiply base by itself, n times:

```<code>(define (slow-expt base n)
  (if (= n 0)
      1
      (* base (slow-expt base (- n 1)))))
</code>```

Body:
I'm trying to create a "slow" exponent function in racket that takes in a base and an exponent, n. I want create this function and multiply the base by itself n times to get my answer. I think creating a list is the best way to get my answer but I'm running into some issues:

(define (slow-expt base n)
  (local [(define listn (make-list n base))]
    (cons (* (- base 1) (first listn))
          (slow-expt base (rest listn)))))

my error is that * expects the second argument to be a number, but it should be given (first listn). Any words of advice?

Body:
Lists have nothing to do with this problem, simply multiply base by itself, n times:

(define (slow-expt base n)
  (if (= n 0)
      1
      (* base (slow-expt base (- n 1)))))


问:
Find all paths of length 2 in a graph
I've tried to create an algorithm for finding all paths of length 2, but it doesn't seem to work properly:

```<code>input_split = input().split(' ')
node_count = int(input_split[0])
input_count = int(input_split[1])
items = np.zeros((node_count, node_count), dtype=np.int32) # matrix of adjacency
for j in range(input_count):
    split = input().split(' ')
    x = int(split[0]) - 1 # convert 1 based coordinates to 0 based
    y = int(split[1]) - 1
    items[x][y] = 1
    items[y][x] = 1
result = np.linalg.matrix_power(items, 2)
result_sum = int(np.sum(result) / 2) # reverse paths are counted only once
print(result_sum)
</code>```

Sample input:

```<code>6 7
1 2
2 3
3 1
2 4
4 5
5 6
6 2
</code>```

The result should be 11, but it prints 18.

答:
You are calculating walks, which would include walks 6-7-6 (which is not a P2)

this discussion might help:
https://math.stackexchange.com/questions/1890620/finding-path-lengths-by-the-power-of-adjacency-matrix-of-an-undirected-graph

Title: Find all paths of length 2 in a graph

Body:
I've tried to create an algorithm for finding all paths of length 2, but it doesn't seem to work properly:

input_split = input().split(' ')
node_count = int(input_split[0])
input_count = int(input_split[1])
items = np.zeros((node_count, node_count), dtype=np.int32) # matrix of adjacency
for j in range(input_count):
    split = input().split(' ')
    x = int(split[0]) - 1 # convert 1 based coordinates to 0 based
    y = int(split[1]) - 1
    items[x][y] = 1
    items[y][x] = 1
result = np.linalg.matrix_power(items, 2)
result_sum = int(np.sum(result) / 2) # reverse paths are counted only once
print(result_sum)

Sample input:

6 7
1 2
2 3
3 1
2 4
4 5
5 6
6 2

The result should be 11, but it prints 18.


问:
How can I log a hyperlink click?
I have a hyperlink which I need to log when it's clicked.

I created a small prototype, and the problem is repeatable by creating a new MVC 2 Web app project.

Add

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

to the Site.Master file.

And

```<code>public ActionResult LogSomething()
{
    string doNothing = DateTime.Now.ToString();
    return new EmptyResult();
}
</code>```

to the HomeController.cs file

And

```<code><p>
    <a id="lnkTestPost" href="/home/about">Test Post</a>

    <script type="text/javascript">
        $("#lnkTestPost").click(function() {
            $.post("/home/LogSomething");
        });
    </script>
</p>
</code>```

in Home/Index.aspx

Put a break point in the LogSomething() action method in the HomeController.

But when I run it, sometimes the breakpoint is hit, other times it isn't.

I'm assuming it's not being hit due to the actual link sending the browser to another page, but shouldn't the post be made before the link is fired?

Is there anyway I can ensure the logging code is fired?

Please note; adding the logging functionality in the link target is not an option.

EDIT: The original hyperlink is actually to a custom protocol for an app installed on the user PC.  So the link is to something like "myapp:myArgs".  I didn't mention that in order to keep things simple, unfortunately, since none of the answers really apply to me, I now think it's necessary to mention.

答: How 'bout an optional "log" parm on each page that is included as part of the links so you don't have to have any Javascript at all? Granted, each page could be logging something from the referrer page, but it shouldn't care, since you could have it just pass off whatever's in the log parm to the logging infra and go on.</p>

Title: How can I log a hyperlink click?

Body:
I have a hyperlink which I need to log when it's clicked.

I created a small prototype, and the problem is repeatable by creating a new MVC 2 Web app project.

Add

to the Site.Master file.

And

public ActionResult LogSomething()
{
    string doNothing = DateTime.Now.ToString();
    return new EmptyResult();
}

to the HomeController.cs file

And

    Test Post

in Home/Index.aspx

Put a break point in the LogSomething() action method in the HomeController.

But when I run it, sometimes the breakpoint is hit, other times it isn't.

I'm assuming it's not being hit due to the actual link sending the browser to another page, but shouldn't the post be made before the link is fired?

Is there anyway I can ensure the logging code is fired?

Please note; adding the logging functionality in the link target is not an option.

EDIT: The original hyperlink is actually to a custom protocol for an app installed on the user PC.  So the link is to something like "myapp:myArgs".  I didn't mention that in order to keep things simple, unfortunately, since none of the answers really apply to me, I now think it's necessary to mention.


问:
How to convert this Regular Expression to 'named group re' Python
I need to convert the following Regular Expression in named groups re format. Which I don't fully understand yet.

```<code> info = re.findall(
                r'.*\/dev\/(sd.):[.\s]*0[xX][1-9a-fA-F]+[.\s]*0[xX][0-9a-fA-F]+[.\s]*(\S+).*', content
            )
</code>```

An string to test if it works could be (matching with sda, 13D0A016FTR7) :

```<code>/dev/sda:   0x1 0x0  '13D0A016FTR7'
</code>```

At the end it should be able to use the info variable in the following way:

```<code>info[0][0] = sda
info[0][1] = 13D0A016FTR7
</code>```

答:
Answer to my question:</p>

```<code>content = "/dev/sda:   0x1 0x0  '13D0A016FTR7'"

info = re.search(r'.*\/dev\/(?P<disk>sd.):[.\s]*0[xX][1-9a-fA-F]+[.\s]*0[xX][0-9a-fA-F]+[.\s]*(?P<serial>\S+).*', content)

info.group('disk')
'sda'

info.group('serial')
"'13D0A016FTR7'"
</code>```

Body:
I need to convert the following Regular Expression in named groups re format. Which I don't fully understand yet.

 info = re.findall(
                r'.*\/dev\/(sd.):[.\s]*0[xX][1-9a-fA-F]+[.\s]*0[xX][0-9a-fA-F]+[.\s]*(\S+).*', content
            )

An string to test if it works could be (matching with sda, 13D0A016FTR7) :

/dev/sda:   0x1 0x0  '13D0A016FTR7'

At the end it should be able to use the info variable in the following way:

info[0][0] = sda
info[0][1] = 13D0A016FTR7

Body:
Answer to my question:

content = "/dev/sda:   0x1 0x0  '13D0A016FTR7'"

info = re.search(r'.*\/dev\/(?P<disk>sd.):[.\s]*0[xX][1-9a-fA-F]+[.\s]*0[xX][0-9a-fA-F]+[.\s]*(?P<serial>\S+).*', content)

info.group('disk')
'sda'

info.group('serial')
"'13D0A016FTR7'"


问:
Run validation on input based on change of checkbox in Angular 4
I am looping through an array of key values to create a list of checkboxes each with a sibling disabled input.  On check of each checkbox, the sibling input text field becomes enabled and is required. In this view there is a 'previous' and 'next' button and the 'next' button should be disabled if a user selects a checkbox and then does not enter anything in it's required sibling input.  I almost have this working, however the 'next' button should become disabled as soon as a user checks the box as this would mean they have not entered anything in the required text input.  Right now the 'next' button only becomes disabled if a user checks the checkbox, focuses on the sibling input and then leaves without entering.

My HTML...

```<code><div *ngFor="let promotion of promotionOptions; let i = index">
    <div class="col-md-6 input-container radio-label">
        <mat-checkbox [checked]="!promotion.key" (change)="promotion.key = !promotion.key">
            {{ promotion.name }}
        </mat-checkbox>
    </div>
    <mat-input-container>
        <input matInput [disabled]="promotion.key" placeholder="Cost" name="promotionCost{{i}}" #promotionCost="ngModel" [ngModel]="" (keyup)="promotionCostInput($event.target.value)"
            [required]="!promotion.key" type="number">
        <div *ngIf="promotionCost.errors && (promotionCost.dirty || promotionCost.touched)" class="alert alert-danger cost-alert">
            <div [hidden]="!promotionCost.errors.required">Please enter the checked promotion's cost</div>
        </div>
    </mat-input-container>
</div>

<div class="clearfix"></div>

<div class="button-container">
    <button class="main-btn dark icon-left" (click)="updateStep(1)"><i class="fa fa-angle-left"></i>Previous</button>
    <button class="main-btn icon-right" (click)="updateStep(3)" [disabled]="!promotionCostValid">Next<i class="fa fa-angle-right"></i></button>
</div>
</code>```

And the method I'm using in my .ts file for disabling the 'next' button:

```<code>promotionCostInput(value) {
    if (!value) {
      this.promotionCostValid = false;
    } else {
      this.promotionCostValid = true;
    }
  }
</code>```

How can I validate the sibling input when a user checks the checkbox?

答:
Your problem is that the state of your next button is only updated when the keyup event is fired on any of your inputs. Besides, it is updated with only the value of one input but according to what you say, youwant to check that every inputs of your ngFor is filled.

I suggest you to store the value of your inputs in your model and to check that promotion cost is valid for all promotions any time the input change or a checkbox is checked.

```<code><div *ngFor="let promotion of promotionOptions; let i = index">
  <div class="col-md-6 input-container radio-label">
    <mat-checkbox [checked]="!promotion.key" (change)="promotion.key = !promotion.key; checkPromotionCost();">
      {{ promotion.name }}
    </mat-checkbox>
  </div>
  <mat-input-container>
    <input
      matInput
      [disabled]="promotion.key"
      placeholder="Cost"
      name="promotionCost{{i}}"
      (keyup)="promotion.cost = $event.target.value; checkPromotionCost();"
      [required]="!promotion.key" type="number"
    >
    <div *ngIf="promotionCost.errors && (promotionCost.dirty || promotionCost.touched)" class="alert alert-danger cost-alert">
      <div [hidden]="!promotionCost.errors.required">
        Please enter the checked promotion's cost</div>
      </div>
  </mat-input-container>
</div>

<div class="clearfix"></div>

<div class="button-container">
  <button class="main-btn dark icon-left" (click)="updateStep(1)"><i class="fa fa-angle-left"></i>Previous</button>
  <button class="main-btn icon-right" (click)="updateStep(3)" [disabled]="!promotionCostValid">Next<i class="fa fa-angle-right"></i></button>
</div>
</code>```

And in the controller:

```<code>checkPromotionCost() {
  this.promotionCostValid = true;
  this.promotionOptions.forEach(promotion => {
    if (promotion.key && promotion.cost === '') {
      this.promotionCostValid = false;
    }
  });
}
</code>```

Body:
I am looping through an array of key values to create a list of checkboxes each with a sibling disabled input.  On check of each checkbox, the sibling input text field becomes enabled and is required. In this view there is a 'previous' and 'next' button and the 'next' button should be disabled if a user selects a checkbox and then does not enter anything in it's required sibling input.  I almost have this working, however the 'next' button should become disabled as soon as a user checks the box as this would mean they have not entered anything in the required text input.  Right now the 'next' button only becomes disabled if a user checks the checkbox, focuses on the sibling input and then leaves without entering.

My HTML...

        <mat-checkbox [checked]="!promotion.key" (change)="promotion.key = !promotion.key">
            {{ promotion.name }}
        </mat-checkbox>

    <mat-input-container>
        <input matInput [disabled]="promotion.key" placeholder="Cost" name="promotionCost{{i}}" #promotionCost="ngModel" [ngModel]="" (keyup)="promotionCostInput($event.target.value)"
            [required]="!promotion.key" type="number">

Please enter the checked promotion's cost

    </mat-input-container>

    <button class="main-btn dark icon-left" (click)="updateStep(1)">Previous</button>
    <button class="main-btn icon-right" (click)="updateStep(3)" [disabled]="!promotionCostValid">Next</button>

And the method I'm using in my .ts file for disabling the 'next' button:

promotionCostInput(value) {
    if (!value) {
      this.promotionCostValid = false;
    } else {
      this.promotionCostValid = true;
    }
  }

How can I validate the sibling input when a user checks the checkbox?

Body:
Your problem is that the state of your next button is only updated when the keyup event is fired on any of your inputs. Besides, it is updated with only the value of one input but according to what you say, youwant to check that every inputs of your ngFor is filled.

I suggest you to store the value of your inputs in your model and to check that promotion cost is valid for all promotions any time the input change or a checkbox is checked.

<div *ngFor="let promotion of promotionOptions; let i = index">
  <div class="col-md-6 input-container radio-label">
    <mat-checkbox [checked]="!promotion.key" (change)="promotion.key = !promotion.key; checkPromotionCost();">
      {{ promotion.name }}
    </mat-checkbox>
  </div>
  <mat-input-container>
    <input
      matInput
      [disabled]="promotion.key"
      placeholder="Cost"
      name="promotionCost{{i}}"
      (keyup)="promotion.cost = $event.target.value; checkPromotionCost();"
      [required]="!promotion.key" type="number"
    >
    <div *ngIf="promotionCost.errors && (promotionCost.dirty || promotionCost.touched)" class="alert alert-danger cost-alert">
      <div [hidden]="!promotionCost.errors.required">
        Please enter the checked promotion's cost</div>
      </div>
  </mat-input-container>
</div>

<div class="clearfix"></div>

<div class="button-container">
  <button class="main-btn dark icon-left" (click)="updateStep(1)"><i class="fa fa-angle-left"></i>Previous</button>
  <button class="main-btn icon-right" (click)="updateStep(3)" [disabled]="!promotionCostValid">Next<i class="fa fa-angle-right"></i></button>
</div>

And in the controller:

checkPromotionCost() {
  this.promotionCostValid = true;
  this.promotionOptions.forEach(promotion => {
    if (promotion.key && promotion.cost === '') {
      this.promotionCostValid = false;
    }
  });
}


问:
How can I copy a string variable to another character by character without defining size of target variable?
I was writing a program where I need to copy a string (length unknown initially) to another string character by character.

I write this code that runs perfectly.

```<code>string a = "Hello";
string b( a.length(), 'a');
for (int i = 0; i < a.length(); i++)
    b[i] = a[i];
</code>```

But as the size of the string in C++ is calculated dynamically as

```<code>string k = "Hello";
string l = "Hello World";
string m = k;
m = l;
</code>```

won't give any error. So it is clear that size of a string variable is changing dynamically according to the requirement.

So I tried the same without defining the size of the variable b.

```<code>string a = "Hello";
string b;
for (int i = 0; i < a.length(); i++)
    b[i] = a[i];
</code>```

But in this case, my program is crashing and saying String subscript out of range.

Why not in this case the size of variable b is increasing?
What is the cause of the error and how can I achieve this without mentioning the size of any variable?

答:
If you must, you can use push_back:

```<code>string a = "Hello";
string b;
for (int i = 0; i < a.length(); i++)
    b.push_back(a[i]);
</code>```

or even1

```<code>string a = "Hello";
string b;
for (auto c : a)
    b.push_back(c);
</code>```

But why?

Reference: http://en.cppreference.com/w/cpp/string/basic_string/push_back

1 But don't do this if a is changed in any way: the underlying iterators will be invalidated.

Body:
I was writing a program where I need to copy a string (length unknown initially) to another string character by character.

I write this code that runs perfectly.

string a = "Hello";
string b( a.length(), 'a');
for (int i = 0; i < a.length(); i++)
    b[i] = a[i];

But as the size of the string in C++ is calculated dynamically as

string k = "Hello";
string l = "Hello World";
string m = k;
m = l;

won't give any error. So it is clear that size of a string variable is changing dynamically according to the requirement.

So I tried the same without defining the size of the variable b.

string a = "Hello";
string b;
for (int i = 0; i < a.length(); i++)
    b[i] = a[i];

But in this case, my program is crashing and saying String subscript out of range.

Why not in this case the size of variable b is increasing?
What is the cause of the error and how can I achieve this without mentioning the size of any variable?

Body:
If you must, you can use push_back:

string a = "Hello";
string b;
for (int i = 0; i < a.length(); i++)
    b.push_back(a[i]);

or even1

string a = "Hello";
string b;
for (auto c : a)
    b.push_back(c);

But why?

Reference: http://en.cppreference.com/w/cpp/string/basic_string/push_back

1 But don't do this if a is changed in any way: the underlying iterators will be invalidated.


问:
Case within a Select returning "missing expression ORA-00905"
this is my first post here, I'd like to ask for help on a theoretically simple query.

The current query I'm creating is to try and generate a random number, which will be identified as even or odd. Depending on that value, it should print either "M" as even, or "W" as odd. Though when I try using a case inside the select, I'm getting the "missing keyword" error. This is my following code:

```<code>select
  case
    when mod(round(dbms_random.value(1,100)),2) = 0 then dbms_output.put_line('M');
    when mod(round(dbms_random.value(1,100)),2) = 1 then dbms_output.put_line('W');
  end
from dual
</code>```

I've tried checking the website for similar problems, and while I've found similar problems and people getting the solution correctly, I don't quite know what I'm missing here. When I run the select alone, I get the even or odd number I want to get, but not when I try to print out a result.

答:
You get the error because of the semicolons.

Also you are calling the random function twice and thus get two different random values. I would use IF-THEN-ELSE instead of a SELECT statement, since the latter one cannot print.

```<code>IF mod(round(dbms_random.value(1,100)),2) = 0 THEN
    dbms_output.put_line('M');
ELSE
    dbms_output.put_line('W');
END IF;
</code>```

Body:
this is my first post here, I'd like to ask for help on a theoretically simple query.

The current query I'm creating is to try and generate a random number, which will be identified as even or odd. Depending on that value, it should print either "M" as even, or "W" as odd. Though when I try using a case inside the select, I'm getting the "missing keyword" error. This is my following code:

select
  case
    when mod(round(dbms_random.value(1,100)),2) = 0 then dbms_output.put_line('M');
    when mod(round(dbms_random.value(1,100)),2) = 1 then dbms_output.put_line('W');
  end
from dual

I've tried checking the website for similar problems, and while I've found similar problems and people getting the solution correctly, I don't quite know what I'm missing here. When I run the select alone, I get the even or odd number I want to get, but not when I try to print out a result.

Body:
You get the error because of the semicolons.

Also you are calling the random function twice and thus get two different random values. I would use IF-THEN-ELSE instead of a SELECT statement, since the latter one cannot print.

IF mod(round(dbms_random.value(1,100)),2) = 0 THEN
    dbms_output.put_line('M');
ELSE
    dbms_output.put_line('W');
END IF;


问:
Can I do everything with react.js just using CDN libraries, without any installations at all ?
Can I do everything with react.js just using CDN libraries, without any installations at all ? </p>

<p>For example can I always use JavaScript libraries like this? </p>

```<code><script src="https://cdn/X.js"></script>

const X = window.X;
</code>```

答:
Yes, this is absolutely possible, and there are loads of resources. It's no different from building any other JS application on a given framework:

http://jamesknelson.com/learn-raw-react-no-jsx-flux-es6-webpack/

https://reactjs.org/docs/react-without-jsx.html

https://medium.com/@clmyles/react-without-npm-babel-or-webpack-1e9a6049714

https://twitter.com/JedWatson/status/927445144453857280

BUT... there's a lot to be said for the current React development ecosystem that makes the build tooling (i.e. Babel, Webpack, ESLint, Prettier, Glamorous, etc.) very enticing. And the use of JSX is an incredible advantage, for the sake of quick prototyping alone, which you will not be able to utilize if you can't build. All in all, building out a comfortable, custom development environment can take time and be pain, however the ROI is tangible. Which is why I'd suggest CRA:

https://github.com/facebookincubator/create-react-app

Body:
Can I do everything with react.js just using CDN libraries, without any installations at all ?

For example can I always use JavaScript libraries like this?

const X = window.X;