问:
SQL monthly statement using recursive cte
I am trying to create a monthly bank account statement from a transaction table which has all history records.
I would like have opening balance as the first row and then the current months transaction with the updated balance at that time using recursive cte.
I know this can be done by table update too but recursion is what i am looking for.

the table structure would be like:

```<code>declare @temp table (date datetime,tran_id int,cust_id int,tran_type char,amount int)
insert into @temp values('2017-06-06 22:05:10.703',1,1,'c',700),
('2017-06-12 22:05:10.703',2,1,'d',100),('2017-06-20 22:05:10.703',3,1,'c',200),
('2017-06-26 22:05:10.703',4,1,'d',450),(getdate()+1,5,1,'d',200),
(getdate()+2,6,1,'d',200),(getdate()+3,7,1,'c',500),
(getdate()+4,8,1,'d',300),(getdate()+5,9,1,'d',200),
('2017-06-18 22:05:10.703',12,1,'d',100)
</code>```

So in here there is transaction for month 6 and 7.
The opening balance of current month would be sum of all transactions in June which will be used as anchor to get recursive balance.
Now i would like the select query to have date,tran_id,cust_id,credit,debit,balance as the result set.

So if table has data like:

```<code>date                   tran_id  cust_id tran_type   amount
2017-06-06 22:05:10.703 1   1   c   700
2017-06-12 22:05:10.703 2   1   d   100
2017-06-20 22:05:10.703 3   1   c   200
2017-06-26 22:05:10.703 4   1   d   450
2017-07-08 16:34:24.817 5   1   d   200
2017-07-09 16:34:24.817 6   1   d   200
2017-07-10 16:34:24.817 7   1   c   500
2017-07-11 16:34:24.817 8   1   d   300
2017-07-12 16:34:24.817 9   1   d   200
2017-06-18 22:05:10.703 12  1   d   100

The monthly statement for month 7 should be like:
opening balance of 250

date                     tran_id    cust_id credit  debit   balance
2017-07-08 16:40:56.810     5        1      NULL     200    50
2017-07-09 16:40:56.810     6        1      NULL     200    -150
2017-07-10 16:40:56.810     7        1      500      NULL   350
2017-07-11 16:40:56.810     8        1      NULL     300    -50
2017-07-12 16:40:56.810     9        1      NULL     200    -250
</code>```

i have tried using recursive cte and sum windowed  function but it does not give continuous balance just a row by row balance.

Also using aggregate functions in a cte is a no no so stuck at that too.

```<code>;with cte as
(
select cust_id,sum(case when tran_type='c' then amount*1 else amount*-1 end)
as 'opening balance' from @temp
where MONTH(date)=6 group by cust_id
),

cte2 as
(
select * from cte
union all
select t.cust_id,amount+[opening balance] as 'balance1' from @temp t join
cte2 c on c.cust_id=t.cust_id
where MONTH(date)=7
)
select * from cte2
</code>```

OR

```<code>;with cte as
(
select cust_id,sum(case when tran_type='c' then amount*1 else amount*-1 end)
as 'opening balance' from @temp
where MONTH(date)=6 group by cust_id
union all
select t.cust_id,SUM(amount+[opening balance]) as 'balance1' from @temp t
join cte c on c.cust_id=t.cust_id
where MONTH(date)=7
)
select * from cte
option (MAXRECURSION 1000)
</code>```

what am i missing?

答:
For older versions, you can use CROSS APPLY to calculate the running balance

```<code>;WITH opening_balance_cte
     AS (SELECT cust_id,
                Sum(CASE WHEN tran_type = 'c' THEN amount ELSE -amount END) AS opening_balance
         FROM   Yourtable
         WHERE  [date] < '2017-07-01'
         GROUP  BY cust_id)
SELECT *,
       balance
FROM   Yourtable a
       JOIN opening_balance_cte ob
         ON ob.cust_id = a.cust_id
       CROSS apply (SELECT ob.opening_balance + Sum(CASE WHEN tran_type = 'c' THEN amount ELSE -amount END) AS balance
                    FROM   Yourtable b
                    WHERE  a.cust_id = b.cust_id
                           AND a.tran_id >= b.tran_id
                           AND b.[date] >= '2017-07-01'
                           AND b.[date] < '2017-08-01') cs
WHERE  a.[date] >= '2017-07-01'
       AND a.[date] < '2017-08-01'
</code>```

If you really want to know how to achieve this using Recursive CTE then

```<code>;WITH opening_balance_cte
     AS (SELECT cust_id,
                Sum(CASE WHEN tran_type = 'c' THEN amount ELSE -amount END) AS opening_balance
         FROM   @temp
         WHERE  [date] < '2017-07-01'
         GROUP  BY cust_id),
     rec_cte
     AS (SELECT TOP 1 a.*,
                      opening_balance + CASE WHEN tran_type = 'c' THEN amount ELSE -amount END AS balance
         FROM   @temp a
                JOIN opening_balance_cte o
                  ON a.cust_id = o.cust_id
         WHERE  a.[date] >= '2017-07-01'
                AND a.[date] < '2017-08-01'
         ORDER  BY a.[date] ASC
         UNION ALL
         SELECT t.*,
                rc.balance + CASE WHEN t.tran_type = 'c' THEN t.amount ELSE -t.amount END
         FROM   rec_cte rc
                JOIN @temp t
                  ON t.cust_id = rc.cust_id
                     AND t.tran_id = rc.tran_id + 1)
SELECT *
FROM   rec_cte
</code>```

Body:
I am trying to create a monthly bank account statement from a transaction table which has all history records.
I would like have opening balance as the first row and then the current months transaction with the updated balance at that time using recursive cte.
I know this can be done by table update too but recursion is what i am looking for.

the table structure would be like:

declare @temp table (date datetime,tran_id int,cust_id int,tran_type char,amount int)
insert into @temp values('2017-06-06 22:05:10.703',1,1,'c',700),
('2017-06-12 22:05:10.703',2,1,'d',100),('2017-06-20 22:05:10.703',3,1,'c',200),
('2017-06-26 22:05:10.703',4,1,'d',450),(getdate()+1,5,1,'d',200),
(getdate()+2,6,1,'d',200),(getdate()+3,7,1,'c',500),
(getdate()+4,8,1,'d',300),(getdate()+5,9,1,'d',200),
('2017-06-18 22:05:10.703',12,1,'d',100)

So in here there is transaction for month 6 and 7.
The opening balance of current month would be sum of all transactions in June which will be used as anchor to get recursive balance.
Now i would like the select query to have date,tran_id,cust_id,credit,debit,balance as the result set.

So if table has data like:

date                   tran_id  cust_id tran_type   amount
2017-06-06 22:05:10.703 1   1   c   700
2017-06-12 22:05:10.703 2   1   d   100
2017-06-20 22:05:10.703 3   1   c   200
2017-06-26 22:05:10.703 4   1   d   450
2017-07-08 16:34:24.817 5   1   d   200
2017-07-09 16:34:24.817 6   1   d   200
2017-07-10 16:34:24.817 7   1   c   500
2017-07-11 16:34:24.817 8   1   d   300
2017-07-12 16:34:24.817 9   1   d   200
2017-06-18 22:05:10.703 12  1   d   100

The monthly statement for month 7 should be like:
opening balance of 250

date                     tran_id    cust_id credit  debit   balance
2017-07-08 16:40:56.810     5        1      NULL     200    50
2017-07-09 16:40:56.810     6        1      NULL     200    -150
2017-07-10 16:40:56.810     7        1      500      NULL   350
2017-07-11 16:40:56.810     8        1      NULL     300    -50
2017-07-12 16:40:56.810     9        1      NULL     200    -250

i have tried using recursive cte and sum windowed  function but it does not give continuous balance just a row by row balance.

Also using aggregate functions in a cte is a no no so stuck at that too.

;with cte as
(
select cust_id,sum(case when tran_type='c' then amount*1 else amount*-1 end)
as 'opening balance' from @temp
where MONTH(date)=6 group by cust_id
),

cte2 as
(
select * from cte
union all
select t.cust_id,amount+[opening balance] as 'balance1' from @temp t join
cte2 c on c.cust_id=t.cust_id
where MONTH(date)=7
)
select * from cte2

OR

;with cte as
(
select cust_id,sum(case when tran_type='c' then amount*1 else amount*-1 end)
as 'opening balance' from @temp
where MONTH(date)=6 group by cust_id
union all
select t.cust_id,SUM(amount+[opening balance]) as 'balance1' from @temp t
join cte c on c.cust_id=t.cust_id
where MONTH(date)=7
)
select * from cte
option (MAXRECURSION 1000)

what am i missing?

Body:
For older versions, you can use CROSS APPLY to calculate the running balance

;WITH opening_balance_cte
     AS (SELECT cust_id,
                Sum(CASE WHEN tran_type = 'c' THEN amount ELSE -amount END) AS opening_balance
         FROM   Yourtable
         WHERE  [date] < '2017-07-01'
         GROUP  BY cust_id)
SELECT *,
       balance
FROM   Yourtable a
       JOIN opening_balance_cte ob
         ON ob.cust_id = a.cust_id
       CROSS apply (SELECT ob.opening_balance + Sum(CASE WHEN tran_type = 'c' THEN amount ELSE -amount END) AS balance
                    FROM   Yourtable b
                    WHERE  a.cust_id = b.cust_id
                           AND a.tran_id >= b.tran_id
                           AND b.[date] >= '2017-07-01'
                           AND b.[date] < '2017-08-01') cs
WHERE  a.[date] >= '2017-07-01'
       AND a.[date] < '2017-08-01'

If you really want to know how to achieve this using Recursive CTE then

;WITH opening_balance_cte
     AS (SELECT cust_id,
                Sum(CASE WHEN tran_type = 'c' THEN amount ELSE -amount END) AS opening_balance
         FROM   @temp
         WHERE  [date] < '2017-07-01'
         GROUP  BY cust_id),
     rec_cte
     AS (SELECT TOP 1 a.*,
                      opening_balance + CASE WHEN tran_type = 'c' THEN amount ELSE -amount END AS balance
         FROM   @temp a
                JOIN opening_balance_cte o
                  ON a.cust_id = o.cust_id
         WHERE  a.[date] >= '2017-07-01'
                AND a.[date] < '2017-08-01'
         ORDER  BY a.[date] ASC
         UNION ALL
         SELECT t.*,
                rc.balance + CASE WHEN t.tran_type = 'c' THEN t.amount ELSE -t.amount END
         FROM   rec_cte rc
                JOIN @temp t
                  ON t.cust_id = rc.cust_id
                     AND t.tran_id = rc.tran_id + 1)
