问:
Dynamically populating Range with chained IF statements in VBA?

I am automating a workbook that uses chained IF statements (non-VBA) across 4 worksheets to generate an output file for upload.

Here is a quick rundown of the code to give context:

Create new worksheet and populate first row from array (works)

Populate second row with IF formulas from array

Populate rest of table with dynamic IF functions used above (seems to work though rather rudimentary)

[Updated Code below]

```<code>Dim WS As Worksheet
Dim cell As Range

TestFormulas() = Array("=If 'Sheet1'!P2 = 'Redundant' Then cell.Value = ''
ElseIf 'Sheet1'!P2 = 'Peripheral' Then cell.Value = '' Else cell.Value = 1")

    With WS
        For i = LBound(TestFormulas()) To UBound(TestFormulas())
          .Cells(2, 1 + i).Formula = TestFormulas(i)
        Next i
    End With

    Range("A3:BN74").Formula = "=A2"
</code>```

The result I am looking to achieve is that the array fills all the rows across with the correct IF statements and then the Range completes the dynamic fill of the relevant cells.

Error I am receiving is

'1004: Application-Defined or Object-Defined error'

and the line .Cells(2, 1 + i).Formula = TestFormulas(i) is highlighted yellow.

答:
You say you've adjusted for quotes, but you have changed them to single quotes instead of leaving them as double quotes

The formula should be adjusted like this....

```<code>=If 'Sheet1'!P2 = ""Redundant"" Then ...
</code>```

Note the doubling of the double quotes.

Also, the Excel spreadsheet does not understand vba code, so your formula should look something like this:

```<code>=IF('Sheet1'!P2 = ""Redundant"","""",IF(...
</code>```

Body:
I am automating a workbook that uses chained IF statements (non-VBA) across 4 worksheets to generate an output file for upload.

Here is a quick rundown of the code to give context:

Create new worksheet and populate first row from array (works)

Populate second row with IF formulas from array

Populate rest of table with dynamic IF functions used above (seems to work though rather rudimentary)

[Updated Code below]

Dim WS As Worksheet
Dim cell As Range