SELECT *
FROM   rec_cte


来源: stackexchange

问:
Update and Change WordPress URLs in database with REGEXP
I want to change several hundred URLs to the graphics inside the posts. URLs are links to images that are on an inactive imagehost. I had backup and I loading them into a new imagehost, but I have a problem with replacement, because old links have variable, random length.

For example:
hostname.org/image/ciiidl/file_name.jpeg

Where "ciiidl" is generate random

I wrote a command in SQL, but unfortunately did not replace URLs:
UPDATE wp_posts SET post_content = REPLACE (post_content, 'https://old_hostname.org/image/[^a-zA-Z0-9]/','https://new_hostname.com/Img/')

I need to use REGEXP, but I do not know how to combine with REPLACE.

答:
Previously I made this changes, but when the link it was static:

UPDATE wp_posts SET post_content= REPLACE(post_content, 'https://old_hostname.org/image/','https://new_hostname.com/img/')

I just changed the beginning of the url. The file name has been unchanged.

ContentLicense: CC BY-SA 3.0


问:
Can integer promotion happen in the reverse order(eg. long int to int) in variadic functions like printf()?
```<code>#include<stdio.h>
int main() {
    long a = 9;
    printf("a = %d",a);//output is 9 but with a warning 'expecting long int'
}
</code>```

Why can't long here be converted to int?

答:
Variadic functions in general and printf family in particular, are odd special cases. They are notorious for their non-existent type safety, so if you pass the wrong type or use the wrong format string, you invoke undefined behavior and anything can happen.

In your case, most likely int and long happen to have the same representation so the program works despite the warning.

In the case of a regular function though, there is a kind of "demotion" taking place if you pass a larger integer type to a function expecting a smaller one. When this happens, you trigger a conversion from the larger type to the smaller, which is well-defined. (The result will however be compiler-specific if you mix types of different signedness.)

Compilers tend to warn against such implicit conversions, so it is better to do the conversion explicitly with a cast.

Body:
#include<stdio.h>
int main() {
    long a = 9;
    printf("a = %d",a);//output is 9 but with a warning 'expecting long int'
}

Why can't long here be converted to int?


问:
Getting 'CategoryNewForm' is not defined no-undef while working with redux-form
I am curretly leanring redux-react and developing a simple application.
I wanted to use redux-form into my app. In my components i have following code

components/AddNewCategory.jsx:

```<code>import React, { Component } from 'react';
import { reduxForm } from 'redux-form';

class CategoryNew extends Component {
    render() {
        const { fields: { title, desc }, handleSubmit } = this.props;
        console.log(title);

        return (
            <form onSubmit={handleSubmit}>
                <h3>Create A New Category</h3>
                <div className="form-group">
                    <label>title: </label>
                    <input type="text" className="form-control" />
                </div>
                <div className="form-group">
                    <label>Description: </label>
                    <input type="text" className="form-control" />
                </div>
                <button type="submit" className="btn btn-primary">Submit</button>
            </form>
        );
    }
}
export default reduxForm({
    form: CategoryNewForm,
    fields: ['title', 'desc']
})(CategoryNew);
</code>```

When I runs application I am getting following error:
./src/app/admin/components/add_new_category/AddNewCategory.jsx
  Line 28:  'CategoryNewForm' is not defined  no-undef
Search for the keywords to learn more about each error.

Please suggest me how do I can solve this error. Thanks in advance.

答:
```<code>export default reduxForm({
    form: 'CategoryNewForm',
    fields: ['title', 'desc']
})(CategoryNew);
</code>```

form name should be string

Body:
I am curretly leanring redux-react and developing a simple application.
I wanted to use redux-form into my app. In my components i have following code

components/AddNewCategory.jsx:

import React, { Component } from 'react';
import { reduxForm } from 'redux-form';

class CategoryNew extends Component {
    render() {
        const { fields: { title, desc }, handleSubmit } = this.props;
        console.log(title);

        return (
            <form onSubmit={handleSubmit}>

Create A New Category

                    title:
                    <input type="text" className="form-control" />

                    Description:
                    <input type="text" className="form-control" />

                <button type="submit" className="btn btn-primary">Submit</button>
            </form>
        );
    }
}
export default reduxForm({
    form: CategoryNewForm,
    fields: ['title', 'desc']
})(CategoryNew);

When I runs application I am getting following error:
./src/app/admin/components/add_new_category/AddNewCategory.jsx
  Line 28:  'CategoryNewForm' is not defined  no-undef
Search for the keywords to learn more about each error.

Please suggest me how do I can solve this error. Thanks in advance.

Body:
export default reduxForm({
    form: 'CategoryNewForm',
    fields: ['title', 'desc']
})(CategoryNew);

form name should be string


问:
What is a good naming convention for Rails custom controller actions regarding formulation (noun vs verb)?
When defining new actions in controllers I often find myself asking how should I formulate the name of the action correctly. Rails default CRUD actions all seem to follow the pattern of verb (new, create, edit, update, destroy, index) but is it a bad habit to use a noun? For ex. payment_history?

I found a lot of information describing the naming conventions for different files and classes and regarding the proper syntax but none about controller#actions from formulation part.

EDIT: I am asking about custom-defined actions not renaming the Rails default CRUD actions.

答:
Assuming you're following the conventional RESTful methodology, it is going to be easiest to follow the convention of index, show, new/create, edit/update and destroy. That is, unless you have a well-grounded reason not to, but then you ought to be able to justify to yourself and possible other developers why the default action names are not sufficient.

Using the default method names, you get a lot of the routing etc. stuff "for free", as Rails assumes you're following the convention. Also, do note that things that might not immediately sound like "resources" can often easily be modeled as such, e.g. your example "payment_history" may well be a subresource of another resource (a User?), in which  case you'd have a singular nested route such as GET /users/{user_id}/payment_history. This route would then call PaymentHistoryController#show, as demonstrated in the Rails guide section on singular resources.


问:
Gtk Notebook call function every time a certain tab is selected
I want a tab on my notebook that pretty much does the same like a button. Every time I select this tab it should execute a certain job (for example print('something') ).

How do I get it to execute every time I open it? Right now it just executes once on startup and that's it.

If someone has some advice on this subject I'd really apreciate some help!

答:
You can use the switch-page signal.

The callback prototype includes the page number id so that you can figure out to which page you are switching.

void user_function (GtkNotebook *notebook,
                 GtkWidget   *page,
                 guint        page_num,
                 gpointer     user_data)

ContentLicense: CC BY-SA 4.0


问:
Dependency installation for Python (Django) project
I'm new to Python, but I had a requirement at my work-place. Another programmer is developing a project on Python, Django framework, and my task is to find a way in which this project will be executed at any computer.
So, I'm talking about something like Composer for PHP. I need an easiest way that at debian branch to write in terminal a command, that will find kind of "composer.json" file on that project, will read all the required software, modules, libraries and install it step-by-step on PC.

Any ideas how to do it in the easiest way? Thanks.

答:
Since you have not talked about virtual environment, assumed that you already setup the environment and activated it.First get all the libraries lists in requirement.txt file in your project directory by typing below command,

```<code>pip freeze > requirements.txt
</code>```

when you need to setup project in another system just run this

```<code>pip install -r requirements.txt
</code>```

All the dependency will be installed in your project enviornment.

Body:
Since you have not talked about virtual environment, assumed that you already setup the environment and activated it.First get all the libraries lists in requirement.txt file in your project directory by typing below command,

pip freeze > requirements.txt

when you need to setup project in another system just run this

pip install -r requirements.txt

All the dependency will be installed in your project enviornment.


问:
If condition inside of map() React
I have a map()function that needs to display views based on a condition. I've looked at the React documentation on how to write conditions and this is how you can write a condition:

```<code>{if (loggedIn) ? (
  // Hello!
) : (
  // ByeBye!
)}
</code>```

Here's the link: https://facebook.github.io/react/docs/conditional-rendering.html#inline-if-else-with-conditional-operator

So, I tried to take that knowledge and implemant it in my React app. And it turned out like this:

```<code>render() {
  return (
    <div>
      <div className="box">
        {this.props.collection.ids
          .filter(
            id =>
              // note: this is only passed when in top level of document
              this.props.collection.documents[id][
                this.props.schema.foreignKey
              ] === this.props.parentDocumentId
          )
          .map(id =>
            {if (this.props.schema.collectionName.length < 0 ? (

              <Expandable>
                <ObjectDisplay
                  key={id}
                  parentDocumentId={id}
                  schema={schema[this.props.schema.collectionName]}
                  value={this.props.collection.documents[id]}
                />
              </Expandable>

            ) : (
              <h1>hejsan</h1>
            )}
          )}
      </div>
    </div>
  )
}
</code>```

But it doesn't work..! Here's the error:

I appreciate all the help I can get!

答:
You are using both ternary operator and if condition, use any one.

By ternary operator:

```<code>.map(id => {
    return this.props.schema.collectionName.length < 0 ?
        <Expandable>
            <ObjectDisplay
                key={id}
                parentDocumentId={id}
                schema={schema[this.props.schema.collectionName]}
                value={this.props.collection.documents[id]}
            />
        </Expandable>
    :
        <h1>hejsan</h1>
}
</code>```

By if condition:

```<code>.map(id => {
    if(this.props.schema.collectionName.length < 0)
        return <Expandable>
                  <ObjectDisplay
                      key={id}
                      parentDocumentId={id}
                      schema={schema[this.props.schema.collectionName]}
                      value={this.props.collection.documents[id]}
                  />
              </Expandable>
    return <h1>hejsan</h1>
}
</code>```

Title: If condition inside of map() React

Body:
I have a map()function that needs to display views based on a condition. I've looked at the React documentation on how to write conditions and this is how you can write a condition:

{if (loggedIn) ? (
  // Hello!
) : (
  // ByeBye!
)}

Here's the link: https://facebook.github.io/react/docs/conditional-rendering.html#inline-if-else-with-conditional-operator

So, I tried to take that knowledge and implemant it in my React app. And it turned out like this:

render() {
  return (

        {this.props.collection.ids
          .filter(
            id =>
              // note: this is only passed when in top level of document
              this.props.collection.documents[id][
                this.props.schema.foreignKey
              ] === this.props.parentDocumentId
          )
          .map(id =>
            {if (this.props.schema.collectionName.length < 0 ? (

              <Expandable>
                <ObjectDisplay
                  key={id}
                  parentDocumentId={id}
                  schema={schema[this.props.schema.collectionName]}
                  value={this.props.collection.documents[id]}
                />
              </Expandable>

            ) : (

hejsan

            )}
          )}

  )
}

But it doesn't work..! Here's the error:

I appreciate all the help I can get!

Body:
You are using both ternary operator and if condition, use any one.

By ternary operator:

.map(id => {
    return this.props.schema.collectionName.length < 0 ?
        <Expandable>
            <ObjectDisplay
                key={id}
                parentDocumentId={id}
                schema={schema[this.props.schema.collectionName]}
                value={this.props.collection.documents[id]}
            />
        </Expandable>
    :
        <h1>hejsan</h1>
}

By if condition:

.map(id => {
    if(this.props.schema.collectionName.length < 0)
        return <Expandable>
                  <ObjectDisplay
                      key={id}
                      parentDocumentId={id}
                      schema={schema[this.props.schema.collectionName]}
                      value={this.props.collection.documents[id]}
                  />
              </Expandable>
    return <h1>hejsan</h1>
}


问:
Append a Parent to a Child Element using Jquery
I need Help for append a Child element to a parent Element. This is my code.I need to put the $input inside the $temp.

Thanks

```<code>function CaixaPin(){

  var $temp;
  $temp = $("<div></div>");
  $temp.addClass("caixa");

  var $input;
  for(var i=0; i<4; i++){
    $input = $("<div></div>");
    $input.addClass("caixaPin");
    $("body").append($input);
  }

  $("body").append($temp);

}

CaixaPin();
</code>```

答:
You should iterate loop of $input after append $temp.

Try below example,

function CaixaPin(){
    var $temp;
    $temp = $("
$temp
");
    $temp.addClass("caixa");

    $("body").append($temp);

    var $input;
    for(var i=0; i<4; i++){
        $input = $("
$input of "+i+"
");
        $input.addClass("caixaPin");
        $(".caixa").append($input);
    }
    console.log("Inspect your html code and check.");
}
CaixaPin();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script></code>```

Body:
I need Help for append a Child element to a parent Element. This is my code.I need to put the $input inside the $temp.

Thanks

function CaixaPin(){

  var $temp;
  $temp = $("

");
  $temp.addClass("caixa");

  var $input;
  for(var i=0; i<4; i++){
    $input = $("

");
    $input.addClass("caixaPin");
    $("body").append($input);
  }

  $("body").append($temp);

}

CaixaPin();

Body:
You should iterate loop of $input after append $temp.

Try below example,

function CaixaPin(){
    var $temp;
    $temp = $("<div>$temp</div>");
    $temp.addClass("caixa");

    $("body").append($temp);

    var $input;
    for(var i=0; i<4; i++){
        $input = $("<div>$input of "+i+"</div>");
        $input.addClass("caixaPin");
        $(".caixa").append($input);
    }
    console.log("Inspect your html code and check.");
}
CaixaPin();

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


问:
Find a string and location in PDF file using iTextSharp using ASP.Net C#
I am trying to find a string and it's location in a PDF using iTextSharp in Asp.net C# for editing. But so far with the help available on Google I am unable to do it. This is the current code but it does read text chunk by chunk but couldn't find the required text. Need help Thanks

```<code>public class RectAndText
    {
        public iTextSharp.text.Rectangle Rect;
        public String Text;
        public RectAndText(iTextSharp.text.Rectangle rect, String text)
        {
            this.Rect = rect;
            this.Text = text;
        }
    }

    public class MyLocationTextExtractionStrategy : LocationTextExtractionStrategy
    {
        public List<RectAndText> myPoints = new List<RectAndText>();
        public String TextToSearchFor { get; set; }
        public System.Globalization.CompareOptions CompareOptions { get; set; }

        public MyLocationTextExtractionStrategy(String textToSearchFor, System.Globalization.CompareOptions compareOptions = System.Globalization.CompareOptions.None)
        {
            this.TextToSearchFor = textToSearchFor;
            this.CompareOptions = compareOptions;
        }
        public override void RenderText(TextRenderInfo renderInfo)
        {
            base.RenderText(renderInfo);
            var startPosition = System.Globalization.CultureInfo.CurrentCulture.CompareInfo.IndexOf(renderInfo.GetText(), this.TextToSearchFor, this.CompareOptions);
            if (startPosition < 0)
            {
                return;
            }
            var chars = renderInfo.GetCharacterRenderInfos().Skip(startPosition).Take(this.TextToSearchFor.Length).ToList();
            var firstChar = chars.First();
            var lastChar = chars.Last();

            var bottomLeft = firstChar.GetDescentLine().GetStartPoint();
            var topRight = lastChar.GetAscentLine().GetEndPoint();
            var rect = new iTextSharp.text.Rectangle(
                                                    bottomLeft[Vector.I1],
                                                    bottomLeft[Vector.I2],
                                                    topRight[Vector.I1],
                                                    topRight[Vector.I2]
                                                    );

            this.myPoints.Add(new RectAndText(rect, this.TextToSearchFor));
        }
    }
</code>```

Call function

```<code>string thisDir = System.Web.Hosting.HostingEnvironment.MapPath("~/");
var testFile = thisDir + "example.pdf";
var t = new MyLocationTextExtractionStrategy("searchstring"); //need to search this searchstring

using (var r = new PdfReader(testFile))
{
   var ex = PdfTextExtractor.GetTextFromPage(r, 1, t);
}

foreach (var p in t.myPoints)
{
   Console.WriteLine(string.Format("Found text {0} at {1}x{2}", p.Text, p.Rect.Left, p.Rect.Bottom));
}
</code>```

答:
This can easily be managed (in iText7) using RegexBasedLocationExtractionStrategy.
This class can be constructed using a regular expression and pushes out the locations of the text matching the expression. Even if you can not switch to iText7, you can still have a look at the source code and see how we implemented it.</p>

Body:
I am trying to find a string and it's location in a PDF using iTextSharp in Asp.net C# for editing. But so far with the help available on Google I am unable to do it. This is the current code but it does read text chunk by chunk but couldn't find the required text. Need help Thanks

public class RectAndText
    {
        public iTextSharp.text.Rectangle Rect;
        public String Text;
        public RectAndText(iTextSharp.text.Rectangle rect, String text)
        {
            this.Rect = rect;
            this.Text = text;
        }
    }

    public class MyLocationTextExtractionStrategy : LocationTextExtractionStrategy
    {
        public List<RectAndText> myPoints = new List<RectAndText>();
        public String TextToSearchFor { get; set; }
        public System.Globalization.CompareOptions CompareOptions { get; set; }

        public MyLocationTextExtractionStrategy(String textToSearchFor, System.Globalization.CompareOptions compareOptions = System.Globalization.CompareOptions.None)
        {
            this.TextToSearchFor = textToSearchFor;
            this.CompareOptions = compareOptions;
        }
        public override void RenderText(TextRenderInfo renderInfo)
        {
            base.RenderText(renderInfo);
            var startPosition = System.Globalization.CultureInfo.CurrentCulture.CompareInfo.IndexOf(renderInfo.GetText(), this.TextToSearchFor, this.CompareOptions);
            if (startPosition < 0)
            {
                return;
            }
            var chars = renderInfo.GetCharacterRenderInfos().Skip(startPosition).Take(this.TextToSearchFor.Length).ToList();
            var firstChar = chars.First();
            var lastChar = chars.Last();

            var bottomLeft = firstChar.GetDescentLine().GetStartPoint();
            var topRight = lastChar.GetAscentLine().GetEndPoint();
            var rect = new iTextSharp.text.Rectangle(
                                                    bottomLeft[Vector.I1],
                                                    bottomLeft[Vector.I2],
                                                    topRight[Vector.I1],
                                                    topRight[Vector.I2]
                                                    );

            this.myPoints.Add(new RectAndText(rect, this.TextToSearchFor));
        }
    }

Call function

string thisDir = System.Web.Hosting.HostingEnvironment.MapPath("~/");
var testFile = thisDir + "example.pdf";
var t = new MyLocationTextExtractionStrategy("searchstring"); //need to search this searchstring

using (var r = new PdfReader(testFile))
{
   var ex = PdfTextExtractor.GetTextFromPage(r, 1, t);
}

foreach (var p in t.myPoints)
{
   Console.WriteLine(string.Format("Found text {0} at {1}x{2}", p.Text, p.Rect.Left, p.Rect.Bottom));
}


问:
How to create an update trigger where an insert operation is performed?
Consider below is my table,

```<code>register_device

id | user_id | device_id | status |

1  |  12     |  1234      |   1    |
2  |  1      |  5678      |   1    |
3  |  11     |  1456      |   1    |
</code>```

Logic for trigger:

Before inserting value in register_device table, i want to check whether the new device_id value already exist in register_device table. If in case the value is already present its status need to be changed to 0, before inserting a new value, like below.

```<code>id | user_id | device_id | status |

1  |  12     |  1234      |   0    |
2  |  1      |  5678      |   1    |
3  |  11     |  1456      |   1    |
4  |  14     |  1234      |   1    |
</code>```

So when i run insert operation through coding, trigger need to perform the above logic by its own in database.

答:
Your current approach is going to make it very difficult to implement your insert logic for several reasons:

You can't use a trigger because a trigger cannot modify the table which caused it to fire

Using ON DUPLICATE KEY UPDATE also won't fly because you actually want to insert the record even if an update also happens

I propose a slightly different table design:

```<code>id | user_id | device_id | status_timestamp
</code>```

The only change here is that status has become status_timestamp, which is a timestamp column.  You can insert records and use NOW() for the current timestamp value.

Logically speaking, any record which does not have the max value of status_timestamp for a given device_id would correspond to a zero status in your original table.  And records having the max status_timestamp value for a given device_id would correspond to a status of 1.

For example, to get the status=1 record for device_id 1234 you could use the following query:

```<code>SELECT *
FROM register_device
WHERE device_id = 1234
ORDER BY status_timestamp DESC
LIMIT 1
</code>```

And to get all the status=0 records for device_id 1234 you could use:

```<code>SELECT *
FROM register_device
WHERE device_id = 1234 AND
      status_timestamp < (SELECT MAX(status_timestamp) FROM register_device
                          WHERE device_id = 1234)
</code>```

Body:
Consider below is my table,

register_device

id | user_id | device_id | status |

1  |  12     |  1234      |   1    |
2  |  1      |  5678      |   1    |
3  |  11     |  1456      |   1    |

Logic for trigger:

Before inserting value in register_device table, i want to check whether the new device_id value already exist in register_device table. If in case the value is already present its status need to be changed to 0, before inserting a new value, like below.

id | user_id | device_id | status |

1  |  12     |  1234      |   0    |
2  |  1      |  5678      |   1    |
3  |  11     |  1456      |   1    |
4  |  14     |  1234      |   1    |

So when i run insert operation through coding, trigger need to perform the above logic by its own in database.

Body:
Your current approach is going to make it very difficult to implement your insert logic for several reasons:

You can't use a trigger because a trigger cannot modify the table which caused it to fire

Using ON DUPLICATE KEY UPDATE also won't fly because you actually want to insert the record even if an update also happens

I propose a slightly different table design:

id | user_id | device_id | status_timestamp

The only change here is that status has become status_timestamp, which is a timestamp column.  You can insert records and use NOW() for the current timestamp value.

Logically speaking, any record which does not have the max value of status_timestamp for a given device_id would correspond to a zero status in your original table.  And records having the max status_timestamp value for a given device_id would correspond to a status of 1.

For example, to get the status=1 record for device_id 1234 you could use the following query:

SELECT *
FROM register_device
WHERE device_id = 1234
ORDER BY status_timestamp DESC
LIMIT 1

And to get all the status=0 records for device_id 1234 you could use:

SELECT *
FROM register_device
WHERE device_id = 1234 AND
      status_timestamp < (SELECT MAX(status_timestamp) FROM register_device
                          WHERE device_id = 1234)


问:
How can we know a new contact is Added to Android?
Hello Guys i m using following code to open Android Add Contact Page ,

```<code>Intent intent1 = new Intent(Intent.ACTION_INSERT);
        intent1.setType(Contacts.CONTENT_ITEM_TYPE);
        intent1.setData(ContactsContract.Contacts.CONTENT_URI);
        startActivityForResult(intent1,300);
</code>```

But as a result code it sends -1 inside onActivityResult function
I want to have the ContactId of the newly added Person , How can we get this?

答:
We can get the Response fron Android Add Contact View by making foloowing function in our activity

```<code>@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (resultCode == RESULT_OK && data != null && requestCode==300) {

        AddNewlyReceivedcontact(ContentUris.parseId(data.getData()));

    }
}
</code>```

Here AddNewlyReceivedcontact is not a android function, it's a user defined function.

ContentLicense: CC BY-SA 2.5

Body:
Hello Guys i m using following code to open Android Add Contact Page ,

Intent intent1 = new Intent(Intent.ACTION_INSERT);
        intent1.setType(Contacts.CONTENT_ITEM_TYPE);
        intent1.setData(ContactsContract.Contacts.CONTENT_URI);
        startActivityForResult(intent1,300);

But as a result code it sends -1 inside onActivityResult function
I want to have the ContactId of the newly added Person , How can we get this?

Body:
We can get the Response fron Android Add Contact View by making foloowing function in our activity

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (resultCode == RESULT_OK && data != null && requestCode==300) {

        AddNewlyReceivedcontact(ContentUris.parseId(data.getData()));

    }
}

Here AddNewlyReceivedcontact is not a android function, it's a user defined function.


问:
How can I call two methods simultaneously using `&`
Instead of calling one method in a block using &,

```<code>objects_array.collect(&:errors)
</code>```

can I call two methods simultaneously using &? I want something like this:

```<code>objects_array.collect(&:errors.full_messages)
</code>```

Is it possible?

答:
Can't do that with a single pass and the shorthand. Either do two passes

```<code>objects_array.collect(&:errors).collect(&:full_messages)
</code>```

or use the full form.

```<code>objects_array.collect{ |obj| obj.errors.full_messages }
</code>```

Body:
Instead of calling one method in a block using &,

objects_array.collect(&:errors)

can I call two methods simultaneously using &? I want something like this:

objects_array.collect(&:errors.full_messages)

Is it possible?

Body:
Can't do that with a single pass and the shorthand. Either do two passes

objects_array.collect(&:errors).collect(&:full_messages)

or use the full form.

objects_array.collect{ |obj| obj.errors.full_messages }


问:
Remove single br in paragraph but not double br?
I have a paragraph with some single
 and double
.

I'd like to add all the single
, but not the double
.

How is that possible?

If I use

```<code>p br {display:none}
</code>```

It hides all the br tags. However, when I have two br, I would like them to still display . . ..  How can we make this work? It seems I can not find any relevant information.

I also tried the following without success:

```<code>p br { content: ' '; }
</code>```

Thanks a lot for your time !

-- edit --

my paragraph is formatted like that:

```<code><p> oremipsum lorem<br/>
orem blalgr<br/><br/>
loremg grthrt
</p>
</code>```

答:
Okay, if you want to show two
 but remove one, then it's simple. You can use + next-child selector:

p {margin: 0;}
br {display: none;}
br + br {display: block; margin-bottom: 2em;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>Hello. One BR below.</p>
<br />
<p>Hello. Two BR below.</p>
<br /><br />
<p>Hello. One BR below.</p>
<br />
<p>Hello. Two BR below.</p>
<br /><br />
<p>Hello. No BR below.</p></code>```

Body:
I have a paragraph with some single
 and double
.

I'd like to add all the single
, but not the double
.

How is that possible?

If I use

p br {display:none}

It hides all the br tags. However, when I have two br, I would like them to still display . . ..  How can we make this work? It seems I can not find any relevant information.

I also tried the following without success:

p br { content: ' '; }

Thanks a lot for your time !

-- edit --

my paragraph is formatted like that:

 oremipsum lorem

orem blalgr

loremg grthrt

Body:
Okay, if you want to show two <br /> but remove one, then it's simple. You can use + next-child selector:

p {margin: 0;}
br {display: none;}
br + br {display: block; margin-bottom: 2em;}

<p>Hello. One BR below.</p>
<br />
<p>Hello. Two BR below.</p>
<br /><br />
<p>Hello. One BR below.</p>
<br />
<p>Hello. Two BR below.</p>
<br /><br />
<p>Hello. No BR below.</p>


问:
Adding class to a div being collided
http://output.jsbin.com/kulobolutu/

This link contains the output of my code.
I have some divs where one div is draggable. You can drag that and collide it with another one. So I want the collided div to move ahead a little in such a way that it does not get out of the screen and adjust itself smoothly to another position.
Please help me in this case, i am badly stuck in this task.
Thanks in advance.

```<code>var overlaps = (function () {
    function getPositions( elem ) {
        var pos, width, height;
        pos = $( elem ).position();
        width = $( elem ).width();
        height = $( elem ).height();
        return [ [ pos.left, pos.left + width ], [ pos.top, pos.top + height ] ];
    }

    function comparePositions( p1, p2 ) {
        var r1, r2;
        r1 = p1[0] < p2[0] ? p1 : p2;
        r2 = p1[0] < p2[0] ? p2 : p1;
        return r1[1] > r2[0] || r1[0] === r2[0];
    }

    return function ( a, b ) {
        var pos1 = getPositions( a ),
            pos2 = getPositions( b );
        return comparePositions( pos1[0], pos2[0] ) && comparePositions( pos1[1], pos2[1] );
    };
})();

function m() {
    var area = $( '#area' )[0],
        box = $( '#box0' )[0],
        html;

    html = $( area ).children().not( box ).map( function ( i ) {
      return '<p>Red box + Box ' + ( i + 1 ) + ' = ' + overlaps( box, this ) + '</p>';
    }).get().join( '' );

    $( '#result' ).html( html );

}

$('#box0').draggable({
  drag: function(){
    m();
  }
});
</code>```

答: html5 and css3 have the div "transform" attribute witch can easily do what u need. here is some documentation https://www.w3schools.com/cssref/css3_pr_transform.asp</p>

Title: Adding class to a div being collided

Body:
http://output.jsbin.com/kulobolutu/

This link contains the output of my code.
I have some divs where one div is draggable. You can drag that and collide it with another one. So I want the collided div to move ahead a little in such a way that it does not get out of the screen and adjust itself smoothly to another position.
Please help me in this case, i am badly stuck in this task.
Thanks in advance.

var overlaps = (function () {
    function getPositions( elem ) {
        var pos, width, height;
        pos = $( elem ).position();
        width = $( elem ).width();
        height = $( elem ).height();
        return [ [ pos.left, pos.left + width ], [ pos.top, pos.top + height ] ];
    }

    function comparePositions( p1, p2 ) {
        var r1, r2;
        r1 = p1[0] < p2[0] ? p1 : p2;
        r2 = p1[0] < p2[0] ? p2 : p1;
        return r1[1] > r2[0] || r1[0] === r2[0];
    }

    return function ( a, b ) {
        var pos1 = getPositions( a ),
            pos2 = getPositions( b );
        return comparePositions( pos1[0], pos2[0] ) && comparePositions( pos1[1], pos2[1] );
    };
})();

function m() {
    var area = $( '#area' )[0],
        box = $( '#box0' )[0],
        html;

    html = $( area ).children().not( box ).map( function ( i ) {
      return '
Red box + Box ' + ( i + 1 ) + ' = ' + overlaps( box, this ) + '
';
    }).get().join( '' );

    $( '#result' ).html( html );

}

$('#box0').draggable({
  drag: function(){
    m();
  }
});


问:
How to change apk name by using gradle like this format?
I'd like to change "app-release.apk" file name to like following when I build an app by using gradle.

```
[format]
(appname of package name)_V(version code)_(yyMMdd)_(R|T)

[explain]
(appname of package name) : example) com.example.myApp -> myApp
(version code) : build version code 2.2.3 -> 223
(yyMMdd) : build date 2015.11.18 -> 151118
(R|T) : if app is release, "R" but debug is "T".
```

If I generate an apk file in release, result is : myApp_V223_151118_R.apk.

How to make a file name like this in gradle?

答:
This may be the shortest way:

```<code>defaultConfig {
    ...
    applicationId "com.blahblah.example"
    versionCode 1
    versionName "1.0"
    setProperty("archivesBaseName", applicationId + "-v" + versionCode + "(" + versionName + ")")
}
</code>```

buildType: like so

```<code>buildTypes {
    debug {
        ...
        versionNameSuffix "-T"
    }
    release {
        ...
        versionNameSuffix "-R"
    }
}
</code>```

Keep in mind, Android Studio adds versionNameSuffix by build type name by default, so you may not need this.

Upd. In new versions of Android Studio you can it write little shorter(thanks for szx comment):

```<code>defaultConfig {
    ...
    archivesBaseName = "$applicationId-v$versionCode($versionName)"
}
</code>```

Body:
I'd like to change "app-release.apk" file name to like following when I build an app by using gradle.

[format]
(appname of package name)_V(version code)_(yyMMdd)_(R|T)

[explain]
(appname of package name) : example) com.example.myApp -> myApp
(version code) : build version code 2.2.3 -> 223
(yyMMdd) : build date 2015.11.18 -> 151118
(R|T) : if app is release, "R" but debug is "T".

If I generate an apk file in release, result is : myApp_V223_151118_R.apk.

How to make a file name like this in gradle?

Body:
This may be the shortest way:

defaultConfig {
    ...
    applicationId "com.blahblah.example"
    versionCode 1
    versionName "1.0"
    setProperty("archivesBaseName", applicationId + "-v" + versionCode + "(" + versionName + ")")
}

buildType: like so

buildTypes {
    debug {
        ...
        versionNameSuffix "-T"
    }
    release {
        ...
        versionNameSuffix "-R"
    }
}

Keep in mind, Android Studio adds versionNameSuffix by build type name by default, so you may not need this.

Upd. In new versions of Android Studio you can it write little shorter(thanks for szx comment):

defaultConfig {
    ...
    archivesBaseName = "$applicationId-v$versionCode($versionName)"
}


答:
Because that's the way variadic functions behave in C language. printf is just a function from the standard library and has no special processing. It is declared as

```<code>int printf(const char restrict *fmt, ...);
</code>```

And the standard (n1256 draft for C99) says (emphasize mine):

6.5.2.2 Function calls
...

  6 If the expression that denotes the called function has a type that does not include a
  prototype, the integer promotions are performed on each argument, and arguments that
  have type float are promoted to double. These are called the default argument
  promotions...

  7 ... The ellipsis notation in a function prototype declarator causes
  argument type conversion to stop after the last declared parameter. The default argument
  promotions are performed on trailing arguments.

That means that on all parameters to printf, float are converted to double and integer promotions occur on integral arguments.

And in 6.3.1.1 Arithmetic operands / Boolean, characters, and integers

2 The following may be used in an expression wherever an int or unsigned int may
  be used:

  — An object or expression with an integer type whose integer conversion rank is less
  than or equal to the rank of int and unsigned int.

  — A bit-field of type _Bool, int, signed int, or unsigned int.

  If an int can represent all values of the original type, the value is converted to an int;
  otherwise, it is converted to an unsigned int. These are called the integer
  promotions.48) All other types are unchanged by the integer promotions.

So as long has a rank greater than int, it is left unchanged by an integer promotion, and the format shall be adapted to accept a long:

```<code>long a = 9;
printf("a = %ld",a);
</code>```

Title: Can integer promotion happen in the reverse order(eg. long int to int) in variadic functions like printf()?

Body:
#include<stdio.h>
int main() {
    long a = 9;
    printf("a = %d",a);//output is 9 but with a warning 'expecting long int'
}

Why can't long here be converted to int?

Body:
Because that's the way variadic functions behave in C language. printf is just a function from the standard library and has no special processing. It is declared as

int printf(const char restrict *fmt, ...);

And the standard (n1256 draft for C99) says (emphasize mine):

6.5.2.2 Function calls
...

  6 If the expression that denotes the called function has a type that does not include a
  prototype, the integer promotions are performed on each argument, and arguments that
  have type float are promoted to double. These are called the default argument
  promotions...

  7 ... The ellipsis notation in a function prototype declarator causes
  argument type conversion to stop after the last declared parameter. The default argument
  promotions are performed on trailing arguments.

That means that on all parameters to printf, float are converted to double and integer promotions occur on integral arguments.

And in 6.3.1.1 Arithmetic operands / Boolean, characters, and integers

2 The following may be used in an expression wherever an int or unsigned int may
  be used:

  — An object or expression with an integer type whose integer conversion rank is less
  than or equal to the rank of int and unsigned int.

  — A bit-field of type _Bool, int, signed int, or unsigned int.

  If an int can represent all values of the original type, the value is converted to an int;
  otherwise, it is converted to an unsigned int. These are called the integer
  promotions.48) All other types are unchanged by the integer promotions.

So as long has a rank greater than int, it is left unchanged by an integer promotion, and the format shall be adapted to accept a long:

long a = 9;
printf("a = %ld",a);


问:
How Pass parameters to JMES path expression in python
Python code.
How to pass parameters to JMESpath instead of hardcoding?

```<code>ext= '.md'
filtered_iterator = page_iterator.search("Contents[?ends_with(Key, `.md`)].Key")
</code>```

I would like to pass ext paramters in the contents path in the place of .md.
What will be the possible way?

答:
```<code>ext= '.md'
filtered_iterator = page_iterator.search("Contents[?ends_with(Key, `%s`)].Key" % ext)
</code>```

Body:
Python code.
How to pass parameters to JMESpath instead of hardcoding?

ext= '.md'
filtered_iterator = page_iterator.search("Contents[?ends_with(Key, `.md`)].Key")

I would like to pass ext paramters in the contents path in the place of .md.
What will be the possible way?


问:
Unable to Pass parameters to MSI thro Msiexec via command prompt
Hii ppl I am trying to pass parameter thro msiexec in command prompt . The problem is eventhough the parameter is passed properly the value doesnt get reflected in the OnBeforeInstallEvent. Therefore the msi doesnt get installed.

The OnBeforeInstall is written  C#.net framework 2.09 (VS 2005) and the event call is given below,

string serverName=Context.Parameters["SERVERNAME"].

For example, In the custom action the parameter is properly declared as /SERVERNAME=[SERVERNAME] so as to access the server name.

There is no problem when I install thro normal UI mode when I pass the parameter thro Msiexec the value doesnt get reflected at the OnBeforeInstall event. I even tried logging the flow of installation thro MSIEXEC /Log , the value gets changed in log ( shown below)

PROPERTY CHANGE: Adding SERVERNAME property. Its value is 'machine1'.

I have given below the msiexec command which I use to pass values,

msiexec.exe /i "C:\Server.msi" /l*v "C:\Server.txt" ALLUSERS=1 REBOOT=ReallySupress  TARGETDIR="C:\Program Files\Server" SERVERNAME="machine1" PORT="9090"

but on reaching ONBeforeInstall the value is empty (show below).

Error 1001. An exception occurred in the OnBeforeInstall event handler of Server.ServicesInstaller. --> Installation cannot be continued as some of the installation parameters are not given.
More Info -Server Name cannot be empty.
DEBUG: Error 2769:  Custom Action _542E7AC5_7403_434A_874B_DE2872A4848D.install did not close 1 MSIHANDLEs.
The installer has encountered an unexpected error installing this package. This may indicate a problem with this package. The error code is 2769.

Moreover, the Operating system is Win 2003 . I even tried the Msiexec in Win XP too Still no go. The SERVERNAME is the property name of one of the textboxes in the TextBox2 Dialog box of setup kit. While observing the installation log , the property change event is recognizing the value change for SERVERNAME but It becomes null while reaching the OnBeforeInstall event don kno wy.

As said earlier it works perfectly in normal UI mode. I even tried modifying the property table of Server.msi thro ORCA(as given below).

Table :Property
Row   :SecureCustomProperties Property -> SecureCustomProperties Changed value from NEWERPRODUCTFOUND to NEWERPRODUCTFOUND;SERVERNAME

Still no go

Please Help.

Many thanks,

byfour

答:
Hii PPl,
        I fixed it myself I jus removed the rows like CustomTextA_SetProperty_EDIT1 from customaction table and their refferences in other tables using ORCA and it solved the issue.

Many thanks,

byfour


答: in python  there is requirements.text file which take care of the libraries that is used in that project. You should also use the virtualenv</p>

Title: Dependency installation for Python (Django) project

Body:
I'm new to Python, but I had a requirement at my work-place. Another programmer is developing a project on Python, Django framework, and my task is to find a way in which this project will be executed at any computer.
So, I'm talking about something like Composer for PHP. I need an easiest way that at debian branch to write in terminal a command, that will find kind of "composer.json" file on that project, will read all the required software, modules, libraries and install it step-by-step on PC.

Any ideas how to do it in the easiest way? Thanks.


问:
Can there be constraints with the same name in a DB?
This is a follow-on question from the one I asked here.

Can constraints in a DB have the same name?

Say I have:

```<code>CREATE TABLE Employer
(
    EmployerCode    VARCHAR(20)    PRIMARY KEY,
    Address         VARCHAR(100)   NULL
)

CREATE TABLE Employee
(
    EmployeeID      INT            PRIMARY KEY,
    EmployerCode    VARCHAR(20)    NOT NULL,
    CONSTRAINT employer_code_fk FOREIGN KEY (EmployerCode) REFERENCES Employer
)

CREATE TABLE BankAccount
(
    BankAccountID   INT            PRIMARY KEY,
    EmployerCode    VARCHAR(20)    NOT NULL,
    Amount          MONEY          NOT NULL,
    CONSTRAINT employer_code_fk FOREIGN KEY (EmployerCode) REFERENCES Employer
)
</code>```

Is this allowable? Does it depend on the DBMS (I'm on SQL Server 2005)? If it is not allowable, does anyone have any suggestions on how to work around it?

答:
It depends on the DBMS.

For example on PostgreSQL, the answer is yes :

Because PostgreSQL does not require constraint names to be unique
  within a schema (but only per-table), it is possible that there is
  more than one match for a specified constraint name.

Source : https://www.postgresql.org/docs/current/static/sql-set-constraints.html

I've seen Foreign Keys constraint names equals on 2 different tables within the same schema.

Body:
This is a follow-on question from the one I asked here.

Can constraints in a DB have the same name?

Say I have:

CREATE TABLE Employer
(
    EmployerCode    VARCHAR(20)    PRIMARY KEY,
    Address         VARCHAR(100)   NULL
)

CREATE TABLE Employee
(
    EmployeeID      INT            PRIMARY KEY,
    EmployerCode    VARCHAR(20)    NOT NULL,
    CONSTRAINT employer_code_fk FOREIGN KEY (EmployerCode) REFERENCES Employer
)

CREATE TABLE BankAccount
(
    BankAccountID   INT            PRIMARY KEY,
    EmployerCode    VARCHAR(20)    NOT NULL,
    Amount          MONEY          NOT NULL,
    CONSTRAINT employer_code_fk FOREIGN KEY (EmployerCode) REFERENCES Employer
)

Is this allowable? Does it depend on the DBMS (I'm on SQL Server 2005)? If it is not allowable, does anyone have any suggestions on how to work around it?


问:
PHP login page using session variable
I am new to php, and trying to create a login page through session without using database, if user successfully logs in, it will be redirected to some page "portfolio.php” and then session will expire after 15 mins but if user randomly types the “portfolio.php” as url it will be redirected to the login page. it should only redirect to that page ("portfolio.php") after the user has login successfully.
here is my "login.php" page code:

```<code> <?php
session_start();
include("functions.php");
$message="";
if(count($_POST)>0) {
    if( $_POST["user_name"] == "admin" and $_POST["password"] == "admin-1") {
        $_SESSION["user_id"] = 1001;
        $_SESSION["user_name"] = $_POST["user_name"];
        $_SESSION['loggedin_time'] = time();

    } else {
        $message = "Invalid Username or Password!";
    }
}
if(isset($_SESSION["user_id"])) {
    if(!isLoginSessionExpired()) {
        header("Location:portfolio.php");
    } else {
        header("Location:logout.php?session_expired=1");
    }
}
if(isset($_GET["session_expired"])) {
    $message = "Login Session is Expired. Please Login Again";
}
?>
</code>```

portfolio.php code:

```<code><?php
session_start();
include("functions.php");
if(isset($_SESSION["user_id"])) {
    if(isLoginSessionExpired()) {
        header("Location:logout.php?session_expired=1");

    }
 }

?>
</code>```

funcation.php code:

```<code><?php
function isLoginSessionExpired() {
    $login_session_duration = 10;
    $current_time = time();
    if(isset($_SESSION['loggedin_time']) and isset($_SESSION["user_id"])){
        if(((time() - $_SESSION['loggedin_time']) > $login_session_duration)){
            return true;
        }
    }
    return false;
}
?>
</code>```

Thanks in advance.

答:
I have seen your code...
You should change $login_session_duration = 10; to   $login_session_duration = 900; for 15 mins

and your portfolio.php should be:

```<code><?php
session_start();
include("funcation.php");
if(isset($_SESSION["user_id"])) {
    if(isLoginSessionExpired()) {
        header("Location:login.php?session_expired=1");
    }
 } else {
     header('Location:login/index(ur html input file)');
 }

?>
</code>```

Title: PHP login page using session variable

Body:
I am new to php, and trying to create a login page through session without using database, if user successfully logs in, it will be redirected to some page "portfolio.php” and then session will expire after 15 mins but if user randomly types the “portfolio.php” as url it will be redirected to the login page. it should only redirect to that page ("portfolio.php") after the user has login successfully.
here is my "login.php" page code:

 <?php
session_start();
include("functions.php");
$message="";
if(count($_POST)>0) {
    if( $_POST["user_name"] == "admin" and $_POST["password"] == "admin-1") {
        $_SESSION["user_id"] = 1001;
        $_SESSION["user_name"] = $_POST["user_name"];
        $_SESSION['loggedin_time'] = time();

    } else {
        $message = "Invalid Username or Password!";
    }
}
if(isset($_SESSION["user_id"])) {
    if(!isLoginSessionExpired()) {
        header("Location:portfolio.php");
    } else {
        header("Location:logout.php?session_expired=1");
    }
}
if(isset($_GET["session_expired"])) {
    $message = "Login Session is Expired. Please Login Again";
}
?>

portfolio.php code:

<?php
session_start();
include("functions.php");
if(isset($_SESSION["user_id"])) {
    if(isLoginSessionExpired()) {
        header("Location:logout.php?session_expired=1");

    }
 }

?>

funcation.php code:

<?php
function isLoginSessionExpired() {
    $login_session_duration = 10;
    $current_time = time();
    if(isset($_SESSION['loggedin_time']) and isset($_SESSION["user_id"])){
        if(((time() - $_SESSION['loggedin_time']) > $login_session_duration)){
            return true;
        }
    }
    return false;
}
?>

Thanks in advance.

Body:
I have seen your code...
You should change $login_session_duration = 10; to   $login_session_duration = 900; for 15 mins

and your portfolio.php should be:

<?php
session_start();
include("funcation.php");
if(isset($_SESSION["user_id"])) {
    if(isLoginSessionExpired()) {
        header("Location:login.php?session_expired=1");
    }
 } else {
     header('Location:login/index(ur html input file)');
 }

?>


问:
Angular 2 FormBuilder disable fields on checkbox select
I have build angular cli project and have a form with checkbox. Some of the fields must disable on checkbox select.

Form is as follows:

need to disable/enable password, new password and re type password fields on checkbox select event.

Html

```<code><form [formGroup]="userProfileForm" (ngSubmit)="submitForm(userProfileForm.value)">

    <div class="row">
        <div class="col">
            <div class="form-group">
                <label> {{ 'USER_PROFILE_MODEL.USER_NAME' | translate }}</label>
                <input class="form-control" type="text" [formControl]="userProfileForm.controls['userName']">
            </div>
            <div class="form-group ">
                <label>{{ 'USER_PROFILE_MODEL.DISPLAY_NAME' | translate }}</label>
                <input class="form-control" type="text" [formControl]="userProfileForm.controls['displayName']">
            </div>
            <div class="form-group ">
                <label>{{ 'USER_PROFILE_MODEL.EMAIL' | translate }}</label>
                <input class="form-control" type="text" [formControl]="userProfileForm.controls['email']">
            </div>
        </div>
        <div class="col">
            <div class="form-group ">
                <label class="checkbox-inline">
                <input type="checkbox" value="isResetPassword" name="isResetPassword" [formControl]="userProfileForm.controls['isResetPassword']">
                 {{ 'USER_PROFILE_MODEL.RESET_PASSWORD' | translate }}
              </label>
            </div>
            <div class="form-group ">
                <label>{{ 'USER_PROFILE_MODEL.PASSWORD' | translate }}</label>
                <input class="form-control" type="password" [formControl]="userProfileForm.controls['password']">
            </div>
            <div class="form-group ">
                <label>{{ 'USER_PROFILE_MODEL.NEW_PASSWORD' | translate }}</label>
                <input class="form-control" type="password" [formControl]="userProfileForm.controls['newPassword']">
            </div>
            <div class="form-group ">
                <label>{{ 'USER_PROFILE_MODEL.RE_TYPE_PASSWORD' | translate }}</label>
                <input class="form-control" type="password" [formControl]="userProfileForm.controls['reTypePassword']">
            </div>

        </div>

    </div>
</form>
</code>```

ts code

```<code>this.isResetPassword = true;
this.userProfileForm = formBuilder.group({
    'userName': [null, [Validators.required]],
    'displayName': [null],
    'email': [null, [Validators.required]],
    'isResetPassword': this.isResetPassword,
    'password': [{
        value: null,
        disabled: this.isResetPassword
    }],
    'newPassword': [{
        value: null,
        disabled: this.isResetPassword
    }],
    'reTypePassword': [{
        value: null,
        disabled: this.isResetPassword
    }]
})
</code>```

Form has built inside the constructor.
How can I disable/enable the above fields on check box select.

答:
The easiest way would be to create a form group just for the passwords:

```<code>this.userProfileForm = formBuilder.group({
  'userName': [null, [Validators.required]],
  'displayName': [null],
  'email': [null, [Validators.required]],
  password: formBuilder.group({
    'isResetPassword': this.isResetPassword,
    'password': [null],
    'newPassword': [null],
    'reTypePassword': [null]
  })
})
</code>```

Then on your template change the passwords col to this:

```<code><div class="col" formGroupName="password>
  <div class="form-group ">
    <label class="checkbox-inline">
      <input type="checkbox" formControlName="isResetPassword">
      {{ 'USER_PROFILE_MODEL.RESET_PASSWORD' | translate }}
    </label>
  </div>
  <div class="form-group ">
    <label>{{ 'USER_PROFILE_MODEL.PASSWORD' | translate }}</label>
    <input class="form-control" type="password" formControlName="password" >
  </div>
  <div class="form-group ">
    <label>{{ 'USER_PROFILE_MODEL.NEW_PASSWORD' | translate }}</label>
    <input class="form-control" type="password" formControlName="newPassword">
  </div>
  <div class="form-group ">
    <label>{{ 'USER_PROFILE_MODEL.RE_TYPE_PASSWORD' | translate }}</label>
    <input class="form-control" type="password" formControlName="reTypePassword">
  </div>
</div>
</code>```

on your component:

```<code>//when value changes, to disable all the fields just do this
this.userProfileForm.controls.password.disable();
// to enable them back
this.userProfileForm.controls.password.enable();
</code>```

Body:
I have build angular cli project and have a form with checkbox. Some of the fields must disable on checkbox select.

Form is as follows:

need to disable/enable password, new password and re type password fields on checkbox select event.

Html

<form [formGroup]="userProfileForm" (ngSubmit)="submitForm(userProfileForm.value)">

                 {{ 'USER_PROFILE_MODEL.USER_NAME' | translate }}
                <input class="form-control" type="text" [formControl]="userProfileForm.controls['userName']">

                {{ 'USER_PROFILE_MODEL.DISPLAY_NAME' | translate }}
                <input class="form-control" type="text" [formControl]="userProfileForm.controls['displayName']">

                {{ 'USER_PROFILE_MODEL.EMAIL' | translate }}
                <input class="form-control" type="text" [formControl]="userProfileForm.controls['email']">

                <input type="checkbox" value="isResetPassword" name="isResetPassword" [formControl]="userProfileForm.controls['isResetPassword']">
                 {{ 'USER_PROFILE_MODEL.RESET_PASSWORD' | translate }}

                {{ 'USER_PROFILE_MODEL.PASSWORD' | translate }}
                <input class="form-control" type="password" [formControl]="userProfileForm.controls['password']">

                {{ 'USER_PROFILE_MODEL.NEW_PASSWORD' | translate }}
                <input class="form-control" type="password" [formControl]="userProfileForm.controls['newPassword']">

                {{ 'USER_PROFILE_MODEL.RE_TYPE_PASSWORD' | translate }}
                <input class="form-control" type="password" [formControl]="userProfileForm.controls['reTypePassword']">

</form>

ts code

this.isResetPassword = true;
this.userProfileForm = formBuilder.group({
    'userName': [null, [Validators.required]],
    'displayName': [null],
    'email': [null, [Validators.required]],
    'isResetPassword': this.isResetPassword,
    'password': [{
        value: null,
        disabled: this.isResetPassword
    }],
    'newPassword': [{
        value: null,
        disabled: this.isResetPassword
    }],
    'reTypePassword': [{
        value: null,
        disabled: this.isResetPassword
    }]
})

Form has built inside the constructor.
How can I disable/enable the above fields on check box select.

Body:
The easiest way would be to create a form group just for the passwords:

this.userProfileForm = formBuilder.group({
  'userName': [null, [Validators.required]],
  'displayName': [null],
  'email': [null, [Validators.required]],
  password: formBuilder.group({
    'isResetPassword': this.isResetPassword,
    'password': [null],
    'newPassword': [null],
    'reTypePassword': [null]
  })
})

Then on your template change the passwords col to this:

<div class="col" formGroupName="password>
  <div class="form-group ">
    <label class="checkbox-inline">
      <input type="checkbox" formControlName="isResetPassword">
      {{ 'USER_PROFILE_MODEL.RESET_PASSWORD' | translate }}
    </label>
  </div>
  <div class="form-group ">
    <label>{{ 'USER_PROFILE_MODEL.PASSWORD' | translate }}</label>
    <input class="form-control" type="password" formControlName="password" >
  </div>
  <div class="form-group ">
    <label>{{ 'USER_PROFILE_MODEL.NEW_PASSWORD' | translate }}</label>
    <input class="form-control" type="password" formControlName="newPassword">
  </div>
  <div class="form-group ">
    <label>{{ 'USER_PROFILE_MODEL.RE_TYPE_PASSWORD' | translate }}</label>
    <input class="form-control" type="password" formControlName="reTypePassword">
  </div>
</div>

on your component:

//when value changes, to disable all the fields just do this
this.userProfileForm.controls.password.disable();
// to enable them back
this.userProfileForm.controls.password.enable();


问:
Create a controller programmatically
It has been decided we should have a common upload http api across different applications. I have a file upload controller which I want to use in multiple webapi projects.

My upload controller looks something like this

```<code>namespace MyNamespace
{
    [Authorize("PolicyName")]
    [Route("Upload")]
    public class UploadController : Controller
    {
        [HttpPost]
        [Route("Upload")]
        public async Task<IActionResult> Upload(UploadModel model)
        {
             // impl..
             return Ok();
        }
    }
}
</code>```

Naively I thought I'd just extract this into a class library and I'd be able to register it, but I can't find how?

Regardless, I do not think this is the correct method to use. I want to be able to configure the Authorize policy name, and potentially the routes. So I'm thinking I want to perhaps build up the controller, its routes and authorize setting and register it some how?

My idea of an api would be like..

```<code>((IApplicationBuilder)app).UseUploadController(config => {
    config.PolicyName = "Whatever",
    config.UploadRoute = "UploadStuff"
});
</code>```

... this would create and register the controller. No idea where to start though. I have absolutely no clue on how controllers are discovered or if they can be registered programatically.

Anyone got any pointers or libraries to look at for inspiration?

答:
You can have your controller in class library that you reference (as you wanted) and then in any project you can inherit from that controller where you want. If you don't want any other functionality, you can leave child class empty, but if you want to add something, you can easily extend it it.
Also, you can have any other name of controller and can set different routes, authorizations etc.</p>

Title: Create a controller programmatically

Body:
It has been decided we should have a common upload http api across different applications. I have a file upload controller which I want to use in multiple webapi projects.

My upload controller looks something like this

namespace MyNamespace
{
    [Authorize("PolicyName")]
    [Route("Upload")]
    public class UploadController : Controller
    {
        [HttpPost]
        [Route("Upload")]
        public async Task<IActionResult> Upload(UploadModel model)
        {
             // impl..
             return Ok();
        }
    }
}

Naively I thought I'd just extract this into a class library and I'd be able to register it, but I can't find how?

Regardless, I do not think this is the correct method to use. I want to be able to configure the Authorize policy name, and potentially the routes. So I'm thinking I want to perhaps build up the controller, its routes and authorize setting and register it some how?

My idea of an api would be like..

((IApplicationBuilder)app).UseUploadController(config => {
    config.PolicyName = "Whatever",
    config.UploadRoute = "UploadStuff"
});

... this would create and register the controller. No idea where to start though. I have absolutely no clue on how controllers are discovered or if they can be registered programatically.

Anyone got any pointers or libraries to look at for inspiration?


答:
Can It possible?

No, it is just a shorthand method, use block instead..

```<code>objects_array.collect { |obl| obj.errors.full_messages }
</code>```

Title: How can I call two methods simultaneously using `&`

Body:
Instead of calling one method in a block using &,

objects_array.collect(&:errors)

can I call two methods simultaneously using &? I want something like this:

objects_array.collect(&:errors.full_messages)

Is it possible?

Body:
Can It possible?

No, it is just a shorthand method, use block instead..

objects_array.collect { |obl| obj.errors.full_messages }


问:
Gtk Notebook call function every time a certain tab is selected
I want a tab on my notebook that pretty much does the same like a button. Every time I select this tab it should execute a certain job (for example print('something') ).

How do I get it to execute every time I open it? Right now it just executes once on startup and that's it.

If someone has some advice on this subject I'd really apreciate some help!

答:
You're looking for the switch-page signal:

```<code>def callback(notebook, tab, index):
    if index == index_of_the_tab:
        print('selected')

    # alternatively:
    # if tab is the_tab:
    #     print('selected')

notebook.connect('switch-page', callback)
</code>```

Body:
You're looking for the switch-page signal:

def callback(notebook, tab, index):
    if index == index_of_the_tab:
        print('selected')

    # alternatively:
    # if tab is the_tab:
    #     print('selected')

notebook.connect('switch-page', callback)


问:
ListView Interference with AppBarLayout
My problem with ListView

ListView Interference with AppBarLayout

I want to be under the AppBarLayout

progressbar in center page

problem screenshot

How to App bar Title and back button to Right?

activity_category.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_category"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.sokhanak.CategoryActivity">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:background="?attr/colorPrimary" />

</android.support.design.widget.AppBarLayout>

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v4.widget.ContentLoadingProgressBar
        android:id="@+id/progress"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal|center_vertical"
        android:visibility="visible" />

    <ListView
        android:id="@+id/listView"
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</FrameLayout>
</LinearLayout>
</code>```

CategoryActivity.java

```<code>package com.example;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.ContentLoadingProgressBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.example.adapter.QuoteArrayAdapter;
import com.example.model.QuoteDataModel;
import com.example.parser.JSONParser;
import com.example.utils.Keys;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class CategoryActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private ListView listView;
    private ArrayList<QuoteDataModel> list;
    private QuoteArrayAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_category);

        Intent i = getIntent();
        final String categoryId = i.getStringExtra("categoryId");
        String categoryName = i.getStringExtra("categoryName");

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        setTitle(categoryName);

        /**
         * Array List for Binding Data from JSON to this List
         */
        list = new ArrayList<>();

        adapter = new QuoteArrayAdapter(this, list);

        /**
         * Getting List and Setting List Adapter
         */
        listView = (ListView) findViewById(R.id.listView);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Snackbar.make(findViewById(R.id.parentLayout), list.get(position).getProfileName() + " => " + list.get(position).getQuoteLike(), Snackbar.LENGTH_LONG).show();
            }
        });

        /**
         * Check internet connection
         */
        if (!MainActivity.NetworkUtil.isOnline(getApplicationContext())) {
            Toast.makeText(CategoryActivity.this, "اتصال به اینترنت برقرار نیست",
                    Toast.LENGTH_LONG).show();
        }

        new GetDataCategory().execute(categoryId);

        listView.setOnScrollListener(new AbsListView.OnScrollListener() {

            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            public void onScroll(AbsListView view, int firstVisibleItem,
                                 int visibleItemCount, int totalItemCount) {

                if(firstVisibleItem+visibleItemCount == totalItemCount && totalItemCount!=0)
                {
                    new GetDataCategory().execute(categoryId);
                }
            }
        });

        // screen turn on ever
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    }