TestFormulas() = Array("=If 'Sheet1'!P2 = 'Redundant' Then cell.Value = ''
ElseIf 'Sheet1'!P2 = 'Peripheral' Then cell.Value = '' Else cell.Value = 1")

    With WS
        For i = LBound(TestFormulas()) To UBound(TestFormulas())
          .Cells(2, 1 + i).Formula = TestFormulas(i)
        Next i
    End With

    Range("A3:BN74").Formula = "=A2"

The result I am looking to achieve is that the array fills all the rows across with the correct IF statements and then the Range completes the dynamic fill of the relevant cells.

Error I am receiving is

'1004: Application-Defined or Object-Defined error'

and the line .Cells(2, 1 + i).Formula = TestFormulas(i) is highlighted yellow.

Body:
You say you've adjusted for quotes, but you have changed them to single quotes instead of leaving them as double quotes

The formula should be adjusted like this....

=If 'Sheet1'!P2 = ""Redundant"" Then ...

Note the doubling of the double quotes.

Also, the Excel spreadsheet does not understand vba code, so your formula should look something like this:

=IF('Sheet1'!P2 = ""Redundant"","""",IF(...


来源: stackexchange

问:
MongoDB Query by DateTime with Python
I want to query MongoDB and return records that have the date of 12/6/2017. The date is in this format:

```<code>u'Date': datetime.datetime(2017, 12, 6, 15, 9, 21, 303000)
</code>```

So, how do I query just the year, month, and day of that entry?  I have tried:

```<code>date = db.data.find({ 'Date' : {'2017, 12, 6'} },{'Date' : '1'})
for document in date:
     print(date)
</code>```

Which returns: "InvalidDocument: Cannot encode object: set(['2017, 12, 6'])".

I also tried:

```<code>date = db.data.find({ 'Date' : {datetime('2017, 12, 6')} },{'Date' : '1'})
for document in date:
    print(date)
</code>```

Which returns: "NameError: name 'datetime' is not defined".

UPDATE...SOLUTION
I was putting the date into Mongo incorrectly. I'm now putting the date into Mongo with Python like this:

```<code>import datetime
import dateutil.parser

# the date
now = datetime.datetime.now()
year = now.year
month = now.month
day = now.day
theDate = str(year) + "-" + str(month) + "-" + str(day)
dateStr = theDate
date = dateutil.parser.parse(dateStr)
# Then put that date into your Mongo insert
</code>```

This is how I'm querying by date. This pulls documents inserted after yersterday (today).

```<code>import dateutil.parser, datetime
now = datetime.datetime.now()
year = now.year
month = now.month
yesterday = now.day - 1
dateStr = str(year) + "-" + str(month) + "-" + str(yesterday)
date = dateutil.parser.parse(dateStr)

cursor = db.data.find({'Date' : { '$gt' : date}},{'Date':'1'})
for document in cursor:
    print(document)
</code>```

答:
When you say the object is stored as datetime.datetime, to what are you referring? A custom object?

Per the Mongo docs, this is the only date object they support explicity:
https://docs.mongodb.com/v3.4/reference/method/Date/

From the Docs:

Date() Returns a date either as a string or as a Date object.

Date() returns the current date as a string in the mongo shell. new
  Date() returns the current date as a Date object. The mongo shell
  wraps the Date object with the ISODate helper. The ISODate is in UTC.
  You can specify a particular date by passing to the Date() method a
  datetime string. For example:

new Date("") which returns the ISODate with the specified
  date. new Date("") which specifies the datetime
  in local datetime and returns the ISODate with the specified datetime
  in UTC. new Date("") which specifies the
  datetime in UTC and returns the ISODate with the specified datetime in
  UTC.

To create a query to search on a Date field in mongo, you would instatiate an ISODate like this

```<code>db.collection.find({"datefield" : ISODate("YYYY-MM-DDTHH:MM:SS")})
</code>```

Generally, this will be of somewhat limited use, since the time is measured in milliseconds, so you'll likely need to do a range query similar to:

```<code>db.collection.find({"datefield" : {"$gte" : <beginning_of_day_as_ISODate>, "$lte" : <end_of_day_as_ISODate>})
</code>```

For example:

```<code>{createdDate : {$gte : ISODate("2017-12-06T00:00:00"), $lte : ISODate("2017-12-06T23:59:59")}}
</code>```

If you are using a custom date object, or storing the date in some non-standard format, your query will need to be tailored to that object.

ContentLicense: CC BY-SA 3.0

Title: MongoDB Query by DateTime with Python

Body:
I want to query MongoDB and return records that have the date of 12/6/2017. The date is in this format:

u'Date': datetime.datetime(2017, 12, 6, 15, 9, 21, 303000)

So, how do I query just the year, month, and day of that entry?  I have tried:

date = db.data.find({ 'Date' : {'2017, 12, 6'} },{'Date' : '1'})
for document in date:
     print(date)

Which returns: "InvalidDocument: Cannot encode object: set(['2017, 12, 6'])".

I also tried:

date = db.data.find({ 'Date' : {datetime('2017, 12, 6')} },{'Date' : '1'})
for document in date:
    print(date)

Which returns: "NameError: name 'datetime' is not defined".

UPDATE...SOLUTION
I was putting the date into Mongo incorrectly. I'm now putting the date into Mongo with Python like this:

import datetime
import dateutil.parser

# the date
now = datetime.datetime.now()
year = now.year
month = now.month
day = now.day
theDate = str(year) + "-" + str(month) + "-" + str(day)
dateStr = theDate
date = dateutil.parser.parse(dateStr)
# Then put that date into your Mongo insert

This is how I'm querying by date. This pulls documents inserted after yersterday (today).

import dateutil.parser, datetime
now = datetime.datetime.now()
year = now.year
month = now.month
yesterday = now.day - 1
dateStr = str(year) + "-" + str(month) + "-" + str(yesterday)
date = dateutil.parser.parse(dateStr)

cursor = db.data.find({'Date' : { '$gt' : date}},{'Date':'1'})
for document in cursor:
    print(document)

Body:
When you say the object is stored as datetime.datetime, to what are you referring? A custom object?

Per the Mongo docs, this is the only date object they support explicity:
https://docs.mongodb.com/v3.4/reference/method/Date/

From the Docs:

Date() Returns a date either as a string or as a Date object.

Date() returns the current date as a string in the mongo shell. new
  Date() returns the current date as a Date object. The mongo shell
  wraps the Date object with the ISODate helper. The ISODate is in UTC.
  You can specify a particular date by passing to the Date() method a
  datetime string. For example:

new Date("") which returns the ISODate with the specified
  date. new Date("") which specifies the datetime
  in local datetime and returns the ISODate with the specified datetime
  in UTC. new Date("") which specifies the
  datetime in UTC and returns the ISODate with the specified datetime in
  UTC.

To create a query to search on a Date field in mongo, you would instatiate an ISODate like this

db.collection.find({"datefield" : ISODate("YYYY-MM-DDTHH:MM:SS")})

Generally, this will be of somewhat limited use, since the time is measured in milliseconds, so you'll likely need to do a range query similar to:

db.collection.find({"datefield" : {"$gte" : <beginning_of_day_as_ISODate>, "$lte" : <end_of_day_as_ISODate>})

For example:

{createdDate : {$gte : ISODate("2017-12-06T00:00:00"), $lte : ISODate("2017-12-06T23:59:59")}}

If you are using a custom date object, or storing the date in some non-standard format, your query will need to be tailored to that object.


问:
Constructing Context Free Grammar From The Following Regular Expression
Have a look at the expression

For the above expression I want to construct a context free grammar, the number of occurrences of 'w's have to be equal to (the occurrences of 'k's divided by 2 because 'k' is n * 2 in the language) + (number of occurrences of 'd's which there are m occurances of)

In other words there must be n+m occurrences of 'w'
I've got this so far

S ---> XYZ

  X ---> kX|k|Y

  Y ---> dY|dd|Z

  Z ---> (here, how do i get m+n occurrences of "w")?

Any suggestions or hints to complete this context free grammar?

答:
Your approach is problematic because you lose the linkage between how many k's you're adding up front and how many w's you need to add later on. Any production which touches the 2n k's must touch w's for this reason; similarly, any production touching the m d's must touch the w's for the same reason.

Look for ways to create these linkages in your language and you can determine what those required productions will look like. An often helpful way of doing this is by rewriting the input and adding parentheses to show the order that things will be handled in. We know we need a linkage between the 2n k's and the w's, and we know we need a link between the m d's and the w's. The d's are closer so we can start there. We can link the d's to the w's by putting parentheses around the d's and enough w's so that we can find a grammar for the enclosed term. By enclosing m w's, we get a simple grammar: odd strings with a k in the middle, d's on the left and w's on the right and the same numbers of d's and w's.

With that handled, we see there's now an easy linkage between the k's and the w's: there are 2n k's and n w's, so we need a production for the same language as before, except we have k's instead of d's and instead of the numbers being the same, we have twice as many k's as w's.

```<code>  k^(2n) d^m k w^(m+n) d^2
= k^(2n) [d^m k w^m] w^n d^2
= [k^(2n) [d^m k w^m] w^n] d^2
</code>```

We understood the linkages inside out, and now we can write the grammar outside in:

```<code>S -> Tdd      // handles the d^2 part on the end
T -> kkTw     // recursive part of the term in the outermost brackets
T -> R        // switch to handle the term in the innermost brackets
R -> dRw      // recursive part of the term in the innermost brackets
R -> k        // base case of the term in the innermost brackets
</code>```

Body:
Your approach is problematic because you lose the linkage between how many k's you're adding up front and how many w's you need to add later on. Any production which touches the 2n k's must touch w's for this reason; similarly, any production touching the m d's must touch the w's for the same reason.

Look for ways to create these linkages in your language and you can determine what those required productions will look like. An often helpful way of doing this is by rewriting the input and adding parentheses to show the order that things will be handled in. We know we need a linkage between the 2n k's and the w's, and we know we need a link between the m d's and the w's. The d's are closer so we can start there. We can link the d's to the w's by putting parentheses around the d's and enough w's so that we can find a grammar for the enclosed term. By enclosing m w's, we get a simple grammar: odd strings with a k in the middle, d's on the left and w's on the right and the same numbers of d's and w's.

With that handled, we see there's now an easy linkage between the k's and the w's: there are 2n k's and n w's, so we need a production for the same language as before, except we have k's instead of d's and instead of the numbers being the same, we have twice as many k's as w's.

  k^(2n) d^m k w^(m+n) d^2
= k^(2n) [d^m k w^m] w^n d^2
= [k^(2n) [d^m k w^m] w^n] d^2

We understood the linkages inside out, and now we can write the grammar outside in:

S -> Tdd      // handles the d^2 part on the end
T -> kkTw     // recursive part of the term in the outermost brackets
T -> R        // switch to handle the term in the innermost brackets
R -> dRw      // recursive part of the term in the innermost brackets
R -> k        // base case of the term in the innermost brackets


问:
Parse XML with comma-separated entries into table in SQL Server
I have a XML file which is something like this

```<code>    declare @X XML
     Set @X  ='<A>
        <B>
        <C>161</C>
        <D>190</D>
        <E>43 ,44 ,48 ,49</E>
        </B>
    <B>
    <C>162</C>
    <D>190</D>
    <E>100</E>
    </B>
    </A>
'
</code>```

I want to parse it into a table:

```<code>    C         D       E
    161      190     43
    161      190     48
    161      190     49
    162      190     100
</code>```

I tried using

```<code>select
    x.r.value('(A)[1]', 'int') as C,
    x.r.value('(D)[1]', 'int') as D,
    x.r.value('(E)[1]', 'varchar(max)') as E
from
    @X.nodes('/A/B') as x(r)

DECLARE @xml as xml, @str as varchar(100), @delimiter as varchar(10)

SET @str = '43,48,49'
SET @delimiter = ','
SET @xml = cast(('<X>'+replace(@str,@delimiter ,'</X><X>')+'</X>') as xml)
        SELECT T.N.value('.', 'int') as value FROM @xml.nodes('X') as T(N)
</code>```

for separating the comma-separated column E into table.

But I am not able to combine both these in one query i.e. parse it into the table

答:
Next time you should really avoid "chameleon" questions. Especially when changes to the initial questions invalidate correct answers this is considered to be impolite...

What you've done instead: Close this question by accepting the most helpful answer and start a new question.

Nevertheless here's a working approach:

```<code>DECLARE @X XML =
N'<A>
  <B>
    <C>161</C>
    <D>190</D>
    <E>43 ,44 ,48 ,49</E>
  </B>
  <B>
    <C>162</C>
    <D>190</D>
    <E>100</E>
  </B>
</A>';

WITH ReturnYourListAsXml AS
(
    SELECT CAST(N'<x>' + REPLACE(B.value(N'(E/text())[1]',N'nvarchar(max)'),',','</x><x>') + '</x>' AS XML) AS E_As_Xml
          ,B.value(N'(C/text())[1]',N'int') AS C
          ,B.value(N'(D/text())[1]',N'int') AS D
          ,ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS B_Nr
    FROM @x.nodes(N'/A/B') AS AllNodes(B)
)
SELECT cte.B_Nr
      ,cte.C
      ,cte.D
      ,YourList.Member.value(N'text()[1]',N'int') AS E
FROM ReturnYourListAsXml AS cte
CROSS APPLY E_As_Xml.nodes(N'/x') AS YourList(Member);
</code>```

Body:
I have a XML file which is something like this

    declare @X XML
     Set @X  ='

        <C>161</C>
        <D>190</D>
        <E>43 ,44 ,48 ,49</E>

    <C>162</C>
    <D>190</D>
    <E>100</E>

'

I want to parse it into a table:

    C         D       E
    161      190     43
    161      190     48
    161      190     49
    162      190     100

I tried using

select
    x.r.value('(A)[1]', 'int') as C,
    x.r.value('(D)[1]', 'int') as D,
    x.r.value('(E)[1]', 'varchar(max)') as E
from
    @X.nodes('/A/B') as x(r)

DECLARE @xml as xml, @str as varchar(100), @delimiter as varchar(10)

SET @str = '43,48,49'
SET @delimiter = ','
SET @xml = cast(('<X>'+replace(@str,@delimiter ,'</X><X>')+'</X>') as xml)
        SELECT T.N.value('.', 'int') as value FROM @xml.nodes('X') as T(N)

for separating the comma-separated column E into table.

But I am not able to combine both these in one query i.e. parse it into the table

Body:
Next time you should really avoid "chameleon" questions. Especially when changes to the initial questions invalidate correct answers this is considered to be impolite...

What you've done instead: Close this question by accepting the most helpful answer and start a new question.

Nevertheless here's a working approach:

DECLARE @X XML =
N'<A>
  <B>
    <C>161</C>
    <D>190</D>
    <E>43 ,44 ,48 ,49</E>
  </B>
  <B>
    <C>162</C>
    <D>190</D>
    <E>100</E>
  </B>
</A>';

WITH ReturnYourListAsXml AS
(
    SELECT CAST(N'<x>' + REPLACE(B.value(N'(E/text())[1]',N'nvarchar(max)'),',','</x><x>') + '</x>' AS XML) AS E_As_Xml
          ,B.value(N'(C/text())[1]',N'int') AS C
          ,B.value(N'(D/text())[1]',N'int') AS D
          ,ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS B_Nr
    FROM @x.nodes(N'/A/B') AS AllNodes(B)
)
SELECT cte.B_Nr
      ,cte.C
      ,cte.D
      ,YourList.Member.value(N'text()[1]',N'int') AS E
FROM ReturnYourListAsXml AS cte
CROSS APPLY E_As_Xml.nodes(N'/x') AS YourList(Member);


问:
Cannot set value to Dictionary Key
I fall in a weird situation, so essentially I need to create a Dictionary with a string as Key and a custom object as Value. The Dictionary have this implementation:

```<code>public static Dictionary<string, ForecastType> FullTime
{
    get
    {
        return new Dictionary<string, ForecastType>()
        {
            { "1", new ForecastType { Type = SignType.PartialFinal, Sign = Signs.HomeHomePF } },
            ...
        }
    }
}
</code>```

as you can see the key is 1 and the value is a custom class called ForecastType:

```<code>public class ForecastType : ViewModel
{
    private double _value;

    public double Value
    {
        get { return _value; }
        set
        {
            _value = value;
            OnPropertyChanged();
        }
    }

    public Signs Sign { get; set; }
    public SignType Type { get; set; }
}
</code>```

the property Sign and Type don't need an explaination, it's only an implementation of an Enum.
The property Value instead, cause me a lot of headache. In particular I can't set the value to this property, each value that I assign I get 0.

I also implemented the ViewModel, I though to an issue related on PropertyChanged, but even this hasn't fixed the situation.

I valorize the Value property in this way:

```<code>FullTime["1"].Value = 5;
</code>```

Note that the OnPropertyChanged() is called correctly, and the value inside it is 5, but when I set a breakpoint, later the FullTime["1"].. line I get as .Value "0".

What am I doing wrong?

Thanks for any help. Best regards.

答:
Instead of having the getter for the FullTime property return a new dictionary, you can, as of C# 6, provide a default value for the property like so:

```<code>public static Dictionary<string, ForecastType> FullTime {get;} = new Dictionary<string, ForecastType> () { /* initial dictionary values go here */ };
</code>```

Title: Cannot set value to Dictionary Key

Body:
I fall in a weird situation, so essentially I need to create a Dictionary with a string as Key and a custom object as Value. The Dictionary have this implementation:

public static Dictionary<string, ForecastType> FullTime
{
    get
    {
        return new Dictionary<string, ForecastType>()
        {
            { "1", new ForecastType { Type = SignType.PartialFinal, Sign = Signs.HomeHomePF } },
            ...
        }
    }
}

as you can see the key is 1 and the value is a custom class called ForecastType:

public class ForecastType : ViewModel
{
    private double _value;

    public double Value
    {
        get { return _value; }
        set
        {
            _value = value;
            OnPropertyChanged();
        }
    }

    public Signs Sign { get; set; }
    public SignType Type { get; set; }
}

the property Sign and Type don't need an explaination, it's only an implementation of an Enum.
The property Value instead, cause me a lot of headache. In particular I can't set the value to this property, each value that I assign I get 0.

I also implemented the ViewModel, I though to an issue related on PropertyChanged, but even this hasn't fixed the situation.

I valorize the Value property in this way:

FullTime["1"].Value = 5;

Note that the OnPropertyChanged() is called correctly, and the value inside it is 5, but when I set a breakpoint, later the FullTime["1"].. line I get as .Value "0".

What am I doing wrong?

Thanks for any help. Best regards.

Body:
Instead of having the getter for the FullTime property return a new dictionary, you can, as of C# 6, provide a default value for the property like so:

public static Dictionary<string, ForecastType> FullTime {get;} = new Dictionary<string, ForecastType> () { /* initial dictionary values go here */ };


问:
Create new record odoo
I want to return only all rubrique_name(nom_rubrique) from rubrique_ids in function create but  it return only the last one and want return all the criter_name(nom_critere)</p>

```<code>def evaluer(self):
    self.ensure_one()
    rub = self.risque.rubrique_ids
    for rec in rub:
       rubriq = rec.nom_rubrique
       critere_ids = rec.critere_ids
           for obj1 in critere_ids:
               crit = obj1.nom_critere
               coeff = obj1.coefficient
           rubrique_etude = rubriq
    test = self.env['risque.evaluation'].create(
        {
            'risque_etude': self.risque.nom_risque,
            'etude': [(0, 0, {
                'rubrique_etude': rubrique_etude,
                'critere_etude': [(0, 0, {
                     'critere_name': crit,
                     'coefficient': coeff,
                     'critere_evaluation': '',
                     'note': '' })],
                })]
        }
    )

    return {
        'name': 'Evaluation',
        'view_type': 'form',
        'view_mode': 'tree,form',
        #'views': [{'view_mode': 'form', 'view_id': 'rub_id'}],
        'res_model': 'risque.evaluation',
        'type': 'ir.actions.act_window',
        'res_id': test.id,
        #'target': 'new',
        'flags': {'initial_mode': 'edit'},
        'context': self.env.context,
    }
</code>```

答:
It's only keeping the last line because you don't save them in list first:

    def evaluer(self):
        self.ensure_one()
        rub = self.risque.rubrique_ids
        for rec in rub:
            rubriq = rec.nom_rubrique
            critere_ids = rec.critere_ids
            # create a list to hold the critere_etude records
            critere_etude = []
            for obj1 in critere_ids:
               critere_etude.append((0, 0,{
                    'critere_name':obj1.nom_critere,
                    'coefficient':obj1.coefficient,
               }))
            rubrique_etude = rubriq
            test = self.env['risque.evaluation'].create({'risque_etude': self.risque.nom_risque,
                                               'etude': [(0, 0, {'rubrique_etude': rubrique_etude,
                                                                 # and here pass the whole list
                                                                 'critere_etude': critere_etude,
                                             })]
                            })
```

Title: Create new record odoo

Body:
I want to return only all rubrique_name(nom_rubrique) from rubrique_ids in function create but  it return only the last one and want return all the criter_name(nom_critere)

def evaluer(self):
    self.ensure_one()
    rub = self.risque.rubrique_ids
    for rec in rub:
       rubriq = rec.nom_rubrique
       critere_ids = rec.critere_ids
           for obj1 in critere_ids:
               crit = obj1.nom_critere
               coeff = obj1.coefficient
           rubrique_etude = rubriq
    test = self.env['risque.evaluation'].create(
        {
            'risque_etude': self.risque.nom_risque,
            'etude': [(0, 0, {
                'rubrique_etude': rubrique_etude,
                'critere_etude': [(0, 0, {
                     'critere_name': crit,
                     'coefficient': coeff,
                     'critere_evaluation': '',
                     'note': '' })],
                })]
        }
    )

    return {
        'name': 'Evaluation',
        'view_type': 'form',
        'view_mode': 'tree,form',
        #'views': [{'view_mode': 'form', 'view_id': 'rub_id'}],
        'res_model': 'risque.evaluation',
        'type': 'ir.actions.act_window',
        'res_id': test.id,
        #'target': 'new',
        'flags': {'initial_mode': 'edit'},
        'context': self.env.context,
    }


问:
regex for .aspx? to modify query string
I need to modify the query string,

from:   http://server/test/default.aspx

to:   http://server/test/default.aspx?videoplay=20

or

from  :   http://server/test/default.aspx?toolPlay=1233136844420765

to    :   http://server/test/default.aspx?videoplay=20&toolPlay=1233136844420765

ie. add videoplay=20& in between the query string

through jQuery. I have tried the .replace function but there is problem - I cannot find the correct regex. Can anyone provide a better approach or provide a regex for ".aspx?"

答:
Well, what I would do is this:

```<code>if (url.indexOf('?') != -1) {
    url += "&videoplay=20";
} else {
    url += "?videoplay=20";
}
</code>```

It doesn't use a regex, and it handles the case where the url does not contain a query string already.

ContentLicense: CC BY-SA 2.5

Title: regex for .aspx? to modify query string

Body:
Well, what I would do is this:

if (url.indexOf('?') != -1) {
    url += "&videoplay=20";
} else {
    url += "?videoplay=20";
}

It doesn't use a regex, and it handles the case where the url does not contain a query string already.


问:
Pandas- creating a table that inserts new rows based on column values?
I have a dataframe that has names of an item, data on it, and then competitor data all in one row:

```<code> name   value1   value2    ex_value1     ex_value2
 jim       0.4      0.6           0.7           0.3
 tim       0.2      0.8   0.766666667   0.233333333
 john        1        0           0.5           0.5
 paul      0.9      0.1   0.533333333   0.466666667
</code>```

What I want to do is create a new table that has indexes by name, but inserts new rows based on the competitor data, so that it shows jim, ex-jim, tim,ex-tim, etc:

```<code>   name       value1        value2
  jim               0.4           0.6
  tim               0.2           0.8
  john                1             0
  paul              0.9           0.1
  ex_jim            0.7           0.3
  ex_tim    0.766666667   0.233333333
  ex_john           0.5           0.5
  ex_paul   0.533333333   0.466666667
</code>```

How would I go about doing this? Would I have to set index on name, then insert new that way? Would I got about this through a loop? Appreciate guidance on this

Body:
I have a dataframe that has names of an item, data on it, and then competitor data all in one row:

 name   value1   value2    ex_value1     ex_value2
 jim       0.4      0.6           0.7           0.3
 tim       0.2      0.8   0.766666667   0.233333333
 john        1        0           0.5           0.5
 paul      0.9      0.1   0.533333333   0.466666667

What I want to do is create a new table that has indexes by name, but inserts new rows based on the competitor data, so that it shows jim, ex-jim, tim,ex-tim, etc:

   name       value1        value2
  jim               0.4           0.6
  tim               0.2           0.8
  john                1             0
  paul              0.9           0.1
  ex_jim            0.7           0.3
  ex_tim    0.766666667   0.233333333
  ex_john           0.5           0.5
  ex_paul   0.533333333   0.466666667

How would I go about doing this? Would I have to set index on name, then insert new that way? Would I got about this through a loop? Appreciate guidance on this

Body:
I would like recreate the df, you can add the reset_index() at the end

pd.DataFrame(df.iloc[:,1:].values.reshape(8,2),index=['','ex_']*4+df.name.repeat(2),columns=['value1','value2'])
Out[986]:
           value1    value2
name
jim      0.400000  0.600000
ex_jim   0.700000  0.300000
tim      0.200000  0.800000
ex_tim   0.766667  0.233333
john     1.000000  0.000000
ex_john  0.500000  0.500000
paul     0.900000  0.100000
ex_paul  0.533333  0.466667


问:
Last line of code wont execute?
Hi I'm having a problem with the last line of the code. It won't print anything.

```<code>invalid=True
global invalid
def start()
  x = input('Type the correct key:')
  if ("m" == x) or ("M"==x):
   print('Correct!')
  elif x!='m' or x!='M':
   print('Invalid Input.')
   invalid=False
 while invalid:
  start()
print('Next Question')
</code>```

When the input is 'm' or 'M' it should say Correct!

  Next question but it doesn't it just prints Correct!

Thank you in advance!

答:
A couple things here:

You have a logic error; invalid should be initialized as False and set to True if the elif is triggered.

You're calling start() from within itself, which is unnecessary; instead, the while could be around the whole definition (encompassing the if-elif), with invalid being set to False inside the if.

Title: Last line of code wont execute?

Body:
Hi I'm having a problem with the last line of the code. It won't print anything.

invalid=True
global invalid
def start()
  x = input('Type the correct key:')
  if ("m" == x) or ("M"==x):
   print('Correct!')
  elif x!='m' or x!='M':
   print('Invalid Input.')
   invalid=False
 while invalid:
  start()
print('Next Question')

When the input is 'm' or 'M' it should say Correct!

  Next question but it doesn't it just prints Correct!

Thank you in advance!


问:
Jquery wordpress post image add class by comparing image width
Problem:

On my WordPress site, I’ve applied some negative margin CSS to target img elements inside posts. My CSS works perfectly for all images with 655px+ width (fullwidth of .entry-content container).

Images with a width less than 655px, however, are unfortunately pulled toward the left of the .entry-content container, so they can’t center align.

To override this, I’ll need a jQuery script that will insert a custom class to all '.entry-content p img' elements below 655px wide.

Attached screenshot to help explain: please find attachment

Here's the post where you can see this problem: https://vegbyte.com/best-apples-for-juicing

So the jQuery logic is basically: "If image is less than 655px wide, insert this class: entry-img-small"

Tried

I have idea how to use jquery in wordpress. I am blank with jquery, thinking with such below code but no idea what to do.

```<code> $(window).load(function () {
   var image = $('.each img');
   if (image.width() < 500) {
      $('.oldclass').addClass('newclass');
  }
 });
</code>```

答:
Not sure if its a good idea but here you go better limit this for the content area too. .content img

```<code>jQuery(window).on('load', function() {
    jQuery('img').each(function() {
        if(jQuery(this).width() < 655) {
            jQuery(this).addClass('entry-img-small');
        }
    });
});
</code>```

In jQuery I think better if you use it on document ready before the images load and check for the width attribute.

```<code>jQuery(document).ready(function($) {
    $('img').each(function() {
        if($(this).attr('width') < 655) {
            $(this).addClass('entry-img-small');
        }
    });
});
</code>```

Body:
Problem:

On my WordPress site, I’ve applied some negative margin CSS to target img elements inside posts. My CSS works perfectly for all images with 655px+ width (fullwidth of .entry-content container).

Images with a width less than 655px, however, are unfortunately pulled toward the left of the .entry-content container, so they can’t center align.

To override this, I’ll need a jQuery script that will insert a custom class to all '.entry-content p img' elements below 655px wide.

Attached screenshot to help explain: please find attachment

Here's the post where you can see this problem: https://vegbyte.com/best-apples-for-juicing

So the jQuery logic is basically: "If image is less than 655px wide, insert this class: entry-img-small"

Tried

I have idea how to use jquery in wordpress. I am blank with jquery, thinking with such below code but no idea what to do.

 $(window).load(function () {
   var image = $('.each img');
   if (image.width() < 500) {
      $('.oldclass').addClass('newclass');
  }
 });

Body:
Not sure if its a good idea but here you go better limit this for the content area too. .content img

jQuery(window).on('load', function() {
    jQuery('img').each(function() {
        if(jQuery(this).width() < 655) {
            jQuery(this).addClass('entry-img-small');
        }
    });
});

In jQuery I think better if you use it on document ready before the images load and check for the width attribute.

jQuery(document).ready(function($) {
    $('img').each(function() {
        if($(this).attr('width') < 655) {
            $(this).addClass('entry-img-small');
        }
    });
});


问:
How to install Stackdriver monitoring agent in Google Container VM images?
I followed this instruction
https://cloud.google.com/monitoring/agent/install-agent#linux-install

```<code>$ curl -O "https://repo.stackdriver.com/stack-install.sh"
$ sudo bash stack-install.sh --write-gcm
Unidentifiable or unsupported platform.
</code>```

The content of /etc/os-release.

```<code>$ cat /etc/os-release
BUILD_ID=8820.0.0
NAME="Container-VM Image"
GOOGLE_CRASH_ID=Lakitu
VERSION_ID=55
BUG_REPORT_URL=https://crbug.com/new
PRETTY_NAME="Google Container-VM Image"
VERSION=55
GOOGLE_METRICS_PRODUCT_ID=26
HOME_URL="https://cloud.google.com/compute/docs/containers/vm-image/"
ID=gci
</code>```

https://cloud.google.com/compute/docs/containers/vm-image/faq#what_is_the_software_package_manager_for_container-vm_image

In order to update a particular package, the entire OS image needs to be updated

So, it seems that we must wait till update for a stackdriver agent installed version of  image or give it up.

Also this vm image is not my choice. Newly created GKE nodes use Container-VM images by default. So for now I'll try to create nodes via gcloud container node-pools create --image-type

答:
The way I was able to get around the issue with the agent's incompatibility with the new Chromium image was to deploy the agent as a container running in privileged mode (conveniently already built: https://github.com/wikiwi/stackdriver-agent) within a kubernetes DaemonSet so it runs on each host.
Here's the YAML for what I ended up using (spaces matter): </p>

```<code>apiVersion: extensions/v1beta1
kind: DaemonSet
metadata:
  name: stackdriver-agent
spec:
  template:
    metadata:
      labels:
        app: stackdriver-agent
    spec:
      containers:
      - name: stackdriver-agent
        image: wikiwi/stackdriver-agent
        securityContext:
          privileged: true
        volumeMounts:
        - mountPath: /mnt/proc
          name: procmnt
        env:
          - name: MONITOR_HOST
            value: "true"
      volumes:
      - name: procmnt
        hostPath:
          path: /proc
</code>```

Body:
I followed this instruction
https://cloud.google.com/monitoring/agent/install-agent#linux-install

$ curl -O "https://repo.stackdriver.com/stack-install.sh"
$ sudo bash stack-install.sh --write-gcm
Unidentifiable or unsupported platform.

The content of /etc/os-release.

$ cat /etc/os-release
BUILD_ID=8820.0.0
NAME="Container-VM Image"
GOOGLE_CRASH_ID=Lakitu
VERSION_ID=55
BUG_REPORT_URL=https://crbug.com/new
PRETTY_NAME="Google Container-VM Image"
VERSION=55
GOOGLE_METRICS_PRODUCT_ID=26
HOME_URL="https://cloud.google.com/compute/docs/containers/vm-image/"
ID=gci

https://cloud.google.com/compute/docs/containers/vm-image/faq#what_is_the_software_package_manager_for_container-vm_image

In order to update a particular package, the entire OS image needs to be updated

So, it seems that we must wait till update for a stackdriver agent installed version of  image or give it up.

Also this vm image is not my choice. Newly created GKE nodes use Container-VM images by default. So for now I'll try to create nodes via gcloud container node-pools create --image-type

Body:
The way I was able to get around the issue with the agent's incompatibility with the new Chromium image was to deploy the agent as a container running in privileged mode (conveniently already built: https://github.com/wikiwi/stackdriver-agent) within a kubernetes DaemonSet so it runs on each host.
Here's the YAML for what I ended up using (spaces matter):

apiVersion: extensions/v1beta1
kind: DaemonSet
metadata:
  name: stackdriver-agent
spec:
  template:
    metadata:
      labels:
        app: stackdriver-agent
    spec:
      containers:
      - name: stackdriver-agent
        image: wikiwi/stackdriver-agent
        securityContext:
          privileged: true
        volumeMounts:
        - mountPath: /mnt/proc
          name: procmnt
        env:
          - name: MONITOR_HOST
            value: "true"
      volumes:
      - name: procmnt
        hostPath:
          path: /proc

ContentLicense: CC BY-SA 4.0


问:
Session, cookies and ids
It was suggested to me to use sessions for cross page storage, and maintain the session ID by storing it in a GET parameter or cookie.

What's the safest way to save data into a session and make it last forever (like login informations)?

答:
The main difference between a cookie and a session is that the session data is stored on the server side while the cookie data is stored on the client side. But as sending sensitive data between server and client implies significant security concerns (data tampering, eavesdropping, etc.), the data should rather be stored on the server side.

But to associate a client with a session you need some kind of identifier. That’s where the session ID comes into use. Because since the HTTP is stateless (i.e. each request is an independent transaction that is unrelated to any previous request), there is no native way to identify a client just by its requests.

So instead of storing the data in a cookie on client side and have it sent back with every request, you just store the session ID on the client side and have it sent back with every request. That is way more secure as sensitive data is not being sent over the wire. All that is sent is the session ID (here you can use either the URL or a cookie as well).

But now as the session ID is the only information to associate a client to a session, it’s the session ID that has become some kind of sensitive data that needs to be protected. Here you need some kind of session authentication and management to avoid attacks on the session.

Title: Session, cookies and ids


问:
Using Cell Arrays in Interpolants in Matlab
I have a griddedInterpolant F and some of the input variables are in a cell array form. As an example, this is how I created the interpolant F:

```<code>[x,y,z] = ndgrid(-5:1:5);
t = x+y+z;
mycell  = {x,y};
F = griddedInterpolant(mycell{:},z,t);
</code>```

In reality, the size of the cell array mycell changes each time I run the code, and that's why I figured I have to use a cell array as an input. Now I'd like to call this function with the same input structure. When I have a single row for each input, everything works fine as in the following example:

```<code>testcell = {1,3};
F(testcell{:},5)

ans =

     9
</code>```

However, when I'd like the inputs in a vector form, the interpolant doesn't work and I get the following error:

```<code>testcell = {1,3; 2, 4};
F(testcell{:,:},[5;1])
</code>```

Error using griddedInterpolant/subsref

Invalid arguments specified in evaluating the interpolant.

Because I don't know the dimensions (number of columns) in my actual cell array, I can not break testcell apart. What is the right way to use the interpolant F in this case? I could, of course, use a for loop but this approach might be very time consuming due to the large number of data that I have.

答:
I got an answer to my problem in another forum. Apparently, this problem is solved just by slightly fixing how testcell is defined at the end as such:

```<code>testcell = {[1;2]; [3; 4]};
</code>```

Body:
I have a griddedInterpolant F and some of the input variables are in a cell array form. As an example, this is how I created the interpolant F:

[x,y,z] = ndgrid(-5:1:5);
t = x+y+z;
mycell  = {x,y};
F = griddedInterpolant(mycell{:},z,t);

In reality, the size of the cell array mycell changes each time I run the code, and that's why I figured I have to use a cell array as an input. Now I'd like to call this function with the same input structure. When I have a single row for each input, everything works fine as in the following example:

testcell = {1,3};
F(testcell{:},5)

ans =

     9

However, when I'd like the inputs in a vector form, the interpolant doesn't work and I get the following error:

testcell = {1,3; 2, 4};
F(testcell{:,:},[5;1])

Error using griddedInterpolant/subsref

Invalid arguments specified in evaluating the interpolant.

Because I don't know the dimensions (number of columns) in my actual cell array, I can not break testcell apart. What is the right way to use the interpolant F in this case? I could, of course, use a for loop but this approach might be very time consuming due to the large number of data that I have.

Body:
I got an answer to my problem in another forum. Apparently, this problem is solved just by slightly fixing how testcell is defined at the end as such:

testcell = {[1;2]; [3; 4]};


问:
Can't get item with python beautifulsoup
I'm trying to learn how to webscrape with beautifulsoup + python, and I want to grab the name of the cinematographer from https://letterboxd.com/film/donnie-darko/ but I can't figure out how to isolate the text. The html for what I want is written as below, what I want to output is "Steven Poster":

```<code><h3><span>Cinematography</span></h3>
<div class="text-sluglist">
    <p>
        <a href="/cinematography/steven-poster/" class="text-slug">Steven Poster</a>
    </p>
</div>
</code>```

within my code I've done soup.find(text="Cinematography"), and a mixture of different thigns like trying to find item or get_text from within the a and p tags, but ...

答:
You can do the same without using regex as well:

```<code>import requests
from bs4 import BeautifulSoup

res = requests.get('https://letterboxd.com/film/donnie-darko/')
soup = BeautifulSoup(res.text,'lxml')
item = soup.select("[href*='cinematography']")[0].text
print(item)
</code>```

Output:

```<code>Steven Poster
</code>```

Body:
I'm trying to learn how to webscrape with beautifulsoup + python, and I want to grab the name of the cinematographer from https://letterboxd.com/film/donnie-darko/ but I can't figure out how to isolate the text. The html for what I want is written as below, what I want to output is "Steven Poster":

Cinematography

        Steven Poster

within my code I've done soup.find(text="Cinematography"), and a mixture of different thigns like trying to find item or get_text from within the a and p tags, but ...

Body:
You can do the same without using regex as well:

import requests
from bs4 import BeautifulSoup

res = requests.get('https://letterboxd.com/film/donnie-darko/')
soup = BeautifulSoup(res.text,'lxml')
item = soup.select("[href*='cinematography']")[0].text
print(item)

Output:

Steven Poster


问:
File Uploader - Upload excel file and convert it into JSON and bind to the table
After uploading the excel file on file uploader control in sapui5, excel file is converted in to JSON using following code.

```<code>handleExcelUpload : function(e) {
  this._import(e.getParameter("files")
               && e.getParameter("files")[0]);
},
  _import : function(file) {
    if (file && window.FileReader) {
      var reader = new FileReader();
      that = this;
      result = {};
      var data;
      reader.onload = function(e) {
        var data = e.target.result;
        var wb = XLSX.read(data, {
          type : 'binary'
        });
        wb.SheetNames
        .forEach(function(sheetName) {
          var roa = XLSX.utils
          .sheet_to_row_object_array(wb.Sheets[sheetName]);
          if (roa.length > 0) {
            result[sheetName] = roa;
          }
        });
      };
      reader.readAsBinaryString(file);
    };
  },
</code>```

Note : I have used jszip.js and xlsx.js library to convert excel to JSON

Now in result variable I am getting JSON format data, and this data I have bind to the table.

The issue is, JSON binding with table is working fine with the Chrome, Firefox latest browser but, its not working on in IE 11 browser or it's showing only No data in table

Is there any other file reader method which supports IE11?

答:
Try this, without external library:

/*In the function "Press" */

```<code>var file = oFileUploader.getFocusDomRef().files[0];

            if (file && window.FileReader) {

                var reader = new FileReader();
                var that = this;

                reader.onload = function(e) {

                    var strCSV = e.target.result;
                    var arrCSV = strCSV.replace(/['",]/g, '').split(/[↵\n]+/).join(';').split(';');
                    var noOfCols = 11; // 11 Columns
                    var hdrRow = arrCSV.splice(0, noOfCols);

                    var oData = [];

                    while (arrCSV.length > 0) {

                        var obj = {};
                        var row = arrCSV.splice(0, noOfCols)

                        if (row.length > 1) {

                            for (var i = 0; i < row.length; i++) obj[hdrRow[i].replace(/\r/g, "")] = row[i].trim();

                            oData.push(obj) // Data Json

                        }

                    }

                    oTable.setModel(new sap.ui.model.json.JSONModel(oData)); // Binding model
                };

                reader.readAsText(file, 'ISO-8859-1');
            }
</code>```

Regards.

Body:
After uploading the excel file on file uploader control in sapui5, excel file is converted in to JSON using following code.

handleExcelUpload : function(e) {
  this._import(e.getParameter("files")
               && e.getParameter("files")[0]);
},
  _import : function(file) {
    if (file && window.FileReader) {
      var reader = new FileReader();
      that = this;
      result = {};
      var data;
      reader.onload = function(e) {
        var data = e.target.result;
        var wb = XLSX.read(data, {
          type : 'binary'
        });
        wb.SheetNames
        .forEach(function(sheetName) {
          var roa = XLSX.utils
          .sheet_to_row_object_array(wb.Sheets[sheetName]);
          if (roa.length > 0) {
            result[sheetName] = roa;
          }
        });
      };
      reader.readAsBinaryString(file);
    };
  },

Note : I have used jszip.js and xlsx.js library to convert excel to JSON

Now in result variable I am getting JSON format data, and this data I have bind to the table.

The issue is, JSON binding with table is working fine with the Chrome, Firefox latest browser but, its not working on in IE 11 browser or it's showing only No data in table

Is there any other file reader method which supports IE11?

Body:
Try this, without external library:

/*In the function "Press" */

var file = oFileUploader.getFocusDomRef().files[0];

            if (file && window.FileReader) {

                var reader = new FileReader();
                var that = this;

                reader.onload = function(e) {

                    var strCSV = e.target.result;
                    var arrCSV = strCSV.replace(/['",]/g, '').split(/[↵\n]+/).join(';').split(';');
                    var noOfCols = 11; // 11 Columns
                    var hdrRow = arrCSV.splice(0, noOfCols);

                    var oData = [];

                    while (arrCSV.length > 0) {

                        var obj = {};
                        var row = arrCSV.splice(0, noOfCols)

                        if (row.length > 1) {

                            for (var i = 0; i < row.length; i++) obj[hdrRow[i].replace(/\r/g, "")] = row[i].trim();

                            oData.push(obj) // Data Json

                        }

                    }

                    oTable.setModel(new sap.ui.model.json.JSONModel(oData)); // Binding model
                };

                reader.readAsText(file, 'ISO-8859-1');
            }

Regards.


问:
How do I run a Tensorflow Object Detection API model in iOS?
I have just trained a model with satisfactory results and I have the frozen_inference_graph.pb . How would I go about running this on iOS? It was trained on SSD Mobilenet V1 if that helps. Optimally I'd like to run it using the GPU (I know the tensorflow API can't do that on iOS), but it would be great to just have it on CPU first. </p>

答:
Support was just announced for importing TensorFlow models into Core ML. This is accomplished using the tfcoreml converter, which should take in your .pb graph and output a Core ML model. From there, you can use this model with Core ML and either take in still images or video frames for processing.

At that point, it's up to you to make sure you're providing the correct input colorspace and size, then extracting and processing the SSD results correctly to get your object classes and bounding boxes.


问:
How to Import XML data into Oracle database table using sqlldr command
I am trying to import XML data into Oracle database, but getting the error described bellow

Created the table:

```<code>CREATE TABLE fv_xml_12 (
   id    NUMBER,
   fv  XMLTYPE)
   XMLTYPE fv STORE AS OBJECT RELATIONAL
      XMLSCHEMA "http://www.example.com/fvInteger.xsd"
      ELEMENT "FeatureVector";
</code>```

Created the loader:

```<code>options (errors=9999999, rows=5)
load data
 characterset WE8MSWIN1252
infile '/home/alucard/fv_data_cophir/loader_pbf/semiestruturado/12dim/FeatureVectors_XML.txt'
 badfile '/home/alucard/fv_data_cophir/loader_pbf/semiestruturado/12dim/FeatureVectors.bad'
 discardfile '/home/alucard/fv_data_cophir/loader_pbf/semiestruturado/12dim/FeatureVectors.dsc'
 into table fv_xml_12
 fields terminated by " "
( id, fv)
</code>```

The data:

```<code>1 <FeatureVector><feature>11</feature><feature>50</feature><feature>19</feature><feature>27</feature><feature>8</feature><feature>13</feature><feature>17</feature><feature>22</feature><feature>25</feature><feature>9</feature><feature>9</feature><feature>20</feature></FeatureVector>
2 <FeatureVector><feature>13</feature><feature>34</feature><feature>31</feature><feature>7</feature><feature>18</feature><feature>8</feature><feature>20</feature><feature>15</feature><feature>12</feature><feature>10</feature><feature>19</feature><feature>19</feature></FeatureVector>
</code>```

sqlldr command:

```<code>sqlldr user/pass control=imp_fv_12dim.ctl
</code>```

But I am getting the errors...

Record 1: Rejected - Error on table FV_XML_12, column FV. Field in
  data file exceeds maximum length
  Record 2: Rejected - Error on table
  FV_XML_12, column FV. Field in data file exceeds maximum length

What is wrong?

答:
You aren't specifying a data type for the fv field, so it defaults to CHAR; and from the documentation:

For a delimited CHAR field for which no length is specified, the default is 255 bytes.

Your XML values are about 280 characters, so they exceed that limit. You can avoid the error by specifying a larger size:

```<code>...
fields terminated by " "
( id, fv char(4000) )
</code>```

Tested in 11gR2; without the size I get the same error, with the size specified the two rows load successfully. (Although I created the table without the store as as I don't have your .xsd.) But it should work exactly the same in 12c.

Also see Load XMLType Data Using SQL*Loader for other approaches, such as putting each XML into a separate file.

Body:
I am trying to import XML data into Oracle database, but getting the error described bellow

Created the table:

CREATE TABLE fv_xml_12 (
   id    NUMBER,
   fv  XMLTYPE)
   XMLTYPE fv STORE AS OBJECT RELATIONAL
      XMLSCHEMA "http://www.example.com/fvInteger.xsd"
      ELEMENT "FeatureVector";

Created the loader:

options (errors=9999999, rows=5)
load data
 characterset WE8MSWIN1252
infile '/home/alucard/fv_data_cophir/loader_pbf/semiestruturado/12dim/FeatureVectors_XML.txt'
 badfile '/home/alucard/fv_data_cophir/loader_pbf/semiestruturado/12dim/FeatureVectors.bad'
 discardfile '/home/alucard/fv_data_cophir/loader_pbf/semiestruturado/12dim/FeatureVectors.dsc'
 into table fv_xml_12
 fields terminated by " "
( id, fv)

The data:

1 <FeatureVector><feature>11</feature><feature>50</feature><feature>19</feature><feature>27</feature><feature>8</feature><feature>13</feature><feature>17</feature><feature>22</feature><feature>25</feature><feature>9</feature><feature>9</feature><feature>20</feature></FeatureVector>
2 <FeatureVector><feature>13</feature><feature>34</feature><feature>31</feature><feature>7</feature><feature>18</feature><feature>8</feature><feature>20</feature><feature>15</feature><feature>12</feature><feature>10</feature><feature>19</feature><feature>19</feature></FeatureVector>

sqlldr command:

sqlldr user/pass control=imp_fv_12dim.ctl

But I am getting the errors...

Record 1: Rejected - Error on table FV_XML_12, column FV. Field in
  data file exceeds maximum length
  Record 2: Rejected - Error on table
  FV_XML_12, column FV. Field in data file exceeds maximum length

What is wrong?

Body:
You aren't specifying a data type for the fv field, so it defaults to CHAR; and from the documentation:

For a delimited CHAR field for which no length is specified, the default is 255 bytes.

Your XML values are about 280 characters, so they exceed that limit. You can avoid the error by specifying a larger size:

...
fields terminated by " "
( id, fv char(4000) )

Tested in 11gR2; without the size I get the same error, with the size specified the two rows load successfully. (Although I created the table without the store as as I don't have your .xsd.) But it should work exactly the same in 12c.

Also see Load XMLType Data Using SQL*Loader for other approaches, such as putting each XML into a separate file.


答:
You can try out something like this

```<code>date = db.data.find({ 'Date' : {new ISODate("2017-12-6T23:59:59Z") } },{'Date' : '1'})

for document in date:
print(date)
</code>```

Or you could try out this,

```<code>date = db.data.find({ 'Date' : {new Date(2017,12,6) } },{'Date' : '1'})
for document in date:
    print(date)
</code>```

Title: MongoDB Query by DateTime with Python

Body:
I want to query MongoDB and return records that have the date of 12/6/2017. The date is in this format:

u'Date': datetime.datetime(2017, 12, 6, 15, 9, 21, 303000)

So, how do I query just the year, month, and day of that entry?  I have tried:

date = db.data.find({ 'Date' : {'2017, 12, 6'} },{'Date' : '1'})
for document in date:
     print(date)

Which returns: "InvalidDocument: Cannot encode object: set(['2017, 12, 6'])".

I also tried:

date = db.data.find({ 'Date' : {datetime('2017, 12, 6')} },{'Date' : '1'})
for document in date:
    print(date)

Which returns: "NameError: name 'datetime' is not defined".

UPDATE...SOLUTION
I was putting the date into Mongo incorrectly. I'm now putting the date into Mongo with Python like this:

import datetime
import dateutil.parser

# the date
now = datetime.datetime.now()
year = now.year
month = now.month
day = now.day
theDate = str(year) + "-" + str(month) + "-" + str(day)
dateStr = theDate
date = dateutil.parser.parse(dateStr)
# Then put that date into your Mongo insert

This is how I'm querying by date. This pulls documents inserted after yersterday (today).

import dateutil.parser, datetime
now = datetime.datetime.now()
year = now.year
month = now.month
yesterday = now.day - 1
dateStr = str(year) + "-" + str(month) + "-" + str(yesterday)
date = dateutil.parser.parse(dateStr)

cursor = db.data.find({'Date' : { '$gt' : date}},{'Date':'1'})
for document in cursor:
    print(document)

Body:
You can try out something like this

date = db.data.find({ 'Date' : {new ISODate("2017-12-6T23:59:59Z") } },{'Date' : '1'})

for document in date:
print(date)

Or you could try out this,

date = db.data.find({ 'Date' : {new Date(2017,12,6) } },{'Date' : '1'})
for document in date:
    print(date)


问:
The sandbox is not in sync with the Podfile.lock-ios
I have got the following errors after trying multiple answers from the google.

```<code>PhaseScriptExecution Check\ Pods\ Manifest.lock /Users/apple/Library/Developer/Xcode/DerivedData/Build/Intermediates/FoodSpot.build/Debug-
    iphonesimulator/FoodSpotTests.build/Script-36819C3C1B6A30F50091382D.sh
        cd "/Users/apple/Downloads/FoodSpot 2"
        /bin/sh -c /Users/apple/Library/Developer/Xcode/DerivedData/Build/Intermediates/FoodSpot.build/Debug-iphonesimulator/FoodSpotTests.build/Script-36819C3C1B6A30F50091382D.sh

    diff: /../Podfile.lock: No such file or directory
    diff: /Manifest.lock: No such file or directory
    error: The sandbox is not in sync with the Podfile.lock.
    Run 'pod   install' or update your CocoaPods installation.
</code>```

I have updated and installed many times, but they are of no use.

答:
If you happen to move your Podfile like i did and face this issue, the solution discussed below may help -

Delete all of the following - Pods folder, xcworkspace
file, podlock file (skip the ones that are not available for subfolders)

delete all steps that has [cp] in it from the build phase tab

repeat step 1 & 2 for all the sub projects that you have in your workspace

open workspace, go into each project and delete framework for pods, and delete the pods folder from each project

close workspace

run pod install

you should now be able to open, build and run the project

Body:
I have got the following errors after trying multiple answers from the google.

PhaseScriptExecution Check\ Pods\ Manifest.lock /Users/apple/Library/Developer/Xcode/DerivedData/Build/Intermediates/FoodSpot.build/Debug-
    iphonesimulator/FoodSpotTests.build/Script-36819C3C1B6A30F50091382D.sh
        cd "/Users/apple/Downloads/FoodSpot 2"
        /bin/sh -c /Users/apple/Library/Developer/Xcode/DerivedData/Build/Intermediates/FoodSpot.build/Debug-iphonesimulator/FoodSpotTests.build/Script-36819C3C1B6A30F50091382D.sh

    diff: /../Podfile.lock: No such file or directory
    diff: /Manifest.lock: No such file or directory
    error: The sandbox is not in sync with the Podfile.lock.
    Run 'pod   install' or update your CocoaPods installation.

I have updated and installed many times, but they are of no use.


问:
asp.net unable to cast object of type error
I am getting an error when trying to convert json response from coinmarketcap.com's API.

The error is:

"Unable to cast object of type
  'System.Collections.Generic.List`1[System.Object]' to type
  'System.Dynamic.ExpandoObject'"

The web client works fine for other API's but for some reason coin object is not populated.  Any insight into a fix in either vb.net or c# would be much appreciated.

```<code>    Dim dt_results As DataTable, dr As DataRow, url As String = String.Empty, json As Object = Nothing, iCount As Integer = 0

    'temporarily store results
    dt_results = New DataTable
    dt_results.Columns.Add("name", GetType(String))
    dt_results.Columns.Add("symbol", GetType(String))
    dt_results.Columns.Add("price_usd", GetType(Double))

    Try
        url = "https://api.coinmarketcap.com/v1/ticker/?convert=usd&limit=10"
        Dim theurl As New Uri(url)

        Using webClient = New System.Net.WebClient()

            json = webClient.DownloadString(theurl)

            'create json object
            Dim converter = New ExpandoObjectConverter()
            Dim coin As Object = JsonConvert.DeserializeObject(Of ExpandoObject)(json, converter)

            For Each item In coin

                Dim name As String = coin(iCount).name
                Dim symbol As String = coin(iCount).symbol
                Dim price_usd As Double = coin(iCount).price_usd
                dr = dt_results.NewRow()
                dr("name") = name
                dr("symbol") = symbol
                dr("price_usd") = price_usd
                dt_results.Rows.Add(dr)
                iCount = iCount + 1
            Next
        End Using

    Catch ex As Exception
        Dim ts As String = ex.Message
        json = "1"
    End Try
</code>```

Working solution...

```<code>        Dim d As JArray = JArray.Parse(json)

            For i As Integer = 0 To d.Count
                Dim name As String = d(i).Item("name")
                Dim symbol As String = d(i).Item("symbol")
                Dim price_usd As Double = CDbl(d(i).Item("price_usd"))
                dr = dt_results.NewRow()
                dr("name") = name
                dr("symbol") = symbol
                dr("price_usd") = price_usd
                dt_results.Rows.Add(dr)
                iCount = iCount + 1
            Next
</code>```

答:
Haven't written in VB.NET for a very long while, but I have a solution for you in C#. If you do not have a clearly defined object model, I would recommend using Json.Net, parsing it as a dynamic object. We're getting and array from the API, so we need to tell Json.Net that we're expecting it to parse it as such. Below is a working solution for me (albeit in C#)</p>

```<code>using (WebClient cli = new WebClient())
        {
            string result = cli.DownloadString("https://api.coinmarketcap.com/v1/ticker/?convert=usd&limit=10");
            dynamic arrayFromApi = JArray.Parse(result);

            // Use however - presumably loop through items
            string s = arrayFromApi[0].name;
        }
</code>```

Body:
I am getting an error when trying to convert json response from coinmarketcap.com's API.

The error is:

"Unable to cast object of type
  'System.Collections.Generic.List`1[System.Object]' to type
  'System.Dynamic.ExpandoObject'"

The web client works fine for other API's but for some reason coin object is not populated.  Any insight into a fix in either vb.net or c# would be much appreciated.

    Dim dt_results As DataTable, dr As DataRow, url As String = String.Empty, json As Object = Nothing, iCount As Integer = 0

    'temporarily store results
    dt_results = New DataTable
    dt_results.Columns.Add("name", GetType(String))
    dt_results.Columns.Add("symbol", GetType(String))
    dt_results.Columns.Add("price_usd", GetType(Double))

    Try
        url = "https://api.coinmarketcap.com/v1/ticker/?convert=usd&limit=10"
        Dim theurl As New Uri(url)

        Using webClient = New System.Net.WebClient()

            json = webClient.DownloadString(theurl)

            'create json object
            Dim converter = New ExpandoObjectConverter()
            Dim coin As Object = JsonConvert.DeserializeObject(Of ExpandoObject)(json, converter)

            For Each item In coin

                Dim name As String = coin(iCount).name
                Dim symbol As String = coin(iCount).symbol
                Dim price_usd As Double = coin(iCount).price_usd
                dr = dt_results.NewRow()
                dr("name") = name
                dr("symbol") = symbol
                dr("price_usd") = price_usd
                dt_results.Rows.Add(dr)
                iCount = iCount + 1
            Next
        End Using

    Catch ex As Exception
        Dim ts As String = ex.Message
        json = "1"
    End Try

Working solution...

        Dim d As JArray = JArray.Parse(json)

            For i As Integer = 0 To d.Count
                Dim name As String = d(i).Item("name")
                Dim symbol As String = d(i).Item("symbol")
                Dim price_usd As Double = CDbl(d(i).Item("price_usd"))
                dr = dt_results.NewRow()
                dr("name") = name
                dr("symbol") = symbol
                dr("price_usd") = price_usd
                dt_results.Rows.Add(dr)
                iCount = iCount + 1
            Next

Body:
Haven't written in VB.NET for a very long while, but I have a solution for you in C#. If you do not have a clearly defined object model, I would recommend using Json.Net, parsing it as a dynamic object. We're getting and array from the API, so we need to tell Json.Net that we're expecting it to parse it as such. Below is a working solution for me (albeit in C#)

using (WebClient cli = new WebClient())
        {
            string result = cli.DownloadString("https://api.coinmarketcap.com/v1/ticker/?convert=usd&limit=10");
            dynamic arrayFromApi = JArray.Parse(result);

            // Use however - presumably loop through items
            string s = arrayFromApi[0].name;
        }


问:
Select multiple columns from another table depending on value of column
I'm not even sure this is possible, but I have an order table (online store).  Within this table, the shipping and billing address columns are ID's which correspond with the address table.

For E.g.

```<code>OrderID     ShippingAddressID   BillingAddressID
201800194   21183               21182
</code>```

The Address table then lists the address information.

```<code>AddressID   Address1            City        RegionCode
21182       123 Somewhere Dr    Hometown1   Florida
21183       456 Elsewhere Rd    Hometown2   Florida
</code>```

I'd like the resulting listing to show something similar to this:

```<code>OrderID     BillingAddress1     BillingCity BillingRegionCode   ShippingAddress1    ShippingCity    ShippingRegionCode
201800194   123 Somewhere Dr    Hometown1   Florida             456 Elsewhere Rd    Hometown2       Florida
</code>```

Is this even possible?

Thanks..

答:
Lets assume your Tables are Order, Address.

```<code>Select A.OrderID, B1.Address1 As 'BillingAddress1', B1.City As 'BillingCity', B1.RegionCode As 'BillingRegionCode', B2.Address1 As 'ShippingAddress1', B2.City As 'ShippingCity', B2.RegionCode As 'ShippingRegionCode'
FROM Order AS A
Left Join Address  AS B1 On A.BillingAddressID = B1.AddressID
Left Join Address  As B2 On A.ShippingAddressID = B2.AddressID
</code>```

Hope this Helps

Body:
I'm not even sure this is possible, but I have an order table (online store).  Within this table, the shipping and billing address columns are ID's which correspond with the address table.

For E.g.

OrderID     ShippingAddressID   BillingAddressID
201800194   21183               21182

The Address table then lists the address information.

AddressID   Address1            City        RegionCode
21182       123 Somewhere Dr    Hometown1   Florida
21183       456 Elsewhere Rd    Hometown2   Florida

I'd like the resulting listing to show something similar to this:

OrderID     BillingAddress1     BillingCity BillingRegionCode   ShippingAddress1    ShippingCity    ShippingRegionCode
201800194   123 Somewhere Dr    Hometown1   Florida             456 Elsewhere Rd    Hometown2       Florida

Is this even possible?

Thanks..

Body:
Lets assume your Tables are Order, Address.

Select A.OrderID, B1.Address1 As 'BillingAddress1', B1.City As 'BillingCity', B1.RegionCode As 'BillingRegionCode', B2.Address1 As 'ShippingAddress1', B2.City As 'ShippingCity', B2.RegionCode As 'ShippingRegionCode'
FROM Order AS A
Left Join Address  AS B1 On A.BillingAddressID = B1.AddressID
Left Join Address  As B2 On A.ShippingAddressID = B2.AddressID

Hope this Helps


问:
TypeScript error TS2449: Class 'x' used before its declaration
I don't understand the tsc compilation process with respect to<reference> and splitting the classes of a namespace across multiple files. I'm using the pattern:

src/base.ts

```<code>namespace MyNameSpace {
  export class Base {
     /** constructor, etc. */
  }
}
</code>```

src/subclass.ts

```<code>/// <reference path="./base.ts" />

namespace MyNameSpace {
  export class Subclass {
     /** constructor, etc. */
  }
}
</code>```

This trivial example works. But as I use the pattern on more files, I periodically get the error TypeScript error TS2449: Class 'x' used before its declaration..

Are we back to manually managing declaration orderings, like .c/.h files? If so, what tools will help be back track the reference to find the error?

My aim to have a manageable set of files that compile into a single .js and .d.ts (for another TypeScript library to use). If there a better solution for this scenario? Attempts with variations of Webpack and imports have failed me.

If it matters, I'm also using nested namespaces, where the members are defined in subdirectories. I'm always using relative reference paths.

This is very similar to typescript Base type 'xxxx' is referenced before its declaration, which dealt with a module split across multiple files.

答:
Major Terminology Alert

Namespaces are not preferred over modules. This is a very important point. Let's dive into the history...

Namespaces used to be declared like this:

```<code>module MyNamespace {

}
</code>```

But they are now declared like this:

```<code>namespace MyNamespace {

}
</code>```

When declaring a namespace, the namespace keyword is preferred to the old module keyword.

The reason the module keyword was replaced with namespace is that people confused them with "modules". You can see where the confusion might come from! Now actual modules (i.e. files that export or import something) are actually a bit better than namespaces, which is why I have spent the entire answer so far covering all this.

Use Modules

With this in mind, you might consider using modules. Each module gives you a naming context and keeps stuff out of the global scope. You can import and export and everything should work as expected (and you can still bundle it if you like).

src/base.ts

```<code>export class Base {

}
</code>```

src/subclass.ts

```<code>import * as Example from './subclass.ts';

export class Base extends Example.Base {

}
</code>```

Namespace Merging

If you want to stick with namespaces, you have to respect that everything you place within a namespace (even when that namespace is spread across multiple files) contributes to a single naming context... so you'll have to name the subclass differently.

src/base.ts

```<code>namespace MyNameSpace {
  export class Base {
     /** constructor, etc. */
  }
}
</code>```

src/subclass.ts

```<code>/// <reference path="./base.ts" />

namespace MyNameSpace {
  export class Sub extends Base {
     /** constructor, etc. */
  }
}
</code>```

So ultimately, you can choose modules (proper external modules) where each file has its own naming context, and you can easily avoid naming collisions - or namsepaces where you'll need to be aware that each namespace is a single naming context.

Small Print

In may examples I have inherited Base in the subclass for illustration. You're question didn't exactly do that, but I wanted to illustrate the concept. The question had two classes within the namespace with the same name, which is a duplicate name conflict.

Body:
I don't understand the tsc compilation process with respect to<reference> and splitting the classes of a namespace across multiple files. I'm using the pattern:

src/base.ts

namespace MyNameSpace {
  export class Base {
     /** constructor, etc. */
  }
}

src/subclass.ts

/// <reference path="./base.ts" />

namespace MyNameSpace {
  export class Subclass {
     /** constructor, etc. */
  }
}

This trivial example works. But as I use the pattern on more files, I periodically get the error TypeScript error TS2449: Class 'x' used before its declaration..

Are we back to manually managing declaration orderings, like .c/.h files? If so, what tools will help be back track the reference to find the error?

My aim to have a manageable set of files that compile into a single .js and .d.ts (for another TypeScript library to use). If there a better solution for this scenario? Attempts with variations of Webpack and imports have failed me.

If it matters, I'm also using nested namespaces, where the members are defined in subdirectories. I'm always using relative reference paths.

This is very similar to typescript Base type 'xxxx' is referenced before its declaration, which dealt with a module split across multiple files.

Body:
Major Terminology Alert

Namespaces are not preferred over modules. This is a very important point. Let's dive into the history...

Namespaces used to be declared like this:

module MyNamespace {

}

But they are now declared like this:

namespace MyNamespace {

}

When declaring a namespace, the namespace keyword is preferred to the old module keyword.

The reason the module keyword was replaced with namespace is that people confused them with "modules". You can see where the confusion might come from! Now actual modules (i.e. files that export or import something) are actually a bit better than namespaces, which is why I have spent the entire answer so far covering all this.

Use Modules

With this in mind, you might consider using modules. Each module gives you a naming context and keeps stuff out of the global scope. You can import and export and everything should work as expected (and you can still bundle it if you like).

src/base.ts

export class Base {

}

src/subclass.ts

import * as Example from './subclass.ts';

export class Base extends Example.Base {

}

Namespace Merging

If you want to stick with namespaces, you have to respect that everything you place within a namespace (even when that namespace is spread across multiple files) contributes to a single naming context... so you'll have to name the subclass differently.

src/base.ts

namespace MyNameSpace {
  export class Base {
     /** constructor, etc. */
  }
}

src/subclass.ts

/// <reference path="./base.ts" />

namespace MyNameSpace {
  export class Sub extends Base {
     /** constructor, etc. */
  }
}

So ultimately, you can choose modules (proper external modules) where each file has its own naming context, and you can easily avoid naming collisions - or namsepaces where you'll need to be aware that each namespace is a single naming context.

Small Print

In may examples I have inherited Base in the subclass for illustration. You're question didn't exactly do that, but I wanted to illustrate the concept. The question had two classes within the namespace with the same name, which is a duplicate name conflict.


问:
Exporting JAR projects that use a common project
I have 4 different Java Projects created in Eclipse.

One of them contains all my Utilities and Helper methods, that the other 3 projects use.

I don't want to copy that same package 3 times into each project, since I want to be able to just edit it in one place if I should have to. So, I have referenced the myUtilities project from all other 3 projects.

I'll be exporting the 3 main projects and they will be going to different servers to run independently as  "java -jar myproject.jar"

Everytime I do an export, the myUtilities.jar is not getting compiled in the JAR. If I open the JAR, I can see it is not there.  And this is going to be a problem when I move them to the other servers.

Is there a way to add the package into the source for the JAR? Or am I going to have to copy the myUtilities.jar into the JAVA_HOME of each server?

This is my current Manifest file:

```<code>Manifest-Version: 1.0
Main-Class: com.elcool.process.alpha.RetrieverMain
</code>```

答:
You should use "Export" -> "Runnable Jar" to have dependent projects included correctly.

There are three different kinds of runnable jars, depending on you want a single jar-file with all classes, a single jar file with dependent jars and a correct Class-Path in the manifest, and a single jar file with the dependent jars enclosed and a special classloader understanding this.

Body:
I have 4 different Java Projects created in Eclipse.

One of them contains all my Utilities and Helper methods, that the other 3 projects use.

I don't want to copy that same package 3 times into each project, since I want to be able to just edit it in one place if I should have to. So, I have referenced the myUtilities project from all other 3 projects.

I'll be exporting the 3 main projects and they will be going to different servers to run independently as  "java -jar myproject.jar"

Everytime I do an export, the myUtilities.jar is not getting compiled in the JAR. If I open the JAR, I can see it is not there.  And this is going to be a problem when I move them to the other servers.

Is there a way to add the package into the source for the JAR? Or am I going to have to copy the myUtilities.jar into the JAVA_HOME of each server?

This is my current Manifest file:

Manifest-Version: 1.0
Main-Class: com.elcool.process.alpha.RetrieverMain


问:
Jenkins Jacoco Plugin not linking Groovy source files
Is there a way to configure the Jenkins Jacoco Plugin to link Groovy source files to the coverage report? The coverage statistics are calculated correctly, however, in a mixed Java/Groovy Project, only the Java files are linked. The configuration looks as follows:

答:
Based upon this bug report, it looks like the 2.2+ releases have changed how source code is linked in the report such that it only works for *.java files. One possible work-around is to downgrade the JaCoCo plugin to 2.1.0. This is what we did and it works; although I am not sure what features and bug fixes we give up in 2.2+ so it might not be worth it in your situation.

It looks like there is a Pull Request that needs to be reviewed and merged so that it can be released in an upcoming version.


问:
How to scrape search results using WebGrude?
I recently used WebGrude for scrape some content from web pages. Then I tried to scrape some search results from e-bay. Here what tried,

```<code>@Page("http://www.ebay.com/sch/{0}")
public class PirateBay {

    public static void main(String[] args) {
        //Search calls Browser, which loads the page on a PirateBay instance
        PirateBay search = PirateBay.search("iPhone");

        while (search != null) {
             search.magnets.forEach(System.out::println);
            search = search.nextPage();
        }
    }

    public static PirateBay search(String term) {
        return Browser.get(PirateBay.class, term);
    }

    private PirateBay() {
    }

    /*
* This selector matches all magnet links. The result is added to this String list.
* The default behaviour is to use the rendered html inside the matched tag, but here
* we want to use the href value instead.
*/
    @Selector(value = "#ResultSetItems a[href*=magnet]", attr = "href")
    public List<String> magnets;

/*
* This selector matches a link to the next page result, wich can be mapped to a PirateBay instance.
* The Link next gets the page on the href attribute of the link when method visit is called.
*/
    @Selector("a:has(img[alt=Next])")
    private Link<PirateBay> next;

    public PirateBay nextPage() {
        if (next == null)
            return null;
        return next.visit();
        }
    }
</code>```

But the result is empty. How may I scrape search results using this?

答:
The selector "#ResultSetItems a[href*=magnet]" selects the links where the href attribute has the string "magnet" on its value.

Here you can read more about Atribute selectors: attribute_selectors

What you want is "#ResultSetItems h3.lvtitle a"

To test your selectors there is this nice repl that uses Jsoup, the same library used by webgrude Try jsoup

Body:
I recently used WebGrude for scrape some content from web pages. Then I tried to scrape some search results from e-bay. Here what tried,

@Page("http://www.ebay.com/sch/{0}")
public class PirateBay {

    public static void main(String[] args) {
        //Search calls Browser, which loads the page on a PirateBay instance
        PirateBay search = PirateBay.search("iPhone");

        while (search != null) {
             search.magnets.forEach(System.out::println);
            search = search.nextPage();
        }
    }

    public static PirateBay search(String term) {
        return Browser.get(PirateBay.class, term);
    }

    private PirateBay() {
    }

    /*
* This selector matches all magnet links. The result is added to this String list.
* The default behaviour is to use the rendered html inside the matched tag, but here
* we want to use the href value instead.
*/
    @Selector(value = "#ResultSetItems a[href*=magnet]", attr = "href")
    public List<String> magnets;

/*
* This selector matches a link to the next page result, wich can be mapped to a PirateBay instance.
* The Link next gets the page on the href attribute of the link when method visit is called.
*/
    @Selector("a:has(img[alt=Next])")
    private Link<PirateBay> next;

    public PirateBay nextPage() {
        if (next == null)
            return null;
        return next.visit();
        }
    }

But the result is empty. How may I scrape search results using this?


问:
passing params to indices of an array in rails controller
I'm collecting user input via forms and trying to combine the values into an array variable in my controller.

controller

```<code>MyController < ApplicationController
  def con_action
   @array_var = Array.new(n)
   @array_var[index] = params[:user_input]
  end
end
</code>```

view

```<code><%= form_for :doesntmatter do |f| %>
    <%= f.text_field :user_input, placeholder: 'input for index 0'

    <%= f.text_field :user_input, placeholder: 'input for index 1'
<% end %>
</code>```

also the array.size is always changing so making it dynamic is ideal.

I edited it so it makes more sense, my problem is that I won't know which index of the array that :user_input belongs to and need to have the form provide that index number

答:
in you view, use this

```<code>    <%= form_tag(controller: : MyController, action: : con_action) do %>
       <%5.time do |n|%>
    <%= text_field_tag "user_input_"+n.to_s, nil,placeholder: "something" %>
       <%end%>
    <%submit_tag%>
    <%end%>
</code>```

then in your controller you will get what you want in the params

use the  to_i function to convert to integer

```<code>    def con_action
      @array_var = Array.new(n)
       5.times do |n|
       @array_var[n] = params['user_input_'+n.to_s]
      end
     end
</code>```

P.S. make sure you have a post route for mycontroller#con_action

Body:
I'm collecting user input via forms and trying to combine the values into an array variable in my controller.

controller

MyController < ApplicationController
  def con_action
   @array_var = Array.new(n)
   @array_var[index] = params[:user_input]
  end
end

view

<%= form_for :doesntmatter do |f| %>
    <%= f.text_field :user_input, placeholder: 'input for index 0'

    <%= f.text_field :user_input, placeholder: 'input for index 1'
<% end %>

also the array.size is always changing so making it dynamic is ideal.

I edited it so it makes more sense, my problem is that I won't know which index of the array that :user_input belongs to and need to have the form provide that index number

Body:
in you view, use this

    <%= form_tag(controller: : MyController, action: : con_action) do %>
       <%5.time do |n|%>
    <%= text_field_tag "user_input_"+n.to_s, nil,placeholder: "something" %>
       <%end%>
    <%submit_tag%>
    <%end%>

then in your controller you will get what you want in the params

use the  to_i function to convert to integer

    def con_action
      @array_var = Array.new(n)
       5.times do |n|
       @array_var[n] = params['user_input_'+n.to_s]
      end
     end

P.S. make sure you have a post route for mycontroller#con_action


问:
Set HSTS Header on WebSphere Application Server
An application can use HSTS by setting the Strict-Transport-Security header with the appropriate values.
Once a browser that supports HSTS receives this header, it will force all future connections to that domain to take place over  or  ridirect to HTTPS.

I've read on this site http://publib.boulder.ibm.com/httpserv/ihsdiag/questions.html#HSTS and it mention that WebSphere does not offer any configuration-only support for HSTS

How do i go about setting or configuring HSTS on IBM - WebSphere Application Server v7.0

答: Setup a servlet filter and use the servlet API to set any response header you like.</p>


问:
Displaying a cv2 image onto Tkinter GUI - "TclError: image "pyimage1" doesn't exist
I am attempting to replicate the following code to output a cv2 image onto a GUI :

```<code>import numpy as np
import cv2
import Tkinter
from PIL import Image
from PIL import ImageTk

# Load an color image
img = cv2.imread('img.jpg')

#Rearrang the color channel
b,g,r = cv2.split(img)
img = cv2.merge((r,g,b))

# A root window for displaying objects
root = Tkinter.Tk()

# Convert the Image object into a TkPhoto object
im = Image.fromarray(img)
imgtk = ImageTk.PhotoImage(image=im)

# Put it in the display window
Tkinter.Label(root, image=imgtk).pack()

root.mainloop() # Start the GUI
</code>```

however on trying to execute this, I end up with the following error:

```<code>TclError: image "pyimage1" doesn't exist
</code>```

In my understanding it is looking for something name pyimage1, I have searched by code multiple times and there is nothing by that name, unless this is a module I am missing.
The output is essentially just a blank GUI with no image being displayed accompanied by the error in my terminal.
Any guidance on how to proceed will be very helpful.

答:
Try changing the line:

```<code>root = Tkinter.Tk()
</code>```

to

```<code>root = Toplevel
</code>```

.. Just a guess let me know if it works.

Body:
I am attempting to replicate the following code to output a cv2 image onto a GUI :

import numpy as np
import cv2
import Tkinter
from PIL import Image
from PIL import ImageTk

# Load an color image
img = cv2.imread('img.jpg')

#Rearrang the color channel
b,g,r = cv2.split(img)
img = cv2.merge((r,g,b))

# A root window for displaying objects
root = Tkinter.Tk()

# Convert the Image object into a TkPhoto object
im = Image.fromarray(img)
imgtk = ImageTk.PhotoImage(image=im)

# Put it in the display window
Tkinter.Label(root, image=imgtk).pack()

root.mainloop() # Start the GUI

however on trying to execute this, I end up with the following error:

TclError: image "pyimage1" doesn't exist

In my understanding it is looking for something name pyimage1, I have searched by code multiple times and there is nothing by that name, unless this is a module I am missing.
The output is essentially just a blank GUI with no image being displayed accompanied by the error in my terminal.
Any guidance on how to proceed will be very helpful.

Body:
Try changing the line:

root = Tkinter.Tk()

to

root = Toplevel

.. Just a guess let me know if it works.


问:
Mongoose's lean usage with populate and nested queries
Im coding an app in Node.js which is using MongoDB. I chose MongooseJS to handle my DB queries.

I have two collections that are referenced to each other (Room which is the 'superior' collection and DeviceGroups which is contained within Room collection).

I have a query that gets a list of all of the rooms from Room collection, populates deviceGroups field (which is the Rooms reference to DeviceGroup collection) and inside it there is a map method that goes through every room found in the Room collection and for every room it makes another query - it looks for any deviceGroups in DeviceGroup collection that are referenced to the current room in the map method.

My goal here is to return a list of all of the rooms with deviceGroups field filled in with actual data, not only references.

What I am getting after the queries (inside the then method) is a Mongoose document. The whole algorithm is used as a handler of a GET method, so I need a pure JavaScript object as a response.

Main goal I want to achieve is to get result of all of the queries and population inside them as pure javascript object, so I can create a response object and send it (i dont want to send everything that db returns, because not all of the data is needed for this case)

EDIT:

I am so sorry, I have deleted my code and didnt realize it.

My current code is below:

Schema:

```<code>const roomSchema = Schema({
  name: {
      type: String,
      required: [true, 'Room name not provided']
  },
  deviceGroups: [{
      type: Schema.Types.ObjectId,
      ref: 'DeviceGroup'
  }]
}, { collection: 'rooms' });

const deviceGroupSchema = Schema({
    parentRoomId: {
        type: Schema.Types.ObjectId,
        ref: 'Room'
    },
    groupType: {
        type: String,
        enum: ['LIGHTS', 'BLINDS', 'ALARM_SENSORS', 'WEATHER_SENSORS']
    },
        devices: [
        {
            type: Schema.Types.ObjectId,
            ref: 'LightBulb'
        }
    ]
}, { collection: 'deviceGroups' });
</code>```

Queries:

```<code>app.get('/api/id/rooms', function(req, res) {
    Room.find({}).populate('deviceGroups').lean().exec(function(err, parentRoom) {
        parentRoom.map(function(currentRoom) {
            DeviceGroup.findOne({ parentRoomId: currentRoom._id }, function (err, devices) {
                return devices;
            });
        });
    }).then(function(roomList) {
        res.send(roomList);
    });
});
</code>```

答:
where are you confusing. here is a simple and effective code snippet</p>

```<code>Room.findById(req.params.id)
.select("roomname")
.populate({
    path: 'deviceGroup',
    select: 'devicename',
    model:'DeviceGroups'
    populate:{
        path: 'device',
        select: 'devicename',
        model:'Device'
        }
})
.lean()
.exec((err, data)=>{
    console.log(data);
})
</code>```

Body:
Im coding an app in Node.js which is using MongoDB. I chose MongooseJS to handle my DB queries.

I have two collections that are referenced to each other (Room which is the 'superior' collection and DeviceGroups which is contained within Room collection).

I have a query that gets a list of all of the rooms from Room collection, populates deviceGroups field (which is the Rooms reference to DeviceGroup collection) and inside it there is a map method that goes through every room found in the Room collection and for every room it makes another query - it looks for any deviceGroups in DeviceGroup collection that are referenced to the current room in the map method.

My goal here is to return a list of all of the rooms with deviceGroups field filled in with actual data, not only references.

What I am getting after the queries (inside the then method) is a Mongoose document. The whole algorithm is used as a handler of a GET method, so I need a pure JavaScript object as a response.

Main goal I want to achieve is to get result of all of the queries and population inside them as pure javascript object, so I can create a response object and send it (i dont want to send everything that db returns, because not all of the data is needed for this case)

EDIT:

I am so sorry, I have deleted my code and didnt realize it.

My current code is below:

Schema:

const roomSchema = Schema({
  name: {
      type: String,
      required: [true, 'Room name not provided']
  },
  deviceGroups: [{
      type: Schema.Types.ObjectId,
      ref: 'DeviceGroup'
  }]
}, { collection: 'rooms' });

const deviceGroupSchema = Schema({
    parentRoomId: {
        type: Schema.Types.ObjectId,
        ref: 'Room'
    },
    groupType: {
        type: String,
        enum: ['LIGHTS', 'BLINDS', 'ALARM_SENSORS', 'WEATHER_SENSORS']
    },
        devices: [
        {
            type: Schema.Types.ObjectId,
            ref: 'LightBulb'
        }
    ]
}, { collection: 'deviceGroups' });

Queries:

app.get('/api/id/rooms', function(req, res) {
    Room.find({}).populate('deviceGroups').lean().exec(function(err, parentRoom) {
        parentRoom.map(function(currentRoom) {
            DeviceGroup.findOne({ parentRoomId: currentRoom._id }, function (err, devices) {
                return devices;
            });
        });
    }).then(function(roomList) {
        res.send(roomList);
    });
});

Body:
where are you confusing. here is a simple and effective code snippet

Room.findById(req.params.id)
.select("roomname")
.populate({
    path: 'deviceGroup',
    select: 'devicename',
    model:'DeviceGroups'
    populate:{
        path: 'device',
        select: 'devicename',
        model:'Device'
        }
})
.lean()
.exec((err, data)=>{
    console.log(data);
})


问:
Eloquent not linking tables
So I've got 3 tables. But Laravel fails to link the tables to eachother, I feel like I'm missing a really small thing but I can't seem to find it.

Controller

```<code>$data = Item::all();
$clipper = $data->first();
dd($clipper->attributes());
</code>```

Item

```<code>protected $table = 'item';
protected $primaryKey = 'item_id';
public $timestamps = false;

public function attributes() {
    return $this->hasMany('App\Attributes', 'item_id');
}
</code>```

Atrributes

```<code>protected $table = 'attributes';
protected $primaryKey = 'attr_id';
public $timestamps = false;

public function name() {
    return $this->hasOne('App\Attributesname', 'name_id');
}
</code>```

Attributes Name

```<code>protected $table = 'item_attributes';
protected $primaryKey = 'item_attr_id';
public $timestamps = false;
</code>```

Result of dd

Database design

答:
Laravel links relations fine, see you output parent model is the Item, related model is the Atribute, try this to see related data (not relation) : </p>

```<code>$data = Item::all();
$clipper = $data->first();
dd($clipper->attributes);
</code>```

Title: Eloquent not linking tables

Body:
So I've got 3 tables. But Laravel fails to link the tables to eachother, I feel like I'm missing a really small thing but I can't seem to find it.

Controller

$data = Item::all();
$clipper = $data->first();
dd($clipper->attributes());

Item

protected $table = 'item';
protected $primaryKey = 'item_id';
public $timestamps = false;

public function attributes() {
    return $this->hasMany('App\Attributes', 'item_id');
}

Atrributes

protected $table = 'attributes';
protected $primaryKey = 'attr_id';
public $timestamps = false;

public function name() {
    return $this->hasOne('App\Attributesname', 'name_id');
}

Attributes Name

protected $table = 'item_attributes';
protected $primaryKey = 'item_attr_id';
public $timestamps = false;

Result of dd

Database design

Body:
Laravel links relations fine, see you output parent model is the Item, related model is the Atribute, try this to see related data (not relation) :

$data = Item::all();
$clipper = $data->first();
dd($clipper->attributes);