/* */
}
</code>```

答:
```<code> /**Make a change in your listview**/

   ListView Interference with AppBarLayout:

  <ListView
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    android:id="@+id/listView"
    android:layout_below="@+id/toolbar"
    android:layout_width="fill_parent"
    android:layout_height="match_parent" />

    App bar Title and back button to Right:

    Just add below line inside application tag in AndroidManifestFile

    android:supportsRtl="true"
</code>```

Title: ListView Interference with AppBarLayout

Body:
My problem with ListView

ListView Interference with AppBarLayout

I want to be under the AppBarLayout

progressbar in center page

problem screenshot

How to App bar Title and back button to Right?

activity_category.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_category"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.sokhanak.CategoryActivity">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:background="?attr/colorPrimary" />

</android.support.design.widget.AppBarLayout>

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v4.widget.ContentLoadingProgressBar
        android:id="@+id/progress"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal|center_vertical"
        android:visibility="visible" />

    <ListView
        android:id="@+id/listView"
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</FrameLayout>
</LinearLayout>

CategoryActivity.java

package com.example;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.ContentLoadingProgressBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.example.adapter.QuoteArrayAdapter;
import com.example.model.QuoteDataModel;
import com.example.parser.JSONParser;
import com.example.utils.Keys;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class CategoryActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private ListView listView;
    private ArrayList<QuoteDataModel> list;
    private QuoteArrayAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_category);

        Intent i = getIntent();
        final String categoryId = i.getStringExtra("categoryId");
        String categoryName = i.getStringExtra("categoryName");

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        setTitle(categoryName);

        /**
         * Array List for Binding Data from JSON to this List
         */
        list = new ArrayList<>();

        adapter = new QuoteArrayAdapter(this, list);

        /**
         * Getting List and Setting List Adapter
         */
        listView = (ListView) findViewById(R.id.listView);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Snackbar.make(findViewById(R.id.parentLayout), list.get(position).getProfileName() + " => " + list.get(position).getQuoteLike(), Snackbar.LENGTH_LONG).show();
            }
        });

        /**
         * Check internet connection
         */
        if (!MainActivity.NetworkUtil.isOnline(getApplicationContext())) {
            Toast.makeText(CategoryActivity.this, "اتصال به اینترنت برقرار نیست",
                    Toast.LENGTH_LONG).show();
        }

        new GetDataCategory().execute(categoryId);

        listView.setOnScrollListener(new AbsListView.OnScrollListener() {

            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            public void onScroll(AbsListView view, int firstVisibleItem,
                                 int visibleItemCount, int totalItemCount) {

                if(firstVisibleItem+visibleItemCount == totalItemCount && totalItemCount!=0)
                {
                    new GetDataCategory().execute(categoryId);
                }
            }
        });

        // screen turn on ever
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    }

/* */
}


问:
Can't create Type Library File with Visual Studio 2010 generated DLL, but can with command-line compiled
I have a TestClass.cs file that contains an interface, and a class, much like this:

```<code>namespace CPierce.CSharpBridge
{
    [System.Runtime.InteropServices.Guid("3D08DF02-EFBA-4A65-AD84-B08ADEADBEEF")]
    public interface ICSide
    {
        // interface definition omitted...
    }
    [System.Runtime.InteropServices.Guid("CBC04D81-398B-4B03-A3D1-C6D5DEADBEEF")]
    public partial class CSide : ICSide
    {
        // class definition omitted...
    }
}
</code>```

When I compile this at the command line, and run regasm on it:

```<code>csc /debug /t:library TestClass.cs
regasm TestClass.dll /tlb:TestClass.tlb
</code>```

I get a nice, big .tlb file suitable for including in a C++ project elsewhere....

```<code> 10/27/2011  01:50 PM             3,616 TestClass.tlb
</code>```

When I put TestClass.cs into a "Class Project" in Visual Studio, compile it, run regasm, the resulting .tlb is pathetic and nearly useless -- it has no interface, no method signatures, etc...

```<code>[Compiled TestClass.cs as part of Project "ClassProject" in Visual Studio]
regasm ClassProject.dll /tlb:ClassProject.dll

10/27/2011  01:58 PM             1,132 ClassProject.tlb
</code>```

This is the same C# code in both cases, one being compiled with Visual Studio one at the command line, giving me completely different results.

What gives?

--

Update:  Hans suggests that the [ComVisible(true)] attribute missing is causing the problem.  Tried it, and it worked.  But that still doesn't answer the question, why?  Why do I get different results based on which compile method I use?

答:
Also check if your class has functions of accessor type public.

In our case, the project was working fine when it was being used from within the solution but when we extracted the logic to create a DLL, it stopped creating the TLB file with no indication on why...

So if you have a class like so,

```<code>public class tlbuser{
    private void functionTLB(){
        //function code
    }
    // rest of the class code
}
</code>```

Ensure it is changed to:

```<code>public class tlbuser{
    public void functionTLB(){
        //function code
    }
    // rest of the class code
}
</code>```

Body:
I have a TestClass.cs file that contains an interface, and a class, much like this:

namespace CPierce.CSharpBridge
{
    [System.Runtime.InteropServices.Guid("3D08DF02-EFBA-4A65-AD84-B08ADEADBEEF")]
    public interface ICSide
    {
        // interface definition omitted...
    }
    [System.Runtime.InteropServices.Guid("CBC04D81-398B-4B03-A3D1-C6D5DEADBEEF")]
    public partial class CSide : ICSide
    {
        // class definition omitted...
    }
}

When I compile this at the command line, and run regasm on it:

csc /debug /t:library TestClass.cs
regasm TestClass.dll /tlb:TestClass.tlb

I get a nice, big .tlb file suitable for including in a C++ project elsewhere....

 10/27/2011  01:50 PM             3,616 TestClass.tlb

When I put TestClass.cs into a "Class Project" in Visual Studio, compile it, run regasm, the resulting .tlb is pathetic and nearly useless -- it has no interface, no method signatures, etc...

[Compiled TestClass.cs as part of Project "ClassProject" in Visual Studio]
regasm ClassProject.dll /tlb:ClassProject.dll

10/27/2011  01:58 PM             1,132 ClassProject.tlb

This is the same C# code in both cases, one being compiled with Visual Studio one at the command line, giving me completely different results.

What gives?

--

Update:  Hans suggests that the [ComVisible(true)] attribute missing is causing the problem.  Tried it, and it worked.  But that still doesn't answer the question, why?  Why do I get different results based on which compile method I use?

Body:
Also check if your class has functions of accessor type public.

In our case, the project was working fine when it was being used from within the solution but when we extracted the logic to create a DLL, it stopped creating the TLB file with no indication on why...

So if you have a class like so,

public class tlbuser{
    private void functionTLB(){
        //function code
    }
    // rest of the class code
}

Ensure it is changed to:

public class tlbuser{
    public void functionTLB(){
        //function code
    }
    // rest of the class code
}


问:
word2vec guesing word embeddings
can word2vec be used for guessing words with just context?
having trained the model with a large data set e.g. Google news how can I use word2vec to predict a similar word with only context  e.g. with input ", who dominated chess for more than 15 years, will compete against nine top players in St Louis, Missouri."  The output should be Kasparov or maybe Carlsen.

I'ven seen only the similarity apis but I can't make sense how to use them for this?  is this not how word2vec was intented to use?

答:
It is not the intended use of word2vec. The word2vec algorithm internally tries to predict exact words, using surrounding words, as a roundabout way to learn useful vectors for those surrounding words.

But even so, it's not forming exact predictions during training. It's just looking at a single narrow training example – context words and target word – and performing a very simple comparison and internal nudge to make its conformance to that one example slightly better. Over time, that self-adjusts towards useful vectors – even if the predictions remain of wildly-varying quality.

Most word2vec libraries don't offer a direct interface for showing ranked predictions, given context words. The Python gensim library, for the last few versions (as of current version 2.2.0 in July 2017), has offered a predict_output_word() method that roughly shows what the model would predict, given context-words, for some training modes. See:

https://radimrehurek.com/gensim/models/word2vec.html#gensim.models.word2vec.Word2Vec.predict_output_word

However, considering your fill-in-the-blank query (also called a 'cloze deletion' in related education or machine-learning contexts):

```<code>_____, who dominated chess for more than 15 years, will compete against nine top players in St Louis, Missouri
</code>```

A vanilla word2vec model is unlikely to get that right. It has little sense of the relative importance of words (except when some words are more narrowly predictive of others). It has no sense of grammar/ordering, or or of the compositional-meaning of connected-phrases (like 'dominated chess' as opposed to the separate words 'dominated' and 'chess'). Even though words describing the same sorts of things are usually near each other, it doesn't know categories to be able to determine that the blank must be a 'person' and a 'chess player', and the fuzzy-similarities of word2vec don't guarantee words-of-a-class will necessarily all be nearer-each-other than other words.

There has been a bunch of work to train word/concept vectors (aka 'dense embeddings') to be better at helping at such question-answering tasks. A random example might be "Creating Causal Embeddings for Question Answering with Minimal Supervision" but queries like [word2vec question answering] or [embeddings for question answering] will find lots more. I don't know of easy out-of-the-box libraries for doing this, with or without a core of word2vec, though.

Title: word2vec guesing word embeddings

Body:
It is not the intended use of word2vec. The word2vec algorithm internally tries to predict exact words, using surrounding words, as a roundabout way to learn useful vectors for those surrounding words.

But even so, it's not forming exact predictions during training. It's just looking at a single narrow training example – context words and target word – and performing a very simple comparison and internal nudge to make its conformance to that one example slightly better. Over time, that self-adjusts towards useful vectors – even if the predictions remain of wildly-varying quality.

Most word2vec libraries don't offer a direct interface for showing ranked predictions, given context words. The Python gensim library, for the last few versions (as of current version 2.2.0 in July 2017), has offered a predict_output_word() method that roughly shows what the model would predict, given context-words, for some training modes. See:

https://radimrehurek.com/gensim/models/word2vec.html#gensim.models.word2vec.Word2Vec.predict_output_word

However, considering your fill-in-the-blank query (also called a 'cloze deletion' in related education or machine-learning contexts):

_____, who dominated chess for more than 15 years, will compete against nine top players in St Louis, Missouri

A vanilla word2vec model is unlikely to get that right. It has little sense of the relative importance of words (except when some words are more narrowly predictive of others). It has no sense of grammar/ordering, or or of the compositional-meaning of connected-phrases (like 'dominated chess' as opposed to the separate words 'dominated' and 'chess'). Even though words describing the same sorts of things are usually near each other, it doesn't know categories to be able to determine that the blank must be a 'person' and a 'chess player', and the fuzzy-similarities of word2vec don't guarantee words-of-a-class will necessarily all be nearer-each-other than other words.

There has been a bunch of work to train word/concept vectors (aka 'dense embeddings') to be better at helping at such question-answering tasks. A random example might be "Creating Causal Embeddings for Question Answering with Minimal Supervision" but queries like [word2vec question answering] or [embeddings for question answering] will find lots more. I don't know of easy out-of-the-box libraries for doing this, with or without a core of word2vec, though.